From a9f7169779909a56c6cba4b15360108112e88d17 Mon Sep 17 00:00:00 2001 From: sunag Date: Mon, 14 Oct 2024 21:27:27 -0300 Subject: [PATCH] Updated builds. --- build/three.webgpu.js | 13250 +++++++++++++++--------------- build/three.webgpu.min.js | 2 +- build/three.webgpu.nodes.js | 13250 +++++++++++++++--------------- build/three.webgpu.nodes.min.js | 2 +- 4 files changed, 13314 insertions(+), 13190 deletions(-) diff --git a/build/three.webgpu.js b/build/three.webgpu.js index ca188cfb920492..1673959404557c 100644 --- a/build/three.webgpu.js +++ b/build/three.webgpu.js @@ -40808,7 +40808,7 @@ class ColorSpaceNode extends TempNode { let outputNode = null; - const colorSpaceFn = renderer.nodes.library.getColorSpaceFunction( colorSpace ); + const colorSpaceFn = renderer.library.getColorSpaceFunction( colorSpace ); if ( colorSpaceFn !== null ) { @@ -41067,7 +41067,7 @@ class ToneMappingNode extends TempNode { let outputNode = null; - const toneMappingFn = builder.renderer.nodes.library.getToneMappingFunction( toneMapping ); + const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping ); if ( toneMappingFn !== null ) { @@ -44697,252 +44697,6 @@ class MorphNode extends Node { const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ); -const sortLights = ( lights ) => { - - return lights.sort( ( a, b ) => a.id - b.id ); - -}; - -const getLightNodeById = ( id, lightNodes ) => { - - for ( const lightNode of lightNodes ) { - - if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) { - - return lightNode; - - } - - } - - return null; - -}; - -const _lightsNodeRef = /*@__PURE__*/ new WeakMap(); - -class LightsNode extends Node { - - static get type() { - - return 'LightsNode'; - - } - - constructor( lights = [] ) { - - super( 'vec3' ); - - this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' ); - this.totalSpecularNode = vec3().toVar( 'totalSpecular' ); - - this.outgoingLightNode = vec3().toVar( 'outgoingLight' ); - - this._lights = lights; - - this._lightNodes = null; - this._lightNodesHash = null; - - this.global = true; - - } - - getHash( builder ) { - - if ( this._lightNodesHash === null ) { - - if ( this._lightNodes === null ) this.setupLightsNode( builder ); - - const hash = []; - - for ( const lightNode of this._lightNodes ) { - - hash.push( lightNode.getHash() ); - - } - - this._lightNodesHash = 'lights-' + hash.join( ',' ); - - } - - return this._lightNodesHash; - - } - - analyze( builder ) { - - const properties = builder.getDataFromNode( this ); - - for ( const node of properties.nodes ) { - - node.build( builder ); - - } - - } - - setupLightsNode( builder ) { - - const lightNodes = []; - - const previousLightNodes = this._lightNodes; - - const lights = sortLights( this._lights ); - const nodeLibrary = builder.renderer.nodes.library; - - for ( const light of lights ) { - - if ( light.isNode ) { - - lightNodes.push( nodeObject( light ) ); - - } else { - - let lightNode = null; - - if ( previousLightNodes !== null ) { - - lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node - - } - - if ( lightNode === null ) { - - const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor ); - - if ( lightNodeClass === null ) { - - console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` ); - continue; - - } - - let lightNode = null; - - if ( ! _lightsNodeRef.has( light ) ) { - - lightNode = new lightNodeClass( light ); - _lightsNodeRef.set( light, lightNode ); - - } else { - - lightNode = _lightsNodeRef.get( light ); - - } - - lightNodes.push( lightNode ); - - } - - } - - } - - this._lightNodes = lightNodes; - - } - - setup( builder ) { - - if ( this._lightNodes === null ) this.setupLightsNode( builder ); - - const context = builder.context; - const lightingModel = context.lightingModel; - - let outgoingLightNode = this.outgoingLightNode; - - if ( lightingModel ) { - - const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this; - - context.outgoingLight = outgoingLightNode; - - const stack = builder.addStack(); - - // - - const properties = builder.getDataFromNode( this ); - properties.nodes = stack.nodes; - - // - - lightingModel.start( context, stack, builder ); - - // lights - - for ( const lightNode of _lightNodes ) { - - lightNode.build( builder ); - - } - - // - - lightingModel.indirect( context, stack, builder ); - - // - - const { backdrop, backdropAlpha } = context; - const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight; - - let totalDiffuse = directDiffuse.add( indirectDiffuse ); - - if ( backdrop !== null ) { - - if ( backdropAlpha !== null ) { - - totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) ); - - } else { - - totalDiffuse = vec3( backdrop ); - - } - - context.material.transparent = true; - - } - - totalDiffuseNode.assign( totalDiffuse ); - totalSpecularNode.assign( directSpecular.add( indirectSpecular ) ); - - outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) ); - - // - - lightingModel.finish( context, stack, builder ); - - // - - outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() ); - - } - - return outgoingLightNode; - - } - - setLights( lights ) { - - this._lights = lights; - - this._lightNodes = null; - this._lightNodesHash = null; - - return this; - - } - - getLights() { - - return this._lights; - - } - -} - -const lights = /*@__PURE__*/ nodeProxy( LightsNode ); - class LightingNode extends Node { static get type() { @@ -46073,7 +45827,7 @@ class NodeMaterial extends Material { if ( materialLightsNode.length > 0 ) { - lightsN = lights( [ ...lightsN.getLights(), ...materialLightsNode ] ); + lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] ); } @@ -46100,7 +45854,7 @@ class NodeMaterial extends Material { let outgoingLightNode = this.setupOutgoingLight( builder ); - if ( lightsNode && lightsNode.getScope().getLights().length > 0 ) { + if ( lightsNode && lightsNode.getScope().hasLights ) { const lightingModel = this.setupLightingModel( builder ); @@ -52221,620 +51975,774 @@ class Bindings extends DataMap { } -class NodeAttribute { +function painterSortStable( a, b ) { - constructor( name, type, node = null ) { + if ( a.groupOrder !== b.groupOrder ) { - this.isNodeAttribute = true; + return a.groupOrder - b.groupOrder; - this.name = name; - this.type = type; - this.node = node; + } else if ( a.renderOrder !== b.renderOrder ) { - } + return a.renderOrder - b.renderOrder; -} + } else if ( a.material.id !== b.material.id ) { -class NodeUniform { + return a.material.id - b.material.id; - constructor( name, type, node ) { + } else if ( a.z !== b.z ) { - this.isNodeUniform = true; + return a.z - b.z; - this.name = name; - this.type = type; - this.node = node.getSelf(); + } else { - } + return a.id - b.id; - get value() { + } - return this.node.value; +} - } +function reversePainterSortStable( a, b ) { - set value( val ) { + if ( a.groupOrder !== b.groupOrder ) { - this.node.value = val; + return a.groupOrder - b.groupOrder; - } + } else if ( a.renderOrder !== b.renderOrder ) { - get id() { + return a.renderOrder - b.renderOrder; - return this.node.id; + } else if ( a.z !== b.z ) { - } + return b.z - a.z; - get groupNode() { + } else { - return this.node.groupNode; + return a.id - b.id; } } -class NodeVar { +class RenderList { - constructor( name, type ) { + constructor( lighting, scene, camera ) { - this.isNodeVar = true; + this.renderItems = []; + this.renderItemsIndex = 0; - this.name = name; - this.type = type; + this.opaque = []; + this.transparent = []; + this.bundles = []; + + this.lightsNode = lighting.getNode( scene, camera ); + this.lightsArray = []; + + this.scene = scene; + this.camera = camera; + + this.occlusionQueryCount = 0; } -} + begin() { -class NodeVarying extends NodeVar { + this.renderItemsIndex = 0; - constructor( name, type ) { + this.opaque.length = 0; + this.transparent.length = 0; + this.bundles.length = 0; - super( name, type ); + this.lightsArray.length = 0; - this.needsInterpolation = false; + this.occlusionQueryCount = 0; - this.isNodeVarying = true; + return this; } -} + getNextRenderItem( object, geometry, material, groupOrder, z, group ) { -class NodeCode { + let renderItem = this.renderItems[ this.renderItemsIndex ]; - constructor( name, type, code = '' ) { + if ( renderItem === undefined ) { - this.name = name; - this.type = type; - this.code = code; + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; - Object.defineProperty( this, 'isNodeCode', { value: true } ); + this.renderItems[ this.renderItemsIndex ] = renderItem; - } + } else { -} + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; -let id$1 = 0; + } -class NodeCache { + this.renderItemsIndex ++; - constructor( parent = null ) { + return renderItem; - this.id = id$1 ++; - this.nodesData = new WeakMap(); + } - this.parent = parent; + push( object, geometry, material, groupOrder, z, group ) { - } + const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group ); - getData( node ) { + if ( object.occlusionTest === true ) this.occlusionQueryCount ++; - let data = this.nodesData.get( node ); + ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem ); - if ( data === undefined && this.parent !== null ) { + } - data = this.parent.getData( node ); + unshift( object, geometry, material, groupOrder, z, group ) { - } + const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group ); - return data; + ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem ); } - setData( node, data ) { + pushBundle( group ) { - this.nodesData.set( node, data ); + this.bundles.push( group ); } -} + pushLight( light ) { -class ParameterNode extends PropertyNode { + this.lightsArray.push( light ); - static get type() { + } - return 'ParameterNode'; + sort( customOpaqueSort, customTransparentSort ) { + + if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable ); + if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable ); } - constructor( nodeType, name = null ) { + finish() { - super( nodeType, name ); + // update lights - this.isParameterNode = true; + this.lightsNode.setLights( this.lightsArray ); - } + // Clear references from inactive renderItems in the list - getHash() { + for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) { - return this.uuid; + const renderItem = this.renderItems[ i ]; - } + if ( renderItem.id === null ) break; - generate() { + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.groupOrder = null; + renderItem.renderOrder = null; + renderItem.z = null; + renderItem.group = null; - return this.name; + } } } -const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) ); +class RenderLists { -class CodeNode extends Node { + constructor( lighting ) { - static get type() { + this.lighting = lighting; - return 'CodeNode'; + this.lists = new ChainMap(); } - constructor( code = '', includes = [], language = '' ) { - - super( 'code' ); + get( scene, camera ) { - this.isCodeNode = true; + const lists = this.lists; + const keys = [ scene, camera ]; - this.code = code; - this.language = language; + let list = lists.get( keys ); - this.includes = includes; + if ( list === undefined ) { - } + list = new RenderList( this.lighting, scene, camera ); + lists.set( keys, list ); - isGlobal() { + } - return true; + return list; } - setIncludes( includes ) { - - this.includes = includes; + dispose() { - return this; + this.lists = new ChainMap(); } - getIncludes( /*builder*/ ) { - - return this.includes; +} - } +let id$1 = 0; - generate( builder ) { +class RenderContext { - const includes = this.getIncludes( builder ); + constructor() { - for ( const include of includes ) { + this.id = id$1 ++; - include.build( builder ); + this.color = true; + this.clearColor = true; + this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 }; - } + this.depth = true; + this.clearDepth = true; + this.clearDepthValue = 1; - const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) ); - nodeCode.code = this.code; + this.stencil = false; + this.clearStencil = true; + this.clearStencilValue = 1; - return nodeCode.code; + this.viewport = false; + this.viewportValue = new Vector4(); - } + this.scissor = false; + this.scissorValue = new Vector4(); - serialize( data ) { + this.textures = null; + this.depthTexture = null; + this.activeCubeFace = 0; + this.sampleCount = 1; - super.serialize( data ); + this.width = 0; + this.height = 0; - data.code = this.code; - data.language = this.language; + this.isRenderContext = true; } - deserialize( data ) { - - super.deserialize( data ); + getCacheKey() { - this.code = data.code; - this.language = data.language; + return getCacheKey( this ); } } -const code = /*@__PURE__*/ nodeProxy( CodeNode ); +function getCacheKey( renderContext ) { -const js = ( src, includes ) => code( src, includes, 'js' ); -const wgsl = ( src, includes ) => code( src, includes, 'wgsl' ); -const glsl = ( src, includes ) => code( src, includes, 'glsl' ); + const { textures, activeCubeFace } = renderContext; -class FunctionNode extends CodeNode { + const values = [ activeCubeFace ]; - static get type() { + for ( const texture of textures ) { - return 'FunctionNode'; + values.push( texture.id ); } - constructor( code = '', includes = [], language = '' ) { + return hashArray( values ); - super( code, includes, language ); +} - } +class RenderContexts { - getNodeType( builder ) { + constructor() { - return this.getNodeFunction( builder ).type; + this.chainMaps = {}; } - getInputs( builder ) { + get( scene, camera, renderTarget = null ) { - return this.getNodeFunction( builder ).inputs; + const chainKey = [ scene, camera ]; - } + let attachmentState; - getNodeFunction( builder ) { + if ( renderTarget === null ) { - const nodeData = builder.getDataFromNode( this ); + attachmentState = 'default'; - let nodeFunction = nodeData.nodeFunction; + } else { - if ( nodeFunction === undefined ) { + const format = renderTarget.texture.format; + const count = renderTarget.textures.length; - nodeFunction = builder.parser.parseFunction( this.code ); + attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`; - nodeData.nodeFunction = nodeFunction; + } + + const chainMap = this.getChainMap( attachmentState ); + + let renderState = chainMap.get( chainKey ); + + if ( renderState === undefined ) { + + renderState = new RenderContext(); + + chainMap.set( chainKey, renderState ); } - return nodeFunction; + if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; + + return renderState; } - generate( builder, output ) { + getChainMap( attachmentState ) { - super.generate( builder ); + return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() ); - const nodeFunction = this.getNodeFunction( builder ); + } - const name = nodeFunction.name; - const type = nodeFunction.type; + dispose() { - const nodeCode = builder.getCodeFromNode( this, type ); + this.chainMaps = {}; - if ( name !== '' ) { + } - // use a custom property name +} - nodeCode.name = name; +const _size$3 = /*@__PURE__*/ new Vector3(); + +class Textures extends DataMap { + + constructor( renderer, backend, info ) { + + super(); + + this.renderer = renderer; + this.backend = backend; + this.info = info; + + } + + updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) { + + const renderTargetData = this.get( renderTarget ); + + const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; + const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} ); + + const textures = renderTarget.textures; + + const size = this.getSize( textures[ 0 ] ); + + const mipWidth = size.width >> activeMipmapLevel; + const mipHeight = size.height >> activeMipmapLevel; + + let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ]; + const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true; + + let textureNeedsUpdate = false; + + if ( depthTexture === undefined && useDepthTexture ) { + + depthTexture = new DepthTexture(); + depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat; + depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType + depthTexture.image.width = mipWidth; + depthTexture.image.height = mipHeight; + + depthTextureMips[ activeMipmapLevel ] = depthTexture; } - const propertyName = builder.getPropertyName( nodeCode ); + if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) { - const code = this.getNodeFunction( builder ).getCode( propertyName ); + textureNeedsUpdate = true; - nodeCode.code = code + '\n'; + if ( depthTexture ) { - if ( output === 'property' ) { + depthTexture.needsUpdate = true; + depthTexture.image.width = mipWidth; + depthTexture.image.height = mipHeight; - return propertyName; + } - } else { + } - return builder.format( `${ propertyName }()`, type, output ); + renderTargetData.width = size.width; + renderTargetData.height = size.height; + renderTargetData.textures = textures; + renderTargetData.depthTexture = depthTexture || null; + renderTargetData.depth = renderTarget.depthBuffer; + renderTargetData.stencil = renderTarget.stencilBuffer; + renderTargetData.renderTarget = renderTarget; + + if ( renderTargetData.sampleCount !== sampleCount ) { + + textureNeedsUpdate = true; + + if ( depthTexture ) { + + depthTexture.needsUpdate = true; + + } + + renderTargetData.sampleCount = sampleCount; } - } + // -} + const options = { sampleCount }; -const nativeFn = ( code, includes = [], language = '' ) => { + for ( let i = 0; i < textures.length; i ++ ) { - for ( let i = 0; i < includes.length; i ++ ) { + const texture = textures[ i ]; - const include = includes[ i ]; + if ( textureNeedsUpdate ) texture.needsUpdate = true; - // TSL Function: glslFn, wgslFn + this.updateTexture( texture, options ); - if ( typeof include === 'function' ) { + } - includes[ i ] = include.functionNode; + if ( depthTexture ) { + + this.updateTexture( depthTexture, options ); } - } + // dispose handler - const functionNode = nodeObject( new FunctionNode( code, includes, language ) ); + if ( renderTargetData.initialized !== true ) { - const fn = ( ...params ) => functionNode.call( ...params ); - fn.functionNode = functionNode; + renderTargetData.initialized = true; - return fn; + // dispose -}; + const onDispose = () => { -const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' ); -const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' ); + renderTarget.removeEventListener( 'dispose', onDispose ); -class Uniform { + for ( let i = 0; i < textures.length; i ++ ) { - constructor( name, value ) { + this._destroyTexture( textures[ i ] ); - this.name = name; - this.value = value; + } - this.boundary = 0; // used to build the uniform buffer according to the STD140 layout - this.itemSize = 0; + if ( depthTexture ) { - this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer + this._destroyTexture( depthTexture ); - } + } - setValue( value ) { + this.delete( renderTarget ); - this.value = value; + }; + + renderTarget.addEventListener( 'dispose', onDispose ); + + } } - getValue() { + updateTexture( texture, options = {} ) { - return this.value; + const textureData = this.get( texture ); + if ( textureData.initialized === true && textureData.version === texture.version ) return; - } + const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture; + const backend = this.backend; -} + if ( isRenderTarget && textureData.initialized === true ) { -class NumberUniform extends Uniform { + // it's an update - constructor( name, value = 0 ) { + backend.destroySampler( texture ); + backend.destroyTexture( texture ); - super( name, value ); + } - this.isNumberUniform = true; + // - this.boundary = 4; - this.itemSize = 1; + if ( texture.isFramebufferTexture ) { - } + const renderer = this.renderer; + const renderTarget = renderer.getRenderTarget(); -} + if ( renderTarget ) { -class Vector2Uniform extends Uniform { + texture.type = renderTarget.texture.type; - constructor( name, value = new Vector2() ) { + } else { - super( name, value ); + texture.type = UnsignedByteType; - this.isVector2Uniform = true; + } - this.boundary = 8; - this.itemSize = 2; + } - } + // -} + const { width, height, depth } = this.getSize( texture ); -class Vector3Uniform extends Uniform { + options.width = width; + options.height = height; + options.depth = depth; + options.needsMipmaps = this.needsMipmaps( texture ); + options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1; - constructor( name, value = new Vector3() ) { + // - super( name, value ); + if ( isRenderTarget || texture.isStorageTexture === true ) { - this.isVector3Uniform = true; + backend.createSampler( texture ); + backend.createTexture( texture, options ); - this.boundary = 16; - this.itemSize = 3; + textureData.generation = texture.version; - } + } else { -} + const needsCreate = textureData.initialized !== true; -class Vector4Uniform extends Uniform { + if ( needsCreate ) backend.createSampler( texture ); - constructor( name, value = new Vector4() ) { + if ( texture.version > 0 ) { - super( name, value ); + const image = texture.image; - this.isVector4Uniform = true; + if ( image === undefined ) { - this.boundary = 16; - this.itemSize = 4; + console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' ); - } + } else if ( image.complete === false ) { -} + console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' ); -class ColorUniform extends Uniform { + } else { - constructor( name, value = new Color() ) { + if ( texture.images ) { - super( name, value ); + const images = []; - this.isColorUniform = true; + for ( const image of texture.images ) { - this.boundary = 16; - this.itemSize = 3; + images.push( image ); - } + } -} + options.images = images; -class Matrix3Uniform extends Uniform { + } else { - constructor( name, value = new Matrix3() ) { + options.image = image; - super( name, value ); + } - this.isMatrix3Uniform = true; + if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) { - this.boundary = 48; - this.itemSize = 12; + backend.createTexture( texture, options ); - } + textureData.isDefaultTexture = false; + textureData.generation = texture.version; -} + } -class Matrix4Uniform extends Uniform { + if ( texture.source.dataReady === true ) backend.updateTexture( texture, options ); - constructor( name, value = new Matrix4() ) { + if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture ); - super( name, value ); + } - this.isMatrix4Uniform = true; + } else { - this.boundary = 64; - this.itemSize = 16; + // async update - } + backend.createDefaultTexture( texture ); -} + textureData.isDefaultTexture = true; + textureData.generation = texture.version; -class NumberNodeUniform extends NumberUniform { + } - constructor( nodeUniform ) { + } - super( nodeUniform.name, nodeUniform.value ); + // dispose handler - this.nodeUniform = nodeUniform; + if ( textureData.initialized !== true ) { - } + textureData.initialized = true; + textureData.generation = texture.version; - getValue() { + // - return this.nodeUniform.value; + this.info.memory.textures ++; - } + // dispose -} + const onDispose = () => { -class Vector2NodeUniform extends Vector2Uniform { + texture.removeEventListener( 'dispose', onDispose ); - constructor( nodeUniform ) { + this._destroyTexture( texture ); - super( nodeUniform.name, nodeUniform.value ); + this.info.memory.textures --; - this.nodeUniform = nodeUniform; + }; - } + texture.addEventListener( 'dispose', onDispose ); - getValue() { + } - return this.nodeUniform.value; + // + + textureData.version = texture.version; } -} + getSize( texture, target = _size$3 ) { -class Vector3NodeUniform extends Vector3Uniform { + let image = texture.images ? texture.images[ 0 ] : texture.image; - constructor( nodeUniform ) { + if ( image ) { - super( nodeUniform.name, nodeUniform.value ); + if ( image.image !== undefined ) image = image.image; - this.nodeUniform = nodeUniform; + target.width = image.width; + target.height = image.height; + target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 ); + + } else { + + target.width = target.height = target.depth = 1; + + } + + return target; } - getValue() { + getMipLevels( texture, width, height ) { - return this.nodeUniform.value; + let mipLevelCount; + + if ( texture.isCompressedTexture ) { + + mipLevelCount = texture.mipmaps.length; + + } else { + + mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1; + + } + + return mipLevelCount; } -} + needsMipmaps( texture ) { -class Vector4NodeUniform extends Vector4Uniform { + if ( this.isEnvironmentTexture( texture ) ) return true; - constructor( nodeUniform ) { + return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) ); - super( nodeUniform.name, nodeUniform.value ); + } - this.nodeUniform = nodeUniform; + isEnvironmentTexture( texture ) { + + const mapping = texture.mapping; + + return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); } - getValue() { + _destroyTexture( texture ) { - return this.nodeUniform.value; + this.backend.destroySampler( texture ); + this.backend.destroyTexture( texture ); + + this.delete( texture ); } } -class ColorNodeUniform extends ColorUniform { +class Color4 extends Color { - constructor( nodeUniform ) { + constructor( r, g, b, a = 1 ) { - super( nodeUniform.name, nodeUniform.value ); + super( r, g, b ); - this.nodeUniform = nodeUniform; + this.a = a; } - getValue() { + set( r, g, b, a = 1 ) { - return this.nodeUniform.value; + this.a = a; + + return super.set( r, g, b ); } -} + copy( color ) { -class Matrix3NodeUniform extends Matrix3Uniform { + if ( color.a !== undefined ) this.a = color.a; - constructor( nodeUniform ) { + return super.copy( color ); - super( nodeUniform.name, nodeUniform.value ); + } - this.nodeUniform = nodeUniform; + clone() { + + return new this.constructor( this.r, this.g, this.b, this.a ); } - getValue() { +} - return this.nodeUniform.value; +class ParameterNode extends PropertyNode { + + static get type() { + + return 'ParameterNode'; } -} + constructor( nodeType, name = null ) { -class Matrix4NodeUniform extends Matrix4Uniform { + super( nodeType, name ); - constructor( nodeUniform ) { + this.isParameterNode = true; - super( nodeUniform.name, nodeUniform.value ); + } - this.nodeUniform = nodeUniform; + getHash() { + + return this.uuid; } - getValue() { + generate() { - return this.nodeUniform.value; + return this.name; } } +const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) ); + class StackNode extends Node { static get type() { @@ -52939,10209 +52847,10327 @@ class StackNode extends Node { const stack = /*@__PURE__*/ nodeProxy( StackNode ); -const LOD_MIN = 4; +class StructTypeNode extends Node { -// The standard deviations (radians) associated with the extra mips. These are -// chosen to approximate a Trowbridge-Reitz distribution function times the -// geometric shadowing function. These sigma values squared must match the -// variance #defines in cube_uv_reflection_fragment.glsl.js. -const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; + static get type() { -// The maximum length of the blur for loop. Smaller sigmas will use fewer -// samples and exit early, but not recompile the shader. -const MAX_SAMPLES = 20; + return 'StructTypeNode'; -const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); -const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 ); -const _clearColor$1 = /*@__PURE__*/ new Color(); -let _oldTarget = null; -let _oldActiveCubeFace = 0; -let _oldActiveMipmapLevel = 0; + } -// Golden Ratio -const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; -const INV_PHI = 1 / PHI; + constructor( types ) { -// Vertices of a dodecahedron (except the opposites, which represent the -// same axis), used as axis directions evenly spread on a sphere. -const _axisDirections = [ - /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ), - /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), - /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), - /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), - /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), - /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), - /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), - /*@__PURE__*/ new Vector3( 1, 1, - 1 ), - /*@__PURE__*/ new Vector3( - 1, 1, 1 ), - /*@__PURE__*/ new Vector3( 1, 1, 1 ) -]; + super(); -// + this.types = types; + this.isStructTypeNode = true; -// WebGPU Face indices -const _faceLib = [ - 3, 1, 5, - 0, 4, 2 -]; + } -const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize(); -const outputDirection = vec3( direction.x, direction.y.negate(), direction.z ); + getMemberTypes() { -/** - * This class generates a Prefiltered, Mipmapped Radiance Environment Map - * (PMREM) from a cubeMap environment texture. This allows different levels of - * blur to be quickly accessed based on material roughness. It is packed into a - * special CubeUV format that allows us to perform custom interpolation so that - * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap - * chain, it only goes down to the LOD_MIN level (above), and then creates extra - * even more filtered 'mips' at the same LOD_MIN resolution, associated with - * higher roughness levels. In this way we maintain resolution to smoothly - * interpolate diffuse lighting while limiting sampling computation. - * - * Paper: Fast, Accurate Image-Based Lighting - * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view -*/ + return this.types; -class PMREMGenerator { + } - constructor( renderer ) { +} - this._renderer = renderer; - this._pingPongRenderTarget = null; +class OutputStructNode extends Node { - this._lodMax = 0; - this._cubeSize = 0; - this._lodPlanes = []; - this._sizeLods = []; - this._sigmas = []; - this._lodMeshes = []; + static get type() { - this._blurMaterial = null; - this._cubemapMaterial = null; - this._equirectMaterial = null; - this._backgroundBox = null; + return 'OutputStructNode'; } - /** - * Generates a PMREM from a supplied Scene, which can be faster than using an - * image if networking bandwidth is low. Optional sigma specifies a blur radius - * in radians to be applied to the scene before PMREM generation. Optional near - * and far planes ensure the scene is rendered in its entirety (the cubeCamera - * is placed at the origin). - */ - fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { - - _oldTarget = this._renderer.getRenderTarget(); - _oldActiveCubeFace = this._renderer.getActiveCubeFace(); - _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); - - this._setSize( 256 ); + constructor( ...members ) { - const cubeUVRenderTarget = this._allocateTargets(); - cubeUVRenderTarget.depthBuffer = true; + super(); - this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); + this.members = members; - if ( sigma > 0 ) { + this.isOutputStructNode = true; - this._blur( cubeUVRenderTarget, 0, 0, sigma ); + } - } + setup( builder ) { - this._applyPMREM( cubeUVRenderTarget ); + super.setup( builder ); - this._cleanup( cubeUVRenderTarget ); + const members = this.members; + const types = []; - return cubeUVRenderTarget; + for ( let i = 0; i < members.length; i ++ ) { - } + types.push( members[ i ].getNodeType( builder ) ); - /** - * Generates a PMREM from an equirectangular texture, which can be either LDR - * or HDR. The ideal input image size is 1k (1024 x 512), - * as this matches best with the 256 x 256 cubemap output. - */ - fromEquirectangular( equirectangular, renderTarget = null ) { + } - return this._fromTexture( equirectangular, renderTarget ); + this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name; } - /** - * Generates a PMREM from an cubemap texture, which can be either LDR - * or HDR. The ideal input cube size is 256 x 256, - * as this matches best with the 256 x 256 cubemap output. - */ - fromCubemap( cubemap, renderTarget = null ) { + generate( builder, output ) { - return this._fromTexture( cubemap, renderTarget ); + const propertyName = builder.getOutputStructName(); + const members = this.members; - } + const structPrefix = propertyName !== '' ? propertyName + '.' : ''; - /** - * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - async compileCubemapShader() { + for ( let i = 0; i < members.length; i ++ ) { - if ( this._cubemapMaterial === null ) { + const snippet = members[ i ].build( builder, output ); - this._cubemapMaterial = _getCubemapMaterial(); - await this._compileMaterial( this._cubemapMaterial ); + builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this ); } - } - - /** - * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - async compileEquirectangularShader() { - - if ( this._equirectMaterial === null ) { + return propertyName; - this._equirectMaterial = _getEquirectMaterial(); - await this._compileMaterial( this._equirectMaterial ); + } - } +} - } +const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode ); - /** - * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, - * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on - * one of them will cause any others to also become unusable. - */ - dispose() { +function getTextureIndex( textures, name ) { - this._dispose(); + for ( let i = 0; i < textures.length; i ++ ) { - if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); - if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); - if ( this._backgroundBox !== null ) { + if ( textures[ i ].name === name ) { - this._backgroundBox.geometry.dispose(); - this._backgroundBox.material.dispose(); + return i; } } - // private interface + return - 1; - _setSize( cubeSize ) { +} - this._lodMax = Math.floor( Math.log2( cubeSize ) ); - this._cubeSize = Math.pow( 2, this._lodMax ); +class MRTNode extends OutputStructNode { - } + static get type() { - _dispose() { + return 'MRTNode'; - if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); + } - if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); + constructor( outputNodes ) { - for ( let i = 0; i < this._lodPlanes.length; i ++ ) { + super(); - this._lodPlanes[ i ].dispose(); + this.outputNodes = outputNodes; - } + this.isMRTNode = true; } - _cleanup( outputTarget ) { + has( name ) { - this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel ); - outputTarget.scissorTest = false; - _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + return this.outputNodes[ name ] !== undefined; } - _fromTexture( texture, renderTarget ) { - - if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { - - this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); - - } else { // Equirectangular - - this._setSize( texture.image.width / 4 ); - - } - - _oldTarget = this._renderer.getRenderTarget(); - _oldActiveCubeFace = this._renderer.getActiveCubeFace(); - _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); - - const cubeUVRenderTarget = renderTarget || this._allocateTargets(); - this._textureToCubeUV( texture, cubeUVRenderTarget ); - this._applyPMREM( cubeUVRenderTarget ); - this._cleanup( cubeUVRenderTarget ); + get( name ) { - return cubeUVRenderTarget; + return this.outputNodes[ name ]; } - _allocateTargets() { + merge( mrtNode ) { - const width = 3 * Math.max( this._cubeSize, 16 * 7 ); - const height = 4 * this._cubeSize; + const outputs = { ...this.outputNodes, ...mrtNode.outputNodes }; - const params = { - magFilter: LinearFilter, - minFilter: LinearFilter, - generateMipmaps: false, - type: HalfFloatType, - format: RGBAFormat, - colorSpace: LinearSRGBColorSpace, - //depthBuffer: false - }; + return mrt( outputs ); - const cubeUVRenderTarget = _createRenderTarget( width, height, params ); + } - if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { + setup( builder ) { - if ( this._pingPongRenderTarget !== null ) { + const outputNodes = this.outputNodes; + const mrt = builder.renderer.getRenderTarget(); - this._dispose(); + const members = []; - } + const textures = mrt.textures; - this._pingPongRenderTarget = _createRenderTarget( width, height, params ); + for ( const name in outputNodes ) { - const { _lodMax } = this; - ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) ); + const index = getTextureIndex( textures, name ); - this._blurMaterial = _getBlurShader( _lodMax, width, height ); + members[ index ] = vec4( outputNodes[ name ] ); } - return cubeUVRenderTarget; - - } - - async _compileMaterial( material ) { + this.members = members; - const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); - await this._renderer.compile( tmpMesh, _flatCamera ); + return super.setup( builder ); } - _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { +} - const cubeCamera = _cubeCamera; - cubeCamera.near = near; - cubeCamera.far = far; +const mrt = /*@__PURE__*/ nodeProxy( MRTNode ); - // px, py, pz, nx, ny, nz - const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ]; - const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; +const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => { - const renderer = this._renderer; + // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org - const originalAutoClear = renderer.autoClear; + const state = seed.toUint().mul( 747796405 ).add( 2891336453 ); + const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 ); + const result = word.shiftRight( 22 ).bitXor( word ); - renderer.getClearColor( _clearColor$1 ); + return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1) - renderer.autoClear = false; +} ); - let backgroundBox = this._backgroundBox; +// remapping functions https://iquilezles.org/articles/functions/ +const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k ); +const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) ); +const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a ); +const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) ); - if ( backgroundBox === null ) { +// https://github.com/cabbibo/glsl-tri-noise-3d - const backgroundMaterial = new MeshBasicMaterial( { - name: 'PMREM.Background', - side: BackSide, - depthWrite: false, - depthTest: false - } ); - backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); +const tri = /*@__PURE__*/ Fn( ( [ x ] ) => { - } + return x.fract().sub( .5 ).abs(); - let useSolidColor = false; - const background = scene.background; +} ).setLayout( { + name: 'tri', + type: 'float', + inputs: [ + { name: 'x', type: 'float' } + ] +} ); - if ( background ) { +const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => { - if ( background.isColor ) { + return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) ); - backgroundBox.material.color.copy( background ); - scene.background = null; - useSolidColor = true; +} ).setLayout( { + name: 'tri3', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] +} ); - } +const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => { - } else { + const p = vec3( p_immutable ).toVar(); + const z = float( 1.4 ).toVar(); + const rz = float( 0.0 ).toVar(); + const bp = vec3( p ).toVar(); - backgroundBox.material.color.copy( _clearColor$1 ); - useSolidColor = true; + Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => { - } + const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar(); + p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) ); + bp.mulAssign( 1.8 ); + z.mulAssign( 1.5 ); + p.mulAssign( 1.2 ); - renderer.setRenderTarget( cubeUVRenderTarget ); + const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar(); + rz.addAssign( t.div( z ) ); + bp.addAssign( 0.14 ); - renderer.clear(); + } ); - if ( useSolidColor ) { + return rz; - renderer.render( backgroundBox, cubeCamera ); +} ).setLayout( { + name: 'triNoise3D', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'spd', type: 'float' }, + { name: 'time', type: 'float' } + ] +} ); - } +class FunctionOverloadingNode extends Node { - for ( let i = 0; i < 6; i ++ ) { + static get type() { - const col = i % 3; + return 'FunctionOverloadingNode'; - if ( col === 0 ) { + } - cubeCamera.up.set( 0, upSign[ i ], 0 ); - cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); + constructor( functionNodes = [], ...parametersNodes ) { - } else if ( col === 1 ) { + super(); - cubeCamera.up.set( 0, 0, upSign[ i ] ); - cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); + this.functionNodes = functionNodes; + this.parametersNodes = parametersNodes; - } else { + this._candidateFnCall = null; - cubeCamera.up.set( 0, upSign[ i ], 0 ); - cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); + this.global = true; - } + } - const size = this._cubeSize; + getNodeType() { - _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); + return this.functionNodes[ 0 ].shaderNode.layout.type; - renderer.render( scene, cubeCamera ); + } - } + setup( builder ) { - renderer.autoClear = originalAutoClear; - scene.background = background; + const params = this.parametersNodes; - } + let candidateFnCall = this._candidateFnCall; - _textureToCubeUV( texture, cubeUVRenderTarget ) { + if ( candidateFnCall === null ) { - const renderer = this._renderer; + let candidateFn = null; + let candidateScore = - 1; - const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); + for ( const functionNode of this.functionNodes ) { - if ( isCubeTexture ) { + const shaderNode = functionNode.shaderNode; + const layout = shaderNode.layout; - if ( this._cubemapMaterial === null ) { + if ( layout === null ) { - this._cubemapMaterial = _getCubemapMaterial( texture ); + throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' ); - } + } - } else { + const inputs = layout.inputs; - if ( this._equirectMaterial === null ) { + if ( params.length === inputs.length ) { - this._equirectMaterial = _getEquirectMaterial( texture ); + let score = 0; - } + for ( let i = 0; i < params.length; i ++ ) { - } + const param = params[ i ]; + const input = inputs[ i ]; - const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; - material.fragmentNode.value = texture; + if ( param.getNodeType( builder ) === input.type ) { - const mesh = this._lodMeshes[ 0 ]; - mesh.material = material; + score ++; - const size = this._cubeSize; + } else { - _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); + score = 0; - renderer.setRenderTarget( cubeUVRenderTarget ); - renderer.render( mesh, _flatCamera ); + } - } + } - _applyPMREM( cubeUVRenderTarget ) { + if ( score > candidateScore ) { - const renderer = this._renderer; - const autoClear = renderer.autoClear; - renderer.autoClear = false; - const n = this._lodPlanes.length; + candidateFn = functionNode; + candidateScore = score; - for ( let i = 1; i < n; i ++ ) { + } - const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); + } - const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ]; + } - this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); + this._candidateFnCall = candidateFnCall = candidateFn( ...params ); } - renderer.autoClear = autoClear; + return candidateFnCall; } - /** - * This is a two-pass Gaussian blur for a cubemap. Normally this is done - * vertically and horizontally, but this breaks down on a cube. Here we apply - * the blur latitudinally (around the poles), and then longitudinally (towards - * the poles) to approximate the orthogonally-separable blur. It is least - * accurate at the poles, but still does a decent job. - */ - _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { +} - const pingPongRenderTarget = this._pingPongRenderTarget; +const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode ); - this._halfBlur( - cubeUVRenderTarget, - pingPongRenderTarget, - lodIn, - lodOut, - sigma, - 'latitudinal', - poleAxis ); +const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params ); - this._halfBlur( - pingPongRenderTarget, - cubeUVRenderTarget, - lodOut, - lodOut, - sigma, - 'longitudinal', - poleAxis ); +const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time ); +const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime ); +const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId ); - } +// Deprecated - _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { +const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170 - const renderer = this._renderer; - const blurMaterial = this._blurMaterial; + console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' ); + return time.mul( timeScale ); - if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { +}; - console.error( 'blur direction must be either latitudinal or longitudinal!' ); +const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170 - } + console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' ); + return time.mul( timeScale ); - // Number of standard deviations at which to cut off the discrete approximation. - const STANDARD_DEVIATIONS = 3; +}; - const blurMesh = this._lodMeshes[ lodOut ]; - blurMesh.material = blurMaterial; +const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170 - const blurUniforms = blurMaterial.uniforms; + console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' ); + return deltaTime.mul( timeScale ); - const pixels = this._sizeLods[ lodIn ] - 1; - const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); - const sigmaPixels = sigmaRadians / radiansPerPixel; - const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; +}; - if ( samples > MAX_SAMPLES ) { +const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 ); +const oscSquare = ( t = time ) => t.fract().round(); +const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs(); +const oscSawtooth = ( t = time ) => t.fract(); - console.warn( `sigmaRadians, ${ - sigmaRadians}, is too large and will clip, as it requested ${ - samples} samples when the maximum is set to ${MAX_SAMPLES}` ); +const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => { - } + return rotate( uv.sub( center ), rotation ).add( center ); - const weights = []; - let sum = 0; +} ); - for ( let i = 0; i < MAX_SAMPLES; ++ i ) { +const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => { - const x = i / sigmaPixels; - const weight = Math.exp( - x * x / 2 ); - weights.push( weight ); + const delta = uv.sub( center ); + const delta2 = delta.dot( delta ); + const delta4 = delta2.mul( delta2 ); + const deltaOffset = delta4.mul( strength ); - if ( i === 0 ) { + return uv.add( delta.mul( deltaOffset ) ); - sum += weight; +} ); - } else if ( i < samples ) { +const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => { - sum += 2 * weight; + let worldMatrix; - } + if ( position !== null ) { - } + worldMatrix = modelWorldMatrix.toVar(); + worldMatrix[ 3 ][ 0 ] = position.x; + worldMatrix[ 3 ][ 1 ] = position.y; + worldMatrix[ 3 ][ 2 ] = position.z; - for ( let i = 0; i < weights.length; i ++ ) { + } else { - weights[ i ] = weights[ i ] / sum; + worldMatrix = modelWorldMatrix; - } + } - targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1; + const modelViewMatrix = cameraViewMatrix.mul( worldMatrix ); - blurUniforms.envMap.value = targetIn.texture; - blurUniforms.samples.value = samples; - blurUniforms.weights.array = weights; - blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0; - - if ( poleAxis ) { - - blurUniforms.poleAxis.value = poleAxis; + if ( defined( horizontal ) ) { - } + modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length(); + modelViewMatrix[ 0 ][ 1 ] = 0; + modelViewMatrix[ 0 ][ 2 ] = 0; - const { _lodMax } = this; - blurUniforms.dTheta.value = radiansPerPixel; - blurUniforms.mipInt.value = _lodMax - lodIn; + } - const outputSize = this._sizeLods[ lodOut ]; - const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); - const y = 4 * ( this._cubeSize - outputSize ); + if ( defined( vertical ) ) { - _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); - renderer.setRenderTarget( targetOut ); - renderer.render( blurMesh, _flatCamera ); + modelViewMatrix[ 1 ][ 0 ] = 0; + modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length(); + modelViewMatrix[ 1 ][ 2 ] = 0; } -} - -function _createPlanes( lodMax ) { - - const lodPlanes = []; - const sizeLods = []; - const sigmas = []; - const lodMeshes = []; + modelViewMatrix[ 2 ][ 0 ] = 0; + modelViewMatrix[ 2 ][ 1 ] = 0; + modelViewMatrix[ 2 ][ 2 ] = 1; - let lod = lodMax; + return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal ); - const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; +} ); - for ( let i = 0; i < totalLods; i ++ ) { +const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => { - const sizeLod = Math.pow( 2, lod ); - sizeLods.push( sizeLod ); - let sigma = 1.0 / sizeLod; + const depth = linearDepth(); + const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth ); + const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv ); - if ( i > lodMax - LOD_MIN ) { + return finalUV; - sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; +} ); - } else if ( i === 0 ) { +class SpriteSheetUVNode extends Node { - sigma = 0; + static get type() { - } + return 'SpriteSheetUVNode'; - sigmas.push( sigma ); + } - const texelSize = 1.0 / ( sizeLod - 2 ); - const min = - texelSize; - const max = 1 + texelSize; - const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { - const cubeFaces = 6; - const vertices = 6; - const positionSize = 3; - const uvSize = 2; - const faceIndexSize = 1; + super( 'vec2' ); - const position = new Float32Array( positionSize * vertices * cubeFaces ); - const uv = new Float32Array( uvSize * vertices * cubeFaces ); - const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + this.countNode = countNode; + this.uvNode = uvNode; + this.frameNode = frameNode; - for ( let face = 0; face < cubeFaces; face ++ ) { + } - const x = ( face % 3 ) * 2 / 3 - 1; - const y = face > 2 ? 0 : - 1; - const coordinates = [ - x, y, 0, - x + 2 / 3, y, 0, - x + 2 / 3, y + 1, 0, - x, y, 0, - x + 2 / 3, y + 1, 0, - x, y + 1, 0 - ]; + setup() { - const faceIdx = _faceLib[ face ]; - position.set( coordinates, positionSize * vertices * faceIdx ); - uv.set( uv1, uvSize * vertices * faceIdx ); - const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ]; - faceIndex.set( fill, faceIndexSize * vertices * faceIdx ); + const { frameNode, uvNode, countNode } = this; - } + const { width, height } = countNode; - const planes = new BufferGeometry(); - planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); - planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); - planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); - lodPlanes.push( planes ); - lodMeshes.push( new Mesh( planes, null ) ); + const frameNum = frameNode.mod( width.mul( height ) ).floor(); - if ( lod > LOD_MIN ) { + const column = frameNum.mod( width ); + const row = height.sub( frameNum.add( 1 ).div( width ).ceil() ); - lod --; + const scale = countNode.reciprocal(); + const uvFrameOffset = vec2( column, row ); - } + return uvNode.add( uvFrameOffset ).mul( scale ); } - return { lodPlanes, sizeLods, sigmas, lodMeshes }; - } -function _createRenderTarget( width, height, params ) { +const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ); - const cubeUVRenderTarget = new RenderTarget( width, height, params ); - cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; - cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; - cubeUVRenderTarget.texture.isPMREMTexture = true; - cubeUVRenderTarget.scissorTest = true; - return cubeUVRenderTarget; +class TriplanarTexturesNode extends Node { -} + static get type() { -function _setViewport( target, x, y, width, height ) { + return 'TriplanarTexturesNode'; - target.viewport.set( x, y, width, height ); - target.scissor.set( x, y, width, height ); + } -} + constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { -function _getMaterial( type ) { + super( 'vec4' ); - const material = new NodeMaterial(); - material.depthTest = false; - material.depthWrite = false; - material.blending = NoBlending; - material.name = `PMREM_${ type }`; + this.textureXNode = textureXNode; + this.textureYNode = textureYNode; + this.textureZNode = textureZNode; - return material; + this.scaleNode = scaleNode; -} + this.positionNode = positionNode; + this.normalNode = normalNode; -function _getBlurShader( lodMax, width, height ) { + } - const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) ); - const poleAxis = uniform( new Vector3( 0, 1, 0 ) ); - const dTheta = uniform( 0 ); - const n = float( MAX_SAMPLES ); - const latitudinal = uniform( 0 ); // false, bool - const samples = uniform( 1 ); // int - const envMap = texture( null ); - const mipInt = uniform( 0 ); // int - const CUBEUV_TEXEL_WIDTH = float( 1 / width ); - const CUBEUV_TEXEL_HEIGHT = float( 1 / height ); - const CUBEUV_MAX_MIP = float( lodMax ); + setup() { - const materialUniforms = { - n, - latitudinal, - weights, - poleAxis, - outputDirection, - dTheta, - samples, - envMap, - mipInt, - CUBEUV_TEXEL_WIDTH, - CUBEUV_TEXEL_HEIGHT, - CUBEUV_MAX_MIP - }; + const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this; - const material = _getMaterial( 'blur' ); - material.uniforms = materialUniforms; // TODO: Move to outside of the material - material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } ); + // Ref: https://github.com/keijiro/StandardTriplanar - return material; + // Blending factor of triplanar mapping + let bf = normalNode.abs().normalize(); + bf = bf.div( bf.dot( vec3( 1.0 ) ) ); -} + // Triplanar mapping + const tx = positionNode.yz.mul( scaleNode ); + const ty = positionNode.zx.mul( scaleNode ); + const tz = positionNode.xy.mul( scaleNode ); -function _getCubemapMaterial( envTexture ) { + // Base color + const textureX = textureXNode.value; + const textureY = textureYNode !== null ? textureYNode.value : textureX; + const textureZ = textureZNode !== null ? textureZNode.value : textureX; - const material = _getMaterial( 'cubemap' ); - material.fragmentNode = cubeTexture( envTexture, outputDirection ); + const cx = texture( textureX, tx ).mul( bf.x ); + const cy = texture( textureY, ty ).mul( bf.y ); + const cz = texture( textureZ, tz ).mul( bf.z ); - return material; + return add( cx, cy, cz ); + + } } -function _getEquirectMaterial( envTexture ) { +const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ); +const triplanarTexture = ( ...params ) => triplanarTextures( ...params ); - const material = _getMaterial( 'equirect' ); - material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 ); +const _reflectorPlane = new Plane(); +const _normal = new Vector3(); +const _reflectorWorldPosition = new Vector3(); +const _cameraWorldPosition = new Vector3(); +const _rotationMatrix = new Matrix4(); +const _lookAtPosition = new Vector3( 0, 0, - 1 ); +const clipPlane = new Vector4(); - return material; +const _view = new Vector3(); +const _target = new Vector3(); +const _q = new Vector4(); -} +const _size$2 = new Vector2(); -let _id$5 = 0; +const _defaultRT = new RenderTarget(); +const _defaultUV = screenUV.flipX(); -class BindGroup { +_defaultRT.depthTexture = new DepthTexture( 1, 1 ); - constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) { +let _inReflector = false; - this.name = name; - this.bindings = bindings; - this.index = index; - this.bindingsReference = bindingsReference; +class ReflectorNode extends TextureNode { - this.id = _id$5 ++; + static get type() { + + return 'ReflectorNode'; } -} + constructor( parameters = {} ) { -const rendererCache = new WeakMap(); + super( parameters.defaultTexture || _defaultRT.texture, _defaultUV ); -const typeFromLength = new Map( [ - [ 2, 'vec2' ], - [ 3, 'vec3' ], - [ 4, 'vec4' ], - [ 9, 'mat3' ], - [ 16, 'mat4' ] -] ); + this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters ); + this._depthNode = null; -const typeFromArray = new Map( [ - [ Int8Array, 'int' ], - [ Int16Array, 'int' ], - [ Int32Array, 'int' ], - [ Uint8Array, 'uint' ], - [ Uint16Array, 'uint' ], - [ Uint32Array, 'uint' ], - [ Float32Array, 'float' ] -] ); + this.setUpdateMatrix( false ); -const toFloat = ( value ) => { + } - if ( /e/g.test( value ) ) { + get reflector() { - return String( value ).replace( /\+/g, '' ); + return this._reflectorBaseNode; - } else { + } - value = Number( value ); + get target() { - return value + ( value % 1 ? '' : '.0' ); + return this._reflectorBaseNode.target; } -}; + getDepthNode() { -class NodeBuilder { + if ( this._depthNode === null ) { - constructor( object, renderer, parser ) { + if ( this._reflectorBaseNode.depth !== true ) { - this.object = object; - this.material = ( object && object.material ) || null; - this.geometry = ( object && object.geometry ) || null; - this.renderer = renderer; - this.parser = parser; - this.scene = null; - this.camera = null; + throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' ); - this.nodes = []; - this.sequentialNodes = []; - this.updateNodes = []; - this.updateBeforeNodes = []; - this.updateAfterNodes = []; - this.hashNodes = {}; + } - this.monitor = null; + this._depthNode = nodeObject( new ReflectorNode( { + defaultTexture: _defaultRT.depthTexture, + reflector: this._reflectorBaseNode + } ) ); - this.lightsNode = null; - this.environmentNode = null; - this.fogNode = null; + } - this.clippingContext = null; + return this._depthNode; - 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.bindings = { vertex: {}, fragment: {}, compute: {} }; - this.bindingsIndexes = {}; - this.bindGroups = null; - this.attributes = []; - this.bufferAttributes = []; - this.varyings = []; - this.codes = {}; - this.vars = {}; - this.flow = { code: '' }; - this.chaining = []; - this.stack = stack(); - this.stacks = []; - this.tab = '\t'; + setup( builder ) { - this.currentFunctionNode = null; + // ignore if used in post-processing + if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder ); - this.context = { - material: this.material - }; + return super.setup( builder ); - this.cache = new NodeCache(); - this.globalCache = this.cache; + } - this.flowsData = new WeakMap(); + clone() { - this.shaderStage = null; - this.buildStage = null; + const texture = new this.constructor( this.reflectorNode ); + texture._reflectorBaseNode = this._reflectorBaseNode; - this.useComparisonMethod = false; + return texture; } - getBindGroupsCache() { +} - let bindGroupsCache = rendererCache.get( this.renderer ); - if ( bindGroupsCache === undefined ) { +class ReflectorBaseNode extends Node { - bindGroupsCache = new ChainMap(); + static get type() { - rendererCache.set( this.renderer, bindGroupsCache ); + return 'ReflectorBaseNode'; - } + } - return bindGroupsCache; + constructor( textureNode, parameters = {} ) { - } + super(); - createRenderTarget( width, height, options ) { + const { + target = new Object3D(), + resolution = 1, + generateMipmaps = false, + bounces = true, + depth = false + } = parameters; - return new RenderTarget( width, height, options ); + // - } + this.textureNode = textureNode; - createCubeRenderTarget( size, options ) { + this.target = target; + this.resolution = resolution; + this.generateMipmaps = generateMipmaps; + this.bounces = bounces; + this.depth = depth; - return new CubeRenderTarget( size, options ); + this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME; + + this.virtualCameras = new WeakMap(); + this.renderTargets = new WeakMap(); } - createPMREMGenerator() { + _updateResolution( renderTarget, renderer ) { - // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support + const resolution = this.resolution; - return new PMREMGenerator( this.renderer ); + renderer.getDrawingBufferSize( _size$2 ); + + renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) ); } - includes( node ) { + setup( builder ) { - return this.nodes.includes( node ); + this._updateResolution( _defaultRT, builder.renderer ); + + return super.setup( builder ); } - _getBindGroup( groupName, bindings ) { + getVirtualCamera( camera ) { - const bindGroupsCache = this.getBindGroupsCache(); + let virtualCamera = this.virtualCameras.get( camera ); - // + if ( virtualCamera === undefined ) { - const bindingsArray = []; + virtualCamera = camera.clone(); - let sharedGroup = true; + this.virtualCameras.set( camera, virtualCamera ); - for ( const binding of bindings ) { + } - bindingsArray.push( binding ); + return virtualCamera; - sharedGroup = sharedGroup && binding.groupNode.shared !== true; + } - } + getRenderTarget( camera ) { - // + let renderTarget = this.renderTargets.get( camera ); - let bindGroup; + if ( renderTarget === undefined ) { - if ( sharedGroup ) { + renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } ); - bindGroup = bindGroupsCache.get( bindingsArray ); + if ( this.generateMipmaps === true ) { - if ( bindGroup === undefined ) { + renderTarget.texture.minFilter = LinearMipMapLinearFilter; + renderTarget.texture.generateMipmaps = true; - bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray ); + } - bindGroupsCache.set( bindingsArray, bindGroup ); + if ( this.depth === true ) { - } + renderTarget.depthTexture = new DepthTexture(); - } else { + } - bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray ); + this.renderTargets.set( camera, renderTarget ); } - return bindGroup; + return renderTarget; } - getBindGroupArray( groupName, shaderStage ) { + updateBefore( frame ) { - const bindings = this.bindings[ shaderStage ]; + if ( this.bounces === false && _inReflector ) return; - let bindGroup = bindings[ groupName ]; + _inReflector = true; - if ( bindGroup === undefined ) { + const { scene, camera, renderer, material } = frame; + const { target } = this; - if ( this.bindingsIndexes[ groupName ] === undefined ) { + const virtualCamera = this.getVirtualCamera( camera ); + const renderTarget = this.getRenderTarget( virtualCamera ); - this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length }; + renderer.getDrawingBufferSize( _size$2 ); - } + this._updateResolution( renderTarget, renderer ); - bindings[ groupName ] = bindGroup = []; + // - } + _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld ); + _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); - return bindGroup; + _rotationMatrix.extractRotation( target.matrixWorld ); - } + _normal.set( 0, 0, 1 ); + _normal.applyMatrix4( _rotationMatrix ); - getBindings() { + _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition ); - let bindingsGroups = this.bindGroups; + // Avoid rendering when reflector is facing away - if ( bindingsGroups === null ) { + if ( _view.dot( _normal ) > 0 ) return; - const groups = {}; - const bindings = this.bindings; + _view.reflect( _normal ).negate(); + _view.add( _reflectorWorldPosition ); - for ( const shaderStage of shaderStages ) { + _rotationMatrix.extractRotation( camera.matrixWorld ); - for ( const groupName in bindings[ shaderStage ] ) { + _lookAtPosition.set( 0, 0, - 1 ); + _lookAtPosition.applyMatrix4( _rotationMatrix ); + _lookAtPosition.add( _cameraWorldPosition ); - const uniforms = bindings[ shaderStage ][ groupName ]; + _target.subVectors( _reflectorWorldPosition, _lookAtPosition ); + _target.reflect( _normal ).negate(); + _target.add( _reflectorWorldPosition ); - const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] ); - groupUniforms.push( ...uniforms ); + // - } + virtualCamera.coordinateSystem = camera.coordinateSystem; + virtualCamera.position.copy( _view ); + virtualCamera.up.set( 0, 1, 0 ); + virtualCamera.up.applyMatrix4( _rotationMatrix ); + virtualCamera.up.reflect( _normal ); + virtualCamera.lookAt( _target ); - } + virtualCamera.near = camera.near; + virtualCamera.far = camera.far; - bindingsGroups = []; + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); - for ( const groupName in groups ) { + // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html + // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf + _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition ); + _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); - const group = groups[ groupName ]; + clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant ); - const bindingsGroup = this._getBindGroup( groupName, group ); + const projectionMatrix = virtualCamera.projectionMatrix; - bindingsGroups.push( bindingsGroup ); + _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; + _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; + _q.z = - 1.0; + _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; - } + // Calculate the scaled plane vector + clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) ); - this.bindGroups = bindingsGroups; - - } - - return bindingsGroups; - - } - - sortBindingGroups() { + const clipBias = 0; - const bindingsGroups = this.getBindings(); + // Replacing the third row of the projection matrix + projectionMatrix.elements[ 2 ] = clipPlane.x; + projectionMatrix.elements[ 6 ] = clipPlane.y; + projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias ); + projectionMatrix.elements[ 14 ] = clipPlane.w; - bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) ); + // - for ( let i = 0; i < bindingsGroups.length; i ++ ) { + this.textureNode.value = renderTarget.texture; - const bindingGroup = bindingsGroups[ i ]; - this.bindingsIndexes[ bindingGroup.name ].group = i; + if ( this.depth === true ) { - bindingGroup.index = i; + this.textureNode.getDepthNode().value = renderTarget.depthTexture; } - } - - setHashNode( node, hash ) { - - this.hashNodes[ hash ] = node; + material.visible = false; - } + const currentRenderTarget = renderer.getRenderTarget(); + const currentMRT = renderer.getMRT(); - addNode( node ) { + renderer.setMRT( null ); + renderer.setRenderTarget( renderTarget ); - if ( this.nodes.includes( node ) === false ) { + renderer.render( scene, virtualCamera ); - this.nodes.push( node ); + renderer.setMRT( currentMRT ); + renderer.setRenderTarget( currentRenderTarget ); - this.setHashNode( node, node.getHash( this ) ); + material.visible = true; - } + _inReflector = false; } - addSequentialNode( node ) { - - if ( this.sequentialNodes.includes( node ) === false ) { - - this.sequentialNodes.push( node ); - - } +} - } +const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) ); - buildUpdateNodes() { +// Helper for passes that need to fill the viewport with a single quad. - for ( const node of this.nodes ) { +const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); - const updateType = node.getUpdateType(); +// https://github.com/mrdoob/three.js/pull/21358 - if ( updateType !== NodeUpdateType.NONE ) { +class QuadGeometry extends BufferGeometry { - this.updateNodes.push( node.getSelf() ); + constructor( flipY = false ) { - } + super(); - } + const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ]; - for ( const node of this.sequentialNodes ) { + this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) ); - const updateBeforeType = node.getUpdateBeforeType(); - const updateAfterType = node.getUpdateAfterType(); + } - if ( updateBeforeType !== NodeUpdateType.NONE ) { +} - this.updateBeforeNodes.push( node.getSelf() ); +const _geometry = /*@__PURE__*/ new QuadGeometry(); - } +class QuadMesh extends Mesh { - if ( updateAfterType !== NodeUpdateType.NONE ) { + constructor( material = null ) { - this.updateAfterNodes.push( node.getSelf() ); + super( _geometry, material ); - } + this.camera = _camera; - } + this.isQuadMesh = true; } - get currentNode() { + renderAsync( renderer ) { - return this.chaining[ this.chaining.length - 1 ]; + return renderer.renderAsync( this, _camera ); } - isFilteredTexture( texture ) { + render( renderer ) { - return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || - texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ); + renderer.render( this, _camera ); } - addChain( node ) { +} - /* - if ( this.chaining.indexOf( node ) !== - 1 ) { +const _size$1 = /*@__PURE__*/ new Vector2(); - console.warn( 'Recursive node: ', node ); +class RTTNode extends TextureNode { - } - */ + static get type() { - this.chaining.push( node ); + return 'RTTNode'; } - removeChain( node ) { + constructor( node, width = null, height = null, options = { type: HalfFloatType } ) { - const lastChain = this.chaining.pop(); + const renderTarget = new RenderTarget( width, height, options ); - if ( lastChain !== node ) { + super( renderTarget.texture, uv() ); - throw new Error( 'NodeBuilder: Invalid node chaining!' ); + this.node = node; + this.width = width; + this.height = height; - } + this.renderTarget = renderTarget; - } + this.textureNeedsUpdate = true; + this.autoUpdate = true; - getMethod( method ) { + this.updateMap = new WeakMap(); - return method; + this._rttNode = null; + this._quadMesh = new QuadMesh( new NodeMaterial() ); + + this.updateBeforeType = NodeUpdateType.RENDER; } - getNodeFromHash( hash ) { + get autoSize() { - return this.hashNodes[ hash ]; + return this.width === null; } - addFlow( shaderStage, node ) { + setup( builder ) { - this.flowNodes[ shaderStage ].push( node ); + this._rttNode = this.node.context( builder.getSharedContext() ); + this._quadMesh.material.name = 'RTT'; + this._quadMesh.material.needsUpdate = true; - return node; + return super.setup( builder ); } - setContext( context ) { + setSize( width, height ) { - this.context = context; + this.width = width; + this.height = height; - } + const effectiveWidth = width * this.pixelRatio; + const effectiveHeight = height * this.pixelRatio; - getContext() { + this.renderTarget.setSize( effectiveWidth, effectiveHeight ); - return this.context; + this.textureNeedsUpdate = true; } - getSharedContext() { + setPixelRatio( pixelRatio ) { - ({ ...this.context }); + this.pixelRatio = pixelRatio; - return this.context; + this.setSize( this.width, this.height ); } - setCache( cache ) { - - this.cache = cache; - - } + updateBefore( { renderer } ) { - getCache() { + if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return; - return this.cache; + this.textureNeedsUpdate = false; - } + // - getCacheFromNode( node, parent = true ) { + if ( this.autoSize === true ) { - const data = this.getDataFromNode( node ); - if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null ); + this.pixelRatio = renderer.getPixelRatio(); - return data.cache; + const size = renderer.getSize( _size$1 ); - } + this.setSize( size.width, size.height ); - isAvailable( /*name*/ ) { + } - return false; + // - } + this._quadMesh.material.fragmentNode = this._rttNode; - getVertexIndex() { + // - console.warn( 'Abstract function.' ); + const currentRenderTarget = renderer.getRenderTarget(); - } + renderer.setRenderTarget( this.renderTarget ); - getInstanceIndex() { + this._quadMesh.render( renderer ); - console.warn( 'Abstract function.' ); + renderer.setRenderTarget( currentRenderTarget ); } - getDrawIndex() { + clone() { - console.warn( 'Abstract function.' ); + const newNode = new TextureNode( this.value, this.uvNode, this.levelNode ); + newNode.sampler = this.sampler; + newNode.referenceNode = this; + + return newNode; } - getFrontFacing() { +} - console.warn( 'Abstract function.' ); +const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) ); +const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ); - } +/** +* Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments +* depth value and the camera's inverse projection matrix. +* +* @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates. +* @param {float} depth - The fragment's depth value. +* @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix. +* @return {vec3} The fragments position in view space. +*/ +const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => { - getFragCoord() { + let clipSpacePosition; - console.warn( 'Abstract function.' ); + if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) { - } + screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 ); + clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 ); - isFlipY() { + } else { - return false; + clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 ); } - increaseUsage( node ) { + const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) ); - const nodeData = this.getDataFromNode( node ); - nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1; + return viewSpacePosition.xyz.div( viewSpacePosition.w ); - return nodeData.usageCount; +} ); - } +/** +* Computes a screen position expressed as uv coordinates based on a fragment's position in view space +* and the camera's projection matrix +* +* @param {vec3} viewPosition - The fragments position in view space. +* @param {mat4} projectionMatrix - The camera's projection matrix. +* @return {vec2} Teh fragment's screen position expressed as uv coordinates. +*/ +const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => { - generateTexture( /* texture, textureProperty, uvSnippet */ ) { + const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) ); + const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar(); + return vec2( sampleUv.x, sampleUv.y.oneMinus() ); - console.warn( 'Abstract function.' ); +} ); - } +class VertexColorNode extends AttributeNode { - generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) { + static get type() { - console.warn( 'Abstract function.' ); + return 'VertexColorNode'; } - generateConst( type, value = null ) { - - if ( value === null ) { - - if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0; - else if ( type === 'bool' ) value = false; - else if ( type === 'color' ) value = new Color(); - else if ( type === 'vec2' ) value = new Vector2(); - else if ( type === 'vec3' ) value = new Vector3(); - else if ( type === 'vec4' ) value = new Vector4(); + constructor( index = 0 ) { - } + super( null, 'vec4' ); - if ( type === 'float' ) return toFloat( value ); - if ( type === 'int' ) return `${ Math.round( value ) }`; - if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u'; - if ( type === 'bool' ) return value ? 'true' : 'false'; - if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`; + this.isVertexColorNode = true; - const typeLength = this.getTypeLength( type ); + this.index = index; - const componentType = this.getComponentType( type ); + } - const generateConst = value => this.generateConst( componentType, value ); + getAttributeName( /*builder*/ ) { - if ( typeLength === 2 ) { + const index = this.index; - return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`; + return 'color' + ( index > 0 ? index : '' ); - } else if ( typeLength === 3 ) { + } - return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`; + generate( builder ) { - } else if ( typeLength === 4 ) { + const attributeName = this.getAttributeName( builder ); + const geometryAttribute = builder.hasGeometryAttribute( attributeName ); - return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`; + let result; - } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) { + if ( geometryAttribute === true ) { - return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`; + result = super.generate( builder ); - } else if ( typeLength > 4 ) { + } else { - return `${ this.getType( type ) }()`; + // Vertex color fallback should be white + result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) ); } - throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` ); + return result; } - getType( type ) { + serialize( data ) { - if ( type === 'color' ) return 'vec3'; + super.serialize( data ); - return type; + data.index = this.index; } - hasGeometryAttribute( name ) { - - return this.geometry && this.geometry.getAttribute( name ) !== undefined; - - } + deserialize( data ) { - getAttribute( name, type ) { + super.deserialize( data ); - const attributes = this.attributes; + this.index = data.index; - // find attribute + } - for ( const attribute of attributes ) { +} - if ( attribute.name === name ) { +const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) ); - return attribute; +class PointUVNode extends Node { - } + static get type() { - } + return 'PointUVNode'; - // create a new if no exist + } - const attribute = new NodeAttribute( name, type ); + constructor() { - attributes.push( attribute ); + super( 'vec2' ); - return attribute; + this.isPointUVNode = true; } - getPropertyName( node/*, shaderStage*/ ) { + generate( /*builder*/ ) { - return node.name; + return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )'; } - isVector( type ) { +} - return /vec\d/.test( type ); +const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode ); - } +class SceneNode extends Node { - isMatrix( type ) { + static get type() { - return /mat\d/.test( type ); + return 'SceneNode'; } - isReference( type ) { - - return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D'; - - } + constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) { - needsToWorkingColorSpace( /*texture*/ ) { + super(); - return false; + this.scope = scope; + this.scene = scene; } - getComponentTypeFromTexture( texture ) { + setup( builder ) { - const type = texture.type; + const scope = this.scope; + const scene = this.scene !== null ? this.scene : builder.scene; - if ( texture.isDataTexture ) { + let output; - if ( type === IntType ) return 'int'; - if ( type === UnsignedIntType ) return 'uint'; + if ( scope === SceneNode.BACKGROUND_BLURRINESS ) { - } + output = reference( 'backgroundBlurriness', 'float', scene ); - return 'float'; + } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) { - } + output = reference( 'backgroundIntensity', 'float', scene ); - getElementType( type ) { + } else { - if ( type === 'mat2' ) return 'vec2'; - if ( type === 'mat3' ) return 'vec3'; - if ( type === 'mat4' ) return 'vec4'; + console.error( 'THREE.SceneNode: Unknown scope:', scope ); - return this.getComponentType( type ); + } - } + return output; - getComponentType( type ) { + } - type = this.getVectorType( type ); +} - if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type; +SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness'; +SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity'; - const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type ); +const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS ); +const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY ); - if ( componentType === null ) return null; +class StorageArrayElementNode extends ArrayElementNode { - if ( componentType[ 1 ] === 'b' ) return 'bool'; - if ( componentType[ 1 ] === 'i' ) return 'int'; - if ( componentType[ 1 ] === 'u' ) return 'uint'; + static get type() { - return 'float'; + return 'StorageArrayElementNode'; } - getVectorType( type ) { + constructor( storageBufferNode, indexNode ) { - if ( type === 'color' ) return 'vec3'; - if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4'; + super( storageBufferNode, indexNode ); - return type; + this.isStorageArrayElementNode = true; } - getTypeFromLength( length, componentType = 'float' ) { - - if ( length === 1 ) return componentType; - - const baseType = typeFromLength.get( length ); - const prefix = componentType === 'float' ? '' : componentType[ 0 ]; + set storageBufferNode( value ) { - return prefix + baseType; + this.node = value; } - getTypeFromArray( array ) { + get storageBufferNode() { - return typeFromArray.get( array.constructor ); + return this.node; } - getTypeFromAttribute( attribute ) { - - let dataAttribute = attribute; - - if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data; + setup( builder ) { - const array = dataAttribute.array; - const itemSize = attribute.itemSize; - const normalized = attribute.normalized; + if ( builder.isAvailable( 'storageBuffer' ) === false ) { - let arrayType; + if ( this.node.bufferObject === true ) { - if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) { + builder.setupPBO( this.node ); - arrayType = this.getTypeFromArray( array ); + } } - return this.getTypeFromLength( itemSize, arrayType ); + return super.setup( builder ); } - getTypeLength( type ) { - - const vecType = this.getVectorType( type ); - const vecNum = /vec([2-4])/.exec( vecType ); - - if ( vecNum !== null ) return Number( vecNum[ 1 ] ); - if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1; - if ( /mat2/.test( type ) === true ) return 4; - if ( /mat3/.test( type ) === true ) return 9; - if ( /mat4/.test( type ) === true ) return 16; + generate( builder, output ) { - return 0; + let snippet; - } + const isAssignContext = builder.context.assign; - getVectorFromMatrix( type ) { + // - return type.replace( 'mat', 'vec' ); + if ( builder.isAvailable( 'storageBuffer' ) === false ) { - } + if ( this.node.bufferObject === true && isAssignContext !== true ) { - changeComponentType( type, newComponentType ) { + snippet = builder.generatePBO( this ); - return this.getTypeFromLength( this.getTypeLength( type ), newComponentType ); + } else { - } + snippet = this.node.build( builder ); - getIntegerType( type ) { + } - const componentType = this.getComponentType( type ); + } else { - if ( componentType === 'int' || componentType === 'uint' ) return type; + snippet = super.generate( builder ); - return this.changeComponentType( type, 'int' ); + } - } + if ( isAssignContext !== true ) { - addStack() { + const type = this.getNodeType( builder ); - this.stack = stack( this.stack ); + snippet = builder.format( snippet, type, output ); - this.stacks.push( getCurrentStack() || this.stack ); - setCurrentStack( this.stack ); + } - return this.stack; + return snippet; } - removeStack() { - - const lastStack = this.stack; - this.stack = lastStack.parent; - - setCurrentStack( this.stacks.pop() ); - - return lastStack; +} - } +const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ); - getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) { +const GPUPrimitiveTopology = { + PointList: 'point-list', + LineList: 'line-list', + LineStrip: 'line-strip', + TriangleList: 'triangle-list', + TriangleStrip: 'triangle-strip', +}; - cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache; +const GPUCompareFunction = { + Never: 'never', + Less: 'less', + Equal: 'equal', + LessEqual: 'less-equal', + Greater: 'greater', + NotEqual: 'not-equal', + GreaterEqual: 'greater-equal', + Always: 'always' +}; - let nodeData = cache.getData( node ); +const GPUStoreOp = { + Store: 'store', + Discard: 'discard' +}; - if ( nodeData === undefined ) { +const GPULoadOp = { + Load: 'load', + Clear: 'clear' +}; - nodeData = {}; +const GPUFrontFace = { + CCW: 'ccw', + CW: 'cw' +}; - cache.setData( node, nodeData ); +const GPUCullMode = { + None: 'none', + Front: 'front', + Back: 'back' +}; - } +const GPUIndexFormat = { + Uint16: 'uint16', + Uint32: 'uint32' +}; - if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {}; +const GPUTextureFormat = { - return nodeData[ shaderStage ]; + // 8-bit formats - } + R8Unorm: 'r8unorm', + R8Snorm: 'r8snorm', + R8Uint: 'r8uint', + R8Sint: 'r8sint', - getNodeProperties( node, shaderStage = 'any' ) { + // 16-bit formats - const nodeData = this.getDataFromNode( node, shaderStage ); + R16Uint: 'r16uint', + R16Sint: 'r16sint', + R16Float: 'r16float', + RG8Unorm: 'rg8unorm', + RG8Snorm: 'rg8snorm', + RG8Uint: 'rg8uint', + RG8Sint: 'rg8sint', - return nodeData.properties || ( nodeData.properties = { outputNode: null } ); + // 32-bit formats - } + R32Uint: 'r32uint', + R32Sint: 'r32sint', + R32Float: 'r32float', + RG16Uint: 'rg16uint', + RG16Sint: 'rg16sint', + RG16Float: 'rg16float', + RGBA8Unorm: 'rgba8unorm', + RGBA8UnormSRGB: 'rgba8unorm-srgb', + RGBA8Snorm: 'rgba8snorm', + RGBA8Uint: 'rgba8uint', + RGBA8Sint: 'rgba8sint', + BGRA8Unorm: 'bgra8unorm', + BGRA8UnormSRGB: 'bgra8unorm-srgb', + // Packed 32-bit formats + RGB9E5UFloat: 'rgb9e5ufloat', + RGB10A2Unorm: 'rgb10a2unorm', + RG11B10uFloat: 'rgb10a2unorm', - getBufferAttributeFromNode( node, type ) { + // 64-bit formats - const nodeData = this.getDataFromNode( node ); + RG32Uint: 'rg32uint', + RG32Sint: 'rg32sint', + RG32Float: 'rg32float', + RGBA16Uint: 'rgba16uint', + RGBA16Sint: 'rgba16sint', + RGBA16Float: 'rgba16float', - let bufferAttribute = nodeData.bufferAttribute; + // 128-bit formats - if ( bufferAttribute === undefined ) { + RGBA32Uint: 'rgba32uint', + RGBA32Sint: 'rgba32sint', + RGBA32Float: 'rgba32float', - const index = this.uniforms.index ++; + // Depth and stencil formats - bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node ); + Stencil8: 'stencil8', + Depth16Unorm: 'depth16unorm', + Depth24Plus: 'depth24plus', + Depth24PlusStencil8: 'depth24plus-stencil8', + Depth32Float: 'depth32float', - this.bufferAttributes.push( bufferAttribute ); + // 'depth32float-stencil8' extension - nodeData.bufferAttribute = bufferAttribute; + Depth32FloatStencil8: 'depth32float-stencil8', - } + // BC compressed formats usable if 'texture-compression-bc' is both + // supported by the device/user agent and enabled in requestDevice. - return bufferAttribute; + BC1RGBAUnorm: 'bc1-rgba-unorm', + BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb', + BC2RGBAUnorm: 'bc2-rgba-unorm', + BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb', + BC3RGBAUnorm: 'bc3-rgba-unorm', + BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb', + BC4RUnorm: 'bc4-r-unorm', + BC4RSnorm: 'bc4-r-snorm', + BC5RGUnorm: 'bc5-rg-unorm', + BC5RGSnorm: 'bc5-rg-snorm', + BC6HRGBUFloat: 'bc6h-rgb-ufloat', + BC6HRGBFloat: 'bc6h-rgb-float', + BC7RGBAUnorm: 'bc7-rgba-unorm', + BC7RGBAUnormSRGB: 'bc7-rgba-srgb', - } + // ETC2 compressed formats usable if 'texture-compression-etc2' is both + // supported by the device/user agent and enabled in requestDevice. - getStructTypeFromNode( node, shaderStage = this.shaderStage ) { + ETC2RGB8Unorm: 'etc2-rgb8unorm', + ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb', + ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm', + ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb', + ETC2RGBA8Unorm: 'etc2-rgba8unorm', + ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb', + EACR11Unorm: 'eac-r11unorm', + EACR11Snorm: 'eac-r11snorm', + EACRG11Unorm: 'eac-rg11unorm', + EACRG11Snorm: 'eac-rg11snorm', - const nodeData = this.getDataFromNode( node, shaderStage ); + // ASTC compressed formats usable if 'texture-compression-astc' is both + // supported by the device/user agent and enabled in requestDevice. - if ( nodeData.structType === undefined ) { + ASTC4x4Unorm: 'astc-4x4-unorm', + ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb', + ASTC5x4Unorm: 'astc-5x4-unorm', + ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb', + ASTC5x5Unorm: 'astc-5x5-unorm', + ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb', + ASTC6x5Unorm: 'astc-6x5-unorm', + ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb', + ASTC6x6Unorm: 'astc-6x6-unorm', + ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb', + ASTC8x5Unorm: 'astc-8x5-unorm', + ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb', + ASTC8x6Unorm: 'astc-8x6-unorm', + ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb', + ASTC8x8Unorm: 'astc-8x8-unorm', + ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb', + ASTC10x5Unorm: 'astc-10x5-unorm', + ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb', + ASTC10x6Unorm: 'astc-10x6-unorm', + ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb', + ASTC10x8Unorm: 'astc-10x8-unorm', + ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb', + ASTC10x10Unorm: 'astc-10x10-unorm', + ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb', + ASTC12x10Unorm: 'astc-12x10-unorm', + ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb', + ASTC12x12Unorm: 'astc-12x12-unorm', + ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb', - const index = this.structs.index ++; +}; - node.name = `StructType${ index }`; - this.structs[ shaderStage ].push( node ); +const GPUAddressMode = { + ClampToEdge: 'clamp-to-edge', + Repeat: 'repeat', + MirrorRepeat: 'mirror-repeat' +}; - nodeData.structType = node; +const GPUFilterMode = { + Linear: 'linear', + Nearest: 'nearest' +}; - } +const GPUBlendFactor = { + Zero: 'zero', + One: 'one', + Src: 'src', + OneMinusSrc: 'one-minus-src', + SrcAlpha: 'src-alpha', + OneMinusSrcAlpha: 'one-minus-src-alpha', + Dst: 'dst', + OneMinusDstColor: 'one-minus-dst', + DstAlpha: 'dst-alpha', + OneMinusDstAlpha: 'one-minus-dst-alpha', + SrcAlphaSaturated: 'src-alpha-saturated', + Constant: 'constant', + OneMinusConstant: 'one-minus-constant' +}; - return node; +const GPUBlendOperation = { + Add: 'add', + Subtract: 'subtract', + ReverseSubtract: 'reverse-subtract', + Min: 'min', + Max: 'max' +}; - } +const GPUColorWriteFlags = { + None: 0, + Red: 0x1, + Green: 0x2, + Blue: 0x4, + Alpha: 0x8, + All: 0xF +}; - getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) { +const GPUStencilOperation = { + Keep: 'keep', + Zero: 'zero', + Replace: 'replace', + Invert: 'invert', + IncrementClamp: 'increment-clamp', + DecrementClamp: 'decrement-clamp', + IncrementWrap: 'increment-wrap', + DecrementWrap: 'decrement-wrap' +}; - const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache ); +const GPUBufferBindingType = { + Uniform: 'uniform', + Storage: 'storage', + ReadOnlyStorage: 'read-only-storage' +}; - let nodeUniform = nodeData.uniform; +const GPUStorageTextureAccess = { + WriteOnly: 'write-only', + ReadOnly: 'read-only', + ReadWrite: 'read-write', +}; - if ( nodeUniform === undefined ) { +const GPUTextureSampleType = { + Float: 'float', + UnfilterableFloat: 'unfilterable-float', + Depth: 'depth', + SInt: 'sint', + UInt: 'uint' +}; - const index = this.uniforms.index ++; +const GPUTextureDimension = { + OneD: '1d', + TwoD: '2d', + ThreeD: '3d' +}; - nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node ); +const GPUTextureViewDimension = { + OneD: '1d', + TwoD: '2d', + TwoDArray: '2d-array', + Cube: 'cube', + CubeArray: 'cube-array', + ThreeD: '3d' +}; - this.uniforms[ shaderStage ].push( nodeUniform ); +const GPUTextureAspect = { + All: 'all', + StencilOnly: 'stencil-only', + DepthOnly: 'depth-only' +}; - nodeData.uniform = nodeUniform; +const GPUInputStepMode = { + Vertex: 'vertex', + Instance: 'instance' +}; - } +const GPUFeatureName = { + DepthClipControl: 'depth-clip-control', + Depth32FloatStencil8: 'depth32float-stencil8', + TextureCompressionBC: 'texture-compression-bc', + TextureCompressionETC2: 'texture-compression-etc2', + TextureCompressionASTC: 'texture-compression-astc', + TimestampQuery: 'timestamp-query', + IndirectFirstInstance: 'indirect-first-instance', + ShaderF16: 'shader-f16', + RG11B10UFloat: 'rg11b10ufloat-renderable', + BGRA8UNormStorage: 'bgra8unorm-storage', + Float32Filterable: 'float32-filterable', + ClipDistances: 'clip-distances', + DualSourceBlending: 'dual-source-blending', + Subgroups: 'subgroups' +}; - return nodeUniform; +class StorageBufferNode extends BufferNode { + + static get type() { + + return 'StorageBufferNode'; } - getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) { + constructor( value, bufferType, bufferCount = 0 ) { - const nodeData = this.getDataFromNode( node, shaderStage ); + super( value, bufferType, bufferCount ); - let nodeVar = nodeData.variable; + this.isStorageBufferNode = true; - if ( nodeVar === undefined ) { + this.access = GPUBufferBindingType.Storage; + this.isAtomic = false; - const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] ); + this.bufferObject = false; + this.bufferCount = bufferCount; - if ( name === null ) name = 'nodeVar' + vars.length; + this._attribute = null; + this._varying = null; - nodeVar = new NodeVar( name, type ); + this.global = true; - vars.push( nodeVar ); + if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) { - nodeData.variable = nodeVar; + // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer - } + if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true; + else value.isStorageBufferAttribute = true; - return nodeVar; + } } - getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) { - - const nodeData = this.getDataFromNode( node, 'any' ); + getHash( builder ) { - let nodeVarying = nodeData.varying; + if ( this.bufferCount === 0 ) { - if ( nodeVarying === undefined ) { + let bufferData = builder.globalCache.getData( this.value ); - const varyings = this.varyings; - const index = varyings.length; + if ( bufferData === undefined ) { - if ( name === null ) name = 'nodeVarying' + index; + bufferData = { + node: this + }; - nodeVarying = new NodeVarying( name, type ); + builder.globalCache.setData( this.value, bufferData ); - varyings.push( nodeVarying ); + } - nodeData.varying = nodeVarying; + return bufferData.node.uuid; } - return nodeVarying; + return this.uuid; } - getCodeFromNode( node, type, shaderStage = this.shaderStage ) { + getInputType( /*builder*/ ) { - const nodeData = this.getDataFromNode( node ); + return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer'; - let nodeCode = nodeData.code; + } - if ( nodeCode === undefined ) { + element( indexNode ) { - const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] ); - const index = codes.length; + return storageElement( this, indexNode ); - nodeCode = new NodeCode( 'nodeCode' + index, type ); + } - codes.push( nodeCode ); + setBufferObject( value ) { - nodeData.code = nodeCode; + this.bufferObject = value; - } + return this; - return nodeCode; + } + + setAccess( value ) { + + this.access = value; + + return this; } - addFlowCodeHierarchy( node, nodeBlock ) { + toReadOnly() { - const { flowCodes, flowCodeBlock } = this.getDataFromNode( node ); + return this.setAccess( GPUBufferBindingType.ReadOnlyStorage ); - let needsFlowCode = true; - let nodeBlockHierarchy = nodeBlock; + } - while ( nodeBlockHierarchy ) { + setAtomic( value ) { - if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) { + this.isAtomic = value; - needsFlowCode = false; - break; + return this; - } + } - nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock; + toAtomic() { - } + return this.setAtomic( true ); - if ( needsFlowCode ) { + } - for ( const flowCode of flowCodes ) { + getAttributeData() { - this.addLineFlowCode( flowCode ); + if ( this._attribute === null ) { - } + this._attribute = bufferAttribute( this.value ); + this._varying = varying( this._attribute ); } + return { + attribute: this._attribute, + varying: this._varying + }; + } - addLineFlowCodeBlock( node, code, nodeBlock ) { + getNodeType( builder ) { - const nodeData = this.getDataFromNode( node ); - const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] ); - const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() ); + if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) { - flowCodes.push( code ); - codeBlock.set( nodeBlock, true ); + return super.getNodeType( builder ); - } + } - addLineFlowCode( code, node = null ) { + const { attribute } = this.getAttributeData(); - if ( code === '' ) return this; + return attribute.getNodeType( builder ); - if ( node !== null && this.context.nodeBlock ) { + } - this.addLineFlowCodeBlock( node, code, this.context.nodeBlock ); + generate( builder ) { - } + if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) { - code = this.tab + code; + return super.generate( builder ); - if ( ! /;\s*$/.test( code ) ) { + } - code = code + ';\n'; + const { attribute, varying } = this.getAttributeData(); - } + const output = varying.build( builder ); - this.flow.code += code; + builder.registerTransform( output, attribute ); - return this; + return output; } - addFlowCode( code ) { +} - this.flow.code += code; +// Read-Write Storage +const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) ); +const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) ); - return this; +class StorageTextureNode extends TextureNode { - } + static get type() { - addFlowTab() { + return 'StorageTextureNode'; - this.tab += '\t'; + } - return this; + constructor( value, uvNode, storeNode = null ) { - } + super( value, uvNode ); - removeFlowTab() { + this.storeNode = storeNode; - this.tab = this.tab.slice( 0, - 1 ); + this.isStorageTextureNode = true; - return this; + this.access = GPUStorageTextureAccess.WriteOnly; } - getFlowData( node/*, shaderStage*/ ) { + getInputType( /*builder*/ ) { - return this.flowsData.get( node ); + return 'storageTexture'; } - flowNode( node ) { + setup( builder ) { - const output = node.getNodeType( this ); + super.setup( builder ); - const flowData = this.flowChildNode( node, output ); + const properties = builder.getNodeProperties( this ); + properties.storeNode = this.storeNode; - this.flowsData.set( node, flowData ); + } - return flowData; + setAccess( value ) { + + this.access = value; + return this; } - buildFunctionNode( shaderNode ) { + generate( builder, output ) { - const fn = new FunctionNode(); + let snippet; - const previous = this.currentFunctionNode; + if ( this.storeNode !== null ) { - this.currentFunctionNode = fn; + snippet = this.generateStore( builder ); - fn.code = this.buildFunctionCode( shaderNode ); + } else { - this.currentFunctionNode = previous; + snippet = super.generate( builder, output ); - return fn; + } + + return snippet; } - flowShaderNode( shaderNode ) { + toReadOnly() { - const layout = shaderNode.layout; + return this.setAccess( GPUStorageTextureAccess.ReadOnly ); - const inputs = { - [ Symbol.iterator ]() { + } - let index = 0; - const values = Object.values( this ); - return { - next: () => ( { - value: values[ index ], - done: index ++ >= values.length - } ) - }; - - } - }; + toWriteOnly() { - for ( const input of layout.inputs ) { + return this.setAccess( GPUStorageTextureAccess.WriteOnly ); - inputs[ input.name ] = new ParameterNode( input.type, input.name ); + } - } + generateStore( builder ) { - // + const properties = builder.getNodeProperties( this ); - shaderNode.layout = null; + const { uvNode, storeNode } = properties; - const callNode = shaderNode.call( inputs ); - const flowData = this.flowStagesNode( callNode, layout.type ); + const textureProperty = super.generate( builder, 'property' ); + const uvSnippet = uvNode.build( builder, 'uvec2' ); + const storeSnippet = storeNode.build( builder, 'vec4' ); - shaderNode.layout = layout; + const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet ); - return flowData; + builder.addLineFlowCode( snippet, this ); } - flowStagesNode( node, output = null ) { - - const previousFlow = this.flow; - const previousVars = this.vars; - const previousCache = this.cache; - const previousBuildStage = this.buildStage; - const previousStack = this.stack; - - const flow = { - code: '' - }; - - this.flow = flow; - this.vars = {}; - this.cache = new NodeCache(); - this.stack = stack(); - - for ( const buildStage of defaultBuildStages ) { - - this.setBuildStage( buildStage ); +} - flow.result = node.build( this, output ); +const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ); - } +const textureStore = ( value, uvNode, storeNode ) => { - flow.vars = this.getVars( this.shaderStage ); + const node = storageTexture( value, uvNode, storeNode ); - this.flow = previousFlow; - this.vars = previousVars; - this.cache = previousCache; - this.stack = previousStack; + if ( storeNode !== null ) node.append(); - this.setBuildStage( previousBuildStage ); + return node; - return flow; +}; - } +class UserDataNode extends ReferenceNode { - getFunctionOperator() { + static get type() { - return null; + return 'UserDataNode'; } - flowChildNode( node, output = null ) { + constructor( property, inputType, userData = null ) { - const previousFlow = this.flow; + super( property, inputType, userData ); - const flow = { - code: '' - }; + this.userData = userData; - this.flow = flow; + } - flow.result = node.build( this, output ); + updateReference( state ) { - this.flow = previousFlow; + this.reference = this.userData !== null ? this.userData : state.object.userData; - return flow; + return this.reference; } - flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) { - - const previousShaderStage = this.shaderStage; - - this.setShaderStage( shaderStage ); +} - const flowData = this.flowChildNode( node, output ); +const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) ); - if ( propertyName !== null ) { +const _objectData = new WeakMap(); - flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`; +class VelocityNode extends TempNode { - } + static get type() { - this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code; + return 'VelocityNode'; - this.setShaderStage( previousShaderStage ); + } - return flowData; + constructor() { - } + super( 'vec2' ); - getAttributesArray() { + this.updateType = NodeUpdateType.OBJECT; + this.updateAfterType = NodeUpdateType.OBJECT; - return this.attributes.concat( this.bufferAttributes ); + this.previousModelWorldMatrix = uniform( new Matrix4() ); + this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup ); + this.previousCameraViewMatrix = uniform( new Matrix4() ); } - getAttributes( /*shaderStage*/ ) { + update( { frameId, camera, object } ) { - console.warn( 'Abstract function.' ); + const previousModelMatrix = getPreviousMatrix( object ); - } + this.previousModelWorldMatrix.value.copy( previousModelMatrix ); - getVaryings( /*shaderStage*/ ) { + // - console.warn( 'Abstract function.' ); + const cameraData = getData( camera ); - } + if ( cameraData.frameId !== frameId ) { - getVar( type, name ) { + cameraData.frameId = frameId; - return `${ this.getType( type ) } ${ name }`; + if ( cameraData.previousProjectionMatrix === undefined ) { - } + cameraData.previousProjectionMatrix = new Matrix4(); + cameraData.previousCameraViewMatrix = new Matrix4(); - getVars( shaderStage ) { + cameraData.currentProjectionMatrix = new Matrix4(); + cameraData.currentCameraViewMatrix = new Matrix4(); - let snippet = ''; + cameraData.previousProjectionMatrix.copy( camera.projectionMatrix ); + cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse ); - const vars = this.vars[ shaderStage ]; + } else { - if ( vars !== undefined ) { + cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix ); + cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix ); - for ( const variable of vars ) { + } - snippet += `${ this.getVar( variable.type, variable.name ) }; `; + cameraData.currentProjectionMatrix.copy( camera.projectionMatrix ); + cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse ); - } + this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix ); + this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix ); } - return snippet; - } - getUniforms( /*shaderStage*/ ) { + updateAfter( { object } ) { - console.warn( 'Abstract function.' ); + getPreviousMatrix( object ).copy( object.matrixWorld ); } - getCodes( shaderStage ) { + setup( /*builder*/ ) { - const codes = this.codes[ shaderStage ]; + const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix ); - let code = ''; + const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal ); + const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious ); - if ( codes !== undefined ) { + const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w ); + const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w ); - for ( const nodeCode of codes ) { + const velocity = sub( ndcPositionCurrent, ndcPositionPrevious ); - code += nodeCode.code + '\n'; + return velocity; - } + } - } +} - return code; +function getData( object ) { - } + let objectData = _objectData.get( object ); - getHash() { + if ( objectData === undefined ) { - return this.vertexShader + this.fragmentShader + this.computeShader; + objectData = {}; + _objectData.set( object, objectData ); } - setShaderStage( shaderStage ) { - - this.shaderStage = shaderStage; + return objectData; - } +} - getShaderStage() { +function getPreviousMatrix( object, index = 0 ) { - return this.shaderStage; + const objectData = getData( object ); - } + let matrix = objectData[ index ]; - setBuildStage( buildStage ) { + if ( matrix === undefined ) { - this.buildStage = buildStage; + objectData[ index ] = matrix = new Matrix4(); } - getBuildStage() { + return matrix; - return this.buildStage; +} - } +const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode ); - buildCode() { +const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { - console.warn( 'Abstract function.' ); + return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus(); - } +} ).setLayout( { + name: 'burnBlend', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] +} ); - build() { +const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { - const { object, material, renderer } = this; + return min$1( base.div( blend.oneMinus() ), 1.0 ); - if ( material !== null ) { +} ).setLayout( { + name: 'dodgeBlend', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] +} ); - let nodeMaterial = renderer.nodes.library.fromMaterial( material ); +const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { - if ( nodeMaterial === null ) { + return base.oneMinus().mul( blend.oneMinus() ).oneMinus(); - console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` ); +} ).setLayout( { + name: 'screenBlend', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] +} ); - nodeMaterial = new NodeMaterial(); +const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { - } + return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) ); - nodeMaterial.build( this ); +} ).setLayout( { + name: 'overlayBlend', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] +} ); - } else { +const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => { - this.addFlow( 'compute', object ); + return luminance( color.rgb ); - } +} ); - // setup() -> stage 1: create possible new nodes and returns an output reference node - // analyze() -> stage 2: analyze nodes to possible optimization and validation - // generate() -> stage 3: generate shader +const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { - for ( const buildStage of defaultBuildStages ) { + return adjustment.mix( luminance( color.rgb ), color.rgb ); - this.setBuildStage( buildStage ); +} ); - if ( this.context.vertex && this.context.vertex.isNode ) { +const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { - this.flowNodeFromShaderStage( 'vertex', this.context.vertex ); + const average = add( color.r, color.g, color.b ).div( 3.0 ); - } + const mx = color.r.max( color.g.max( color.b ) ); + const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 ); - for ( const shaderStage of shaderStages ) { + return mix( color.rgb, mx, amt ); - this.setShaderStage( shaderStage ); +} ); - const flowNodes = this.flowNodes[ shaderStage ]; +const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { - for ( const node of flowNodes ) { + const k = vec3( 0.57735, 0.57735, 0.57735 ); - if ( buildStage === 'generate' ) { + const cosAngle = adjustment.cos(); - this.flowNode( node ); + return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) ); - } else { +} ); - node.build( this ); +const luminance = ( + color, + luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) ) +) => dot( color, luminanceCoefficients ); - } +const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) ); - } +/** + * Color Decision List (CDL) v1.2 + * + * Compact representation of color grading information, defined by slope, offset, power, and + * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc, + * or AgX Log), and will return output in the same space. Output may require clamping >=0. + * + * @param {vec4} color Input (-Infinity < input < +Infinity) + * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity) + * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1) + * @param {number | vec3} power Power (0 < power < +Infinity) + * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4) + * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709 + * @return Output, -Infinity < output < +Infinity + * + * References: + * - ASC CDL v1.2 + * - https://blender.stackexchange.com/a/55239/43930 + * - https://docs.acescentral.com/specifications/acescc/ + */ +const cdl = /*@__PURE__*/ Fn( ( [ + color, + slope = vec3( 1 ), + offset = vec3( 0 ), + power = vec3( 1 ), + saturation = float( 1 ), + // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients. + luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) ) +] ) => { - } + // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the + // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support + // values outside [0, 1], requiring a workaround for negative values in the power expression. - } + const luma = color.rgb.dot( vec3( luminanceCoefficients ) ); - this.setBuildStage( null ); - this.setShaderStage( null ); + const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar(); + const pv = v.pow( power ).toVar(); - // stage 4: build code for a specific output + If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line + If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line + If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line - this.buildCode(); - this.buildUpdateNodes(); + v.assign( luma.add( v.sub( luma ).mul( saturation ) ) ); - return this; + return vec4( v.rgb, color.a ); - } +} ); - getNodeUniform( uniformNode, type ) { +class PosterizeNode extends TempNode { - if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode ); - if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode ); - if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode ); - if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode ); - if ( type === 'color' ) return new ColorNodeUniform( uniformNode ); - if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode ); - if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode ); + static get type() { - throw new Error( `Uniform "${type}" not declared.` ); + return 'PosterizeNode'; } - createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168 - - throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` ); + constructor( sourceNode, stepsNode ) { - } + super(); - format( snippet, fromType, toType ) { + this.sourceNode = sourceNode; + this.stepsNode = stepsNode; - fromType = this.getVectorType( fromType ); - toType = this.getVectorType( toType ); + } - if ( fromType === toType || toType === null || this.isReference( toType ) ) { + setup() { - return snippet; + const { sourceNode, stepsNode } = this; - } + return sourceNode.mul( stepsNode ).floor().div( stepsNode ); - const fromTypeLength = this.getTypeLength( fromType ); - const toTypeLength = this.getTypeLength( toType ); + } - if ( fromTypeLength === 16 && toTypeLength === 9 ) { +} - return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`; +const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ); - } +let _sharedFramebuffer = null; - if ( fromTypeLength === 9 && toTypeLength === 4 ) { +class ViewportSharedTextureNode extends ViewportTextureNode { - return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`; + static get type() { - } + return 'ViewportSharedTextureNode'; + } - if ( fromTypeLength > 4 ) { // fromType is matrix-like + constructor( uvNode = screenUV, levelNode = null ) { - // @TODO: ignore for now + if ( _sharedFramebuffer === null ) { - return snippet; + _sharedFramebuffer = new FramebufferTexture(); } - if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown - - // @TODO: ignore for now + super( uvNode, levelNode, _sharedFramebuffer ); - return snippet; + } - } + updateReference() { - if ( fromTypeLength === toTypeLength ) { + return this; - return `${ this.getType( toType ) }( ${ snippet } )`; + } - } +} - if ( fromTypeLength > toTypeLength ) { +const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ); - return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType ); +const _size = /*@__PURE__*/ new Vector2(); - } +class PassTextureNode extends TextureNode { - if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like + static get type() { - return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`; + return 'PassTextureNode'; - } + } - if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like + constructor( passNode, texture ) { - return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`; + super( texture ); - } + this.passNode = passNode; - if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like + this.setUpdateMatrix( false ); - // convert a number value to vector type, e.g: - // vec3( 1u ) -> vec3( float( 1u ) ) + } - snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`; + setup( builder ) { - } + if ( builder.object.isQuadMesh ) this.passNode.build( builder ); - return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like + return super.setup( builder ); } - getSignature() { + clone() { - return `// Three.js r${ REVISION } - Node System\n`; + return new this.constructor( this.passNode, this.value ); } } -class NodeFrame { +class PassMultipleTextureNode extends PassTextureNode { - constructor() { + static get type() { - this.time = 0; - this.deltaTime = 0; + return 'PassMultipleTextureNode'; - this.frameId = 0; - this.renderId = 0; + } - this.startTime = null; + constructor( passNode, textureName, previousTexture = false ) { - this.updateMap = new WeakMap(); - this.updateBeforeMap = new WeakMap(); - this.updateAfterMap = new WeakMap(); + super( passNode, null ); - this.renderer = null; - this.material = null; - this.camera = null; - this.object = null; - this.scene = null; + this.textureName = textureName; + this.previousTexture = previousTexture; } - _getMaps( referenceMap, nodeRef ) { - - let maps = referenceMap.get( nodeRef ); + updateTexture() { - if ( maps === undefined ) { + this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName ); - maps = { - renderMap: new WeakMap(), - frameMap: new WeakMap() - }; + } - referenceMap.set( nodeRef, maps ); + setup( builder ) { - } + this.updateTexture(); - return maps; + return super.setup( builder ); } - updateBeforeNode( node ) { + clone() { - const updateType = node.getUpdateBeforeType(); - const reference = node.updateReference( this ); + return new this.constructor( this.passNode, this.textureName, this.previousTexture ); - if ( updateType === NodeUpdateType.FRAME ) { + } - const { frameMap } = this._getMaps( this.updateBeforeMap, reference ); +} - if ( frameMap.get( reference ) !== this.frameId ) { +class PassNode extends TempNode { - if ( node.updateBefore( this ) !== false ) { + static get type() { - frameMap.set( reference, this.frameId ); + return 'PassNode'; - } + } - } + constructor( scope, scene, camera, options = {} ) { - } else if ( updateType === NodeUpdateType.RENDER ) { + super( 'vec4' ); - const { renderMap } = this._getMaps( this.updateBeforeMap, reference ); - - if ( renderMap.get( reference ) !== this.renderId ) { - - if ( node.updateBefore( this ) !== false ) { - - renderMap.set( reference, this.renderId ); - - } - - } - - } else if ( updateType === NodeUpdateType.OBJECT ) { - - node.updateBefore( this ); - - } - - } - - updateAfterNode( node ) { + this.scope = scope; + this.scene = scene; + this.camera = camera; + this.options = options; - const updateType = node.getUpdateAfterType(); - const reference = node.updateReference( this ); + this._pixelRatio = 1; + this._width = 1; + this._height = 1; - if ( updateType === NodeUpdateType.FRAME ) { + const depthTexture = new DepthTexture(); + depthTexture.isRenderTargetTexture = true; + //depthTexture.type = FloatType; + depthTexture.name = 'depth'; - const { frameMap } = this._getMaps( this.updateAfterMap, reference ); + const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } ); + renderTarget.texture.name = 'output'; + renderTarget.depthTexture = depthTexture; - if ( frameMap.get( reference ) !== this.frameId ) { + this.renderTarget = renderTarget; - if ( node.updateAfter( this ) !== false ) { + this.updateBeforeType = NodeUpdateType.FRAME; - frameMap.set( reference, this.frameId ); + this._textures = { + output: renderTarget.texture, + depth: depthTexture + }; - } + this._textureNodes = {}; + this._linearDepthNodes = {}; + this._viewZNodes = {}; - } + this._previousTextures = {}; + this._previousTextureNodes = {}; - } else if ( updateType === NodeUpdateType.RENDER ) { + this._cameraNear = uniform( 0 ); + this._cameraFar = uniform( 0 ); - const { renderMap } = this._getMaps( this.updateAfterMap, reference ); + this._mrt = null; - if ( renderMap.get( reference ) !== this.renderId ) { + this.isPassNode = true; - if ( node.updateAfter( this ) !== false ) { + } - renderMap.set( reference, this.renderId ); + setMRT( mrt ) { - } + this._mrt = mrt; - } + return this; - } else if ( updateType === NodeUpdateType.OBJECT ) { + } - node.updateAfter( this ); + getMRT() { - } + return this._mrt; } - updateNode( node ) { + isGlobal() { - const updateType = node.getUpdateType(); - const reference = node.updateReference( this ); + return true; - if ( updateType === NodeUpdateType.FRAME ) { + } - const { frameMap } = this._getMaps( this.updateMap, reference ); + getTexture( name ) { - if ( frameMap.get( reference ) !== this.frameId ) { + let texture = this._textures[ name ]; - if ( node.update( this ) !== false ) { + if ( texture === undefined ) { - frameMap.set( reference, this.frameId ); + const refTexture = this.renderTarget.texture; - } + texture = refTexture.clone(); + texture.isRenderTargetTexture = true; + texture.name = name; - } + this._textures[ name ] = texture; - } else if ( updateType === NodeUpdateType.RENDER ) { + this.renderTarget.textures.push( texture ); - const { renderMap } = this._getMaps( this.updateMap, reference ); + } - if ( renderMap.get( reference ) !== this.renderId ) { + return texture; - if ( node.update( this ) !== false ) { + } - renderMap.set( reference, this.renderId ); + getPreviousTexture( name ) { - } + let texture = this._previousTextures[ name ]; - } + if ( texture === undefined ) { - } else if ( updateType === NodeUpdateType.OBJECT ) { + texture = this.getTexture( name ).clone(); + texture.isRenderTargetTexture = true; - node.update( this ); + this._previousTextures[ name ] = texture; } - } - - update() { - - this.frameId ++; - - if ( this.lastTime === undefined ) this.lastTime = performance.now(); - - this.deltaTime = ( performance.now() - this.lastTime ) / 1000; - - this.lastTime = performance.now(); - - this.time += this.deltaTime; + return texture; } -} - -class NodeFunctionInput { - - constructor( type, name, count = null, qualifier = '', isConst = false ) { + toggleTexture( name ) { - this.type = type; - this.name = name; - this.count = count; - this.qualifier = qualifier; - this.isConst = isConst; + const prevTexture = this._previousTextures[ name ]; - } + if ( prevTexture !== undefined ) { -} + const texture = this._textures[ name ]; -NodeFunctionInput.isNodeFunctionInput = true; + const index = this.renderTarget.textures.indexOf( texture ); + this.renderTarget.textures[ index ] = prevTexture; -class StructTypeNode extends Node { + this._textures[ name ] = prevTexture; + this._previousTextures[ name ] = texture; - static get type() { + this._textureNodes[ name ].updateTexture(); + this._previousTextureNodes[ name ].updateTexture(); - return 'StructTypeNode'; + } } - constructor( types ) { + getTextureNode( name = 'output' ) { - super(); + let textureNode = this._textureNodes[ name ]; - this.types = types; - this.isStructTypeNode = true; + if ( textureNode === undefined ) { - } + this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) ); + this._textureNodes[ name ].updateTexture(); - getMemberTypes() { + } - return this.types; + return textureNode; } -} - -class OutputStructNode extends Node { - - static get type() { + getPreviousTextureNode( name = 'output' ) { - return 'OutputStructNode'; + let textureNode = this._previousTextureNodes[ name ]; - } + if ( textureNode === undefined ) { - constructor( ...members ) { + if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name ); - super(); + this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) ); + this._previousTextureNodes[ name ].updateTexture(); - this.members = members; + } - this.isOutputStructNode = true; + return textureNode; } - setup( builder ) { + getViewZNode( name = 'depth' ) { - super.setup( builder ); + let viewZNode = this._viewZNodes[ name ]; - const members = this.members; - const types = []; + if ( viewZNode === undefined ) { - for ( let i = 0; i < members.length; i ++ ) { + const cameraNear = this._cameraNear; + const cameraFar = this._cameraFar; - types.push( members[ i ].getNodeType( builder ) ); + this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar ); } - this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name; + return viewZNode; } - generate( builder, output ) { + getLinearDepthNode( name = 'depth' ) { - const propertyName = builder.getOutputStructName(); - const members = this.members; + let linearDepthNode = this._linearDepthNodes[ name ]; - const structPrefix = propertyName !== '' ? propertyName + '.' : ''; + if ( linearDepthNode === undefined ) { - for ( let i = 0; i < members.length; i ++ ) { + const cameraNear = this._cameraNear; + const cameraFar = this._cameraFar; + const viewZNode = this.getViewZNode( name ); - const snippet = members[ i ].build( builder, output ); + // TODO: just if ( builder.camera.isPerspectiveCamera ) - builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this ); + this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar ); } - return propertyName; + return linearDepthNode; } -} + setup( { renderer } ) { -const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode ); + this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples; -function getTextureIndex( textures, name ) { + // Disable MSAA for WebGL backend for now + if ( renderer.backend.isWebGLBackend === true ) { - for ( let i = 0; i < textures.length; i ++ ) { + this.renderTarget.samples = 0; - if ( textures[ i ].name === name ) { + } - return i; + this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1; - } + return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode(); } - return - 1; + updateBefore( frame ) { -} + const { renderer } = frame; + const { scene, camera } = this; -class MRTNode extends OutputStructNode { + this._pixelRatio = renderer.getPixelRatio(); - static get type() { + const size = renderer.getSize( _size ); - return 'MRTNode'; + this.setSize( size.width, size.height ); - } + const currentRenderTarget = renderer.getRenderTarget(); + const currentMRT = renderer.getMRT(); - constructor( outputNodes ) { + this._cameraNear.value = camera.near; + this._cameraFar.value = camera.far; - super(); + for ( const name in this._previousTextures ) { - this.outputNodes = outputNodes; + this.toggleTexture( name ); - this.isMRTNode = true; + } - } + renderer.setRenderTarget( this.renderTarget ); + renderer.setMRT( this._mrt ); - has( name ) { + renderer.render( scene, camera ); - return this.outputNodes[ name ] !== undefined; + renderer.setRenderTarget( currentRenderTarget ); + renderer.setMRT( currentMRT ); } - get( name ) { - - return this.outputNodes[ name ]; - - } + setSize( width, height ) { - merge( mrtNode ) { + this._width = width; + this._height = height; - const outputs = { ...this.outputNodes, ...mrtNode.outputNodes }; + const effectiveWidth = this._width * this._pixelRatio; + const effectiveHeight = this._height * this._pixelRatio; - return mrt( outputs ); + this.renderTarget.setSize( effectiveWidth, effectiveHeight ); } - setup( builder ) { - - const outputNodes = this.outputNodes; - const mrt = builder.renderer.getRenderTarget(); - - const members = []; - - const textures = mrt.textures; - - for ( const name in outputNodes ) { + setPixelRatio( pixelRatio ) { - const index = getTextureIndex( textures, name ); + this._pixelRatio = pixelRatio; - members[ index ] = vec4( outputNodes[ name ] ); + this.setSize( this._width, this._height ); - } + } - this.members = members; + dispose() { - return super.setup( builder ); + this.renderTarget.dispose(); } + } -const mrt = /*@__PURE__*/ nodeProxy( MRTNode ); +PassNode.COLOR = 'color'; +PassNode.DEPTH = 'depth'; -class FunctionOverloadingNode extends Node { +const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) ); +const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) ); +const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); + +class ToonOutlinePassNode extends PassNode { static get type() { - return 'FunctionOverloadingNode'; + return 'ToonOutlinePassNode'; } - constructor( functionNodes = [], ...parametersNodes ) { - - super(); + constructor( scene, camera, colorNode, thicknessNode, alphaNode ) { - this.functionNodes = functionNodes; - this.parametersNodes = parametersNodes; + super( PassNode.COLOR, scene, camera ); - this._candidateFnCall = null; + this.colorNode = colorNode; + this.thicknessNode = thicknessNode; + this.alphaNode = alphaNode; - this.global = true; + this._materialCache = new WeakMap(); } - getNodeType() { + updateBefore( frame ) { - return this.functionNodes[ 0 ].shaderNode.layout.type; + const { renderer } = frame; - } + const currentRenderObjectFunction = renderer.getRenderObjectFunction(); - setup( builder ) { + renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => { - const params = this.parametersNodes; + // only render outline for supported materials - let candidateFnCall = this._candidateFnCall; + if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) { - if ( candidateFnCall === null ) { + if ( material.wireframe === false ) { - let candidateFn = null; - let candidateScore = - 1; + const outlineMaterial = this._getOutlineMaterial( material ); + renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode ); - for ( const functionNode of this.functionNodes ) { + } - const shaderNode = functionNode.shaderNode; - const layout = shaderNode.layout; + } - if ( layout === null ) { + // default - throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' ); + renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode ); - } + } ); - const inputs = layout.inputs; + super.updateBefore( frame ); - if ( params.length === inputs.length ) { + renderer.setRenderObjectFunction( currentRenderObjectFunction ); - let score = 0; + } - for ( let i = 0; i < params.length; i ++ ) { + _createMaterial() { - const param = params[ i ]; - const input = inputs[ i ]; + const material = new NodeMaterial(); + material.isMeshToonOutlineMaterial = true; + material.name = 'Toon_Outline'; + material.side = BackSide; - if ( param.getNodeType( builder ) === input.type ) { + // vertex node - score ++; + const outlineNormal = normalLocal.negate(); + const mvp = cameraProjectionMatrix.mul( modelViewMatrix ); - } else { + const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex + const pos = mvp.mul( vec4( positionLocal, 1.0 ) ); + const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) ); + const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative - score = 0; + material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) ); - } + // color node - } + material.colorNode = vec4( this.colorNode, this.alphaNode ); - if ( score > candidateScore ) { + return material; - candidateFn = functionNode; - candidateScore = score; + } - } + _getOutlineMaterial( originalMaterial ) { - } + let outlineMaterial = this._materialCache.get( originalMaterial ); - } + if ( outlineMaterial === undefined ) { - this._candidateFnCall = candidateFnCall = candidateFn( ...params ); + outlineMaterial = this._createMaterial(); + + this._materialCache.set( originalMaterial, outlineMaterial ); } - return candidateFnCall; + return outlineMaterial; } } -const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode ); +const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) ); -const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params ); +const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => { -class SpriteSheetUVNode extends Node { + const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 ); + const b = color.mul( 0.0773993808 ); + const factor = color.lessThanEqual( 0.04045 ); - static get type() { + const rgbResult = mix( a, b, factor ); - return 'SpriteSheetUVNode'; + return rgbResult; - } +} ).setLayout( { + name: 'sRGBToLinearSRGB', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' } + ] +} ); - constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { +const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => { - super( 'vec2' ); + const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 ); + const b = color.mul( 12.92 ); + const factor = color.lessThanEqual( 0.0031308 ); - this.countNode = countNode; - this.uvNode = uvNode; - this.frameNode = frameNode; + const rgbResult = mix( a, b, factor ); - } + return rgbResult; - setup() { +} ).setLayout( { + name: 'linearSRGBTosRGB', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' } + ] +} ); - const { frameNode, uvNode, countNode } = this; +// exposure only - const { width, height } = countNode; +const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - const frameNum = frameNode.mod( width.mul( height ) ).floor(); + return color.mul( exposure ).clamp(); - const column = frameNum.mod( width ); - const row = height.sub( frameNum.add( 1 ).div( width ).ceil() ); +} ).setLayout( { + name: 'linearToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); - const scale = countNode.reciprocal(); - const uvFrameOffset = vec2( column, row ); +// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf - return uvNode.add( uvFrameOffset ).mul( scale ); +const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - } + color = color.mul( exposure ); -} + return color.div( color.add( 1.0 ) ).clamp(); -const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ); +} ).setLayout( { + name: 'reinhardToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); -class StorageArrayElementNode extends ArrayElementNode { +// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/ - static get type() { +const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - return 'StorageArrayElementNode'; + // filmic operator by Jim Hejl and Richard Burgess-Dawson + color = color.mul( exposure ); + color = color.sub( 0.004 ).max( 0.0 ); - } + const a = color.mul( color.mul( 6.2 ).add( 0.5 ) ); + const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 ); - constructor( storageBufferNode, indexNode ) { + return a.div( b ).pow( 2.2 ); - super( storageBufferNode, indexNode ); +} ).setLayout( { + name: 'cineonToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); - this.isStorageArrayElementNode = true; +// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs - } +const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => { - set storageBufferNode( value ) { + const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 ); + const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 ); - this.node = value; + return a.div( b ); - } +} ); - get storageBufferNode() { +// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs - return this.node; +const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - } + // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT + const ACESInputMat = mat3( + 0.59719, 0.35458, 0.04823, + 0.07600, 0.90834, 0.01566, + 0.02840, 0.13383, 0.83777 + ); - setup( builder ) { + // ODT_SAT => XYZ => D60_2_D65 => sRGB + const ACESOutputMat = mat3( + 1.60475, - 0.53108, - 0.07367, + - 0.10208, 1.10813, - 0.00605, + - 0.00327, - 0.07276, 1.07602 + ); - if ( builder.isAvailable( 'storageBuffer' ) === false ) { + color = color.mul( exposure ).div( 0.6 ); - if ( this.node.bufferObject === true ) { + color = ACESInputMat.mul( color ); - builder.setupPBO( this.node ); + // Apply RRT and ODT + color = RRTAndODTFit( color ); - } + color = ACESOutputMat.mul( color ); - } + // Clamp to [0, 1] + return color.clamp(); - return super.setup( builder ); +} ).setLayout( { + name: 'acesFilmicToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); - } +const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); +const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); - generate( builder, output ) { +const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { - let snippet; + const x = vec3( x_immutable ).toVar(); + const x2 = vec3( x.mul( x ) ).toVar(); + const x4 = vec3( x2.mul( x2 ) ).toVar(); - const isAssignContext = builder.context.assign; + return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) ); - // +} ); - if ( builder.isAvailable( 'storageBuffer' ) === false ) { +const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - if ( this.node.bufferObject === true && isAssignContext !== true ) { + const colortone = vec3( color ).toVar(); + const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); + const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); + const AgxMinEv = float( - 12.47393 ); + const AgxMaxEv = float( 4.026069 ); + colortone.mulAssign( exposure ); + colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) ); + colortone.assign( AgXInsetMatrix.mul( colortone ) ); + colortone.assign( max$1( colortone, 1e-10 ) ); + colortone.assign( log2( colortone ) ); + colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + colortone.assign( agxDefaultContrastApprox( colortone ) ); + colortone.assign( AgXOutsetMatrix.mul( colortone ) ); + colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) ); + colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); - snippet = builder.generatePBO( this ); + return colortone; - } else { +} ).setLayout( { + name: 'agxToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); - snippet = this.node.build( builder ); +// https://modelviewer.dev/examples/tone-mapping - } +const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - } else { + const StartCompression = float( 0.8 - 0.04 ); + const Desaturation = float( 0.15 ); - snippet = super.generate( builder ); + color = color.mul( exposure ); - } + const x = min$1( color.r, min$1( color.g, color.b ) ); + const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 ); - if ( isAssignContext !== true ) { + color.subAssign( offset ); - const type = this.getNodeType( builder ); + const peak = max$1( color.r, max$1( color.g, color.b ) ); - snippet = builder.format( snippet, type, output ); + If( peak.lessThan( StartCompression ), () => { - } + return color; - return snippet; + } ); - } + const d = sub( 1, StartCompression ); + const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) ); + color.mulAssign( newPeak.div( peak ) ); + const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) ); -} + return mix( color, vec3( newPeak ), g ); -const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ); +} ).setLayout( { + name: 'neutralToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); -class TriplanarTexturesNode extends Node { +class CodeNode extends Node { static get type() { - return 'TriplanarTexturesNode'; + return 'CodeNode'; } - constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { + constructor( code = '', includes = [], language = '' ) { - super( 'vec4' ); + super( 'code' ); - this.textureXNode = textureXNode; - this.textureYNode = textureYNode; - this.textureZNode = textureZNode; + this.isCodeNode = true; - this.scaleNode = scaleNode; + this.code = code; + this.language = language; - this.positionNode = positionNode; - this.normalNode = normalNode; + this.includes = includes; } - setup() { + isGlobal() { - const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this; + return true; - // Ref: https://github.com/keijiro/StandardTriplanar + } - // Blending factor of triplanar mapping - let bf = normalNode.abs().normalize(); - bf = bf.div( bf.dot( vec3( 1.0 ) ) ); + setIncludes( includes ) { - // Triplanar mapping - const tx = positionNode.yz.mul( scaleNode ); - const ty = positionNode.zx.mul( scaleNode ); - const tz = positionNode.xy.mul( scaleNode ); + this.includes = includes; - // Base color - const textureX = textureXNode.value; - const textureY = textureYNode !== null ? textureYNode.value : textureX; - const textureZ = textureZNode !== null ? textureZNode.value : textureX; + return this; - const cx = texture( textureX, tx ).mul( bf.x ); - const cy = texture( textureY, ty ).mul( bf.y ); - const cz = texture( textureZ, tz ).mul( bf.z ); + } - return add( cx, cy, cz ); + getIncludes( /*builder*/ ) { + + return this.includes; } -} + generate( builder ) { -const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ); -const triplanarTexture = ( ...params ) => triplanarTextures( ...params ); + const includes = this.getIncludes( builder ); -const _reflectorPlane = new Plane(); -const _normal = new Vector3(); -const _reflectorWorldPosition = new Vector3(); -const _cameraWorldPosition = new Vector3(); -const _rotationMatrix = new Matrix4(); -const _lookAtPosition = new Vector3( 0, 0, - 1 ); -const clipPlane = new Vector4(); + for ( const include of includes ) { -const _view = new Vector3(); -const _target = new Vector3(); -const _q = new Vector4(); + include.build( builder ); -const _size$3 = new Vector2(); + } -const _defaultRT = new RenderTarget(); -const _defaultUV = screenUV.flipX(); + const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) ); + nodeCode.code = this.code; -_defaultRT.depthTexture = new DepthTexture( 1, 1 ); + return nodeCode.code; -let _inReflector = false; + } -class ReflectorNode extends TextureNode { + serialize( data ) { - static get type() { + super.serialize( data ); - return 'ReflectorNode'; + data.code = this.code; + data.language = this.language; } - constructor( parameters = {} ) { - - super( parameters.defaultTexture || _defaultRT.texture, _defaultUV ); + deserialize( data ) { - this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters ); - this._depthNode = null; + super.deserialize( data ); - this.setUpdateMatrix( false ); + this.code = data.code; + this.language = data.language; } - get reflector() { +} - return this._reflectorBaseNode; +const code = /*@__PURE__*/ nodeProxy( CodeNode ); - } +const js = ( src, includes ) => code( src, includes, 'js' ); +const wgsl = ( src, includes ) => code( src, includes, 'wgsl' ); +const glsl = ( src, includes ) => code( src, includes, 'glsl' ); - get target() { +class FunctionNode extends CodeNode { - return this._reflectorBaseNode.target; + static get type() { + + return 'FunctionNode'; } - getDepthNode() { + constructor( code = '', includes = [], language = '' ) { - if ( this._depthNode === null ) { + super( code, includes, language ); - if ( this._reflectorBaseNode.depth !== true ) { + } - throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' ); + getNodeType( builder ) { - } + return this.getNodeFunction( builder ).type; - this._depthNode = nodeObject( new ReflectorNode( { - defaultTexture: _defaultRT.depthTexture, - reflector: this._reflectorBaseNode - } ) ); + } - } + getInputs( builder ) { - return this._depthNode; + return this.getNodeFunction( builder ).inputs; } - setup( builder ) { + getNodeFunction( builder ) { - // ignore if used in post-processing - if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder ); + const nodeData = builder.getDataFromNode( this ); - return super.setup( builder ); + let nodeFunction = nodeData.nodeFunction; - } + if ( nodeFunction === undefined ) { - clone() { + nodeFunction = builder.parser.parseFunction( this.code ); - const texture = new this.constructor( this.reflectorNode ); - texture._reflectorBaseNode = this._reflectorBaseNode; + nodeData.nodeFunction = nodeFunction; - return texture; + } + + return nodeFunction; } -} + generate( builder, output ) { + super.generate( builder ); -class ReflectorBaseNode extends Node { + const nodeFunction = this.getNodeFunction( builder ); - static get type() { + const name = nodeFunction.name; + const type = nodeFunction.type; - return 'ReflectorBaseNode'; + const nodeCode = builder.getCodeFromNode( this, type ); - } + if ( name !== '' ) { - constructor( textureNode, parameters = {} ) { + // use a custom property name - super(); + nodeCode.name = name; - const { - target = new Object3D(), - resolution = 1, - generateMipmaps = false, - bounces = true, - depth = false - } = parameters; + } - // + const propertyName = builder.getPropertyName( nodeCode ); - this.textureNode = textureNode; + const code = this.getNodeFunction( builder ).getCode( propertyName ); - this.target = target; - this.resolution = resolution; - this.generateMipmaps = generateMipmaps; - this.bounces = bounces; - this.depth = depth; + nodeCode.code = code + '\n'; - this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME; + if ( output === 'property' ) { - this.virtualCameras = new WeakMap(); - this.renderTargets = new WeakMap(); + return propertyName; - } + } else { - _updateResolution( renderTarget, renderer ) { + return builder.format( `${ propertyName }()`, type, output ); - const resolution = this.resolution; + } - renderer.getDrawingBufferSize( _size$3 ); + } - renderTarget.setSize( Math.round( _size$3.width * resolution ), Math.round( _size$3.height * resolution ) ); +} - } +const nativeFn = ( code, includes = [], language = '' ) => { - setup( builder ) { + for ( let i = 0; i < includes.length; i ++ ) { - this._updateResolution( _defaultRT, builder.renderer ); + const include = includes[ i ]; - return super.setup( builder ); + // TSL Function: glslFn, wgslFn - } + if ( typeof include === 'function' ) { - getVirtualCamera( camera ) { + includes[ i ] = include.functionNode; - let virtualCamera = this.virtualCameras.get( camera ); + } - if ( virtualCamera === undefined ) { + } - virtualCamera = camera.clone(); + const functionNode = nodeObject( new FunctionNode( code, includes, language ) ); - this.virtualCameras.set( camera, virtualCamera ); + const fn = ( ...params ) => functionNode.call( ...params ); + fn.functionNode = functionNode; - } + return fn; - return virtualCamera; +}; - } +const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' ); +const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' ); - getRenderTarget( camera ) { +class ScriptableValueNode extends Node { - let renderTarget = this.renderTargets.get( camera ); + static get type() { - if ( renderTarget === undefined ) { + return 'ScriptableValueNode'; - renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } ); + } - if ( this.generateMipmaps === true ) { + constructor( value = null ) { - renderTarget.texture.minFilter = LinearMipMapLinearFilter; - renderTarget.texture.generateMipmaps = true; + super(); - } + this._value = value; + this._cache = null; - if ( this.depth === true ) { + this.inputType = null; + this.outpuType = null; - renderTarget.depthTexture = new DepthTexture(); + this.events = new EventDispatcher(); - } + this.isScriptableValueNode = true; - this.renderTargets.set( camera, renderTarget ); + } - } + get isScriptableOutputNode() { - return renderTarget; + return this.outputType !== null; } - updateBefore( frame ) { + set value( val ) { - if ( this.bounces === false && _inReflector ) return; + if ( this._value === val ) return; - _inReflector = true; + if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) { - const { scene, camera, renderer, material } = frame; - const { target } = this; + URL.revokeObjectURL( this._cache ); - const virtualCamera = this.getVirtualCamera( camera ); - const renderTarget = this.getRenderTarget( virtualCamera ); + this._cache = null; - renderer.getDrawingBufferSize( _size$3 ); + } - this._updateResolution( renderTarget, renderer ); + this._value = val; - // + this.events.dispatchEvent( { type: 'change' } ); - _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld ); - _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); + this.refresh(); - _rotationMatrix.extractRotation( target.matrixWorld ); + } - _normal.set( 0, 0, 1 ); - _normal.applyMatrix4( _rotationMatrix ); + get value() { - _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition ); + return this._value; - // Avoid rendering when reflector is facing away + } - if ( _view.dot( _normal ) > 0 ) return; + refresh() { - _view.reflect( _normal ).negate(); - _view.add( _reflectorWorldPosition ); + this.events.dispatchEvent( { type: 'refresh' } ); - _rotationMatrix.extractRotation( camera.matrixWorld ); + } - _lookAtPosition.set( 0, 0, - 1 ); - _lookAtPosition.applyMatrix4( _rotationMatrix ); - _lookAtPosition.add( _cameraWorldPosition ); + getValue() { - _target.subVectors( _reflectorWorldPosition, _lookAtPosition ); - _target.reflect( _normal ).negate(); - _target.add( _reflectorWorldPosition ); + const value = this.value; - // + if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) { - virtualCamera.coordinateSystem = camera.coordinateSystem; - virtualCamera.position.copy( _view ); - virtualCamera.up.set( 0, 1, 0 ); - virtualCamera.up.applyMatrix4( _rotationMatrix ); - virtualCamera.up.reflect( _normal ); - virtualCamera.lookAt( _target ); + this._cache = URL.createObjectURL( new Blob( [ value.value ] ) ); - virtualCamera.near = camera.near; - virtualCamera.far = camera.far; + } else if ( value && value.value !== null && value.value !== undefined && ( + ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) || + ( this.inputType === 'Number' && typeof value.value === 'number' ) || + ( this.inputType === 'Vector2' && value.value.isVector2 ) || + ( this.inputType === 'Vector3' && value.value.isVector3 ) || + ( this.inputType === 'Vector4' && value.value.isVector4 ) || + ( this.inputType === 'Color' && value.value.isColor ) || + ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) || + ( this.inputType === 'Matrix4' && value.value.isMatrix4 ) + ) ) { - virtualCamera.updateMatrixWorld(); - virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); + return value.value; - // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html - // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf - _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition ); - _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); + } - clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant ); + return this._cache || value; - const projectionMatrix = virtualCamera.projectionMatrix; + } - _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; - _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; - _q.z = - 1.0; - _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; + getNodeType( builder ) { - // Calculate the scaled plane vector - clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) ); + return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float'; - const clipBias = 0; + } - // Replacing the third row of the projection matrix - projectionMatrix.elements[ 2 ] = clipPlane.x; - projectionMatrix.elements[ 6 ] = clipPlane.y; - projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias ); - projectionMatrix.elements[ 14 ] = clipPlane.w; + setup() { - // + return this.value && this.value.isNode ? this.value : float(); - this.textureNode.value = renderTarget.texture; + } - if ( this.depth === true ) { + serialize( data ) { - this.textureNode.getDepthNode().value = renderTarget.depthTexture; + super.serialize( data ); - } + if ( this.value !== null ) { - material.visible = false; + if ( this.inputType === 'ArrayBuffer' ) { - const currentRenderTarget = renderer.getRenderTarget(); - const currentMRT = renderer.getMRT(); + data.value = arrayBufferToBase64( this.value ); - renderer.setMRT( null ); - renderer.setRenderTarget( renderTarget ); + } else { - renderer.render( scene, virtualCamera ); + data.value = this.value ? this.value.toJSON( data.meta ).uuid : null; - renderer.setMRT( currentMRT ); - renderer.setRenderTarget( currentRenderTarget ); + } - material.visible = true; + } else { - _inReflector = false; + data.value = null; - } + } -} + data.inputType = this.inputType; + data.outputType = this.outputType; -const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) ); + } -// Helper for passes that need to fill the viewport with a single quad. + deserialize( data ) { -const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + super.deserialize( data ); -// https://github.com/mrdoob/three.js/pull/21358 + let value = null; -class QuadGeometry extends BufferGeometry { + if ( data.value !== null ) { - constructor( flipY = false ) { + if ( data.inputType === 'ArrayBuffer' ) { - super(); + value = base64ToArrayBuffer( data.value ); - const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ]; + } else if ( data.inputType === 'Texture' ) { - this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) ); + value = data.meta.textures[ data.value ]; - } + } else { -} + value = data.meta.nodes[ data.value ] || null; -const _geometry = /*@__PURE__*/ new QuadGeometry(); + } -class QuadMesh extends Mesh { + } - constructor( material = null ) { + this.value = value; - super( _geometry, material ); + this.inputType = data.inputType; + this.outputType = data.outputType; - this.camera = _camera; + } - this.isQuadMesh = true; +} - } +const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ); - renderAsync( renderer ) { +class Resources extends Map { - return renderer.renderAsync( this, _camera ); + get( key, callback = null, ...params ) { - } + if ( this.has( key ) ) return super.get( key ); - render( renderer ) { + if ( callback !== null ) { - renderer.render( this, _camera ); + const value = callback( ...params ); + this.set( key, value ); + return value; + + } } } -const _size$2 = /*@__PURE__*/ new Vector2(); +class Parameters { -class RTTNode extends TextureNode { + constructor( scriptableNode ) { - static get type() { + this.scriptableNode = scriptableNode; - return 'RTTNode'; + } + + get parameters() { + + return this.scriptableNode.parameters; } - constructor( node, width = null, height = null, options = { type: HalfFloatType } ) { + get layout() { - const renderTarget = new RenderTarget( width, height, options ); + return this.scriptableNode.getLayout(); - super( renderTarget.texture, uv() ); + } - this.node = node; - this.width = width; - this.height = height; + getInputLayout( id ) { - this.renderTarget = renderTarget; + return this.scriptableNode.getInputLayout( id ); - this.textureNeedsUpdate = true; - this.autoUpdate = true; + } - this.updateMap = new WeakMap(); + get( name ) { - this._rttNode = null; - this._quadMesh = new QuadMesh( new NodeMaterial() ); + const param = this.parameters[ name ]; + const value = param ? param.getValue() : null; - this.updateBeforeType = NodeUpdateType.RENDER; + return value; } - get autoSize() { +} - return this.width === null; +const global = new Resources(); + +class ScriptableNode extends Node { + + static get type() { + + return 'ScriptableNode'; } - setup( builder ) { + constructor( codeNode = null, parameters = {} ) { - this._rttNode = this.node.context( builder.getSharedContext() ); - this._quadMesh.material.name = 'RTT'; - this._quadMesh.material.needsUpdate = true; + super(); - return super.setup( builder ); + this.codeNode = codeNode; + this.parameters = parameters; - } + this._local = new Resources(); + this._output = scriptableValue(); + this._outputs = {}; + this._source = this.source; + this._method = null; + this._object = null; + this._value = null; + this._needsOutputUpdate = true; - setSize( width, height ) { + this.onRefresh = this.onRefresh.bind( this ); - this.width = width; - this.height = height; + this.isScriptableNode = true; - const effectiveWidth = width * this.pixelRatio; - const effectiveHeight = height * this.pixelRatio; + } - this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + get source() { - this.textureNeedsUpdate = true; + return this.codeNode ? this.codeNode.code : ''; } - setPixelRatio( pixelRatio ) { + setLocal( name, value ) { - this.pixelRatio = pixelRatio; + return this._local.set( name, value ); - this.setSize( this.width, this.height ); + } + + getLocal( name ) { + + return this._local.get( name ); } - updateBefore( { renderer } ) { + onRefresh() { - if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return; + this._refresh(); - this.textureNeedsUpdate = false; + } - // + getInputLayout( id ) { - if ( this.autoSize === true ) { + for ( const element of this.getLayout() ) { - this.pixelRatio = renderer.getPixelRatio(); + if ( element.inputType && ( element.id === id || element.name === id ) ) { - const size = renderer.getSize( _size$2 ); + return element; - this.setSize( size.width, size.height ); + } } - // + } - this._quadMesh.material.fragmentNode = this._rttNode; + getOutputLayout( id ) { - // + for ( const element of this.getLayout() ) { - const currentRenderTarget = renderer.getRenderTarget(); + if ( element.outputType && ( element.id === id || element.name === id ) ) { - renderer.setRenderTarget( this.renderTarget ); + return element; - this._quadMesh.render( renderer ); + } - renderer.setRenderTarget( currentRenderTarget ); + } } - clone() { - - const newNode = new TextureNode( this.value, this.uvNode, this.levelNode ); - newNode.sampler = this.sampler; - newNode.referenceNode = this; + setOutput( name, value ) { - return newNode; + const outputs = this._outputs; - } + if ( outputs[ name ] === undefined ) { -} + outputs[ name ] = scriptableValue( value ); -const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) ); -const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ); + } else { -class VertexColorNode extends AttributeNode { + outputs[ name ].value = value; - static get type() { + } - return 'VertexColorNode'; + return this; } - constructor( index = 0 ) { + getOutput( name ) { - super( null, 'vec4' ); + return this._outputs[ name ]; - this.isVertexColorNode = true; + } - this.index = index; + getParameter( name ) { + + return this.parameters[ name ]; } - getAttributeName( /*builder*/ ) { + setParameter( name, value ) { - const index = this.index; + const parameters = this.parameters; - return 'color' + ( index > 0 ? index : '' ); + if ( value && value.isScriptableNode ) { - } + this.deleteParameter( name ); - generate( builder ) { + parameters[ name ] = value; + parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh ); - const attributeName = this.getAttributeName( builder ); - const geometryAttribute = builder.hasGeometryAttribute( attributeName ); + } else if ( value && value.isScriptableValueNode ) { - let result; + this.deleteParameter( name ); - if ( geometryAttribute === true ) { + parameters[ name ] = value; + parameters[ name ].events.addEventListener( 'refresh', this.onRefresh ); - result = super.generate( builder ); + } else if ( parameters[ name ] === undefined ) { + + parameters[ name ] = scriptableValue( value ); + parameters[ name ].events.addEventListener( 'refresh', this.onRefresh ); } else { - // Vertex color fallback should be white - result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) ); + parameters[ name ].value = value; } - return result; + return this; } - serialize( data ) { - - super.serialize( data ); + getValue() { - data.index = this.index; + return this.getDefaultOutput().getValue(); } - deserialize( data ) { - - super.deserialize( data ); - - this.index = data.index; + deleteParameter( name ) { - } + let valueNode = this.parameters[ name ]; -} + if ( valueNode ) { -const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) ); + if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput(); -class PointUVNode extends Node { + valueNode.events.removeEventListener( 'refresh', this.onRefresh ); - static get type() { + } - return 'PointUVNode'; + return this; } - constructor() { + clearParameters() { - super( 'vec2' ); + for ( const name of Object.keys( this.parameters ) ) { - this.isPointUVNode = true; + this.deleteParameter( name ); - } + } - generate( /*builder*/ ) { + this.needsUpdate = true; - return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )'; + return this; } -} + call( name, ...params ) { -const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode ); + const object = this.getObject(); + const method = object[ name ]; -class SceneNode extends Node { + if ( typeof method === 'function' ) { - static get type() { + return method( ...params ); - return 'SceneNode'; + } } - constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) { + async callAsync( name, ...params ) { - super(); + const object = this.getObject(); + const method = object[ name ]; - this.scope = scope; - this.scene = scene; + if ( typeof method === 'function' ) { - } + return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params ); - setup( builder ) { + } - const scope = this.scope; - const scene = this.scene !== null ? this.scene : builder.scene; + } - let output; + getNodeType( builder ) { - if ( scope === SceneNode.BACKGROUND_BLURRINESS ) { + return this.getDefaultOutputNode().getNodeType( builder ); - output = reference( 'backgroundBlurriness', 'float', scene ); + } - } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) { + refresh( output = null ) { - output = reference( 'backgroundIntensity', 'float', scene ); + if ( output !== null ) { + + this.getOutput( output ).refresh(); } else { - console.error( 'THREE.SceneNode: Unknown scope:', scope ); + this._refresh(); } - return output; - } -} + getObject() { -SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness'; -SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity'; + if ( this.needsUpdate ) this.dispose(); + if ( this._object !== null ) return this._object; -const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS ); -const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY ); + // -const GPUPrimitiveTopology = { - PointList: 'point-list', - LineList: 'line-list', - LineStrip: 'line-strip', - TriangleList: 'triangle-list', - TriangleStrip: 'triangle-strip', -}; + const refresh = () => this.refresh(); + const setOutput = ( id, value ) => this.setOutput( id, value ); -const GPUCompareFunction = { - Never: 'never', - Less: 'less', - Equal: 'equal', - LessEqual: 'less-equal', - Greater: 'greater', - NotEqual: 'not-equal', - GreaterEqual: 'greater-equal', - Always: 'always' -}; + const parameters = new Parameters( this ); -const GPUStoreOp = { - Store: 'store', - Discard: 'discard' -}; + const THREE = global.get( 'THREE' ); + const TSL = global.get( 'TSL' ); -const GPULoadOp = { - Load: 'load', - Clear: 'clear' -}; + const method = this.getMethod( this.codeNode ); + const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ]; -const GPUFrontFace = { - CCW: 'ccw', - CW: 'cw' -}; + this._object = method( ...params ); -const GPUCullMode = { - None: 'none', - Front: 'front', - Back: 'back' -}; + const layout = this._object.layout; -const GPUIndexFormat = { - Uint16: 'uint16', - Uint32: 'uint32' -}; + if ( layout ) { -const GPUTextureFormat = { + if ( layout.cache === false ) { - // 8-bit formats + this._local.clear(); - R8Unorm: 'r8unorm', - R8Snorm: 'r8snorm', - R8Uint: 'r8uint', - R8Sint: 'r8sint', + } - // 16-bit formats + // default output + this._output.outputType = layout.outputType || null; - R16Uint: 'r16uint', - R16Sint: 'r16sint', - R16Float: 'r16float', - RG8Unorm: 'rg8unorm', - RG8Snorm: 'rg8snorm', - RG8Uint: 'rg8uint', - RG8Sint: 'rg8sint', + if ( Array.isArray( layout.elements ) ) { - // 32-bit formats + for ( const element of layout.elements ) { - R32Uint: 'r32uint', - R32Sint: 'r32sint', - R32Float: 'r32float', - RG16Uint: 'rg16uint', - RG16Sint: 'rg16sint', - RG16Float: 'rg16float', - RGBA8Unorm: 'rgba8unorm', - RGBA8UnormSRGB: 'rgba8unorm-srgb', - RGBA8Snorm: 'rgba8snorm', - RGBA8Uint: 'rgba8uint', - RGBA8Sint: 'rgba8sint', - BGRA8Unorm: 'bgra8unorm', - BGRA8UnormSRGB: 'bgra8unorm-srgb', - // Packed 32-bit formats - RGB9E5UFloat: 'rgb9e5ufloat', - RGB10A2Unorm: 'rgb10a2unorm', - RG11B10uFloat: 'rgb10a2unorm', + const id = element.id || element.name; - // 64-bit formats + if ( element.inputType ) { - RG32Uint: 'rg32uint', - RG32Sint: 'rg32sint', - RG32Float: 'rg32float', - RGBA16Uint: 'rgba16uint', - RGBA16Sint: 'rgba16sint', - RGBA16Float: 'rgba16float', + if ( this.getParameter( id ) === undefined ) this.setParameter( id, null ); - // 128-bit formats + this.getParameter( id ).inputType = element.inputType; - RGBA32Uint: 'rgba32uint', - RGBA32Sint: 'rgba32sint', - RGBA32Float: 'rgba32float', + } - // Depth and stencil formats + if ( element.outputType ) { - Stencil8: 'stencil8', - Depth16Unorm: 'depth16unorm', - Depth24Plus: 'depth24plus', - Depth24PlusStencil8: 'depth24plus-stencil8', - Depth32Float: 'depth32float', + if ( this.getOutput( id ) === undefined ) this.setOutput( id, null ); - // 'depth32float-stencil8' extension + this.getOutput( id ).outputType = element.outputType; - Depth32FloatStencil8: 'depth32float-stencil8', + } - // BC compressed formats usable if 'texture-compression-bc' is both - // supported by the device/user agent and enabled in requestDevice. + } - BC1RGBAUnorm: 'bc1-rgba-unorm', - BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb', - BC2RGBAUnorm: 'bc2-rgba-unorm', - BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb', - BC3RGBAUnorm: 'bc3-rgba-unorm', - BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb', - BC4RUnorm: 'bc4-r-unorm', - BC4RSnorm: 'bc4-r-snorm', - BC5RGUnorm: 'bc5-rg-unorm', - BC5RGSnorm: 'bc5-rg-snorm', - BC6HRGBUFloat: 'bc6h-rgb-ufloat', - BC6HRGBFloat: 'bc6h-rgb-float', - BC7RGBAUnorm: 'bc7-rgba-unorm', - BC7RGBAUnormSRGB: 'bc7-rgba-srgb', + } - // ETC2 compressed formats usable if 'texture-compression-etc2' is both - // supported by the device/user agent and enabled in requestDevice. + } - ETC2RGB8Unorm: 'etc2-rgb8unorm', - ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb', - ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm', - ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb', - ETC2RGBA8Unorm: 'etc2-rgba8unorm', - ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb', - EACR11Unorm: 'eac-r11unorm', - EACR11Snorm: 'eac-r11snorm', - EACRG11Unorm: 'eac-rg11unorm', - EACRG11Snorm: 'eac-rg11snorm', + return this._object; - // ASTC compressed formats usable if 'texture-compression-astc' is both - // supported by the device/user agent and enabled in requestDevice. + } - ASTC4x4Unorm: 'astc-4x4-unorm', - ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb', - ASTC5x4Unorm: 'astc-5x4-unorm', - ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb', - ASTC5x5Unorm: 'astc-5x5-unorm', - ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb', - ASTC6x5Unorm: 'astc-6x5-unorm', - ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb', - ASTC6x6Unorm: 'astc-6x6-unorm', - ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb', - ASTC8x5Unorm: 'astc-8x5-unorm', - ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb', - ASTC8x6Unorm: 'astc-8x6-unorm', - ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb', - ASTC8x8Unorm: 'astc-8x8-unorm', - ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb', - ASTC10x5Unorm: 'astc-10x5-unorm', - ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb', - ASTC10x6Unorm: 'astc-10x6-unorm', - ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb', - ASTC10x8Unorm: 'astc-10x8-unorm', - ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb', - ASTC10x10Unorm: 'astc-10x10-unorm', - ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb', - ASTC12x10Unorm: 'astc-12x10-unorm', - ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb', - ASTC12x12Unorm: 'astc-12x12-unorm', - ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb', + deserialize( data ) { -}; + super.deserialize( data ); -const GPUAddressMode = { - ClampToEdge: 'clamp-to-edge', - Repeat: 'repeat', - MirrorRepeat: 'mirror-repeat' -}; + for ( const name in this.parameters ) { -const GPUFilterMode = { - Linear: 'linear', - Nearest: 'nearest' -}; + let valueNode = this.parameters[ name ]; -const GPUBlendFactor = { - Zero: 'zero', - One: 'one', - Src: 'src', - OneMinusSrc: 'one-minus-src', - SrcAlpha: 'src-alpha', - OneMinusSrcAlpha: 'one-minus-src-alpha', - Dst: 'dst', - OneMinusDstColor: 'one-minus-dst', - DstAlpha: 'dst-alpha', - OneMinusDstAlpha: 'one-minus-dst-alpha', - SrcAlphaSaturated: 'src-alpha-saturated', - Constant: 'constant', - OneMinusConstant: 'one-minus-constant' -}; + if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput(); -const GPUBlendOperation = { - Add: 'add', - Subtract: 'subtract', - ReverseSubtract: 'reverse-subtract', - Min: 'min', - Max: 'max' -}; + valueNode.events.addEventListener( 'refresh', this.onRefresh ); -const GPUColorWriteFlags = { - None: 0, - Red: 0x1, - Green: 0x2, - Blue: 0x4, - Alpha: 0x8, - All: 0xF -}; + } -const GPUStencilOperation = { - Keep: 'keep', - Zero: 'zero', - Replace: 'replace', - Invert: 'invert', - IncrementClamp: 'increment-clamp', - DecrementClamp: 'decrement-clamp', - IncrementWrap: 'increment-wrap', - DecrementWrap: 'decrement-wrap' -}; + } -const GPUBufferBindingType = { - Uniform: 'uniform', - Storage: 'storage', - ReadOnlyStorage: 'read-only-storage' -}; + getLayout() { -const GPUStorageTextureAccess = { - WriteOnly: 'write-only', - ReadOnly: 'read-only', - ReadWrite: 'read-write', -}; + return this.getObject().layout; -const GPUTextureSampleType = { - Float: 'float', - UnfilterableFloat: 'unfilterable-float', - Depth: 'depth', - SInt: 'sint', - UInt: 'uint' -}; + } -const GPUTextureDimension = { - OneD: '1d', - TwoD: '2d', - ThreeD: '3d' -}; + getDefaultOutputNode() { -const GPUTextureViewDimension = { - OneD: '1d', - TwoD: '2d', - TwoDArray: '2d-array', - Cube: 'cube', - CubeArray: 'cube-array', - ThreeD: '3d' -}; + const output = this.getDefaultOutput().value; -const GPUTextureAspect = { - All: 'all', - StencilOnly: 'stencil-only', - DepthOnly: 'depth-only' -}; + if ( output && output.isNode ) { -const GPUInputStepMode = { - Vertex: 'vertex', - Instance: 'instance' -}; + return output; -const GPUFeatureName = { - DepthClipControl: 'depth-clip-control', - Depth32FloatStencil8: 'depth32float-stencil8', - TextureCompressionBC: 'texture-compression-bc', - TextureCompressionETC2: 'texture-compression-etc2', - TextureCompressionASTC: 'texture-compression-astc', - TimestampQuery: 'timestamp-query', - IndirectFirstInstance: 'indirect-first-instance', - ShaderF16: 'shader-f16', - RG11B10UFloat: 'rg11b10ufloat-renderable', - BGRA8UNormStorage: 'bgra8unorm-storage', - Float32Filterable: 'float32-filterable', - ClipDistances: 'clip-distances', - DualSourceBlending: 'dual-source-blending', - Subgroups: 'subgroups' -}; + } -class StorageBufferNode extends BufferNode { + return float(); - static get type() { + } - return 'StorageBufferNode'; + getDefaultOutput() { + + return this._exec()._output; } - constructor( value, bufferType, bufferCount = 0 ) { + getMethod() { - super( value, bufferType, bufferCount ); + if ( this.needsUpdate ) this.dispose(); + if ( this._method !== null ) return this._method; - this.isStorageBufferNode = true; + // - this.access = GPUBufferBindingType.Storage; - this.isAtomic = false; + const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ]; + const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ]; - this.bufferObject = false; - this.bufferCount = bufferCount; + const properties = interfaceProps.join( ', ' ); + const declarations = 'var ' + properties + '; var output = {};\n'; + const returns = '\nreturn { ...output, ' + properties + ' };'; - this._attribute = null; - this._varying = null; + const code = declarations + this.codeNode.code + returns; - this.global = true; + // - if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) { + this._method = new Function( ...parametersProps, code ); - // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer + return this._method; - if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true; - else value.isStorageBufferAttribute = true; + } + + dispose() { + + if ( this._method === null ) return; + + if ( this._object && typeof this._object.dispose === 'function' ) { + + this._object.dispose(); } - } + this._method = null; + this._object = null; + this._source = null; + this._value = null; + this._needsOutputUpdate = true; + this._output.value = null; + this._outputs = {}; - getHash( builder ) { + } - if ( this.bufferCount === 0 ) { + setup() { - let bufferData = builder.globalCache.getData( this.value ); + return this.getDefaultOutputNode(); - if ( bufferData === undefined ) { + } - bufferData = { - node: this - }; + getCacheKey( force ) { - builder.globalCache.setData( this.value, bufferData ); + const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ]; - } + for ( const param in this.parameters ) { - return bufferData.node.uuid; + values.push( this.parameters[ param ].getCacheKey( force ) ); } - return this.uuid; + return hashArray( values ); } - getInputType( /*builder*/ ) { + set needsUpdate( value ) { - return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer'; + if ( value === true ) this.dispose(); } - element( indexNode ) { + get needsUpdate() { - return storageElement( this, indexNode ); + return this.source !== this._source; } - setBufferObject( value ) { + _exec() { - this.bufferObject = value; + if ( this.codeNode === null ) return this; - return this; + if ( this._needsOutputUpdate === true ) { - } + this._value = this.call( 'main' ); - setAccess( value ) { + this._needsOutputUpdate = false; - this.access = value; + } + + this._output.value = this._value; return this; } - toReadOnly() { + _refresh() { - return this.setAccess( GPUBufferBindingType.ReadOnlyStorage ); + this.needsUpdate = true; + + this._exec(); + + this._output.refresh(); } - setAtomic( value ) { +} - this.isAtomic = value; +const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ); - return this; +class FogNode extends Node { + + static get type() { + + return 'FogNode'; } - toAtomic() { + constructor( colorNode, factorNode ) { - return this.setAtomic( true ); + super( 'float' ); + + this.isFogNode = true; + + this.colorNode = colorNode; + this.factorNode = factorNode; } - getAttributeData() { + getViewZNode( builder ) { - if ( this._attribute === null ) { + let viewZ; - this._attribute = bufferAttribute( this.value ); - this._varying = varying( this._attribute ); + const getViewZ = builder.context.getViewZ; + + if ( getViewZ !== undefined ) { + + viewZ = getViewZ( this ); } - return { - attribute: this._attribute, - varying: this._varying - }; + return ( viewZ || positionView.z ).negate(); } - getNodeType( builder ) { + setup() { - if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) { + return this.factorNode; - return super.getNodeType( builder ); + } - } +} - const { attribute } = this.getAttributeData(); +const fog = /*@__PURE__*/ nodeProxy( FogNode ); - return attribute.getNodeType( builder ); +class FogRangeNode extends FogNode { + + static get type() { + + return 'FogRangeNode'; } - generate( builder ) { + constructor( colorNode, nearNode, farNode ) { - if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) { + super( colorNode ); - return super.generate( builder ); + this.isFogRangeNode = true; - } + this.nearNode = nearNode; + this.farNode = farNode; - const { attribute, varying } = this.getAttributeData(); + } - const output = varying.build( builder ); + setup( builder ) { - builder.registerTransform( output, attribute ); + const viewZ = this.getViewZNode( builder ); - return output; + return smoothstep( this.nearNode, this.farNode, viewZ ); } } -// Read-Write Storage -const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) ); -const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) ); +const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode ); -class StorageTextureNode extends TextureNode { +class FogExp2Node extends FogNode { static get type() { - return 'StorageTextureNode'; + return 'FogExp2Node'; } - constructor( value, uvNode, storeNode = null ) { - - super( value, uvNode ); + constructor( colorNode, densityNode ) { - this.storeNode = storeNode; + super( colorNode ); - this.isStorageTextureNode = true; + this.isFogExp2Node = true; - this.access = GPUStorageTextureAccess.WriteOnly; + this.densityNode = densityNode; } - getInputType( /*builder*/ ) { + setup( builder ) { - return 'storageTexture'; + const viewZ = this.getViewZNode( builder ); + const density = this.densityNode; + + return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus(); } - setup( builder ) { +} - super.setup( builder ); +const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node ); - const properties = builder.getNodeProperties( this ); - properties.storeNode = this.storeNode; +let min = null; +let max = null; - } +class RangeNode extends Node { - setAccess( value ) { + static get type() { - this.access = value; - return this; + return 'RangeNode'; } - generate( builder, output ) { - - let snippet; + constructor( minNode = float(), maxNode = float() ) { - if ( this.storeNode !== null ) { + super(); - snippet = this.generateStore( builder ); + this.minNode = minNode; + this.maxNode = maxNode; - } else { + } - snippet = super.generate( builder, output ); + getVectorLength( builder ) { - } + const minLength = builder.getTypeLength( getValueType( this.minNode.value ) ); + const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) ); - return snippet; + return minLength > maxLength ? minLength : maxLength; } - toReadOnly() { + getNodeType( builder ) { - return this.setAccess( GPUStorageTextureAccess.ReadOnly ); + return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float'; } - toWriteOnly() { + setup( builder ) { - return this.setAccess( GPUStorageTextureAccess.WriteOnly ); + const object = builder.object; - } + let output = null; - generateStore( builder ) { + if ( object.count > 1 ) { - const properties = builder.getNodeProperties( this ); + const minValue = this.minNode.value; + const maxValue = this.maxNode.value; - const { uvNode, storeNode } = properties; + const minLength = builder.getTypeLength( getValueType( minValue ) ); + const maxLength = builder.getTypeLength( getValueType( maxValue ) ); - const textureProperty = super.generate( builder, 'property' ); - const uvSnippet = uvNode.build( builder, 'uvec2' ); - const storeSnippet = storeNode.build( builder, 'vec4' ); + min = min || new Vector4(); + max = max || new Vector4(); - const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet ); + min.setScalar( 0 ); + max.setScalar( 0 ); - builder.addLineFlowCode( snippet, this ); + if ( minLength === 1 ) min.setScalar( minValue ); + else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b ); + else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 ); - } + if ( maxLength === 1 ) max.setScalar( maxValue ); + else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b ); + else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 ); -} + const stride = 4; -const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ); + const length = stride * object.count; + const array = new Float32Array( length ); -const textureStore = ( value, uvNode, storeNode ) => { + for ( let i = 0; i < length; i ++ ) { - const node = storageTexture( value, uvNode, storeNode ); + const index = i % stride; - if ( storeNode !== null ) node.append(); + const minElementValue = min.getComponent( index ); + const maxElementValue = max.getComponent( index ); - return node; + array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() ); -}; + } -class UserDataNode extends ReferenceNode { + const nodeType = this.getNodeType( builder ); - static get type() { + if ( object.count <= 4096 ) { - return 'UserDataNode'; + output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType ); - } + } else { - constructor( property, inputType, userData = null ) { + // TODO: Improve anonymous buffer attribute creation removing this part + const bufferAttribute = new InstancedBufferAttribute( array, 4 ); + builder.geometry.setAttribute( '__range' + this.id, bufferAttribute ); - super( property, inputType, userData ); + output = instancedBufferAttribute( bufferAttribute ).convert( nodeType ); - this.userData = userData; + } - } + } else { - updateReference( state ) { + output = float( 0 ); - this.reference = this.userData !== null ? this.userData : state.object.userData; + } - return this.reference; + return output; } } -const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) ); +const range = /*@__PURE__*/ nodeProxy( RangeNode ); -class PosterizeNode extends TempNode { +class ComputeBuiltinNode extends Node { static get type() { - return 'PosterizeNode'; + return 'ComputeBuiltinNode'; } - constructor( sourceNode, stepsNode ) { + constructor( builtinName, nodeType ) { - super(); + super( nodeType ); - this.sourceNode = sourceNode; - this.stepsNode = stepsNode; + this._builtinName = builtinName; } - setup() { - - const { sourceNode, stepsNode } = this; + getHash( builder ) { - return sourceNode.mul( stepsNode ).floor().div( stepsNode ); + return this.getBuiltinName( builder ); } -} - -const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ); - -let _sharedFramebuffer = null; - -class ViewportSharedTextureNode extends ViewportTextureNode { - - static get type() { + getNodeType( /*builder*/ ) { - return 'ViewportSharedTextureNode'; + return this.nodeType; } - constructor( uvNode = screenUV, levelNode = null ) { - - if ( _sharedFramebuffer === null ) { - - _sharedFramebuffer = new FramebufferTexture(); + setBuiltinName( builtinName ) { - } + this._builtinName = builtinName; - super( uvNode, levelNode, _sharedFramebuffer ); + return this; } - updateReference() { + getBuiltinName( /*builder*/ ) { - return this; + return this._builtinName; } -} - -const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ); + hasBuiltin( builder ) { -const _size$1 = /*@__PURE__*/ new Vector2(); + builder.hasBuiltin( this._builtinName ); -class PassTextureNode extends TextureNode { + } - static get type() { + generate( builder, output ) { - return 'PassTextureNode'; + const builtinName = this.getBuiltinName( builder ); + const nodeType = this.getNodeType( builder ); - } + if ( builder.shaderStage === 'compute' ) { - constructor( passNode, texture ) { + return builder.format( builtinName, nodeType, output ); - super( texture ); + } else { - this.passNode = passNode; + console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` ); + return builder.generateConst( nodeType ); - this.setUpdateMatrix( false ); + } } - setup( builder ) { + serialize( data ) { - if ( builder.object.isQuadMesh ) this.passNode.build( builder ); + super.serialize( data ); - return super.setup( builder ); + data.global = this.global; + data._builtinName = this._builtinName; } - clone() { + deserialize( data ) { - return new this.constructor( this.passNode, this.value ); + super.deserialize( data ); + + this.global = data.global; + this._builtinName = data._builtinName; } } -class PassMultipleTextureNode extends PassTextureNode { - - static get type() { +const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) ); - return 'PassMultipleTextureNode'; +const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' ); +const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' ); +const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' ); +const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' ); - } +class BarrierNode extends Node { - constructor( passNode, textureName, previousTexture = false ) { + constructor( scope ) { - super( passNode, null ); + super(); - this.textureName = textureName; - this.previousTexture = previousTexture; + this.scope = scope; } - updateTexture() { + generate( builder ) { - this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName ); + const { scope } = this; + const { renderer } = builder; - } + if ( renderer.backend.isWebGLBackend === true ) { - setup( builder ) { + builder.addFlowCode( `\t// ${scope}Barrier \n` ); - this.updateTexture(); + } else { - return super.setup( builder ); + builder.addLineFlowCode( `${scope}Barrier()`, this ); + + } } - clone() { +} - return new this.constructor( this.passNode, this.textureName, this.previousTexture ); +const barrier = nodeProxy( BarrierNode ); - } +const workgroupBarrier = () => barrier( 'workgroup' ).append(); +const storageBarrier = () => barrier( 'storage' ).append(); +const textureBarrier = () => barrier( 'texture' ).append(); -} +class WorkgroupInfoElementNode extends ArrayElementNode { -class PassNode extends TempNode { + constructor( workgroupInfoNode, indexNode ) { - static get type() { + super( workgroupInfoNode, indexNode ); - return 'PassNode'; + this.isWorkgroupInfoElementNode = true; } - constructor( scope, scene, camera, options = {} ) { + generate( builder, output ) { - super( 'vec4' ); + let snippet; - this.scope = scope; - this.scene = scene; - this.camera = camera; - this.options = options; + const isAssignContext = builder.context.assign; + snippet = super.generate( builder ); - this._pixelRatio = 1; - this._width = 1; - this._height = 1; + if ( isAssignContext !== true ) { - const depthTexture = new DepthTexture(); - depthTexture.isRenderTargetTexture = true; - //depthTexture.type = FloatType; - depthTexture.name = 'depth'; + const type = this.getNodeType( builder ); - const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } ); - renderTarget.texture.name = 'output'; - renderTarget.depthTexture = depthTexture; + snippet = builder.format( snippet, type, output ); - this.renderTarget = renderTarget; + } - this.updateBeforeType = NodeUpdateType.FRAME; + // TODO: Possibly activate clip distance index on index access rather than from clipping context - this._textures = { - output: renderTarget.texture, - depth: depthTexture - }; + return snippet; - this._textureNodes = {}; - this._linearDepthNodes = {}; - this._viewZNodes = {}; + } - this._previousTextures = {}; - this._previousTextureNodes = {}; +} - this._cameraNear = uniform( 0 ); - this._cameraFar = uniform( 0 ); - this._mrt = null; +class WorkgroupInfoNode extends Node { - this.isPassNode = true; + constructor( scope, bufferType, bufferCount = 0 ) { - } + super( bufferType ); - setMRT( mrt ) { + this.bufferType = bufferType; + this.bufferCount = bufferCount; - this._mrt = mrt; + this.isWorkgroupInfoNode = true; - return this; + this.scope = scope; } - getMRT() { + label( name ) { - return this._mrt; + this.name = name; + + return this; } - isGlobal() { + getHash() { - return true; + return this.uuid; } - getTexture( name ) { + setScope( scope ) { - let texture = this._textures[ name ]; + this.scope = scope; - if ( texture === undefined ) { + return this; - const refTexture = this.renderTarget.texture; + } - texture = refTexture.clone(); - texture.isRenderTargetTexture = true; - texture.name = name; + getInputType( /*builder*/ ) { - this._textures[ name ] = texture; + return `${this.scope}Array`; - this.renderTarget.textures.push( texture ); + } - } + element( indexNode ) { - return texture; + return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) ); } - getPreviousTexture( name ) { + generate( builder ) { - let texture = this._previousTextures[ name ]; + return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount ); - if ( texture === undefined ) { + } - texture = this.getTexture( name ).clone(); - texture.isRenderTargetTexture = true; +} - this._previousTextures[ name ] = texture; +const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) ); - } +class AtomicFunctionNode extends TempNode { - return texture; + static get type() { + + return 'AtomicFunctionNode'; } - toggleTexture( name ) { + constructor( method, pointerNode, valueNode, storeNode = null ) { - const prevTexture = this._previousTextures[ name ]; + super( 'uint' ); - if ( prevTexture !== undefined ) { + this.method = method; - const texture = this._textures[ name ]; + this.pointerNode = pointerNode; + this.valueNode = valueNode; + this.storeNode = storeNode; - const index = this.renderTarget.textures.indexOf( texture ); - this.renderTarget.textures[ index ] = prevTexture; + } - this._textures[ name ] = prevTexture; - this._previousTextures[ name ] = texture; + getInputType( builder ) { - this._textureNodes[ name ].updateTexture(); - this._previousTextureNodes[ name ].updateTexture(); + return this.pointerNode.getNodeType( builder ); - } + } + + getNodeType( builder ) { + + return this.getInputType( builder ); } - getTextureNode( name = 'output' ) { + generate( builder ) { - let textureNode = this._textureNodes[ name ]; + const method = this.method; - if ( textureNode === undefined ) { + const type = this.getNodeType( builder ); + const inputType = this.getInputType( builder ); - this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) ); - this._textureNodes[ name ].updateTexture(); + const a = this.pointerNode; + const b = this.valueNode; - } + const params = []; - return textureNode; + params.push( `&${ a.build( builder, inputType ) }` ); + params.push( b.build( builder, inputType ) ); - } + const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`; - getPreviousTextureNode( name = 'output' ) { + if ( this.storeNode !== null ) { - let textureNode = this._previousTextureNodes[ name ]; + const varSnippet = this.storeNode.build( builder, inputType ); - if ( textureNode === undefined ) { + builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this ); - if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name ); + } else { - this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) ); - this._previousTextureNodes[ name ].updateTexture(); + builder.addLineFlowCode( methodSnippet, this ); } - return textureNode; - } - getViewZNode( name = 'depth' ) { +} - let viewZNode = this._viewZNodes[ name ]; +AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad'; +AtomicFunctionNode.ATOMIC_STORE = 'atomicStore'; +AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd'; +AtomicFunctionNode.ATOMIC_SUB = 'atomicSub'; +AtomicFunctionNode.ATOMIC_MAX = 'atomicMax'; +AtomicFunctionNode.ATOMIC_MIN = 'atomicMin'; +AtomicFunctionNode.ATOMIC_AND = 'atomicAnd'; +AtomicFunctionNode.ATOMIC_OR = 'atomicOr'; +AtomicFunctionNode.ATOMIC_XOR = 'atomicXor'; - if ( viewZNode === undefined ) { +const atomicNode = nodeProxy( AtomicFunctionNode ); - const cameraNear = this._cameraNear; - const cameraFar = this._cameraFar; +const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => { - this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar ); + const node = atomicNode( method, pointerNode, valueNode, storeNode ); + node.append(); - } + return node; - return viewZNode; +}; - } +const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode ); +const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode ); +const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode ); +const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode ); +const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode ); +const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode ); +const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode ); +const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode ); - getLinearDepthNode( name = 'depth' ) { +let uniformsLib; - let linearDepthNode = this._linearDepthNodes[ name ]; +function getLightData( light ) { - if ( linearDepthNode === undefined ) { + uniformsLib = uniformsLib || new WeakMap(); - const cameraNear = this._cameraNear; - const cameraFar = this._cameraFar; - const viewZNode = this.getViewZNode( name ); + let uniforms = uniformsLib.get( light ); - // TODO: just if ( builder.camera.isPerspectiveCamera ) + if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} ); - this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar ); + return uniforms; - } +} - return linearDepthNode; +function lightPosition( light ) { - } + const data = getLightData( light ); - setup( { renderer } ) { + return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) ); - this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples; +} - // Disable MSAA for WebGL backend for now - if ( renderer.backend.isWebGLBackend === true ) { +function lightTargetPosition( light ) { - this.renderTarget.samples = 0; + const data = getLightData( light ); - } + return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) ); - this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1; +} - return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode(); +function lightViewPosition( light ) { - } + const data = getLightData( light ); - updateBefore( frame ) { + return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => { - const { renderer } = frame; - const { scene, camera } = this; + self.value = self.value || new Vector3(); + self.value.setFromMatrixPosition( light.matrixWorld ); - this._pixelRatio = renderer.getPixelRatio(); + self.value.applyMatrix4( camera.matrixWorldInverse ); - const size = renderer.getSize( _size$1 ); + } ) ); - this.setSize( size.width, size.height ); +} - const currentRenderTarget = renderer.getRenderTarget(); - const currentMRT = renderer.getMRT(); +const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) ); - this._cameraNear.value = camera.near; - this._cameraFar.value = camera.far; +const sortLights = ( lights ) => { - for ( const name in this._previousTextures ) { + return lights.sort( ( a, b ) => a.id - b.id ); - this.toggleTexture( name ); +}; - } +const getLightNodeById = ( id, lightNodes ) => { - renderer.setRenderTarget( this.renderTarget ); - renderer.setMRT( this._mrt ); + for ( const lightNode of lightNodes ) { - renderer.render( scene, camera ); + if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) { - renderer.setRenderTarget( currentRenderTarget ); - renderer.setMRT( currentMRT ); + return lightNode; + + } } - setSize( width, height ) { + return null; - this._width = width; - this._height = height; +}; - const effectiveWidth = this._width * this._pixelRatio; - const effectiveHeight = this._height * this._pixelRatio; +const _lightsNodeRef = /*@__PURE__*/ new WeakMap(); - this.renderTarget.setSize( effectiveWidth, effectiveHeight ); +class LightsNode extends Node { - } + static get type() { - setPixelRatio( pixelRatio ) { + return 'LightsNode'; - this._pixelRatio = pixelRatio; + } - this.setSize( this._width, this._height ); + constructor() { - } + super( 'vec3' ); - dispose() { + this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' ); + this.totalSpecularNode = vec3().toVar( 'totalSpecular' ); - this.renderTarget.dispose(); + this.outgoingLightNode = vec3().toVar( 'outgoingLight' ); - } + this._lights = []; + this._lightNodes = null; + this._lightNodesHash = null; -} + this.global = true; -PassNode.COLOR = 'color'; -PassNode.DEPTH = 'depth'; + } -const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) ); -const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) ); -const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); + getHash( builder ) { -class ToonOutlinePassNode extends PassNode { + if ( this._lightNodesHash === null ) { - static get type() { + if ( this._lightNodes === null ) this.setupLightsNode( builder ); - return 'ToonOutlinePassNode'; + const hash = []; - } + for ( const lightNode of this._lightNodes ) { - constructor( scene, camera, colorNode, thicknessNode, alphaNode ) { + hash.push( lightNode.getSelf().getHash() ); - super( PassNode.COLOR, scene, camera ); + } - this.colorNode = colorNode; - this.thicknessNode = thicknessNode; - this.alphaNode = alphaNode; + this._lightNodesHash = 'lights-' + hash.join( ',' ); - this._materialCache = new WeakMap(); + } + + return this._lightNodesHash; } - updateBefore( frame ) { + analyze( builder ) { - const { renderer } = frame; + const properties = builder.getDataFromNode( this ); - const currentRenderObjectFunction = renderer.getRenderObjectFunction(); + for ( const node of properties.nodes ) { - renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => { + node.build( builder ); - // only render outline for supported materials + } - if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) { + } - if ( material.wireframe === false ) { + setupLightsNode( builder ) { - const outlineMaterial = this._getOutlineMaterial( material ); - renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode ); + const lightNodes = []; - } + const previousLightNodes = this._lightNodes; - } + const lights = sortLights( this._lights ); + const nodeLibrary = builder.renderer.library; - // default + for ( const light of lights ) { - renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode ); + if ( light.isNode ) { - } ); + lightNodes.push( nodeObject( light ) ); - super.updateBefore( frame ); + } else { - renderer.setRenderObjectFunction( currentRenderObjectFunction ); + let lightNode = null; - } + if ( previousLightNodes !== null ) { - _createMaterial() { + lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node - const material = new NodeMaterial(); - material.isMeshToonOutlineMaterial = true; - material.name = 'Toon_Outline'; - material.side = BackSide; + } - // vertex node + if ( lightNode === null ) { - const outlineNormal = normalLocal.negate(); - const mvp = cameraProjectionMatrix.mul( modelViewMatrix ); + const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor ); - const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex - const pos = mvp.mul( vec4( positionLocal, 1.0 ) ); - const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) ); - const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative + if ( lightNodeClass === null ) { - material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) ); + console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` ); + continue; - // color node + } - material.colorNode = vec4( this.colorNode, this.alphaNode ); + let lightNode = null; - return material; + if ( ! _lightsNodeRef.has( light ) ) { - } + lightNode = nodeObject( new lightNodeClass( light ) ); + _lightsNodeRef.set( light, lightNode ); - _getOutlineMaterial( originalMaterial ) { + } else { - let outlineMaterial = this._materialCache.get( originalMaterial ); + lightNode = _lightsNodeRef.get( light ); - if ( outlineMaterial === undefined ) { + } - outlineMaterial = this._createMaterial(); + lightNodes.push( lightNode ); - this._materialCache.set( originalMaterial, outlineMaterial ); + } + + } } - return outlineMaterial; + this._lightNodes = lightNodes; } -} - -const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) ); + setupLights( builder, lightNodes ) { -class ScriptableValueNode extends Node { + for ( const lightNode of lightNodes ) { - static get type() { + lightNode.build( builder ); - return 'ScriptableValueNode'; + } } - constructor( value = null ) { + setup( builder ) { - super(); + if ( this._lightNodes === null ) this.setupLightsNode( builder ); - this._value = value; - this._cache = null; + const context = builder.context; + const lightingModel = context.lightingModel; - this.inputType = null; - this.outpuType = null; + let outgoingLightNode = this.outgoingLightNode; - this.events = new EventDispatcher(); + if ( lightingModel ) { - this.isScriptableValueNode = true; + const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this; - } + context.outgoingLight = outgoingLightNode; - get isScriptableOutputNode() { + const stack = builder.addStack(); - return this.outputType !== null; + // - } + const properties = builder.getDataFromNode( this ); + properties.nodes = stack.nodes; - set value( val ) { + // - if ( this._value === val ) return; + lightingModel.start( context, stack, builder ); - if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) { + // lights - URL.revokeObjectURL( this._cache ); + this.setupLights( builder, _lightNodes ); - this._cache = null; + // - } + lightingModel.indirect( context, stack, builder ); - this._value = val; + // - this.events.dispatchEvent( { type: 'change' } ); + const { backdrop, backdropAlpha } = context; + const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight; - this.refresh(); + let totalDiffuse = directDiffuse.add( indirectDiffuse ); - } + if ( backdrop !== null ) { - get value() { + if ( backdropAlpha !== null ) { - return this._value; + totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) ); - } + } else { - refresh() { + totalDiffuse = vec3( backdrop ); - this.events.dispatchEvent( { type: 'refresh' } ); + } - } + context.material.transparent = true; - getValue() { + } - const value = this.value; + totalDiffuseNode.assign( totalDiffuse ); + totalSpecularNode.assign( directSpecular.add( indirectSpecular ) ); - if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) { + outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) ); - this._cache = URL.createObjectURL( new Blob( [ value.value ] ) ); + // - } else if ( value && value.value !== null && value.value !== undefined && ( - ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) || - ( this.inputType === 'Number' && typeof value.value === 'number' ) || - ( this.inputType === 'Vector2' && value.value.isVector2 ) || - ( this.inputType === 'Vector3' && value.value.isVector3 ) || - ( this.inputType === 'Vector4' && value.value.isVector4 ) || - ( this.inputType === 'Color' && value.value.isColor ) || - ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) || - ( this.inputType === 'Matrix4' && value.value.isMatrix4 ) - ) ) { + lightingModel.finish( context, stack, builder ); - return value.value; + // + + outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() ); } - return this._cache || value; + return outgoingLightNode; } - getNodeType( builder ) { - - return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float'; + setLights( lights ) { - } + this._lights = lights; - setup() { + this._lightNodes = null; + this._lightNodesHash = null; - return this.value && this.value.isNode ? this.value : float(); + return this; } - serialize( data ) { + getLights() { - super.serialize( data ); + return this._lights; - if ( this.value !== null ) { + } - if ( this.inputType === 'ArrayBuffer' ) { + get hasLights() { - data.value = arrayBufferToBase64( this.value ); + return this._lights.length > 0; - } else { + } - data.value = this.value ? this.value.toJSON( data.meta ).uuid : null; +} - } +const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights ); - } else { +const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => { - data.value = null; + return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z ); - } +} ); - data.inputType = this.inputType; - data.outputType = this.outputType; +const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => { - } + const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare ); - deserialize( data ) { + const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); + const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup ); - super.deserialize( data ); + const texelSize = vec2( 1 ).div( mapSize ); + const dx0 = texelSize.x.negate().mul( radius ); + const dy0 = texelSize.y.negate().mul( radius ); + const dx1 = texelSize.x.mul( radius ); + const dy1 = texelSize.y.mul( radius ); + const dx2 = dx0.div( 2 ); + const dy2 = dy0.div( 2 ); + const dx3 = dx1.div( 2 ); + const dy3 = dy1.div( 2 ); - let value = null; + return add( + depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy, shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z ) + ).mul( 1 / 17 ); - if ( data.value !== null ) { +} ); - if ( data.inputType === 'ArrayBuffer' ) { +const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => { - value = base64ToArrayBuffer( data.value ); + const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare ); - } else if ( data.inputType === 'Texture' ) { + const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); - value = data.meta.textures[ data.value ]; + const texelSize = vec2( 1 ).div( mapSize ); + const dx = texelSize.x; + const dy = texelSize.y; - } else { + const uv = shadowCoord.xy; + const f = fract( uv.mul( mapSize ).add( 0.5 ) ); + uv.subAssign( f.mul( texelSize ) ); - value = data.meta.nodes[ data.value ] || null; + return add( + depthCompare( uv, shadowCoord.z ), + depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ), + depthCompare( uv.add( texelSize ), shadowCoord.z ), + mix( + depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ), + f.x + ), + mix( + depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ), + f.x + ), + mix( + depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ), + f.y + ), + mix( + depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ), + f.y + ), + mix( + mix( + depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ), + f.x + ), + mix( + depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ), + f.x + ), + f.y + ) + ).mul( 1 / 9 ); - } +} ); - } +// VSM - this.value = value; +const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => { - this.inputType = data.inputType; - this.outputType = data.outputType; + const occlusion = float( 1 ).toVar(); - } + const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg; -} + const hardShadow = step( shadowCoord.z, distribution.x ); -const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ); + If( hardShadow.notEqual( float( 1.0 ) ), () => { -class Resources extends Map { + const distance = shadowCoord.z.sub( distribution.x ); + const variance = max$1( 0, distribution.y.mul( distribution.y ) ); + let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality + softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) ); + occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) ); - get( key, callback = null, ...params ) { + } ); - if ( this.has( key ) ) return super.get( key ); + return occlusion; - if ( callback !== null ) { +} ); - const value = callback( ...params ); - this.set( key, value ); - return value; +const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => { - } + const mean = float( 0 ).toVar(); + const squaredMean = float( 0 ).toVar(); - } + const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) ); + const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) ); -} + Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => { -class Parameters { + const uvOffset = uvStart.add( float( i ).mul( uvStride ) ); - constructor( scriptableNode ) { + const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x; + mean.addAssign( depth ); + squaredMean.addAssign( depth.mul( depth ) ); - this.scriptableNode = scriptableNode; + } ); - } + mean.divAssign( samples ); + squaredMean.divAssign( samples ); - get parameters() { + const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) ); + return vec2( mean, std_dev ); - return this.scriptableNode.parameters; +} ); - } +const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => { - get layout() { + const mean = float( 0 ).toVar(); + const squaredMean = float( 0 ).toVar(); - return this.scriptableNode.getLayout(); + const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) ); + const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) ); - } + Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => { - getInputLayout( id ) { + const uvOffset = uvStart.add( float( i ).mul( uvStride ) ); - return this.scriptableNode.getInputLayout( id ); + const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) ); + mean.addAssign( distribution.x ); + squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) ); - } + } ); - get( name ) { + mean.divAssign( samples ); + squaredMean.divAssign( samples ); - const param = this.parameters[ name ]; - const value = param ? param.getValue() : null; + const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) ); + return vec2( mean, std_dev ); - return value; +} ); - } +const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ]; -} +// -const global = new Resources(); +let _overrideMaterial = null; +const _quadMesh$1 = /*@__PURE__*/ new QuadMesh(); -class ScriptableNode extends Node { +class ShadowNode extends Node { static get type() { - return 'ScriptableNode'; + return 'ShadowNode'; } - constructor( codeNode = null, parameters = {} ) { + constructor( light, shadow = null ) { super(); - this.codeNode = codeNode; - this.parameters = parameters; + this.light = light; + this.shadow = shadow || light.shadow; - this._local = new Resources(); - this._output = scriptableValue(); - this._outputs = {}; - this._source = this.source; - this._method = null; - this._object = null; - this._value = null; - this._needsOutputUpdate = true; + this.shadowMap = null; - this.onRefresh = this.onRefresh.bind( this ); + this.vsmShadowMapVertical = null; + this.vsmShadowMapHorizontal = null; - this.isScriptableNode = true; + this.vsmMaterialVertical = null; + this.vsmMaterialHorizontal = null; + + this.updateBeforeType = NodeUpdateType.RENDER; + this._node = null; + + this.isShadowNode = true; } - get source() { + setupShadow( builder ) { - return this.codeNode ? this.codeNode.code : ''; + const { object, renderer } = builder; - } + if ( _overrideMaterial === null ) { - setLocal( name, value ) { + _overrideMaterial = new NodeMaterial(); + _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 ); + _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode + _overrideMaterial.name = 'ShadowMaterial'; - return this._local.set( name, value ); + } - } + const shadow = this.shadow; + const shadowMapType = renderer.shadowMap.type; - getLocal( name ) { + const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height ); + depthTexture.compareFunction = LessCompare; - return this._local.get( name ); + const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height ); + shadowMap.depthTexture = depthTexture; - } + shadow.camera.updateProjectionMatrix(); - onRefresh() { + // VSM - this._refresh(); + if ( shadowMapType === VSMShadowMap ) { - } + depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare() - getInputLayout( id ) { + this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } ); + this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } ); - for ( const element of this.getLayout() ) { + const shadowPassVertical = texture( depthTexture ); + const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture ); - if ( element.inputType && ( element.id === id || element.name === id ) ) { + const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup ); + const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup ); + const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); - return element; + let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() ); + material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() ); + material.name = 'VSMVertical'; - } + material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() ); + material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() ); + material.name = 'VSMHorizontal'; } - } - - getOutputLayout( id ) { + // - for ( const element of this.getLayout() ) { + const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup ); + const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup ); + const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup ); - if ( element.outputType && ( element.id === id || element.name === id ) ) { + const position = object.material.shadowPositionNode || positionWorld; - return element; + let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) ); - } + let coordZ; - } + if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) { - } + shadowCoord = shadowCoord.xyz.div( shadowCoord.w ); - setOutput( name, value ) { + coordZ = shadowCoord.z; - const outputs = this._outputs; + if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) { - if ( outputs[ name ] === undefined ) { + coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ] - outputs[ name ] = scriptableValue( value ); + } } else { - outputs[ name ].value = value; + const w = shadowCoord.w; + shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z + + // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get + // updated to use the shadow camera. So, we have to declare our own "local" ones here. + // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here? + const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near ); + const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far ); + + coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal ); } - return this; + shadowCoord = vec3( + shadowCoord.x, + shadowCoord.y.oneMinus(), // follow webgpu standards + coordZ.add( bias ) + ); - } + const frustumTest = shadowCoord.x.greaterThanEqual( 0 ) + .and( shadowCoord.x.lessThanEqual( 1 ) ) + .and( shadowCoord.y.greaterThanEqual( 0 ) ) + .and( shadowCoord.y.lessThanEqual( 1 ) ) + .and( shadowCoord.z.lessThanEqual( 1 ) ); - getOutput( name ) { + // - return this._outputs[ name ]; + const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null; - } + if ( filterFn === null ) { - getParameter( name ) { + throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' ); - return this.parameters[ name ]; + } + + const shadowColor = texture( shadowMap.texture, shadowCoord ); + const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) ); + + this.shadowMap = shadowMap; + this.shadow.map = shadowMap; + + return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ); } - setParameter( name, value ) { + setup( builder ) { - const parameters = this.parameters; + if ( builder.renderer.shadowMap.enabled === false ) return; - if ( value && value.isScriptableNode ) { + return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) ); - this.deleteParameter( name ); + } - parameters[ name ] = value; - parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh ); + updateShadow( frame ) { - } else if ( value && value.isScriptableValueNode ) { + const { shadowMap, light, shadow } = this; + const { renderer, scene, camera } = frame; - this.deleteParameter( name ); + const shadowType = renderer.shadowMap.type; - parameters[ name ] = value; - parameters[ name ].events.addEventListener( 'refresh', this.onRefresh ); + const depthVersion = shadowMap.depthTexture.version; + this._depthVersionCached = depthVersion; - } else if ( parameters[ name ] === undefined ) { + const currentOverrideMaterial = scene.overrideMaterial; - parameters[ name ] = scriptableValue( value ); - parameters[ name ].events.addEventListener( 'refresh', this.onRefresh ); + scene.overrideMaterial = _overrideMaterial; - } else { + shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height ); - parameters[ name ].value = value; + shadow.updateMatrices( light ); + shadow.camera.layers.mask = camera.layers.mask; - } + const currentRenderTarget = renderer.getRenderTarget(); + const currentRenderObjectFunction = renderer.getRenderObjectFunction(); - return this; + renderer.setRenderObjectFunction( ( object, ...params ) => { - } + if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) { - getValue() { + renderer.renderObject( object, ...params ); - return this.getDefaultOutput().getValue(); + } - } + } ); - deleteParameter( name ) { + renderer.setRenderTarget( shadowMap ); + renderer.render( scene, shadow.camera ); - let valueNode = this.parameters[ name ]; + renderer.setRenderObjectFunction( currentRenderObjectFunction ); - if ( valueNode ) { + // vsm blur pass - if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput(); + if ( light.isPointLight !== true && shadowType === VSMShadowMap ) { - valueNode.events.removeEventListener( 'refresh', this.onRefresh ); + this.vsmPass( renderer ); } - return this; + renderer.setRenderTarget( currentRenderTarget ); - } + scene.overrideMaterial = currentOverrideMaterial; - clearParameters() { + } - for ( const name of Object.keys( this.parameters ) ) { + vsmPass( renderer ) { - this.deleteParameter( name ); + const { shadow } = this; - } + this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height ); + this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height ); - this.needsUpdate = true; + renderer.setRenderTarget( this.vsmShadowMapVertical ); + _quadMesh$1.material = this.vsmMaterialVertical; + _quadMesh$1.render( renderer ); - return this; + renderer.setRenderTarget( this.vsmShadowMapHorizontal ); + _quadMesh$1.material = this.vsmMaterialHorizontal; + _quadMesh$1.render( renderer ); } - call( name, ...params ) { - - const object = this.getObject(); - const method = object[ name ]; + dispose() { - if ( typeof method === 'function' ) { + this.shadowMap.dispose(); + this.shadowMap = null; - return method( ...params ); + if ( this.vsmShadowMapVertical !== null ) { - } + this.vsmShadowMapVertical.dispose(); + this.vsmShadowMapVertical = null; - } + this.vsmMaterialVertical.dispose(); + this.vsmMaterialVertical = null; - async callAsync( name, ...params ) { + } - const object = this.getObject(); - const method = object[ name ]; + if ( this.vsmShadowMapHorizontal !== null ) { - if ( typeof method === 'function' ) { + this.vsmShadowMapHorizontal.dispose(); + this.vsmShadowMapHorizontal = null; - return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params ); + this.vsmMaterialHorizontal.dispose(); + this.vsmMaterialHorizontal = null; } + this.updateBeforeType = NodeUpdateType.NONE; + } - getNodeType( builder ) { + updateBefore( frame ) { - return this.getDefaultOutputNode().getNodeType( builder ); + const { shadow } = this; - } + const needsUpdate = shadow.needsUpdate || shadow.autoUpdate; - refresh( output = null ) { + if ( needsUpdate ) { - if ( output !== null ) { + this.updateShadow( frame ); - this.getOutput( output ).refresh(); + if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) { - } else { + shadow.needsUpdate = false; - this._refresh(); + } } } - getObject() { +} - if ( this.needsUpdate ) this.dispose(); - if ( this._object !== null ) return this._object; +const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) ); - // +class AnalyticLightNode extends LightingNode { - const refresh = () => this.refresh(); - const setOutput = ( id, value ) => this.setOutput( id, value ); + static get type() { - const parameters = new Parameters( this ); + return 'AnalyticLightNode'; - const THREE = global.get( 'THREE' ); - const TSL = global.get( 'TSL' ); + } - const method = this.getMethod( this.codeNode ); - const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ]; + constructor( light = null ) { - this._object = method( ...params ); + super(); - const layout = this._object.layout; + this.updateType = NodeUpdateType.FRAME; - if ( layout ) { + this.light = light; - if ( layout.cache === false ) { + this.color = new Color(); + this.colorNode = uniform( this.color ).setGroup( renderGroup ); - this._local.clear(); + this.baseColorNode = null; - } + this.shadowNode = null; + this.shadowColorNode = null; - // default output - this._output.outputType = layout.outputType || null; + this.isAnalyticLightNode = true; - if ( Array.isArray( layout.elements ) ) { + } - for ( const element of layout.elements ) { + getCacheKey() { - const id = element.id || element.name; + return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 ); - if ( element.inputType ) { + } - if ( this.getParameter( id ) === undefined ) this.setParameter( id, null ); + getHash() { - this.getParameter( id ).inputType = element.inputType; + return this.light.uuid; - } + } - if ( element.outputType ) { + setupShadow( builder ) { - if ( this.getOutput( id ) === undefined ) this.setOutput( id, null ); + const { renderer } = builder; - this.getOutput( id ).outputType = element.outputType; + if ( renderer.shadowMap.enabled === false ) return; - } + let shadowColorNode = this.shadowColorNode; - } + if ( shadowColorNode === null ) { - } + const shadowNode = shadow( this.light ); - } + this.shadowNode = shadowNode; - return this._object; + this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode ); - } + this.baseColorNode = this.colorNode; - deserialize( data ) { + } - super.deserialize( data ); - - for ( const name in this.parameters ) { - - let valueNode = this.parameters[ name ]; - - if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput(); - - valueNode.events.addEventListener( 'refresh', this.onRefresh ); + // - } + this.colorNode = shadowColorNode; } - getLayout() { + setup( builder ) { - return this.getObject().layout; + this.colorNode = this.baseColorNode || this.colorNode; - } + if ( this.light.castShadow ) { - getDefaultOutputNode() { + if ( builder.object.receiveShadow ) { - const output = this.getDefaultOutput().value; + this.setupShadow( builder ); - if ( output && output.isNode ) { + } - return output; + } else if ( this.shadowNode !== null ) { - } + this.shadowNode.dispose(); - return float(); + } } - getDefaultOutput() { + update( /*frame*/ ) { - return this._exec()._output; + const { light } = this; - } + this.color.copy( light.color ).multiplyScalar( light.intensity ); - getMethod() { + } - if ( this.needsUpdate ) this.dispose(); - if ( this._method !== null ) return this._method; +} - // +const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => { - const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ]; - const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ]; + const { lightDistance, cutoffDistance, decayExponent } = inputs; - const properties = interfaceProps.join( ', ' ); - const declarations = 'var ' + properties + '; var output = {};\n'; - const returns = '\nreturn { ...output, ' + properties + ' };'; + // based upon Frostbite 3 Moving to Physically-based Rendering + // page 32, equation 26: E[window1] + // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal(); - const code = declarations + this.codeNode.code + returns; + return cutoffDistance.greaterThan( 0 ).select( + distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ), + distanceFalloff + ); - // +} ); // validated - this._method = new Function( ...parametersProps, code ); +const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => { - return this._method; + const lightingModel = builder.context.lightingModel; - } + const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode - dispose() { + const lightDirection = lVector.normalize(); + const lightDistance = lVector.length(); - if ( this._method === null ) return; + const lightAttenuation = getDistanceAttenuation( { + lightDistance, + cutoffDistance, + decayExponent + } ); - if ( this._object && typeof this._object.dispose === 'function' ) { + const lightColor = color.mul( lightAttenuation ); - this._object.dispose(); + const reflectedLight = builder.context.reflectedLight; - } + lightingModel.direct( { + lightDirection, + lightColor, + reflectedLight + }, builder.stack, builder ); - this._method = null; - this._object = null; - this._source = null; - this._value = null; - this._needsOutputUpdate = true; - this._output.value = null; - this._outputs = {}; +} ); - } +class PointLightNode extends AnalyticLightNode { - setup() { + static get type() { - return this.getDefaultOutputNode(); + return 'PointLightNode'; } - getCacheKey( force ) { - - const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ]; - - for ( const param in this.parameters ) { - - values.push( this.parameters[ param ].getCacheKey( force ) ); + constructor( light = null ) { - } + super( light ); - return hashArray( values ); + this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup ); + this.decayExponentNode = uniform( 0 ).setGroup( renderGroup ); } - set needsUpdate( value ) { - - if ( value === true ) this.dispose(); + update( frame ) { - } + const { light } = this; - get needsUpdate() { + super.update( frame ); - return this.source !== this._source; + this.cutoffDistanceNode.value = light.distance; + this.decayExponentNode.value = light.decay; } - _exec() { + setup() { - if ( this.codeNode === null ) return this; + directPointLight( { + color: this.colorNode, + lightViewPosition: lightViewPosition( this.light ), + cutoffDistance: this.cutoffDistanceNode, + decayExponent: this.decayExponentNode + } ).append(); - if ( this._needsOutputUpdate === true ) { + } - this._value = this.call( 'main' ); +} - this._needsOutputUpdate = false; +const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => { - } + const uv = coord.mul( 2.0 ); - this._output.value = this._value; + const cx = uv.x.floor(); + const cy = uv.y.floor(); + const result = cx.add( cy ).mod( 2.0 ); - return this; + return result.sign(); - } +} ); - _refresh() { +// Three.js Transpiler +// https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl - this.needsUpdate = true; - this._exec(); - this._output.refresh(); +const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => { - } + const f = float( f_immutable ).toVar(); + const t = float( t_immutable ).toVar(); + const b = bool( b_immutable ).toVar(); -} + return select( b, t, f ); -const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ); +} ).setLayout( { + name: 'mx_select', + type: 'float', + inputs: [ + { name: 'b', type: 'bool' }, + { name: 't', type: 'float' }, + { name: 'f', type: 'float' } + ] +} ); -class FogNode extends Node { +const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => { - static get type() { + const b = bool( b_immutable ).toVar(); + const val = float( val_immutable ).toVar(); - return 'FogNode'; + return select( b, val.negate(), val ); - } +} ).setLayout( { + name: 'mx_negate_if', + type: 'float', + inputs: [ + { name: 'val', type: 'float' }, + { name: 'b', type: 'bool' } + ] +} ); - constructor( colorNode, factorNode ) { +const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { - super( 'float' ); + const x = float( x_immutable ).toVar(); - this.isFogNode = true; + return int( floor( x ) ); - this.colorNode = colorNode; - this.factorNode = factorNode; +} ).setLayout( { + name: 'mx_floor', + type: 'int', + inputs: [ + { name: 'x', type: 'float' } + ] +} ); - } +const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => { - getViewZNode( builder ) { + const x = float( x_immutable ).toVar(); + i.assign( mx_floor( x ) ); - let viewZ; + return x.sub( float( i ) ); - const getViewZ = builder.context.getViewZ; +} ); - if ( getViewZ !== undefined ) { +const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => { - viewZ = getViewZ( this ); + const t = float( t_immutable ).toVar(); + const s = float( s_immutable ).toVar(); + const v3 = float( v3_immutable ).toVar(); + const v2 = float( v2_immutable ).toVar(); + const v1 = float( v1_immutable ).toVar(); + const v0 = float( v0_immutable ).toVar(); + const s1 = float( sub( 1.0, s ) ).toVar(); - } + return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ); - return ( viewZ || positionView.z ).negate(); +} ).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' } + ] +} ); - } +const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => { - setup() { + const t = float( t_immutable ).toVar(); + const s = float( s_immutable ).toVar(); + const v3 = vec3( v3_immutable ).toVar(); + const v2 = vec3( v2_immutable ).toVar(); + const v1 = vec3( v1_immutable ).toVar(); + const v0 = vec3( v0_immutable ).toVar(); + const s1 = float( sub( 1.0, s ) ).toVar(); - return this.factorNode; + return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ); - } +} ).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' } + ] +} ); -} +const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] ); -const fog = /*@__PURE__*/ nodeProxy( FogNode ); +const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => { -class FogRangeNode extends FogNode { + const r = float( r_immutable ).toVar(); + const t = float( t_immutable ).toVar(); + const s = float( s_immutable ).toVar(); + const v7 = float( v7_immutable ).toVar(); + const v6 = float( v6_immutable ).toVar(); + const v5 = float( v5_immutable ).toVar(); + const v4 = float( v4_immutable ).toVar(); + const v3 = float( v3_immutable ).toVar(); + const v2 = float( v2_immutable ).toVar(); + const v1 = float( v1_immutable ).toVar(); + const v0 = float( v0_immutable ).toVar(); + const s1 = float( sub( 1.0, s ) ).toVar(); + const t1 = float( sub( 1.0, t ) ).toVar(); + const r1 = float( sub( 1.0, r ) ).toVar(); - static get type() { + return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) ); - return 'FogRangeNode'; +} ).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' } + ] +} ); - } +const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => { - constructor( colorNode, nearNode, farNode ) { + const r = float( r_immutable ).toVar(); + const t = float( t_immutable ).toVar(); + const s = float( s_immutable ).toVar(); + const v7 = vec3( v7_immutable ).toVar(); + const v6 = vec3( v6_immutable ).toVar(); + const v5 = vec3( v5_immutable ).toVar(); + const v4 = vec3( v4_immutable ).toVar(); + const v3 = vec3( v3_immutable ).toVar(); + const v2 = vec3( v2_immutable ).toVar(); + const v1 = vec3( v1_immutable ).toVar(); + const v0 = vec3( v0_immutable ).toVar(); + const s1 = float( sub( 1.0, s ) ).toVar(); + const t1 = float( sub( 1.0, t ) ).toVar(); + const r1 = float( sub( 1.0, r ) ).toVar(); - super( colorNode ); + return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) ); - this.isFogRangeNode = true; +} ).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' } + ] +} ); - this.nearNode = nearNode; - this.farNode = farNode; +const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] ); - } +const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => { - setup( builder ) { + const y = float( y_immutable ).toVar(); + const x = float( x_immutable ).toVar(); + const hash = uint( hash_immutable ).toVar(); + const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar(); + const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar(); + const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar(); - const viewZ = this.getViewZNode( builder ); + return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) ); - return smoothstep( this.nearNode, this.farNode, viewZ ); +} ).setLayout( { + name: 'mx_gradient_float_0', + type: 'float', + inputs: [ + { name: 'hash', type: 'uint' }, + { name: 'x', type: 'float' }, + { name: 'y', type: 'float' } + ] +} ); - } +const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => { -} + const z = float( z_immutable ).toVar(); + const y = float( y_immutable ).toVar(); + const x = float( x_immutable ).toVar(); + const hash = uint( hash_immutable ).toVar(); + const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar(); + const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar(); + const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar(); -const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode ); + return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) ); -class FogExp2Node extends FogNode { +} ).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' } + ] +} ); - static get type() { +const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] ); - return 'FogExp2Node'; +const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => { - } + const y = float( y_immutable ).toVar(); + const x = float( x_immutable ).toVar(); + const hash = uvec3( hash_immutable ).toVar(); - constructor( colorNode, densityNode ) { + return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) ); - super( colorNode ); +} ).setLayout( { + name: 'mx_gradient_vec3_0', + type: 'vec3', + inputs: [ + { name: 'hash', type: 'uvec3' }, + { name: 'x', type: 'float' }, + { name: 'y', type: 'float' } + ] +} ); - this.isFogExp2Node = true; +const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => { - this.densityNode = densityNode; + const z = float( z_immutable ).toVar(); + const y = float( y_immutable ).toVar(); + const x = float( x_immutable ).toVar(); + const hash = uvec3( hash_immutable ).toVar(); - } + return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) ); - setup( builder ) { +} ).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' } + ] +} ); - const viewZ = this.getViewZNode( builder ); - const density = this.densityNode; +const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] ); - return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus(); +const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { - } + const v = float( v_immutable ).toVar(); -} + return mul( 0.6616, v ); -const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node ); +} ).setLayout( { + name: 'mx_gradient_scale2d_0', + type: 'float', + inputs: [ + { name: 'v', type: 'float' } + ] +} ); -let min = null; -let max = null; +const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { -class RangeNode extends Node { + const v = float( v_immutable ).toVar(); - static get type() { + return mul( 0.9820, v ); - return 'RangeNode'; +} ).setLayout( { + name: 'mx_gradient_scale3d_0', + type: 'float', + inputs: [ + { name: 'v', type: 'float' } + ] +} ); - } +const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { - constructor( minNode = float(), maxNode = float() ) { + const v = vec3( v_immutable ).toVar(); - super(); + return mul( 0.6616, v ); - this.minNode = minNode; - this.maxNode = maxNode; +} ).setLayout( { + name: 'mx_gradient_scale2d_1', + type: 'vec3', + inputs: [ + { name: 'v', type: 'vec3' } + ] +} ); - } +const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] ); - getVectorLength( builder ) { +const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { - const minLength = builder.getTypeLength( getValueType( this.minNode.value ) ); - const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) ); + const v = vec3( v_immutable ).toVar(); - return minLength > maxLength ? minLength : maxLength; + return mul( 0.9820, v ); - } +} ).setLayout( { + name: 'mx_gradient_scale3d_1', + type: 'vec3', + inputs: [ + { name: 'v', type: 'vec3' } + ] +} ); - getNodeType( builder ) { +const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] ); - return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float'; +const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => { - } + const k = int( k_immutable ).toVar(); + const x = uint( x_immutable ).toVar(); - setup( builder ) { + return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) ); - const object = builder.object; +} ).setLayout( { + name: 'mx_rotl32', + type: 'uint', + inputs: [ + { name: 'x', type: 'uint' }, + { name: 'k', type: 'int' } + ] +} ); - let output = null; +const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => { - if ( object.count > 1 ) { + a.subAssign( c ); + a.bitXorAssign( mx_rotl32( c, int( 4 ) ) ); + c.addAssign( b ); + b.subAssign( a ); + b.bitXorAssign( mx_rotl32( a, int( 6 ) ) ); + a.addAssign( c ); + c.subAssign( b ); + c.bitXorAssign( mx_rotl32( b, int( 8 ) ) ); + b.addAssign( a ); + a.subAssign( c ); + a.bitXorAssign( mx_rotl32( c, int( 16 ) ) ); + c.addAssign( b ); + b.subAssign( a ); + b.bitXorAssign( mx_rotl32( a, int( 19 ) ) ); + a.addAssign( c ); + c.subAssign( b ); + c.bitXorAssign( mx_rotl32( b, int( 4 ) ) ); + b.addAssign( a ); - const minValue = this.minNode.value; - const maxValue = this.maxNode.value; +} ); - const minLength = builder.getTypeLength( getValueType( minValue ) ); - const maxLength = builder.getTypeLength( getValueType( maxValue ) ); +const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => { - min = min || new Vector4(); - max = max || new Vector4(); - - min.setScalar( 0 ); - max.setScalar( 0 ); + const c = uint( c_immutable ).toVar(); + const b = uint( b_immutable ).toVar(); + const a = uint( a_immutable ).toVar(); + c.bitXorAssign( b ); + c.subAssign( mx_rotl32( b, int( 14 ) ) ); + a.bitXorAssign( c ); + a.subAssign( mx_rotl32( c, int( 11 ) ) ); + b.bitXorAssign( a ); + b.subAssign( mx_rotl32( a, int( 25 ) ) ); + c.bitXorAssign( b ); + c.subAssign( mx_rotl32( b, int( 16 ) ) ); + a.bitXorAssign( c ); + a.subAssign( mx_rotl32( c, int( 4 ) ) ); + b.bitXorAssign( a ); + b.subAssign( mx_rotl32( a, int( 14 ) ) ); + c.bitXorAssign( b ); + c.subAssign( mx_rotl32( b, int( 24 ) ) ); - if ( minLength === 1 ) min.setScalar( minValue ); - else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b ); - else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 ); + return c; - if ( maxLength === 1 ) max.setScalar( maxValue ); - else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b ); - else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 ); +} ).setLayout( { + name: 'mx_bjfinal', + type: 'uint', + inputs: [ + { name: 'a', type: 'uint' }, + { name: 'b', type: 'uint' }, + { name: 'c', type: 'uint' } + ] +} ); - const stride = 4; +const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => { - const length = stride * object.count; - const array = new Float32Array( length ); + const bits = uint( bits_immutable ).toVar(); - for ( let i = 0; i < length; i ++ ) { + return float( bits ).div( float( uint( int( 0xffffffff ) ) ) ); - const index = i % stride; +} ).setLayout( { + name: 'mx_bits_to_01', + type: 'float', + inputs: [ + { name: 'bits', type: 'uint' } + ] +} ); - const minElementValue = min.getComponent( index ); - const maxElementValue = max.getComponent( index ); +const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => { - array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() ); + const t = float( t_immutable ).toVar(); - } + return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) ); - const nodeType = this.getNodeType( builder ); +} ).setLayout( { + name: 'mx_fade', + type: 'float', + inputs: [ + { name: 't', type: 'float' } + ] +} ); - if ( object.count <= 4096 ) { +const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { - output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType ); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 1 ) ).toVar(); + const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar(); - } else { + return mx_bjfinal( seed.add( uint( x ) ), seed, seed ); - // TODO: Improve anonymous buffer attribute creation removing this part - const bufferAttribute = new InstancedBufferAttribute( array, 4 ); - builder.geometry.setAttribute( '__range' + this.id, bufferAttribute ); +} ).setLayout( { + name: 'mx_hash_int_0', + type: 'uint', + inputs: [ + { name: 'x', type: 'int' } + ] +} ); - output = instancedBufferAttribute( bufferAttribute ).convert( nodeType ); +const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => { - } + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 2 ) ).toVar(); + const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); + a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); + a.addAssign( uint( x ) ); + b.addAssign( uint( y ) ); - } else { + return mx_bjfinal( a, b, c ); - output = float( 0 ); +} ).setLayout( { + name: 'mx_hash_int_1', + type: 'uint', + inputs: [ + { name: 'x', type: 'int' }, + { name: 'y', type: 'int' } + ] +} ); - } +const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => { - return output; + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 3 ) ).toVar(); + const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); + a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); + a.addAssign( uint( x ) ); + b.addAssign( uint( y ) ); + c.addAssign( uint( z ) ); - } + return mx_bjfinal( a, b, c ); -} +} ).setLayout( { + name: 'mx_hash_int_2', + type: 'uint', + inputs: [ + { name: 'x', type: 'int' }, + { name: 'y', type: 'int' }, + { name: 'z', type: 'int' } + ] +} ); -const range = /*@__PURE__*/ nodeProxy( RangeNode ); +const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => { -const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => { + const xx = int( xx_immutable ).toVar(); + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 4 ) ).toVar(); + const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); + a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); + a.addAssign( uint( x ) ); + b.addAssign( uint( y ) ); + c.addAssign( uint( z ) ); + mx_bjmix( a, b, c ); + a.addAssign( uint( xx ) ); - return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z ); + return mx_bjfinal( a, b, 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' } + ] } ); -const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => { +const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => { - const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare ); + const yy = int( yy_immutable ).toVar(); + const xx = int( xx_immutable ).toVar(); + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 5 ) ).toVar(); + const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); + a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); + a.addAssign( uint( x ) ); + b.addAssign( uint( y ) ); + c.addAssign( uint( z ) ); + mx_bjmix( a, b, c ); + a.addAssign( uint( xx ) ); + b.addAssign( uint( yy ) ); - const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); - const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup ); + return mx_bjfinal( a, b, c ); - const texelSize = vec2( 1 ).div( mapSize ); - const dx0 = texelSize.x.negate().mul( radius ); - const dy0 = texelSize.y.negate().mul( radius ); - const dx1 = texelSize.x.mul( radius ); - const dy1 = texelSize.y.mul( radius ); - const dx2 = dx0.div( 2 ); - const dy2 = dy0.div( 2 ); - const dx3 = dx1.div( 2 ); - const dy3 = dy1.div( 2 ); +} ).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' } + ] +} ); - return add( - depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy, shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z ) - ).mul( 1 / 17 ); +const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] ); -} ); +const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => { -const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => { + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const h = uint( mx_hash_int( x, y ) ).toVar(); + const result = uvec3().toVar(); + result.x.assign( h.bitAnd( int( 0xFF ) ) ); + result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) ); + result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) ); - const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare ); + return result; - const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); +} ).setLayout( { + name: 'mx_hash_vec3_0', + type: 'uvec3', + inputs: [ + { name: 'x', type: 'int' }, + { name: 'y', type: 'int' } + ] +} ); - const texelSize = vec2( 1 ).div( mapSize ); - const dx = texelSize.x; - const dy = texelSize.y; +const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => { - const uv = shadowCoord.xy; - const f = fract( uv.mul( mapSize ).add( 0.5 ) ); - uv.subAssign( f.mul( texelSize ) ); + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const h = uint( mx_hash_int( x, y, z ) ).toVar(); + const result = uvec3().toVar(); + result.x.assign( h.bitAnd( int( 0xFF ) ) ); + result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) ); + result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) ); - return add( - depthCompare( uv, shadowCoord.z ), - depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ), - depthCompare( uv.add( texelSize ), shadowCoord.z ), - mix( - depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ), - f.x - ), - mix( - depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ), - f.x - ), - mix( - depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ), - f.y - ), - mix( - depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ), - f.y - ), - mix( - mix( - depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ), - f.x - ), - mix( - depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ), - f.x - ), - f.y - ) - ).mul( 1 / 9 ); + return result; +} ).setLayout( { + name: 'mx_hash_vec3_1', + type: 'uvec3', + inputs: [ + { name: 'x', type: 'int' }, + { name: 'y', type: 'int' }, + { name: 'z', type: 'int' } + ] } ); -// VSM - -const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => { +const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] ); - const occlusion = float( 1 ).toVar(); +const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg; + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const fx = float( mx_floorfrac( p.x, X ) ).toVar(); + const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); + const u = float( mx_fade( fx ) ).toVar(); + const v = float( mx_fade( fy ) ).toVar(); + const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar(); - const hardShadow = step( shadowCoord.z, distribution.x ); + return mx_gradient_scale2d( result ); - If( hardShadow.notEqual( float( 1.0 ) ), () => { +} ).setLayout( { + name: 'mx_perlin_noise_float_0', + type: 'float', + inputs: [ + { name: 'p', type: 'vec2' } + ] +} ); - const distance = shadowCoord.z.sub( distribution.x ); - const variance = max$1( 0, distribution.y.mul( distribution.y ) ); - let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality - softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) ); - occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) ); +const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - } ); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const fx = float( mx_floorfrac( p.x, X ) ).toVar(); + const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); + const fz = float( mx_floorfrac( p.z, Z ) ).toVar(); + const u = float( mx_fade( fx ) ).toVar(); + const v = float( mx_fade( fy ) ).toVar(); + const w = float( mx_fade( fz ) ).toVar(); + const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar(); - return occlusion; + return mx_gradient_scale3d( result ); +} ).setLayout( { + name: 'mx_perlin_noise_float_1', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' } + ] } ); -const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => { - - const mean = float( 0 ).toVar(); - const squaredMean = float( 0 ).toVar(); +const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] ); - const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) ); - const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) ); +const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => { + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const fx = float( mx_floorfrac( p.x, X ) ).toVar(); + const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); + const u = float( mx_fade( fx ) ).toVar(); + const v = float( mx_fade( fy ) ).toVar(); + const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar(); - const uvOffset = uvStart.add( float( i ).mul( uvStride ) ); + return mx_gradient_scale2d( result ); - const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x; - mean.addAssign( depth ); - squaredMean.addAssign( depth.mul( depth ) ); +} ).setLayout( { + name: 'mx_perlin_noise_vec3_0', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec2' } + ] +} ); - } ); +const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - mean.divAssign( samples ); - squaredMean.divAssign( samples ); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const fx = float( mx_floorfrac( p.x, X ) ).toVar(); + const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); + const fz = float( mx_floorfrac( p.z, Z ) ).toVar(); + const u = float( mx_fade( fx ) ).toVar(); + const v = float( mx_fade( fy ) ).toVar(); + const w = float( mx_fade( fz ) ).toVar(); + const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar(); - const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) ); - return vec2( mean, std_dev ); + return mx_gradient_scale3d( result ); +} ).setLayout( { + name: 'mx_perlin_noise_vec3_1', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] } ); -const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => { - - const mean = float( 0 ).toVar(); - const squaredMean = float( 0 ).toVar(); +const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] ); - const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) ); - const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) ); +const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => { + const p = float( p_immutable ).toVar(); + const ix = int( mx_floor( p ) ).toVar(); - const uvOffset = uvStart.add( float( i ).mul( uvStride ) ); + return mx_bits_to_01( mx_hash_int( ix ) ); - const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) ); - mean.addAssign( distribution.x ); - squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) ); +} ).setLayout( { + name: 'mx_cell_noise_float_0', + type: 'float', + inputs: [ + { name: 'p', type: 'float' } + ] +} ); - } ); +const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - mean.divAssign( samples ); - squaredMean.divAssign( samples ); + const p = vec2( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); - const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) ); - return vec2( mean, std_dev ); + return mx_bits_to_01( mx_hash_int( ix, iy ) ); +} ).setLayout( { + name: 'mx_cell_noise_float_1', + type: 'float', + inputs: [ + { name: 'p', type: 'vec2' } + ] } ); -const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ]; +const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { -// + const p = vec3( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); + const iz = int( mx_floor( p.z ) ).toVar(); -let _overrideMaterial = null; -const _quadMesh$1 = /*@__PURE__*/ new QuadMesh(); + return mx_bits_to_01( mx_hash_int( ix, iy, iz ) ); -class ShadowNode extends Node { +} ).setLayout( { + name: 'mx_cell_noise_float_2', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' } + ] +} ); - static get type() { +const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - return 'ShadowNode'; + const p = vec4( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); + const iz = int( mx_floor( p.z ) ).toVar(); + const iw = int( mx_floor( p.w ) ).toVar(); - } + return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) ); - constructor( light, shadow = null ) { +} ).setLayout( { + name: 'mx_cell_noise_float_3', + type: 'float', + inputs: [ + { name: 'p', type: 'vec4' } + ] +} ); - super(); +const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] ); - this.light = light; - this.shadow = shadow || light.shadow; +const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - this.shadowMap = null; + const p = float( p_immutable ).toVar(); + const ix = int( mx_floor( p ) ).toVar(); - this.vsmShadowMapVertical = null; - this.vsmShadowMapHorizontal = null; + return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) ); - this.vsmMaterialVertical = null; - this.vsmMaterialHorizontal = null; +} ).setLayout( { + name: 'mx_cell_noise_vec3_0', + type: 'vec3', + inputs: [ + { name: 'p', type: 'float' } + ] +} ); - this.updateBeforeType = NodeUpdateType.RENDER; - this._node = null; +const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - this.isShadowNode = true; + const p = vec2( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); - } + return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) ); - setupShadow( builder ) { +} ).setLayout( { + name: 'mx_cell_noise_vec3_1', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec2' } + ] +} ); - const { object, renderer } = builder; +const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - if ( _overrideMaterial === null ) { - - _overrideMaterial = new NodeMaterial(); - _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 ); - _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode - _overrideMaterial.name = 'ShadowMaterial'; - - } - - const shadow = this.shadow; - const shadowMapType = renderer.shadowMap.type; - - const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height ); - depthTexture.compareFunction = LessCompare; + const p = vec3( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); + const iz = int( mx_floor( p.z ) ).toVar(); - const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height ); - shadowMap.depthTexture = depthTexture; + return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) ); - shadow.camera.updateProjectionMatrix(); +} ).setLayout( { + name: 'mx_cell_noise_vec3_2', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] +} ); - // VSM +const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - if ( shadowMapType === VSMShadowMap ) { + const p = vec4( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); + const iz = int( mx_floor( p.z ) ).toVar(); + const iw = int( mx_floor( p.w ) ).toVar(); - depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare() + return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) ); - this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } ); - this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } ); +} ).setLayout( { + name: 'mx_cell_noise_vec3_3', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec4' } + ] +} ); - const shadowPassVertical = texture( depthTexture ); - const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture ); +const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] ); - const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup ); - const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup ); - const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); +const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { - let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() ); - material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() ); - material.name = 'VSMVertical'; + const diminish = float( diminish_immutable ).toVar(); + const lacunarity = float( lacunarity_immutable ).toVar(); + const octaves = int( octaves_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const result = float( 0.0 ).toVar(); + const amplitude = float( 1.0 ).toVar(); - material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() ); - material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() ); - material.name = 'VSMHorizontal'; + Loop( octaves, () => { - } + result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) ); + amplitude.mulAssign( diminish ); + p.mulAssign( lacunarity ); - // + } ); - const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup ); - const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup ); - const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup ); + return result; - const position = object.material.shadowPositionNode || positionWorld; +} ).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' } + ] +} ); - let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) ); +const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { - let coordZ; + const diminish = float( diminish_immutable ).toVar(); + const lacunarity = float( lacunarity_immutable ).toVar(); + const octaves = int( octaves_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const result = vec3( 0.0 ).toVar(); + const amplitude = float( 1.0 ).toVar(); - if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) { + Loop( octaves, () => { - shadowCoord = shadowCoord.xyz.div( shadowCoord.w ); + result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) ); + amplitude.mulAssign( diminish ); + p.mulAssign( lacunarity ); - coordZ = shadowCoord.z; + } ); - if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) { + return result; - coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ] +} ).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' } + ] +} ); - } +const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { - } else { + const diminish = float( diminish_immutable ).toVar(); + const lacunarity = float( lacunarity_immutable ).toVar(); + const octaves = int( octaves_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); - const w = shadowCoord.w; - shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z + return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ); - // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get - // updated to use the shadow camera. So, we have to declare our own "local" ones here. - // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here? - const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near ); - const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far ); +} ).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' } + ] +} ); - coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal ); +const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { - } + const diminish = float( diminish_immutable ).toVar(); + const lacunarity = float( lacunarity_immutable ).toVar(); + const octaves = int( octaves_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar(); + const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar(); - shadowCoord = vec3( - shadowCoord.x, - shadowCoord.y.oneMinus(), // follow webgpu standards - coordZ.add( bias ) - ); + return vec4( c, f ); - const frustumTest = shadowCoord.x.greaterThanEqual( 0 ) - .and( shadowCoord.x.lessThanEqual( 1 ) ) - .and( shadowCoord.y.greaterThanEqual( 0 ) ) - .and( shadowCoord.y.lessThanEqual( 1 ) ) - .and( shadowCoord.z.lessThanEqual( 1 ) ); +} ).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' } + ] +} ); - // +const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => { - const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null; + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const yoff = int( yoff_immutable ).toVar(); + const xoff = int( xoff_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const p = vec2( p_immutable ).toVar(); + const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar(); + const off = vec2( tmp.x, tmp.y ).toVar(); + off.subAssign( 0.5 ); + off.mulAssign( jitter ); + off.addAssign( 0.5 ); + const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar(); + const diff = vec2( cellpos.sub( p ) ).toVar(); - if ( filterFn === null ) { + If( metric.equal( int( 2 ) ), () => { - throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' ); + return abs( diff.x ).add( abs( diff.y ) ); - } + } ); - const shadowColor = texture( shadowMap.texture, shadowCoord ); - const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) ); + If( metric.equal( int( 3 ) ), () => { - this.shadowMap = shadowMap; - this.shadow.map = shadowMap; + return max$1( abs( diff.x ), abs( diff.y ) ); - return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ); + } ); - } + return dot( diff, diff ); - setup( builder ) { +} ).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' } + ] +} ); - if ( builder.renderer.shadowMap.enabled === false ) return; +const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => { - return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) ); + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const zoff = int( zoff_immutable ).toVar(); + const yoff = int( yoff_immutable ).toVar(); + const xoff = int( xoff_immutable ).toVar(); + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar(); + off.subAssign( 0.5 ); + off.mulAssign( jitter ); + off.addAssign( 0.5 ); + const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar(); + const diff = vec3( cellpos.sub( p ) ).toVar(); - } + If( metric.equal( int( 2 ) ), () => { - updateShadow( frame ) { + return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) ); - const { shadowMap, light, shadow } = this; - const { renderer, scene, camera } = frame; + } ); - const shadowType = renderer.shadowMap.type; + If( metric.equal( int( 3 ) ), () => { - const depthVersion = shadowMap.depthTexture.version; - this._depthVersionCached = depthVersion; + return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) ); - const currentOverrideMaterial = scene.overrideMaterial; + } ); - scene.overrideMaterial = _overrideMaterial; + return dot( diff, diff ); - shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height ); +} ).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' } + ] +} ); - shadow.updateMatrices( light ); - shadow.camera.layers.mask = camera.layers.mask; +const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] ); - const currentRenderTarget = renderer.getRenderTarget(); - const currentRenderObjectFunction = renderer.getRenderObjectFunction(); +const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - renderer.setRenderObjectFunction( ( object, ...params ) => { + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); + const sqdist = float( 1e6 ).toVar(); - if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) { + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - renderer.renderObject( object, ...params ); + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - } + const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); + sqdist.assign( min$1( sqdist, dist ) ); } ); - renderer.setRenderTarget( shadowMap ); - renderer.render( scene, shadow.camera ); + } ); - renderer.setRenderObjectFunction( currentRenderObjectFunction ); + If( metric.equal( int( 0 ) ), () => { - // vsm blur pass + sqdist.assign( sqrt( sqdist ) ); - if ( light.isPointLight !== true && shadowType === VSMShadowMap ) { + } ); - this.vsmPass( renderer ); + return sqdist; - } +} ).setLayout( { + name: 'mx_worley_noise_float_0', + type: 'float', + inputs: [ + { name: 'p', type: 'vec2' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - renderer.setRenderTarget( currentRenderTarget ); +const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - scene.overrideMaterial = currentOverrideMaterial; + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); + const sqdist = vec2( 1e6, 1e6 ).toVar(); - } + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - vsmPass( renderer ) { + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - const { shadow } = this; + const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); - this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height ); - this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height ); + If( dist.lessThan( sqdist.x ), () => { - renderer.setRenderTarget( this.vsmShadowMapVertical ); - _quadMesh$1.material = this.vsmMaterialVertical; - _quadMesh$1.render( renderer ); + sqdist.y.assign( sqdist.x ); + sqdist.x.assign( dist ); - renderer.setRenderTarget( this.vsmShadowMapHorizontal ); - _quadMesh$1.material = this.vsmMaterialHorizontal; - _quadMesh$1.render( renderer ); + } ).ElseIf( dist.lessThan( sqdist.y ), () => { - } + sqdist.y.assign( dist ); - dispose() { + } ); - this.shadowMap.dispose(); - this.shadowMap = null; + } ); - if ( this.vsmShadowMapVertical !== null ) { + } ); - this.vsmShadowMapVertical.dispose(); - this.vsmShadowMapVertical = null; + If( metric.equal( int( 0 ) ), () => { - this.vsmMaterialVertical.dispose(); - this.vsmMaterialVertical = null; + sqdist.assign( sqrt( sqdist ) ); - } + } ); - if ( this.vsmShadowMapHorizontal !== null ) { + return sqdist; - this.vsmShadowMapHorizontal.dispose(); - this.vsmShadowMapHorizontal = null; +} ).setLayout( { + name: 'mx_worley_noise_vec2_0', + type: 'vec2', + inputs: [ + { name: 'p', type: 'vec2' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - this.vsmMaterialHorizontal.dispose(); - this.vsmMaterialHorizontal = null; +const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - } + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); + const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar(); - this.updateBeforeType = NodeUpdateType.NONE; + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - } + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - updateBefore( frame ) { + const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); - const { shadow } = this; + If( dist.lessThan( sqdist.x ), () => { - const needsUpdate = shadow.needsUpdate || shadow.autoUpdate; + sqdist.z.assign( sqdist.y ); + sqdist.y.assign( sqdist.x ); + sqdist.x.assign( dist ); - if ( needsUpdate ) { + } ).ElseIf( dist.lessThan( sqdist.y ), () => { - this.updateShadow( frame ); + sqdist.z.assign( sqdist.y ); + sqdist.y.assign( dist ); - if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) { + } ).ElseIf( dist.lessThan( sqdist.z ), () => { - shadow.needsUpdate = false; + sqdist.z.assign( dist ); - } + } ); - } + } ); - } + } ); -} + If( metric.equal( int( 0 ) ), () => { -const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) ); + sqdist.assign( sqrt( sqdist ) ); -class AnalyticLightNode extends LightingNode { + } ); - static get type() { + return sqdist; - return 'AnalyticLightNode'; +} ).setLayout( { + name: 'mx_worley_noise_vec3_0', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec2' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - } +const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - constructor( light = null ) { + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); + const sqdist = float( 1e6 ).toVar(); - super(); + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - this.updateType = NodeUpdateType.FRAME; + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - this.light = light; + Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { - this.color = new Color(); - this.colorNode = uniform( this.color ).setGroup( renderGroup ); + const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); + sqdist.assign( min$1( sqdist, dist ) ); - this.baseColorNode = null; + } ); - this.shadowNode = null; - this.shadowColorNode = null; + } ); - this.isAnalyticLightNode = true; + } ); - } + If( metric.equal( int( 0 ) ), () => { - getCacheKey() { + sqdist.assign( sqrt( sqdist ) ); - return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 ); + } ); - } + return sqdist; - getHash() { +} ).setLayout( { + name: 'mx_worley_noise_float_1', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - return this.light.uuid; +const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] ); - } +const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - setupShadow( builder ) { + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); + const sqdist = vec2( 1e6, 1e6 ).toVar(); - const { renderer } = builder; + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - if ( renderer.shadowMap.enabled === false ) return; + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - let shadowColorNode = this.shadowColorNode; + Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { - if ( shadowColorNode === null ) { + const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); - const shadowNode = shadow( this.light ); + If( dist.lessThan( sqdist.x ), () => { - this.shadowNode = shadowNode; + sqdist.y.assign( sqdist.x ); + sqdist.x.assign( dist ); - this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode ); + } ).ElseIf( dist.lessThan( sqdist.y ), () => { - this.baseColorNode = this.colorNode; + sqdist.y.assign( dist ); - } + } ); - // + } ); - this.colorNode = shadowColorNode; + } ); - } + } ); - setup( builder ) { + If( metric.equal( int( 0 ) ), () => { - this.colorNode = this.baseColorNode || this.colorNode; + sqdist.assign( sqrt( sqdist ) ); - if ( this.light.castShadow ) { + } ); - if ( builder.object.receiveShadow ) { + return sqdist; - this.setupShadow( builder ); - - } +} ).setLayout( { + name: 'mx_worley_noise_vec2_1', + type: 'vec2', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - } else if ( this.shadowNode !== null ) { +const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] ); - this.shadowNode.dispose(); +const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - } + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); + const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar(); - } + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - update( /*frame*/ ) { + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - const { light } = this; + Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { - this.color.copy( light.color ).multiplyScalar( light.intensity ); + const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); - } + If( dist.lessThan( sqdist.x ), () => { -} + sqdist.z.assign( sqdist.y ); + sqdist.y.assign( sqdist.x ); + sqdist.x.assign( dist ); -const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => { + } ).ElseIf( dist.lessThan( sqdist.y ), () => { - const { lightDistance, cutoffDistance, decayExponent } = inputs; + sqdist.z.assign( sqdist.y ); + sqdist.y.assign( dist ); - // based upon Frostbite 3 Moving to Physically-based Rendering - // page 32, equation 26: E[window1] - // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal(); + } ).ElseIf( dist.lessThan( sqdist.z ), () => { - return cutoffDistance.greaterThan( 0 ).select( - distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ), - distanceFalloff - ); + sqdist.z.assign( dist ); -} ); // validated + } ); -let uniformsLib; + } ); -function getLightData( light ) { + } ); - uniformsLib = uniformsLib || new WeakMap(); + } ); - let uniforms = uniformsLib.get( light ); + If( metric.equal( int( 0 ) ), () => { - if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} ); + sqdist.assign( sqrt( sqdist ) ); - return uniforms; + } ); -} + return sqdist; -function lightPosition( light ) { +} ).setLayout( { + name: 'mx_worley_noise_vec3_1', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - const data = getLightData( light ); +const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] ); - return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) ); +// Three.js Transpiler +// https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl -} -function lightTargetPosition( light ) { +const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => { - const data = getLightData( light ); + const s = hsv.y; + const v = hsv.z; - return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) ); + const result = vec3().toVar(); -} + If( s.lessThan( 0.0001 ), () => { -function lightViewPosition( light ) { + result.assign( vec3( v, v, v ) ); - const data = getLightData( light ); + } ).Else( () => { - return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => { + let h = hsv.x; + h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache + const hi = int( trunc( h ) ); + const f = h.sub( float( hi ) ); + const p = v.mul( s.oneMinus() ); + const q = v.mul( s.mul( f ).oneMinus() ); + const t = v.mul( s.mul( f.oneMinus() ).oneMinus() ); - self.value = self.value || new Vector3(); - self.value.setFromMatrixPosition( light.matrixWorld ); + If( hi.equal( int( 0 ) ), () => { - self.value.applyMatrix4( camera.matrixWorldInverse ); + result.assign( vec3( v, t, p ) ); - } ) ); + } ).ElseIf( hi.equal( int( 1 ) ), () => { -} + result.assign( vec3( q, v, p ) ); -const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) ); + } ).ElseIf( hi.equal( int( 2 ) ), () => { -const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => { + result.assign( vec3( p, v, t ) ); - // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org + } ).ElseIf( hi.equal( int( 3 ) ), () => { - const state = seed.toUint().mul( 747796405 ).add( 2891336453 ); - const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 ); - const result = word.shiftRight( 22 ).bitXor( word ); + result.assign( vec3( p, q, v ) ); - return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1) + } ).ElseIf( hi.equal( int( 4 ) ), () => { -} ); + result.assign( vec3( t, p, v ) ); -// remapping functions https://iquilezles.org/articles/functions/ -const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k ); -const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) ); -const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a ); -const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) ); + } ).Else( () => { -// https://github.com/cabbibo/glsl-tri-noise-3d + result.assign( vec3( v, p, q ) ); + } ); -const tri = /*@__PURE__*/ Fn( ( [ x ] ) => { + } ); - return x.fract().sub( .5 ).abs(); + return result; } ).setLayout( { - name: 'tri', - type: 'float', + name: 'mx_hsvtorgb', + type: 'vec3', inputs: [ - { name: 'x', type: 'float' } + { name: 'hsv', type: 'vec3' } ] } ); -const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => { +const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => { - return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) ); + const c = vec3( c_immutable ).toVar(); + const r = float( c.x ).toVar(); + const g = float( c.y ).toVar(); + const b = float( c.z ).toVar(); + const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar(); + const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar(); + const delta = float( maxcomp.sub( mincomp ) ).toVar(); + const h = float().toVar(), s = float().toVar(), v = float().toVar(); + v.assign( maxcomp ); + + If( maxcomp.greaterThan( 0.0 ), () => { + + s.assign( delta.div( maxcomp ) ); + + } ).Else( () => { + + s.assign( 0.0 ); + + } ); + + If( s.lessThanEqual( 0.0 ), () => { + + h.assign( 0.0 ); + + } ).Else( () => { + + If( r.greaterThanEqual( maxcomp ), () => { + + h.assign( g.sub( b ).div( delta ) ); + + } ).ElseIf( g.greaterThanEqual( maxcomp ), () => { + + h.assign( add( 2.0, b.sub( r ).div( delta ) ) ); + + } ).Else( () => { + + h.assign( add( 4.0, r.sub( g ).div( delta ) ) ); + + } ); + + h.mulAssign( 1.0 / 6.0 ); + + If( h.lessThan( 0.0 ), () => { + + h.addAssign( 1.0 ); + + } ); + + } ); + + return vec3( h, s, v ); } ).setLayout( { - name: 'tri3', + name: 'mx_rgbtohsv', type: 'vec3', inputs: [ - { name: 'p', type: 'vec3' } + { name: 'c', type: 'vec3' } ] } ); -const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => { - - const p = vec3( p_immutable ).toVar(); - const z = float( 1.4 ).toVar(); - const rz = float( 0.0 ).toVar(); - const bp = vec3( p ).toVar(); - - Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => { +// Three.js Transpiler +// https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl - const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar(); - p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) ); - bp.mulAssign( 1.8 ); - z.mulAssign( 1.5 ); - p.mulAssign( 1.2 ); - const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar(); - rz.addAssign( t.div( z ) ); - bp.addAssign( 0.14 ); +const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => { - } ); + const color = vec3( color_immutable ).toVar(); + const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar(); + const linSeg = vec3( color.div( 12.92 ) ).toVar(); + const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar(); - return rz; + return mix( linSeg, powSeg, isAbove ); } ).setLayout( { - name: 'triNoise3D', - type: 'float', + name: 'mx_srgb_texture_to_lin_rec709', + type: 'vec3', inputs: [ - { name: 'p', type: 'vec3' }, - { name: 'spd', type: 'float' }, - { name: 'time', type: 'float' } + { name: 'color', type: 'vec3' } ] } ); -const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time ); -const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime ); -const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId ); +const mx_aastep = ( threshold, value ) => { -// Deprecated + threshold = float( threshold ); + value = float( value ); -const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170 + const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 ); - console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' ); - return time.mul( timeScale ); + return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value ); }; -const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170 +const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() ); +const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' ); +const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' ); - console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' ); - return time.mul( timeScale ); +const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) ); +const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' ); +const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' ); -}; +const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset ); -const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170 +const mx_safepower = ( in1, in2 = 1 ) => { - console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' ); - return deltaTime.mul( timeScale ); + in1 = float( in1 ); + + return in1.abs().pow( in2 ).mul( in1.sign() ); }; -const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 ); -const oscSquare = ( t = time ) => t.fract().round(); -const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs(); -const oscSawtooth = ( t = time ) => t.fract(); +const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot ); -const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => { +const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +//export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => { - return rotate( uv.sub( center ), rotation ).add( center ); + texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type -} ); + const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) ); -const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => { + return noise_vec4.mul( amplitude ).add( pivot ); - const delta = uv.sub( center ); - const delta2 = delta.dot( delta ); - const delta4 = delta2.mul( delta2 ); - const deltaOffset = delta4.mul( strength ); +}; - return uv.add( delta.mul( deltaOffset ) ); +const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -} ); +const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) ); -const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => { +const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); - let worldMatrix; +const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => { - if ( position !== null ) { + // normal is assumed to have unit length - worldMatrix = modelWorldMatrix.toVar(); - worldMatrix[ 3 ][ 0 ] = position.x; - worldMatrix[ 3 ][ 1 ] = position.y; - worldMatrix[ 3 ][ 2 ] = position.z; + const x = normal.x, y = normal.y, z = normal.z; - } else { + // band 0 + let result = shCoefficients.element( 0 ).mul( 0.886227 ); - worldMatrix = modelWorldMatrix; + // band 1 + result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) ); + result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) ); + result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) ); - } + // band 2 + result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) ); + result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) ); + result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) ); + result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) ); + result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) ); - const modelViewMatrix = cameraViewMatrix.mul( worldMatrix ); + return result; - if ( defined( horizontal ) ) { +} ); - modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length(); - modelViewMatrix[ 0 ][ 1 ] = 0; - modelViewMatrix[ 0 ][ 2 ] = 0; +const _clearColor$1 = /*@__PURE__*/ new Color4(); - } +class Background extends DataMap { - if ( defined( vertical ) ) { + constructor( renderer, nodes ) { - modelViewMatrix[ 1 ][ 0 ] = 0; - modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length(); - modelViewMatrix[ 1 ][ 2 ] = 0; + super(); + + this.renderer = renderer; + this.nodes = nodes; } - modelViewMatrix[ 2 ][ 0 ] = 0; - modelViewMatrix[ 2 ][ 1 ] = 0; - modelViewMatrix[ 2 ][ 2 ] = 1; + update( scene, renderList, renderContext ) { - return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal ); + const renderer = this.renderer; + const background = this.nodes.getBackgroundNode( scene ) || scene.background; -} ); + let forceClear = false; -const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => { + if ( background === null ) { - const depth = linearDepth(); - const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth ); - const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv ); + // no background settings, use clear color configuration from the renderer - return finalUV; + renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace ); + _clearColor$1.a = renderer._clearColor.a; -} ); + } else if ( background.isColor === true ) { -/** -* Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments -* depth value and the camera's inverse projection matrix. -* -* @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates. -* @param {float} depth - The fragment's depth value. -* @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix. -* @return {vec3} The fragments position in view space. -*/ -const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => { + // background is an opaque color - let clipSpacePosition; + background.getRGB( _clearColor$1, LinearSRGBColorSpace ); + _clearColor$1.a = 1; - if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) { + forceClear = true; - screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 ); - clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 ); + } else if ( background.isNode === true ) { - } else { + const sceneData = this.get( scene ); + const backgroundNode = background; - clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 ); + _clearColor$1.copy( renderer._clearColor ); - } + let backgroundMesh = sceneData.backgroundMesh; - const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) ); + if ( backgroundMesh === undefined ) { - return viewSpacePosition.xyz.div( viewSpacePosition.w ); + const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), { + // @TODO: Add Texture2D support using node context + getUV: () => normalWorld, + getTextureLevel: () => backgroundBlurriness + } ); -} ); + let viewProj = modelViewProjection(); + viewProj = viewProj.setZ( viewProj.w ); -/** -* Computes a screen position expressed as uv coordinates based on a fragment's position in view space -* and the camera's projection matrix -* -* @param {vec3} viewPosition - The fragments position in view space. -* @param {mat4} projectionMatrix - The camera's projection matrix. -* @return {vec2} Teh fragment's screen position expressed as uv coordinates. -*/ -const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => { + const nodeMaterial = new NodeMaterial(); + nodeMaterial.name = 'Background.material'; + nodeMaterial.side = BackSide; + nodeMaterial.depthTest = false; + nodeMaterial.depthWrite = false; + nodeMaterial.fog = false; + nodeMaterial.lights = false; + nodeMaterial.vertexNode = viewProj; + nodeMaterial.colorNode = backgroundMeshNode; - const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) ); - const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar(); - return vec2( sampleUv.x, sampleUv.y.oneMinus() ); + sceneData.backgroundMeshNode = backgroundMeshNode; + sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial ); + backgroundMesh.frustumCulled = false; + backgroundMesh.name = 'Background.mesh'; -} ); + backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) { -const _objectData = new WeakMap(); + this.matrixWorld.copyPosition( camera.matrixWorld ); -class VelocityNode extends TempNode { + }; - static get type() { + } - return 'VelocityNode'; + const backgroundCacheKey = backgroundNode.getCacheKey(); - } + if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) { - constructor() { + sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity ); + sceneData.backgroundMeshNode.needsUpdate = true; - super( 'vec2' ); + backgroundMesh.material.needsUpdate = true; - this.updateType = NodeUpdateType.OBJECT; - this.updateAfterType = NodeUpdateType.OBJECT; + sceneData.backgroundCacheKey = backgroundCacheKey; - this.previousModelWorldMatrix = uniform( new Matrix4() ); - this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup ); - this.previousCameraViewMatrix = uniform( new Matrix4() ); + } - } + renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null ); - update( { frameId, camera, object } ) { + } else { - const previousModelMatrix = getPreviousMatrix( object ); + console.error( 'THREE.Renderer: Unsupported background configuration.', background ); - this.previousModelWorldMatrix.value.copy( previousModelMatrix ); + } // - const cameraData = getData( camera ); - - if ( cameraData.frameId !== frameId ) { - - cameraData.frameId = frameId; - - if ( cameraData.previousProjectionMatrix === undefined ) { + if ( renderer.autoClear === true || forceClear === true ) { - cameraData.previousProjectionMatrix = new Matrix4(); - cameraData.previousCameraViewMatrix = new Matrix4(); + const clearColorValue = renderContext.clearColorValue; - cameraData.currentProjectionMatrix = new Matrix4(); - cameraData.currentCameraViewMatrix = new Matrix4(); + clearColorValue.r = _clearColor$1.r; + clearColorValue.g = _clearColor$1.g; + clearColorValue.b = _clearColor$1.b; + clearColorValue.a = _clearColor$1.a; - cameraData.previousProjectionMatrix.copy( camera.projectionMatrix ); - cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse ); + // premultiply alpha - } else { + if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) { - cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix ); - cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix ); + clearColorValue.r *= clearColorValue.a; + clearColorValue.g *= clearColorValue.a; + clearColorValue.b *= clearColorValue.a; } - cameraData.currentProjectionMatrix.copy( camera.projectionMatrix ); - cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse ); + // - this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix ); - this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix ); + renderContext.depthClearValue = renderer._clearDepth; + renderContext.stencilClearValue = renderer._clearStencil; - } + renderContext.clearColor = renderer.autoClearColor === true; + renderContext.clearDepth = renderer.autoClearDepth === true; + renderContext.clearStencil = renderer.autoClearStencil === true; - } + } else { - updateAfter( { object } ) { + renderContext.clearColor = false; + renderContext.clearDepth = false; + renderContext.clearStencil = false; - getPreviousMatrix( object ).copy( object.matrixWorld ); + } } - setup( /*builder*/ ) { +} - const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix ); +let _id$5 = 0; - const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal ); - const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious ); +class BindGroup { - const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w ); - const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w ); + constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) { - const velocity = sub( ndcPositionCurrent, ndcPositionPrevious ); + this.name = name; + this.bindings = bindings; + this.index = index; + this.bindingsReference = bindingsReference; - return velocity; + this.id = _id$5 ++; } } -function getData( object ) { +class NodeBuilderState { - let objectData = _objectData.get( object ); - - if ( objectData === undefined ) { - - objectData = {}; - _objectData.set( object, objectData ); - - } + constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) { - return objectData; + this.vertexShader = vertexShader; + this.fragmentShader = fragmentShader; + this.computeShader = computeShader; + this.transforms = transforms; -} + this.nodeAttributes = nodeAttributes; + this.bindings = bindings; -function getPreviousMatrix( object, index = 0 ) { + this.updateNodes = updateNodes; + this.updateBeforeNodes = updateBeforeNodes; + this.updateAfterNodes = updateAfterNodes; - const objectData = getData( object ); + this.monitor = monitor; - let matrix = objectData[ index ]; + this.usedTimes = 0; - if ( matrix === undefined ) { + } - objectData[ index ] = matrix = new Matrix4(); + createBindings() { - } + const bindings = []; - return matrix; + for ( const instanceGroup of this.bindings ) { -} + const shared = instanceGroup.bindings[ 0 ].groupNode.shared; -const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode ); + if ( shared !== true ) { -const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { + const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup ); + bindings.push( bindingsGroup ); - return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus(); + for ( const instanceBinding of instanceGroup.bindings ) { -} ).setLayout( { - name: 'burnBlend', - type: 'vec3', - inputs: [ - { name: 'base', type: 'vec3' }, - { name: 'blend', type: 'vec3' } - ] -} ); + bindingsGroup.bindings.push( instanceBinding.clone() ); -const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { + } - return min$1( base.div( blend.oneMinus() ), 1.0 ); + } else { -} ).setLayout( { - name: 'dodgeBlend', - type: 'vec3', - inputs: [ - { name: 'base', type: 'vec3' }, - { name: 'blend', type: 'vec3' } - ] -} ); + bindings.push( instanceGroup ); -const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { + } - return base.oneMinus().mul( blend.oneMinus() ).oneMinus(); + } -} ).setLayout( { - name: 'screenBlend', - type: 'vec3', - inputs: [ - { name: 'base', type: 'vec3' }, - { name: 'blend', type: 'vec3' } - ] -} ); + return bindings; -const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { + } - return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) ); +} -} ).setLayout( { - name: 'overlayBlend', - type: 'vec3', - inputs: [ - { name: 'base', type: 'vec3' }, - { name: 'blend', type: 'vec3' } - ] -} ); +class NodeAttribute { -const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => { + constructor( name, type, node = null ) { - return luminance( color.rgb ); + this.isNodeAttribute = true; -} ); + this.name = name; + this.type = type; + this.node = node; -const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { + } - return adjustment.mix( luminance( color.rgb ), color.rgb ); +} -} ); +class NodeUniform { -const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { + constructor( name, type, node ) { - const average = add( color.r, color.g, color.b ).div( 3.0 ); + this.isNodeUniform = true; - const mx = color.r.max( color.g.max( color.b ) ); - const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 ); + this.name = name; + this.type = type; + this.node = node.getSelf(); - return mix( color.rgb, mx, amt ); + } -} ); + get value() { -const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { + return this.node.value; - const k = vec3( 0.57735, 0.57735, 0.57735 ); + } - const cosAngle = adjustment.cos(); + set value( val ) { - return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) ); + this.node.value = val; -} ); + } -const luminance = ( - color, - luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) ) -) => dot( color, luminanceCoefficients ); + get id() { -const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) ); + return this.node.id; -/** - * Color Decision List (CDL) v1.2 - * - * Compact representation of color grading information, defined by slope, offset, power, and - * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc, - * or AgX Log), and will return output in the same space. Output may require clamping >=0. - * - * @param {vec4} color Input (-Infinity < input < +Infinity) - * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity) - * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1) - * @param {number | vec3} power Power (0 < power < +Infinity) - * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4) - * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709 - * @return Output, -Infinity < output < +Infinity - * - * References: - * - ASC CDL v1.2 - * - https://blender.stackexchange.com/a/55239/43930 - * - https://docs.acescentral.com/specifications/acescc/ - */ -const cdl = /*@__PURE__*/ Fn( ( [ - color, - slope = vec3( 1 ), - offset = vec3( 0 ), - power = vec3( 1 ), - saturation = float( 1 ), - // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients. - luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) ) -] ) => { + } - // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the - // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support - // values outside [0, 1], requiring a workaround for negative values in the power expression. + get groupNode() { - const luma = color.rgb.dot( vec3( luminanceCoefficients ) ); + return this.node.groupNode; - const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar(); - const pv = v.pow( power ).toVar(); + } - If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line - If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line - If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line +} - v.assign( luma.add( v.sub( luma ).mul( saturation ) ) ); +class NodeVar { - return vec4( v.rgb, color.a ); + constructor( name, type ) { -} ); + this.isNodeVar = true; -const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => { + this.name = name; + this.type = type; - const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 ); - const b = color.mul( 0.0773993808 ); - const factor = color.lessThanEqual( 0.04045 ); + } - const rgbResult = mix( a, b, factor ); +} - return rgbResult; +class NodeVarying extends NodeVar { -} ).setLayout( { - name: 'sRGBToLinearSRGB', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' } - ] -} ); + constructor( name, type ) { -const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => { + super( name, type ); - const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 ); - const b = color.mul( 12.92 ); - const factor = color.lessThanEqual( 0.0031308 ); + this.needsInterpolation = false; - const rgbResult = mix( a, b, factor ); + this.isNodeVarying = true; - return rgbResult; + } -} ).setLayout( { - name: 'linearSRGBTosRGB', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' } - ] -} ); +} -// exposure only +class NodeCode { -const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { + constructor( name, type, code = '' ) { - return color.mul( exposure ).clamp(); + this.name = name; + this.type = type; + this.code = code; -} ).setLayout( { - name: 'linearToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + Object.defineProperty( this, 'isNodeCode', { value: true } ); -// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf + } -const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { +} - color = color.mul( exposure ); +let id = 0; - return color.div( color.add( 1.0 ) ).clamp(); +class NodeCache { -} ).setLayout( { - name: 'reinhardToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + constructor( parent = null ) { -// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/ + this.id = id ++; + this.nodesData = new WeakMap(); -const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { + this.parent = parent; - // filmic operator by Jim Hejl and Richard Burgess-Dawson - color = color.mul( exposure ); - color = color.sub( 0.004 ).max( 0.0 ); + } - const a = color.mul( color.mul( 6.2 ).add( 0.5 ) ); - const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 ); + getData( node ) { - return a.div( b ).pow( 2.2 ); + let data = this.nodesData.get( node ); -} ).setLayout( { - name: 'cineonToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + if ( data === undefined && this.parent !== null ) { -// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs + data = this.parent.getData( node ); -const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => { + } - const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 ); - const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 ); + return data; - return a.div( b ); + } -} ); + setData( node, data ) { -// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs + this.nodesData.set( node, data ); -const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { + } - // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT - const ACESInputMat = mat3( - 0.59719, 0.35458, 0.04823, - 0.07600, 0.90834, 0.01566, - 0.02840, 0.13383, 0.83777 - ); +} - // ODT_SAT => XYZ => D60_2_D65 => sRGB - const ACESOutputMat = mat3( - 1.60475, - 0.53108, - 0.07367, - - 0.10208, 1.10813, - 0.00605, - - 0.00327, - 0.07276, 1.07602 - ); +class Uniform { - color = color.mul( exposure ).div( 0.6 ); + constructor( name, value ) { - color = ACESInputMat.mul( color ); + this.name = name; + this.value = value; - // Apply RRT and ODT - color = RRTAndODTFit( color ); + this.boundary = 0; // used to build the uniform buffer according to the STD140 layout + this.itemSize = 0; - color = ACESOutputMat.mul( color ); + this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer - // Clamp to [0, 1] - return color.clamp(); + } -} ).setLayout( { - name: 'acesFilmicToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + setValue( value ) { -const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); -const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); + this.value = value; -const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { + } - const x = vec3( x_immutable ).toVar(); - const x2 = vec3( x.mul( x ) ).toVar(); - const x4 = vec3( x2.mul( x2 ) ).toVar(); + getValue() { - return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) ); + return this.value; -} ); + } -const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { +} - const colortone = vec3( color ).toVar(); - const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); - const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); - const AgxMinEv = float( - 12.47393 ); - const AgxMaxEv = float( 4.026069 ); - colortone.mulAssign( exposure ); - colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) ); - colortone.assign( AgXInsetMatrix.mul( colortone ) ); - colortone.assign( max$1( colortone, 1e-10 ) ); - colortone.assign( log2( colortone ) ); - colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) ); - colortone.assign( clamp( colortone, 0.0, 1.0 ) ); - colortone.assign( agxDefaultContrastApprox( colortone ) ); - colortone.assign( AgXOutsetMatrix.mul( colortone ) ); - colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) ); - colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) ); - colortone.assign( clamp( colortone, 0.0, 1.0 ) ); +class NumberUniform extends Uniform { - return colortone; + constructor( name, value = 0 ) { -} ).setLayout( { - name: 'agxToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + super( name, value ); -// https://modelviewer.dev/examples/tone-mapping + this.isNumberUniform = true; -const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { + this.boundary = 4; + this.itemSize = 1; - const StartCompression = float( 0.8 - 0.04 ); - const Desaturation = float( 0.15 ); + } - color = color.mul( exposure ); +} - const x = min$1( color.r, min$1( color.g, color.b ) ); - const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 ); +class Vector2Uniform extends Uniform { - color.subAssign( offset ); + constructor( name, value = new Vector2() ) { - const peak = max$1( color.r, max$1( color.g, color.b ) ); + super( name, value ); - If( peak.lessThan( StartCompression ), () => { + this.isVector2Uniform = true; - return color; + this.boundary = 8; + this.itemSize = 2; - } ); + } - const d = sub( 1, StartCompression ); - const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) ); - color.mulAssign( newPeak.div( peak ) ); - const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) ); +} - return mix( color, vec3( newPeak ), g ); +class Vector3Uniform extends Uniform { -} ).setLayout( { - name: 'neutralToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + constructor( name, value = new Vector3() ) { -class ComputeBuiltinNode extends Node { + super( name, value ); - static get type() { + this.isVector3Uniform = true; - return 'ComputeBuiltinNode'; + this.boundary = 16; + this.itemSize = 3; } - constructor( builtinName, nodeType ) { +} - super( nodeType ); +class Vector4Uniform extends Uniform { - this._builtinName = builtinName; + constructor( name, value = new Vector4() ) { - } + super( name, value ); - getHash( builder ) { + this.isVector4Uniform = true; - return this.getBuiltinName( builder ); + this.boundary = 16; + this.itemSize = 4; } - getNodeType( /*builder*/ ) { +} - return this.nodeType; +class ColorUniform extends Uniform { - } + constructor( name, value = new Color() ) { - setBuiltinName( builtinName ) { + super( name, value ); - this._builtinName = builtinName; + this.isColorUniform = true; - return this; + this.boundary = 16; + this.itemSize = 3; } - getBuiltinName( /*builder*/ ) { +} - return this._builtinName; +class Matrix3Uniform extends Uniform { - } + constructor( name, value = new Matrix3() ) { - hasBuiltin( builder ) { + super( name, value ); - builder.hasBuiltin( this._builtinName ); + this.isMatrix3Uniform = true; - } + this.boundary = 48; + this.itemSize = 12; - generate( builder, output ) { + } - const builtinName = this.getBuiltinName( builder ); - const nodeType = this.getNodeType( builder ); +} - if ( builder.shaderStage === 'compute' ) { +class Matrix4Uniform extends Uniform { - return builder.format( builtinName, nodeType, output ); + constructor( name, value = new Matrix4() ) { - } else { + super( name, value ); - console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` ); - return builder.generateConst( nodeType ); + this.isMatrix4Uniform = true; - } + this.boundary = 64; + this.itemSize = 16; } - serialize( data ) { +} - super.serialize( data ); +class NumberNodeUniform extends NumberUniform { - data.global = this.global; - data._builtinName = this._builtinName; + constructor( nodeUniform ) { - } + super( nodeUniform.name, nodeUniform.value ); - deserialize( data ) { + this.nodeUniform = nodeUniform; - super.deserialize( data ); + } - this.global = data.global; - this._builtinName = data._builtinName; + getValue() { + + return this.nodeUniform.value; } } -const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) ); +class Vector2NodeUniform extends Vector2Uniform { -const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' ); -const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' ); -const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' ); -const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' ); + constructor( nodeUniform ) { -class BarrierNode extends Node { + super( nodeUniform.name, nodeUniform.value ); - constructor( scope ) { + this.nodeUniform = nodeUniform; - super(); + } - this.scope = scope; + getValue() { + + return this.nodeUniform.value; } - generate( builder ) { +} - const { scope } = this; - const { renderer } = builder; +class Vector3NodeUniform extends Vector3Uniform { - if ( renderer.backend.isWebGLBackend === true ) { + constructor( nodeUniform ) { - builder.addFlowCode( `\t// ${scope}Barrier \n` ); + super( nodeUniform.name, nodeUniform.value ); - } else { + this.nodeUniform = nodeUniform; - builder.addLineFlowCode( `${scope}Barrier()`, this ); + } - } + getValue() { + + return this.nodeUniform.value; } } -const barrier = nodeProxy( BarrierNode ); +class Vector4NodeUniform extends Vector4Uniform { -const workgroupBarrier = () => barrier( 'workgroup' ).append(); -const storageBarrier = () => barrier( 'storage' ).append(); -const textureBarrier = () => barrier( 'texture' ).append(); + constructor( nodeUniform ) { -class WorkgroupInfoElementNode extends ArrayElementNode { + super( nodeUniform.name, nodeUniform.value ); - constructor( workgroupInfoNode, indexNode ) { + this.nodeUniform = nodeUniform; - super( workgroupInfoNode, indexNode ); + } - this.isWorkgroupInfoElementNode = true; + getValue() { - } + return this.nodeUniform.value; - generate( builder, output ) { + } - let snippet; +} - const isAssignContext = builder.context.assign; - snippet = super.generate( builder ); +class ColorNodeUniform extends ColorUniform { - if ( isAssignContext !== true ) { + constructor( nodeUniform ) { - const type = this.getNodeType( builder ); + super( nodeUniform.name, nodeUniform.value ); - snippet = builder.format( snippet, type, output ); + this.nodeUniform = nodeUniform; - } + } - // TODO: Possibly activate clip distance index on index access rather than from clipping context + getValue() { - return snippet; + return this.nodeUniform.value; } } +class Matrix3NodeUniform extends Matrix3Uniform { -class WorkgroupInfoNode extends Node { + constructor( nodeUniform ) { - constructor( scope, bufferType, bufferCount = 0 ) { + super( nodeUniform.name, nodeUniform.value ); - super( bufferType ); + this.nodeUniform = nodeUniform; - this.bufferType = bufferType; - this.bufferCount = bufferCount; + } - this.isWorkgroupInfoNode = true; + getValue() { - this.scope = scope; + return this.nodeUniform.value; } - label( name ) { +} - this.name = name; +class Matrix4NodeUniform extends Matrix4Uniform { - return this; + constructor( nodeUniform ) { + + super( nodeUniform.name, nodeUniform.value ); + + this.nodeUniform = nodeUniform; } - getHash() { + getValue() { - return this.uuid; + return this.nodeUniform.value; } - setScope( scope ) { +} - this.scope = scope; +const LOD_MIN = 4; - return this; +// The standard deviations (radians) associated with the extra mips. These are +// chosen to approximate a Trowbridge-Reitz distribution function times the +// geometric shadowing function. These sigma values squared must match the +// variance #defines in cube_uv_reflection_fragment.glsl.js. +const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; - } +// The maximum length of the blur for loop. Smaller sigmas will use fewer +// samples and exit early, but not recompile the shader. +const MAX_SAMPLES = 20; - getInputType( /*builder*/ ) { +const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); +const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 ); +const _clearColor = /*@__PURE__*/ new Color(); +let _oldTarget = null; +let _oldActiveCubeFace = 0; +let _oldActiveMipmapLevel = 0; - return `${this.scope}Array`; +// Golden Ratio +const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; +const INV_PHI = 1 / PHI; - } +// Vertices of a dodecahedron (except the opposites, which represent the +// same axis), used as axis directions evenly spread on a sphere. +const _axisDirections = [ + /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), + /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, 1 ), + /*@__PURE__*/ new Vector3( 1, 1, 1 ) +]; - element( indexNode ) { +// - return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) ); +// WebGPU Face indices +const _faceLib = [ + 3, 1, 5, + 0, 4, 2 +]; - } +const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize(); +const outputDirection = vec3( direction.x, direction.y.negate(), direction.z ); - generate( builder ) { +/** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * Paper: Fast, Accurate Image-Based Lighting + * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view +*/ - return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount ); +class PMREMGenerator { + + constructor( renderer ) { + + this._renderer = renderer; + 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; } -} + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { -const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) ); + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); -class AtomicFunctionNode extends TempNode { + this._setSize( 256 ); - static get type() { + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; - return 'AtomicFunctionNode'; + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); - } + if ( sigma > 0 ) { - constructor( method, pointerNode, valueNode, storeNode = null ) { + this._blur( cubeUVRenderTarget, 0, 0, sigma ); - super( 'uint' ); + } - this.method = method; + this._applyPMREM( cubeUVRenderTarget ); - this.pointerNode = pointerNode; - this.valueNode = valueNode; - this.storeNode = storeNode; + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; } - getInputType( builder ) { + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { - return this.pointerNode.getNodeType( builder ); + return this._fromTexture( equirectangular, renderTarget ); } - getNodeType( builder ) { + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap( cubemap, renderTarget = null ) { - return this.getInputType( builder ); + return this._fromTexture( cubemap, renderTarget ); } - generate( builder ) { + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + async compileCubemapShader() { - const method = this.method; + if ( this._cubemapMaterial === null ) { - const type = this.getNodeType( builder ); - const inputType = this.getInputType( builder ); + this._cubemapMaterial = _getCubemapMaterial(); + await this._compileMaterial( this._cubemapMaterial ); - const a = this.pointerNode; - const b = this.valueNode; + } - const params = []; + } - params.push( `&${ a.build( builder, inputType ) }` ); - params.push( b.build( builder, inputType ) ); + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + async compileEquirectangularShader() { - const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`; + if ( this._equirectMaterial === null ) { - if ( this.storeNode !== null ) { + this._equirectMaterial = _getEquirectMaterial(); + await this._compileMaterial( this._equirectMaterial ); - const varSnippet = this.storeNode.build( builder, inputType ); + } - builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this ); + } - } else { + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { - builder.addLineFlowCode( methodSnippet, this ); + this._dispose(); + + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); + if ( this._backgroundBox !== null ) { + + this._backgroundBox.geometry.dispose(); + this._backgroundBox.material.dispose(); } } -} + // private interface -AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad'; -AtomicFunctionNode.ATOMIC_STORE = 'atomicStore'; -AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd'; -AtomicFunctionNode.ATOMIC_SUB = 'atomicSub'; -AtomicFunctionNode.ATOMIC_MAX = 'atomicMax'; -AtomicFunctionNode.ATOMIC_MIN = 'atomicMin'; -AtomicFunctionNode.ATOMIC_AND = 'atomicAnd'; -AtomicFunctionNode.ATOMIC_OR = 'atomicOr'; -AtomicFunctionNode.ATOMIC_XOR = 'atomicXor'; + _setSize( cubeSize ) { -const atomicNode = nodeProxy( AtomicFunctionNode ); + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); -const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => { + } - const node = atomicNode( method, pointerNode, valueNode, storeNode ); - node.append(); + _dispose() { - return node; + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); -}; + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); -const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode ); -const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode ); -const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode ); -const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode ); -const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode ); -const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode ); -const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode ); -const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode ); + for ( let i = 0; i < this._lodPlanes.length; i ++ ) { -const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => { + this._lodPlanes[ i ].dispose(); - const uv = coord.mul( 2.0 ); + } - const cx = uv.x.floor(); - const cy = uv.y.floor(); - const result = cx.add( cy ).mod( 2.0 ); + } - return result.sign(); + _cleanup( outputTarget ) { -} ); + this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel ); + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); -// Three.js Transpiler -// https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl + } + _fromTexture( texture, renderTarget ) { + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { -const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => { + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); - const f = float( f_immutable ).toVar(); - const t = float( t_immutable ).toVar(); - const b = bool( b_immutable ).toVar(); + } else { // Equirectangular - return select( b, t, f ); + this._setSize( texture.image.width / 4 ); -} ).setLayout( { - name: 'mx_select', - type: 'float', - inputs: [ - { name: 'b', type: 'bool' }, - { name: 't', type: 'float' }, - { name: 'f', type: 'float' } - ] -} ); + } -const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => { + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); - const b = bool( b_immutable ).toVar(); - const val = float( val_immutable ).toVar(); + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); - return select( b, val.negate(), val ); + return cubeUVRenderTarget; -} ).setLayout( { - name: 'mx_negate_if', - type: 'float', - inputs: [ - { name: 'val', type: 'float' }, - { name: 'b', type: 'bool' } - ] -} ); + } -const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { + _allocateTargets() { - const x = float( x_immutable ).toVar(); + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; - return int( floor( x ) ); + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + //depthBuffer: false + }; -} ).setLayout( { - name: 'mx_floor', - type: 'int', - inputs: [ - { name: 'x', type: 'float' } - ] -} ); + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); -const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => { + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { - const x = float( x_immutable ).toVar(); - i.assign( mx_floor( x ) ); + if ( this._pingPongRenderTarget !== null ) { - return x.sub( float( i ) ); + this._dispose(); -} ); + } -const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => { + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); - const t = float( t_immutable ).toVar(); - const s = float( s_immutable ).toVar(); - const v3 = float( v3_immutable ).toVar(); - const v2 = float( v2_immutable ).toVar(); - const v1 = float( v1_immutable ).toVar(); - const v0 = float( v0_immutable ).toVar(); - const s1 = float( sub( 1.0, s ) ).toVar(); + const { _lodMax } = this; + ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) ); - return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ); + this._blurMaterial = _getBlurShader( _lodMax, width, height ); -} ).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' } - ] -} ); + } -const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => { + return cubeUVRenderTarget; - const t = float( t_immutable ).toVar(); - const s = float( s_immutable ).toVar(); - const v3 = vec3( v3_immutable ).toVar(); - const v2 = vec3( v2_immutable ).toVar(); - const v1 = vec3( v1_immutable ).toVar(); - const v0 = vec3( v0_immutable ).toVar(); - const s1 = float( sub( 1.0, s ) ).toVar(); + } - return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ); + async _compileMaterial( material ) { -} ).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' } - ] -} ); + const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); + await this._renderer.compile( tmpMesh, _flatCamera ); -const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] ); + } -const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => { + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { - const r = float( r_immutable ).toVar(); - const t = float( t_immutable ).toVar(); - const s = float( s_immutable ).toVar(); - const v7 = float( v7_immutable ).toVar(); - const v6 = float( v6_immutable ).toVar(); - const v5 = float( v5_immutable ).toVar(); - const v4 = float( v4_immutable ).toVar(); - const v3 = float( v3_immutable ).toVar(); - const v2 = float( v2_immutable ).toVar(); - const v1 = float( v1_immutable ).toVar(); - const v0 = float( v0_immutable ).toVar(); - const s1 = float( sub( 1.0, s ) ).toVar(); - const t1 = float( sub( 1.0, t ) ).toVar(); - const r1 = float( sub( 1.0, r ) ).toVar(); + const cubeCamera = _cubeCamera; + cubeCamera.near = near; + cubeCamera.far = far; - return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) ); + // px, py, pz, nx, ny, nz + const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ]; + const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; -} ).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' } - ] -} ); + const renderer = this._renderer; -const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => { + const originalAutoClear = renderer.autoClear; - const r = float( r_immutable ).toVar(); - const t = float( t_immutable ).toVar(); - const s = float( s_immutable ).toVar(); - const v7 = vec3( v7_immutable ).toVar(); - const v6 = vec3( v6_immutable ).toVar(); - const v5 = vec3( v5_immutable ).toVar(); - const v4 = vec3( v4_immutable ).toVar(); - const v3 = vec3( v3_immutable ).toVar(); - const v2 = vec3( v2_immutable ).toVar(); - const v1 = vec3( v1_immutable ).toVar(); - const v0 = vec3( v0_immutable ).toVar(); - const s1 = float( sub( 1.0, s ) ).toVar(); - const t1 = float( sub( 1.0, t ) ).toVar(); - const r1 = float( sub( 1.0, r ) ).toVar(); + renderer.getClearColor( _clearColor ); - return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) ); + renderer.autoClear = false; -} ).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' } - ] -} ); + let backgroundBox = this._backgroundBox; -const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] ); + if ( backgroundBox === null ) { -const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => { + const backgroundMaterial = new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false + } ); - const y = float( y_immutable ).toVar(); - const x = float( x_immutable ).toVar(); - const hash = uint( hash_immutable ).toVar(); - const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar(); - const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar(); - const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar(); + backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); - return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) ); + } -} ).setLayout( { - name: 'mx_gradient_float_0', - type: 'float', - inputs: [ - { name: 'hash', type: 'uint' }, - { name: 'x', type: 'float' }, - { name: 'y', type: 'float' } - ] -} ); + let useSolidColor = false; + const background = scene.background; -const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => { + if ( background ) { - const z = float( z_immutable ).toVar(); - const y = float( y_immutable ).toVar(); - const x = float( x_immutable ).toVar(); - const hash = uint( hash_immutable ).toVar(); - const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar(); - const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar(); - const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar(); + if ( background.isColor ) { - return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) ); + backgroundBox.material.color.copy( background ); + scene.background = null; + useSolidColor = true; -} ).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' } - ] -} ); + } -const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] ); + } else { -const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => { + backgroundBox.material.color.copy( _clearColor ); + useSolidColor = true; - const y = float( y_immutable ).toVar(); - const x = float( x_immutable ).toVar(); - const hash = uvec3( hash_immutable ).toVar(); + } - return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) ); + renderer.setRenderTarget( cubeUVRenderTarget ); -} ).setLayout( { - name: 'mx_gradient_vec3_0', - type: 'vec3', - inputs: [ - { name: 'hash', type: 'uvec3' }, - { name: 'x', type: 'float' }, - { name: 'y', type: 'float' } - ] -} ); + renderer.clear(); -const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => { + if ( useSolidColor ) { - const z = float( z_immutable ).toVar(); - const y = float( y_immutable ).toVar(); - const x = float( x_immutable ).toVar(); - const hash = uvec3( hash_immutable ).toVar(); + renderer.render( backgroundBox, cubeCamera ); - return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) ); + } -} ).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' } - ] -} ); + for ( let i = 0; i < 6; i ++ ) { -const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] ); + const col = i % 3; -const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { + if ( col === 0 ) { - const v = float( v_immutable ).toVar(); + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); - return mul( 0.6616, v ); + } else if ( col === 1 ) { -} ).setLayout( { - name: 'mx_gradient_scale2d_0', - type: 'float', - inputs: [ - { name: 'v', type: 'float' } - ] -} ); + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); -const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { + } else { - const v = float( v_immutable ).toVar(); + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); - return mul( 0.9820, v ); + } -} ).setLayout( { - name: 'mx_gradient_scale3d_0', - type: 'float', - inputs: [ - { name: 'v', type: 'float' } - ] -} ); + const size = this._cubeSize; -const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); - const v = vec3( v_immutable ).toVar(); + renderer.render( scene, cubeCamera ); - return mul( 0.6616, v ); + } -} ).setLayout( { - name: 'mx_gradient_scale2d_1', - type: 'vec3', - inputs: [ - { name: 'v', type: 'vec3' } - ] -} ); + renderer.autoClear = originalAutoClear; + scene.background = background; -const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] ); + } -const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { + _textureToCubeUV( texture, cubeUVRenderTarget ) { - const v = vec3( v_immutable ).toVar(); + const renderer = this._renderer; - return mul( 0.9820, v ); + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); -} ).setLayout( { - name: 'mx_gradient_scale3d_1', - type: 'vec3', - inputs: [ - { name: 'v', type: 'vec3' } - ] -} ); + if ( isCubeTexture ) { -const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] ); + if ( this._cubemapMaterial === null ) { -const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => { + this._cubemapMaterial = _getCubemapMaterial( texture ); - const k = int( k_immutable ).toVar(); - const x = uint( x_immutable ).toVar(); + } - return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) ); + } else { -} ).setLayout( { - name: 'mx_rotl32', - type: 'uint', - inputs: [ - { name: 'x', type: 'uint' }, - { name: 'k', type: 'int' } - ] -} ); + if ( this._equirectMaterial === null ) { -const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => { + this._equirectMaterial = _getEquirectMaterial( texture ); - a.subAssign( c ); - a.bitXorAssign( mx_rotl32( c, int( 4 ) ) ); - c.addAssign( b ); - b.subAssign( a ); - b.bitXorAssign( mx_rotl32( a, int( 6 ) ) ); - a.addAssign( c ); - c.subAssign( b ); - c.bitXorAssign( mx_rotl32( b, int( 8 ) ) ); - b.addAssign( a ); - a.subAssign( c ); - a.bitXorAssign( mx_rotl32( c, int( 16 ) ) ); - c.addAssign( b ); - b.subAssign( a ); - b.bitXorAssign( mx_rotl32( a, int( 19 ) ) ); - a.addAssign( c ); - c.subAssign( b ); - c.bitXorAssign( mx_rotl32( b, int( 4 ) ) ); - b.addAssign( a ); + } -} ); + } -const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => { + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + material.fragmentNode.value = texture; - const c = uint( c_immutable ).toVar(); - const b = uint( b_immutable ).toVar(); - const a = uint( a_immutable ).toVar(); - c.bitXorAssign( b ); - c.subAssign( mx_rotl32( b, int( 14 ) ) ); - a.bitXorAssign( c ); - a.subAssign( mx_rotl32( c, int( 11 ) ) ); - b.bitXorAssign( a ); - b.subAssign( mx_rotl32( a, int( 25 ) ) ); - c.bitXorAssign( b ); - c.subAssign( mx_rotl32( b, int( 16 ) ) ); - a.bitXorAssign( c ); - a.subAssign( mx_rotl32( c, int( 4 ) ) ); - b.bitXorAssign( a ); - b.subAssign( mx_rotl32( a, int( 14 ) ) ); - c.bitXorAssign( b ); - c.subAssign( mx_rotl32( b, int( 24 ) ) ); + const mesh = this._lodMeshes[ 0 ]; + mesh.material = material; - return c; + const size = this._cubeSize; -} ).setLayout( { - name: 'mx_bjfinal', - type: 'uint', - inputs: [ - { name: 'a', type: 'uint' }, - { name: 'b', type: 'uint' }, - { name: 'c', type: 'uint' } - ] -} ); + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); -const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => { + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); - const bits = uint( bits_immutable ).toVar(); + } - return float( bits ).div( float( uint( int( 0xffffffff ) ) ) ); + _applyPMREM( cubeUVRenderTarget ) { -} ).setLayout( { - name: 'mx_bits_to_01', - type: 'float', - inputs: [ - { name: 'bits', type: 'uint' } - ] -} ); + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + const n = this._lodPlanes.length; -const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => { + for ( let i = 1; i < n; i ++ ) { - const t = float( t_immutable ).toVar(); + const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); - return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) ); + const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ]; -} ).setLayout( { - name: 'mx_fade', - type: 'float', - inputs: [ - { name: 't', type: 'float' } - ] -} ); + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); -const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { + } - const x = int( x_immutable ).toVar(); - const len = uint( uint( 1 ) ).toVar(); - const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar(); + renderer.autoClear = autoClear; - return mx_bjfinal( seed.add( uint( x ) ), seed, seed ); + } -} ).setLayout( { - name: 'mx_hash_int_0', - type: 'uint', - inputs: [ - { name: 'x', type: 'int' } - ] -} ); + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { -const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => { + const pingPongRenderTarget = this._pingPongRenderTarget; - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const len = uint( uint( 2 ) ).toVar(); - const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); - a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); - a.addAssign( uint( x ) ); - b.addAssign( uint( y ) ); + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); - return mx_bjfinal( a, b, c ); + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); -} ).setLayout( { - name: 'mx_hash_int_1', - type: 'uint', - inputs: [ - { name: 'x', type: 'int' }, - { name: 'y', type: 'int' } - ] -} ); + } -const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => { + _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const len = uint( uint( 3 ) ).toVar(); - const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); - a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); - a.addAssign( uint( x ) ); - b.addAssign( uint( y ) ); - c.addAssign( uint( z ) ); + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; - return mx_bjfinal( a, b, c ); + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { -} ).setLayout( { - name: 'mx_hash_int_2', - type: 'uint', - inputs: [ - { name: 'x', type: 'int' }, - { name: 'y', type: 'int' }, - { name: 'z', type: 'int' } - ] -} ); + console.error( 'blur direction must be either latitudinal or longitudinal!' ); -const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => { + } - const xx = int( xx_immutable ).toVar(); - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const len = uint( uint( 4 ) ).toVar(); - const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); - a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); - a.addAssign( uint( x ) ); - b.addAssign( uint( y ) ); - c.addAssign( uint( z ) ); - mx_bjmix( a, b, c ); - a.addAssign( uint( xx ) ); + // Number of standard deviations at which to cut off the discrete approximation. + const STANDARD_DEVIATIONS = 3; - return mx_bjfinal( a, b, c ); + const blurMesh = this._lodMeshes[ lodOut ]; + blurMesh.material = blurMaterial; -} ).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' } - ] -} ); + const blurUniforms = blurMaterial.uniforms; -const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => { + const pixels = this._sizeLods[ lodIn ] - 1; + const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; - const yy = int( yy_immutable ).toVar(); - const xx = int( xx_immutable ).toVar(); - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const len = uint( uint( 5 ) ).toVar(); - const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); - a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); - a.addAssign( uint( x ) ); - b.addAssign( uint( y ) ); - c.addAssign( uint( z ) ); - mx_bjmix( a, b, c ); - a.addAssign( uint( xx ) ); - b.addAssign( uint( yy ) ); + if ( samples > MAX_SAMPLES ) { - return mx_bjfinal( a, b, c ); + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); -} ).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' } - ] -} ); + } -const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] ); + const weights = []; + let sum = 0; -const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => { + for ( let i = 0; i < MAX_SAMPLES; ++ i ) { - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const h = uint( mx_hash_int( x, y ) ).toVar(); - const result = uvec3().toVar(); - result.x.assign( h.bitAnd( int( 0xFF ) ) ); - result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) ); - result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) ); + const x = i / sigmaPixels; + const weight = Math.exp( - x * x / 2 ); + weights.push( weight ); - return result; + if ( i === 0 ) { -} ).setLayout( { - name: 'mx_hash_vec3_0', - type: 'uvec3', - inputs: [ - { name: 'x', type: 'int' }, - { name: 'y', type: 'int' } - ] -} ); + sum += weight; -const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => { + } else if ( i < samples ) { - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const h = uint( mx_hash_int( x, y, z ) ).toVar(); - const result = uvec3().toVar(); - result.x.assign( h.bitAnd( int( 0xFF ) ) ); - result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) ); - result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) ); + sum += 2 * weight; - return result; + } -} ).setLayout( { - name: 'mx_hash_vec3_1', - type: 'uvec3', - inputs: [ - { name: 'x', type: 'int' }, - { name: 'y', type: 'int' }, - { name: 'z', type: 'int' } - ] -} ); + } -const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] ); + for ( let i = 0; i < weights.length; i ++ ) { -const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + weights[ i ] = weights[ i ] / sum; - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const fx = float( mx_floorfrac( p.x, X ) ).toVar(); - const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); - const u = float( mx_fade( fx ) ).toVar(); - const v = float( mx_fade( fy ) ).toVar(); - const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar(); + } - return mx_gradient_scale2d( result ); + targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1; -} ).setLayout( { - name: 'mx_perlin_noise_float_0', - type: 'float', - inputs: [ - { name: 'p', type: 'vec2' } - ] -} ); + blurUniforms.envMap.value = targetIn.texture; + blurUniforms.samples.value = samples; + blurUniforms.weights.array = weights; + blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0; -const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + if ( poleAxis ) { - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const fx = float( mx_floorfrac( p.x, X ) ).toVar(); - const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); - const fz = float( mx_floorfrac( p.z, Z ) ).toVar(); - const u = float( mx_fade( fx ) ).toVar(); - const v = float( mx_fade( fy ) ).toVar(); - const w = float( mx_fade( fz ) ).toVar(); - const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar(); + blurUniforms.poleAxis.value = poleAxis; - return mx_gradient_scale3d( result ); + } -} ).setLayout( { - name: 'mx_perlin_noise_float_1', - type: 'float', - inputs: [ - { name: 'p', type: 'vec3' } - ] -} ); + const { _lodMax } = this; + blurUniforms.dTheta.value = radiansPerPixel; + blurUniforms.mipInt.value = _lodMax - lodIn; -const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] ); + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); + + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); + + } + +} + +function _createPlanes( lodMax ) { + + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + const lodMeshes = []; + + let lod = lodMax; + + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + + for ( let i = 0; i < totalLods; i ++ ) { + + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + let sigma = 1.0 / sizeLod; + + if ( i > lodMax - LOD_MIN ) { + + sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; + + } else if ( i === 0 ) { + + sigma = 0; + + } + + sigmas.push( sigma ); + + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const uv = new Float32Array( uvSize * vertices * cubeFaces ); + const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + + for ( let face = 0; face < cubeFaces; face ++ ) { + + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : - 1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + + const faceIdx = _faceLib[ face ]; + position.set( coordinates, positionSize * vertices * faceIdx ); + uv.set( uv1, uvSize * vertices * faceIdx ); + const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ]; + faceIndex.set( fill, faceIndexSize * vertices * faceIdx ); + + } + + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + lodPlanes.push( planes ); + lodMeshes.push( new Mesh( planes, null ) ); + + if ( lod > LOD_MIN ) { + + lod --; + + } + + } + + return { lodPlanes, sizeLods, sigmas, lodMeshes }; + +} + +function _createRenderTarget( width, height, params ) { + + const cubeUVRenderTarget = new RenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.texture.isPMREMTexture = true; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + +} + +function _setViewport( target, x, y, width, height ) { + + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); + +} + +function _getMaterial( type ) { + + const material = new NodeMaterial(); + material.depthTest = false; + material.depthWrite = false; + material.blending = NoBlending; + material.name = `PMREM_${ type }`; + + return material; + +} + +function _getBlurShader( lodMax, width, height ) { + + const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) ); + const poleAxis = uniform( new Vector3( 0, 1, 0 ) ); + const dTheta = uniform( 0 ); + const n = float( MAX_SAMPLES ); + const latitudinal = uniform( 0 ); // false, bool + const samples = uniform( 1 ); // int + const envMap = texture( null ); + const mipInt = uniform( 0 ); // int + const CUBEUV_TEXEL_WIDTH = float( 1 / width ); + const CUBEUV_TEXEL_HEIGHT = float( 1 / height ); + const CUBEUV_MAX_MIP = float( lodMax ); + + const materialUniforms = { + n, + latitudinal, + weights, + poleAxis, + outputDirection, + dTheta, + samples, + envMap, + mipInt, + CUBEUV_TEXEL_WIDTH, + CUBEUV_TEXEL_HEIGHT, + CUBEUV_MAX_MIP + }; + + const material = _getMaterial( 'blur' ); + material.uniforms = materialUniforms; // TODO: Move to outside of the material + material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } ); + + return material; + +} + +function _getCubemapMaterial( envTexture ) { + + const material = _getMaterial( 'cubemap' ); + material.fragmentNode = cubeTexture( envTexture, outputDirection ); + + return material; + +} + +function _getEquirectMaterial( envTexture ) { + + const material = _getMaterial( 'equirect' ); + material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 ); + + return material; + +} + +const rendererCache = new WeakMap(); + +const typeFromLength = new Map( [ + [ 2, 'vec2' ], + [ 3, 'vec3' ], + [ 4, 'vec4' ], + [ 9, 'mat3' ], + [ 16, 'mat4' ] +] ); + +const typeFromArray = new Map( [ + [ Int8Array, 'int' ], + [ Int16Array, 'int' ], + [ Int32Array, 'int' ], + [ Uint8Array, 'uint' ], + [ Uint16Array, 'uint' ], + [ Uint32Array, 'uint' ], + [ Float32Array, 'float' ] +] ); + +const toFloat = ( value ) => { + + if ( /e/g.test( value ) ) { + + return String( value ).replace( /\+/g, '' ); + + } else { + + value = Number( value ); + + return value + ( value % 1 ? '' : '.0' ); + + } + +}; + +class NodeBuilder { + + constructor( object, renderer, parser ) { + + this.object = object; + this.material = ( object && object.material ) || null; + this.geometry = ( object && object.geometry ) || null; + this.renderer = renderer; + this.parser = parser; + this.scene = null; + this.camera = null; + + this.nodes = []; + this.sequentialNodes = []; + this.updateNodes = []; + this.updateBeforeNodes = []; + this.updateAfterNodes = []; + this.hashNodes = {}; + + this.monitor = 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.bindings = { vertex: {}, fragment: {}, compute: {} }; + this.bindingsIndexes = {}; + this.bindGroups = null; + this.attributes = []; + this.bufferAttributes = []; + this.varyings = []; + this.codes = {}; + this.vars = {}; + this.flow = { code: '' }; + this.chaining = []; + this.stack = stack(); + this.stacks = []; + this.tab = '\t'; + + this.currentFunctionNode = null; + + this.context = { + material: this.material + }; + + this.cache = new NodeCache(); + this.globalCache = this.cache; + + this.flowsData = new WeakMap(); + + this.shaderStage = null; + this.buildStage = null; + + this.useComparisonMethod = false; + + } + + getBindGroupsCache() { + + let bindGroupsCache = rendererCache.get( this.renderer ); + + if ( bindGroupsCache === undefined ) { + + bindGroupsCache = new ChainMap(); + + rendererCache.set( this.renderer, bindGroupsCache ); + + } + + return bindGroupsCache; + + } + + createRenderTarget( width, height, options ) { + + return new RenderTarget( width, height, options ); -const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + } - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const fx = float( mx_floorfrac( p.x, X ) ).toVar(); - const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); - const u = float( mx_fade( fx ) ).toVar(); - const v = float( mx_fade( fy ) ).toVar(); - const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar(); + createCubeRenderTarget( size, options ) { - return mx_gradient_scale2d( result ); + return new CubeRenderTarget( size, options ); -} ).setLayout( { - name: 'mx_perlin_noise_vec3_0', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec2' } - ] -} ); + } -const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + createPMREMGenerator() { - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const fx = float( mx_floorfrac( p.x, X ) ).toVar(); - const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); - const fz = float( mx_floorfrac( p.z, Z ) ).toVar(); - const u = float( mx_fade( fx ) ).toVar(); - const v = float( mx_fade( fy ) ).toVar(); - const w = float( mx_fade( fz ) ).toVar(); - const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar(); + // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support - return mx_gradient_scale3d( result ); + return new PMREMGenerator( this.renderer ); -} ).setLayout( { - name: 'mx_perlin_noise_vec3_1', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec3' } - ] -} ); + } -const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] ); + includes( node ) { -const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + return this.nodes.includes( node ); - const p = float( p_immutable ).toVar(); - const ix = int( mx_floor( p ) ).toVar(); + } - return mx_bits_to_01( mx_hash_int( ix ) ); + _getBindGroup( groupName, bindings ) { -} ).setLayout( { - name: 'mx_cell_noise_float_0', - type: 'float', - inputs: [ - { name: 'p', type: 'float' } - ] -} ); + const bindGroupsCache = this.getBindGroupsCache(); -const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + // - const p = vec2( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); + const bindingsArray = []; - return mx_bits_to_01( mx_hash_int( ix, iy ) ); + let sharedGroup = true; -} ).setLayout( { - name: 'mx_cell_noise_float_1', - type: 'float', - inputs: [ - { name: 'p', type: 'vec2' } - ] -} ); + for ( const binding of bindings ) { -const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + bindingsArray.push( binding ); - const p = vec3( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); - const iz = int( mx_floor( p.z ) ).toVar(); + sharedGroup = sharedGroup && binding.groupNode.shared !== true; - return mx_bits_to_01( mx_hash_int( ix, iy, iz ) ); + } -} ).setLayout( { - name: 'mx_cell_noise_float_2', - type: 'float', - inputs: [ - { name: 'p', type: 'vec3' } - ] -} ); + // -const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + let bindGroup; - const p = vec4( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); - const iz = int( mx_floor( p.z ) ).toVar(); - const iw = int( mx_floor( p.w ) ).toVar(); + if ( sharedGroup ) { - return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) ); + bindGroup = bindGroupsCache.get( bindingsArray ); -} ).setLayout( { - name: 'mx_cell_noise_float_3', - type: 'float', - inputs: [ - { name: 'p', type: 'vec4' } - ] -} ); + if ( bindGroup === undefined ) { -const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] ); + bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray ); -const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + bindGroupsCache.set( bindingsArray, bindGroup ); - const p = float( p_immutable ).toVar(); - const ix = int( mx_floor( p ) ).toVar(); + } - return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) ); + } else { -} ).setLayout( { - name: 'mx_cell_noise_vec3_0', - type: 'vec3', - inputs: [ - { name: 'p', type: 'float' } - ] -} ); + bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray ); -const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + } - const p = vec2( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); + return bindGroup; - return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) ); + } -} ).setLayout( { - name: 'mx_cell_noise_vec3_1', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec2' } - ] -} ); + getBindGroupArray( groupName, shaderStage ) { -const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + const bindings = this.bindings[ shaderStage ]; - const p = vec3( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); - const iz = int( mx_floor( p.z ) ).toVar(); + let bindGroup = bindings[ groupName ]; - return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) ); + if ( bindGroup === undefined ) { -} ).setLayout( { - name: 'mx_cell_noise_vec3_2', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec3' } - ] -} ); + if ( this.bindingsIndexes[ groupName ] === undefined ) { -const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length }; - const p = vec4( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); - const iz = int( mx_floor( p.z ) ).toVar(); - const iw = int( mx_floor( p.w ) ).toVar(); + } - return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) ); + bindings[ groupName ] = bindGroup = []; -} ).setLayout( { - name: 'mx_cell_noise_vec3_3', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec4' } - ] -} ); + } -const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] ); + return bindGroup; -const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { + } - const diminish = float( diminish_immutable ).toVar(); - const lacunarity = float( lacunarity_immutable ).toVar(); - const octaves = int( octaves_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const result = float( 0.0 ).toVar(); - const amplitude = float( 1.0 ).toVar(); + getBindings() { - Loop( octaves, () => { + let bindingsGroups = this.bindGroups; - result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) ); - amplitude.mulAssign( diminish ); - p.mulAssign( lacunarity ); + if ( bindingsGroups === null ) { - } ); + const groups = {}; + const bindings = this.bindings; - return result; + for ( const shaderStage of shaderStages ) { -} ).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' } - ] -} ); + for ( const groupName in bindings[ shaderStage ] ) { -const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { + const uniforms = bindings[ shaderStage ][ groupName ]; - const diminish = float( diminish_immutable ).toVar(); - const lacunarity = float( lacunarity_immutable ).toVar(); - const octaves = int( octaves_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const result = vec3( 0.0 ).toVar(); - const amplitude = float( 1.0 ).toVar(); + const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] ); + groupUniforms.push( ...uniforms ); - Loop( octaves, () => { + } - result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) ); - amplitude.mulAssign( diminish ); - p.mulAssign( lacunarity ); + } - } ); + bindingsGroups = []; - return result; + for ( const groupName in groups ) { -} ).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' } - ] -} ); + const group = groups[ groupName ]; -const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { + const bindingsGroup = this._getBindGroup( groupName, group ); - const diminish = float( diminish_immutable ).toVar(); - const lacunarity = float( lacunarity_immutable ).toVar(); - const octaves = int( octaves_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); + bindingsGroups.push( bindingsGroup ); - return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ); + } -} ).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' } - ] -} ); + this.bindGroups = bindingsGroups; -const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { + } - const diminish = float( diminish_immutable ).toVar(); - const lacunarity = float( lacunarity_immutable ).toVar(); - const octaves = int( octaves_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar(); - const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar(); + return bindingsGroups; - return vec4( c, f ); + } -} ).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' } - ] -} ); + sortBindingGroups() { -const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => { + const bindingsGroups = this.getBindings(); - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const yoff = int( yoff_immutable ).toVar(); - const xoff = int( xoff_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const p = vec2( p_immutable ).toVar(); - const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar(); - const off = vec2( tmp.x, tmp.y ).toVar(); - off.subAssign( 0.5 ); - off.mulAssign( jitter ); - off.addAssign( 0.5 ); - const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar(); - const diff = vec2( cellpos.sub( p ) ).toVar(); + bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) ); - If( metric.equal( int( 2 ) ), () => { + for ( let i = 0; i < bindingsGroups.length; i ++ ) { - return abs( diff.x ).add( abs( diff.y ) ); + const bindingGroup = bindingsGroups[ i ]; + this.bindingsIndexes[ bindingGroup.name ].group = i; - } ); + bindingGroup.index = i; - If( metric.equal( int( 3 ) ), () => { + } - return max$1( abs( diff.x ), abs( diff.y ) ); + } - } ); + setHashNode( node, hash ) { - return dot( diff, diff ); + this.hashNodes[ hash ] = node; -} ).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' } - ] -} ); + } -const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => { + addNode( node ) { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const zoff = int( zoff_immutable ).toVar(); - const yoff = int( yoff_immutable ).toVar(); - const xoff = int( xoff_immutable ).toVar(); - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar(); - off.subAssign( 0.5 ); - off.mulAssign( jitter ); - off.addAssign( 0.5 ); - const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar(); - const diff = vec3( cellpos.sub( p ) ).toVar(); + if ( this.nodes.includes( node ) === false ) { - If( metric.equal( int( 2 ) ), () => { + this.nodes.push( node ); - return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) ); + this.setHashNode( node, node.getHash( this ) ); - } ); + } - If( metric.equal( int( 3 ) ), () => { + } - return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) ); + addSequentialNode( node ) { - } ); + if ( this.sequentialNodes.includes( node ) === false ) { - return dot( diff, diff ); + this.sequentialNodes.push( node ); -} ).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' } - ] -} ); + } -const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] ); + } -const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + buildUpdateNodes() { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); - const sqdist = float( 1e6 ).toVar(); + for ( const node of this.nodes ) { - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + const updateType = node.getUpdateType(); - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + if ( updateType !== NodeUpdateType.NONE ) { - const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); - sqdist.assign( min$1( sqdist, dist ) ); + this.updateNodes.push( node.getSelf() ); - } ); + } - } ); + } - If( metric.equal( int( 0 ) ), () => { + for ( const node of this.sequentialNodes ) { - sqdist.assign( sqrt( sqdist ) ); + const updateBeforeType = node.getUpdateBeforeType(); + const updateAfterType = node.getUpdateAfterType(); - } ); + if ( updateBeforeType !== NodeUpdateType.NONE ) { - return sqdist; + this.updateBeforeNodes.push( node.getSelf() ); -} ).setLayout( { - name: 'mx_worley_noise_float_0', - type: 'float', - inputs: [ - { name: 'p', type: 'vec2' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + } -const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + if ( updateAfterType !== NodeUpdateType.NONE ) { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); - const sqdist = vec2( 1e6, 1e6 ).toVar(); + this.updateAfterNodes.push( node.getSelf() ); - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + } - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + } - const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); + } - If( dist.lessThan( sqdist.x ), () => { + get currentNode() { - sqdist.y.assign( sqdist.x ); - sqdist.x.assign( dist ); + return this.chaining[ this.chaining.length - 1 ]; - } ).ElseIf( dist.lessThan( sqdist.y ), () => { + } - sqdist.y.assign( dist ); + isFilteredTexture( texture ) { - } ); + return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || + texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ); - } ); + } - } ); + addChain( node ) { - If( metric.equal( int( 0 ) ), () => { + /* + if ( this.chaining.indexOf( node ) !== - 1 ) { - sqdist.assign( sqrt( sqdist ) ); + console.warn( 'Recursive node: ', node ); - } ); + } + */ - return sqdist; + this.chaining.push( node ); -} ).setLayout( { - name: 'mx_worley_noise_vec2_0', - type: 'vec2', - inputs: [ - { name: 'p', type: 'vec2' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + } -const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + removeChain( node ) { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); - const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar(); + const lastChain = this.chaining.pop(); - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + if ( lastChain !== node ) { - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + throw new Error( 'NodeBuilder: Invalid node chaining!' ); - const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); + } - If( dist.lessThan( sqdist.x ), () => { + } - sqdist.z.assign( sqdist.y ); - sqdist.y.assign( sqdist.x ); - sqdist.x.assign( dist ); + getMethod( method ) { - } ).ElseIf( dist.lessThan( sqdist.y ), () => { + return method; - sqdist.z.assign( sqdist.y ); - sqdist.y.assign( dist ); + } - } ).ElseIf( dist.lessThan( sqdist.z ), () => { + getNodeFromHash( hash ) { - sqdist.z.assign( dist ); + return this.hashNodes[ hash ]; - } ); + } - } ); + addFlow( shaderStage, node ) { - } ); + this.flowNodes[ shaderStage ].push( node ); - If( metric.equal( int( 0 ) ), () => { + return node; - sqdist.assign( sqrt( sqdist ) ); + } - } ); + setContext( context ) { - return sqdist; + this.context = context; -} ).setLayout( { - name: 'mx_worley_noise_vec3_0', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec2' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + } -const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + getContext() { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); - const sqdist = float( 1e6 ).toVar(); + return this.context; - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + } - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + getSharedContext() { - Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { + ({ ...this.context }); - const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); - sqdist.assign( min$1( sqdist, dist ) ); + return this.context; - } ); + } - } ); + setCache( cache ) { - } ); + this.cache = cache; - If( metric.equal( int( 0 ) ), () => { + } - sqdist.assign( sqrt( sqdist ) ); + getCache() { - } ); + return this.cache; - return sqdist; + } -} ).setLayout( { - name: 'mx_worley_noise_float_1', - type: 'float', - inputs: [ - { name: 'p', type: 'vec3' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + getCacheFromNode( node, parent = true ) { -const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] ); + const data = this.getDataFromNode( node ); + if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null ); -const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + return data.cache; - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); - const sqdist = vec2( 1e6, 1e6 ).toVar(); + } - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + isAvailable( /*name*/ ) { - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + return false; - Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { + } - const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); + getVertexIndex() { - If( dist.lessThan( sqdist.x ), () => { + console.warn( 'Abstract function.' ); - sqdist.y.assign( sqdist.x ); - sqdist.x.assign( dist ); + } - } ).ElseIf( dist.lessThan( sqdist.y ), () => { + getInstanceIndex() { - sqdist.y.assign( dist ); + console.warn( 'Abstract function.' ); - } ); + } - } ); + getDrawIndex() { - } ); + console.warn( 'Abstract function.' ); - } ); + } - If( metric.equal( int( 0 ) ), () => { + getFrontFacing() { - sqdist.assign( sqrt( sqdist ) ); + console.warn( 'Abstract function.' ); - } ); + } - return sqdist; + getFragCoord() { -} ).setLayout( { - name: 'mx_worley_noise_vec2_1', - type: 'vec2', - inputs: [ - { name: 'p', type: 'vec3' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + console.warn( 'Abstract function.' ); -const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] ); + } -const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + isFlipY() { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); - const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar(); + return false; - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + } - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + increaseUsage( node ) { - Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { + const nodeData = this.getDataFromNode( node ); + nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1; - const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); + return nodeData.usageCount; - If( dist.lessThan( sqdist.x ), () => { + } - sqdist.z.assign( sqdist.y ); - sqdist.y.assign( sqdist.x ); - sqdist.x.assign( dist ); + generateTexture( /* texture, textureProperty, uvSnippet */ ) { - } ).ElseIf( dist.lessThan( sqdist.y ), () => { + console.warn( 'Abstract function.' ); - sqdist.z.assign( sqdist.y ); - sqdist.y.assign( dist ); + } - } ).ElseIf( dist.lessThan( sqdist.z ), () => { + generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) { - sqdist.z.assign( dist ); + console.warn( 'Abstract function.' ); - } ); + } - } ); + generateConst( type, value = null ) { - } ); + if ( value === null ) { - } ); + if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0; + else if ( type === 'bool' ) value = false; + else if ( type === 'color' ) value = new Color(); + else if ( type === 'vec2' ) value = new Vector2(); + else if ( type === 'vec3' ) value = new Vector3(); + else if ( type === 'vec4' ) value = new Vector4(); - If( metric.equal( int( 0 ) ), () => { + } - sqdist.assign( sqrt( sqdist ) ); + if ( type === 'float' ) return toFloat( value ); + if ( type === 'int' ) return `${ Math.round( value ) }`; + if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u'; + if ( type === 'bool' ) return value ? 'true' : 'false'; + if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`; - } ); + const typeLength = this.getTypeLength( type ); - return sqdist; + const componentType = this.getComponentType( type ); -} ).setLayout( { - name: 'mx_worley_noise_vec3_1', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec3' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + const generateConst = value => this.generateConst( componentType, value ); -const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] ); + if ( typeLength === 2 ) { -// Three.js Transpiler -// https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl + return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`; + } else if ( typeLength === 3 ) { -const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => { + return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`; - const s = hsv.y; - const v = hsv.z; + } else if ( typeLength === 4 ) { - const result = vec3().toVar(); + return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`; - If( s.lessThan( 0.0001 ), () => { + } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) { - result.assign( vec3( v, v, v ) ); + return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`; - } ).Else( () => { + } else if ( typeLength > 4 ) { - let h = hsv.x; - h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache - const hi = int( trunc( h ) ); - const f = h.sub( float( hi ) ); - const p = v.mul( s.oneMinus() ); - const q = v.mul( s.mul( f ).oneMinus() ); - const t = v.mul( s.mul( f.oneMinus() ).oneMinus() ); + return `${ this.getType( type ) }()`; - If( hi.equal( int( 0 ) ), () => { + } - result.assign( vec3( v, t, p ) ); + throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` ); - } ).ElseIf( hi.equal( int( 1 ) ), () => { + } - result.assign( vec3( q, v, p ) ); + getType( type ) { - } ).ElseIf( hi.equal( int( 2 ) ), () => { + if ( type === 'color' ) return 'vec3'; - result.assign( vec3( p, v, t ) ); + return type; - } ).ElseIf( hi.equal( int( 3 ) ), () => { + } - result.assign( vec3( p, q, v ) ); + hasGeometryAttribute( name ) { - } ).ElseIf( hi.equal( int( 4 ) ), () => { + return this.geometry && this.geometry.getAttribute( name ) !== undefined; - result.assign( vec3( t, p, v ) ); + } - } ).Else( () => { + getAttribute( name, type ) { - result.assign( vec3( v, p, q ) ); + const attributes = this.attributes; - } ); + // find attribute - } ); + for ( const attribute of attributes ) { - return result; + if ( attribute.name === name ) { -} ).setLayout( { - name: 'mx_hsvtorgb', - type: 'vec3', - inputs: [ - { name: 'hsv', type: 'vec3' } - ] -} ); + return attribute; -const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => { + } - const c = vec3( c_immutable ).toVar(); - const r = float( c.x ).toVar(); - const g = float( c.y ).toVar(); - const b = float( c.z ).toVar(); - const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar(); - const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar(); - const delta = float( maxcomp.sub( mincomp ) ).toVar(); - const h = float().toVar(), s = float().toVar(), v = float().toVar(); - v.assign( maxcomp ); + } - If( maxcomp.greaterThan( 0.0 ), () => { + // create a new if no exist - s.assign( delta.div( maxcomp ) ); + const attribute = new NodeAttribute( name, type ); - } ).Else( () => { + attributes.push( attribute ); - s.assign( 0.0 ); + return attribute; - } ); + } - If( s.lessThanEqual( 0.0 ), () => { + getPropertyName( node/*, shaderStage*/ ) { - h.assign( 0.0 ); + return node.name; - } ).Else( () => { + } - If( r.greaterThanEqual( maxcomp ), () => { + isVector( type ) { - h.assign( g.sub( b ).div( delta ) ); + return /vec\d/.test( type ); - } ).ElseIf( g.greaterThanEqual( maxcomp ), () => { + } - h.assign( add( 2.0, b.sub( r ).div( delta ) ) ); + isMatrix( type ) { - } ).Else( () => { + return /mat\d/.test( type ); - h.assign( add( 4.0, r.sub( g ).div( delta ) ) ); + } - } ); + isReference( type ) { - h.mulAssign( 1.0 / 6.0 ); + return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D'; - If( h.lessThan( 0.0 ), () => { + } - h.addAssign( 1.0 ); + needsToWorkingColorSpace( /*texture*/ ) { - } ); + return false; - } ); + } - return vec3( h, s, v ); + getComponentTypeFromTexture( texture ) { -} ).setLayout( { - name: 'mx_rgbtohsv', - type: 'vec3', - inputs: [ - { name: 'c', type: 'vec3' } - ] -} ); + const type = texture.type; -// Three.js Transpiler -// https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl + if ( texture.isDataTexture ) { + if ( type === IntType ) return 'int'; + if ( type === UnsignedIntType ) return 'uint'; -const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => { + } - const color = vec3( color_immutable ).toVar(); - const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar(); - const linSeg = vec3( color.div( 12.92 ) ).toVar(); - const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar(); + return 'float'; - return mix( linSeg, powSeg, isAbove ); + } -} ).setLayout( { - name: 'mx_srgb_texture_to_lin_rec709', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' } - ] -} ); + getElementType( type ) { -const mx_aastep = ( threshold, value ) => { + if ( type === 'mat2' ) return 'vec2'; + if ( type === 'mat3' ) return 'vec3'; + if ( type === 'mat4' ) return 'vec4'; - threshold = float( threshold ); - value = float( value ); + return this.getComponentType( type ); - const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 ); + } - return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value ); + getComponentType( type ) { -}; + type = this.getVectorType( type ); -const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() ); -const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' ); -const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' ); + if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type; -const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) ); -const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' ); -const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' ); + const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type ); -const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset ); + if ( componentType === null ) return null; -const mx_safepower = ( in1, in2 = 1 ) => { + if ( componentType[ 1 ] === 'b' ) return 'bool'; + if ( componentType[ 1 ] === 'i' ) return 'int'; + if ( componentType[ 1 ] === 'u' ) return 'uint'; - in1 = float( in1 ); + return 'float'; - return in1.abs().pow( in2 ).mul( in1.sign() ); + } -}; + getVectorType( type ) { -const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot ); + if ( type === 'color' ) return 'vec3'; + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4'; -const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -//export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => { + return type; - texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type + } - const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) ); + getTypeFromLength( length, componentType = 'float' ) { - return noise_vec4.mul( amplitude ).add( pivot ); + if ( length === 1 ) return componentType; -}; + const baseType = typeFromLength.get( length ); + const prefix = componentType === 'float' ? '' : componentType[ 0 ]; -const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); + return prefix + baseType; -const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) ); + } -const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); + getTypeFromArray( array ) { -const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => { + return typeFromArray.get( array.constructor ); - // normal is assumed to have unit length + } - const x = normal.x, y = normal.y, z = normal.z; + getTypeFromAttribute( attribute ) { - // band 0 - let result = shCoefficients.element( 0 ).mul( 0.886227 ); + let dataAttribute = attribute; - // band 1 - result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) ); - result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) ); - result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) ); + if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data; - // band 2 - result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) ); - result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) ); - result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) ); - result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) ); - result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) ); + const array = dataAttribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; - return result; + let arrayType; -} ); + if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) { -class PointLightNode extends AnalyticLightNode { + arrayType = this.getTypeFromArray( array ); - static get type() { + } - return 'PointLightNode'; + return this.getTypeFromLength( itemSize, arrayType ); } - constructor( light = null ) { + getTypeLength( type ) { - super( light ); + const vecType = this.getVectorType( type ); + const vecNum = /vec([2-4])/.exec( vecType ); - this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup ); - this.decayExponentNode = uniform( 0 ).setGroup( renderGroup ); + if ( vecNum !== null ) return Number( vecNum[ 1 ] ); + if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1; + if ( /mat2/.test( type ) === true ) return 4; + if ( /mat3/.test( type ) === true ) return 9; + if ( /mat4/.test( type ) === true ) return 16; + + return 0; } - update( frame ) { + getVectorFromMatrix( type ) { - const { light } = this; + return type.replace( 'mat', 'vec' ); - super.update( frame ); + } - this.cutoffDistanceNode.value = light.distance; - this.decayExponentNode.value = light.decay; + changeComponentType( type, newComponentType ) { + + return this.getTypeFromLength( this.getTypeLength( type ), newComponentType ); } - setup( builder ) { + getIntegerType( type ) { - const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this; + const componentType = this.getComponentType( type ); - const lightingModel = builder.context.lightingModel; + if ( componentType === 'int' || componentType === 'uint' ) return type; - const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode + return this.changeComponentType( type, 'int' ); - const lightDirection = lVector.normalize(); - const lightDistance = lVector.length(); + } - const lightAttenuation = getDistanceAttenuation( { - lightDistance, - cutoffDistance: cutoffDistanceNode, - decayExponent: decayExponentNode - } ); + addStack() { - const lightColor = colorNode.mul( lightAttenuation ); + this.stack = stack( this.stack ); - const reflectedLight = builder.context.reflectedLight; + this.stacks.push( getCurrentStack() || this.stack ); + setCurrentStack( this.stack ); - lightingModel.direct( { - lightDirection, - lightColor, - reflectedLight - }, builder.stack, builder ); + return this.stack; } -} + removeStack() { -class DirectionalLightNode extends AnalyticLightNode { + const lastStack = this.stack; + this.stack = lastStack.parent; - static get type() { + setCurrentStack( this.stacks.pop() ); - return 'DirectionalLightNode'; + return lastStack; } - constructor( light = null ) { + getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) { - super( light ); + cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache; - } + let nodeData = cache.getData( node ); - setup( builder ) { + if ( nodeData === undefined ) { - super.setup( builder ); + nodeData = {}; - const lightingModel = builder.context.lightingModel; + cache.setData( node, nodeData ); - const lightColor = this.colorNode; - const lightDirection = lightTargetDirection( this.light ); - const reflectedLight = builder.context.reflectedLight; + } - lightingModel.direct( { - lightDirection, - lightColor, - reflectedLight - }, builder.stack, builder ); + if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {}; + + return nodeData[ shaderStage ]; + + } + + getNodeProperties( node, shaderStage = 'any' ) { + + const nodeData = this.getDataFromNode( node, shaderStage ); + + return nodeData.properties || ( nodeData.properties = { outputNode: null } ); } -} + getBufferAttributeFromNode( node, type ) { -const _matrix41 = /*@__PURE__*/ new Matrix4(); -const _matrix42 = /*@__PURE__*/ new Matrix4(); + const nodeData = this.getDataFromNode( node ); -let ltcLib = null; + let bufferAttribute = nodeData.bufferAttribute; -class RectAreaLightNode extends AnalyticLightNode { + if ( bufferAttribute === undefined ) { - static get type() { + const index = this.uniforms.index ++; - return 'RectAreaLightNode'; + bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node ); - } + this.bufferAttributes.push( bufferAttribute ); - constructor( light = null ) { + nodeData.bufferAttribute = bufferAttribute; - super( light ); + } - this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup ); - this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup ); + return bufferAttribute; } - update( frame ) { + getStructTypeFromNode( node, shaderStage = this.shaderStage ) { - super.update( frame ); + const nodeData = this.getDataFromNode( node, shaderStage ); - const { light } = this; + if ( nodeData.structType === undefined ) { - const viewMatrix = frame.camera.matrixWorldInverse; + const index = this.structs.index ++; - _matrix42.identity(); - _matrix41.copy( light.matrixWorld ); - _matrix41.premultiply( viewMatrix ); - _matrix42.extractRotation( _matrix41 ); + node.name = `StructType${ index }`; + this.structs[ shaderStage ].push( node ); - this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 ); - this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 ); + nodeData.structType = node; - this.halfWidth.value.applyMatrix4( _matrix42 ); - this.halfHeight.value.applyMatrix4( _matrix42 ); + } - } + return node; - setup( builder ) { + } - super.setup( builder ); + getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) { - let ltc_1, ltc_2; + const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache ); - if ( builder.isAvailable( 'float32Filterable' ) ) { + let nodeUniform = nodeData.uniform; - ltc_1 = texture( ltcLib.LTC_FLOAT_1 ); - ltc_2 = texture( ltcLib.LTC_FLOAT_2 ); + if ( nodeUniform === undefined ) { - } else { + const index = this.uniforms.index ++; - ltc_1 = texture( ltcLib.LTC_HALF_1 ); - ltc_2 = texture( ltcLib.LTC_HALF_2 ); + nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node ); - } + this.uniforms[ shaderStage ].push( nodeUniform ); - const { colorNode, light } = this; - const lightingModel = builder.context.lightingModel; + nodeData.uniform = nodeUniform; - const lightPosition = lightViewPosition( light ); - const reflectedLight = builder.context.reflectedLight; + } - lightingModel.directRectArea( { - lightColor: colorNode, - lightPosition, - halfWidth: this.halfWidth, - halfHeight: this.halfHeight, - reflectedLight, - ltc_1, - ltc_2 - }, builder.stack, builder ); + return nodeUniform; } - static setLTC( ltc ) { - - ltcLib = ltc; + getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) { - } + const nodeData = this.getDataFromNode( node, shaderStage ); -} + let nodeVar = nodeData.variable; -class SpotLightNode extends AnalyticLightNode { + if ( nodeVar === undefined ) { - static get type() { + const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] ); - return 'SpotLightNode'; + if ( name === null ) name = 'nodeVar' + vars.length; - } + nodeVar = new NodeVar( name, type ); - constructor( light = null ) { + vars.push( nodeVar ); - super( light ); + nodeData.variable = nodeVar; - this.coneCosNode = uniform( 0 ).setGroup( renderGroup ); - this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup ); + } - this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup ); - this.decayExponentNode = uniform( 0 ).setGroup( renderGroup ); + return nodeVar; } - update( frame ) { + getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) { - super.update( frame ); + const nodeData = this.getDataFromNode( node, 'any' ); - const { light } = this; + let nodeVarying = nodeData.varying; - this.coneCosNode.value = Math.cos( light.angle ); - this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) ); + if ( nodeVarying === undefined ) { - this.cutoffDistanceNode.value = light.distance; - this.decayExponentNode.value = light.decay; + const varyings = this.varyings; + const index = varyings.length; - } + if ( name === null ) name = 'nodeVarying' + index; - getSpotAttenuation( angleCosine ) { + nodeVarying = new NodeVarying( name, type ); - const { coneCosNode, penumbraCosNode } = this; + varyings.push( nodeVarying ); - return smoothstep( coneCosNode, penumbraCosNode, angleCosine ); + nodeData.varying = nodeVarying; - } + } - setup( builder ) { + return nodeVarying; - super.setup( builder ); + } - const lightingModel = builder.context.lightingModel; + getCodeFromNode( node, type, shaderStage = this.shaderStage ) { - const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this; + const nodeData = this.getDataFromNode( node ); - const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode + let nodeCode = nodeData.code; - const lightDirection = lVector.normalize(); - const angleCos = lightDirection.dot( lightTargetDirection( light ) ); - const spotAttenuation = this.getSpotAttenuation( angleCos ); + if ( nodeCode === undefined ) { - const lightDistance = lVector.length(); + const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] ); + const index = codes.length; - const lightAttenuation = getDistanceAttenuation( { - lightDistance, - cutoffDistance: cutoffDistanceNode, - decayExponent: decayExponentNode - } ); + nodeCode = new NodeCode( 'nodeCode' + index, type ); - const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation ); + codes.push( nodeCode ); - const reflectedLight = builder.context.reflectedLight; + nodeData.code = nodeCode; - lightingModel.direct( { - lightDirection, - lightColor, - reflectedLight - }, builder.stack, builder ); + } + + return nodeCode; } -} + addFlowCodeHierarchy( node, nodeBlock ) { -class IESSpotLightNode extends SpotLightNode { + const { flowCodes, flowCodeBlock } = this.getDataFromNode( node ); - static get type() { + let needsFlowCode = true; + let nodeBlockHierarchy = nodeBlock; - return 'IESSpotLightNode'; + while ( nodeBlockHierarchy ) { - } + if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) { - getSpotAttenuation( angleCosine ) { + needsFlowCode = false; + break; - const iesMap = this.light.iesMap; + } - let spotAttenuation = null; + nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock; - if ( iesMap && iesMap.isTexture === true ) { + } - const angle = angleCosine.acos().mul( 1.0 / Math.PI ); + if ( needsFlowCode ) { - spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r; + for ( const flowCode of flowCodes ) { - } else { + this.addLineFlowCode( flowCode ); - spotAttenuation = super.getSpotAttenuation( angleCosine ); + } } - return spotAttenuation; - } -} - -class AmbientLightNode extends AnalyticLightNode { + addLineFlowCodeBlock( node, code, nodeBlock ) { - static get type() { + const nodeData = this.getDataFromNode( node ); + const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] ); + const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() ); - return 'AmbientLightNode'; + flowCodes.push( code ); + codeBlock.set( nodeBlock, true ); } - constructor( light = null ) { + addLineFlowCode( code, node = null ) { - super( light ); + if ( code === '' ) return this; - } + if ( node !== null && this.context.nodeBlock ) { - setup( { context } ) { + this.addLineFlowCodeBlock( node, code, this.context.nodeBlock ); - context.irradiance.addAssign( this.colorNode ); + } - } + code = this.tab + code; -} + if ( ! /;\s*$/.test( code ) ) { -class HemisphereLightNode extends AnalyticLightNode { + code = code + ';\n'; - static get type() { + } - return 'HemisphereLightNode'; + this.flow.code += code; - } + return this; - constructor( light = null ) { + } - super( light ); + addFlowCode( code ) { - this.lightPositionNode = lightPosition( light ); - this.lightDirectionNode = this.lightPositionNode.normalize(); + this.flow.code += code; - this.groundColorNode = uniform( new Color() ).setGroup( renderGroup ); + return this; } - update( frame ) { - - const { light } = this; - - super.update( frame ); + addFlowTab() { - this.lightPositionNode.object3d = light; + this.tab += '\t'; - this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity ); + return this; } - setup( builder ) { + removeFlowTab() { - const { colorNode, groundColorNode, lightDirectionNode } = this; + this.tab = this.tab.slice( 0, - 1 ); - const dotNL = normalView.dot( lightDirectionNode ); - const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 ); + return this; - const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight ); + } - builder.context.irradiance.addAssign( irradiance ); + getFlowData( node/*, shaderStage*/ ) { + + return this.flowsData.get( node ); } -} + flowNode( node ) { -class LightProbeNode extends AnalyticLightNode { + const output = node.getNodeType( this ); - static get type() { + const flowData = this.flowChildNode( node, output ); - return 'LightProbeNode'; + this.flowsData.set( node, flowData ); + + return flowData; } - constructor( light = null ) { + buildFunctionNode( shaderNode ) { - super( light ); + const fn = new FunctionNode(); - const array = []; + const previous = this.currentFunctionNode; - for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() ); + this.currentFunctionNode = fn; - this.lightProbe = uniformArray( array ); + fn.code = this.buildFunctionCode( shaderNode ); + + this.currentFunctionNode = previous; + + return fn; } - update( frame ) { + flowShaderNode( shaderNode ) { - const { light } = this; + const layout = shaderNode.layout; - super.update( frame ); + const inputs = { + [ Symbol.iterator ]() { - // + let index = 0; + const values = Object.values( this ); + return { + next: () => ( { + value: values[ index ], + done: index ++ >= values.length + } ) + }; - for ( let i = 0; i < 9; i ++ ) { + } + }; - this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity ); + for ( const input of layout.inputs ) { + + inputs[ input.name ] = new ParameterNode( input.type, input.name ); } - } + // - setup( builder ) { + shaderNode.layout = null; - const irradiance = getShIrradianceAt( normalWorld, this.lightProbe ); + const callNode = shaderNode.call( inputs ); + const flowData = this.flowStagesNode( callNode, layout.type ); - builder.context.irradiance.addAssign( irradiance ); + shaderNode.layout = layout; + + return flowData; } -} + flowStagesNode( node, output = null ) { -class NodeParser { + const previousFlow = this.flow; + const previousVars = this.vars; + const previousCache = this.cache; + const previousBuildStage = this.buildStage; + const previousStack = this.stack; - parseFunction( /*source*/ ) { + const flow = { + code: '' + }; - console.warn( 'Abstract function.' ); + this.flow = flow; + this.vars = {}; + this.cache = new NodeCache(); + this.stack = stack(); - } + for ( const buildStage of defaultBuildStages ) { -} + this.setBuildStage( buildStage ); -class NodeFunction { + flow.result = node.build( this, output ); - constructor( type, inputs, name = '', precision = '' ) { + } - this.type = type; - this.inputs = inputs; - this.name = name; - this.precision = precision; + flow.vars = this.getVars( this.shaderStage ); - } + this.flow = previousFlow; + this.vars = previousVars; + this.cache = previousCache; + this.stack = previousStack; - getCode( /*name = this.name*/ ) { + this.setBuildStage( previousBuildStage ); - console.warn( 'Abstract function.' ); + return flow; } -} + getFunctionOperator() { -NodeFunction.isNodeFunction = true; + return null; -const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i; -const propertiesRegexp$1 = /[a-z_0-9]+/ig; + } -const pragmaMain = '#pragma main'; + flowChildNode( node, output = null ) { -const parse$1 = ( source ) => { + const previousFlow = this.flow; - source = source.trim(); + const flow = { + code: '' + }; - const pragmaMainIndex = source.indexOf( pragmaMain ); + this.flow = flow; - const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source; + flow.result = node.build( this, output ); - const declaration = mainCode.match( declarationRegexp$1 ); + this.flow = previousFlow; - if ( declaration !== null && declaration.length === 5 ) { + return flow; - // tokenizer + } - const inputsCode = declaration[ 4 ]; - const propsMatches = []; + flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) { - let nameMatch = null; + const previousShaderStage = this.shaderStage; - while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) { + this.setShaderStage( shaderStage ); - propsMatches.push( nameMatch ); + const flowData = this.flowChildNode( node, output ); + + if ( propertyName !== null ) { + + flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`; } - // parser + this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code; - const inputs = []; + this.setShaderStage( previousShaderStage ); - let i = 0; + return flowData; - while ( i < propsMatches.length ) { + } - const isConst = propsMatches[ i ][ 0 ] === 'const'; + getAttributesArray() { - if ( isConst === true ) { + return this.attributes.concat( this.bufferAttributes ); - i ++; + } - } + getAttributes( /*shaderStage*/ ) { - let qualifier = propsMatches[ i ][ 0 ]; + console.warn( 'Abstract function.' ); - if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) { + } - i ++; + getVaryings( /*shaderStage*/ ) { - } else { + console.warn( 'Abstract function.' ); - qualifier = ''; + } - } + getVar( type, name ) { - const type = propsMatches[ i ++ ][ 0 ]; + return `${ this.getType( type ) } ${ name }`; - let count = Number.parseInt( propsMatches[ i ][ 0 ] ); + } - if ( Number.isNaN( count ) === false ) i ++; - else count = null; + getVars( shaderStage ) { - const name = propsMatches[ i ++ ][ 0 ]; + let snippet = ''; - inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) ); + const vars = this.vars[ shaderStage ]; - } + if ( vars !== undefined ) { - // + for ( const variable of vars ) { - const blockCode = mainCode.substring( declaration[ 0 ].length ); + snippet += `${ this.getVar( variable.type, variable.name ) }; `; - const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : ''; - const type = declaration[ 2 ]; + } - const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : ''; + } - const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : ''; + return snippet; - return { - type, - inputs, - name, - precision, - inputsCode, - blockCode, - headerCode - }; + } - } else { + getUniforms( /*shaderStage*/ ) { - throw new Error( 'FunctionNode: Function is not a GLSL code.' ); + console.warn( 'Abstract function.' ); } -}; - -class GLSLNodeFunction extends NodeFunction { + getCodes( shaderStage ) { - constructor( source ) { + const codes = this.codes[ shaderStage ]; - const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source ); + let code = ''; - super( type, inputs, name, precision ); + if ( codes !== undefined ) { - this.inputsCode = inputsCode; - this.blockCode = blockCode; - this.headerCode = headerCode; + for ( const nodeCode of codes ) { - } + code += nodeCode.code + '\n'; - getCode( name = this.name ) { + } - let code; + } - const blockCode = this.blockCode; + return code; - if ( blockCode !== '' ) { + } - const { type, inputsCode, headerCode, precision } = this; + getHash() { - let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`; + return this.vertexShader + this.fragmentShader + this.computeShader; - if ( precision !== '' ) { + } - declarationCode = `${ precision } ${ declarationCode }`; + setShaderStage( shaderStage ) { - } + this.shaderStage = shaderStage; - code = headerCode + declarationCode + blockCode; + } - } else { + getShaderStage() { - // interface function + return this.shaderStage; - code = ''; + } - } + setBuildStage( buildStage ) { - return code; + this.buildStage = buildStage; } -} + getBuildStage() { + + return this.buildStage; -class GLSLNodeParser extends NodeParser { + } - parseFunction( source ) { + buildCode() { - return new GLSLNodeFunction( source ); + console.warn( 'Abstract function.' ); } -} + build() { -function painterSortStable( a, b ) { + const { object, material, renderer } = this; - if ( a.groupOrder !== b.groupOrder ) { + if ( material !== null ) { - return a.groupOrder - b.groupOrder; + let nodeMaterial = renderer.library.fromMaterial( material ); - } else if ( a.renderOrder !== b.renderOrder ) { + if ( nodeMaterial === null ) { - return a.renderOrder - b.renderOrder; + console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` ); - } else if ( a.material.id !== b.material.id ) { + nodeMaterial = new NodeMaterial(); - return a.material.id - b.material.id; + } - } else if ( a.z !== b.z ) { + nodeMaterial.build( this ); - return a.z - b.z; + } else { - } else { + this.addFlow( 'compute', object ); - return a.id - b.id; + } - } + // setup() -> stage 1: create possible new nodes and returns an output reference node + // analyze() -> stage 2: analyze nodes to possible optimization and validation + // generate() -> stage 3: generate shader -} + for ( const buildStage of defaultBuildStages ) { -function reversePainterSortStable( a, b ) { + this.setBuildStage( buildStage ); - if ( a.groupOrder !== b.groupOrder ) { + if ( this.context.vertex && this.context.vertex.isNode ) { - return a.groupOrder - b.groupOrder; + this.flowNodeFromShaderStage( 'vertex', this.context.vertex ); - } else if ( a.renderOrder !== b.renderOrder ) { + } - return a.renderOrder - b.renderOrder; + for ( const shaderStage of shaderStages ) { - } else if ( a.z !== b.z ) { + this.setShaderStage( shaderStage ); - return b.z - a.z; + const flowNodes = this.flowNodes[ shaderStage ]; - } else { + for ( const node of flowNodes ) { - return a.id - b.id; + if ( buildStage === 'generate' ) { - } + this.flowNode( node ); -} + } else { -class RenderList { + node.build( this ); - constructor() { + } - this.renderItems = []; - this.renderItemsIndex = 0; + } - this.opaque = []; - this.transparent = []; - this.bundles = []; + } - this.lightsNode = new LightsNode( [] ); - this.lightsArray = []; + } - this.occlusionQueryCount = 0; + this.setBuildStage( null ); + this.setShaderStage( null ); - } + // stage 4: build code for a specific output - begin() { + this.buildCode(); + this.buildUpdateNodes(); - this.renderItemsIndex = 0; + return this; - this.opaque.length = 0; - this.transparent.length = 0; - this.bundles.length = 0; + } - this.lightsArray.length = 0; + getNodeUniform( uniformNode, type ) { - this.occlusionQueryCount = 0; + if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode ); + if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode ); + if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode ); + if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode ); + if ( type === 'color' ) return new ColorNodeUniform( uniformNode ); + if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode ); + if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode ); - return this; + throw new Error( `Uniform "${type}" not declared.` ); } - getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168 - let renderItem = this.renderItems[ this.renderItemsIndex ]; + throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` ); - if ( renderItem === undefined ) { + } - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - groupOrder: groupOrder, - renderOrder: object.renderOrder, - z: z, - group: group - }; + format( snippet, fromType, toType ) { - this.renderItems[ this.renderItemsIndex ] = renderItem; + fromType = this.getVectorType( fromType ); + toType = this.getVectorType( toType ); - } else { + if ( fromType === toType || toType === null || this.isReference( toType ) ) { - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.groupOrder = groupOrder; - renderItem.renderOrder = object.renderOrder; - renderItem.z = z; - renderItem.group = group; + return snippet; } - this.renderItemsIndex ++; - - return renderItem; - - } + const fromTypeLength = this.getTypeLength( fromType ); + const toTypeLength = this.getTypeLength( toType ); - push( object, geometry, material, groupOrder, z, group ) { + if ( fromTypeLength === 16 && toTypeLength === 9 ) { - const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group ); + return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`; - if ( object.occlusionTest === true ) this.occlusionQueryCount ++; + } - ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem ); + if ( fromTypeLength === 9 && toTypeLength === 4 ) { - } + return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`; - unshift( object, geometry, material, groupOrder, z, group ) { + } - const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group ); - ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem ); + if ( fromTypeLength > 4 ) { // fromType is matrix-like - } + // @TODO: ignore for now - pushBundle( group ) { + return snippet; - this.bundles.push( group ); + } - } + if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown - pushLight( light ) { + // @TODO: ignore for now - this.lightsArray.push( light ); + return snippet; - } + } - sort( customOpaqueSort, customTransparentSort ) { + if ( fromTypeLength === toTypeLength ) { - if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable ); - if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable ); + return `${ this.getType( toType ) }( ${ snippet } )`; - } + } - finish() { + if ( fromTypeLength > toTypeLength ) { - // update lights + return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType ); - this.lightsNode.setLights( this.lightsArray ); + } - // Clear references from inactive renderItems in the list + if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like - for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) { + return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`; - const renderItem = this.renderItems[ i ]; + } - if ( renderItem.id === null ) break; + if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like - renderItem.id = null; - renderItem.object = null; - renderItem.geometry = null; - renderItem.material = null; - renderItem.groupOrder = null; - renderItem.renderOrder = null; - renderItem.z = null; - renderItem.group = null; + return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`; } - } + if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like -} + // convert a number value to vector type, e.g: + // vec3( 1u ) -> vec3( float( 1u ) ) -class RenderLists { + snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`; - constructor() { + } - this.lists = new ChainMap(); + return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like } - get( scene, camera ) { + getSignature() { - const lists = this.lists; - const keys = [ scene, camera ]; + return `// Three.js r${ REVISION } - Node System\n`; - let list = lists.get( keys ); + } - if ( list === undefined ) { +} - list = new RenderList(); - lists.set( keys, list ); +class NodeFrame { - } + constructor() { - return list; + this.time = 0; + this.deltaTime = 0; - } + this.frameId = 0; + this.renderId = 0; - dispose() { + this.startTime = null; - this.lists = new ChainMap(); + 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( referenceMap, nodeRef ) { -let id = 0; + let maps = referenceMap.get( nodeRef ); -class RenderContext { + if ( maps === undefined ) { - constructor() { + maps = { + renderMap: new WeakMap(), + frameMap: new WeakMap() + }; - this.id = id ++; + referenceMap.set( nodeRef, maps ); - this.color = true; - this.clearColor = true; - this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 }; + } - this.depth = true; - this.clearDepth = true; - this.clearDepthValue = 1; + return maps; - this.stencil = false; - this.clearStencil = true; - this.clearStencilValue = 1; + } - this.viewport = false; - this.viewportValue = new Vector4(); + updateBeforeNode( node ) { - this.scissor = false; - this.scissorValue = new Vector4(); + const updateType = node.getUpdateBeforeType(); + const reference = node.updateReference( this ); - this.textures = null; - this.depthTexture = null; - this.activeCubeFace = 0; - this.sampleCount = 1; + if ( updateType === NodeUpdateType.FRAME ) { - this.width = 0; - this.height = 0; + const { frameMap } = this._getMaps( this.updateBeforeMap, reference ); - this.isRenderContext = true; + if ( frameMap.get( reference ) !== this.frameId ) { - } + if ( node.updateBefore( this ) !== false ) { - getCacheKey() { + frameMap.set( reference, this.frameId ); - return getCacheKey( this ); + } - } + } -} + } else if ( updateType === NodeUpdateType.RENDER ) { -function getCacheKey( renderContext ) { + const { renderMap } = this._getMaps( this.updateBeforeMap, reference ); - const { textures, activeCubeFace } = renderContext; + if ( renderMap.get( reference ) !== this.renderId ) { - const values = [ activeCubeFace ]; + if ( node.updateBefore( this ) !== false ) { - for ( const texture of textures ) { + renderMap.set( reference, this.renderId ); - values.push( texture.id ); + } - } + } - return hashArray( values ); + } else if ( updateType === NodeUpdateType.OBJECT ) { -} + node.updateBefore( this ); -class RenderContexts { + } - constructor() { + } - this.chainMaps = {}; + updateAfterNode( node ) { - } + const updateType = node.getUpdateAfterType(); + const reference = node.updateReference( this ); - get( scene, camera, renderTarget = null ) { + if ( updateType === NodeUpdateType.FRAME ) { - const chainKey = [ scene, camera ]; + const { frameMap } = this._getMaps( this.updateAfterMap, reference ); - let attachmentState; + if ( frameMap.get( reference ) !== this.frameId ) { - if ( renderTarget === null ) { + if ( node.updateAfter( this ) !== false ) { - attachmentState = 'default'; + frameMap.set( reference, this.frameId ); - } else { + } - const format = renderTarget.texture.format; - const count = renderTarget.textures.length; + } - attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`; + } else if ( updateType === NodeUpdateType.RENDER ) { - } + const { renderMap } = this._getMaps( this.updateAfterMap, reference ); - const chainMap = this.getChainMap( attachmentState ); + if ( renderMap.get( reference ) !== this.renderId ) { - let renderState = chainMap.get( chainKey ); + if ( node.updateAfter( this ) !== false ) { - if ( renderState === undefined ) { + renderMap.set( reference, this.renderId ); - renderState = new RenderContext(); + } - chainMap.set( chainKey, renderState ); + } - } + } else if ( updateType === NodeUpdateType.OBJECT ) { - if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; + node.updateAfter( this ); - return renderState; + } } - getChainMap( attachmentState ) { + updateNode( node ) { - return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() ); + const updateType = node.getUpdateType(); + const reference = node.updateReference( this ); - } + if ( updateType === NodeUpdateType.FRAME ) { - dispose() { + const { frameMap } = this._getMaps( this.updateMap, reference ); - this.chainMaps = {}; + if ( frameMap.get( reference ) !== this.frameId ) { - } + if ( node.update( this ) !== false ) { -} + frameMap.set( reference, this.frameId ); -const _size = /*@__PURE__*/ new Vector3(); + } -class Textures extends DataMap { + } - constructor( renderer, backend, info ) { + } else if ( updateType === NodeUpdateType.RENDER ) { - super(); + const { renderMap } = this._getMaps( this.updateMap, reference ); - this.renderer = renderer; - this.backend = backend; - this.info = info; + if ( renderMap.get( reference ) !== this.renderId ) { - } + if ( node.update( this ) !== false ) { - updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) { + renderMap.set( reference, this.renderId ); - const renderTargetData = this.get( renderTarget ); + } - const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; - const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} ); + } - const textures = renderTarget.textures; + } else if ( updateType === NodeUpdateType.OBJECT ) { - const size = this.getSize( textures[ 0 ] ); + node.update( this ); - const mipWidth = size.width >> activeMipmapLevel; - const mipHeight = size.height >> activeMipmapLevel; + } - let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ]; - const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true; + } - let textureNeedsUpdate = false; + update() { - if ( depthTexture === undefined && useDepthTexture ) { + this.frameId ++; - depthTexture = new DepthTexture(); - depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat; - depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType - depthTexture.image.width = mipWidth; - depthTexture.image.height = mipHeight; + if ( this.lastTime === undefined ) this.lastTime = performance.now(); - depthTextureMips[ activeMipmapLevel ] = depthTexture; + this.deltaTime = ( performance.now() - this.lastTime ) / 1000; - } + this.lastTime = performance.now(); - if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) { + this.time += this.deltaTime; - textureNeedsUpdate = true; + } - if ( depthTexture ) { +} - depthTexture.needsUpdate = true; - depthTexture.image.width = mipWidth; - depthTexture.image.height = mipHeight; +class NodeFunctionInput { - } + constructor( type, name, count = null, qualifier = '', isConst = false ) { - } + this.type = type; + this.name = name; + this.count = count; + this.qualifier = qualifier; + this.isConst = isConst; - renderTargetData.width = size.width; - renderTargetData.height = size.height; - renderTargetData.textures = textures; - renderTargetData.depthTexture = depthTexture || null; - renderTargetData.depth = renderTarget.depthBuffer; - renderTargetData.stencil = renderTarget.stencilBuffer; - renderTargetData.renderTarget = renderTarget; + } - if ( renderTargetData.sampleCount !== sampleCount ) { +} - textureNeedsUpdate = true; +NodeFunctionInput.isNodeFunctionInput = true; - if ( depthTexture ) { +class DirectionalLightNode extends AnalyticLightNode { - depthTexture.needsUpdate = true; + static get type() { - } + return 'DirectionalLightNode'; - renderTargetData.sampleCount = sampleCount; + } - } + constructor( light = null ) { - // + super( light ); - const options = { sampleCount }; + } - for ( let i = 0; i < textures.length; i ++ ) { + setup( builder ) { - const texture = textures[ i ]; + super.setup( builder ); - if ( textureNeedsUpdate ) texture.needsUpdate = true; + const lightingModel = builder.context.lightingModel; - this.updateTexture( texture, options ); + const lightColor = this.colorNode; + const lightDirection = lightTargetDirection( this.light ); + const reflectedLight = builder.context.reflectedLight; - } + lightingModel.direct( { + lightDirection, + lightColor, + reflectedLight + }, builder.stack, builder ); - if ( depthTexture ) { + } - this.updateTexture( depthTexture, options ); +} - } +const _matrix41 = /*@__PURE__*/ new Matrix4(); +const _matrix42 = /*@__PURE__*/ new Matrix4(); - // dispose handler +let ltcLib = null; - if ( renderTargetData.initialized !== true ) { +class RectAreaLightNode extends AnalyticLightNode { - renderTargetData.initialized = true; + static get type() { - // dispose + return 'RectAreaLightNode'; - const onDispose = () => { + } - renderTarget.removeEventListener( 'dispose', onDispose ); + constructor( light = null ) { - for ( let i = 0; i < textures.length; i ++ ) { + super( light ); - this._destroyTexture( textures[ i ] ); + this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup ); + this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup ); - } + } - if ( depthTexture ) { + update( frame ) { - this._destroyTexture( depthTexture ); + super.update( frame ); - } + const { light } = this; - this.delete( renderTarget ); + const viewMatrix = frame.camera.matrixWorldInverse; - }; + _matrix42.identity(); + _matrix41.copy( light.matrixWorld ); + _matrix41.premultiply( viewMatrix ); + _matrix42.extractRotation( _matrix41 ); - renderTarget.addEventListener( 'dispose', onDispose ); + this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 ); + this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 ); - } + this.halfWidth.value.applyMatrix4( _matrix42 ); + this.halfHeight.value.applyMatrix4( _matrix42 ); } - updateTexture( texture, options = {} ) { + setup( builder ) { + + super.setup( builder ); - const textureData = this.get( texture ); - if ( textureData.initialized === true && textureData.version === texture.version ) return; + let ltc_1, ltc_2; - const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture; - const backend = this.backend; + if ( builder.isAvailable( 'float32Filterable' ) ) { - if ( isRenderTarget && textureData.initialized === true ) { + ltc_1 = texture( ltcLib.LTC_FLOAT_1 ); + ltc_2 = texture( ltcLib.LTC_FLOAT_2 ); - // it's an update + } else { - backend.destroySampler( texture ); - backend.destroyTexture( texture ); + ltc_1 = texture( ltcLib.LTC_HALF_1 ); + ltc_2 = texture( ltcLib.LTC_HALF_2 ); } - // - - if ( texture.isFramebufferTexture ) { + const { colorNode, light } = this; + const lightingModel = builder.context.lightingModel; - const renderer = this.renderer; - const renderTarget = renderer.getRenderTarget(); + const lightPosition = lightViewPosition( light ); + const reflectedLight = builder.context.reflectedLight; - if ( renderTarget ) { + lightingModel.directRectArea( { + lightColor: colorNode, + lightPosition, + halfWidth: this.halfWidth, + halfHeight: this.halfHeight, + reflectedLight, + ltc_1, + ltc_2 + }, builder.stack, builder ); - texture.type = renderTarget.texture.type; + } - } else { + static setLTC( ltc ) { - texture.type = UnsignedByteType; + ltcLib = ltc; - } + } - } +} - // +class SpotLightNode extends AnalyticLightNode { - const { width, height, depth } = this.getSize( texture ); + static get type() { - options.width = width; - options.height = height; - options.depth = depth; - options.needsMipmaps = this.needsMipmaps( texture ); - options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1; + return 'SpotLightNode'; - // + } - if ( isRenderTarget || texture.isStorageTexture === true ) { + constructor( light = null ) { - backend.createSampler( texture ); - backend.createTexture( texture, options ); + super( light ); - textureData.generation = texture.version; + this.coneCosNode = uniform( 0 ).setGroup( renderGroup ); + this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup ); - } else { + this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup ); + this.decayExponentNode = uniform( 0 ).setGroup( renderGroup ); - const needsCreate = textureData.initialized !== true; + } - if ( needsCreate ) backend.createSampler( texture ); + update( frame ) { - if ( texture.version > 0 ) { + super.update( frame ); - const image = texture.image; + const { light } = this; - if ( image === undefined ) { + this.coneCosNode.value = Math.cos( light.angle ); + this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) ); - console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' ); + this.cutoffDistanceNode.value = light.distance; + this.decayExponentNode.value = light.decay; - } else if ( image.complete === false ) { + } - console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' ); + getSpotAttenuation( angleCosine ) { - } else { + const { coneCosNode, penumbraCosNode } = this; - if ( texture.images ) { + return smoothstep( coneCosNode, penumbraCosNode, angleCosine ); - const images = []; + } - for ( const image of texture.images ) { + setup( builder ) { - images.push( image ); + super.setup( builder ); - } + const lightingModel = builder.context.lightingModel; - options.images = images; + const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this; - } else { + const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode - options.image = image; + const lightDirection = lVector.normalize(); + const angleCos = lightDirection.dot( lightTargetDirection( light ) ); + const spotAttenuation = this.getSpotAttenuation( angleCos ); - } + const lightDistance = lVector.length(); - if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) { + const lightAttenuation = getDistanceAttenuation( { + lightDistance, + cutoffDistance: cutoffDistanceNode, + decayExponent: decayExponentNode + } ); - backend.createTexture( texture, options ); + const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation ); - textureData.isDefaultTexture = false; - textureData.generation = texture.version; + const reflectedLight = builder.context.reflectedLight; - } + lightingModel.direct( { + lightDirection, + lightColor, + reflectedLight + }, builder.stack, builder ); - if ( texture.source.dataReady === true ) backend.updateTexture( texture, options ); + } - if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture ); +} - } +class IESSpotLightNode extends SpotLightNode { - } else { + static get type() { - // async update + return 'IESSpotLightNode'; - backend.createDefaultTexture( texture ); + } - textureData.isDefaultTexture = true; - textureData.generation = texture.version; + getSpotAttenuation( angleCosine ) { - } + const iesMap = this.light.iesMap; - } + let spotAttenuation = null; - // dispose handler + if ( iesMap && iesMap.isTexture === true ) { - if ( textureData.initialized !== true ) { + const angle = angleCosine.acos().mul( 1.0 / Math.PI ); - textureData.initialized = true; - textureData.generation = texture.version; + spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r; - // + } else { - this.info.memory.textures ++; + spotAttenuation = super.getSpotAttenuation( angleCosine ); - // dispose + } - const onDispose = () => { + return spotAttenuation; - texture.removeEventListener( 'dispose', onDispose ); + } - this._destroyTexture( texture ); +} - this.info.memory.textures --; +class AmbientLightNode extends AnalyticLightNode { - }; + static get type() { - texture.addEventListener( 'dispose', onDispose ); + return 'AmbientLightNode'; - } + } - // + constructor( light = null ) { - textureData.version = texture.version; + super( light ); } - getSize( texture, target = _size ) { + setup( { context } ) { - let image = texture.images ? texture.images[ 0 ] : texture.image; + context.irradiance.addAssign( this.colorNode ); - if ( image ) { + } - if ( image.image !== undefined ) image = image.image; +} - target.width = image.width; - target.height = image.height; - target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 ); +class HemisphereLightNode extends AnalyticLightNode { - } else { + static get type() { - target.width = target.height = target.depth = 1; + return 'HemisphereLightNode'; - } + } - return target; + constructor( light = null ) { - } + super( light ); - getMipLevels( texture, width, height ) { + this.lightPositionNode = lightPosition( light ); + this.lightDirectionNode = this.lightPositionNode.normalize(); - let mipLevelCount; + this.groundColorNode = uniform( new Color() ).setGroup( renderGroup ); - if ( texture.isCompressedTexture ) { + } - mipLevelCount = texture.mipmaps.length; + update( frame ) { - } else { + const { light } = this; - mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1; + super.update( frame ); - } + this.lightPositionNode.object3d = light; - return mipLevelCount; + this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity ); } - needsMipmaps( texture ) { + setup( builder ) { - if ( this.isEnvironmentTexture( texture ) ) return true; + const { colorNode, groundColorNode, lightDirectionNode } = this; - return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) ); + const dotNL = normalView.dot( lightDirectionNode ); + const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 ); + + const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight ); + + builder.context.irradiance.addAssign( irradiance ); } - isEnvironmentTexture( texture ) { +} - const mapping = texture.mapping; +class LightProbeNode extends AnalyticLightNode { - return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); + static get type() { + + return 'LightProbeNode'; } - _destroyTexture( texture ) { + constructor( light = null ) { - this.backend.destroySampler( texture ); - this.backend.destroyTexture( texture ); + super( light ); - this.delete( texture ); + const array = []; - } + for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() ); -} + this.lightProbe = uniformArray( array ); -class Color4 extends Color { + } - constructor( r, g, b, a = 1 ) { + update( frame ) { - super( r, g, b ); + const { light } = this; - this.a = a; + super.update( frame ); - } + // - set( r, g, b, a = 1 ) { + for ( let i = 0; i < 9; i ++ ) { - this.a = a; + this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity ); - return super.set( r, g, b ); + } } - copy( color ) { + setup( builder ) { - if ( color.a !== undefined ) this.a = color.a; + const irradiance = getShIrradianceAt( normalWorld, this.lightProbe ); - return super.copy( color ); + builder.context.irradiance.addAssign( irradiance ); } - clone() { +} - return new this.constructor( this.r, this.g, this.b, this.a ); +class NodeParser { + + parseFunction( /*source*/ ) { + + console.warn( 'Abstract function.' ); } } -const _clearColor = /*@__PURE__*/ new Color4(); +class NodeFunction { -class Background extends DataMap { + constructor( type, inputs, name = '', precision = '' ) { - constructor( renderer, nodes ) { + this.type = type; + this.inputs = inputs; + this.name = name; + this.precision = precision; - super(); + } - this.renderer = renderer; - this.nodes = nodes; + getCode( /*name = this.name*/ ) { + + console.warn( 'Abstract function.' ); } - update( scene, renderList, renderContext ) { +} - const renderer = this.renderer; - const background = this.nodes.getBackgroundNode( scene ) || scene.background; +NodeFunction.isNodeFunction = true; - let forceClear = false; +const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i; +const propertiesRegexp$1 = /[a-z_0-9]+/ig; - if ( background === null ) { +const pragmaMain = '#pragma main'; - // no background settings, use clear color configuration from the renderer +const parse$1 = ( source ) => { - renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace ); - _clearColor.a = renderer._clearColor.a; + source = source.trim(); - } else if ( background.isColor === true ) { + const pragmaMainIndex = source.indexOf( pragmaMain ); - // background is an opaque color + const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source; - background.getRGB( _clearColor, LinearSRGBColorSpace ); - _clearColor.a = 1; + const declaration = mainCode.match( declarationRegexp$1 ); - forceClear = true; + if ( declaration !== null && declaration.length === 5 ) { - } else if ( background.isNode === true ) { + // tokenizer - const sceneData = this.get( scene ); - const backgroundNode = background; + const inputsCode = declaration[ 4 ]; + const propsMatches = []; - _clearColor.copy( renderer._clearColor ); + let nameMatch = null; - let backgroundMesh = sceneData.backgroundMesh; + while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) { - if ( backgroundMesh === undefined ) { + propsMatches.push( nameMatch ); - const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), { - // @TODO: Add Texture2D support using node context - getUV: () => normalWorld, - getTextureLevel: () => backgroundBlurriness - } ); + } - let viewProj = modelViewProjection(); - viewProj = viewProj.setZ( viewProj.w ); + // parser - const nodeMaterial = new NodeMaterial(); - nodeMaterial.name = 'Background.material'; - nodeMaterial.side = BackSide; - nodeMaterial.depthTest = false; - nodeMaterial.depthWrite = false; - nodeMaterial.fog = false; - nodeMaterial.lights = false; - nodeMaterial.vertexNode = viewProj; - nodeMaterial.colorNode = backgroundMeshNode; + const inputs = []; - sceneData.backgroundMeshNode = backgroundMeshNode; - sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial ); - backgroundMesh.frustumCulled = false; - backgroundMesh.name = 'Background.mesh'; + let i = 0; - backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) { + while ( i < propsMatches.length ) { - this.matrixWorld.copyPosition( camera.matrixWorld ); + const isConst = propsMatches[ i ][ 0 ] === 'const'; - }; + if ( isConst === true ) { + + i ++; } - const backgroundCacheKey = backgroundNode.getCacheKey(); + let qualifier = propsMatches[ i ][ 0 ]; - if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) { + if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) { - sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity ); - sceneData.backgroundMeshNode.needsUpdate = true; + i ++; - backgroundMesh.material.needsUpdate = true; + } else { - sceneData.backgroundCacheKey = backgroundCacheKey; + qualifier = ''; } - renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null ); + const type = propsMatches[ i ++ ][ 0 ]; - } else { + let count = Number.parseInt( propsMatches[ i ][ 0 ] ); - console.error( 'THREE.Renderer: Unsupported background configuration.', background ); + if ( Number.isNaN( count ) === false ) i ++; + else count = null; - } + const name = propsMatches[ i ++ ][ 0 ]; - // + inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) ); - if ( renderer.autoClear === true || forceClear === true ) { + } - const clearColorValue = renderContext.clearColorValue; + // - clearColorValue.r = _clearColor.r; - clearColorValue.g = _clearColor.g; - clearColorValue.b = _clearColor.b; - clearColorValue.a = _clearColor.a; + const blockCode = mainCode.substring( declaration[ 0 ].length ); - // premultiply alpha + const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : ''; + const type = declaration[ 2 ]; - if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) { + const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : ''; - clearColorValue.r *= clearColorValue.a; - clearColorValue.g *= clearColorValue.a; - clearColorValue.b *= clearColorValue.a; + const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : ''; - } + return { + type, + inputs, + name, + precision, + inputsCode, + blockCode, + headerCode + }; - // + } else { - renderContext.depthClearValue = renderer._clearDepth; - renderContext.stencilClearValue = renderer._clearStencil; + throw new Error( 'FunctionNode: Function is not a GLSL code.' ); - renderContext.clearColor = renderer.autoClearColor === true; - renderContext.clearDepth = renderer.autoClearDepth === true; - renderContext.clearStencil = renderer.autoClearStencil === true; + } - } else { +}; - renderContext.clearColor = false; - renderContext.clearDepth = false; - renderContext.clearStencil = false; +class GLSLNodeFunction extends NodeFunction { - } + constructor( source ) { - } + const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source ); -} + super( type, inputs, name, precision ); -class NodeBuilderState { + this.inputsCode = inputsCode; + this.blockCode = blockCode; + this.headerCode = headerCode; - constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) { + } - this.vertexShader = vertexShader; - this.fragmentShader = fragmentShader; - this.computeShader = computeShader; - this.transforms = transforms; + getCode( name = this.name ) { - this.nodeAttributes = nodeAttributes; - this.bindings = bindings; + let code; - this.updateNodes = updateNodes; - this.updateBeforeNodes = updateBeforeNodes; - this.updateAfterNodes = updateAfterNodes; + const blockCode = this.blockCode; - this.monitor = monitor; + if ( blockCode !== '' ) { - this.usedTimes = 0; + const { type, inputsCode, headerCode, precision } = this; - } + let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`; - createBindings() { + if ( precision !== '' ) { - const bindings = []; + declarationCode = `${ precision } ${ declarationCode }`; - for ( const instanceGroup of this.bindings ) { + } - const shared = instanceGroup.bindings[ 0 ].groupNode.shared; + code = headerCode + declarationCode + blockCode; - if ( shared !== true ) { + } else { - const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup ); - bindings.push( bindingsGroup ); + // interface function - for ( const instanceBinding of instanceGroup.bindings ) { + code = ''; - bindingsGroup.bindings.push( instanceBinding.clone() ); + } - } + return code; - } else { + } - bindings.push( instanceGroup ); +} - } +class GLSLNodeParser extends NodeParser { - } + parseFunction( source ) { - return bindings; + return new GLSLNodeFunction( source ); } @@ -63838,6 +63864,47 @@ class NodeLibrary { } +const _defaultLights = /*@__PURE__*/ new LightsNode(); + +class Lighting extends ChainMap { + + constructor() { + + super(); + + } + + createNode( lights = [] ) { + + return new LightsNode().setLights( lights ); + + } + + getNode( scene, camera ) { + + // ignore post-processing + + if ( scene.isQuadMesh ) return _defaultLights; + + // tiled lighting + + const keys = [ scene, camera ]; + + let node = this.get( keys ); + + if ( node === undefined ) { + + node = this.createNode(); + this.set( keys, node ); + + } + + return node; + + } + +} + const _scene = /*@__PURE__*/ new Scene(); const _drawingBufferSize = /*@__PURE__*/ new Vector2(); const _screen = /*@__PURE__*/ new Vector4(); @@ -63894,11 +63961,13 @@ class Renderer { this.info = new Info(); this.nodes = { - library: new NodeLibrary(), modelViewMatrix: null, modelNormalViewMatrix: null }; + this.library = new NodeLibrary(); + this.lighting = new Lighting(); + // internals this._getFallback = getFallback; @@ -64050,7 +64119,7 @@ class Renderer { this._pipelines = new Pipelines( backend, this._nodes ); this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info ); this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info ); - this._renderLists = new RenderLists(); + this._renderLists = new RenderLists( this.lighting ); this._bundles = new RenderBundles(); this._renderContexts = new RenderContexts(); @@ -70730,8 +70799,6 @@ class WebGLBackend extends Backend { // Bindings - this.createBindings( null, bindings ); - this._setupBindings( bindings, programGPU ); const attributeNodes = computeProgram.attributes; @@ -70803,8 +70870,6 @@ class WebGLBackend extends Backend { updateBindings( bindGroup /*, bindings*/ ) { - if ( bindGroup === null ) return; - const { gl } = this; const bindGroupData = this.get( bindGroup ); @@ -71754,9 +71819,17 @@ class WebGPUTextureUtils { magFilter: this._convertFilterMode( texture.magFilter ), minFilter: this._convertFilterMode( texture.minFilter ), mipmapFilter: this._convertFilterMode( texture.minFilter ), - maxAnisotropy: texture.anisotropy + maxAnisotropy: 1 }; + // anisotropy can only be used when all filter modes are set to linear. + + if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) { + + samplerDescriptorGPU.maxAnisotropy = texture.anisotropy; + + } + if ( texture.isDepthTexture && texture.compareFunction !== null ) { samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ]; @@ -73104,19 +73177,8 @@ const wgslTypeLib = { bvec4: 'vec4', mat2: 'mat2x2', - imat2: 'mat2x2', - umat2: 'mat2x2', - bmat2: 'mat2x2', - mat3: 'mat3x3', - imat3: 'mat3x3', - umat3: 'mat3x3', - bmat3: 'mat3x3', - - mat4: 'mat4x4', - imat4: 'mat4x4', - umat4: 'mat4x4', - bmat4: 'mat4x4' + mat4: 'mat4x4' }; const wgslPolyfill = { @@ -77446,7 +77508,7 @@ class WebGPURenderer extends Renderer { //super( new Proxy( backend, debugHandler ) ); super( backend, parameters ); - this.nodes.library = new StandardNodeLibrary(); + this.library = new StandardNodeLibrary(); this.isWebGPURenderer = true; @@ -78003,4 +78065,4 @@ if ( typeof window !== 'undefined' ) { } -export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicEnvironmentNode, BasicShadowMap$1 as BasicShadowMap, BatchNode, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, Controls, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, Discard, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightProbeNode, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, Loop, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureLoader, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformArrayNode, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getColorSpaceMethod, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, global, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearSRGBTosRGB, linearToneMapping, localId, log, log2, loop, luminance, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToLogarithmicDepth, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rotate, rotateUV, roughness, round, rtt, sRGBToLinearSRGB, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor }; +export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicEnvironmentNode, BasicShadowMap$1 as BasicShadowMap, BatchNode, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, Controls, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, Discard, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, Loop, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureLoader, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformArrayNode, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directPointLight, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getColorSpaceMethod, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, global, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearSRGBTosRGB, linearToneMapping, localId, log, log2, loop, luminance, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToLogarithmicDepth, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rotate, rotateUV, roughness, round, rtt, sRGBToLinearSRGB, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor }; diff --git a/build/three.webgpu.min.js b/build/three.webgpu.min.js index f395a0e86827a2..4ea76fc5641996 100644 --- a/build/three.webgpu.min.js +++ b/build/three.webgpu.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2024 Three.js Authors * SPDX-License-Identifier: MIT */ -const e="170dev",t={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},s={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},i=0,r=1,n=2,o=3,a=0,h=1,u=2,l=3,c=0,d=1,p=2,m=0,g=1,f=2,y=3,x=4,b=5,v=100,T=101,_=102,w=103,S=104,M=200,A=201,N=202,C=203,R=204,E=205,B=206,I=207,P=208,F=209,U=210,O=211,z=212,L=213,V=214,D=0,k=1,G=2,W=3,j=4,H=5,q=6,$=7,X=0,Y=1,Z=2,J=0,K=1,Q=2,ee=3,te=4,se=5,ie=6,re=7,ne="attached",oe="detached",ae=300,he=301,ue=302,le=303,ce=304,de=306,pe=1e3,me=1001,ge=1002,fe=1003,ye=1004,xe=1004,be=1005,ve=1005,Te=1006,_e=1007,we=1007,Se=1008,Me=1008,Ae=1009,Ne=1010,Ce=1011,Re=1012,Ee=1013,Be=1014,Ie=1015,Pe=1016,Fe=1017,Ue=1018,Oe=1020,ze=35902,Le=1021,Ve=1022,De=1023,ke=1024,Ge=1025,We=1026,je=1027,He=1028,qe=1029,$e=1030,Xe=1031,Ye=1032,Ze=1033,Je=33776,Ke=33777,Qe=33778,et=33779,tt=35840,st=35841,it=35842,rt=35843,nt=36196,ot=37492,at=37496,ht=37808,ut=37809,lt=37810,ct=37811,dt=37812,pt=37813,mt=37814,gt=37815,ft=37816,yt=37817,xt=37818,bt=37819,vt=37820,Tt=37821,_t=36492,wt=36494,St=36495,Mt=36283,At=36284,Nt=36285,Ct=36286,Rt=2200,Et=2201,Bt=2202,It=2300,Pt=2301,Ft=2302,Ut=2400,Ot=2401,zt=2402,Lt=2500,Vt=2501,Dt=0,kt=1,Gt=2,Wt=3200,jt=3201,Ht=3202,qt=3203,$t=0,Xt=1,Yt="",Zt="srgb",Jt="srgb-linear",Kt="linear",Qt="srgb",es=0,ts=7680,ss=7681,is=7682,rs=7683,ns=34055,os=34056,as=5386,hs=512,us=513,ls=514,cs=515,ds=516,ps=517,ms=518,gs=519,fs=512,ys=513,xs=514,bs=515,vs=516,Ts=517,_s=518,ws=519,Ss=35044,Ms=35048,As=35040,Ns=35045,Cs=35049,Rs=35041,Es=35046,Bs=35050,Is=35042,Ps="100",Fs="300 es",Us=2e3,Os=2001;class zs{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const s=this._listeners;void 0===s[e]&&(s[e]=[]),-1===s[e].indexOf(t)&&s[e].push(t)}hasEventListener(e,t){if(void 0===this._listeners)return!1;const s=this._listeners;return void 0!==s[e]&&-1!==s[e].indexOf(t)}removeEventListener(e,t){if(void 0===this._listeners)return;const s=this._listeners[e];if(void 0!==s){const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}dispatchEvent(e){if(void 0===this._listeners)return;const t=this._listeners[e.type];if(void 0!==t){e.target=this;const s=t.slice(0);for(let t=0,i=s.length;t>8&255]+Ls[e>>16&255]+Ls[e>>24&255]+"-"+Ls[255&t]+Ls[t>>8&255]+"-"+Ls[t>>16&15|64]+Ls[t>>24&255]+"-"+Ls[63&s|128]+Ls[s>>8&255]+"-"+Ls[s>>16&255]+Ls[s>>24&255]+Ls[255&i]+Ls[i>>8&255]+Ls[i>>16&255]+Ls[i>>24&255]).toLowerCase()}function Ws(e,t,s){return Math.max(t,Math.min(s,e))}function js(e,t){return(e%t+t)%t}function Hs(e,t,s){return(1-s)*e+s*t}function qs(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function $s(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Xs={DEG2RAD:Ds,RAD2DEG:ks,generateUUID:Gs,clamp:Ws,euclideanModulo:js,mapLinear:function(e,t,s,i,r){return i+(e-t)*(r-i)/(s-t)},inverseLerp:function(e,t,s){return e!==t?(s-e)/(t-e):0},lerp:Hs,damp:function(e,t,s,i){return Hs(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(js(e,2*t)-t)},smoothstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*(3-2*e)},smootherstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Vs=e);let t=Vs+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*Ds},radToDeg:function(e){return e*ks},isPowerOfTwo:function(e){return 0==(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,s,i,r){const n=Math.cos,o=Math.sin,a=n(s/2),h=o(s/2),u=n((t+i)/2),l=o((t+i)/2),c=n((t-i)/2),d=o((t-i)/2),p=n((i-t)/2),m=o((i-t)/2);switch(r){case"XYX":e.set(a*l,h*c,h*d,a*u);break;case"YZY":e.set(h*d,a*l,h*c,a*u);break;case"ZXZ":e.set(h*c,h*d,a*l,a*u);break;case"XZX":e.set(a*l,h*m,h*p,a*u);break;case"YXY":e.set(h*p,a*l,h*m,a*u);break;case"ZYZ":e.set(h*m,h*p,a*l,a*u);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:$s,denormalize:qs};class Ys{constructor(e=0,t=0){Ys.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Ws(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const s=Math.cos(t),i=Math.sin(t),r=this.x-e.x,n=this.y-e.y;return this.x=r*s-n*i+e.x,this.y=r*i+n*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Zs{constructor(e,t,s,i,r,n,o,a,h){Zs.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,h)}set(e,t,s,i,r,n,o,a,h){const u=this.elements;return u[0]=e,u[1]=i,u[2]=o,u[3]=t,u[4]=r,u[5]=a,u[6]=s,u[7]=n,u[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[3],a=s[6],h=s[1],u=s[4],l=s[7],c=s[2],d=s[5],p=s[8],m=i[0],g=i[3],f=i[6],y=i[1],x=i[4],b=i[7],v=i[2],T=i[5],_=i[8];return r[0]=n*m+o*y+a*v,r[3]=n*g+o*x+a*T,r[6]=n*f+o*b+a*_,r[1]=h*m+u*y+l*v,r[4]=h*g+u*x+l*T,r[7]=h*f+u*b+l*_,r[2]=c*m+d*y+p*v,r[5]=c*g+d*x+p*T,r[8]=c*f+d*b+p*_,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8];return t*n*u-t*o*h-s*r*u+s*o*a+i*r*h-i*n*a}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8],l=u*n-o*h,c=o*a-u*r,d=h*r-n*a,p=t*l+s*c+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=l*m,e[1]=(i*h-u*s)*m,e[2]=(o*s-i*n)*m,e[3]=c*m,e[4]=(u*t-i*a)*m,e[5]=(i*r-o*t)*m,e[6]=d*m,e[7]=(s*a-h*t)*m,e[8]=(n*t-s*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,s,i,r,n,o){const a=Math.cos(r),h=Math.sin(r);return this.set(s*a,s*h,-s*(a*n+h*o)+n+e,-i*h,i*a,-i*(-h*n+a*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Js.makeScale(e,t)),this}rotate(e){return this.premultiply(Js.makeRotation(-e)),this}translate(e,t){return this.premultiply(Js.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<9;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const Js=new Zs;const Ks={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Qs(e,t){return new Ks[e](t)}function ei(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function ti(){const e=ei("canvas");return e.style.display="block",e}const si={};const ii={enabled:!0,workingColorSpace:Jt,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Qt&&(e.r=ri(e.r),e.g=ri(e.g),e.b=ri(e.b)),this.spaces[t].primaries!==this.spaces[s].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Qt&&(e.r=ni(e.r),e.g=ni(e.g),e.b=ni(e.b)),e):e},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===Yt?Kt:this.spaces[e].transfer},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,s){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace}};function ri(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function ni(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}const oi=[.64,.33,.3,.6,.15,.06],ai=[.2126,.7152,.0722],hi=[.3127,.329],ui=(new Zs).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),li=(new Zs).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);let ci;ii.define({[Jt]:{primaries:oi,whitePoint:hi,transfer:Kt,toXYZ:ui,fromXYZ:li,luminanceCoefficients:ai,workingColorSpaceConfig:{unpackColorSpace:Zt},outputColorSpaceConfig:{drawingBufferColorSpace:Zt}},[Zt]:{primaries:oi,whitePoint:hi,transfer:Qt,toXYZ:ui,fromXYZ:li,luminanceCoefficients:ai,outputColorSpaceConfig:{drawingBufferColorSpace:Zt}}});class di{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===ci&&(ci=ei("canvas")),ci.width=e.width,ci.height=e.height;const s=ci.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),t=ci}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=ei("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==ae)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case pe:e.x=e.x-Math.floor(e.x);break;case me:e.x=e.x<0?0:1;break;case ge:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case pe:e.y=e.y-Math.floor(e.y);break;case me:e.y=e.y<0?0:1;break;case ge:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}yi.DEFAULT_IMAGE=null,yi.DEFAULT_MAPPING=ae,yi.DEFAULT_ANISOTROPY=1;class xi{constructor(e=0,t=0,s=0,i=1){xi.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=this.w,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i+n[12]*r,this.y=n[1]*t+n[5]*s+n[9]*i+n[13]*r,this.z=n[2]*t+n[6]*s+n[10]*i+n[14]*r,this.w=n[3]*t+n[7]*s+n[11]*i+n[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,s,i,r;const n=.01,o=.1,a=e.elements,h=a[0],u=a[4],l=a[8],c=a[1],d=a[5],p=a[9],m=a[2],g=a[6],f=a[10];if(Math.abs(u-c)a&&e>y?ey?a=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),n=Math.atan2(r,t*s);e=Math.sin(e*n)/r,o=Math.sin(o*n)/r}const r=o*s;if(a=a*e+c*r,h=h*e+d*r,u=u*e+p*r,l=l*e+m*r,e===1-o){const e=1/Math.sqrt(a*a+h*h+u*u+l*l);a*=e,h*=e,u*=e,l*=e}}e[t]=a,e[t+1]=h,e[t+2]=u,e[t+3]=l}static multiplyQuaternionsFlat(e,t,s,i,r,n){const o=s[i],a=s[i+1],h=s[i+2],u=s[i+3],l=r[n],c=r[n+1],d=r[n+2],p=r[n+3];return e[t]=o*p+u*l+a*d-h*c,e[t+1]=a*p+u*c+h*l-o*d,e[t+2]=h*p+u*d+o*c-a*l,e[t+3]=u*p-o*l-a*c-h*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,r=e._z,n=e._order,o=Math.cos,a=Math.sin,h=o(s/2),u=o(i/2),l=o(r/2),c=a(s/2),d=a(i/2),p=a(r/2);switch(n){case"XYZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"YXZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"ZXY":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"ZYX":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"YZX":this._x=c*u*l+h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l-c*d*p;break;case"XZY":this._x=c*u*l-h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l+c*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],r=t[8],n=t[1],o=t[5],a=t[9],h=t[2],u=t[6],l=t[10],c=s+o+l;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(u-a)*e,this._y=(r-h)*e,this._z=(n-i)*e}else if(s>o&&s>l){const e=2*Math.sqrt(1+s-o-l);this._w=(u-a)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+h)/e}else if(o>l){const e=2*Math.sqrt(1+o-s-l);this._w=(r-h)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(a+u)/e}else{const e=2*Math.sqrt(1+l-s-o);this._w=(n-i)/e,this._x=(r+h)/e,this._y=(a+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return sMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ws(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(0===s)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,i=e._y,r=e._z,n=e._w,o=t._x,a=t._y,h=t._z,u=t._w;return this._x=s*u+n*o+i*h-r*a,this._y=i*u+n*a+r*o-s*h,this._z=r*u+n*h+s*a-i*o,this._w=n*u-s*o-i*a-r*h,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const s=this._x,i=this._y,r=this._z,n=this._w;let o=n*e._w+s*e._x+i*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=n,this._x=s,this._y=i,this._z=r,this;const a=1-o*o;if(a<=Number.EPSILON){const e=1-t;return this._w=e*n+t*this._w,this._x=e*s+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const h=Math.sqrt(a),u=Math.atan2(h,o),l=Math.sin((1-t)*u)/h,c=Math.sin(t*u)/h;return this._w=n*l+this._w*c,this._x=s*l+this._x*c,this._y=i*l+this._y*c,this._z=r*l+this._z*c,this._onChangeCallback(),this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),r=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ai{constructor(e=0,t=0,s=0){Ai.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return void 0===s&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Ci.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ci.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6]*i,this.y=r[1]*t+r[4]*s+r[7]*i,this.z=r[2]*t+r[5]*s+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=e.elements,n=1/(r[3]*t+r[7]*s+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*s+r[8]*i+r[12])*n,this.y=(r[1]*t+r[5]*s+r[9]*i+r[13])*n,this.z=(r[2]*t+r[6]*s+r[10]*i+r[14])*n,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,r=e.x,n=e.y,o=e.z,a=e.w,h=2*(n*i-o*s),u=2*(o*t-r*i),l=2*(r*s-n*t);return this.x=t+a*h+n*l-o*u,this.y=s+a*u+o*h-r*l,this.z=i+a*l+r*u-n*h,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i,this.y=r[1]*t+r[5]*s+r[9]*i,this.z=r[2]*t+r[6]*s+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,r=e.z,n=t.x,o=t.y,a=t.z;return this.x=i*a-r*o,this.y=r*n-s*a,this.z=s*o-i*n,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Ni.copy(this).projectOnVector(e),this.sub(Ni)}reflect(e){return this.sub(Ni.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Ws(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ni=new Ai,Ci=new Mi;class Ri{constructor(e=new Ai(1/0,1/0,1/0),t=new Ai(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Bi),Bi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Vi),Di.subVectors(this.max,Vi),Pi.subVectors(e.a,Vi),Fi.subVectors(e.b,Vi),Ui.subVectors(e.c,Vi),Oi.subVectors(Fi,Pi),zi.subVectors(Ui,Fi),Li.subVectors(Pi,Ui);let t=[0,-Oi.z,Oi.y,0,-zi.z,zi.y,0,-Li.z,Li.y,Oi.z,0,-Oi.x,zi.z,0,-zi.x,Li.z,0,-Li.x,-Oi.y,Oi.x,0,-zi.y,zi.x,0,-Li.y,Li.x,0];return!!Wi(t,Pi,Fi,Ui,Di)&&(t=[1,0,0,0,1,0,0,0,1],!!Wi(t,Pi,Fi,Ui,Di)&&(ki.crossVectors(Oi,zi),t=[ki.x,ki.y,ki.z],Wi(t,Pi,Fi,Ui,Di)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Bi).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Ei[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ei[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ei[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ei[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ei[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ei[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ei[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ei[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ei)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Ei=[new Ai,new Ai,new Ai,new Ai,new Ai,new Ai,new Ai,new Ai],Bi=new Ai,Ii=new Ri,Pi=new Ai,Fi=new Ai,Ui=new Ai,Oi=new Ai,zi=new Ai,Li=new Ai,Vi=new Ai,Di=new Ai,ki=new Ai,Gi=new Ai;function Wi(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){Gi.fromArray(e,n);const o=r.x*Math.abs(Gi.x)+r.y*Math.abs(Gi.y)+r.z*Math.abs(Gi.z),a=t.dot(Gi),h=s.dot(Gi),u=i.dot(Gi);if(Math.max(-Math.max(a,h,u),Math.min(a,h,u))>o)return!1}return!0}const ji=new Ri,Hi=new Ai,qi=new Ai;class $i{constructor(e=new Ai,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const s=this.center;void 0!==t?s.copy(t):ji.setFromPoints(e).getCenter(s);let i=0;for(let t=0,r=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Hi.subVectors(e,this.center);const t=Hi.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Hi,s/e),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(qi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Hi.copy(e.center).add(qi)),this.expandByPoint(Hi.copy(e.center).sub(qi))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Xi=new Ai,Yi=new Ai,Zi=new Ai,Ji=new Ai,Ki=new Ai,Qi=new Ai,er=new Ai;class tr{constructor(e=new Ai,t=new Ai(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Xi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Xi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Xi.copy(this.origin).addScaledVector(this.direction,t),Xi.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){Yi.copy(e).add(t).multiplyScalar(.5),Zi.copy(t).sub(e).normalize(),Ji.copy(this.origin).sub(Yi);const r=.5*e.distanceTo(t),n=-this.direction.dot(Zi),o=Ji.dot(this.direction),a=-Ji.dot(Zi),h=Ji.lengthSq(),u=Math.abs(1-n*n);let l,c,d,p;if(u>0)if(l=n*a-o,c=n*o-a,p=r*u,l>=0)if(c>=-p)if(c<=p){const e=1/u;l*=e,c*=e,d=l*(l+n*c+2*o)+c*(n*l+c+2*a)+h}else c=r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;else c=-r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;else c<=-p?(l=Math.max(0,-(-n*r+o)),c=l>0?-r:Math.min(Math.max(-r,-a),r),d=-l*l+c*(c+2*a)+h):c<=p?(l=0,c=Math.min(Math.max(-r,-a),r),d=c*(c+2*a)+h):(l=Math.max(0,-(n*r+o)),c=l>0?r:Math.min(Math.max(-r,-a),r),d=-l*l+c*(c+2*a)+h);else c=n>0?-r:r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;return s&&s.copy(this.origin).addScaledVector(this.direction,l),i&&i.copy(Yi).addScaledVector(Zi,c),d}intersectSphere(e,t){Xi.subVectors(e.center,this.origin);const s=Xi.dot(this.direction),i=Xi.dot(Xi)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),o=s-n,a=s+n;return a<0?null:o<0?this.at(a,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return null===s?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,r,n,o,a;const h=1/this.direction.x,u=1/this.direction.y,l=1/this.direction.z,c=this.origin;return h>=0?(s=(e.min.x-c.x)*h,i=(e.max.x-c.x)*h):(s=(e.max.x-c.x)*h,i=(e.min.x-c.x)*h),u>=0?(r=(e.min.y-c.y)*u,n=(e.max.y-c.y)*u):(r=(e.max.y-c.y)*u,n=(e.min.y-c.y)*u),s>n||r>i?null:((r>s||isNaN(s))&&(s=r),(n=0?(o=(e.min.z-c.z)*l,a=(e.max.z-c.z)*l):(o=(e.max.z-c.z)*l,a=(e.min.z-c.z)*l),s>a||o>i?null:((o>s||s!=s)&&(s=o),(a=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Xi)}intersectTriangle(e,t,s,i,r){Ki.subVectors(t,e),Qi.subVectors(s,e),er.crossVectors(Ki,Qi);let n,o=this.direction.dot(er);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}Ji.subVectors(this.origin,e);const a=n*this.direction.dot(Qi.crossVectors(Ji,Qi));if(a<0)return null;const h=n*this.direction.dot(Ki.cross(Ji));if(h<0)return null;if(a+h>o)return null;const u=-n*Ji.dot(er);return u<0?null:this.at(u/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class sr{constructor(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g){sr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g)}set(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g){const f=this.elements;return f[0]=e,f[4]=t,f[8]=s,f[12]=i,f[1]=r,f[5]=n,f[9]=o,f[13]=a,f[2]=h,f[6]=u,f[10]=l,f[14]=c,f[3]=d,f[7]=p,f[11]=m,f[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new sr).fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,s){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,s=e.elements,i=1/ir.setFromMatrixColumn(e,0).length(),r=1/ir.setFromMatrixColumn(e,1).length(),n=1/ir.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*r,t[5]=s[5]*r,t[6]=s[6]*r,t[7]=0,t[8]=s[8]*n,t[9]=s[9]*n,t[10]=s[10]*n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,r=e.z,n=Math.cos(s),o=Math.sin(s),a=Math.cos(i),h=Math.sin(i),u=Math.cos(r),l=Math.sin(r);if("XYZ"===e.order){const e=n*u,s=n*l,i=o*u,r=o*l;t[0]=a*u,t[4]=-a*l,t[8]=h,t[1]=s+i*h,t[5]=e-r*h,t[9]=-o*a,t[2]=r-e*h,t[6]=i+s*h,t[10]=n*a}else if("YXZ"===e.order){const e=a*u,s=a*l,i=h*u,r=h*l;t[0]=e+r*o,t[4]=i*o-s,t[8]=n*h,t[1]=n*l,t[5]=n*u,t[9]=-o,t[2]=s*o-i,t[6]=r+e*o,t[10]=n*a}else if("ZXY"===e.order){const e=a*u,s=a*l,i=h*u,r=h*l;t[0]=e-r*o,t[4]=-n*l,t[8]=i+s*o,t[1]=s+i*o,t[5]=n*u,t[9]=r-e*o,t[2]=-n*h,t[6]=o,t[10]=n*a}else if("ZYX"===e.order){const e=n*u,s=n*l,i=o*u,r=o*l;t[0]=a*u,t[4]=i*h-s,t[8]=e*h+r,t[1]=a*l,t[5]=r*h+e,t[9]=s*h-i,t[2]=-h,t[6]=o*a,t[10]=n*a}else if("YZX"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*u,t[4]=r-e*l,t[8]=i*l+s,t[1]=l,t[5]=n*u,t[9]=-o*u,t[2]=-h*u,t[6]=s*l+i,t[10]=e-r*l}else if("XZY"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*u,t[4]=-l,t[8]=h*u,t[1]=e*l+r,t[5]=n*u,t[9]=s*l-i,t[2]=i*l-s,t[6]=o*u,t[10]=r*l+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(nr,e,or)}lookAt(e,t,s){const i=this.elements;return ur.subVectors(e,t),0===ur.lengthSq()&&(ur.z=1),ur.normalize(),ar.crossVectors(s,ur),0===ar.lengthSq()&&(1===Math.abs(s.z)?ur.x+=1e-4:ur.z+=1e-4,ur.normalize(),ar.crossVectors(s,ur)),ar.normalize(),hr.crossVectors(ur,ar),i[0]=ar.x,i[4]=hr.x,i[8]=ur.x,i[1]=ar.y,i[5]=hr.y,i[9]=ur.y,i[2]=ar.z,i[6]=hr.z,i[10]=ur.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[4],a=s[8],h=s[12],u=s[1],l=s[5],c=s[9],d=s[13],p=s[2],m=s[6],g=s[10],f=s[14],y=s[3],x=s[7],b=s[11],v=s[15],T=i[0],_=i[4],w=i[8],S=i[12],M=i[1],A=i[5],N=i[9],C=i[13],R=i[2],E=i[6],B=i[10],I=i[14],P=i[3],F=i[7],U=i[11],O=i[15];return r[0]=n*T+o*M+a*R+h*P,r[4]=n*_+o*A+a*E+h*F,r[8]=n*w+o*N+a*B+h*U,r[12]=n*S+o*C+a*I+h*O,r[1]=u*T+l*M+c*R+d*P,r[5]=u*_+l*A+c*E+d*F,r[9]=u*w+l*N+c*B+d*U,r[13]=u*S+l*C+c*I+d*O,r[2]=p*T+m*M+g*R+f*P,r[6]=p*_+m*A+g*E+f*F,r[10]=p*w+m*N+g*B+f*U,r[14]=p*S+m*C+g*I+f*O,r[3]=y*T+x*M+b*R+v*P,r[7]=y*_+x*A+b*E+v*F,r[11]=y*w+x*N+b*B+v*U,r[15]=y*S+x*C+b*I+v*O,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[4],i=e[8],r=e[12],n=e[1],o=e[5],a=e[9],h=e[13],u=e[2],l=e[6],c=e[10],d=e[14];return e[3]*(+r*a*l-i*h*l-r*o*c+s*h*c+i*o*d-s*a*d)+e[7]*(+t*a*d-t*h*c+r*n*c-i*n*d+i*h*u-r*a*u)+e[11]*(+t*h*l-t*o*d-r*n*l+s*n*d+r*o*u-s*h*u)+e[15]*(-i*o*u-t*a*l+t*o*c+i*n*l-s*n*c+s*a*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8],l=e[9],c=e[10],d=e[11],p=e[12],m=e[13],g=e[14],f=e[15],y=l*g*h-m*c*h+m*a*d-o*g*d-l*a*f+o*c*f,x=p*c*h-u*g*h-p*a*d+n*g*d+u*a*f-n*c*f,b=u*m*h-p*l*h+p*o*d-n*m*d-u*o*f+n*l*f,v=p*l*a-u*m*a-p*o*c+n*m*c+u*o*g-n*l*g,T=t*y+s*x+i*b+r*v;if(0===T)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const _=1/T;return e[0]=y*_,e[1]=(m*c*r-l*g*r-m*i*d+s*g*d+l*i*f-s*c*f)*_,e[2]=(o*g*r-m*a*r+m*i*h-s*g*h-o*i*f+s*a*f)*_,e[3]=(l*a*r-o*c*r-l*i*h+s*c*h+o*i*d-s*a*d)*_,e[4]=x*_,e[5]=(u*g*r-p*c*r+p*i*d-t*g*d-u*i*f+t*c*f)*_,e[6]=(p*a*r-n*g*r-p*i*h+t*g*h+n*i*f-t*a*f)*_,e[7]=(n*c*r-u*a*r+u*i*h-t*c*h-n*i*d+t*a*d)*_,e[8]=b*_,e[9]=(p*l*r-u*m*r-p*s*d+t*m*d+u*s*f-t*l*f)*_,e[10]=(n*m*r-p*o*r+p*s*h-t*m*h-n*s*f+t*o*f)*_,e[11]=(u*o*r-n*l*r-u*s*h+t*l*h+n*s*d-t*o*d)*_,e[12]=v*_,e[13]=(u*m*i-p*l*i+p*s*c-t*m*c-u*s*g+t*l*g)*_,e[14]=(p*o*i-n*m*i-p*s*a+t*m*a+n*s*g-t*o*g)*_,e[15]=(n*l*i-u*o*i+u*s*a-t*l*a-n*s*c+t*o*c)*_,this}scale(e){const t=this.elements,s=e.x,i=e.y,r=e.z;return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),r=1-s,n=e.x,o=e.y,a=e.z,h=r*n,u=r*o;return this.set(h*n+s,h*o-i*a,h*a+i*o,0,h*o+i*a,u*o+s,u*a-i*n,0,h*a-i*o,u*a+i*n,r*a*a+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,r,n){return this.set(1,s,r,0,e,1,n,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,r=t._x,n=t._y,o=t._z,a=t._w,h=r+r,u=n+n,l=o+o,c=r*h,d=r*u,p=r*l,m=n*u,g=n*l,f=o*l,y=a*h,x=a*u,b=a*l,v=s.x,T=s.y,_=s.z;return i[0]=(1-(m+f))*v,i[1]=(d+b)*v,i[2]=(p-x)*v,i[3]=0,i[4]=(d-b)*T,i[5]=(1-(c+f))*T,i[6]=(g+y)*T,i[7]=0,i[8]=(p+x)*_,i[9]=(g-y)*_,i[10]=(1-(c+m))*_,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;let r=ir.set(i[0],i[1],i[2]).length();const n=ir.set(i[4],i[5],i[6]).length(),o=ir.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],rr.copy(this);const a=1/r,h=1/n,u=1/o;return rr.elements[0]*=a,rr.elements[1]*=a,rr.elements[2]*=a,rr.elements[4]*=h,rr.elements[5]*=h,rr.elements[6]*=h,rr.elements[8]*=u,rr.elements[9]*=u,rr.elements[10]*=u,t.setFromRotationMatrix(rr),s.x=r,s.y=n,s.z=o,this}makePerspective(e,t,s,i,r,n,o=2e3){const a=this.elements,h=2*r/(t-e),u=2*r/(s-i),l=(t+e)/(t-e),c=(s+i)/(s-i);let d,p;if(o===Us)d=-(n+r)/(n-r),p=-2*n*r/(n-r);else{if(o!==Os)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-n/(n-r),p=-n*r/(n-r)}return a[0]=h,a[4]=0,a[8]=l,a[12]=0,a[1]=0,a[5]=u,a[9]=c,a[13]=0,a[2]=0,a[6]=0,a[10]=d,a[14]=p,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(e,t,s,i,r,n,o=2e3){const a=this.elements,h=1/(t-e),u=1/(s-i),l=1/(n-r),c=(t+e)*h,d=(s+i)*u;let p,m;if(o===Us)p=(n+r)*l,m=-2*l;else{if(o!==Os)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);p=r*l,m=-1*l}return a[0]=2*h,a[4]=0,a[8]=0,a[12]=-c,a[1]=0,a[5]=2*u,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=m,a[14]=-p,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<16;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const ir=new Ai,rr=new sr,nr=new Ai(0,0,0),or=new Ai(1,1,1),ar=new Ai,hr=new Ai,ur=new Ai,lr=new sr,cr=new Mi;class dr{constructor(e=0,t=0,s=0,i=dr.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,r=i[0],n=i[4],o=i[8],a=i[1],h=i[5],u=i[9],l=i[2],c=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Ws(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(c,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Ws(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,h)):(this._y=Math.atan2(-l,r),this._z=0);break;case"ZXY":this._x=Math.asin(Ws(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(-l,d),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(a,r));break;case"ZYX":this._y=Math.asin(-Ws(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(a,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(Ws(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,h),this._y=Math.atan2(-l,r)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-Ws(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,h),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-u,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return lr.makeRotationFromQuaternion(e),this.setFromRotationMatrix(lr,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return cr.setFromEuler(this),this.setFromQuaternion(cr,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}dr.DEFAULT_ORDER="XYZ";class pr{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const s=t.shapes;if(Array.isArray(s))for(let t=0,i=s.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(s.geometries=t),i.length>0&&(s.materials=i),r.length>0&&(s.textures=r),o.length>0&&(s.images=o),a.length>0&&(s.shapes=a),h.length>0&&(s.skeletons=h),u.length>0&&(s.animations=u),l.length>0&&(s.nodes=l)}return s.object=i,s;function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,s,i,r){Er.subVectors(i,t),Br.subVectors(s,t),Ir.subVectors(e,t);const n=Er.dot(Er),o=Er.dot(Br),a=Er.dot(Ir),h=Br.dot(Br),u=Br.dot(Ir),l=n*h-o*o;if(0===l)return r.set(0,0,0),null;const c=1/l,d=(h*a-o*u)*c,p=(n*u-o*a)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,Pr)&&(Pr.x>=0&&Pr.y>=0&&Pr.x+Pr.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,Pr)?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(r,Pr.x),a.addScaledVector(n,Pr.y),a.addScaledVector(o,Pr.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return Dr.setScalar(0),kr.setScalar(0),Gr.setScalar(0),Dr.fromBufferAttribute(e,t),kr.fromBufferAttribute(e,s),Gr.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Dr,r.x),n.addScaledVector(kr,r.y),n.addScaledVector(Gr,r.z),n}static isFrontFacing(e,t,s,i){return Er.subVectors(s,t),Br.subVectors(e,t),Er.cross(Br).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Er.subVectors(this.c,this.b),Br.subVectors(this.a,this.b),.5*Er.cross(Br).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Wr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Wr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Wr.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Wr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Wr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,r=this.c;let n,o;Fr.subVectors(i,s),Ur.subVectors(r,s),zr.subVectors(e,s);const a=Fr.dot(zr),h=Ur.dot(zr);if(a<=0&&h<=0)return t.copy(s);Lr.subVectors(e,i);const u=Fr.dot(Lr),l=Ur.dot(Lr);if(u>=0&&l<=u)return t.copy(i);const c=a*l-u*h;if(c<=0&&a>=0&&u<=0)return n=a/(a-u),t.copy(s).addScaledVector(Fr,n);Vr.subVectors(e,r);const d=Fr.dot(Vr),p=Ur.dot(Vr);if(p>=0&&d<=p)return t.copy(r);const m=d*h-a*p;if(m<=0&&h>=0&&p<=0)return o=h/(h-p),t.copy(s).addScaledVector(Ur,o);const g=u*p-d*l;if(g<=0&&l-u>=0&&d-p>=0)return Or.subVectors(r,i),o=(l-u)/(l-u+(d-p)),t.copy(i).addScaledVector(Or,o);const f=1/(g+m+c);return n=m*f,o=c*f,t.copy(s).addScaledVector(Fr,n).addScaledVector(Ur,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const jr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Hr={h:0,s:0,l:0},qr={h:0,s:0,l:0};function $r(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class Xr{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Zt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,ii.toWorkingColorSpace(this,t),this}setRGB(e,t,s,i=ii.workingColorSpace){return this.r=e,this.g=t,this.b=s,ii.toWorkingColorSpace(this,i),this}setHSL(e,t,s,i=ii.workingColorSpace){if(e=js(e,1),t=Ws(t,0,1),s=Ws(s,0,1),0===t)this.r=this.g=this.b=s;else{const i=s<=.5?s*(1+t):s+t-s*t,r=2*s-i;this.r=$r(r,i,e+1/3),this.g=$r(r,i,e),this.b=$r(r,i,e-1/3)}return ii.toWorkingColorSpace(this,i),this}setStyle(e,t=Zt){function s(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],o=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],r=s.length;if(3===r)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Zt){const s=jr[e.toLowerCase()];return void 0!==s?this.setHex(s,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=ri(e.r),this.g=ri(e.g),this.b=ri(e.b),this}copyLinearToSRGB(e){return this.r=ni(e.r),this.g=ni(e.g),this.b=ni(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Zt){return ii.fromWorkingColorSpace(Yr.copy(this),e),65536*Math.round(Ws(255*Yr.r,0,255))+256*Math.round(Ws(255*Yr.g,0,255))+Math.round(Ws(255*Yr.b,0,255))}getHexString(e=Zt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ii.workingColorSpace){ii.fromWorkingColorSpace(Yr.copy(this),t);const s=Yr.r,i=Yr.g,r=Yr.b,n=Math.max(s,i,r),o=Math.min(s,i,r);let a,h;const u=(o+n)/2;if(o===n)a=0,h=0;else{const e=n-o;switch(h=u<=.5?e/(n+o):e/(2-n-o),n){case s:a=(i-r)/e+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const s=e[t];if(void 0===s){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s:console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const s={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),void 0!==this.roughness&&(s.roughness=this.roughness),void 0!==this.metalness&&(s.metalness=this.metalness),void 0!==this.sheen&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(s.shininess=this.shininess),void 0!==this.clearcoat&&(s.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(s.dispersion=this.dispersion),void 0!==this.iridescence&&(s.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(s.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(s.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(s.combine=this.combine)),void 0!==this.envMapRotation&&(s.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(s.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(s.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(s.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(s.size=this.size),null!==this.shadowSide&&(s.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(s.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(s.blending=this.blending),this.side!==c&&(s.side=this.side),!0===this.vertexColors&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),!0===this.transparent&&(s.transparent=!0),this.blendSrc!==R&&(s.blendSrc=this.blendSrc),this.blendDst!==E&&(s.blendDst=this.blendDst),this.blendEquation!==v&&(s.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(s.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(s.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(s.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(s.depthFunc=this.depthFunc),!1===this.depthTest&&(s.depthTest=this.depthTest),!1===this.depthWrite&&(s.depthWrite=this.depthWrite),!1===this.colorWrite&&(s.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==gs&&(s.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(s.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ts&&(s.stencilFail=this.stencilFail),this.stencilZFail!==ts&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==ts&&(s.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(s.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(s.rotation=this.rotation),!0===this.polygonOffset&&(s.polygonOffset=!0),0!==this.polygonOffsetFactor&&(s.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(s.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(s.linewidth=this.linewidth),void 0!==this.dashSize&&(s.dashSize=this.dashSize),void 0!==this.gapSize&&(s.gapSize=this.gapSize),void 0!==this.scale&&(s.scale=this.scale),!0===this.dithering&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),!0===this.alphaHash&&(s.alphaHash=!0),!0===this.alphaToCoverage&&(s.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(s.premultipliedAlpha=!0),!0===this.forceSinglePass&&(s.forceSinglePass=!0),!0===this.wireframe&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(s.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(s.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(s.flatShading=!0),!1===this.visible&&(s.visible=!1),!1===this.toneMapped&&(s.toneMapped=!1),!1===this.fog&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(s.textures=t),r.length>0&&(s.images=r)}return s}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let s=null;if(null!==t){const e=t.length;s=new Array(e);for(let i=0;i!==e;++i)s[i]=t[i].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Kr extends Jr{static get type(){return"MeshBasicMaterial"}constructor(e){super(),this.isMeshBasicMaterial=!0,this.color=new Xr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Qr=en();function en(){const e=new ArrayBuffer(4),t=new Float32Array(e),s=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const n=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,s=0;for(;0==(8388608&t);)t<<=1,s-=8388608;t&=-8388609,s+=947912704,n[e]=t|s}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(a[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:o,offsetTable:a}}function tn(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Ws(e,-65504,65504),Qr.floatView[0]=e;const t=Qr.uint32View[0],s=t>>23&511;return Qr.baseTable[s]+((8388607&t)>>Qr.shiftTable[s])}function sn(e){const t=e>>10;return Qr.uint32View[0]=Qr.mantissaTable[Qr.offsetTable[t]+(1023&e)]+Qr.exponentTable[t],Qr.floatView[0]}const rn={toHalfFloat:tn,fromHalfFloat:sn},nn=new Ai,on=new Ys;class an{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Ss,this.updateRanges=[],this.gpuType=Ie,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,r=this.itemSize;i=0;--t)if(e[t]>=65535)return!0;return!1}(e)?mn:dn)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(void 0!==s){const t=(new Zs).getNormalMatrix(e);s.applyNormalMatrix(t),s.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return xn.makeRotationFromQuaternion(e),this.applyMatrix4(xn),this}rotateX(e){return xn.makeRotationX(e),this.applyMatrix4(xn),this}rotateY(e){return xn.makeRotationY(e),this.applyMatrix4(xn),this}rotateZ(e){return xn.makeRotationZ(e),this.applyMatrix4(xn),this}translate(e,t,s){return xn.makeTranslation(e,t,s),this.applyMatrix4(xn),this}scale(e,t,s){return xn.makeScale(e,t,s),this.applyMatrix4(xn),this}lookAt(e){return bn.lookAt(e),bn.updateMatrix(),this.applyMatrix4(bn.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(vn).negate(),this.translate(vn.x,vn.y,vn.z),this}setFromPoints(e){const t=[];for(let s=0,i=e.length;s0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const s in t)void 0!==t[s]&&(e[s]=t[s]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const t in s){const i=s[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const s=this.morphAttributes[t],n=[];for(let t=0,i=s.length;t0&&(i[t]=n,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(e.data.groups=JSON.parse(JSON.stringify(n)));const o=this.boundingSphere;return null!==o&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const s=e.index;null!==s&&this.setIndex(s.clone(t));const i=e.attributes;for(const e in i){const s=i[e];this.setAttribute(e,s.clone(t))}const r=e.morphAttributes;for(const e in r){const s=[],i=r[e];for(let e=0,r=i.length;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;e(e.far-e.near)**2)return}Mn.copy(r).invert(),An.copy(e.ray).applyMatrix4(Mn),null!==s.boundingBox&&!1===An.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,An)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,o=r.index,a=r.attributes.position,h=r.attributes.uv,u=r.attributes.uv1,l=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==o)if(Array.isArray(n))for(let r=0,a=c.length;rs.far?null:{distance:u,point:Un.clone(),object:e}}(e,t,s,i,Rn,En,Bn,Fn);if(l){const e=new Ai;Wr.getBarycoord(Fn,Rn,En,Bn,e),r&&(l.uv=Wr.getInterpolatedAttribute(r,a,h,u,e,new Ys)),n&&(l.uv1=Wr.getInterpolatedAttribute(n,a,h,u,e,new Ys)),o&&(l.normal=Wr.getInterpolatedAttribute(o,a,h,u,e,new Ai),l.normal.dot(i.direction)>0&&l.normal.multiplyScalar(-1));const t={a:a,b:h,c:u,normal:new Ai,materialIndex:0};Wr.getNormal(Rn,En,Bn,t.normal),l.face=t,l.barycoord=e}return l}class Ln extends Sn{constructor(e=1,t=1,s=1,i=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:r,depthSegments:n};const o=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const a=[],h=[],u=[],l=[];let c=0,d=0;function p(e,t,s,i,r,n,p,m,g,f,y){const x=n/g,b=p/f,v=n/2,T=p/2,_=m/2,w=g+1,S=f+1;let M=0,A=0;const N=new Ai;for(let n=0;n0?1:-1,u.push(N.x,N.y,N.z),l.push(a/g),l.push(1-n/f),M+=1}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const e in this.extensions)!0===this.extensions[e]&&(s[e]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class kn extends Rr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new sr,this.projectionMatrix=new sr,this.projectionMatrixInverse=new sr,this.coordinateSystem=Us}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Gn=new Ai,Wn=new Ys,jn=new Ys;class Hn extends kn{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*ks*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Ds*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*ks*Math.atan(Math.tan(.5*Ds*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,s){Gn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Gn.x,Gn.y).multiplyScalar(-e/Gn.z),Gn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Gn.x,Gn.y).multiplyScalar(-e/Gn.z)}getViewSize(e,t){return this.getViewBounds(e,Wn,jn),t.subVectors(jn,Wn)}setViewOffset(e,t,s,i,r,n){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*Ds*this.fov)/this.zoom,s=2*t,i=this.aspect*s,r=-.5*i;const n=this.view;if(null!==this.view&&this.view.enabled){const e=n.fullWidth,o=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/o,i*=n.width/e,s*=n.height/o}const o=this.filmOffset;0!==o&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-s,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const qn=-90;class $n extends Rr{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Hn(qn,1,e,t);i.layers=this.layers,this.add(i);const r=new Hn(qn,1,e,t);r.layers=this.layers,this.add(r);const n=new Hn(qn,1,e,t);n.layers=this.layers,this.add(n);const o=new Hn(qn,1,e,t);o.layers=this.layers,this.add(o);const a=new Hn(qn,1,e,t);a.layers=this.layers,this.add(a);const h=new Hn(qn,1,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,o,a]=t;for(const e of t)this.remove(e);if(e===Us)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else{if(e!==Os)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,n,o,a,h,u]=this.children,l=e.getRenderTarget(),c=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1,e.setRenderTarget(s,0,i),e.render(t,r),e.setRenderTarget(s,1,i),e.render(t,n),e.setRenderTarget(s,2,i),e.render(t,o),e.setRenderTarget(s,3,i),e.render(t,a),e.setRenderTarget(s,4,i),e.render(t,h),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,u),e.setRenderTarget(l,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Xn extends yi{constructor(e,t,s,i,r,n,o,a,h,u){super(e=void 0!==e?e:[],t=void 0!==t?t:he,s,i,r,n,o,a,h,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Yn extends vi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Xn(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:Te}fromEquirectangularTexture(e,t){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 s={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Ln(5,5,5),r=new Dn({name:"CubemapFromEquirect",uniforms:Vn(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:d,blending:m});r.uniforms.tEquirect.value=t;const n=new On(i,r),o=t.minFilter;t.minFilter===Se&&(t.minFilter=Te);return new $n(1,10,this).update(e,n),t.minFilter=o,n.geometry.dispose(),n.material.dispose(),this}clear(e,t,s,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}class Zn{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new Xr(e),this.density=t}clone(){return new Zn(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Jn{constructor(e,t=1,s=1e3){this.isFog=!0,this.name="",this.color=new Xr(e),this.near=t,this.far=s}clone(){return new Jn(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Kn extends Rr{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new dr,this.environmentIntensity=1,this.environmentRotation=new dr,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Qn{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Ss,this.updateRanges=[],this.version=0,this.uuid=Gs()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,s){e*=this.stride,s*=t.stride;for(let i=0,r=this.stride;ie.far||t.push({distance:a,point:ro.clone(),uv:Wr.getInterpolation(ro,lo,co,po,mo,go,fo,new Ys),face:null,object:this})}copy(e,t){return super.copy(e,t),void 0!==e.center&&this.center.copy(e.center),this.material=e.material,this}}function xo(e,t,s,i,r,n){ao.subVectors(e,s).addScalar(.5).multiply(i),void 0!==r?(ho.x=n*ao.x-r*ao.y,ho.y=r*ao.x+n*ao.y):ho.copy(ao),e.copy(t),e.x+=ho.x,e.y+=ho.y,e.applyMatrix4(uo)}const bo=new Ai,vo=new Ai;class To extends Rr{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let e=0,s=t.length;e0){let s,i;for(s=1,i=t.length;s0){bo.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(bo);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){bo.setFromMatrixPosition(e.matrixWorld),vo.setFromMatrixPosition(this.matrixWorld);const s=bo.distanceTo(vo)/e.zoom;let i,r;for(t[0].object.visible=!0,i=1,r=t.length;i=e))break;t[i-1].object.visible=!1,t[i].object.visible=!0}for(this._currentLevel=i-1;i1?null:t.copy(e.start).addScaledVector(s,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const s=t||Xo.getNormalMatrix(e),i=this.coplanarPoint(qo).applyMatrix4(e),r=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const Zo=new $i,Jo=new Ai;class Ko{constructor(e=new Yo,t=new Yo,s=new Yo,i=new Yo,r=new Yo,n=new Yo){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(s),o[3].copy(i),o[4].copy(r),o[5].copy(n),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=2e3){const s=this.planes,i=e.elements,r=i[0],n=i[1],o=i[2],a=i[3],h=i[4],u=i[5],l=i[6],c=i[7],d=i[8],p=i[9],m=i[10],g=i[11],f=i[12],y=i[13],x=i[14],b=i[15];if(s[0].setComponents(a-r,c-h,g-d,b-f).normalize(),s[1].setComponents(a+r,c+h,g+d,b+f).normalize(),s[2].setComponents(a+n,c+u,g+p,b+y).normalize(),s[3].setComponents(a-n,c-u,g-p,b-y).normalize(),s[4].setComponents(a-o,c-l,g-m,b-x).normalize(),t===Us)s[5].setComponents(a+o,c+l,g+m,b+x).normalize();else{if(t!==Os)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);s[5].setComponents(o,l,m,x).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Zo.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Zo.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Zo)}intersectsSprite(e){return Zo.center.set(0,0,0),Zo.radius=.7071067811865476,Zo.applyMatrix4(e.matrixWorld),this.intersectsSphere(Zo)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(s)0?e.max.x:e.min.x,Jo.y=i.normal.y>0?e.max.y:e.min.y,Jo.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Jo)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function Qo(e,t){return e-t}function ea(e,t){return e.z-t.z}function ta(e,t){return t.z-e.z}class sa{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t,s){const i=this.pool,r=this.list;this.index>=i.length&&i.push({start:-1,count:-1,z:-1,index:-1});const n=i[this.index];r.push(n),this.index++,n.start=e.start,n.count=e.count,n.z=t,n.index=s}reset(){this.list.length=0,this.index=0}}const ia=new sr,ra=new sr,na=new sr,oa=new Xr(1,1,1),aa=new sr,ha=new Ko,ua=new Ri,la=new $i,ca=new Ai,da=new Ai,pa=new Ai,ma=new sa,ga=new On,fa=[];function ya(e,t,s=0){const i=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){const r=e.count;for(let n=0;n65535?new Uint32Array(i):new Uint16Array(i);t.setIndex(new an(e,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(Boolean(e.getIndex())!==Boolean(t.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const s in t.attributes){if(!e.hasAttribute(s))throw new Error(`BatchedMesh: Added geometry missing "${s}". All geometries must have consistent attributes.`);const i=e.getAttribute(s),r=t.getAttribute(s);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ri);const e=this.boundingBox,t=this._drawInfo;e.makeEmpty();for(let s=0,i=t.length;s=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("BatchedMesh: Maximum item count reached.");const t={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(Qo),s=this._availableInstanceIds.shift(),this._drawInfo[s]=t):(s=this._drawInfo.length,this._drawInfo.push(t));const i=this._matricesTexture,r=i.image.data;na.toArray(r,16*s),i.needsUpdate=!0;const n=this._colorsTexture;return n&&(oa.toArray(n.image.data,4*s),n.needsUpdate=!0),s}addGeometry(e,t=-1,s=-1){this._initializeGeometry(e),this._validateGeometry(e);const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let r=null;const n=this._reservedRanges,o=this._drawRanges,a=this._bounds;0!==this._geometryCount&&(r=n[n.length-1]),i.vertexCount=-1===t?e.getAttribute("position").count:t,i.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const h=e.getIndex(),u=null!==h;if(u&&(i.indexCount=-1===s?h.count:s,i.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==i.indexStart&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const l={start:u?i.indexStart:i.vertexStart,count:-1,active:!0},c={boxInitialized:!1,box:new Ri,sphereInitialized:!1,sphere:new $i};let d;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Qo),d=this._availableGeometryIds.shift(),n[d]=i,o[d]=l,a[d]=c):(d=this._geometryCount,this._geometryCount++,n.push(i),o.push(l),a.push(c)),this.setGeometryAt(d,e),d}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const s=this.geometry,i=null!==s.getIndex(),r=s.getIndex(),n=t.getIndex(),o=this._reservedRanges[e];if(i&&n.count>o.indexCount||t.attributes.position.count>o.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const a=o.vertexStart,h=o.vertexCount;for(const e in s.attributes){const i=t.getAttribute(e),r=s.getAttribute(e);ya(i,r,a);const n=i.itemSize;for(let e=i.count,t=h;e=t.length||!1===t[e].active)return this;const s=this._drawInfo;for(let t=0,i=s.length;t=t.length||!1===t[e].active||(t[e].active=!1,this._availableInstanceIds.push(e),this._visibilityChanged=!0),this}optimize(){let e=0,t=0;const s=this._drawRanges,i=this._reservedRanges,r=this.geometry;for(let n=0,o=s.length;n=this._geometryCount)return null;const s=this._bounds[e],i=s.box,r=this.geometry;if(!1===s.boxInitialized){i.makeEmpty();const t=r.index,n=r.attributes.position,o=this._drawRanges[e];for(let e=o.start,s=o.start+o.count;e=this._geometryCount)return null;const s=this._bounds[e],i=s.sphere,r=this.geometry;if(!1===s.sphereInitialized){i.makeEmpty(),this.getBoundingBoxAt(e,ua),ua.getCenter(i.center);const t=r.index,n=r.attributes.position,o=this._drawRanges[e];let a=0;for(let e=o.start,s=o.start+o.count;e=s.length||!1===s[e].active||(t.toArray(r,16*e),i.needsUpdate=!0),this}getMatrixAt(e,t){const s=this._drawInfo,i=this._matricesTexture.image.data;return e>=s.length||!1===s[e].active?null:t.fromArray(i,16*e)}setColorAt(e,t){null===this._colorsTexture&&this._initColorsTexture();const s=this._colorsTexture,i=this._colorsTexture.image.data,r=this._drawInfo;return e>=r.length||!1===r[e].active||(t.toArray(i,4*e),s.needsUpdate=!0),this}getColorAt(e,t){const s=this._colorsTexture.image.data,i=this._drawInfo;return e>=i.length||!1===i[e].active?null:t.fromArray(s,4*e)}setVisibleAt(e,t){const s=this._drawInfo;return e>=s.length||!1===s[e].active||s[e].visible===t||(s[e].visible=t,this._visibilityChanged=!0),this}getVisibleAt(e){const t=this._drawInfo;return!(e>=t.length||!1===t[e].active)&&t[e].visible}setGeometryIdAt(e,t){const s=this._drawInfo;return e>=s.length||!1===s[e].active||t<0||t>=this._geometryCount?null:(s[e].geometryIndex=t,this)}getGeometryIdAt(e){const t=this._drawInfo;return e>=t.length||!1===t[e].active?-1:t[e].geometryIndex}getGeometryRangeAt(e,t={}){if(e<0||e>=this._geometryCount)return null;const s=this._drawRanges[e];return t.start=s.start,t.count=s.count,t}setInstanceCount(e){const t=this._availableInstanceIds,s=this._drawInfo;for(t.sort(Qo);t[t.length-1]===s.length;)s.pop(),t.pop();if(ethis._drawRanges[t].active)),i=Math.max(...s.map((e=>e.vertexStart+e.vertexCount)));if(i>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index){const e=Math.max(...s.map((e=>e.indexStart+e.indexCount)));if(e>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`)}const r=this.geometry;r.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized=!1,this.geometry=new Sn,this._initializeGeometry(r);const n=this.geometry;r.index&&xa(r.index.array,n.index.array);for(const e in r.attributes)xa(r.attributes[e].array,n.attributes[e].array)}raycast(e,t){const s=this._drawInfo,i=this._drawRanges,r=this.matrixWorld,n=this.geometry;ga.material=this.material,ga.geometry.index=n.index,ga.geometry.attributes=n.attributes,null===ga.geometry.boundingBox&&(ga.geometry.boundingBox=new Ri),null===ga.geometry.boundingSphere&&(ga.geometry.boundingSphere=new $i);for(let n=0,o=s.length;n({...e}))),this._reservedRanges=e._reservedRanges.map((e=>({...e}))),this._drawInfo=e._drawInfo.map((e=>({...e}))),this._bounds=e._bounds.map((e=>({boxInitialized:e.boxInitialized,box:e.box.clone(),sphereInitialized:e.sphereInitialized,sphere:e.sphere.clone()}))),this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(e,t,s,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const n=i.getIndex(),o=null===n?1:n.array.BYTES_PER_ELEMENT,a=this._drawInfo,h=this._multiDrawStarts,u=this._multiDrawCounts,l=this._drawRanges,c=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data;c&&(aa.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse).multiply(this.matrixWorld),ha.setFromProjectionMatrix(aa,e.coordinateSystem));let m=0;if(this.sortObjects){ra.copy(this.matrixWorld).invert(),ca.setFromMatrixPosition(s.matrixWorld).applyMatrix4(ra),da.set(0,0,-1).transformDirection(s.matrixWorld).transformDirection(ra);for(let e=0,t=a.length;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;ei)return;Aa.applyMatrix4(e.matrixWorld);const a=t.ray.origin.distanceTo(Aa);return at.far?void 0:{distance:a,point:Na.clone().applyMatrix4(e.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:e}}const Ea=new Ai,Ba=new Ai;class Ia extends Ca{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,s=[];for(let e=0,i=t.count;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;er.far)return;n.push({distance:h,distanceToRay:Math.sqrt(a),point:s,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}class ka extends Rr{constructor(){super(),this.isGroup=!0,this.type="Group"}}class Ga extends yi{constructor(e,t,s,i,r,n,o,a,h){super(e,t,s,i,r,n,o,a,h),this.isVideoTexture=!0,this.minFilter=void 0!==n?n:Te,this.magFilter=void 0!==r?r:Te,this.generateMipmaps=!1;const u=this;"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback((function t(){u.needsUpdate=!0,e.requestVideoFrameCallback(t)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;!1==="requestVideoFrameCallback"in e&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class Wa extends yi{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=fe,this.minFilter=fe,this.generateMipmaps=!1,this.needsUpdate=!0}}class ja extends yi{constructor(e,t,s,i,r,n,o,a,h,u,l,c){super(null,n,o,a,h,u,i,r,l,c),this.isCompressedTexture=!0,this.image={width:t,height:s},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class Ha extends ja{constructor(e,t,s,i,r,n){super(e,t,s,r,n),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=me,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class qa extends ja{constructor(e,t,s){super(void 0,e[0].width,e[0].height,t,s,he),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class $a extends yi{constructor(e,t,s,i,r,n,o,a,h){super(e,t,s,i,r,n,o,a,h),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Xa extends yi{constructor(e,t,s,i,r,n,o,a,h,u=1026){if(u!==We&&u!==je)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===s&&u===We&&(s=Be),void 0===s&&u===je&&(s=Oe),super(null,i,r,n,o,a,u,s,h),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==o?o:fe,this.minFilter=void 0!==a?a:fe,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class Ya{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){const s=this.getUtoTmapping(e);return this.getPoint(s,t)}getPoints(e=5){const t=[];for(let s=0;s<=e;s++)t.push(this.getPoint(s/e));return t}getSpacedPoints(e=5){const t=[];for(let s=0;s<=e;s++)t.push(this.getPointAt(s/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let s,i=this.getPoint(0),r=0;t.push(0);for(let n=1;n<=e;n++)s=this.getPoint(n/e),r+=s.distanceTo(i),t.push(r),i=s;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){const s=this.getLengths();let i=0;const r=s.length;let n;n=t||e*s[r-1];let o,a=0,h=r-1;for(;a<=h;)if(i=Math.floor(a+(h-a)/2),o=s[i]-n,o<0)a=i+1;else{if(!(o>0)){h=i;break}h=i-1}if(i=h,s[i]===n)return i/(r-1);const u=s[i];return(i+(n-u)/(s[i+1]-u))/(r-1)}getTangent(e,t){const s=1e-4;let i=e-s,r=e+s;i<0&&(i=0),r>1&&(r=1);const n=this.getPoint(i),o=this.getPoint(r),a=t||(n.isVector2?new Ys:new Ai);return a.copy(o).sub(n).normalize(),a}getTangentAt(e,t){const s=this.getUtoTmapping(e);return this.getTangent(s,t)}computeFrenetFrames(e,t){const s=new Ai,i=[],r=[],n=[],o=new Ai,a=new sr;for(let t=0;t<=e;t++){const s=t/e;i[t]=this.getTangentAt(s,new Ai)}r[0]=new Ai,n[0]=new Ai;let h=Number.MAX_VALUE;const u=Math.abs(i[0].x),l=Math.abs(i[0].y),c=Math.abs(i[0].z);u<=h&&(h=u,s.set(1,0,0)),l<=h&&(h=l,s.set(0,1,0)),c<=h&&s.set(0,0,1),o.crossVectors(i[0],s).normalize(),r[0].crossVectors(i[0],o),n[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),n[t]=n[t-1].clone(),o.crossVectors(i[t-1],i[t]),o.length()>Number.EPSILON){o.normalize();const e=Math.acos(Ws(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(a.makeRotationAxis(o,e))}n[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(Ws(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(o.crossVectors(r[0],r[e]))>0&&(t=-t);for(let s=1;s<=e;s++)r[s].applyMatrix4(a.makeRotationAxis(i[s],t*s)),n[s].crossVectors(i[s],r[s])}return{tangents:i,normals:r,binormals:n}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Za extends Ya{constructor(e=0,t=0,s=1,i=1,r=0,n=2*Math.PI,o=!1,a=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=s,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=n,this.aClockwise=o,this.aRotation=a}getPoint(e,t=new Ys){const s=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const n=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(h)/r)+1)*r:0===u&&h===r-1&&(h=r-2,u=1),this.closed||h>0?o=i[(h-1)%r]:(Qa.subVectors(i[0],i[1]).add(i[0]),o=Qa);const l=i[h%r],c=i[(h+1)%r];if(this.closed||h+2i.length-2?i.length-1:n+1],l=i[n>i.length-3?i.length-1:n+2];return s.set(rh(o,a.x,h.x,u.x,l.x),rh(o,a.y,h.y,u.y,l.y)),s}copy(e){super.copy(e),this.points=[];for(let t=0,s=e.points.length;t=s){const e=i[r]-s,n=this.curves[r],o=n.getLength(),a=0===o?0:1-e/o;return n.getPointAt(a,t)}r++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let s=0,i=this.curves.length;s1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,s=e.curves.length;t0){const e=h.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y)}this.curves.push(h);const u=h.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class yh extends Sn{constructor(e=[new Ys(0,-.5),new Ys(.5,0),new Ys(0,.5)],t=12,s=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:s,phiLength:i},t=Math.floor(t),i=Ws(i,0,2*Math.PI);const r=[],n=[],o=[],a=[],h=[],u=1/t,l=new Ai,c=new Ys,d=new Ai,p=new Ai,m=new Ai;let g=0,f=0;for(let t=0;t<=e.length-1;t++)switch(t){case 0:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,d.x=1*f,d.y=-g,d.z=0*f,m.copy(d),d.normalize(),a.push(d.x,d.y,d.z);break;case e.length-1:a.push(m.x,m.y,m.z);break;default:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,d.x=1*f,d.y=-g,d.z=0*f,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),a.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=t;r++){const d=s+r*u*i,p=Math.sin(d),m=Math.cos(d);for(let s=0;s<=e.length-1;s++){l.x=e[s].x*p,l.y=e[s].y,l.z=e[s].x*m,n.push(l.x,l.y,l.z),c.x=r/t,c.y=s/(e.length-1),o.push(c.x,c.y);const i=a[3*s+0]*p,u=a[3*s+1],d=a[3*s+0]*m;h.push(i,u,d)}}for(let s=0;s0&&(u.push(r,n,a),x+=3),t>0&&(u.push(n,o,a),x+=3)}h.addGroup(f,x,0),f+=x}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new fn(l,3)),this.setAttribute("normal",new fn(c,3)),this.setAttribute("uv",new fn(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vh(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Th extends vh{constructor(e=1,t=1,s=32,i=1,r=!1,n=0,o=2*Math.PI){super(0,e,t,s,i,r,n,o),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:s,heightSegments:i,openEnded:r,thetaStart:n,thetaLength:o}}static fromJSON(e){return new Th(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class _h extends Sn{constructor(e=[],t=[],s=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:s,detail:i};const r=[],n=[];function o(e,t,s,i){const r=i+1,n=[];for(let i=0;i<=r;i++){n[i]=[];const o=e.clone().lerp(s,i/r),a=t.clone().lerp(s,i/r),h=r-i;for(let e=0;e<=h;e++)n[i][e]=0===e&&i===r?o:o.clone().lerp(a,e/h)}for(let e=0;e.9&&o<.1&&(t<.2&&(n[e+0]+=1),s<.2&&(n[e+2]+=1),i<.2&&(n[e+4]+=1))}}()}(),this.setAttribute("position",new fn(r,3)),this.setAttribute("normal",new fn(r.slice(),3)),this.setAttribute("uv",new fn(n,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new _h(e.vertices,e.indices,e.radius,e.details)}}class wh extends _h{constructor(e=1,t=0){const s=(1+Math.sqrt(5))/2,i=1/s;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-s,0,-i,s,0,i,-s,0,i,s,-i,-s,0,-i,s,0,i,-s,0,i,s,0,-s,0,-i,s,0,-i,-s,0,i,s,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new wh(e.radius,e.detail)}}const Sh=new Ai,Mh=new Ai,Ah=new Ai,Nh=new Wr;class Ch extends Sn{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},null!==e){const s=4,i=Math.pow(10,s),r=Math.cos(Ds*t),n=e.getIndex(),o=e.getAttribute("position"),a=n?n.count:o.count,h=[0,0,0],u=["a","b","c"],l=new Array(3),c={},d=[];for(let e=0;e80*s){a=u=e[0],h=l=e[1];for(let t=s;tu&&(u=c),d>l&&(l=d);p=Math.max(u-a,l-h),p=0!==p?32767/p:0}return Ph(n,o,s,a,h,p,0),o};function Bh(e,t,s,i,r){let n,o;if(r===function(e,t,s,i){let r=0;for(let n=t,o=s-i;n0)for(n=t;n=t;n-=i)o=Kh(n,e[n],e[n+1],o);return o&&qh(o,o.next)&&(Qh(o),o=o.next),o}function Ih(e,t){if(!e)return e;t||(t=e);let s,i=e;do{if(s=!1,i.steiner||!qh(i,i.next)&&0!==Hh(i.prev,i,i.next))i=i.next;else{if(Qh(i),i=t=i.prev,i===i.next)break;s=!0}}while(s||i!==t);return t}function Ph(e,t,s,i,r,n,o){if(!e)return;!o&&n&&function(e,t,s,i){let r=e;do{0===r.z&&(r.z=kh(r.x,r.y,t,s,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,s,i,r,n,o,a,h,u=1;do{for(s=e,e=null,n=null,o=0;s;){for(o++,i=s,a=0,t=0;t0||h>0&&i;)0!==a&&(0===h||!i||s.z<=i.z)?(r=s,s=s.nextZ,a--):(r=i,i=i.nextZ,h--),n?n.nextZ=r:e=r,r.prevZ=n,n=r;s=i}n.nextZ=null,u*=2}while(o>1)}(r)}(e,i,r,n);let a,h,u=e;for(;e.prev!==e.next;)if(a=e.prev,h=e.next,n?Uh(e,i,r,n):Fh(e))t.push(a.i/s|0),t.push(e.i/s|0),t.push(h.i/s|0),Qh(e),e=h.next,u=h.next;else if((e=h)===u){o?1===o?Ph(e=Oh(Ih(e),t,s),t,s,i,r,n,2):2===o&&zh(e,t,s,i,r,n):Ph(Ih(e),t,s,i,r,n,1);break}}function Fh(e){const t=e.prev,s=e,i=e.next;if(Hh(t,s,i)>=0)return!1;const r=t.x,n=s.x,o=i.x,a=t.y,h=s.y,u=i.y,l=rn?r>o?r:o:n>o?n:o,p=a>h?a>u?a:u:h>u?h:u;let m=i.next;for(;m!==t;){if(m.x>=l&&m.x<=d&&m.y>=c&&m.y<=p&&Wh(r,a,n,h,o,u,m.x,m.y)&&Hh(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Uh(e,t,s,i){const r=e.prev,n=e,o=e.next;if(Hh(r,n,o)>=0)return!1;const a=r.x,h=n.x,u=o.x,l=r.y,c=n.y,d=o.y,p=ah?a>u?a:u:h>u?h:u,f=l>c?l>d?l:d:c>d?c:d,y=kh(p,m,t,s,i),x=kh(g,f,t,s,i);let b=e.prevZ,v=e.nextZ;for(;b&&b.z>=y&&v&&v.z<=x;){if(b.x>=p&&b.x<=g&&b.y>=m&&b.y<=f&&b!==r&&b!==o&&Wh(a,l,h,c,u,d,b.x,b.y)&&Hh(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==o&&Wh(a,l,h,c,u,d,v.x,v.y)&&Hh(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;b&&b.z>=y;){if(b.x>=p&&b.x<=g&&b.y>=m&&b.y<=f&&b!==r&&b!==o&&Wh(a,l,h,c,u,d,b.x,b.y)&&Hh(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=x;){if(v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==o&&Wh(a,l,h,c,u,d,v.x,v.y)&&Hh(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function Oh(e,t,s){let i=e;do{const r=i.prev,n=i.next.next;!qh(r,n)&&$h(r,i,i.next,n)&&Zh(r,n)&&Zh(n,r)&&(t.push(r.i/s|0),t.push(i.i/s|0),t.push(n.i/s|0),Qh(i),Qh(i.next),i=e=n),i=i.next}while(i!==e);return Ih(i)}function zh(e,t,s,i,r,n){let o=e;do{let e=o.next.next;for(;e!==o.prev;){if(o.i!==e.i&&jh(o,e)){let a=Jh(o,e);return o=Ih(o,o.next),a=Ih(a,a.next),Ph(o,t,s,i,r,n,0),void Ph(a,t,s,i,r,n,0)}e=e.next}o=o.next}while(o!==e)}function Lh(e,t){return e.x-t.x}function Vh(e,t){const s=function(e,t){let s,i=t,r=-1/0;const n=e.x,o=e.y;do{if(o<=i.y&&o>=i.next.y&&i.next.y!==i.y){const e=i.x+(o-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=n&&e>r&&(r=e,s=i.x=i.x&&i.x>=h&&n!==i.x&&Wh(os.x||i.x===s.x&&Dh(s,i)))&&(s=i,c=l)),i=i.next}while(i!==a);return s}(e,t);if(!s)return t;const i=Jh(s,e);return Ih(i,i.next),Ih(s,s.next)}function Dh(e,t){return Hh(e.prev,e,t.prev)<0&&Hh(t.next,e,e.next)<0}function kh(e,t,s,i,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Gh(e){let t=e,s=e;do{(t.x=(e-o)*(n-a)&&(e-o)*(i-a)>=(s-o)*(t-a)&&(s-o)*(n-a)>=(r-o)*(i-a)}function jh(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let s=e;do{if(s.i!==e.i&&s.next.i!==e.i&&s.i!==t.i&&s.next.i!==t.i&&$h(s,s.next,e,t))return!0;s=s.next}while(s!==e);return!1}(e,t)&&(Zh(e,t)&&Zh(t,e)&&function(e,t){let s=e,i=!1;const r=(e.x+t.x)/2,n=(e.y+t.y)/2;do{s.y>n!=s.next.y>n&&s.next.y!==s.y&&r<(s.next.x-s.x)*(n-s.y)/(s.next.y-s.y)+s.x&&(i=!i),s=s.next}while(s!==e);return i}(e,t)&&(Hh(e.prev,e,t.prev)||Hh(e,t.prev,t))||qh(e,t)&&Hh(e.prev,e,e.next)>0&&Hh(t.prev,t,t.next)>0)}function Hh(e,t,s){return(t.y-e.y)*(s.x-t.x)-(t.x-e.x)*(s.y-t.y)}function qh(e,t){return e.x===t.x&&e.y===t.y}function $h(e,t,s,i){const r=Yh(Hh(e,t,s)),n=Yh(Hh(e,t,i)),o=Yh(Hh(s,i,e)),a=Yh(Hh(s,i,t));return r!==n&&o!==a||(!(0!==r||!Xh(e,s,t))||(!(0!==n||!Xh(e,i,t))||(!(0!==o||!Xh(s,e,i))||!(0!==a||!Xh(s,t,i)))))}function Xh(e,t,s){return t.x<=Math.max(e.x,s.x)&&t.x>=Math.min(e.x,s.x)&&t.y<=Math.max(e.y,s.y)&&t.y>=Math.min(e.y,s.y)}function Yh(e){return e>0?1:e<0?-1:0}function Zh(e,t){return Hh(e.prev,e,e.next)<0?Hh(e,t,e.next)>=0&&Hh(e,e.prev,t)>=0:Hh(e,t,e.prev)<0||Hh(e,e.next,t)<0}function Jh(e,t){const s=new eu(e.i,e.x,e.y),i=new eu(t.i,t.x,t.y),r=e.next,n=t.prev;return e.next=t,t.prev=e,s.next=r,r.prev=s,i.next=s,s.prev=i,n.next=i,i.prev=n,i}function Kh(e,t,s,i){const r=new eu(e,t,s);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Qh(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function eu(e,t,s){this.i=e,this.x=t,this.y=s,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class tu{static area(e){const t=e.length;let s=0;for(let i=t-1,r=0;r2&&e[t-1].equals(e[0])&&e.pop()}function iu(e,t){for(let s=0;sNumber.EPSILON){const c=Math.sqrt(l),d=Math.sqrt(h*h+u*u),p=t.x-a/c,m=t.y+o/c,g=((s.x-u/d-p)*u-(s.y+h/d-m)*h)/(o*u-a*h);i=p+o*g-e.x,r=m+a*g-e.y;const f=i*i+r*r;if(f<=2)return new Ys(i,r);n=Math.sqrt(f/2)}else{let e=!1;o>Number.EPSILON?h>Number.EPSILON&&(e=!0):o<-Number.EPSILON?h<-Number.EPSILON&&(e=!0):Math.sign(a)===Math.sign(u)&&(e=!0),e?(i=-a,r=o,n=Math.sqrt(l)):(i=o,r=a,n=Math.sqrt(l/2))}return new Ys(i/n,r/n)}const B=[];for(let e=0,t=A.length,s=t-1,i=e+1;e=0;e--){const t=e/p,s=l*Math.cos(t*Math.PI/2),i=c*Math.sin(t*Math.PI/2)+d;for(let e=0,t=A.length;e=0;){const i=s;let r=s-1;r<0&&(r=e.length-1);for(let e=0,s=a+2*p;e0)&&d.push(t,r,h),(e!==s-1||a0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class wu extends Jr{static get type(){return"MeshPhongMaterial"}constructor(e){super(),this.isMeshPhongMaterial=!0,this.color=new Xr(16777215),this.specular=new Xr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Su extends Jr{static get type(){return"MeshToonMaterial"}constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.color=new Xr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class Mu extends Jr{static get type(){return"MeshNormalMaterial"}constructor(e){super(),this.isMeshNormalMaterial=!0,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Au extends Jr{static get type(){return"MeshLambertMaterial"}constructor(e){super(),this.isMeshLambertMaterial=!0,this.color=new Xr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Nu extends Jr{static get type(){return"MeshDepthMaterial"}constructor(e){super(),this.isMeshDepthMaterial=!0,this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Cu extends Jr{static get type(){return"MeshDistanceMaterial"}constructor(e){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class Ru extends Jr{static get type(){return"MeshMatcapMaterial"}constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.color=new Xr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Eu extends va{static get type(){return"LineDashedMaterial"}constructor(e){super(),this.isLineDashedMaterial=!0,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function Bu(e,t,s){return!e||!s&&e.constructor===t?e:"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e)}function Iu(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Pu(e){const t=e.length,s=new Array(t);for(let e=0;e!==t;++e)s[e]=e;return s.sort((function(t,s){return e[t]-e[s]})),s}function Fu(e,t,s){const i=e.length,r=new e.constructor(i);for(let n=0,o=0;o!==i;++n){const i=s[n]*t;for(let s=0;s!==t;++s)r[o++]=e[i+s]}return r}function Uu(e,t,s,i){let r=1,n=e[0];for(;void 0!==n&&void 0===n[i];)n=e[r++];if(void 0===n)return;let o=n[i];if(void 0!==o)if(Array.isArray(o))do{o=n[i],void 0!==o&&(t.push(n.time),s.push.apply(s,o)),n=e[r++]}while(void 0!==n);else if(void 0!==o.toArray)do{o=n[i],void 0!==o&&(t.push(n.time),o.toArray(s,s.length)),n=e[r++]}while(void 0!==n);else do{o=n[i],void 0!==o&&(t.push(n.time),s.push(o)),n=e[r++]}while(void 0!==n)}const Ou={convertArray:Bu,isTypedArray:Iu,getKeyframeOrder:Pu,sortedArray:Fu,flattenJSON:Uu,subclip:function(e,t,s,i,r=30){const n=e.clone();n.name=t;const o=[];for(let e=0;e=i)){h.push(t.times[e]);for(let s=0;sn.tracks[e].times[0]&&(a=n.tracks[e].times[0]);for(let e=0;e=i.times[c]){const e=c*h+a,t=e+h-a;d=i.values.slice(e,t)}else{const e=i.createInterpolant(),t=a,s=h-a;e.evaluate(n),d=e.resultBuffer.slice(t,s)}if("quaternion"===r){(new Mi).fromArray(d).normalize().conjugate().toArray(d)}const p=o.times.length;for(let e=0;e=r)break e;{const o=t[1];e=r)break t}n=s,s=0}}for(;s>>1;et;)--n;if(++n,0!==r||n!==i){r>=n&&(n=Math.max(n,1),r=n-1);const e=this.getValueSize();this.times=s.slice(r,n),this.values=this.values.slice(r*e,n*e)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const s=this.times,i=this.values,r=s.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let n=null;for(let t=0;t!==r;t++){const i=s[t];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,t,i),e=!1;break}if(null!==n&&n>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,t,i,n),e=!1;break}n=i}if(void 0!==i&&Iu(i))for(let t=0,s=i.length;t!==s;++t){const s=i[t];if(isNaN(s)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,t,s),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),s=this.getValueSize(),i=this.getInterpolation()===Ft,r=e.length-1;let n=1;for(let o=1;o0){e[n]=e[r];for(let e=r*s,i=n*s,o=0;o!==s;++o)t[i+o]=t[e+o];++n}return n!==e.length?(this.times=e.slice(0,n),this.values=t.slice(0,n*s)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),s=new(0,this.constructor)(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}ku.prototype.TimeBufferType=Float32Array,ku.prototype.ValueBufferType=Float32Array,ku.prototype.DefaultInterpolation=Pt;class Gu extends ku{constructor(e,t,s){super(e,t,s)}}Gu.prototype.ValueTypeName="bool",Gu.prototype.ValueBufferType=Array,Gu.prototype.DefaultInterpolation=It,Gu.prototype.InterpolantFactoryMethodLinear=void 0,Gu.prototype.InterpolantFactoryMethodSmooth=void 0;class Wu extends ku{}Wu.prototype.ValueTypeName="color";class ju extends ku{}ju.prototype.ValueTypeName="number";class Hu extends zu{constructor(e,t,s,i){super(e,t,s,i)}interpolate_(e,t,s,i){const r=this.resultBuffer,n=this.sampleValues,o=this.valueSize,a=(s-t)/(i-t);let h=e*o;for(let e=h+o;h!==e;h+=4)Mi.slerpFlat(r,0,n,h-o,n,h,a);return r}}class qu extends ku{InterpolantFactoryMethodLinear(e){return new Hu(this.times,this.values,this.getValueSize(),e)}}qu.prototype.ValueTypeName="quaternion",qu.prototype.InterpolantFactoryMethodSmooth=void 0;class $u extends ku{constructor(e,t,s){super(e,t,s)}}$u.prototype.ValueTypeName="string",$u.prototype.ValueBufferType=Array,$u.prototype.DefaultInterpolation=It,$u.prototype.InterpolantFactoryMethodLinear=void 0,$u.prototype.InterpolantFactoryMethodSmooth=void 0;class Xu extends ku{}Xu.prototype.ValueTypeName="vector";class Yu{constructor(e="",t=-1,s=[],i=2500){this.name=e,this.tracks=s,this.duration=t,this.blendMode=i,this.uuid=Gs(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],s=e.tracks,i=1/(e.fps||1);for(let e=0,r=s.length;e!==r;++e)t.push(Zu(s[e]).scale(i));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){const t=[],s=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let e=0,i=s.length;e!==i;++e)t.push(ku.toJSON(s[e]));return i}static CreateFromMorphTargetSequence(e,t,s,i){const r=t.length,n=[];for(let e=0;e1){const e=n[1];let t=i[e];t||(i[e]=t=[]),t.push(s)}}const n=[];for(const e in i)n.push(this.CreateFromMorphTargetSequence(e,i[e],t,s));return n}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const s=function(e,t,s,i,r){if(0!==s.length){const n=[],o=[];Uu(s,n,o,i),0!==n.length&&r.push(new e(t,n,o))}},i=[],r=e.name||"default",n=e.fps||30,o=e.blendMode;let a=e.length||-1;const h=e.hierarchy||[];for(let e=0;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==tl[e])return void tl[e].push({onLoad:t,onProgress:s,onError:i});tl[e]=[],tl[e].push({onLoad:t,onProgress:s,onError:i});const n=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),o=this.mimeType,a=this.responseType;fetch(n).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body||void 0===t.body.getReader)return t;const s=tl[e],i=t.body.getReader(),r=t.headers.get("X-File-Size")||t.headers.get("Content-Length"),n=r?parseInt(r):0,o=0!==n;let a=0;const h=new ReadableStream({start(e){!function t(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:o,loaded:a,total:n});for(let e=0,t=s.length;e{e.error(t)}))}()}});return new Response(h)}throw new sl(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)})).then((e=>{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,o)));case"json":return e.json();default:if(void 0===o)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(o),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Ju.add(e,t);const s=tl[e];delete tl[e];for(let e=0,i=s.length;e{const s=tl[e];if(void 0===s)throw this.manager.itemError(e),t;delete tl[e];for(let e=0,i=s.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class rl extends el{constructor(e){super(e)}load(e,t,s,i){const r=this,n=new il(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(e,(function(s){try{t(r.parse(JSON.parse(s)))}catch(t){i?i(t):console.error(t),r.manager.itemError(e)}}),s,i)}parse(e){const t=[];for(let s=0;s0:i.vertexColors=e.vertexColors),void 0!==e.uniforms)for(const t in e.uniforms){const r=e.uniforms[t];switch(i.uniforms[t]={},r.type){case"t":i.uniforms[t].value=s(r.value);break;case"c":i.uniforms[t].value=(new Xr).setHex(r.value);break;case"v2":i.uniforms[t].value=(new Ys).fromArray(r.value);break;case"v3":i.uniforms[t].value=(new Ai).fromArray(r.value);break;case"v4":i.uniforms[t].value=(new xi).fromArray(r.value);break;case"m3":i.uniforms[t].value=(new Zs).fromArray(r.value);break;case"m4":i.uniforms[t].value=(new sr).fromArray(r.value);break;default:i.uniforms[t].value=r.value}}if(void 0!==e.defines&&(i.defines=e.defines),void 0!==e.vertexShader&&(i.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(i.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(i.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)i.extensions[t]=e.extensions[t];if(void 0!==e.lights&&(i.lights=e.lights),void 0!==e.clipping&&(i.clipping=e.clipping),void 0!==e.size&&(i.size=e.size),void 0!==e.sizeAttenuation&&(i.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(i.map=s(e.map)),void 0!==e.matcap&&(i.matcap=s(e.matcap)),void 0!==e.alphaMap&&(i.alphaMap=s(e.alphaMap)),void 0!==e.bumpMap&&(i.bumpMap=s(e.bumpMap)),void 0!==e.bumpScale&&(i.bumpScale=e.bumpScale),void 0!==e.normalMap&&(i.normalMap=s(e.normalMap)),void 0!==e.normalMapType&&(i.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),i.normalScale=(new Ys).fromArray(t)}return void 0!==e.displacementMap&&(i.displacementMap=s(e.displacementMap)),void 0!==e.displacementScale&&(i.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(i.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(i.roughnessMap=s(e.roughnessMap)),void 0!==e.metalnessMap&&(i.metalnessMap=s(e.metalnessMap)),void 0!==e.emissiveMap&&(i.emissiveMap=s(e.emissiveMap)),void 0!==e.emissiveIntensity&&(i.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(i.specularMap=s(e.specularMap)),void 0!==e.specularIntensityMap&&(i.specularIntensityMap=s(e.specularIntensityMap)),void 0!==e.specularColorMap&&(i.specularColorMap=s(e.specularColorMap)),void 0!==e.envMap&&(i.envMap=s(e.envMap)),void 0!==e.envMapRotation&&i.envMapRotation.fromArray(e.envMapRotation),void 0!==e.envMapIntensity&&(i.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(i.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(i.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(i.lightMap=s(e.lightMap)),void 0!==e.lightMapIntensity&&(i.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(i.aoMap=s(e.aoMap)),void 0!==e.aoMapIntensity&&(i.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(i.gradientMap=s(e.gradientMap)),void 0!==e.clearcoatMap&&(i.clearcoatMap=s(e.clearcoatMap)),void 0!==e.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=s(e.clearcoatRoughnessMap)),void 0!==e.clearcoatNormalMap&&(i.clearcoatNormalMap=s(e.clearcoatNormalMap)),void 0!==e.clearcoatNormalScale&&(i.clearcoatNormalScale=(new Ys).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(i.iridescenceMap=s(e.iridescenceMap)),void 0!==e.iridescenceThicknessMap&&(i.iridescenceThicknessMap=s(e.iridescenceThicknessMap)),void 0!==e.transmissionMap&&(i.transmissionMap=s(e.transmissionMap)),void 0!==e.thicknessMap&&(i.thicknessMap=s(e.thicknessMap)),void 0!==e.anisotropyMap&&(i.anisotropyMap=s(e.anisotropyMap)),void 0!==e.sheenColorMap&&(i.sheenColorMap=s(e.sheenColorMap)),void 0!==e.sheenRoughnessMap&&(i.sheenRoughnessMap=s(e.sheenRoughnessMap)),i}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return El.createMaterialFromType(e)}static createMaterialFromType(e){return new{ShadowMaterial:bu,SpriteMaterial:so,RawShaderMaterial:vu,ShaderMaterial:Dn,PointsMaterial:Fa,MeshPhysicalMaterial:_u,MeshStandardMaterial:Tu,MeshPhongMaterial:wu,MeshToonMaterial:Su,MeshNormalMaterial:Mu,MeshLambertMaterial:Au,MeshDepthMaterial:Nu,MeshDistanceMaterial:Cu,MeshBasicMaterial:Kr,MeshMatcapMaterial:Ru,LineDashedMaterial:Eu,LineBasicMaterial:va,Material:Jr}[e]}}class Bl{static decodeText(e){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0,i=e.length;s0){const s=new Ku(t);r=new ol(s),r.setCrossOrigin(this.crossOrigin);for(let t=0,s=e.length;t0){i=new ol(this.manager),i.setCrossOrigin(this.crossOrigin);for(let t=0,i=e.length;t{const t=new Ri;t.min.fromArray(e.boxMin),t.max.fromArray(e.boxMax);const s=new $i;return s.radius=e.sphereRadius,s.center.fromArray(e.sphereCenter),{boxInitialized:e.boxInitialized,box:t,sphereInitialized:e.sphereInitialized,sphere:s}})),n._maxInstanceCount=e.maxInstanceCount,n._maxVertexCount=e.maxVertexCount,n._maxIndexCount=e.maxIndexCount,n._geometryInitialized=e.geometryInitialized,n._geometryCount=e.geometryCount,n._matricesTexture=l(e.matricesTexture.uuid),void 0!==e.colorsTexture&&(n._colorsTexture=l(e.colorsTexture.uuid));break;case"LOD":n=new To;break;case"Line":n=new Ca(h(e.geometry),u(e.material));break;case"LineLoop":n=new Pa(h(e.geometry),u(e.material));break;case"LineSegments":n=new Ia(h(e.geometry),u(e.material));break;case"PointCloud":case"Points":n=new Va(h(e.geometry),u(e.material));break;case"Sprite":n=new yo(u(e.material));break;case"Group":n=new ka;break;case"Bone":n=new Io;break;default:n=new Rr}if(n.uuid=e.uuid,void 0!==e.name&&(n.name=e.name),void 0!==e.matrix?(n.matrix.fromArray(e.matrix),void 0!==e.matrixAutoUpdate&&(n.matrixAutoUpdate=e.matrixAutoUpdate),n.matrixAutoUpdate&&n.matrix.decompose(n.position,n.quaternion,n.scale)):(void 0!==e.position&&n.position.fromArray(e.position),void 0!==e.rotation&&n.rotation.fromArray(e.rotation),void 0!==e.quaternion&&n.quaternion.fromArray(e.quaternion),void 0!==e.scale&&n.scale.fromArray(e.scale)),void 0!==e.up&&n.up.fromArray(e.up),void 0!==e.castShadow&&(n.castShadow=e.castShadow),void 0!==e.receiveShadow&&(n.receiveShadow=e.receiveShadow),e.shadow&&(void 0!==e.shadow.intensity&&(n.shadow.intensity=e.shadow.intensity),void 0!==e.shadow.bias&&(n.shadow.bias=e.shadow.bias),void 0!==e.shadow.normalBias&&(n.shadow.normalBias=e.shadow.normalBias),void 0!==e.shadow.radius&&(n.shadow.radius=e.shadow.radius),void 0!==e.shadow.mapSize&&n.shadow.mapSize.fromArray(e.shadow.mapSize),void 0!==e.shadow.camera&&(n.shadow.camera=this.parseObject(e.shadow.camera))),void 0!==e.visible&&(n.visible=e.visible),void 0!==e.frustumCulled&&(n.frustumCulled=e.frustumCulled),void 0!==e.renderOrder&&(n.renderOrder=e.renderOrder),void 0!==e.userData&&(n.userData=e.userData),void 0!==e.layers&&(n.layers.mask=e.layers),void 0!==e.children){const o=e.children;for(let e=0;e{t&&t(s),r.manager.itemEnd(e)})).catch((e=>{i&&i(e)})):(setTimeout((function(){t&&t(n),r.manager.itemEnd(e)}),0),n);const o={};o.credentials="anonymous"===this.crossOrigin?"same-origin":"include",o.headers=this.requestHeader;const a=fetch(e,o).then((function(e){return e.blob()})).then((function(e){return createImageBitmap(e,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(s){return Ju.add(e,s),t&&t(s),r.manager.itemEnd(e),s})).catch((function(t){i&&i(t),Ju.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)}));Ju.add(e,a),r.manager.itemStart(e)}}let Vl;class Dl{static getContext(){return void 0===Vl&&(Vl=new(window.AudioContext||window.webkitAudioContext)),Vl}static setContext(e){Vl=e}}class kl extends el{constructor(e){super(e)}load(e,t,s,i){const r=this,n=new il(this.manager);function o(t){i?i(t):console.error(t),r.manager.itemError(e)}n.setResponseType("arraybuffer"),n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(e,(function(e){try{const s=e.slice(0);Dl.getContext().decodeAudioData(s,(function(e){t(e)})).catch(o)}catch(e){o(e)}}),s,i)}}const Gl=new sr,Wl=new sr,jl=new sr;class Hl{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Hn,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Hn,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,jl.copy(e.projectionMatrix);const s=t.eyeSep/2,i=s*t.near/t.focus,r=t.near*Math.tan(Ds*t.fov*.5)/t.zoom;let n,o;Wl.elements[12]=-s,Gl.elements[12]=s,n=-r*t.aspect+i,o=r*t.aspect+i,jl.elements[0]=2*t.near/(o-n),jl.elements[8]=(o+n)/(o-n),this.cameraL.projectionMatrix.copy(jl),n=-r*t.aspect-i,o=r*t.aspect-i,jl.elements[0]=2*t.near/(o-n),jl.elements[8]=(o+n)/(o-n),this.cameraR.projectionMatrix.copy(jl)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Wl),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Gl)}}class ql extends Hn{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class $l{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Xl(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=Xl();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Xl(){return performance.now()}const Yl=new Ai,Zl=new Mi,Jl=new Ai,Kl=new Ai;class Ql extends Rr{constructor(){super(),this.type="AudioListener",this.context=Dl.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new $l}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener,s=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Yl,Zl,Jl),Kl.set(0,0,-1).applyQuaternion(Zl),t.positionX){const e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Yl.x,e),t.positionY.linearRampToValueAtTime(Yl.y,e),t.positionZ.linearRampToValueAtTime(Yl.z,e),t.forwardX.linearRampToValueAtTime(Kl.x,e),t.forwardY.linearRampToValueAtTime(Kl.y,e),t.forwardZ.linearRampToValueAtTime(Kl.z,e),t.upX.linearRampToValueAtTime(s.x,e),t.upY.linearRampToValueAtTime(s.y,e),t.upZ.linearRampToValueAtTime(s.z,e)}else t.setPosition(Yl.x,Yl.y,Yl.z),t.setOrientation(Kl.x,Kl.y,Kl.z,s.x,s.y,s.z)}}class ec extends Rr{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(!0===this.isPlaying)return void console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.Audio: this Audio has no playback control.");this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;console.warn("THREE.Audio: this Audio has no playback control.")}stop(e=0){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this;console.warn("THREE.Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(s,i,this._addIndex*t,1,t);for(let e=t,r=t+t;e!==r;++e)if(s[e]!==s[e+t]){o.setValue(s,i);break}}saveOriginalState(){const e=this.binding,t=this.buffer,s=this.valueSize,i=s*this._origIndex;e.getValue(t,i);for(let e=s,r=i;e!==r;++e)t[e]=t[i+e%s];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=3*this.valueSize;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let s=e;s=.5)for(let i=0;i!==r;++i)e[t+i]=e[s+i]}_slerp(e,t,s,i){Mi.slerpFlat(e,t,e,t,e,s,i)}_slerpAdditive(e,t,s,i,r){const n=this._workIndex*r;Mi.multiplyQuaternionsFlat(e,n,e,t,e,s),Mi.slerpFlat(e,t,e,t,e,n,i)}_lerp(e,t,s,i,r){const n=1-i;for(let o=0;o!==r;++o){const r=t+o;e[r]=e[r]*n+e[s+o]*i}}_lerpAdditive(e,t,s,i,r){for(let n=0;n!==r;++n){const r=t+n;e[r]=e[r]+e[s+n]*i}}}const hc="\\[\\]\\.:\\/",uc=new RegExp("["+hc+"]","g"),lc="[^"+hc+"]",cc="[^"+hc.replace("\\.","")+"]",dc=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",lc)+/(WCOD+)?/.source.replace("WCOD",cc)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",lc)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",lc)+"$"),pc=["material","materials","bones","map"];class mc{constructor(e,t,s){this.path=t,this.parsedPath=s||mc.parseTrackName(t),this.node=mc.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,s){return e&&e.isAnimationObjectGroup?new mc.Composite(e,t,s):new mc(e,t,s)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(uc,"")}static parseTrackName(e){const t=dc.exec(e);if(null===t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const s={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=s.nodeName&&s.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const e=s.nodeName.substring(i+1);-1!==pc.indexOf(e)&&(s.nodeName=s.nodeName.substring(0,i),s.objectName=e)}if(null===s.propertyName||0===s.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return s}static findNode(e,t){if(void 0===t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const s=e.skeleton.getBoneByName(t);if(void 0!==s)return s}if(e.children){const s=function(e){for(let i=0;i=r){const n=r++,u=e[n];t[u.uuid]=h,e[h]=u,t[a]=n,e[n]=o;for(let e=0,t=i;e!==t;++e){const t=s[e],i=t[n],r=t[h];t[h]=i,t[n]=r}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,s=this._bindings,i=s.length;let r=this.nCachedObjects_,n=e.length;for(let o=0,a=arguments.length;o!==a;++o){const a=arguments[o].uuid,h=t[a];if(void 0!==h)if(delete t[a],h0&&(t[o.uuid]=h),e[h]=o,e.pop();for(let e=0,t=i;e!==t;++e){const t=s[e];t[h]=t[r],t.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const s=this._bindingsIndicesByPath;let i=s[e];const r=this._bindings;if(void 0!==i)return r[i];const n=this._paths,o=this._parsedPaths,a=this._objects,h=a.length,u=this.nCachedObjects_,l=new Array(h);i=r.length,s[e]=i,n.push(e),o.push(t),r.push(l);for(let s=u,i=a.length;s!==i;++s){const i=a[s];l[s]=new mc(i,e,t)}return l}unsubscribe_(e){const t=this._bindingsIndicesByPath,s=t[e];if(void 0!==s){const i=this._paths,r=this._parsedPaths,n=this._bindings,o=n.length-1,a=n[o];t[e[o]]=s,n[s]=a,n.pop(),r[s]=r[o],r.pop(),i[s]=i[o],i.pop()}}}class fc{constructor(e,t,s=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=s,this.blendMode=i;const r=t.tracks,n=r.length,o=new Array(n),a={endingStart:Ut,endingEnd:Ut};for(let e=0;e!==n;++e){const t=r[e].createInterpolant(null);o[e]=t,t.settings=a}this._interpolantSettings=a,this._interpolants=o,this._propertyBindings=new Array(n),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,s){if(e.fadeOut(t),this.fadeIn(t),s){const s=this._clip.duration,i=e._clip.duration,r=i/s,n=s/i;e.warp(1,r,t),this.warp(n,1,t)}return this}crossFadeTo(e,t,s){return e.crossFadeFrom(this,t,s)}stopFading(){const e=this._weightInterpolant;return null!==e&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,s){const i=this._mixer,r=i.time,n=this.timeScale;let o=this._timeScaleInterpolant;null===o&&(o=i._lendControlInterpolant(),this._timeScaleInterpolant=o);const a=o.parameterPositions,h=o.sampleValues;return a[0]=r,a[1]=r+s,h[0]=e/n,h[1]=t/n,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,s,i){if(!this.enabled)return void this._updateWeight(e);const r=this._startTime;if(null!==r){const i=(e-r)*s;i<0||0===s?t=0:(this._startTime=null,t=s*i)}t*=this._updateTimeScale(e);const n=this._updateTime(t),o=this._updateWeight(e);if(o>0){const e=this._interpolants,t=this._propertyBindings;if(this.blendMode===Vt)for(let s=0,i=e.length;s!==i;++s)e[s].evaluate(n),t[s].accumulateAdditive(o);else for(let s=0,r=e.length;s!==r;++s)e[s].evaluate(n),t[s].accumulate(i,o)}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const s=this._weightInterpolant;if(null!==s){const i=s.evaluate(e)[0];t*=i,e>s.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const s=this._timeScaleInterpolant;if(null!==s){t*=s.evaluate(e)[0],e>s.parameterPositions[1]&&(this.stopWarping(),0===t?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,s=this.loop;let i=this.time+e,r=this._loopCount;const n=2202===s;if(0===e)return-1===r?i:n&&1==(1&r)?t-i:i;if(2200===s){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else{if(!(i<0)){this.time=i;break e}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(-1===r&&(e>=0?(r=0,this._setEndings(!0,0===this.repetitions,n)):this._setEndings(0===this.repetitions,!0,n)),i>=t||i<0){const s=Math.floor(i/t);i-=t*s,r+=Math.abs(s);const o=this.repetitions-r;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(1===o){const t=e<0;this._setEndings(t,!t,n)}else this._setEndings(!1,!1,n);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:s})}}else this.time=i;if(n&&1==(1&r))return t-i}return i}_setEndings(e,t,s){const i=this._interpolantSettings;s?(i.endingStart=Ot,i.endingEnd=Ot):(i.endingStart=e?this.zeroSlopeAtStart?Ot:Ut:zt,i.endingEnd=t?this.zeroSlopeAtEnd?Ot:Ut:zt)}_scheduleFading(e,t,s){const i=this._mixer,r=i.time;let n=this._weightInterpolant;null===n&&(n=i._lendControlInterpolant(),this._weightInterpolant=n);const o=n.parameterPositions,a=n.sampleValues;return o[0]=r,a[0]=t,o[1]=r+e,a[1]=s,this}}const yc=new Float32Array(1);class xc extends zs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const s=e._localRoot||this._root,i=e._clip.tracks,r=i.length,n=e._propertyBindings,o=e._interpolants,a=s.uuid,h=this._bindingsByRootAndName;let u=h[a];void 0===u&&(u={},h[a]=u);for(let e=0;e!==r;++e){const r=i[e],h=r.name;let l=u[h];if(void 0!==l)++l.referenceCount,n[e]=l;else{if(l=n[e],void 0!==l){null===l._cacheIndex&&(++l.referenceCount,this._addInactiveBinding(l,a,h));continue}const i=t&&t._propertyBindings[e].binding.parsedPath;l=new ac(mc.create(s,h,i),r.ValueTypeName,r.getValueSize()),++l.referenceCount,this._addInactiveBinding(l,a,h),n[e]=l}o[e].resultBuffer=l.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,s=e._clip.uuid,i=this._actionsByClip[s];this._bindAction(e,i&&i.knownActions[0]),this._addInactiveAction(e,s,t)}const t=e._propertyBindings;for(let e=0,s=t.length;e!==s;++e){const s=t[e];0==s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,s=t.length;e!==s;++e){const s=t[e];0==--s.useCount&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return null!==t&&t=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,s=this._nActiveActions,i=this.time+=e,r=Math.sign(e),n=this._accuIndex^=1;for(let o=0;o!==s;++o){t[o]._update(i,e,r,n)}const o=this._bindings,a=this._nActiveBindings;for(let e=0;e!==a;++e)o[e].apply(n);return this}setTime(e){this.time=0;for(let e=0;e=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bc).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Pc=new Ai,Fc=new Ai;class Uc{constructor(e=new Ai,t=new Ai){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){Pc.subVectors(e,this.start),Fc.subVectors(this.end,this.start);const s=Fc.dot(Fc);let i=Fc.dot(Pc)/s;return t&&(i=Ws(i,0,1)),i}closestPointToPoint(e,t,s){const i=this.closestPointToPointParameter(e,t);return this.delta(s).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const Oc=new Ai;class zc extends Rr{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const s=new Sn,i=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let e=0,t=1,s=32;e1)for(let s=0;s.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{hd.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(hd,t)}}setLength(e,t=.2*e,s=.2*t){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(s,t,s),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class dd extends Ia{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],s=new Sn;s.setAttribute("position",new fn(t,3)),s.setAttribute("color",new fn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(s,new va({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(e,t,s){const i=new Xr,r=this.geometry.attributes.color.array;return i.set(e),i.toArray(r,0),i.toArray(r,3),i.set(t),i.toArray(r,6),i.toArray(r,9),i.set(s),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class pd{constructor(){this.type="ShapePath",this.color=new Xr,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new fh,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,s,i){return this.currentPath.quadraticCurveTo(e,t,s,i),this}bezierCurveTo(e,t,s,i,r,n){return this.currentPath.bezierCurveTo(e,t,s,i,r,n),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(e,t){const s=t.length;let i=!1;for(let r=s-1,n=0;nNumber.EPSILON){if(h<0&&(s=t[n],a=-a,o=t[r],h=-h),e.yo.y)continue;if(e.y===s.y){if(e.x===s.x)return!0}else{const t=h*(e.x-s.x)-a*(e.y-s.y);if(0===t)return!0;if(t<0)continue;i=!i}}else{if(e.y!==s.y)continue;if(o.x<=e.x&&e.x<=s.x||s.x<=e.x&&e.x<=o.x)return!0}}return i}const s=tu.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,n,o;const a=[];if(1===i.length)return n=i[0],o=new Rh,o.curves=n.curves,a.push(o),a;let h=!s(i[0].getPoints());h=e?!h:h;const u=[],l=[];let c,d,p=[],m=0;l[m]=void 0,p[m]=[];for(let t=0,o=i.length;t1){let e=!1,s=0;for(let e=0,t=l.length;e0&&!1===e&&(p=u)}for(let e=0,t=l.length;e>>16,2246822507),s^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(s^s>>>13,3266489909),4294967296*(2097151&i)+(s>>>0)}const bd=e=>xd(e),vd=e=>xd(e),Td=(...e)=>xd(e);function _d(e,t=!1){const s=[];!0===e.isNode&&(s.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of wd(e))s.push(s,xd(i.slice(0,-4)),r.getCacheKey(t));return xd(s)}function*wd(e,t=!1){for(const s in e){if(!0===s.startsWith("_"))continue;const i=e[s];if(!0===Array.isArray(i))for(let e=0;ee.charCodeAt(0))).buffer}var Cd=Object.freeze({__proto__:null,arrayBufferToBase64:Ad,base64ToArrayBuffer:Nd,getCacheKey:_d,getNodeChildren:wd,getValueFromType:Md,getValueType:Sd,hash:Td,hashArray:vd,hashString:bd});const Rd={VERTEX:"vertex",FRAGMENT:"fragment"},Ed={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Bd={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Id=["fragment","vertex"],Pd=["setup","analyze","generate"],Fd=[...Id,"compute"],Ud=["x","y","z","w"];let Od=0;class zd extends zs{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Ed.NONE,this.updateBeforeType=Ed.NONE,this.updateAfterType=Ed.NONE,this.uuid=Xs.generateUUID(),this.version=0,this._cacheKey=null,this._cacheKeyVersion=0,this.global=!1,this.isNode=!0,Object.defineProperty(this,"id",{value:Od++})}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.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Ed.FRAME)}onRenderUpdate(e){return this.onUpdate(e,Ed.RENDER)}onObjectUpdate(e){return this.onUpdate(e,Ed.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of wd(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=_d(this,e),this._cacheKeyVersion=this.version),this._cacheKey}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)}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}setup(e){const t=e.getNodeProperties(this);let s=0;for(const e of this.getChildren())t["node"+s++]=e;return null}analyze(e){if(1===e.increaseUsage(this)){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){e.stack.nodes.length;t.initialized=!0,t.outputNode=this.setup(e),null!==t.outputNode&&e.stack.nodes.length;for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const s=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i?(i=this.generate(e)||"",r.snippet=i):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),i=e.format(i,s,t)}else i=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),i}getSerializeChildren(){return wd(this)}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:r,childNode:n}of t)void 0!==r?(void 0===s[i]&&(s[i]=Number.isInteger(r)?[]:{}),s[i][r]=n.toJSON(e.meta).uuid):s[i]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const r of e.inputNodes[s])i.push(t[r]);this[s]=i}else if("object"==typeof e.inputNodes[s]){const i={};for(const r in e.inputNodes[s]){const n=e.inputNodes[s][r];i[r]=t[n]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:s,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=n(e.textures),s=n(e.images),i=n(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),i.length>0&&(r.nodes=i)}return r}}class Ld extends zd{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){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}class Vd extends zd{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(i)||(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),r=s.build(e,i);return e.format(r,i,t)}}class Dd extends zd{static get type(){return"TempNode"}constructor(e){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,s,t);if("void"!==s&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,s),n=e.getVarFromNode(this,null,s),o=e.getPropertyName(n);return e.addLineFlowCode(`${o} = ${r}`,this),i.snippet=r,i.propertyName=o,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class kd extends Dd{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,s)=>t+e.getTypeLength(s.getNodeType(e))),0))}generate(e,t){const s=this.getNodeType(e),i=this.nodes,r=e.getComponentType(s),n=[];for(const t of i){let s=t.build(e);const i=e.getComponentType(t.getNodeType(e));i!==r&&(s=e.format(s,i,r)),n.push(s)}const o=`${e.getType(s)}( ${n.join(", ")} )`;return e.format(o,s,t)}}const Gd=Ud.join("");class Wd extends zd{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(Ud.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))}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let r=null;if(i>1){let n=null;this.getVectorLength()>=i&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const o=s.build(e,n);r=this.components.length===i&&this.components===Gd.slice(0,this.components.length)?e.format(o,n,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else r=s.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class jd extends Dd{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,r=this.getNodeType(e),n=e.getTypeFromLength(s.length,i.getNodeType(e)),o=i.build(e,n),a=t.build(e,r),h=e.getTypeLength(r),u=[];for(let e=0;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Kd=e=>Jd(e).split("").sort().join(""),Qd={setup(e,t){const s=t.shift();return e(Sp(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Xd.assign(s,...e),s);if(Yd.has(t)){const i=Yd.get(t);return e.isStackNode?(...e)=>s.add(i(...e)):(...e)=>i(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Yd.has(t.slice(0,t.length-6))){const i=Yd.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>s.assign(e[0],i(...e)):(...e)=>s.assign(i(s,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=Jd(t),wp(new Wd(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Kd(t.slice(3).toLowerCase()),s=>wp(new jd(e,t,s));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Kd(t.slice(4).toLowerCase()),()=>wp(new Hd(wp(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),wp(new Wd(e,t));if(!0===/^\d+$/.test(t))return wp(new Ld(s,new $d(Number(t),"uint")))}return Reflect.get(e,t,s)},set:(e,t,s,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,s,i):(i[t].assign(s),!0)},ep=new WeakMap,tp=new WeakMap,sp=function(e,t=null){for(const s in e)e[s]=wp(e[s],t);return e},ip=function(e,t=null){const s=e.length;for(let i=0;iwp(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...Mp(t))):null!==s?(s=wp(s),(...i)=>r(new e(t,...Mp(i),s))):(...s)=>r(new e(t,...Mp(s)))},np=function(e,...t){return wp(new e(...Mp(t)))};class op extends zd{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}call(e){const{shaderNode:t,inputNodes:s}=this,i=e.getNodeProperties(t);if(i.onceOutput)return i.onceOutput;let r=null;if(t.layout){let i=tp.get(e.constructor);void 0===i&&(i=new WeakMap,tp.set(e.constructor,i));let n=i.get(t);void 0===n&&(n=wp(e.buildFunctionNode(t)),i.set(t,n)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(n),r=wp(n.call(s))}else{const i=t.jsFunc,n=null!==s?i(s,e):i(e);r=wp(n)}return t.once&&(i.onceOutput=r),r}getOutputNode(e){const t=e.getNodeProperties(this);return null===t.outputNode&&(t.outputNode=this.setupOutput(e)),t.outputNode}setup(e){return this.getOutputNode(e)}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){return this.getOutputNode(e).build(e,t)}}class ap extends zd{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 Sp(e),wp(new op(this,e))}setup(){return this.call()}}const hp=[!1,!0],up=[0,1,2,3],lp=[-1,-2],cp=[.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],dp=new Map;for(const e of hp)dp.set(e,new $d(e));const pp=new Map;for(const e of up)pp.set(e,new $d(e,"uint"));const mp=new Map([...pp].map((e=>new $d(e.value,"int"))));for(const e of lp)mp.set(e,new $d(e,"int"));const gp=new Map([...mp].map((e=>new $d(e.value))));for(const e of cp)gp.set(e,new $d(e));for(const e of cp)gp.set(-e,new $d(-e));const fp={bool:dp,uint:pp,ints:mp,float:gp},yp=new Map([...dp,...gp]),xp=(e,t)=>yp.has(e)?yp.get(e):!0===e.isNode?e:new $d(e,t),bp=function(e,t=null){return(...s)=>{if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every((e=>"object"!=typeof e)))&&(s=[Md(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return wp(t.get(s[0]));if(1===s.length){const t=xp(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?wp(t):wp(new Vd(t,e))}const i=s.map((e=>xp(e)));return wp(new kd(i,e))}},vp=e=>"object"==typeof e&&null!==e?e.value:e,Tp=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function _p(e,t){return new Proxy(new ap(e,t),Qd)}const wp=(e,t=null)=>function(e,t=null){const s=Sd(e);if("node"===s){let t=ep.get(e);return void 0===t&&(t=new Proxy(e,Qd),ep.set(e,t),ep.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?wp(xp(e,t)):"shader"===s?Cp(e):e}(e,t),Sp=(e,t=null)=>new sp(e,t),Mp=(e,t=null)=>new ip(e,t),Ap=(...e)=>new rp(...e),Np=(...e)=>new np(...e),Cp=(e,t)=>{const s=new _p(e,t),i=(...e)=>{let t;return Sp(e),t=e[0]&&e[0].isNode?[...e]:e[0],s.call(t)};return i.shaderNode=s,i.setLayout=e=>(s.setLayout(e),i),i.once=()=>(s.once=!0,i),i},Rp=(...e)=>(console.warn("TSL.ShaderNode: tslFn() has been renamed to Fn()."),Cp(...e));Zd("toGlobal",(e=>(e.global=!0,e)));const Ep=e=>{Xd=e},Bp=()=>Xd,Ip=(...e)=>Xd.If(...e);function Pp(e){return Xd&&Xd.add(e),e}Zd("append",Pp);const Fp=new bp("color"),Up=new bp("float",fp.float),Op=new bp("int",fp.ints),zp=new bp("uint",fp.uint),Lp=new bp("bool",fp.bool),Vp=new bp("vec2"),Dp=new bp("ivec2"),kp=new bp("uvec2"),Gp=new bp("bvec2"),Wp=new bp("vec3"),jp=new bp("ivec3"),Hp=new bp("uvec3"),qp=new bp("bvec3"),$p=new bp("vec4"),Xp=new bp("ivec4"),Yp=new bp("uvec4"),Zp=new bp("bvec4"),Jp=new bp("mat2"),Kp=new bp("mat3"),Qp=new bp("mat4"),em=(e="")=>wp(new $d(e,"string")),tm=e=>wp(new $d(e,"ArrayBuffer"));Zd("toColor",Fp),Zd("toFloat",Up),Zd("toInt",Op),Zd("toUint",zp),Zd("toBool",Lp),Zd("toVec2",Vp),Zd("toIVec2",Dp),Zd("toUVec2",kp),Zd("toBVec2",Gp),Zd("toVec3",Wp),Zd("toIVec3",jp),Zd("toUVec3",Hp),Zd("toBVec3",qp),Zd("toVec4",$p),Zd("toIVec4",Xp),Zd("toUVec4",Yp),Zd("toBVec4",Zp),Zd("toMat2",Jp),Zd("toMat3",Kp),Zd("toMat4",Qp);const sm=Ap(Ld),im=(e,t)=>wp(new Vd(wp(e),t)),rm=(e,t)=>wp(new Wd(wp(e),t));Zd("element",sm),Zd("convert",im);class nm extends zd{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.version=0,this.shared=t,this.order=s,this.isUniformGroup=!0}set needsUpdate(e){!0===e&&this.version++}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 om=e=>new nm(e),am=(e,t=0)=>new nm(e,!0,t),hm=am("frame"),um=am("render"),lm=om("object");class cm extends qd{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=lm}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const s=this.getSelf();return e=e.bind(s),super.onUpdate((t=>{const i=e(t,s);void 0!==i&&(this.value=i)}),t)}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const n=r.getInputType(e),o=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.label),a=e.getPropertyName(o);return void 0!==e.context.label&&delete e.context.label,e.format(a,s,t)}}const dm=(e,t)=>{const s=Tp(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return wp(new cm(i,s))};class pm extends zd{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}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 mm=(e,t)=>wp(new pm(e,t)),gm=(e,t)=>wp(new pm(e,t,!0)),fm=Np(pm,"vec4","DiffuseColor"),ym=Np(pm,"vec3","EmissiveColor"),xm=Np(pm,"float","Roughness"),bm=Np(pm,"float","Metalness"),vm=Np(pm,"float","Clearcoat"),Tm=Np(pm,"float","ClearcoatRoughness"),_m=Np(pm,"vec3","Sheen"),wm=Np(pm,"float","SheenRoughness"),Sm=Np(pm,"float","Iridescence"),Mm=Np(pm,"float","IridescenceIOR"),Am=Np(pm,"float","IridescenceThickness"),Nm=Np(pm,"float","AlphaT"),Cm=Np(pm,"float","Anisotropy"),Rm=Np(pm,"vec3","AnisotropyT"),Em=Np(pm,"vec3","AnisotropyB"),Bm=Np(pm,"color","SpecularColor"),Im=Np(pm,"float","SpecularF90"),Pm=Np(pm,"float","Shininess"),Fm=Np(pm,"vec4","Output"),Um=Np(pm,"float","dashSize"),Om=Np(pm,"float","gapSize"),zm=Np(pm,"float","pointWidth"),Lm=Np(pm,"float","IOR"),Vm=Np(pm,"float","Transmission"),Dm=Np(pm,"float","Thickness"),km=Np(pm,"float","AttenuationDistance"),Gm=Np(pm,"color","AttenuationColor"),Wm=Np(pm,"float","Dispersion");class jm extends Dd{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}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 s=e.getTypeLength(t.node.getNodeType(e));return Ud.join("").slice(0,s)!==t.components}return!1}generate(e,t){const{targetNode:s,sourceNode:i}=this,r=this.needsSplitAssign(e),n=s.getNodeType(e),o=s.context({assign:!0}).build(e),a=i.build(e,n),h=i.getNodeType(e),u=e.getDataFromNode(this);let l;if(!0===u.initialized)"void"!==t&&(l=o);else if(r){const i=e.getVarFromNode(this,null,n),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${a}`,this);const h=s.node.context({assign:!0}).build(e);for(let t=0;t{const i=s.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r))for(let e=0;e(t=t.length>1||t[0]&&!0===t[0].isNode?Mp(t):Sp(t[0]),wp(new qm(wp(e),t)));Zd("call",$m);class Xm extends Dd{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new Xm(e,t,s);for(let t=0;t>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"=="===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("<"===s||">"===s||"<="===s||">="===s){const s=t?e.getTypeLength(t):Math.max(e.getTypeLength(n),e.getTypeLength(o));return s>1?`bvec${s}`:"bool"}return"float"===n&&e.isMatrix(o)?o:e.isMatrix(n)&&e.isVector(o)?e.getVectorFromMatrix(n):e.isVector(n)&&e.isMatrix(o)?e.getVectorFromMatrix(o):e.getTypeLength(o)>e.getTypeLength(n)?o:n}generate(e,t){const s=this.op,i=this.aNode,r=this.bNode,n=this.getNodeType(e,t);let o=null,a=null;"void"!==n?(o=i.getNodeType(e),a=void 0!==r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s?e.isVector(o)?a=o:o!==a&&(o=a="float"):">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):e.isMatrix(o)&&e.isVector(a)?a=e.getVectorFromMatrix(o):o=e.isVector(o)&&e.isMatrix(a)?e.getVectorFromMatrix(a):a=n):o=a=n;const h=i.build(e,o),u=void 0!==r?r.build(e,a):null,l=e.getTypeLength(t),c=e.getFunctionOperator(s);return"void"!==t?"<"===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThan",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} < ${u} )`,n,t):"<="===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThanEqual",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} <= ${u} )`,n,t):">"===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThan",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} > ${u} )`,n,t):">="===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThanEqual",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} >= ${u} )`,n,t):"!"===s||"~"===s?e.format(`(${s}${h})`,o,t):c?e.format(`${c}( ${h}, ${u} )`,n,t):e.format(`( ${h} ${s} ${u} )`,n,t):"void"!==o?c?e.format(`${c}( ${h}, ${u} )`,n,t):e.format(`${h} ${s} ${u}`,n,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Ym=Ap(Xm,"+"),Zm=Ap(Xm,"-"),Jm=Ap(Xm,"*"),Km=Ap(Xm,"/"),Qm=Ap(Xm,"%"),eg=Ap(Xm,"=="),tg=Ap(Xm,"!="),sg=Ap(Xm,"<"),ig=Ap(Xm,">"),rg=Ap(Xm,"<="),ng=Ap(Xm,">="),og=Ap(Xm,"&&"),ag=Ap(Xm,"||"),hg=Ap(Xm,"!"),ug=Ap(Xm,"^^"),lg=Ap(Xm,"&"),cg=Ap(Xm,"~"),dg=Ap(Xm,"|"),pg=Ap(Xm,"^"),mg=Ap(Xm,"<<"),gg=Ap(Xm,">>");Zd("add",Ym),Zd("sub",Zm),Zd("mul",Jm),Zd("div",Km),Zd("modInt",Qm),Zd("equal",eg),Zd("notEqual",tg),Zd("lessThan",sg),Zd("greaterThan",ig),Zd("lessThanEqual",rg),Zd("greaterThanEqual",ng),Zd("and",og),Zd("or",ag),Zd("not",hg),Zd("xor",ug),Zd("bitAnd",lg),Zd("bitNot",cg),Zd("bitOr",dg),Zd("bitXor",pg),Zd("shiftLeft",mg),Zd("shiftRight",gg);const fg=(...e)=>(console.warn("TSL.OperatorNode: .remainder() has been renamed to .modInt()."),Qm(...e));Zd("remainder",fg);class yg extends Dd{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=s,this.cNode=i}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>o?t:n>o?s:o>r?i:t}getNodeType(e){const t=this.method;return t===yg.LENGTH||t===yg.DISTANCE||t===yg.DOT?"float":t===yg.CROSS?"vec3":t===yg.ALL?"bool":t===yg.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===yg.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,h=!0===e.renderer.isWebGLRenderer;if(s===yg.TRANSFORM_DIRECTION){let s=n,i=o;e.isMatrix(s.getNodeType(e))?i=$p(Wp(i),0):s=$p(Wp(s),0);const r=Jm(s,i).xyz;return Ug(r).build(e,t)}if(s===yg.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);if(s===yg.ONE_MINUS)return Zm(1,n).build(e,t);if(s===yg.RECIPROCAL)return Km(1,n).build(e,t);if(s===yg.DIFFERENCE)return Wg(Zm(n,o)).build(e,t);{const u=[];return s===yg.CROSS||s===yg.MOD?u.push(n.build(e,i),o.build(e,i)):h&&s===yg.STEP?u.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):h&&(s===yg.MIN||s===yg.MAX)||s===yg.MOD?u.push(n.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):s===yg.REFRACT?u.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===yg.MIX?u.push(n.build(e,r),o.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):(u.push(n.build(e,r)),null!==o&&u.push(o.build(e,r)),null!==a&&u.push(a.build(e,r))),e.format(`${e.getMethod(s,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}yg.ALL="all",yg.ANY="any",yg.EQUALS="equals",yg.RADIANS="radians",yg.DEGREES="degrees",yg.EXP="exp",yg.EXP2="exp2",yg.LOG="log",yg.LOG2="log2",yg.SQRT="sqrt",yg.INVERSE_SQRT="inversesqrt",yg.FLOOR="floor",yg.CEIL="ceil",yg.NORMALIZE="normalize",yg.FRACT="fract",yg.SIN="sin",yg.COS="cos",yg.TAN="tan",yg.ASIN="asin",yg.ACOS="acos",yg.ATAN="atan",yg.ABS="abs",yg.SIGN="sign",yg.LENGTH="length",yg.NEGATE="negate",yg.ONE_MINUS="oneMinus",yg.DFDX="dFdx",yg.DFDY="dFdy",yg.ROUND="round",yg.RECIPROCAL="reciprocal",yg.TRUNC="trunc",yg.FWIDTH="fwidth",yg.BITCAST="bitcast",yg.TRANSPOSE="transpose",yg.ATAN2="atan2",yg.MIN="min",yg.MAX="max",yg.MOD="mod",yg.STEP="step",yg.REFLECT="reflect",yg.DISTANCE="distance",yg.DIFFERENCE="difference",yg.DOT="dot",yg.CROSS="cross",yg.POW="pow",yg.TRANSFORM_DIRECTION="transformDirection",yg.MIX="mix",yg.CLAMP="clamp",yg.REFRACT="refract",yg.SMOOTHSTEP="smoothstep",yg.FACEFORWARD="faceforward";const xg=Up(1e-6),bg=Up(1e6),vg=Up(Math.PI),Tg=Up(2*Math.PI),_g=Ap(yg,yg.ALL),wg=Ap(yg,yg.ANY),Sg=Ap(yg,yg.EQUALS),Mg=Ap(yg,yg.RADIANS),Ag=Ap(yg,yg.DEGREES),Ng=Ap(yg,yg.EXP),Cg=Ap(yg,yg.EXP2),Rg=Ap(yg,yg.LOG),Eg=Ap(yg,yg.LOG2),Bg=Ap(yg,yg.SQRT),Ig=Ap(yg,yg.INVERSE_SQRT),Pg=Ap(yg,yg.FLOOR),Fg=Ap(yg,yg.CEIL),Ug=Ap(yg,yg.NORMALIZE),Og=Ap(yg,yg.FRACT),zg=Ap(yg,yg.SIN),Lg=Ap(yg,yg.COS),Vg=Ap(yg,yg.TAN),Dg=Ap(yg,yg.ASIN),kg=Ap(yg,yg.ACOS),Gg=Ap(yg,yg.ATAN),Wg=Ap(yg,yg.ABS),jg=Ap(yg,yg.SIGN),Hg=Ap(yg,yg.LENGTH),qg=Ap(yg,yg.NEGATE),$g=Ap(yg,yg.ONE_MINUS),Xg=Ap(yg,yg.DFDX),Yg=Ap(yg,yg.DFDY),Zg=Ap(yg,yg.ROUND),Jg=Ap(yg,yg.RECIPROCAL),Kg=Ap(yg,yg.TRUNC),Qg=Ap(yg,yg.FWIDTH),ef=Ap(yg,yg.BITCAST),tf=Ap(yg,yg.TRANSPOSE),sf=Ap(yg,yg.ATAN2),rf=Ap(yg,yg.MIN),nf=Ap(yg,yg.MAX),of=Ap(yg,yg.MOD),af=Ap(yg,yg.STEP),hf=Ap(yg,yg.REFLECT),uf=Ap(yg,yg.DISTANCE),lf=Ap(yg,yg.DIFFERENCE),cf=Ap(yg,yg.DOT),df=Ap(yg,yg.CROSS),pf=Ap(yg,yg.POW),mf=Ap(yg,yg.POW,2),gf=Ap(yg,yg.POW,3),ff=Ap(yg,yg.POW,4),yf=Ap(yg,yg.TRANSFORM_DIRECTION),xf=e=>Jm(jg(e),pf(Wg(e),1/3)),bf=e=>cf(e,e),vf=Ap(yg,yg.MIX),Tf=(e,t=0,s=1)=>wp(new yg(yg.CLAMP,wp(e),wp(t),wp(s))),_f=e=>Tf(e),wf=Ap(yg,yg.REFRACT),Sf=Ap(yg,yg.SMOOTHSTEP),Mf=Ap(yg,yg.FACEFORWARD),Af=Cp((([e])=>{const t=cf(e.xy,Vp(12.9898,78.233)),s=of(t,vg);return Og(zg(s).mul(43758.5453))})),Nf=(e,t,s)=>vf(t,s,e),Cf=(e,t,s)=>Sf(t,s,e);Zd("all",_g),Zd("any",wg),Zd("equals",Sg),Zd("radians",Mg),Zd("degrees",Ag),Zd("exp",Ng),Zd("exp2",Cg),Zd("log",Rg),Zd("log2",Eg),Zd("sqrt",Bg),Zd("inverseSqrt",Ig),Zd("floor",Pg),Zd("ceil",Fg),Zd("normalize",Ug),Zd("fract",Og),Zd("sin",zg),Zd("cos",Lg),Zd("tan",Vg),Zd("asin",Dg),Zd("acos",kg),Zd("atan",Gg),Zd("abs",Wg),Zd("sign",jg),Zd("length",Hg),Zd("lengthSq",bf),Zd("negate",qg),Zd("oneMinus",$g),Zd("dFdx",Xg),Zd("dFdy",Yg),Zd("round",Zg),Zd("reciprocal",Jg),Zd("trunc",Kg),Zd("fwidth",Qg),Zd("atan2",sf),Zd("min",rf),Zd("max",nf),Zd("mod",of),Zd("step",af),Zd("reflect",hf),Zd("distance",uf),Zd("dot",cf),Zd("cross",df),Zd("pow",pf),Zd("pow2",mf),Zd("pow3",gf),Zd("pow4",ff),Zd("transformDirection",yf),Zd("mix",Nf),Zd("clamp",Tf),Zd("refract",wf),Zd("smoothstep",Cf),Zd("faceForward",Mf),Zd("difference",lf),Zd("saturate",_f),Zd("cbrt",xf),Zd("transpose",tf),Zd("rand",Af);class Rf extends zd{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const t=this.ifNode.getNodeType(e);if(null!==this.elseNode){const s=this.elseNode.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(t))return s}return t}setup(e){const t=this.condNode.cache(),s=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=s.context({nodeBlock:s}),n.elseNode=i?i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:n,elseNode:o}=e.getNodeProperties(this),a="void"!==t,h=a?mm(s).build(e):"";i.nodeProperty=h;const u=r.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let l=n.build(e,s);if(l&&(l=a?h+" = "+l+";":"return "+l+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+l+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=o.build(e,s);t&&(t=a?h+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(h,s,t)}}const Ef=Ap(Rf);Zd("select",Ef);const Bf=(...e)=>(console.warn("TSL.ConditionalNode: cond() has been renamed to select()."),Ef(...e));Zd("cond",Bf);class If extends zd{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)}analyze(e){this.node.build(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e);return e.setContext(t),s}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(s),i}}const Pf=Ap(If),Ff=(e,t)=>Pf(e,{label:t});Zd("context",Pf),Zd("label",Ff);class Uf extends zd{static get type(){return"VarNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s}=this,i=e.getVarFromNode(this,s,e.getVectorType(this.getNodeType(e))),r=e.getPropertyName(i),n=t.build(e,i.type);return e.addLineFlowCode(`${r} = ${n}`,this),r}}const Of=Ap(Uf);Zd("toVar",((...e)=>Of(...e).append()));const zf=e=>(console.warn('TSL: "temp" is deprecated. Use ".toVar()" instead.'),Of(e));Zd("temp",zf);class Lf extends zd{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(void 0===s){const i=this.name,r=this.getNodeType(e);t.varying=s=e.getVaryingFromNode(this,i,r),t.node=this.node}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e)}analyze(e){return this.setupVarying(e),this.node.analyze(e)}generate(e){const t=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===t.propertyName){const i=this.getNodeType(e),r=e.getPropertyName(s,Rd.VERTEX);e.flowNodeFromShaderStage(Rd.VERTEX,this.node,i,r),t.propertyName=r}return e.getPropertyName(s)}}const Vf=Ap(Lf);Zd("varying",Vf);const Df="WorkingColorSpace",kf="OutputColorSpace";function Gf(e){let t=null;return e===Jt?t="Linear":e===Zt&&(t="sRGB"),t}function Wf(e,t){return Gf(e)+"To"+Gf(t)}class jf extends Dd{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}getColorSpace(e,t){return t===Df?ii.workingColorSpace:t===kf?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{renderer:t}=e,{colorNode:s}=this,i=this.getColorSpace(e,this.source),r=this.getColorSpace(e,this.target);if(i===r)return s;const n=Wf(i,r);let o=null;const a=t.nodes.library.getColorSpaceFunction(n);return null!==a?o=$p(a(s.rgb),s.a):(console.error("ColorSpaceNode: Unsupported Color Space configuration.",n),o=s),o}}const Hf=e=>wp(new jf(wp(e),Df,kf)),qf=e=>wp(new jf(wp(e),kf,Df)),$f=(e,t)=>wp(new jf(wp(e),Df,t)),Xf=(e,t)=>wp(new jf(wp(e),t,Df));Zd("toOutputColorSpace",Hf),Zd("toWorkingColorSpace",qf),Zd("workingToColorSpace",$f),Zd("colorSpaceToWorking",Xf);let Yf=class extends Ld{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),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class Zf extends zd{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=Ed.OBJECT}setGroup(e){return this.group=e,this}element(e){return wp(new Yf(this,wp(e)))}setNodeType(e){const t=dm(null,e).getSelf();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 s=e[t[0]];for(let e=1;ewp(new Jf(e,t,s));class Qf extends Dd{static get type(){return"ToneMappingNode"}constructor(e,t=ty,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}getCacheKey(){return Td(super.getCacheKey(),this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,s=this.toneMapping;if(0===s)return t;let i=null;const r=e.renderer.nodes.library.getToneMappingFunction(s);return null!==r?i=$p(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const ey=(e,t,s)=>wp(new Qf(e,wp(t),wp(s))),ty=Kf("toneMappingExposure","float");Zd("toneMapping",((e,t,s)=>ey(t,s,e)));class sy extends qd{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=Ss,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),s=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,n=this.bufferOffset,o=!0===s.isInterleavedBuffer?s:new Qn(s,r),a=new to(o,i,n);o.setUsage(this.usage),this.attribute=a,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=Vf(this).build(e,t)}return r}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 iy=(e,t,s,i)=>wp(new sy(e,t,s,i)),ry=(e,t,s,i)=>iy(e,t,s,i).setUsage(Ms),ny=(e,t,s,i)=>iy(e,t,s,i).setInstanced(!0),oy=(e,t,s,i)=>ry(e,t,s,i).setInstanced(!0);Zd("toAttribute",(e=>iy(e.value)));class ay extends zd{static get type(){return"ComputeNode"}constructor(e,t,s=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=s,this.dispatchCount=0,this.version=1,this.updateBeforeType=Ed.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let s=t[0];for(let e=1;ewp(new ay(wp(e),t,s));Zd("compute",hy);class uy extends zd{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){return this.node.getNodeType(e)}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(s),r}}const ly=(e,...t)=>wp(new uy(wp(e),...t));Zd("cache",ly);class cy extends zd{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 dy=Ap(cy);Zd("bypass",dy);class py extends zd{static get type(){return"RemapNode"}constructor(e,t,s,i=Up(0),r=Up(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:r,doClamp:n}=this;let o=e.sub(t).div(s.sub(t));return!0===n&&(o=o.clamp()),o.mul(r.sub(i)).add(i)}}const my=Ap(py,null,null,{doClamp:!1}),gy=Ap(py);Zd("remap",my),Zd("remapClamp",gy);class fy extends zd{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if("void"!==s)return e.format(`( ${i} )`,s,t);e.addLineFlowCode(i,this)}}const yy=Ap(fy),xy=e=>(e?Ef(e,yy("discard")):yy("discard")).append(),by=()=>yy("return").append();Zd("discard",xy);class vy extends Dd{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutput=!0}setup({context:e}){let t=this.colorNode||e.color;const s=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||Yt;return 0!==s&&(t=t.toneMapping(s)),i!==Yt&&i!==ii.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const Ty=(e,t=null,s=null)=>wp(new vy(wp(e),t,s));function _y(e){console.warn("THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)}Zd("renderOutput",Ty);class wy extends zd{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 s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),n=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(n.name,r,s);return Vf(this).build(e,s)}return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}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 Sy=(e,t)=>wp(new wy(e,t)),My=e=>Sy("uv"+(e>0?e:""),"vec2");class Ay extends zd{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const Ny=Ap(Ay);class Cy extends cm{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Ed.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const Ry=Ap(Cy);class Ey extends cm{static get type(){return"TextureNode"}constructor(e,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=Ed.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===Be?"uvec4":this.value.type===Ee?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return My(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=dm(this.value.matrix)),this._matrixUniform.mul(Wp(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Ed.FRAME:Ed.NONE,this}setupUV(e,t){const s=this.value;return!e.isFlipY()||!0!==s.isRenderTargetTexture&&!0!==s.isFramebufferTexture&&!0!==s.isDepthTexture||(t=this.sampler?t.flipY():t.setY(Op(Ny(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this)),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}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,s,i,r,n,o,a){const h=this.value;let u;return u=i?e.generateTextureLevel(h,t,s,i,n):r?e.generateTextureBias(h,t,s,r,n):a?e.generateTextureGrad(h,t,s,a,n):o?e.generateTextureCompare(h,t,s,o,n):!1===this.sampler?e.generateTextureLoad(h,t,s,n):e.generateTexture(h,t,s,n),u}generate(e,t){const s=e.getNodeProperties(this),i=this.value;if(!i||!0!==i.isTexture)throw new Error("TextureNode: Need a three.js texture.");const r=super.generate(e,"property");if("sampler"===t)return r+"_sampler";if(e.isReference(t))return r;{const n=e.getDataFromNode(this);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:i,biasNode:a,compareNode:h,depthNode:u,gradNode:l}=s,c=this.generateUV(e,t),d=i?i.build(e,"float"):null,p=a?a.build(e,"float"):null,m=u?u.build(e,"int"):null,g=h?h.build(e,"float"):null,f=l?[l[0].build(e,"vec2"),l[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);o=e.getPropertyName(y);const x=this.generateSnippet(e,r,c,d,p,m,g,f);e.addLineFlowCode(`${o} = ${x}`,this),n.snippet=x,n.propertyName=o}let a=o;const h=this.getNodeType(e);return e.needsToWorkingColorSpace(i)&&(a=Xf(yy(a,h),i.colorSpace).setup(e).build(e,h)),e.format(a,h,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){const t=this.clone();return t.uvNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}blur(e){const t=this.clone();return t.biasNode=wp(e).mul(Ry(t)),t.referenceNode=this.getSelf(),wp(t)}level(e){const t=this.clone();return t.levelNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}size(e){return Ny(this,e)}bias(e){const t=this.clone();return t.biasNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}compare(e){const t=this.clone();return t.compareNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}grad(e,t){const s=this.clone();return s.gradNode=[wp(e),wp(t)],s.referenceNode=this.getSelf(),wp(s)}depth(e){const t=this.clone();return t.depthNode=wp(e),t.referenceNode=this.getSelf(),wp(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}}const By=Ap(Ey),Iy=(...e)=>By(...e).setSampler(!1),Py=e=>(!0===e.isNode?e:By(e)).convert("sampler"),Fy=dm("float").label("cameraNear").setGroup(um).onRenderUpdate((({camera:e})=>e.near)),Uy=dm("float").label("cameraFar").setGroup(um).onRenderUpdate((({camera:e})=>e.far)),Oy=dm("mat4").label("cameraProjectionMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.projectionMatrix)),zy=dm("mat4").label("cameraProjectionMatrixInverse").setGroup(um).onRenderUpdate((({camera:e})=>e.projectionMatrixInverse)),Ly=dm("mat4").label("cameraViewMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.matrixWorldInverse)),Vy=dm("mat4").label("cameraWorldMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.matrixWorld)),Dy=dm("mat3").label("cameraNormalMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.normalMatrix)),ky=dm(new Ai).label("cameraPosition").setGroup(um).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld)));class Gy extends zd{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Ed.OBJECT,this._uniformNode=new cm(null)}getNodeType(){const e=this.scope;return e===Gy.WORLD_MATRIX?"mat4":e===Gy.POSITION||e===Gy.VIEW_POSITION||e===Gy.DIRECTION||e===Gy.SCALE?"vec3":void 0}update(e){const t=this.object3d,s=this._uniformNode,i=this.scope;if(i===Gy.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Gy.POSITION)s.value=s.value||new Ai,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Gy.SCALE)s.value=s.value||new Ai,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Gy.DIRECTION)s.value=s.value||new Ai,t.getWorldDirection(s.value);else if(i===Gy.VIEW_POSITION){const i=e.camera;s.value=s.value||new Ai,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}}generate(e){const t=this.scope;return t===Gy.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t!==Gy.POSITION&&t!==Gy.VIEW_POSITION&&t!==Gy.DIRECTION&&t!==Gy.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Gy.WORLD_MATRIX="worldMatrix",Gy.POSITION="position",Gy.SCALE="scale",Gy.VIEW_POSITION="viewPosition",Gy.DIRECTION="direction";const Wy=Ap(Gy,Gy.DIRECTION),jy=Ap(Gy,Gy.WORLD_MATRIX),Hy=Ap(Gy,Gy.POSITION),qy=Ap(Gy,Gy.SCALE),$y=Ap(Gy,Gy.VIEW_POSITION);class Xy extends Gy{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Yy=Np(Xy,Xy.DIRECTION),Zy=Np(Xy,Xy.WORLD_MATRIX),Jy=Np(Xy,Xy.POSITION),Ky=Np(Xy,Xy.SCALE),Qy=Np(Xy,Xy.VIEW_POSITION),ex=dm(new Zs).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),tx=dm(new sr).onObjectUpdate((({object:e},t)=>t.value.copy(e.matrixWorld).invert())),sx=Ly.mul(Zy).toVar("modelViewMatrix"),ix=Cp((e=>(e.context.isHighPrecisionModelViewMatrix=!0,dm("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highPrecisionModelViewMatrix"),rx=Cp((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return dm("mat3").onObjectUpdate((({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highPrecisionModelNormalMatrix"),nx=Sy("position","vec3"),ox=nx.varying("positionLocal"),ax=nx.varying("positionPrevious"),hx=Zy.mul(ox).xyz.varying("v_positionWorld"),ux=ox.transformDirection(Zy).varying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),lx=sx.mul(ox).xyz.varying("v_positionView"),cx=lx.negate().varying("v_positionViewDirection").normalize().toVar("positionViewDirection");class dx extends zd{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Us&&s.side===d?"false":e.getFrontFacing()}}const px=Np(dx),mx=Up(px).mul(2).sub(1),gx=Sy("normal","vec3"),fx=Cp((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('TSL.NormalNode: Vertex attribute "normal" not found on geometry.'),Wp(0,1,0)):gx),"vec3").once()().toVar("normalLocal"),yx=lx.dFdx().cross(lx.dFdy()).normalize().toVar("normalFlat"),xx=Cp((e=>{let t;return t=!0===e.material.flatShading?yx:Vf(Sx(fx),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),bx=Vf(xx.transformDirection(Ly),"v_normalWorld").normalize().toVar("normalWorld"),vx=Cp((e=>e.context.setupNormal()),"vec3").once()().mul(mx).toVar("transformedNormalView"),Tx=vx.transformDirection(Ly).toVar("transformedNormalWorld"),_x=Cp((e=>e.context.setupClearcoatNormal()),"vec3").once()().mul(mx).toVar("transformedClearcoatNormalView"),wx=Cp((([e,t=Zy])=>{const s=Kp(t),i=e.div(Wp(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz})),Sx=Cp((([e],t)=>{const s=t.renderer.nodes.modelNormalViewMatrix;if(null!==s)return s.transformDirection(e);const i=ex.mul(e);return Ly.transformDirection(i)})),Mx=dm(0).onReference((({material:e})=>e)).onRenderUpdate((({material:e})=>e.refractionRatio)),Ax=cx.negate().reflect(vx),Nx=cx.negate().refract(vx,Mx),Cx=Ax.transformDirection(Ly).toVar("reflectVector"),Rx=Nx.transformDirection(Ly).toVar("reflectVector");class Ex extends Ey{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===he?Cx:e.mapping===ue?Rx:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),Wp(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==Os&&s.isRenderTargetTexture?t:Wp(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const Bx=Ap(Ex);class Ix extends cm{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Px=(e,t,s)=>wp(new Ix(e,t,s));class Fx extends Ld{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType();return e.format(t,"vec4",s)}}class Ux extends Ix{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null,"vec4"),this.array=e,this.elementType=t,this._elementType=null,this._elementLength=0,this.updateType=Ed.RENDER,this.isArrayBufferNode=!0}getElementType(){return this.elementType||this._elementType}getElementLength(){return this._elementLength}update(){const{array:e,value:t}=this,s=this.getElementLength(),i=this.getElementType();if(1===s)for(let s=0;swp(new Ux(e,t)),zx=(e,t)=>(console.warn("TSL.UniformArrayNode: uniforms() has been renamed to uniformArray()."),wp(new Ux(e,t)));class Lx extends Ld{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),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class Vx extends zd{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=Ed.OBJECT}element(e){return wp(new Lx(this,wp(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Px(null,e,this.count):Array.isArray(this.getValueFromReference())?Ox(null,e):"texture"===e?By(null):"cubeTexture"===e?Bx(null):dm(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;ewp(new Vx(e,t,s)),kx=(e,t,s,i)=>wp(new Vx(e,t,i,s));class Gx extends Vx{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Wx=(e,t,s)=>wp(new Gx(e,t,s)),jx=Cp((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Sy("tangent","vec4"))))(),Hx=jx.xyz.toVar("tangentLocal"),qx=sx.mul($p(Hx,0)).xyz.varying("v_tangentView").normalize().toVar("tangentView"),$x=qx.transformDirection(Ly).varying("v_tangentWorld").normalize().toVar("tangentWorld"),Xx=qx.toVar("transformedTangentView"),Yx=Xx.transformDirection(Ly).normalize().toVar("transformedTangentWorld"),Zx=e=>e.mul(jx.w).xyz,Jx=Vf(Zx(gx.cross(jx)),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Kx=Vf(Zx(fx.cross(Hx)),"v_bitangentLocal").normalize().toVar("bitangentLocal"),Qx=Vf(Zx(xx.cross(qx)),"v_bitangentView").normalize().toVar("bitangentView"),eb=Vf(Zx(bx.cross($x)),"v_bitangentWorld").normalize().toVar("bitangentWorld"),tb=Zx(vx.cross(Xx)).normalize().toVar("transformedBitangentView"),sb=tb.transformDirection(Ly).normalize().toVar("transformedBitangentWorld"),ib=Kp(qx,Qx,xx),rb=cx.mul(ib),nb=(e,t)=>e.sub(rb.mul(t)),ob=(()=>{let e=Em.cross(cx);return e=e.cross(Em).normalize(),e=vf(e,vx,Cm.mul(xm.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),ab=Cp((e=>{const{eye_pos:t,surf_norm:s,mapN:i,uv:r}=e,n=t.dFdx(),o=t.dFdy(),a=r.dFdx(),h=r.dFdy(),u=s,l=o.cross(u),c=u.cross(n),d=l.mul(a.x).add(c.mul(h.x)),p=l.mul(a.y).add(c.mul(h.y)),m=d.dot(d).max(p.dot(p)),g=mx.mul(m.inverseSqrt());return Ym(d.mul(i.x,g),p.mul(i.y,g),u.mul(i.z)).normalize()}));class hb extends Dd{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:s}=this;let i=this.node.mul(2).sub(1);null!==s&&(i=Wp(i.xy.mul(s),i.z));let r=null;if(1===t)r=Sx(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?ib.mul(i).normalize():ab({eye_pos:lx,surf_norm:xx,mapN:i,uv:My()})}return r}}const ub=Ap(hb),lb=Cp((({textureNode:e,bumpScale:t})=>{const s=t=>e.cache().context({getUV:e=>t(e.uvNode||My()),forceUVContext:!0}),i=Up(s((e=>e)));return Vp(Up(s((e=>e.add(e.dFdx())))).sub(i),Up(s((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),cb=Cp((e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,o=t.dFdy().normalize().cross(n),a=n.cross(r),h=r.dot(o).mul(mx),u=h.sign().mul(i.x.mul(o).add(i.y.mul(a)));return h.abs().mul(s).sub(u).normalize()}));class db extends Dd{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=lb({textureNode:this.textureNode,bumpScale:e});return cb({surf_pos:lx,surf_norm:xx,dHdxy:t})}}const pb=Ap(db),mb=new Map;class gb extends zd{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=mb.get(e);return void 0===s&&(s=Wx(e,t),mb.set(e,s)),s}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,s=this.scope;let i=null;if(s===gb.COLOR){const e=void 0!==t.color?this.getColor(s):Wp();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===gb.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===gb.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Up(1);else if(s===gb.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularMap?e.mul(this.getTexture(s).a):e}else if(s===gb.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===gb.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===gb.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===gb.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(s)):r}else if(s===gb.NORMAL)t.normalMap?(i=ub(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?pb(this.getTexture("bump").r,this.getFloat("bumpScale")):xx;else if(s===gb.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===gb.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===gb.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?ub(this.getTexture(s),this.getCache(s+"Scale","vec2")):xx;else if(s===gb.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===gb.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(.07,1)}else if(s===gb.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=Jp(Qb.x,Qb.y,Qb.y.negate(),Qb.x).mul(e.rg.mul(2).sub(Vp(1)).normalize().mul(e.b))}else i=Qb;else if(s===gb.IRIDESCENCE_THICKNESS){const e=Dx("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Dx("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===gb.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===gb.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===gb.IOR)i=this.getFloat(s);else if(s===gb.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===gb.AO_MAP)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}gb.ALPHA_TEST="alphaTest",gb.COLOR="color",gb.OPACITY="opacity",gb.SHININESS="shininess",gb.SPECULAR="specular",gb.SPECULAR_STRENGTH="specularStrength",gb.SPECULAR_INTENSITY="specularIntensity",gb.SPECULAR_COLOR="specularColor",gb.REFLECTIVITY="reflectivity",gb.ROUGHNESS="roughness",gb.METALNESS="metalness",gb.NORMAL="normal",gb.CLEARCOAT="clearcoat",gb.CLEARCOAT_ROUGHNESS="clearcoatRoughness",gb.CLEARCOAT_NORMAL="clearcoatNormal",gb.EMISSIVE="emissive",gb.ROTATION="rotation",gb.SHEEN="sheen",gb.SHEEN_ROUGHNESS="sheenRoughness",gb.ANISOTROPY="anisotropy",gb.IRIDESCENCE="iridescence",gb.IRIDESCENCE_IOR="iridescenceIOR",gb.IRIDESCENCE_THICKNESS="iridescenceThickness",gb.IOR="ior",gb.TRANSMISSION="transmission",gb.THICKNESS="thickness",gb.ATTENUATION_DISTANCE="attenuationDistance",gb.ATTENUATION_COLOR="attenuationColor",gb.LINE_SCALE="scale",gb.LINE_DASH_SIZE="dashSize",gb.LINE_GAP_SIZE="gapSize",gb.LINE_WIDTH="linewidth",gb.LINE_DASH_OFFSET="dashOffset",gb.POINT_WIDTH="pointWidth",gb.DISPERSION="dispersion",gb.LIGHT_MAP="light",gb.AO_MAP="ao";const fb=Np(gb,gb.ALPHA_TEST),yb=Np(gb,gb.COLOR),xb=Np(gb,gb.SHININESS),bb=Np(gb,gb.EMISSIVE),vb=Np(gb,gb.OPACITY),Tb=Np(gb,gb.SPECULAR),_b=Np(gb,gb.SPECULAR_INTENSITY),wb=Np(gb,gb.SPECULAR_COLOR),Sb=Np(gb,gb.SPECULAR_STRENGTH),Mb=Np(gb,gb.REFLECTIVITY),Ab=Np(gb,gb.ROUGHNESS),Nb=Np(gb,gb.METALNESS),Cb=Np(gb,gb.NORMAL).context({getUV:null}),Rb=Np(gb,gb.CLEARCOAT),Eb=Np(gb,gb.CLEARCOAT_ROUGHNESS),Bb=Np(gb,gb.CLEARCOAT_NORMAL).context({getUV:null}),Ib=Np(gb,gb.ROTATION),Pb=Np(gb,gb.SHEEN),Fb=Np(gb,gb.SHEEN_ROUGHNESS),Ub=Np(gb,gb.ANISOTROPY),Ob=Np(gb,gb.IRIDESCENCE),zb=Np(gb,gb.IRIDESCENCE_IOR),Lb=Np(gb,gb.IRIDESCENCE_THICKNESS),Vb=Np(gb,gb.TRANSMISSION),Db=Np(gb,gb.THICKNESS),kb=Np(gb,gb.IOR),Gb=Np(gb,gb.ATTENUATION_DISTANCE),Wb=Np(gb,gb.ATTENUATION_COLOR),jb=Np(gb,gb.LINE_SCALE),Hb=Np(gb,gb.LINE_DASH_SIZE),qb=Np(gb,gb.LINE_GAP_SIZE),$b=Np(gb,gb.LINE_WIDTH),Xb=Np(gb,gb.LINE_DASH_OFFSET),Yb=Np(gb,gb.POINT_WIDTH),Zb=Np(gb,gb.DISPERSION),Jb=Np(gb,gb.LIGHT_MAP),Kb=Np(gb,gb.AO_MAP),Qb=dm(new Ys).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))}));class ev extends Dd{static get type(){return"ModelViewProjectionNode"}constructor(e=null){super("vec4"),this.positionNode=e}setup(e){if("fragment"===e.shaderStage)return Vf(e.context.mvp);const t=this.positionNode||ox,s=e.renderer.nodes.modelViewMatrix||sx;return Oy.mul(s).mul(t)}}const tv=Ap(ev);class sv extends zd{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isInstanceIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i,r;if(s===sv.VERTEX)i=e.getVertexIndex();else if(s===sv.INSTANCE)i=e.getInstanceIndex();else if(s===sv.DRAW)i=e.getDrawIndex();else if(s===sv.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===sv.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==sv.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Vf(this).build(e,t)}return r}}sv.VERTEX="vertex",sv.INSTANCE="instance",sv.SUBGROUP="subgroup",sv.INVOCATION_LOCAL="invocationLocal",sv.INVOCATION_SUBGROUP="invocationSubgroup",sv.DRAW="draw";const iv=Np(sv,sv.VERTEX),rv=Np(sv,sv.INSTANCE),nv=Np(sv,sv.SUBGROUP),ov=Np(sv,sv.INVOCATION_SUBGROUP),av=Np(sv,sv.INVOCATION_LOCAL),hv=Np(sv,sv.DRAW);class uv extends zd{static get type(){return"InstanceNode"}constructor(e){super("void"),this.instanceMesh=e,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Ed.FRAME,this.buffer=null,this.bufferColor=null}setup(e){let t=this.instanceMatrixNode,s=this.instanceColorNode;const i=this.instanceMesh;if(null===t){const e=i.instanceMatrix;if(i.count<=1e3)t=Px(e.array,"mat4",Math.max(i.count,1)).element(rv);else{const s=new _c(e.array,16,1);this.buffer=s;const i=e.usage===Ms?oy:ny,r=[i(s,"vec4",16,0),i(s,"vec4",16,4),i(s,"vec4",16,8),i(s,"vec4",16,12)];t=Qp(...r)}this.instanceMatrixNode=t}const r=i.instanceColor;if(r&&null===s){const e=new zo(r.array,3),t=r.usage===Ms?oy:ny;this.bufferColor=e,s=Wp(t(e,"vec3",3,0)),this.instanceColorNode=s}const n=t.mul(ox).xyz;if(ox.assign(n),e.hasGeometryAttribute("normal")){const e=wx(fx,t);fx.assign(e)}null!==this.instanceColorNode&&gm("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMesh.instanceMatrix.usage!==Ms&&null!=this.buffer&&this.instanceMesh.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMesh.instanceMatrix.version),this.instanceMesh.instanceColor&&this.instanceMesh.instanceColor.usage!==Ms&&null!=this.bufferColor&&this.instanceMesh.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceMesh.instanceColor.version)}}const lv=Ap(uv);class cv extends zd{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=rv:this.batchingIdNode=hv);const t=Cp((([e])=>{const t=Ny(Iy(this.batchMesh._indirectTexture),0),s=Op(e).modInt(Op(t)),i=Op(e).div(Op(t));return Iy(this.batchMesh._indirectTexture,Dp(s,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(Op(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=Ny(Iy(i),0),n=Up(s).mul(4).toInt().toVar(),o=n.modInt(r),a=n.div(Op(r)),h=Qp(Iy(i,Dp(o,a)),Iy(i,Dp(o.add(1),a)),Iy(i,Dp(o.add(2),a)),Iy(i,Dp(o.add(3),a))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Cp((([e])=>{const t=Ny(Iy(u),0).x,s=e,i=s.modInt(t),r=s.div(t);return Iy(u,Dp(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);gm("vec3","vBatchColor").assign(t)}const l=Kp(h);ox.assign(h.mul(ox));const c=fx.div(Wp(l[0].dot(l[0]),l[1].dot(l[1]),l[2].dot(l[2]))),d=l.mul(c).xyz;fx.assign(d),e.hasGeometryAttribute("tangent")&&Hx.mulAssign(l)}}const dv=Ap(cv),pv=new WeakMap;class mv extends zd{static get type(){return"SkinningNode"}constructor(e,t=!1){let s,i,r;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=Ed.OBJECT,this.skinIndexNode=Sy("skinIndex","uvec4"),this.skinWeightNode=Sy("skinWeight","vec4"),t?(s=Dx("bindMatrix","mat4"),i=Dx("bindMatrixInverse","mat4"),r=kx("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(s=dm(e.bindMatrix,"mat4"),i=dm(e.bindMatrixInverse,"mat4"),r=Px(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=s,this.bindMatrixInverseNode=i,this.boneMatricesNode=r,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=ox){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),u=e.element(s.w),l=r.mul(t),c=Ym(o.mul(i.x).mul(l),a.mul(i.y).mul(l),h.mul(i.z).mul(l),u.mul(i.w).mul(l));return n.mul(c).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=fx){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),u=e.element(s.w);let l=Ym(i.x.mul(o),i.y.mul(a),i.z.mul(h),i.w.mul(u));return l=n.mul(l).mul(r),l.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=kx("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,ax)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")}setup(e){this.needsPreviousBoneMatrices(e)&&ax.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(ox.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();fx.assign(t),e.hasGeometryAttribute("tangent")&&Hx.assign(t)}}generate(e,t){if("void"!==t)return ox.build(e,t)}update(e){const t=(this.useReference?e.object:this.skinnedMesh).skeleton;pv.get(t)!==e.frameId&&(pv.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const gv=e=>wp(new mv(e)),fv=e=>wp(new mv(e,!0));class yv extends zd{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt()+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;eNumber(n)?">=":"<"));const l={start:r,end:n,condition:h},c=l.start,d=l.end;let p="",m="",g="";u||(u="int"===a||"uint"===a?h.includes("<")?"++":"--":h.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(a,o)+" = "+c,m+=o+" "+h+" "+d,g+=o+" "+u;const f=`for ( ${p}; ${m}; ${g} )`;e.addFlowCode((0===t?"\n":"")+e.tab+f+" {\n\n").addFlowTab()}const r=i.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,s=this.params.length-1;twp(new yv(Mp(e,"int"))).append(),bv=()=>yy("continue").append(),vv=()=>yy("break").append(),Tv=(...e)=>(console.warn("TSL.LoopNode: loop() has been renamed to Loop()."),xv(...e)),_v=new WeakMap,wv=new xi,Sv=Cp((({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=Op(iv).mul(s).add(n),a=o.div(i),h=o.sub(a.mul(i));return Iy(e,Dp(h,a)).depth(r).mul(t)}));class Mv extends zd{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=dm(1),this.updateType=Ed.OBJECT}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,n=void 0!==r?r.length:0,{texture:o,stride:a,size:h}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,n=void 0!==r?r.length:0;let o=_v.get(e);if(void 0===o||o.count!==n){void 0!==o&&o.texture.dispose();const a=e.morphAttributes.position||[],h=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let l=0;!0===t&&(l=1),!0===s&&(l=2),!0===i&&(l=3);let c=e.attributes.position.count*l,d=1;const p=4096;c>p&&(d=Math.ceil(c/p),c=p);const m=new Float32Array(c*d*4*n),g=new Ti(m,c,d,n);g.type=Ie,g.needsUpdate=!0;const f=4*l;for(let x=0;x{const t=Up(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Iy(this.mesh.morphTexture,Dp(Op(e).add(1),Op(rv))).r):t.assign(Dx("morphTargetInfluences","float").element(e).toVar()),!0===s&&ox.addAssign(Sv({bufferMap:o,influence:t,stride:a,width:u,depth:e,offset:Op(0)})),!0===i&&fx.addAssign(Sv({bufferMap:o,influence:t,stride:a,width:u,depth:e,offset:Op(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 Av=Ap(Mv),Nv=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},Cv=new WeakMap;class Rv extends zd{static get type(){return"LightsNode"}constructor(e=[]){super("vec3"),this.totalDiffuseNode=Wp().toVar("totalDiffuse"),this.totalSpecularNode=Wp().toVar("totalSpecular"),this.outgoingLightNode=Wp().toVar("outgoingLight"),this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this.global=!0}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getDataFromNode(this);for(const s of t.nodes)s.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=(e=>e.sort(((e,t)=>e.id-t.id)))(this._lights),r=e.renderer.nodes.library;for(const e of i)if(e.isNode)t.push(wp(e));else{let i=null;if(null!==s&&(i=Nv(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;Cv.has(e)?i=Cv.get(e):(i=new s(e),Cv.set(e,i)),t.push(i)}}this._lightNodes=t}setup(e){null===this._lightNodes&&this.setupLightsNode(e);const t=e.context,s=t.lightingModel;let i=this.outgoingLightNode;if(s){const{_lightNodes:r,totalDiffuseNode:n,totalSpecularNode:o}=this;t.outgoingLight=i;const a=e.addStack();e.getDataFromNode(this).nodes=a.nodes,s.start(t,a,e);for(const t of r)t.build(e);s.indirect(t,a,e);const{backdrop:h,backdropAlpha:u}=t,{directDiffuse:l,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=t.reflectedLight;let m=l.add(d);null!==h&&(m=Wp(null!==u?u.mix(m,h):h),t.material.transparent=!0),n.assign(m),o.assign(c.add(p)),i.assign(n.add(o)),s.finish(t,a,e),i=i.bypass(e.removeStack())}return i}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}}const Ev=Ap(Rv);class Bv extends zd{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}generate(){console.warn("Abstract function.")}}class Iv extends Bv{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Pv extends If{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:Wp().toVar("directDiffuse"),directSpecular:Wp().toVar("directSpecular"),indirectDiffuse:Wp().toVar("indirectDiffuse"),indirectSpecular:Wp().toVar("indirectSpecular")};return{radiance:Wp().toVar("radiance"),irradiance:Wp().toVar("irradiance"),iblIrradiance:Wp().toVar("iblIrradiance"),ambientOcclusion:Up(1).toVar("ambientOcclusion"),reflectedLight:s,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 Fv=Ap(Pv);class Uv extends Bv{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Ov,zv;class Lv extends zd{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Lv.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Ed.NONE;return this.scope!==Lv.SIZE&&this.scope!==Lv.VIEWPORT||(e=Ed.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Lv.VIEWPORT?null!==t?zv.copy(t.viewport):(e.getViewport(zv),zv.multiplyScalar(e.getPixelRatio())):null!==t?(Ov.width=t.width,Ov.height=t.height):e.getDrawingBufferSize(Ov)}setup(){const e=this.scope;let t=null;return t=e===Lv.SIZE?dm(Ov||(Ov=new Ys)):e===Lv.VIEWPORT?dm(zv||(zv=new xi)):Vp(kv.div(Dv)),t}generate(e){if(this.scope===Lv.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Dv).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Lv.COORDINATE="coordinate",Lv.VIEWPORT="viewport",Lv.SIZE="size",Lv.UV="uv";const Vv=Np(Lv,Lv.UV),Dv=Np(Lv,Lv.SIZE),kv=Np(Lv,Lv.COORDINATE),Gv=Np(Lv,Lv.VIEWPORT),Wv=Gv.zw,jv=kv.sub(Gv.xy),Hv=jv.div(Wv),qv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.'),Dv)),"vec2").once()(),$v=Cp((()=>(console.warn('TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.'),Vv)),"vec2").once()(),Xv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.'),Vv.flipY())),"vec2").once()(),Yv=new Ys;class Zv extends Ey{static get type(){return"ViewportTextureNode"}constructor(e=Vv,t=null,s=null){null===s&&((s=new Wa).minFilter=Se),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Ed.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Yv);const s=this.value;s.image.width===Yv.width&&s.image.height===Yv.height||(s.image.width=Yv.width,s.image.height=Yv.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 Jv=Ap(Zv),Kv=Ap(Zv,null,null,{generateMipmaps:!0});let Qv=null;class eT extends Zv{static get type(){return"ViewportDepthTextureNode"}constructor(e=Vv,t=null){null===Qv&&(Qv=new Xa),super(e,t,Qv)}}const tT=Ap(eT);class sT extends zd{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===sT.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===sT.DEPTH_BASE)null!==s&&(i=hT().assign(s));else if(t===sT.DEPTH)i=e.isPerspectiveCamera?nT(lx.z,Fy,Uy):iT(lx.z,Fy,Uy);else if(t===sT.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=oT(s,Fy,Uy);i=iT(e,Fy,Uy)}else i=s;else i=iT(lx.z,Fy,Uy);return i}}sT.DEPTH_BASE="depthBase",sT.DEPTH="depth",sT.LINEAR_DEPTH="linearDepth";const iT=(e,t,s)=>e.add(t).div(t.sub(s)),rT=(e,t,s)=>t.sub(s).mul(e).sub(t),nT=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),oT=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),aT=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Eg(e.div(t).add(1)),r=Eg(s.div(t).add(1));return i.div(r)},hT=Ap(sT,sT.DEPTH_BASE),uT=Np(sT,sT.DEPTH),lT=Ap(sT,sT.LINEAR_DEPTH),cT=lT(tT());uT.assign=e=>hT(e);class dT extends zd{static get type(){return"ClippingNode"}constructor(e=dT.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{localClipIntersection:s,localClippingCount:i,globalClippingCount:r}=t,n=r+i,o=s?n-i:n;return this.scope===dT.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(t.planes,n,o):this.setupDefault(t.planes,n,o)}setupAlphaToCoverage(e,t,s){return Cp((()=>{const i=Ox(e),r=mm("float","distanceToPlane"),n=mm("float","distanceToGradient"),o=mm("float","clipOpacity");let a;if(o.assign(1),xv(s,(({i:e})=>{a=i.element(e),r.assign(lx.dot(a.xyz).negate().add(a.w)),n.assign(r.fwidth().div(2)),o.mulAssign(Sf(n.negate(),n,r)),o.equal(0).discard()})),s{a=i.element(t),r.assign(lx.dot(a.xyz).negate().add(a.w)),n.assign(r.fwidth().div(2)),e.mulAssign(Sf(n.negate(),n,r).oneMinus())})),o.mulAssign(e.oneMinus())}fm.a.mulAssign(o),fm.a.equal(0).discard()}))()}setupDefault(e,t,s){return Cp((()=>{const i=Ox(e);let r;if(xv(s,(({i:e})=>{r=i.element(e),lx.dot(r.xyz).greaterThan(r.w).discard()})),s{r=i.element(t),e.assign(lx.dot(r.xyz).greaterThan(r.w).and(e))})),e.discard()}}))()}}dT.ALPHA_TO_COVERAGE="alphaToCoverage",dT.DEFAULT="default";class pT extends Jr{static get type(){return"NodeMaterial"}constructor(){super(),this.isNodeMaterial=!0,this.type=this.constructor.type,this.forceSinglePass=!1,this.fog=!0,this.lights=!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.positionNode=null,this.geometryNode=null,this.depthNode=null,this.shadowNode=null,this.shadowPositionNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+_d(this)}build(e){this.setup(e)}setupObserver(e){return new yd(e)}setup(e){let t;e.context.setupNormal=()=>this.setupNormal(e),e.addStack(),e.stack.outputNode=this.vertexNode||this.setupPosition(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const s=this.setupClipping(e);if(!0===this.depthWrite&&this.setupDepth(e),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==s&&e.stack.add(s);const r=$p(i,fm.a).max(0);t=this.setupOutput(e,r),Fm.assign(t),null!==this.outputNode&&(t=this.outputNode);if(null!==e.renderer.getRenderTarget()){const s=e.renderer.getMRT(),i=this.mrtNode;null!==s?(t=s,null!==i&&(t=s.merge(i))):null!==i&&(t=i)}}else{let s=this.fragmentNode;!0!==s.isOutputStructNode&&(s=$p(s)),t=this.setupOutput(e,s)}e.stack.outputNode=t,e.addFlow("fragment",e.removeStack()),e.monitor=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{globalClippingCount:t,localClippingCount:s}=e.clippingContext;let i=null;if(t||s){const t=e.renderer.samples;this.alphaToCoverage&&t>1?i=wp(new dT(dT.ALPHA_TO_COVERAGE)):e.stack.add(wp(new dT))}return i}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=s.isPerspectiveCamera?aT(tv().w,Fy,Uy):iT(lx.z,Fy,Uy))}null!==i&&uT.assign(i).append()}setupPosition(e){const{object:t}=e,s=t.geometry;if(e.addStack(),(s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Av(t).append(),!0===t.isSkinnedMesh&&fv(t).append(),this.displacementMap){const e=Wx("displacementMap","texture"),t=Wx("displacementScale","float"),s=Wx("displacementBias","float");ox.addAssign(fx.normalize().mul(e.x.mul(t).add(s)))}t.isBatchedMesh&&dv(t).append(),t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&lv(t).append(),null!==this.positionNode&&ox.assign(this.positionNode);const i=tv();return e.context.vertex=e.removeStack(),e.context.mvp=i,i}setupDiffuseColor({object:e,geometry:t}){let s=this.colorNode?$p(this.colorNode):yb;if(!0===this.vertexColors&&t.hasAttribute("color")&&(s=$p(s.xyz.mul(Sy("color","vec3")),s.a)),e.instanceColor){s=gm("vec3","vInstanceColor").mul(s)}if(e.isBatchedMesh&&e._colorsTexture){s=gm("vec3","vBatchColor").mul(s)}fm.assign(s);const i=this.opacityNode?Up(this.opacityNode):vb;if(fm.a.assign(fm.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?Up(this.alphaTestNode):fb;fm.a.lessThanEqual(e).discard()}!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&fm.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Wp(0):fm.rgb}setupNormal(){return this.normalNode?Wp(this.normalNode):Cb}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Wx("envMap","cubeTexture"):Wx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Uv(Jb)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Kb;t.push(new Iv(e))}let r=this.lightsNode||e.lightsNode;return t.length>0&&(r=Ev([...r.getLights(),...t])),r}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:r}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let o=this.setupOutgoingLight(e);if(n&&n.getScope().getLights().length>0){const t=this.setupLightingModel(e);o=Fv(n,t,s,i)}else null!==s&&(o=Wp(null!==i?vf(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(ym.assign(Wp(r||bb)),o=o.add(ym)),o}setupOutput(e,t){if(!0===this.fog){const s=e.fogNode;s&&(t=$p(s.mix(t.rgb,s.colorNode),t.a))}return t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.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 s=Jr.prototype.toJSON.call(this,e),i=wd(this);s.inputNodes={};for(const{property:t,childNode:r}of i)s.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),n=r(e.nodes);t.length>0&&(s.textures=t),i.length>0&&(s.images=i),n.length>0&&(s.nodes=n)}return s}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.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.shadowNode=e.shadowNode,this.shadowPositionNode=e.shadowPositionNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const mT=new Fa;class gT extends pT{static get type(){return"InstancedPointsNodeMaterial"}constructor(e={}){super(),this.lights=!1,this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.pointWidth=1,this.pointColorNode=null,this.pointWidthNode=null,this.setDefaultValues(mT),this.setValues(e)}setup(e){this.setupShaders(e),super.setup(e)}setupShaders({renderer:e}){const t=this.alphaToCoverage,s=this.useColor;this.vertexNode=Cp((()=>{const e=Sy("instancePosition").xyz,t=$p(sx.mul($p(e,1))),s=Gv.z.div(Gv.w),i=Oy.mul(t),r=nx.xy.toVar();return r.mulAssign(this.pointWidthNode?this.pointWidthNode:Yb),r.assign(r.div(Gv.z)),r.y.assign(r.y.mul(s)),r.assign(r.mul(i.w)),i.addAssign($p(r,0,0)),i}))(),this.fragmentNode=Cp((()=>{const i=Up(1).toVar(),r=bf(My().mul(2).sub(1));if(t&&e.samples>1){const e=Up(r.fwidth()).toVar();i.assign(Sf(e.oneMinus(),e.add(1),r).oneMinus())}else r.greaterThan(1).discard();let n;if(this.pointColorNode)n=this.pointColorNode;else if(s){n=Sy("instanceColor").mul(yb)}else n=yb;return i.mulAssign(vb),$p(n,i)}))()}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.needsUpdate=!0)}}const fT=new va;class yT extends pT{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.lights=!1,this.setDefaultValues(fT),this.setValues(e)}}const xT=new Eu;class bT extends pT{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.lights=!1,this.setDefaultValues(xT),this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode,t=this.dashScaleNode?Up(this.dashScaleNode):jb,s=this.dashSizeNode?Up(this.dashSizeNode):Hb,i=this.dashSizeNode?Up(this.dashGapNode):qb;Um.assign(s),Om.assign(i);const r=Vf(Sy("lineDistance").mul(t));(e?r.add(e):r).mod(Um.add(Om)).greaterThan(Um).discard()}}const vT=new Eu;class TT extends pT{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.lights=!1,this.setDefaultValues(vT),this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.useDash=e.dashed,this.useWorldUnits=!1,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setup(e){this.setupShaders(e),super.setup(e)}setupShaders({renderer:e}){const t=this.alphaToCoverage,s=this.useColor,i=this.dashed,r=this.worldUnits,n=Cp((({start:e,end:t})=>{const s=Oy.element(2).element(2),i=Oy.element(3).element(2).mul(-.5).div(s).sub(e.z).div(t.z.sub(e.z));return $p(vf(e.xyz,t.xyz,i),t.w)})).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=Cp((()=>{const e=Sy("instanceStart"),t=Sy("instanceEnd"),s=$p(sx.mul($p(e,1))).toVar("start"),o=$p(sx.mul($p(t,1))).toVar("end");r&&(gm("vec3","worldStart").assign(s.xyz),gm("vec3","worldEnd").assign(o.xyz));const a=Gv.z.div(Gv.w),h=Oy.element(2).element(3).equal(-1);Ip(h,(()=>{Ip(s.z.lessThan(0).and(o.z.greaterThan(0)),(()=>{o.assign(n({start:s,end:o}))})).ElseIf(o.z.lessThan(0).and(s.z.greaterThanEqual(0)),(()=>{s.assign(n({start:o,end:s}))}))}));const u=Oy.mul(s),l=Oy.mul(o),c=u.xyz.div(u.w),d=l.xyz.div(l.w),p=d.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(a)),p.assign(p.normalize());const m=$p().toVar();if(r){const e=o.xyz.sub(s.xyz).normalize(),t=vf(s.xyz,o.xyz,.5).normalize(),r=e.cross(t).normalize(),n=e.cross(r),a=gm("vec4","worldPos");a.assign(nx.y.lessThan(.5).select(s,o));const h=$b.mul(.5);a.addAssign($p(nx.x.lessThan(0).select(r.mul(h),r.mul(h).negate()),0)),i||(a.addAssign($p(nx.y.lessThan(.5).select(e.mul(h).negate(),e.mul(h)),0)),a.addAssign($p(n.mul(h),0)),Ip(nx.y.greaterThan(1).or(nx.y.lessThan(0)),(()=>{a.subAssign($p(n.mul(2).mul(h),0))}))),m.assign(Oy.mul(a));const u=Wp().toVar();u.assign(nx.y.lessThan(.5).select(c,d)),m.z.assign(u.z.mul(m.w))}else{const e=Vp(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(a)),e.x.assign(e.x.div(a)),e.assign(nx.x.lessThan(0).select(e.negate(),e)),Ip(nx.y.lessThan(0),(()=>{e.assign(e.sub(p))})).ElseIf(nx.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul($b)),e.assign(e.div(Gv.w)),m.assign(nx.y.lessThan(.5).select(u,l)),e.assign(e.mul(m.w)),m.assign(m.add($p(e,0,0)))}return m}))();const o=Cp((({p1:e,p2:t,p3:s,p4:i})=>{const r=e.sub(s),n=i.sub(s),o=t.sub(e),a=r.dot(n),h=n.dot(o),u=r.dot(o),l=n.dot(n),c=o.dot(o).mul(l).sub(h.mul(h)),d=a.mul(h).sub(u.mul(l)).div(c).clamp(),p=a.add(h.mul(d)).div(l).clamp();return Vp(d,p)}));this.fragmentNode=Cp((()=>{const n=My();if(i){const e=this.offsetNode?Up(this.offsetNodeNode):Xb,t=this.dashScaleNode?Up(this.dashScaleNode):jb,s=this.dashSizeNode?Up(this.dashSizeNode):Hb,i=this.dashSizeNode?Up(this.dashGapNode):qb;Um.assign(s),Om.assign(i);const r=Sy("instanceDistanceStart"),o=Sy("instanceDistanceEnd"),a=nx.y.lessThan(.5).select(t.mul(r),jb.mul(o)),h=Vf(a.add(Xb)),u=e?h.add(e):h;n.y.lessThan(-1).or(n.y.greaterThan(1)).discard(),u.mod(Um.add(Om)).greaterThan(Um).discard()}const a=Up(1).toVar("alpha");if(r){const s=gm("vec3","worldStart"),r=gm("vec3","worldEnd"),n=gm("vec4","worldPos").xyz.normalize().mul(1e5),h=r.sub(s),u=o({p1:s,p2:r,p3:Wp(0,0,0),p4:n}),l=s.add(h.mul(u.x)),c=n.mul(u.y),d=l.sub(c).length().div($b);if(!i)if(t&&e.samples>1){const e=d.fwidth();a.assign(Sf(e.negate().add(.5),e.add(.5),d).oneMinus())}else d.greaterThan(.5).discard()}else if(t&&e.samples>1){const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1)),s=e.mul(e).add(t.mul(t)),i=Up(s.fwidth()).toVar("dlen");Ip(n.y.abs().greaterThan(1),(()=>{a.assign(Sf(i.oneMinus(),i.add(1),s).oneMinus())}))}else Ip(n.y.abs().greaterThan(1),(()=>{const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()}));let h;if(this.lineColorNode)h=this.lineColorNode;else if(s){const e=Sy("instanceColorStart"),t=Sy("instanceColorEnd");h=nx.y.lessThan(.5).select(e,t).mul(yb)}else h=yb;return $p(h,a)}))()}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 _T=e=>wp(e).mul(.5).add(.5),wT=e=>wp(e).mul(2).sub(1),ST=new Mu;class MT extends pT{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(ST),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Up(this.opacityNode):vb;fm.assign($p(_T(vx),e))}}class AT extends Dd{static get type(){return"EquirectUVNode"}constructor(e=ux){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan2(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Vp(t,s)}}const NT=Ap(AT);class CT extends Yn{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=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 r=new Ln(5,5,5),n=NT(ux),o=new pT;o.colorNode=By(t,n,0),o.side=d,o.blending=m;const a=new On(r,o),h=new Kn;h.add(a),t.minFilter===Se&&(t.minFilter=Te);const u=new $n(1,10,this),l=e.getMRT();return e.setMRT(null),u.update(e,h),e.setMRT(l),t.minFilter=s,t.currentGenerateMipmaps=i,a.geometry.dispose(),a.material.dispose(),this}}const RT=new WeakMap;class ET extends Dd{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Bx();const t=new Xn;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Ed.RENDER}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:s[i.property];if(e&&e.isTexture){const s=e.mapping;if(s===le||s===ce){if(RT.has(e)){const t=RT.get(e);IT(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new CT(s.height);i.fromEquirectangularTexture(t,e),IT(i.texture,e.mapping),this._cubeTexture=i.texture,RT.set(e,i.texture),e.addEventListener("dispose",BT)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function BT(e){const t=e.target;t.removeEventListener("dispose",BT);const s=RT.get(t);void 0!==s&&(RT.delete(t),s.dispose())}function IT(e,t){t===le?e.mapping=he:t===ce&&(e.mapping=ue)}const PT=Ap(ET);class FT extends Bv{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=PT(this.envNode)}}class UT extends Bv{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Up(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class OT{start(){}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class zT extends OT{constructor(){super()}indirect(e,t,s){const i=e.ambientOcclusion,r=e.reflectedLight,n=s.context.irradianceLightMap;r.indirectDiffuse.assign($p(0)),n?r.indirectDiffuse.addAssign(n):r.indirectDiffuse.addAssign($p(1,1,1,0)),r.indirectDiffuse.mulAssign(i),r.indirectDiffuse.mulAssign(fm.rgb)}finish(e,t,s){const i=s.material,r=e.outgoingLight,n=s.context.environment;if(n)switch(i.combine){case 0:r.rgb.assign(vf(r.rgb,r.rgb.mul(n.rgb),Sb.mul(Mb)));break;case 1:r.rgb.assign(vf(r.rgb,n.rgb,Sb.mul(Mb)));break;case 2:r.rgb.addAssign(n.rgb.mul(Sb.mul(Mb)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",i.combine)}}}const LT=new Kr;class VT extends pT{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(LT),this.setValues(e)}setupNormal(){return xx}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new FT(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new UT(Jb)),t}setupOutgoingLight(){return fm.rgb}setupLightingModel(){return new zT}}const DT=Cp((({f0:e,f90:t,dotVH:s})=>{const i=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(i.oneMinus()).add(t.mul(i))})),kT=Cp((e=>e.diffuseColor.mul(1/Math.PI))),GT=Cp((({dotNH:e})=>Pm.mul(Up(.5)).add(1).mul(Up(1/Math.PI)).mul(e.pow(Pm)))),WT=Cp((({lightDirection:e})=>{const t=e.add(cx).normalize(),s=vx.dot(t).clamp(),i=cx.dot(t).clamp(),r=DT({f0:Bm,f90:1,dotVH:i}),n=Up(.25),o=GT({dotNH:s});return r.mul(n).mul(o)}));class jT extends zT{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=vx.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(kT({diffuseColor:fm.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(WT({lightDirection:e})).mul(Sb))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(kT({diffuseColor:fm}))),s.indirectDiffuse.mulAssign(e)}}const HT=new Au;class qT extends pT{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(HT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new FT(t):null}setupLightingModel(){return new jT(!1)}}const $T=new wu;class XT extends pT{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues($T),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new FT(t):null}setupLightingModel(){return new jT}setupVariants(){const e=(this.shininessNode?Up(this.shininessNode):xb).max(1e-4);Pm.assign(e);const t=this.specularNode||Tb;Bm.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const YT=Cp((e=>{if(!1===e.geometry.hasAttribute("normal"))return Up(0);const t=xx.dFdx().abs().max(xx.dFdy().abs());return t.x.max(t.y).max(t.z)})),ZT=Cp((e=>{const{roughness:t}=e,s=YT();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i})),JT=Cp((({alpha:e,dotNL:t,dotNV:s})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt()),n=s.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return Km(.5,r.add(n).max(xg))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),KT=Cp((({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const h=a.mul(Wp(e.mul(s),t.mul(i),o).length()),u=o.mul(Wp(e.mul(r),t.mul(n),a).length());return Km(.5,h.add(u)).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"}]}),QT=Cp((({alpha:e,dotNH:t})=>{const s=e.pow2(),i=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(i.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),e_=Up(1/Math.PI),t_=Cp((({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=Wp(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),h=n.div(a);return e_.mul(n.mul(h.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"}]}),s_=Cp((e=>{const{lightDirection:t,f0:s,f90:i,roughness:r,f:n,USE_IRIDESCENCE:o,USE_ANISOTROPY:a}=e,h=e.normalView||vx,u=r.pow2(),l=t.add(cx).normalize(),c=h.dot(t).clamp(),d=h.dot(cx).clamp(),p=h.dot(l).clamp(),m=cx.dot(l).clamp();let g,f,y=DT({f0:s,f90:i,dotVH:m});if(vp(o)&&(y=Sm.mix(y,n)),vp(a)){const e=Rm.dot(t),s=Rm.dot(cx),i=Rm.dot(l),r=Em.dot(t),n=Em.dot(cx),o=Em.dot(l);g=KT({alphaT:Nm,alphaB:u,dotTV:s,dotBV:n,dotTL:e,dotBL:r,dotNV:d,dotNL:c}),f=t_({alphaT:Nm,alphaB:u,dotNH:p,dotTH:i,dotBH:o})}else g=JT({alpha:u,dotNL:c,dotNV:d}),f=QT({alpha:u,dotNH:p});return y.mul(g).mul(f)})),i_=Cp((({roughness:e,dotNV:t})=>{const s=$p(-1,-.0275,-.572,.022),i=$p(1,.0425,1.04,-.04),r=e.mul(s).add(i),n=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return Vp(-1.04,1.04).mul(n).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),r_=Cp((e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=i_({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))})),n_=Cp((({f:e,f90:t,dotVH:s})=>{const i=s.oneMinus().saturate(),r=i.mul(i),n=i.mul(r,r).clamp(0,.9999);return e.sub(Wp(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"}]}),o_=Cp((({roughness:e,dotNH:t})=>{const s=e.pow2(),i=Up(1).div(s),r=t.pow2().oneMinus().max(.0078125);return Up(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),a_=Cp((({dotNV:e,dotNL:t})=>Up(1).div(Up(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),h_=Cp((({lightDirection:e})=>{const t=e.add(cx).normalize(),s=vx.dot(e).clamp(),i=vx.dot(cx).clamp(),r=vx.dot(t).clamp(),n=o_({roughness:wm,dotNH:r}),o=a_({dotNV:i,dotNL:s});return _m.mul(n).mul(o)})),u_=Cp((({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=Vp(s,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r})).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),l_=Cp((({f:e})=>{const t=e.length();return nf(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),c_=Cp((({v1:e,v2:t})=>{const s=e.dot(t),i=s.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),n=i.add(4.1616724).mul(i).add(3.417594).toVar(),o=r.div(n),a=s.greaterThan(0).select(o,nf(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return e.cross(t).mul(a)})).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),d_=Cp((({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:o,p3:a})=>{const h=n.sub(r).toVar(),u=a.sub(r).toVar(),l=h.cross(u),c=Wp().toVar();return Ip(l.dot(s.sub(r)).greaterThanEqual(0),(()=>{const h=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(h).negate(),l=i.mul(Kp(h,u,e).transpose()).toVar(),d=l.mul(r.sub(s)).normalize().toVar(),p=l.mul(n.sub(s)).normalize().toVar(),m=l.mul(o.sub(s)).normalize().toVar(),g=l.mul(a.sub(s)).normalize().toVar(),f=Wp(0).toVar();f.addAssign(c_({v1:d,v2:p})),f.addAssign(c_({v1:p,v2:m})),f.addAssign(c_({v1:m,v2:g})),f.addAssign(c_({v1:g,v2:d})),c.assign(Wp(l_({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"}]}),p_=1/6,m_=e=>Jm(p_,Jm(e,Jm(e,e.negate().add(3)).sub(3)).add(1)),g_=e=>Jm(p_,Jm(e,Jm(e,Jm(3,e).sub(6))).add(4)),f_=e=>Jm(p_,Jm(e,Jm(e,Jm(-3,e).add(3)).add(3)).add(1)),y_=e=>Jm(p_,pf(e,3)),x_=e=>m_(e).add(g_(e)),b_=e=>f_(e).add(y_(e)),v_=e=>Ym(-1,g_(e).div(m_(e).add(g_(e)))),T_=e=>Ym(1,y_(e).div(f_(e).add(y_(e)))),__=(e,t,s)=>{const i=e.uvNode,r=Jm(i,t.zw).add(.5),n=Pg(r),o=Og(r),a=x_(o.x),h=b_(o.x),u=v_(o.x),l=T_(o.x),c=v_(o.y),d=T_(o.y),p=Vp(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),m=Vp(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Vp(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),f=Vp(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),y=x_(o.y).mul(Ym(a.mul(e.uv(p).level(s)),h.mul(e.uv(m).level(s)))),x=b_(o.y).mul(Ym(a.mul(e.uv(g).level(s)),h.mul(e.uv(f).level(s))));return y.add(x)},w_=Cp((([e,t=Up(3)])=>{const s=Vp(e.size(Op(t))),i=Vp(e.size(Op(t.add(1)))),r=Km(1,s),n=Km(1,i),o=__(e,$p(r,s),Pg(t)),a=__(e,$p(n,i),Fg(t));return Og(t).mix(o,a)})),S_=Cp((([e,t,s,i,r])=>{const n=Wp(wf(t.negate(),Ug(e),Km(1,i))),o=Wp(Hg(r[0].xyz),Hg(r[1].xyz),Hg(r[2].xyz));return Ug(n).mul(s.mul(o))})).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"}]}),M_=Cp((([e,t])=>e.mul(Tf(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),A_=Kv(),N_=Cp((([e,t,s])=>{const i=A_.uv(e),r=Eg(Up(Dv.x)).mul(M_(t,s));return w_(i,r)})),C_=Cp((([e,t,s])=>(Ip(s.notEqual(0),(()=>{const i=Rg(t).negate().div(s);return Ng(i.negate().mul(e))})),Wp(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),R_=Cp((([e,t,s,i,r,n,o,a,h,u,l,c,d,p,m])=>{let g,f;if(m){g=$p().toVar(),f=Wp().toVar();const r=l.sub(1).mul(m.mul(.025)),n=Wp(l.sub(r),l,l.add(r));xv({start:0,end:3},(({i:r})=>{const l=n.element(r),m=S_(e,t,c,l,a),y=o.add(m),x=u.mul(h.mul($p(y,1))),b=Vp(x.xy.div(x.w)).toVar();b.addAssign(1),b.divAssign(2),b.assign(Vp(b.x,b.y.oneMinus()));const v=N_(b,s,l);g.element(r).assign(v.element(r)),g.a.addAssign(v.a),f.element(r).assign(i.element(r).mul(C_(Hg(m),d,p).element(r)))})),g.a.divAssign(3)}else{const r=S_(e,t,c,l,a),n=o.add(r),m=u.mul(h.mul($p(n,1))),y=Vp(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Vp(y.x,y.y.oneMinus())),g=N_(y,s,l),f=i.mul(C_(Hg(r),d,p))}const y=f.rgb.mul(g.rgb),x=e.dot(t).clamp(),b=Wp(r_({dotNV:x,specularColor:r,specularF90:n,roughness:s})),v=f.r.add(f.g,f.b).div(3);return $p(b.oneMinus().mul(y),g.a.oneMinus().mul(v).oneMinus())})),E_=Kp(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),B_=(e,t)=>e.sub(t).div(e.add(t)).pow2(),I_=(e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=Wp(54856e-17,44201e-17,52481e-17),r=Wp(1681e3,1795300,2208400),n=Wp(43278e5,93046e5,66121e5),o=Up(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let a=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());a=Wp(a.x.add(o),a.y,a.z).div(1.0685e-7);return E_.mul(a)},P_=Cp((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=vf(e,t,Sf(0,.03,i)),o=e.div(n).pow2().mul(Up(1).sub(s.pow2())),a=Up(1).sub(o).sqrt(),h=B_(n,e),u=DT({f0:h,f90:1,dotVH:s}),l=u.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=Up(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Wp(1).add(t).div(Wp(1).sub(t))})(r.clamp(0,.9999)),m=B_(p,n.toVec3()),g=DT({f0:m,f90:1,dotVH:a}),f=Wp(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(i,a,2),x=Wp(d).add(f),b=u.mul(g).clamp(1e-5,.9999),v=b.sqrt(),T=l.pow2().mul(g).div(Wp(1).sub(b));let _=u.add(T),w=T.sub(l);for(let e=1;e<=2;++e){w=w.mul(v);const t=I_(Up(e).mul(y),Up(e).mul(x)).mul(2);_=_.add(w.mul(t))}return _.max(Wp(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"}]}),F_=Cp((({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.pow2(),n=Ef(s.lessThan(.25),Up(-339.2).mul(r).add(Up(161.4).mul(s)).sub(25.9),Up(-8.48).mul(r).add(Up(14.3).mul(s)).sub(9.95)),o=Ef(s.lessThan(.25),Up(44).mul(r).sub(Up(23.7).mul(s)).add(3.26),Up(1.97).mul(r).sub(Up(3.27).mul(s)).add(.72));return Ef(s.lessThan(.25),0,Up(.1).mul(s).sub(.025)).add(n.mul(i).add(o).exp()).mul(1/Math.PI).saturate()})),U_=Wp(.04),O_=Up(1);class z_ extends OT{constructor(e=!1,t=!1,s=!1,i=!1,r=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=r,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=Wp().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Wp().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Wp().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Wp().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Wp().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=vx.dot(cx).clamp();this.iridescenceFresnel=P_({outsideIOR:Up(1),eta2:Mm,cosTheta1:e,thinFilmThickness:Am,baseF0:Bm}),this.iridescenceF0=n_({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=hx,s=ky.sub(hx).normalize(),i=Tx;e.backdrop=R_(i,s,xm,fm,Bm,Im,t,Zy,Ly,Oy,Lm,Dm,Gm,km,this.dispersion?Wm:null),e.backdropAlpha=Vm,fm.a.mulAssign(vf(1,e.backdrop.a,Vm))}}computeMultiscattering(e,t,s){const i=vx.dot(cx).clamp(),r=i_({roughness:xm,dotNV:i}),n=(this.iridescenceF0?Sm.mix(Bm,this.iridescenceF0):Bm).mul(r.x).add(s.mul(r.y)),o=r.x.add(r.y).oneMinus(),a=Bm.add(Bm.oneMinus().mul(.047619)),h=n.mul(a).div(o.mul(a).oneMinus());e.addAssign(n),t.addAssign(h.mul(o))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=vx.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(h_({lightDirection:e}))),!0===this.clearcoat){const s=_x.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(s_({lightDirection:e,f0:U_,f90:O_,roughness:Tm,normalView:_x})))}s.directDiffuse.addAssign(i.mul(kT({diffuseColor:fm.rgb}))),s.directSpecular.addAssign(i.mul(s_({lightDirection:e,f0:Bm,f90:1,roughness:xm,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:r,ltc_1:n,ltc_2:o}){const a=t.add(s).sub(i),h=t.sub(s).sub(i),u=t.sub(s).add(i),l=t.add(s).add(i),c=vx,d=cx,p=lx.toVar(),m=u_({N:c,V:d,roughness:xm}),g=n.uv(m).toVar(),f=o.uv(m).toVar(),y=Kp(Wp(g.x,0,g.y),Wp(0,1,0),Wp(g.z,0,g.w)).toVar(),x=Bm.mul(f.x).add(Bm.oneMinus().mul(f.y)).toVar();r.directSpecular.addAssign(e.mul(x).mul(d_({N:c,V:d,P:p,mInv:y,p0:a,p1:h,p2:u,p3:l}))),r.directDiffuse.addAssign(e.mul(fm).mul(d_({N:c,V:d,P:p,mInv:Kp(1,0,0,0,1,0,0,0,1),p0:a,p1:h,p2:u,p3:l})))}indirect(e,t,s){this.indirectDiffuse(e,t,s),this.indirectSpecular(e,t,s),this.ambientOcclusion(e,t,s)}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(kT({diffuseColor:fm})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:s}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(_m,F_({normal:vx,viewDir:cx,roughness:wm}))),!0===this.clearcoat){const e=_x.dot(cx).clamp(),t=r_({dotNV:e,specularColor:U_,specularF90:O_,roughness:Tm});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=Wp().toVar("singleScattering"),r=Wp().toVar("multiScattering"),n=t.mul(1/Math.PI);this.computeMultiscattering(i,r,Im);const o=i.add(r),a=fm.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(e.mul(i)),s.indirectSpecular.addAssign(r.mul(n)),s.indirectDiffuse.addAssign(a.mul(n))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const s=vx.dot(cx).clamp().add(e),i=xm.mul(-16).oneMinus().negate().exp2(),r=e.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(r)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=_x.dot(cx).clamp(),s=DT({dotVH:e,f0:U_,f90:O_}),i=t.mul(vm.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(vm));t.assign(i)}if(!0===this.sheen){const e=_m.r.max(_m.g).max(_m.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const L_=Up(1),V_=Up(-2),D_=Up(.8),k_=Up(-1),G_=Up(.4),W_=Up(2),j_=Up(.305),H_=Up(3),q_=Up(.21),$_=Up(4),X_=Up(4),Y_=Up(16),Z_=Cp((([e])=>{const t=Wp(Wg(e)).toVar(),s=Up(-1).toVar();return Ip(t.x.greaterThan(t.z),(()=>{Ip(t.x.greaterThan(t.y),(()=>{s.assign(Ef(e.x.greaterThan(0),0,3))})).Else((()=>{s.assign(Ef(e.y.greaterThan(0),1,4))}))})).Else((()=>{Ip(t.z.greaterThan(t.y),(()=>{s.assign(Ef(e.z.greaterThan(0),2,5))})).Else((()=>{s.assign(Ef(e.y.greaterThan(0),1,4))}))})),s})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),J_=Cp((([e,t])=>{const s=Vp().toVar();return Ip(t.equal(0),(()=>{s.assign(Vp(e.z,e.y).div(Wg(e.x)))})).ElseIf(t.equal(1),(()=>{s.assign(Vp(e.x.negate(),e.z.negate()).div(Wg(e.y)))})).ElseIf(t.equal(2),(()=>{s.assign(Vp(e.x.negate(),e.y).div(Wg(e.z)))})).ElseIf(t.equal(3),(()=>{s.assign(Vp(e.z.negate(),e.y).div(Wg(e.x)))})).ElseIf(t.equal(4),(()=>{s.assign(Vp(e.x.negate(),e.z).div(Wg(e.y)))})).Else((()=>{s.assign(Vp(e.x,e.y).div(Wg(e.z)))})),Jm(.5,s.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),K_=Cp((([e])=>{const t=Up(0).toVar();return Ip(e.greaterThanEqual(D_),(()=>{t.assign(L_.sub(e).mul(k_.sub(V_)).div(L_.sub(D_)).add(V_))})).ElseIf(e.greaterThanEqual(G_),(()=>{t.assign(D_.sub(e).mul(W_.sub(k_)).div(D_.sub(G_)).add(k_))})).ElseIf(e.greaterThanEqual(j_),(()=>{t.assign(G_.sub(e).mul(H_.sub(W_)).div(G_.sub(j_)).add(W_))})).ElseIf(e.greaterThanEqual(q_),(()=>{t.assign(j_.sub(e).mul($_.sub(H_)).div(j_.sub(q_)).add(H_))})).Else((()=>{t.assign(Up(-2).mul(Eg(Jm(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Q_=Cp((([e,t])=>{const s=e.toVar();s.assign(Jm(2,s).sub(1));const i=Wp(s,1).toVar();return Ip(t.equal(0),(()=>{i.assign(i.zyx)})).ElseIf(t.equal(1),(()=>{i.assign(i.xzy),i.xz.mulAssign(-1)})).ElseIf(t.equal(2),(()=>{i.x.mulAssign(-1)})).ElseIf(t.equal(3),(()=>{i.assign(i.zyx),i.xz.mulAssign(-1)})).ElseIf(t.equal(4),(()=>{i.assign(i.xzy),i.xy.mulAssign(-1)})).ElseIf(t.equal(5),(()=>{i.z.mulAssign(-1)})),i})).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),ew=Cp((([e,t,s,i,r,n])=>{const o=Up(s),a=Wp(t),h=Tf(K_(o),V_,n),u=Og(h),l=Pg(h),c=Wp(tw(e,a,l,i,r,n)).toVar();return Ip(u.notEqual(0),(()=>{const t=Wp(tw(e,a,l.add(1),i,r,n)).toVar();c.assign(vf(c,t,u))})),c})),tw=Cp((([e,t,s,i,r,n])=>{const o=Up(s).toVar(),a=Wp(t),h=Up(Z_(a)).toVar(),u=Up(nf(X_.sub(o),0)).toVar();o.assign(nf(o,X_));const l=Up(Cg(o)).toVar(),c=Vp(J_(a,h).mul(l.sub(2)).add(1)).toVar();return Ip(h.greaterThan(2),(()=>{c.y.addAssign(l),h.subAssign(3)})),c.x.addAssign(h.mul(l)),c.x.addAssign(u.mul(Jm(3,Y_))),c.y.addAssign(Jm(4,Cg(n).sub(l))),c.x.mulAssign(i),c.y.mulAssign(r),e.uv(c).grad(Vp(),Vp())})),sw=Cp((({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const h=Lg(i),u=s.mul(h).add(r.cross(s).mul(zg(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return tw(e,u,t,n,o,a)})),iw=Cp((({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:o,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})=>{const d=Wp(Ef(t,s,df(s,i))).toVar();Ip(_g(d.equals(Wp(0))),(()=>{d.assign(Wp(i.z,0,i.x.negate()))})),d.assign(Ug(d));const p=Wp().toVar();return p.addAssign(r.element(Op(0)).mul(sw({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),xv({start:Op(1),end:e},(({i:e})=>{Ip(e.greaterThanEqual(n),(()=>{vv()}));const t=Up(o.mul(Up(e))).toVar();p.addAssign(r.element(e).mul(sw({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(sw({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})))})),$p(p,1)}));let rw=null;const nw=new WeakMap;function ow(e){let t=nw.get(e);if((void 0!==t?t.pmremVersion:-1)!==e.pmremVersion){const s=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const s=6;for(let i=0;i0}(s))return null;t=rw.fromEquirectangular(e,t)}t.pmremVersion=e.pmremVersion,nw.set(e,t)}return t.texture}class aw extends Dd{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new yi;i.isRenderTargetTexture=!0,this._texture=By(i),this._width=dm(0),this._height=dm(0),this._maxMip=dm(0),this.updateBeforeType=Ed.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,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:s,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(){let e=this._pmrem;const t=e?e.pmremVersion:-1,s=this._value;t!==s.pmremVersion&&(e=!0===s.isPMREMTexture?s:ow(s),null!==e&&(this._pmrem=e,this.updateFromTexture(e)))}setup(e){null===rw&&(rw=e.createPMREMGenerator()),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this));const s=this.value;e.renderer.coordinateSystem===Us&&!0!==s.isPMREMTexture&&!0===s.isRenderTargetTexture&&(t=Wp(t.x.negate(),t.yz));let i=this.levelNode;return null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),ew(this._texture,t,i,this._width,this._height,this._maxMip)}}const hw=Ap(aw),uw=new WeakMap;class lw extends Bv{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:t[s.property];let i=uw.get(e);void 0===i&&(i=hw(e),uw.set(e,i)),s=i}const i=t.envMap?Dx("envMapIntensity","float",e.material):Dx("environmentIntensity","float",e.scene),r=!0===t.useAnisotropy||t.anisotropy>0?ob:vx,n=s.context(cw(xm,r)).mul(i),o=s.context(dw(Tx)).mul(Math.PI).mul(i),a=ly(n),h=ly(o);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(h);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=s.context(cw(Tm,_x)).mul(i),t=ly(e);u.addAssign(t)}}}const cw=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=cx.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(Ly)),s),getTextureLevel:()=>e}},dw=e=>({getUV:()=>e,getTextureLevel:()=>Up(1)}),pw=new Tu;class mw extends pT{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(pw),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new lw(t):null}setupLightingModel(){return new z_}setupSpecular(){const e=vf(Wp(.04),fm.rgb,bm);Bm.assign(e),Im.assign(1)}setupVariants(){const e=this.metalnessNode?Up(this.metalnessNode):Nb;bm.assign(e);let t=this.roughnessNode?Up(this.roughnessNode):Ab;t=ZT({roughness:t}),xm.assign(t),this.setupSpecular(),fm.assign($p(fm.rgb.mul(e.oneMinus()),fm.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const gw=new _u;class fw extends mw{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(gw),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?Up(this.iorNode):kb;Lm.assign(e),Bm.assign(vf(rf(mf(Lm.sub(1).div(Lm.add(1))).mul(wb),Wp(1)).mul(_b),fm.rgb,bm)),Im.assign(vf(_b,1,bm))}setupLightingModel(){return new z_(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Up(this.clearcoatNode):Rb,t=this.clearcoatRoughnessNode?Up(this.clearcoatRoughnessNode):Eb;vm.assign(e),Tm.assign(ZT({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Wp(this.sheenNode):Pb,t=this.sheenRoughnessNode?Up(this.sheenRoughnessNode):Fb;_m.assign(e),wm.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Up(this.iridescenceNode):Ob,t=this.iridescenceIORNode?Up(this.iridescenceIORNode):zb,s=this.iridescenceThicknessNode?Up(this.iridescenceThicknessNode):Lb;Sm.assign(e),Mm.assign(t),Am.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?Vp(this.anisotropyNode):Ub).toVar();Cm.assign(e.length()),Ip(Cm.equal(0),(()=>{e.assign(Vp(1,0))})).Else((()=>{e.divAssign(Vp(Cm)),Cm.assign(Cm.saturate())})),Nm.assign(Cm.pow2().mix(xm.pow2(),1)),Rm.assign(ib[0].mul(e.x).add(ib[1].mul(e.y))),Em.assign(ib[1].mul(e.x).sub(ib[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Up(this.transmissionNode):Vb,t=this.thicknessNode?Up(this.thicknessNode):Db,s=this.attenuationDistanceNode?Up(this.attenuationDistanceNode):Gb,i=this.attenuationColorNode?Wp(this.attenuationColorNode):Wb;if(Vm.assign(e),Dm.assign(t),km.assign(s),Gm.assign(i),this.useDispersion){const e=this.dispersionNode?Up(this.dispersionNode):Zb;Wm.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Wp(this.clearcoatNormalNode):Bb}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),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 yw extends z_{constructor(e,t,s,i){super(e,t,s),this.useSSS=i}direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){if(!0===this.useSSS){const i=r.material,{thicknessColorNode:n,thicknessDistortionNode:o,thicknessAmbientNode:a,thicknessAttenuationNode:h,thicknessPowerNode:u,thicknessScaleNode:l}=i,c=e.add(vx.mul(o)).normalize(),d=Up(cx.dot(c.negate()).saturate().pow(u).mul(l)),p=Wp(d.add(a).mul(n));s.directDiffuse.addAssign(p.mul(h.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r)}}class xw extends fw{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=Up(.1),this.thicknessAmbientNode=Up(0),this.thicknessAttenuationNode=Up(.1),this.thicknessPowerNode=Up(2),this.thicknessScaleNode=Up(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new yw(this.useClearcoat,this.useSheen,this.useIridescence,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 bw=Cp((({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=Vp(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=Wx("gradientMap","texture").context({getUV:()=>r});return Wp(e.r)}{const e=r.fwidth().mul(.5);return vf(Wp(.7),Wp(1),Sf(Up(.7).sub(e.x),Up(.7).add(e.x),r.x))}}));class vw extends OT{direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){const n=bw({normal:gx,lightDirection:e,builder:r}).mul(t);s.directDiffuse.addAssign(n.mul(kT({diffuseColor:fm.rgb})))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(kT({diffuseColor:fm}))),s.indirectDiffuse.mulAssign(e)}}const Tw=new Su;class _w extends pT{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Tw),this.setValues(e)}setupLightingModel(){return new vw}}class ww extends Dd{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=Wp(cx.z,0,cx.x.negate()).normalize(),t=cx.cross(e);return Vp(e.dot(vx),t.dot(vx)).mul(.495).add(.5)}}const Sw=Np(ww),Mw=new Ru;class Aw extends pT{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Mw),this.setValues(e)}setupVariants(e){const t=Sw;let s;s=e.material.matcap?Wx("matcap","texture").context({getUV:()=>t}):Wp(vf(.2,.8,t.y)),fm.rgb.mulAssign(s.rgb)}}const Nw=new Fa;class Cw extends pT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.isPointsNodeMaterial=!0,this.lights=!1,this.transparent=!0,this.sizeNode=null,this.setDefaultValues(Nw),this.setValues(e)}copy(e){return this.sizeNode=e.sizeNode,super.copy(e)}}class Rw extends Dd{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:s}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return Jp(e,i,i.negate(),e).mul(s)}{const e=t,i=Qp($p(1,0,0,0),$p(0,Lg(e.x),zg(e.x).negate(),0),$p(0,zg(e.x),Lg(e.x),0),$p(0,0,0,1)),r=Qp($p(Lg(e.y),0,zg(e.y),0),$p(0,1,0,0),$p(zg(e.y).negate(),0,Lg(e.y),0),$p(0,0,0,1)),n=Qp($p(Lg(e.z),zg(e.z).negate(),0,0),$p(zg(e.z),Lg(e.z),0,0),$p(0,0,1,0),$p(0,0,0,1));return i.mul(r).mul(n).mul($p(s,1)).xyz}}}const Ew=Ap(Rw),Bw=new so;class Iw extends pT{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this.lights=!1,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.setDefaultValues(Bw),this.setValues(e)}setupPosition({object:e,camera:t,context:s}){const i=this.sizeAttenuation,{positionNode:r,rotationNode:n,scaleNode:o}=this,a=ox;let h=sx.mul(Wp(r||0)),u=Vp(Zy[0].xyz.length(),Zy[1].xyz.length());if(null!==o&&(u=u.mul(o)),!i)if(t.isPerspectiveCamera)u=u.mul(h.z.negate());else{const e=Up(2).div(Oy.element(1).element(1));u=u.mul(e.mul(2))}let l=a.xy;if(e.center&&!0===e.center.isVector2){const e=((e,t,s)=>wp(new Zf(e,t,s)))("center","vec2");l=l.sub(e.sub(.5))}l=l.mul(u);const c=Up(n||Ib),d=Ew(l,c);h=$p(h.xy.add(d),h.zw);const p=Oy.mul(h);return s.vertex=a,p}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)}}class Pw extends OT{constructor(){super(),this.shadowNode=Up(1).toVar("shadowMask")}direct({shadowMask:e}){this.shadowNode.mulAssign(e)}finish(e){fm.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(fm.rgb)}}const Fw=new bu;class Uw extends pT{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Fw),this.setValues(e)}setupLightingModel(){return new Pw}}const Ow=Cp((({texture:e,uv:t})=>{const s=1e-4,i=Wp().toVar();return Ip(t.x.lessThan(s),(()=>{i.assign(Wp(1,0,0))})).ElseIf(t.y.lessThan(s),(()=>{i.assign(Wp(0,1,0))})).ElseIf(t.z.lessThan(s),(()=>{i.assign(Wp(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(Wp(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(Wp(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(Wp(0,0,-1))})).Else((()=>{const s=.01,r=e.uv(t.add(Wp(-.01,0,0))).r.sub(e.uv(t.add(Wp(s,0,0))).r),n=e.uv(t.add(Wp(0,-.01,0))).r.sub(e.uv(t.add(Wp(0,s,0))).r),o=e.uv(t.add(Wp(0,0,-.01))).r.sub(e.uv(t.add(Wp(0,0,s))).r);i.assign(Wp(r,n,o))})),i.normalize()}));class zw extends Ey{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Wp(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){return t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return Ow({texture:this,uv:e})}}const Lw=Ap(zw);class Vw extends pT{static get type(){return"VolumeNodeMaterial"}constructor(e={}){super(),this.lights=!1,this.isVolumeNodeMaterial=!0,this.testNode=null,this.setValues(e)}setup(e){const t=Lw(this.map,null,0),s=Cp((({orig:e,dir:t})=>{const s=Wp(-.5),i=Wp(.5),r=t.reciprocal(),n=s.sub(e).mul(r),o=i.sub(e).mul(r),a=rf(n,o),h=nf(n,o),u=nf(a.x,nf(a.y,a.z)),l=rf(h.x,rf(h.y,h.z));return Vp(u,l)}));this.fragmentNode=Cp((()=>{const e=Vf(Wp(tx.mul($p(ky,1)))),i=Vf(nx.sub(e)).normalize(),r=Vp(s({orig:e,dir:i})).toVar();r.x.greaterThan(r.y).discard(),r.assign(Vp(nf(r.x,0),r.y));const n=Wp(e.add(r.x.mul(i))).toVar(),o=Wp(i.abs().reciprocal()).toVar(),a=Up(rf(o.x,rf(o.y,o.z))).toVar("delta");a.divAssign(Wx("steps","float"));const h=$p(Wx("base","color"),0).toVar();return xv({type:"float",start:r.x,end:r.y,update:"+= delta"},(()=>{const e=mm("float","d").assign(t.uv(n.add(.5)).r);null!==this.testNode?this.testNode({map:t,mapValue:e,probe:n,finalColor:h}).append():(h.a.assign(1),vv()),n.addAssign(i.mul(a))})),h.a.equal(0).discard(),$p(h)}))(),super.setup(e)}}class Dw{constructor(e,t){this.nodes=e,this.info=t,this.animationLoop=null,this.requestId=null,this._init()}_init(){const e=(t,s)=>{this.requestId=self.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,s)};e()}dispose(){self.cancelAnimationFrame(this.requestId),this.requestId=null}setAnimationLoop(e){this.animationLoop=e}}class kw{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let s=0;s{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){const t=this.material;let s=this.clippingContext;Array.isArray(t.clippingPlanes)?(s!==e&&s||(s=new Ww,this.clippingContext=s),s.update(e,t)):this.clippingContext!==e&&(this.clippingContext=e)}get clippingNeedsUpdate(){return this.clippingContext.version!==this.clippingContextVersion&&(this.clippingContextVersion=this.clippingContext.version,!0)}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().monitor)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;s.push(e);const n=e.isInterleavedBufferAttribute?e.data:e;i.add(n)}return this.attributes=s,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:r}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),o=this.getIndex(),a=null!==o,h=s.isInstancedBufferGeometry?s.instanceCount:e.count>1?e.count:1;if(0===h)return null;if(n.instanceCount=h,!0===e.isBatchedMesh)return n;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let l=r.start*u,c=(r.start+r.count)*u;null!==i&&(l=Math.max(l,i.start*u),c=Math.min(c,(i.start+i.count)*u));const d=s.attributes.position;let p=1/0;a?p=o.count:null!=d&&(p=d.count),l=Math.max(l,0),c=Math.min(c,p);const m=c-l;return m<0||m===1/0?null:(n.vertexCount=m,n.firstVertex=l,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t}=this;let s=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let s=Object.getPrototypeOf(e);for(;s;){const e=Object.getOwnPropertyDescriptors(s);for(const s in e)if(void 0!==e[s]){const i=e[s];i&&"function"==typeof i.get&&t.push(s)}s=Object.getPrototypeOf(s)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const i=t[e];let r;if(null!==i){const e=typeof i;"number"===e?r=0!==i?"1":"0":"object"===e?(r="{",i.isTexture&&(r+=i.mapping),r+="}"):r=String(i)}else r=String(i);s+=r+","}return s+=this.clippingContext.cacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.morphTargetInfluences&&(s+=e.morphTargetInfluences.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),bd(s)}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=this._nodes.getCacheKey(this.scene,this.lightsNode);return this.object.receiveShadow&&(e+=1),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const qw=[];class $w{constructor(e,t,s,i,r,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=r,this.info=n,this.chainMaps={}}get(e,t,s,i,r,n,o){const a=this.getChainMap(o);qw[0]=e,qw[1]=t,qw[2]=n,qw[3]=r;let h=a.get(qw);return void 0===h?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o),a.set(qw,h)):(h.updateClipping(n.clippingContext),(h.version!==t.version||h.needsUpdate)&&(h.initialCacheKey!==h.getCacheKey()?(h.dispose(),h=this.get(e,t,s,i,r,n,o)):h.version=t.version)),h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new kw)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,h,u){const l=this.getChainMap(u),c=new Hw(e,t,s,i,r,n,o,a,h);return c.onDispose=()=>{this.pipelines.delete(c),this.bindings.delete(c),this.nodes.delete(c),l.delete(c.getChainArray())},c}}class Xw{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;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 Yw=1,Zw=2,Jw=3,Kw=4,Qw=16;class eS extends Xw{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return void 0!==t&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===Yw?this.backend.createAttribute(e):t===Zw?this.backend.createIndexAttribute(e):t===Jw?this.backend.createStorageAttribute(e):t===Kw&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version=0;--t)if(e[t]>=65535)return!0;return!1}(t)?mn:dn)(t,1);return r.version=tS(e),r}class iS extends Xw{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",s)};t.addEventListener("dispose",s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,Jw):this.updateAttribute(e,Yw);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,Zw);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,Kw)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=sS(t),e.set(t,s)):s.version!==tS(t)&&(this.attributes.delete(s),s=sS(t),e.set(t,s)),i=s}return i}}class rS{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,previousFrameCalls:0,timestampCalls:0},this.compute={calls:0,frameCalls:0,timestamp:0,previousFrameCalls:0,timestampCalls:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}updateTimestamp(e,t){0===this[e].timestampCalls&&(this[e].timestamp=0),this[e].timestamp+=t,this[e].timestampCalls++,this[e].timestampCalls>=this[e].previousFrameCalls&&(this[e].timestampCalls=0)}reset(){const e=this.render.frameCalls;this.render.previousFrameCalls=e;const t=this.compute.frameCalls;this.compute.previousFrameCalls=t,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 nS{constructor(e){this.cacheKey=e,this.usedTimes=0}}class oS extends nS{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class aS extends nS{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let hS=0;class uS{constructor(e,t,s=null,i=null){this.id=hS++,this.code=e,this.stage=t,this.transforms=s,this.attributes=i,this.usedTimes=0}}class lS extends Xw{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:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let o=this.programs.compute.get(n.computeShader);void 0===o&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),o=new uS(n.computeShader,"compute",n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,o),s.createProgram(o));const a=this._getComputeCacheKey(e,o);let h=this.caches.get(a);void 0===h&&(r&&0===r.usedTimes&&this._releasePipeline(r),h=this._getComputePipeline(e,o,a,t)),h.usedTimes++,o.usedTimes++,i.version=e.version,i.pipeline=h}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState();let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new uS(n.vertexShader,"vertex"),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o));let a=this.programs.fragment.get(n.fragmentShader);void 0===a&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),a=new uS(n.fragmentShader,"fragment"),this.programs.fragment.set(n.fragmentShader,a),s.createProgram(a));const h=this._getRenderCacheKey(e,o,a);let u=this.caches.get(h);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,o,a,h,t)):e.pipeline=u,u.usedTimes++,o.usedTimes++,a.usedTimes++,i.pipeline=u}return i.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,s,i){s=s||this._getComputeCacheKey(e,t);let r=this.caches.get(s);return void 0===r&&(r=new aS(s,t),this.caches.set(s,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,s,i,r){i=i||this._getRenderCacheKey(e,t,s);let n=this.caches.get(i);return void 0===n&&(n=new oS(i,t,s),this.caches.set(i,n),e.pipeline=n,this.backend.createRenderPipeline(e,r)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].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 cS extends Xw{constructor(e,t,s,i,r,n){super(),this.backend=e,this.textures=s,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t),s.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t),s.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,s=e.isIndirectStorageBufferAttribute?Kw:Jw;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!this.nodes.updateGroup(t))continue}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){t.needsBindingsUpdate(this.textures.get(t.texture).generation)&&(i=!0);const e=t.update(),r=t.texture;e&&this.textures.updateTexture(r);const n=s.get(r);if(!0===s.isWebGPUBackend&&void 0===n.texture&&void 0===n.externalTexture&&(console.error("Bindings._update: binding should be available:",t,e,r,t.textureNode.value,i),this.textures.updateTexture(r),i=!0),!0===r.isStorageTexture){const e=this.get(r);!0===t.store?e.needsMipmap=!0:!0===r.generateMipmaps&&this.textures.needsMipmaps(r)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(r),e.needsMipmap=!1)}}}!0===i&&this.backend.updateBindings(e,t)}}class dS{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class pS{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf()}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 mS{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class gS extends mS{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class fS{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let yS=0;class xS{constructor(e=null){this.id=yS++,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 bS extends pm{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}const vS=(e,t)=>wp(new bS(e,t));class TS extends zd{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.code=e,this.language=s,this.includes=t}isGlobal(){return!0}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.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 _S=Ap(TS),wS=(e,t)=>_S(e,t,"js"),SS=(e,t)=>_S(e,t,"wgsl"),MS=(e,t)=>_S(e,t,"glsl");class AS extends TS{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,r=s.type,n=e.getCodeFromNode(this,r);""!==i&&(n.name=i);const o=e.getPropertyName(n),a=this.getNodeFunction(e).getCode(o);return n.code=a+"\n","property"===t?o:e.format(`${o}()`,r,t)}}const NS=(e,t=[],s="")=>{for(let e=0;ei.call(...e);return r.functionNode=i,r},CS=(e,t)=>NS(e,t,"glsl"),RS=(e,t)=>NS(e,t,"wgsl");class ES{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 BS extends ES{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class IS extends ES{constructor(e,t=new Ys){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class PS extends ES{constructor(e,t=new Ai){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class FS extends ES{constructor(e,t=new xi){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class US extends ES{constructor(e,t=new Xr){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class OS extends ES{constructor(e,t=new Zs){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class zS extends ES{constructor(e,t=new sr){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class LS extends BS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class VS extends IS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class DS extends PS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class kS extends FS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class GS extends US{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class WS extends OS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class jS extends zS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class HS extends zd{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}add(e){return this.nodes.push(e),this}If(e,t){const s=new _p(t);return this._currentCond=Ef(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new _p(t),i=Ef(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new _p(e),this}build(e,...t){const s=Bp();Ep(this);for(const t of this.nodes)t.build(e,"void");return Ep(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("TSL.StackNode: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("TSL.StackNode: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const qS=Ap(HS),$S=[.125,.215,.35,.446,.526,.582],XS=20,YS=new wl(-1,1,1,-1,0,1),ZS=new Hn(90,1),JS=new Xr;let KS=null,QS=0,eM=0;const tM=(1+Math.sqrt(5))/2,sM=1/tM,iM=[new Ai(-tM,sM,0),new Ai(tM,sM,0),new Ai(-sM,0,tM),new Ai(sM,0,tM),new Ai(0,tM,-sM),new Ai(0,tM,sM),new Ai(-1,1,-1),new Ai(1,1,-1),new Ai(-1,1,1),new Ai(1,1,1)],rM=[3,1,5,0,4,2],nM=Q_(My(),Sy("faceIndex")).normalize(),oM=Wp(nM.x,nM.y.negate(),nM.z);class aM{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}fromScene(e,t=0,s=.1,i=100){KS=this._renderer.getRenderTarget(),QS=this._renderer.getActiveCubeFace(),eM=this._renderer.getActiveMipmapLevel(),this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,s,i,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=cM(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=dM(),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())}_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?h=$S[a-e+4-1]:0===a&&(h=0),i.push(h);const u=1/(o-2),l=-u,c=1+u,d=[l,l,c,l,c,c,l,l,c,c,l,c],p=6,m=6,g=3,f=2,y=1,x=new Float32Array(g*m*p),b=new Float32Array(f*m*p),v=new Float32Array(y*m*p);for(let e=0;e2?0:-1,i=[t,s,0,t+2/3,s,0,t+2/3,s+1,0,t,s,0,t+2/3,s+1,0,t,s+1,0],r=rM[e];x.set(i,g*m*r),b.set(d,f*m*r);const n=[r,r,r,r,r,r];v.set(n,y*m*r)}const T=new Sn;T.setAttribute("position",new an(x,g)),T.setAttribute("uv",new an(b,f)),T.setAttribute("faceIndex",new an(v,y)),t.push(T),r.push(new On(T,null)),n>4&&n--}return{lodPlanes:t,sizeLods:s,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,s){const i=Ox(new Array(XS).fill(0)),r=dm(new Ai(0,1,0)),n=dm(0),o=Up(XS),a=dm(0),h=dm(1),u=By(null),l=dm(0),c=Up(1/t),d=Up(1/s),p=Up(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:oM,dTheta:n,samples:h,envMap:u,mipInt:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=lM("blur");return g.uniforms=m,g.fragmentNode=iw({...m,latitudinal:a.equal(1)}),g}(i,e,t)}return i}async _compileMaterial(e){const t=new On(this._lodPlanes[0],e);await this._renderer.compile(t,YS)}_sceneToCubeUV(e,t,s,i){const r=ZS;r.near=t,r.far=s;const n=[-1,1,-1,-1,-1,-1],o=[1,1,1,-1,-1,-1],a=this._renderer,h=a.autoClear;a.getClearColor(JS),a.autoClear=!1;let u=this._backgroundBox;if(null===u){const e=new Kr({name:"PMREM.Background",side:d,depthWrite:!1,depthTest:!1});u=new On(new Ln,e)}let l=!1;const c=e.background;c?c.isColor&&(u.material.color.copy(c),e.background=null,l=!0):(u.material.color.copy(JS),l=!0),a.setRenderTarget(i),a.clear(),l&&a.render(u,r);for(let t=0;t<6;t++){const s=t%3;0===s?(r.up.set(0,n[t],0),r.lookAt(o[t],0,0)):1===s?(r.up.set(0,0,n[t]),r.lookAt(0,o[t],0)):(r.up.set(0,n[t],0),r.lookAt(0,0,o[t]));const h=this._cubeSize;uM(i,s*h,t>2?h:0,h,h),a.render(e,r)}a.autoClear=h,e.background=c}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===he||e.mapping===ue;i?null===this._cubemapMaterial&&(this._cubemapMaterial=cM(e)):null===this._equirectMaterial&&(this._equirectMaterial=dM(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;uM(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,YS)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;tXS&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const g=[];let f=0;for(let e=0;ey-4?i-y+4:0),4*(this._cubeSize-x),3*x,2*x),a.setRenderTarget(t),a.render(u,YS)}}function hM(e,t,s){const i=new bi(e,t,s);return i.texture.mapping=de,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function uM(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function lM(e){const t=new pT;return t.depthTest=!1,t.depthWrite=!1,t.blending=m,t.name=`PMREM_${e}`,t}function cM(e){const t=lM("cubemap");return t.fragmentNode=Bx(e,oM),t}function dM(e){const t=lM("equirect");return t.fragmentNode=By(e,NT(oM),0),t}let pM=0;class mM{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=pM++}}const gM=new WeakMap,fM=new Map([[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),yM=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),xM=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class bM{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.monitor=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.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=qS(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new xS,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.useComparisonMethod=!1}getBindGroupsCache(){let e=gM.get(this.renderer);return void 0===e&&(e=new kw,gM.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new bi(e,t,s)}createCubeRenderTarget(e,t){return new CT(e,t)}createPMREMGenerator(){return new aM(this.renderer)}includes(e){return this.nodes.includes(e)}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let r,n=!0;for(const e of t)i.push(e),n=n&&!0!==e.groupNode.shared;return n?(r=s.get(i),void 0===r&&(r=new mM(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new mM(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},s=this.bindings;for(const e of Fd)for(const i in s[e]){const r=s[e][i];(t[i]||(t[i]=[])).push(...r)}e=[];for(const s in t){const i=t[s],r=this._getBindGroup(s,i);e.push(r)}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(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${xM(t.r)}, ${xM(t.g)}, ${xM(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>4&&t&&(t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' 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 s=this.attributes;for(const t of s)if(t.name===e)return t;const i=new dS(e,t);return s.push(i),i}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||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Ee)return"int";if(t===Be)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;const s=fM.get(e);return("float"===t?"":t[0])+s}getTypeFromArray(e){return yM.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof gn||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[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(){return this.stack=qS(this.stack),this.stacks.push(Bp()||this.stack),Ep(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Ep(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let i=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getData(e);return void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e);let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new dS("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeFromNode(e,t=this.shaderStage){const s=this.getDataFromNode(e,t);if(void 0===s.structType){const i=this.structs.index++;e.name=`StructType${i}`,this.structs[t].push(e),s.structType=e}return e}getUniformFromNode(e,t,s=this.shaderStage,i=null){const r=this.getDataFromNode(e,s,this.globalCache);let n=r.uniform;if(void 0===n){const o=this.uniforms.index++;n=new pS(i||"nodeUniform"+o,t,e),this.uniforms[s].push(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage){const r=this.getDataFromNode(e,i);let n=r.variable;if(void 0===n){const e=this.vars[i]||(this.vars[i]=[]);null===t&&(t="nodeVar"+e.length),n=new mS(t,s),e.push(n),r.variable=n}return n}getVaryingFromNode(e,t=null,s=e.getNodeType(this)){const i=this.getDataFromNode(e,"any");let r=i.varying;if(void 0===r){const e=this.varyings,n=e.length;null===t&&(t="nodeVarying"+n),r=new gS(t,s),e.push(r),i.varying=r}return r}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;r=new fS("nodeCode"+n,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,n=t;for(;n;){if(!0===i.get(n)){r=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(r)for(const e of s)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),n=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),n.set(s,!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),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}buildFunctionNode(e){const t=new AS,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[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)s[e.name]=new bS(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,r=this.cache,n=this.buildStage,o=this.stack,a={code:""};this.flow=a,this.vars={},this.cache=new xS,this.stack=qS();for(const s of Pd)this.setBuildStage(s),a.result=e.build(this,t);return a.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.cache=r,this.stack=o,this.setBuildStage(n),a}getFunctionOperator(){return null}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const r=this.shaderStage;this.setShaderStage(e);const n=this.flowChildNode(t,s);return null!==i&&(n.code+=`${this.tab+i} = ${n.result};\n`),this.flowCode[e]=this.flowCode[e]+n.code,this.setShaderStage(r),n}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t){return`${this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(void 0!==s)for(const e of s)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}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.")}build(){const{object:e,material:t,renderer:s}=this;if(null!==t){let e=s.nodes.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new pT),e.build(this)}else this.addFlow("compute",e);for(const e of Pd){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of Fd){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"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 LS(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new VS(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new DS(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new kS(e);if("color"===t)return new GS(e);if("mat3"===t)return new WS(e);if("mat4"===t)return new jS(e);throw new Error(`Uniform "${t}" not declared.`)}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const i=this.getTypeLength(t),r=this.getTypeLength(s);return 16===i&&9===r?`${this.getType(s)}(${e}[0].xyz, ${e}[1].xyz, ${e}[2].xyz)`:9===i&&4===r?`${this.getType(s)}(${e}[0].xy, ${e}[1].xy)`:i>4||r>4||0===r?e:i===r?`${this.getType(s)}( ${e} )`:i>r?this.format(`${e}.${"xyz".slice(0,r)}`,this.getTypeFromLength(r,this.getComponentType(t)),s):4===r&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${e} - Node System\n`}}class vM{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.startTime=null,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 s=e.get(t);return void 0===s&&(s={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(s,this.renderId)}else t===Ed.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(s,this.renderId)}else t===Ed.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.frameId&&!1!==e.update(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.renderId&&!1!==e.update(this)&&t.set(s,this.renderId)}else t===Ed.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 TM{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}TM.isNodeFunctionInput=!0;class _M extends zd{static get type(){return"StructTypeNode"}constructor(e){super(),this.types=e,this.isStructTypeNode=!0}getMemberTypes(){return this.types}}class wM extends zd{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}setup(e){super.setup(e);const t=this.members,s=[];for(let i=0;ir&&(i=s,r=n)}}this._candidateFnCall=s=i(...t)}return s}}const RM=Ap(CM),EM=e=>(...t)=>RM(e,...t);class BM extends zd{static get type(){return"SpriteSheetUVNode"}constructor(e,t=My(),s=Up(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=s}setup(){const{frameNode:e,uvNode:t,countNode:s}=this,{width:i,height:r}=s,n=e.mod(i.mul(r)).floor(),o=n.mod(i),a=r.sub(n.add(1).div(i).ceil()),h=s.reciprocal(),u=Vp(o,a);return t.add(u).mul(h)}}const IM=Ap(BM);class PM extends Ld{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}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.bufferObject&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let s;const i=e.context.assign;if(s=!1===e.isAvailable("storageBuffer")?!0===this.node.bufferObject&&!0!==i?e.generatePBO(this):this.node.build(e):super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}const FM=Ap(PM);class UM extends zd{static get type(){return"TriplanarTexturesNode"}constructor(e,t=null,s=null,i=Up(1),r=ox,n=fx){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=s,this.scaleNode=i,this.positionNode=r,this.normalNode=n}setup(){const{textureXNode:e,textureYNode:t,textureZNode:s,scaleNode:i,positionNode:r,normalNode:n}=this;let o=n.abs().normalize();o=o.div(o.dot(Wp(1)));const a=r.yz.mul(i),h=r.zx.mul(i),u=r.xy.mul(i),l=e.value,c=null!==t?t.value:l,d=null!==s?s.value:l,p=By(l,a).mul(o.x),m=By(c,h).mul(o.y),g=By(d,u).mul(o.z);return Ym(p,m,g)}}const OM=Ap(UM),zM=(...e)=>OM(...e),LM=new Yo,VM=new Ai,DM=new Ai,kM=new Ai,GM=new sr,WM=new Ai(0,0,-1),jM=new xi,HM=new Ai,qM=new Ai,$M=new xi,XM=new Ys,YM=new bi,ZM=Vv.flipX();YM.depthTexture=new Xa(1,1);let JM=!1;class KM extends Ey{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||YM.texture,ZM),this._reflectorBaseNode=e.reflector||new QM(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=wp(new KM({defaultTexture:YM.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._reflectorBaseNode=this._reflectorBaseNode,e}}class QM extends zd{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:s=new Rr,resolution:i=1,generateMipmaps:r=!1,bounces:n=!0,depth:o=!1}=t;this.textureNode=e,this.target=s,this.resolution=i,this.generateMipmaps=r,this.bounces=n,this.depth=o,this.updateBeforeType=n?Ed.RENDER:Ed.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new WeakMap}_updateResolution(e,t){const s=this.resolution;t.getDrawingBufferSize(XM),e.setSize(Math.round(XM.width*s),Math.round(XM.height*s))}setup(e){return this._updateResolution(YM,e.renderer),super.setup(e)}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 bi(0,0,{type:Pe}),!0===this.generateMipmaps&&(t.texture.minFilter=1008,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new Xa),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&JM)return;JM=!0;const{scene:t,camera:s,renderer:i,material:r}=e,{target:n}=this,o=this.getVirtualCamera(s),a=this.getRenderTarget(o);if(i.getDrawingBufferSize(XM),this._updateResolution(a,i),DM.setFromMatrixPosition(n.matrixWorld),kM.setFromMatrixPosition(s.matrixWorld),GM.extractRotation(n.matrixWorld),VM.set(0,0,1),VM.applyMatrix4(GM),HM.subVectors(DM,kM),HM.dot(VM)>0)return;HM.reflect(VM).negate(),HM.add(DM),GM.extractRotation(s.matrixWorld),WM.set(0,0,-1),WM.applyMatrix4(GM),WM.add(kM),qM.subVectors(DM,WM),qM.reflect(VM).negate(),qM.add(DM),o.coordinateSystem=s.coordinateSystem,o.position.copy(HM),o.up.set(0,1,0),o.up.applyMatrix4(GM),o.up.reflect(VM),o.lookAt(qM),o.near=s.near,o.far=s.far,o.updateMatrixWorld(),o.projectionMatrix.copy(s.projectionMatrix),LM.setFromNormalAndCoplanarPoint(VM,DM),LM.applyMatrix4(o.matrixWorldInverse),jM.set(LM.normal.x,LM.normal.y,LM.normal.z,LM.constant);const h=o.projectionMatrix;$M.x=(Math.sign(jM.x)+h.elements[8])/h.elements[0],$M.y=(Math.sign(jM.y)+h.elements[9])/h.elements[5],$M.z=-1,$M.w=(1+h.elements[10])/h.elements[14],jM.multiplyScalar(1/jM.dot($M));h.elements[2]=jM.x,h.elements[6]=jM.y,h.elements[10]=i.coordinateSystem===Os?jM.z-0:jM.z+1-0,h.elements[14]=jM.w,this.textureNode.value=a.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=a.depthTexture),r.visible=!1;const u=i.getRenderTarget(),l=i.getMRT();i.setMRT(null),i.setRenderTarget(a),i.render(t,o),i.setMRT(l),i.setRenderTarget(u),r.visible=!0,JM=!1}}const eA=e=>wp(new KM(e)),tA=new wl(-1,1,1,-1,0,1);class sA extends Sn{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new fn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new fn(t,2))}}const iA=new sA;class rA extends On{constructor(e=null){super(iA,e),this.camera=tA,this.isQuadMesh=!0}renderAsync(e){return e.renderAsync(this,tA)}render(e){e.render(this,tA)}}const nA=new Ys;class oA extends Ey{static get type(){return"RTTNode"}constructor(e,t=null,s=null,i={type:Pe}){const r=new bi(t,s,i);super(r.texture,My()),this.node=e,this.width=t,this.height=s,this.renderTarget=r,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this.updateMap=new WeakMap,this._rttNode=null,this._quadMesh=new rA(new pT),this.updateBeforeType=Ed.RENDER}get autoSize(){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 s=e*this.pixelRatio,i=t*this.pixelRatio;this.renderTarget.setSize(s,i),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.autoSize){this.pixelRatio=e.getPixelRatio();const t=e.getSize(nA);this.setSize(t.width,t.height)}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 Ey(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const aA=(e,...t)=>wp(new oA(wp(e),...t)),hA=(e,...t)=>e.isTextureNode?e:aA(e,...t);class uA extends wy{static get type(){return"VertexColorNode"}constructor(e=0){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 s;return s=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new xi(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const lA=(...e)=>wp(new uA(...e));class cA extends zd{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const dA=Np(cA);class pA extends zd{static get type(){return"SceneNode"}constructor(e=pA.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let i;return t===pA.BACKGROUND_BLURRINESS?i=Dx("backgroundBlurriness","float",s):t===pA.BACKGROUND_INTENSITY?i=Dx("backgroundIntensity","float",s):console.error("THREE.SceneNode: Unknown scope:",t),i}}pA.BACKGROUND_BLURRINESS="backgroundBlurriness",pA.BACKGROUND_INTENSITY="backgroundIntensity";const mA=Np(pA,pA.BACKGROUND_BLURRINESS),gA=Np(pA,pA.BACKGROUND_INTENSITY),fA="point-list",yA="line-list",xA="line-strip",bA="triangle-list",vA="triangle-strip",TA="never",_A="less",wA="equal",SA="less-equal",MA="greater",AA="not-equal",NA="greater-equal",CA="always",RA="store",EA="load",BA="clear",IA="ccw",PA="none",FA="front",UA="back",OA="uint16",zA="uint32",LA={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10uFloat:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Stencil8:"stencil8",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},VA="clamp-to-edge",DA="repeat",kA="mirror-repeat",GA="linear",WA="nearest",jA="zero",HA="one",qA="src",$A="one-minus-src",XA="src-alpha",YA="one-minus-src-alpha",ZA="dst",JA="one-minus-dst",KA="dst-alpha",QA="one-minus-dst-alpha",eN="src-alpha-saturated",tN="constant",sN="one-minus-constant",iN="add",rN="subtract",nN="reverse-subtract",oN="min",aN="max",hN=0,uN=15,lN="keep",cN="zero",dN="replace",pN="invert",mN="increment-clamp",gN="decrement-clamp",fN="increment-wrap",yN="decrement-wrap",xN="storage",bN="read-only-storage",vN="write-only",TN="read-only",_N="float",wN="unfilterable-float",SN="depth",MN="sint",AN="uint",NN="2d",CN="3d",RN="2d",EN="2d-array",BN="cube",IN="3d",PN="all",FN="vertex",UN="instance",ON={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class zN extends Ix{static get type(){return"StorageBufferNode"}constructor(e,t,s=0){super(e,t,s),this.isStorageBufferNode=!0,this.access=xN,this.isAtomic=!1,this.bufferObject=!1,this.bufferCount=s,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 FM(this,e)}setBufferObject(e){return this.bufferObject=e,this}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(bN)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=iy(this.value),this._varying=Vf(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}generate(e){if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:s}=this.getAttributeData(),i=s.build(e);return e.registerTransform(i,t),i}}const LN=(e,t,s)=>wp(new zN(e,t,s)),VN=(e,t,s)=>wp(new zN(e,t,s).setBufferObject(!0));class DN extends Ey{static get type(){return"StorageTextureNode"}constructor(e,t,s=null){super(e,t),this.storeNode=s,this.isStorageTextureNode=!0,this.access=vN}getInputType(){return"storageTexture"}setup(e){super.setup(e);e.getNodeProperties(this).storeNode=this.storeNode}setAccess(e){return this.access=e,this}generate(e,t){let s;return s=null!==this.storeNode?this.generateStore(e):super.generate(e,t),s}toReadOnly(){return this.setAccess(TN)}toWriteOnly(){return this.setAccess(vN)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:s,storeNode:i}=t,r=super.generate(e,"property"),n=s.build(e,"uvec2"),o=i.build(e,"vec4"),a=e.generateTextureStore(e,r,n,o);e.addLineFlowCode(a,this)}}const kN=Ap(DN),GN=(e,t,s)=>{const i=kN(e,t,s);return null!==s&&i.append(),i};class WN extends Vx{static get type(){return"UserDataNode"}constructor(e,t,s=null){super(e,t,s),this.userData=s}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const jN=(e,t,s)=>wp(new WN(e,t,s));class HN extends Dd{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 qN=Ap(HN);let $N=null;class XN extends Zv{static get type(){return"ViewportSharedTextureNode"}constructor(e=Vv,t=null){null===$N&&($N=new Wa),super(e,t,$N)}updateReference(){return this}}const YN=Ap(XN),ZN=new Ys;class JN extends Ey{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class KN extends JN{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class QN extends Dd{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new Xa;r.isRenderTargetTexture=!0,r.name="depth";const n=new bi(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Pe,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this.updateBeforeType=Ed.FRAME,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=dm(0),this._cameraFar=dm(0),this._mrt=null,this.isPassNode=!0}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}isGlobal(){return!0}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.isRenderTargetTexture=!0,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(),t.isRenderTargetTexture=!0,this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(this._textureNodes[e]=t=wp(new KN(this,e)),this._textureNodes[e].updateTexture()),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),this._previousTextureNodes[e]=t=wp(new KN(this,e,!0)),this._previousTextureNodes[e].updateTexture()),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=oT(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=iT(r,s,i)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,!0===e.backend.isWebGLBackend&&(this.renderTarget.samples=0),this.renderTarget.depthTexture.isMultisampleRenderTargetTexture=this.renderTarget.samples>1,this.scope===QN.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s,camera:i}=this;this._pixelRatio=t.getPixelRatio();const r=t.getSize(ZN);this.setSize(r.width,r.height);const n=t.getRenderTarget(),o=t.getMRT();this._cameraNear.value=i.near,this._cameraFar.value=i.far;for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(n),t.setMRT(o)}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}QN.COLOR="color",QN.DEPTH="depth";const eC=(e,t,s)=>wp(new QN(QN.COLOR,e,t,s)),tC=(e,t)=>wp(new JN(e,t)),sC=(e,t)=>wp(new QN(QN.DEPTH,e,t));class iC extends QN{static get type(){return"ToonOutlinePassNode"}constructor(e,t,s,i,r){super(QN.COLOR,e,t),this.colorNode=s,this.thicknessNode=i,this.alphaNode=r,this._materialCache=new WeakMap}updateBefore(e){const{renderer:t}=e,s=t.getRenderObjectFunction();t.setRenderObjectFunction(((e,s,i,r,n,o,a)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const h=this._getOutlineMaterial(n);t.renderObject(e,s,i,r,h,o,a)}t.renderObject(e,s,i,r,n,o,a)})),super.updateBefore(e),t.setRenderObjectFunction(s)}_createMaterial(){const e=new pT;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=d;const t=fx.negate(),s=Oy.mul(sx),i=Up(1),r=s.mul($p(ox,1)),n=s.mul($p(ox.add(t),1)),o=Ug(r.sub(n));return e.vertexNode=r.add(o.mul(this.thicknessNode).mul(r.w).mul(i)),e.colorNode=$p(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 rC=(e,t,s=new Xr(0,0,0),i=.003,r=1)=>wp(new iC(e,t,wp(s),wp(i),wp(r)));class nC extends zd{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outpuType=null,this.events=new zs,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:Up()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Ad(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?Nd(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 oC=Ap(nC);class aC extends Map{get(e,t=null,...s){if(this.has(e))return super.get(e);if(null!==t){const i=t(...s);return this.set(e,i),i}}}class hC{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 uC=new aC;class lC extends zd{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new aC,this._output=oC(),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 s=this._outputs;return void 0===s[e]?s[e]=oC(t):s[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const s=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),s[e]=t,s[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),s[e]=t,s[e].events.addEventListener("refresh",this.onRefresh)):void 0===s[e]?(s[e]=oC(t),s[e].events.addEventListener("refresh",this.onRefresh)):s[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 s=this.getObject()[e];if("function"==typeof s)return s(...t)}async callAsync(e,...t){const s=this.getObject()[e];if("function"==typeof s)return"AsyncFunction"===s.constructor.name?await s(...t):s(...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 hC(this),t=uC.get("THREE"),s=uC.get("TSL"),i=this.getMethod(this.codeNode),r=[e,this._local,uC,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,s];this._object=i(...r);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:Up()}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+" };",s="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],s),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=[bd(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const s in this.parameters)t.push(this.parameters[s].getCacheKey(e));return vd(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 cC=Ap(lC);class dC extends zd{static get type(){return"FogNode"}constructor(e,t){super("float"),this.isFogNode=!0,this.colorNode=e,this.factorNode=t}getViewZNode(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||lx.z).negate()}setup(){return this.factorNode}}const pC=Ap(dC);class mC extends dC{static get type(){return"FogRangeNode"}constructor(e,t,s){super(e),this.isFogRangeNode=!0,this.nearNode=t,this.farNode=s}setup(e){const t=this.getViewZNode(e);return Sf(this.nearNode,this.farNode,t)}}const gC=Ap(mC);class fC extends dC{static get type(){return"FogExp2Node"}constructor(e,t){super(e),this.isFogExp2Node=!0,this.densityNode=t}setup(e){const t=this.getViewZNode(e),s=this.densityNode;return s.mul(s,t,t).negate().exp().oneMinus()}}const yC=Ap(fC);let xC=null,bC=null;class vC extends zd{static get type(){return"RangeNode"}constructor(e=Up(),t=Up()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Sd(this.minNode.value)),s=e.getTypeLength(Sd(this.maxNode.value));return t>s?t:s}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let s=null;if(t.count>1){const i=this.minNode.value,r=this.maxNode.value,n=e.getTypeLength(Sd(i)),o=e.getTypeLength(Sd(r));xC=xC||new xi,bC=bC||new xi,xC.setScalar(0),bC.setScalar(0),1===n?xC.setScalar(i):i.isColor?xC.set(i.r,i.g,i.b):xC.set(i.x,i.y,i.z||0,i.w||0),1===o?bC.setScalar(r):r.isColor?bC.set(r.r,r.g,r.b):bC.set(r.x,r.y,r.z||0,r.w||0);const a=4,h=a*t.count,u=new Float32Array(h);for(let e=0;eBy(e,t.xy).compare(t.z))),wC=Cp((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>By(e,t).compare(s),r=Dx("mapSize","vec2",s).setGroup(um),n=Dx("radius","float",s).setGroup(um),o=Vp(1).div(r),a=o.x.negate().mul(n),h=o.y.negate().mul(n),u=o.x.mul(n),l=o.y.mul(n),c=a.div(2),d=h.div(2),p=u.div(2),m=l.div(2);return Ym(i(t.xy.add(Vp(a,h)),t.z),i(t.xy.add(Vp(0,h)),t.z),i(t.xy.add(Vp(u,h)),t.z),i(t.xy.add(Vp(c,d)),t.z),i(t.xy.add(Vp(0,d)),t.z),i(t.xy.add(Vp(p,d)),t.z),i(t.xy.add(Vp(a,0)),t.z),i(t.xy.add(Vp(c,0)),t.z),i(t.xy,t.z),i(t.xy.add(Vp(p,0)),t.z),i(t.xy.add(Vp(u,0)),t.z),i(t.xy.add(Vp(c,m)),t.z),i(t.xy.add(Vp(0,m)),t.z),i(t.xy.add(Vp(p,m)),t.z),i(t.xy.add(Vp(a,l)),t.z),i(t.xy.add(Vp(0,l)),t.z),i(t.xy.add(Vp(u,l)),t.z)).mul(1/17)})),SC=Cp((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>By(e,t).compare(s),r=Dx("mapSize","vec2",s).setGroup(um),n=Vp(1).div(r),o=n.x,a=n.y,h=t.xy,u=Og(h.mul(r).add(.5));return h.subAssign(u.mul(n)),Ym(i(h,t.z),i(h.add(Vp(o,0)),t.z),i(h.add(Vp(0,a)),t.z),i(h.add(n),t.z),vf(i(h.add(Vp(o.negate(),0)),t.z),i(h.add(Vp(o.mul(2),0)),t.z),u.x),vf(i(h.add(Vp(o.negate(),a)),t.z),i(h.add(Vp(o.mul(2),a)),t.z),u.x),vf(i(h.add(Vp(0,a.negate())),t.z),i(h.add(Vp(0,a.mul(2))),t.z),u.y),vf(i(h.add(Vp(o,a.negate())),t.z),i(h.add(Vp(o,a.mul(2))),t.z),u.y),vf(vf(i(h.add(Vp(o.negate(),a.negate())),t.z),i(h.add(Vp(o.mul(2),a.negate())),t.z),u.x),vf(i(h.add(Vp(o.negate(),a.mul(2))),t.z),i(h.add(Vp(o.mul(2),a.mul(2))),t.z),u.x),u.y)).mul(1/9)})),MC=Cp((({depthTexture:e,shadowCoord:t})=>{const s=Up(1).toVar(),i=By(e).uv(t.xy).rg,r=af(t.z,i.x);return Ip(r.notEqual(Up(1)),(()=>{const e=t.z.sub(i.x),n=nf(0,i.y.mul(i.y));let o=n.div(n.add(e.mul(e)));o=Tf(Zm(o,.3).div(.95-.3)),s.assign(Tf(nf(r,o)))})),s})),AC=Cp((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Up(0).toVar(),n=Up(0).toVar(),o=e.lessThanEqual(Up(1)).select(Up(0),Up(2).div(e.sub(1))),a=e.lessThanEqual(Up(1)).select(Up(0),Up(-1));xv({start:Op(0),end:Op(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Up(e).mul(o)),u=i.uv(Ym(kv.xy,Vp(0,h).mul(t)).div(s)).x;r.addAssign(u),n.addAssign(u.mul(u))})),r.divAssign(e),n.divAssign(e);const h=Bg(n.sub(r.mul(r)));return Vp(r,h)})),NC=Cp((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Up(0).toVar(),n=Up(0).toVar(),o=e.lessThanEqual(Up(1)).select(Up(0),Up(2).div(e.sub(1))),a=e.lessThanEqual(Up(1)).select(Up(0),Up(-1));xv({start:Op(0),end:Op(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Up(e).mul(o)),u=i.uv(Ym(kv.xy,Vp(h,0).mul(t)).div(s));r.addAssign(u.x),n.addAssign(Ym(u.y.mul(u.y),u.x.mul(u.x)))})),r.divAssign(e),n.divAssign(e);const h=Bg(n.sub(r.mul(r)));return Vp(r,h)})),CC=[_C,wC,SC,MC];let RC=null;const EC=new rA;class BC extends zd{static get type(){return"ShadowNode"}constructor(e,t=null){super(),this.light=e,this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this.updateBeforeType=Ed.RENDER,this._node=null,this.isShadowNode=!0}setupShadow(e){const{object:t,renderer:s}=e;null===RC&&(RC=new pT,RC.fragmentNode=$p(0,0,0,1),RC.isShadowNodeMaterial=!0,RC.name="ShadowMaterial");const i=this.shadow,r=s.shadowMap.type,n=new Xa(i.mapSize.width,i.mapSize.height);n.compareFunction=ys;const o=e.createRenderTarget(i.mapSize.width,i.mapSize.height);if(o.depthTexture=n,i.camera.updateProjectionMatrix(),3===r){n.compareFunction=null,this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$e,type:Pe}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$e,type:Pe});const t=By(n),s=By(this.vsmShadowMapVertical.texture),r=Dx("blurSamples","float",i).setGroup(um),o=Dx("radius","float",i).setGroup(um),a=Dx("mapSize","vec2",i).setGroup(um);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new pT);h.fragmentNode=AC({samples:r,radius:o,size:a,shadowPass:t}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new pT),h.fragmentNode=NC({samples:r,radius:o,size:a,shadowPass:s}).context(e.getSharedContext()),h.name="VSMHorizontal"}const a=Dx("intensity","float",i).setGroup(um),h=Dx("bias","float",i).setGroup(um),u=Dx("normalBias","float",i).setGroup(um),l=t.material.shadowPositionNode||hx;let c,d=dm(i.matrix).setGroup(um).mul(l.add(Tx.mul(u)));if(i.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)d=d.xyz.div(d.w),c=d.z,s.coordinateSystem===Os&&(c=c.mul(2).sub(1));else{const e=d.w;d=d.xy.div(e);const t=dm("float").onRenderUpdate((()=>i.camera.near)),s=dm("float").onRenderUpdate((()=>i.camera.far));c=aT(e,t,s)}d=Wp(d.x,d.y.oneMinus(),c.add(h));const p=d.x.greaterThanEqual(0).and(d.x.lessThanEqual(1)).and(d.y.greaterThanEqual(0)).and(d.y.lessThanEqual(1)).and(d.z.lessThanEqual(1)),m=i.filterNode||CC[s.shadowMap.type]||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const g=By(o.texture,d),f=p.select(m({depthTexture:3===r?this.vsmShadowMapHorizontal.texture:n,shadowCoord:d,shadow:i}),Up(1));return this.shadowMap=o,this.shadow.map=o,vf(1,f.rgb.mix(g,1),a.mul(g.a))}setup(e){if(!1!==e.renderer.shadowMap.enabled)return null!==this._node?this._node:this._node=this.setupShadow(e)}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:o}=e,a=r.shadowMap.type,h=t.depthTexture.version;this._depthVersionCached=h;const u=n.overrideMaterial;n.overrideMaterial=RC,t.setSize(i.mapSize.width,i.mapSize.height),i.updateMatrices(s),i.camera.layers.mask=o.layers.mask;const l=r.getRenderTarget(),c=r.getRenderObjectFunction();r.setRenderObjectFunction(((e,...t)=>{(!0===e.castShadow||e.receiveShadow&&3===a)&&r.renderObject(e,...t)})),r.setRenderTarget(t),r.render(n,i.camera),r.setRenderObjectFunction(c),!0!==s.isPointLight&&3===a&&this.vsmPass(r),r.setRenderTarget(l),n.overrideMaterial=u}vsmPass(e){const{shadow:t}=this;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height),e.setRenderTarget(this.vsmShadowMapVertical),EC.material=this.vsmMaterialVertical,EC.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),EC.material=this.vsmMaterialHorizontal,EC.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),this.updateBeforeType=Ed.NONE}updateBefore(e){const{shadow:t}=this;(t.needsUpdate||t.autoUpdate)&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const IC=(e,t)=>wp(new BC(e,t));class PC extends Bv{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.updateType=Ed.FRAME,this.light=e,this.color=new Xr,this.colorNode=dm(this.color).setGroup(um),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0}getCacheKey(){return Td(super.getCacheKey(),this.light.id,this.light.castShadow?1:0)}getHash(){return this.light.uuid}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const e=IC(this.light);this.shadowNode=e,this.shadowColorNode=s=this.colorNode.mul(e),this.baseColorNode=this.colorNode}this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&this.shadowNode.dispose()}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const FC=Cp((e=>{const{lightDistance:t,cutoffDistance:s,decayExponent:i}=e,r=t.pow(i).max(.01).reciprocal();return s.greaterThan(0).select(r.mul(t.div(s).pow4().oneMinus().clamp().pow2()),r)}));let UC;function OC(e){UC=UC||new WeakMap;let t=UC.get(e);return void 0===t&&UC.set(e,t={}),t}function zC(e){const t=OC(e);return t.position||(t.position=dm(new Ai).setGroup(um).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld))))}function LC(e){const t=OC(e);return t.targetPosition||(t.targetPosition=dm(new Ai).setGroup(um).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld))))}function VC(e){const t=OC(e);return t.viewPosition||(t.viewPosition=dm(new Ai).setGroup(um).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new Ai,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}const DC=e=>Ly.transformDirection(zC(e).sub(LC(e))),kC=Cp((([e])=>{const t=e.toUint().mul(747796405).add(2891336453),s=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return s.shiftRight(22).bitXor(s).toFloat().mul(1/2**32)})),GC=(e,t)=>pf(Jm(4,e.mul(Zm(1,e))),t),WC=(e,t)=>e.lessThan(.5)?GC(e.mul(2),t).div(2):Zm(1,GC(Jm(Zm(1,e),2),t).div(2)),jC=(e,t,s)=>pf(Km(pf(e,t),Ym(pf(e,t),pf(Zm(1,e),s))),1/t),HC=(e,t)=>zg(vg.mul(t.mul(e).sub(1))).div(vg.mul(t.mul(e).sub(1))),qC=Cp((([e])=>e.fract().sub(.5).abs())).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),$C=Cp((([e])=>Wp(qC(e.z.add(qC(e.y.mul(1)))),qC(e.z.add(qC(e.x.mul(1)))),qC(e.y.add(qC(e.x.mul(1))))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),XC=Cp((([e,t,s])=>{const i=Wp(e).toVar(),r=Up(1.4).toVar(),n=Up(0).toVar(),o=Wp(i).toVar();return xv({start:Up(0),end:Up(3),type:"float",condition:"<="},(()=>{const e=Wp($C(o.mul(2))).toVar();i.addAssign(e.add(s.mul(Up(.1).mul(t)))),o.mulAssign(1.8),r.mulAssign(1.5),i.mulAssign(1.2);const a=Up(qC(i.z.add(qC(i.x.add(qC(i.y)))))).toVar();n.addAssign(a.div(r)),o.addAssign(.14)})),n})).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"p",type:"vec3"},{name:"spd",type:"float"},{name:"time",type:"float"}]}),YC=dm(0).setGroup(um).onRenderUpdate((e=>e.time)),ZC=dm(0).setGroup(um).onRenderUpdate((e=>e.deltaTime)),JC=dm(0,"uint").setGroup(um).onRenderUpdate((e=>e.frameId)),KC=(e=1)=>(console.warn('TSL: timerLocal() is deprecated. Use "time" instead.'),YC.mul(e)),QC=(e=1)=>(console.warn('TSL: timerGlobal() is deprecated. Use "time" instead.'),YC.mul(e)),eR=(e=1)=>(console.warn('TSL: timerDelta() is deprecated. Use "deltaTime" instead.'),ZC.mul(e)),tR=(e=YC)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),sR=(e=YC)=>e.fract().round(),iR=(e=YC)=>e.add(.5).fract().mul(2).sub(1).abs(),rR=(e=YC)=>e.fract(),nR=Cp((([e,t,s=Vp(.5)])=>Ew(e.sub(s),t).add(s))),oR=Cp((([e,t,s=Vp(.5)])=>{const i=e.sub(s),r=i.dot(i),n=r.mul(r).mul(t);return e.add(i.mul(n))})),aR=Cp((({position:e=null,horizontal:t=!0,vertical:s=!1})=>{let i;null!==e?(i=Zy.toVar(),i[3][0]=e.x,i[3][1]=e.y,i[3][2]=e.z):i=Zy;const r=Ly.mul(i);return vp(t)&&(r[0][0]=Zy[0].length(),r[0][1]=0,r[0][2]=0),vp(s)&&(r[1][0]=0,r[1][1]=Zy[1].length(),r[1][2]=0),r[2][0]=0,r[2][1]=0,r[2][2]=1,Oy.mul(r).mul(ox)})),hR=Cp((([e=null])=>{const t=lT();return lT(tT(e)).sub(t).lessThan(0).select(Vv,e)})),uR=Cp((([e,t,s],i)=>{let r;i.renderer.coordinateSystem===Os?(e=Vp(e.x,e.y.oneMinus()).mul(2).sub(1),r=$p(Wp(e,t),1)):r=$p(Wp(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=$p(s.mul(r));return n.xyz.div(n.w)})),lR=Cp((([e,t])=>{const s=t.mul($p(e,1)),i=s.xy.div(s.w).mul(.5).add(.5).toVar();return Vp(i.x,i.y.oneMinus())})),cR=new WeakMap;class dR extends Dd{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.updateType=Ed.OBJECT,this.updateAfterType=Ed.OBJECT,this.previousModelWorldMatrix=dm(new sr),this.previousProjectionMatrix=dm(new sr).setGroup(um),this.previousCameraViewMatrix=dm(new sr)}update({frameId:e,camera:t,object:s}){const i=mR(s);this.previousModelWorldMatrix.value.copy(i);const r=pR(t);r.frameId!==e&&(r.frameId=e,void 0===r.previousProjectionMatrix?(r.previousProjectionMatrix=new sr,r.previousCameraViewMatrix=new sr,r.currentProjectionMatrix=new sr,r.currentCameraViewMatrix=new sr,r.previousProjectionMatrix.copy(t.projectionMatrix),r.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(r.previousProjectionMatrix.copy(r.currentProjectionMatrix),r.previousCameraViewMatrix.copy(r.currentCameraViewMatrix)),r.currentProjectionMatrix.copy(t.projectionMatrix),r.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(r.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(r.previousCameraViewMatrix))}updateAfter({object:e}){mR(e).copy(e.matrixWorld)}setup(){const e=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),t=Oy.mul(sx).mul(ox),s=this.previousProjectionMatrix.mul(e).mul(ax),i=t.xy.div(t.w),r=s.xy.div(s.w);return Zm(i,r)}}function pR(e){let t=cR.get(e);return void 0===t&&(t={},cR.set(e,t)),t}function mR(e,t=0){const s=pR(e);let i=s[t];return void 0===i&&(s[t]=i=new sr),i}const gR=Np(dR),fR=Cp((([e,t])=>rf(1,e.oneMinus().div(t)).oneMinus())).setLayout({name:"burnBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),yR=Cp((([e,t])=>rf(e.div(t.oneMinus()),1))).setLayout({name:"dodgeBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),xR=Cp((([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus())).setLayout({name:"screenBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),bR=Cp((([e,t])=>vf(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),af(.5,e)))).setLayout({name:"overlayBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),vR=Cp((([e])=>SR(e.rgb))),TR=Cp((([e,t=Up(1)])=>t.mix(SR(e.rgb),e.rgb))),_R=Cp((([e,t=Up(1)])=>{const s=Ym(e.r,e.g,e.b).div(3),i=e.r.max(e.g.max(e.b)),r=i.sub(s).mul(t).mul(-3);return vf(e.rgb,i,r)})),wR=Cp((([e,t=Up(1)])=>{const s=Wp(.57735,.57735,.57735),i=t.cos();return Wp(e.rgb.mul(i).add(s.cross(e.rgb).mul(t.sin()).add(s.mul(cf(s,e.rgb).mul(i.oneMinus())))))})),SR=(e,t=Wp(ii.getLuminanceCoefficients(new Ai)))=>cf(e,t),MR=(e,t)=>vf(Wp(0),e,SR(e).sub(t).max(0)),AR=Cp((([e,t=Wp(1),s=Wp(0),i=Wp(1),r=Up(1),n=Wp(ii.getLuminanceCoefficients(new Ai,Jt))])=>{const o=e.rgb.dot(Wp(n)),a=nf(e.rgb.mul(t).add(s),0).toVar(),h=a.pow(i).toVar();return Ip(a.r.greaterThan(0),(()=>{a.r.assign(h.r)})),Ip(a.g.greaterThan(0),(()=>{a.g.assign(h.g)})),Ip(a.b.greaterThan(0),(()=>{a.b.assign(h.b)})),a.assign(o.add(a.sub(o).mul(r))),$p(a.rgb,e.a)})),NR=Cp((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return vf(t,s,i)})).setLayout({name:"sRGBToLinearSRGB",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),CR=Cp((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return vf(t,s,i)})).setLayout({name:"linearSRGBTosRGB",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),RR=Cp((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),ER=Cp((([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"}]}),BR=Cp((([e,t])=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(i).pow(2.2)})).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),IR=Cp((([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)})),PR=Cp((([e,t])=>{const s=Kp(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Kp(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=IR(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),FR=Kp(Wp(1.6605,-.1246,-.0182),Wp(-.5876,1.1329,-.1006),Wp(-.0728,-.0083,1.1187)),UR=Kp(Wp(.6274,.0691,.0164),Wp(.3293,.9195,.088),Wp(.0433,.0113,.8956)),OR=Cp((([e])=>{const t=Wp(e).toVar(),s=Wp(t.mul(t)).toVar(),i=Wp(s.mul(s)).toVar();return Up(15.5).mul(i.mul(s)).sub(Jm(40.14,i.mul(t))).add(Jm(31.96,i).sub(Jm(6.868,s.mul(t))).add(Jm(.4298,s).add(Jm(.1191,t).sub(.00232))))})),zR=Cp((([e,t])=>{const s=Wp(e).toVar(),i=Kp(Wp(.856627153315983,.137318972929847,.11189821299995),Wp(.0951212405381588,.761241990602591,.0767994186031903),Wp(.0482516061458583,.101439036467562,.811302368396859)),r=Kp(Wp(1.1271005818144368,-.1413297634984383,-.14132976349843826),Wp(-.11060664309660323,1.157823702216272,-.11060664309660294),Wp(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Up(-12.47393),o=Up(4.026069);return s.mulAssign(t),s.assign(UR.mul(s)),s.assign(i.mul(s)),s.assign(nf(s,1e-10)),s.assign(Eg(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(Tf(s,0,1)),s.assign(OR(s)),s.assign(r.mul(s)),s.assign(pf(nf(Wp(0),s),Wp(2.2))),s.assign(FR.mul(s)),s.assign(Tf(s,0,1)),s})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),LR=Cp((([e,t])=>{const s=Up(.76),i=Up(.15);e=e.mul(t);const r=rf(e.r,rf(e.g,e.b)),n=Ef(r.lessThan(.08),r.sub(Jm(6.25,r.mul(r))),.04);e.subAssign(n);const o=nf(e.r,nf(e.g,e.b));Ip(o.lessThan(s),(()=>e));const a=Zm(1,s),h=Zm(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(h.div(o));const u=Zm(1,Km(1,i.mul(o.sub(h)).add(1)));return vf(e,Wp(h),u)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class VR extends zd{static get type(){return"ComputeBuiltinNode"}constructor(e,t){super(t),this._builtinName=e}getHash(e){return this.getBuiltinName(e)}getNodeType(){return this.nodeType}setBuiltinName(e){return this._builtinName=e,this}getBuiltinName(){return this._builtinName}hasBuiltin(e){e.hasBuiltin(this._builtinName)}generate(e,t){const s=this.getBuiltinName(e),i=this.getNodeType(e);return"compute"===e.shaderStage?e.format(s,i,t):(console.warn(`ComputeBuiltinNode: Compute built-in value ${s} can not be accessed in the ${e.shaderStage} stage`),e.generateConst(i))}serialize(e){super.serialize(e),e.global=this.global,e._builtinName=this._builtinName}deserialize(e){super.deserialize(e),this.global=e.global,this._builtinName=e._builtinName}}const DR=(e,t)=>wp(new VR(e,t)),kR=DR("numWorkgroups","uvec3"),GR=DR("workgroupId","uvec3"),WR=DR("localId","uvec3"),jR=DR("subgroupSize","uint");const HR=Ap(class extends zd{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;!0===s.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}}),qR=()=>HR("workgroup").append(),$R=()=>HR("storage").append(),XR=()=>HR("texture").append();class YR extends Ld{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let s;const i=e.context.assign;if(s=super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}class ZR extends zd{constructor(e,t,s=0){super(t),this.bufferType=t,this.bufferCount=s,this.isWorkgroupInfoNode=!0,this.scope=e}label(e){return this.name=e,this}getHash(){return this.uuid}setScope(e){return this.scope=e,this}getInputType(){return`${this.scope}Array`}element(e){return wp(new YR(this,e))}generate(e){return e.getScopedArray(this.name||`${this.scope}Array_${this.id}`,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}const JR=(e,t)=>wp(new ZR("Workgroup",e,t));class KR extends Dd{static get type(){return"AtomicFunctionNode"}constructor(e,t,s,i=null){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.storeNode=i}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=this.method,s=this.getNodeType(e),i=this.getInputType(e),r=this.pointerNode,n=this.valueNode,o=[];o.push(`&${r.build(e,i)}`),o.push(n.build(e,i));const a=`${e.getMethod(t,s)}( ${o.join(", ")} )`;if(null!==this.storeNode){const t=this.storeNode.build(e,i);e.addLineFlowCode(`${t} = ${a}`,this)}else e.addLineFlowCode(a,this)}}KR.ATOMIC_LOAD="atomicLoad",KR.ATOMIC_STORE="atomicStore",KR.ATOMIC_ADD="atomicAdd",KR.ATOMIC_SUB="atomicSub",KR.ATOMIC_MAX="atomicMax",KR.ATOMIC_MIN="atomicMin",KR.ATOMIC_AND="atomicAnd",KR.ATOMIC_OR="atomicOr",KR.ATOMIC_XOR="atomicXor";const QR=Ap(KR),eE=(e,t,s,i)=>{const r=QR(e,t,s,i);return r.append(),r},tE=(e,t,s=null)=>eE(KR.ATOMIC_STORE,e,t,s),sE=(e,t,s=null)=>eE(KR.ATOMIC_ADD,e,t,s),iE=(e,t,s=null)=>eE(KR.ATOMIC_SUB,e,t,s),rE=(e,t,s=null)=>eE(KR.ATOMIC_MAX,e,t,s),nE=(e,t,s=null)=>eE(KR.ATOMIC_MIN,e,t,s),oE=(e,t,s=null)=>eE(KR.ATOMIC_AND,e,t,s),aE=(e,t,s=null)=>eE(KR.ATOMIC_OR,e,t,s),hE=(e,t,s=null)=>eE(KR.ATOMIC_XOR,e,t,s),uE=Cp((([e=t()])=>{const t=e.mul(2),s=t.x.floor(),i=t.y.floor();return s.add(i).mod(2).sign()})),lE=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=Lp(e).toVar();return Ef(n,r,i)})).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),cE=Cp((([e,t])=>{const s=Lp(t).toVar(),i=Up(e).toVar();return Ef(s,i.negate(),i)})).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),dE=Cp((([e])=>{const t=Up(e).toVar();return Op(Pg(t))})).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),pE=Cp((([e,t])=>{const s=Up(e).toVar();return t.assign(dE(s)),s.sub(Up(t))})),mE=EM([Cp((([e,t,s,i,r,n])=>{const o=Up(n).toVar(),a=Up(r).toVar(),h=Up(i).toVar(),u=Up(s).toVar(),l=Up(t).toVar(),c=Up(e).toVar(),d=Up(Zm(1,a)).toVar();return Zm(1,o).mul(c.mul(d).add(l.mul(a))).add(o.mul(u.mul(d).add(h.mul(a))))})).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"}]}),Cp((([e,t,s,i,r,n])=>{const o=Up(n).toVar(),a=Up(r).toVar(),h=Wp(i).toVar(),u=Wp(s).toVar(),l=Wp(t).toVar(),c=Wp(e).toVar(),d=Up(Zm(1,a)).toVar();return Zm(1,o).mul(c.mul(d).add(l.mul(a))).add(o.mul(u.mul(d).add(h.mul(a))))})).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"}]})]),gE=EM([Cp((([e,t,s,i,r,n,o,a,h,u,l])=>{const c=Up(l).toVar(),d=Up(u).toVar(),p=Up(h).toVar(),m=Up(a).toVar(),g=Up(o).toVar(),f=Up(n).toVar(),y=Up(r).toVar(),x=Up(i).toVar(),b=Up(s).toVar(),v=Up(t).toVar(),T=Up(e).toVar(),_=Up(Zm(1,p)).toVar(),w=Up(Zm(1,d)).toVar();return Up(Zm(1,c)).toVar().mul(w.mul(T.mul(_).add(v.mul(p))).add(d.mul(b.mul(_).add(x.mul(p))))).add(c.mul(w.mul(y.mul(_).add(f.mul(p))).add(d.mul(g.mul(_).add(m.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"}]}),Cp((([e,t,s,i,r,n,o,a,h,u,l])=>{const c=Up(l).toVar(),d=Up(u).toVar(),p=Up(h).toVar(),m=Wp(a).toVar(),g=Wp(o).toVar(),f=Wp(n).toVar(),y=Wp(r).toVar(),x=Wp(i).toVar(),b=Wp(s).toVar(),v=Wp(t).toVar(),T=Wp(e).toVar(),_=Up(Zm(1,p)).toVar(),w=Up(Zm(1,d)).toVar();return Up(Zm(1,c)).toVar().mul(w.mul(T.mul(_).add(v.mul(p))).add(d.mul(b.mul(_).add(x.mul(p))))).add(c.mul(w.mul(y.mul(_).add(f.mul(p))).add(d.mul(g.mul(_).add(m.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"}]})]),fE=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=zp(e).toVar(),o=zp(n.bitAnd(zp(7))).toVar(),a=Up(lE(o.lessThan(zp(4)),r,i)).toVar(),h=Up(Jm(2,lE(o.lessThan(zp(4)),i,r))).toVar();return cE(a,Lp(o.bitAnd(zp(1)))).add(cE(h,Lp(o.bitAnd(zp(2)))))})).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),yE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Up(t).toVar(),a=zp(e).toVar(),h=zp(a.bitAnd(zp(15))).toVar(),u=Up(lE(h.lessThan(zp(8)),o,n)).toVar(),l=Up(lE(h.lessThan(zp(4)),n,lE(h.equal(zp(12)).or(h.equal(zp(14))),o,r))).toVar();return cE(u,Lp(h.bitAnd(zp(1)))).add(cE(l,Lp(h.bitAnd(zp(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"}]}),xE=EM([fE,yE]),bE=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=Hp(e).toVar();return Wp(xE(n.x,r,i),xE(n.y,r,i),xE(n.z,r,i))})).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),vE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Up(t).toVar(),a=Hp(e).toVar();return Wp(xE(a.x,o,n,r),xE(a.y,o,n,r),xE(a.z,o,n,r))})).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"}]}),TE=EM([bE,vE]),_E=Cp((([e])=>{const t=Up(e).toVar();return Jm(.6616,t)})).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),wE=Cp((([e])=>{const t=Up(e).toVar();return Jm(.982,t)})).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),SE=EM([_E,Cp((([e])=>{const t=Wp(e).toVar();return Jm(.6616,t)})).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),ME=EM([wE,Cp((([e])=>{const t=Wp(e).toVar();return Jm(.982,t)})).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),AE=Cp((([e,t])=>{const s=Op(t).toVar(),i=zp(e).toVar();return i.shiftLeft(s).bitOr(i.shiftRight(Op(32).sub(s)))})).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),NE=Cp((([e,t,s])=>{e.subAssign(s),e.bitXorAssign(AE(s,Op(4))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(AE(e,Op(6))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(AE(t,Op(8))),t.addAssign(e),e.subAssign(s),e.bitXorAssign(AE(s,Op(16))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(AE(e,Op(19))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(AE(t,Op(4))),t.addAssign(e)})),CE=Cp((([e,t,s])=>{const i=zp(s).toVar(),r=zp(t).toVar(),n=zp(e).toVar();return i.bitXorAssign(r),i.subAssign(AE(r,Op(14))),n.bitXorAssign(i),n.subAssign(AE(i,Op(11))),r.bitXorAssign(n),r.subAssign(AE(n,Op(25))),i.bitXorAssign(r),i.subAssign(AE(r,Op(16))),n.bitXorAssign(i),n.subAssign(AE(i,Op(4))),r.bitXorAssign(n),r.subAssign(AE(n,Op(14))),i.bitXorAssign(r),i.subAssign(AE(r,Op(24))),i})).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),RE=Cp((([e])=>{const t=zp(e).toVar();return Up(t).div(Up(zp(Op(4294967295))))})).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),EE=Cp((([e])=>{const t=Up(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"}]}),BE=EM([Cp((([e])=>{const t=Op(e).toVar(),s=zp(zp(1)).toVar(),i=zp(zp(Op(3735928559)).add(s.shiftLeft(zp(2))).add(zp(13))).toVar();return CE(i.add(zp(t)),i,i)})).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),Cp((([e,t])=>{const s=Op(t).toVar(),i=Op(e).toVar(),r=zp(zp(2)).toVar(),n=zp().toVar(),o=zp().toVar(),a=zp().toVar();return n.assign(o.assign(a.assign(zp(Op(3735928559)).add(r.shiftLeft(zp(2))).add(zp(13))))),n.addAssign(zp(i)),o.addAssign(zp(s)),CE(n,o,a)})).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Op(t).toVar(),n=Op(e).toVar(),o=zp(zp(3)).toVar(),a=zp().toVar(),h=zp().toVar(),u=zp().toVar();return a.assign(h.assign(u.assign(zp(Op(3735928559)).add(o.shiftLeft(zp(2))).add(zp(13))))),a.addAssign(zp(n)),h.addAssign(zp(r)),u.addAssign(zp(i)),CE(a,h,u)})).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Cp((([e,t,s,i])=>{const r=Op(i).toVar(),n=Op(s).toVar(),o=Op(t).toVar(),a=Op(e).toVar(),h=zp(zp(4)).toVar(),u=zp().toVar(),l=zp().toVar(),c=zp().toVar();return u.assign(l.assign(c.assign(zp(Op(3735928559)).add(h.shiftLeft(zp(2))).add(zp(13))))),u.addAssign(zp(a)),l.addAssign(zp(o)),c.addAssign(zp(n)),NE(u,l,c),u.addAssign(zp(r)),CE(u,l,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"}]}),Cp((([e,t,s,i,r])=>{const n=Op(r).toVar(),o=Op(i).toVar(),a=Op(s).toVar(),h=Op(t).toVar(),u=Op(e).toVar(),l=zp(zp(5)).toVar(),c=zp().toVar(),d=zp().toVar(),p=zp().toVar();return c.assign(d.assign(p.assign(zp(Op(3735928559)).add(l.shiftLeft(zp(2))).add(zp(13))))),c.addAssign(zp(u)),d.addAssign(zp(h)),p.addAssign(zp(a)),NE(c,d,p),c.addAssign(zp(o)),d.addAssign(zp(n)),CE(c,d,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"}]})]),IE=EM([Cp((([e,t])=>{const s=Op(t).toVar(),i=Op(e).toVar(),r=zp(BE(i,s)).toVar(),n=Hp().toVar();return n.x.assign(r.bitAnd(Op(255))),n.y.assign(r.shiftRight(Op(8)).bitAnd(Op(255))),n.z.assign(r.shiftRight(Op(16)).bitAnd(Op(255))),n})).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Op(t).toVar(),n=Op(e).toVar(),o=zp(BE(n,r,i)).toVar(),a=Hp().toVar();return a.x.assign(o.bitAnd(Op(255))),a.y.assign(o.shiftRight(Op(8)).bitAnd(Op(255))),a.z.assign(o.shiftRight(Op(16)).bitAnd(Op(255))),a})).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),PE=EM([Cp((([e])=>{const t=Vp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Up(pE(t.x,s)).toVar(),n=Up(pE(t.y,i)).toVar(),o=Up(EE(r)).toVar(),a=Up(EE(n)).toVar(),h=Up(mE(xE(BE(s,i),r,n),xE(BE(s.add(Op(1)),i),r.sub(1),n),xE(BE(s,i.add(Op(1))),r,n.sub(1)),xE(BE(s.add(Op(1)),i.add(Op(1))),r.sub(1),n.sub(1)),o,a)).toVar();return SE(h)})).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Op().toVar(),n=Up(pE(t.x,s)).toVar(),o=Up(pE(t.y,i)).toVar(),a=Up(pE(t.z,r)).toVar(),h=Up(EE(n)).toVar(),u=Up(EE(o)).toVar(),l=Up(EE(a)).toVar(),c=Up(gE(xE(BE(s,i,r),n,o,a),xE(BE(s.add(Op(1)),i,r),n.sub(1),o,a),xE(BE(s,i.add(Op(1)),r),n,o.sub(1),a),xE(BE(s.add(Op(1)),i.add(Op(1)),r),n.sub(1),o.sub(1),a),xE(BE(s,i,r.add(Op(1))),n,o,a.sub(1)),xE(BE(s.add(Op(1)),i,r.add(Op(1))),n.sub(1),o,a.sub(1)),xE(BE(s,i.add(Op(1)),r.add(Op(1))),n,o.sub(1),a.sub(1)),xE(BE(s.add(Op(1)),i.add(Op(1)),r.add(Op(1))),n.sub(1),o.sub(1),a.sub(1)),h,u,l)).toVar();return ME(c)})).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),FE=EM([Cp((([e])=>{const t=Vp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Up(pE(t.x,s)).toVar(),n=Up(pE(t.y,i)).toVar(),o=Up(EE(r)).toVar(),a=Up(EE(n)).toVar(),h=Wp(mE(TE(IE(s,i),r,n),TE(IE(s.add(Op(1)),i),r.sub(1),n),TE(IE(s,i.add(Op(1))),r,n.sub(1)),TE(IE(s.add(Op(1)),i.add(Op(1))),r.sub(1),n.sub(1)),o,a)).toVar();return SE(h)})).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Op().toVar(),n=Up(pE(t.x,s)).toVar(),o=Up(pE(t.y,i)).toVar(),a=Up(pE(t.z,r)).toVar(),h=Up(EE(n)).toVar(),u=Up(EE(o)).toVar(),l=Up(EE(a)).toVar(),c=Wp(gE(TE(IE(s,i,r),n,o,a),TE(IE(s.add(Op(1)),i,r),n.sub(1),o,a),TE(IE(s,i.add(Op(1)),r),n,o.sub(1),a),TE(IE(s.add(Op(1)),i.add(Op(1)),r),n.sub(1),o.sub(1),a),TE(IE(s,i,r.add(Op(1))),n,o,a.sub(1)),TE(IE(s.add(Op(1)),i,r.add(Op(1))),n.sub(1),o,a.sub(1)),TE(IE(s,i.add(Op(1)),r.add(Op(1))),n,o.sub(1),a.sub(1)),TE(IE(s.add(Op(1)),i.add(Op(1)),r.add(Op(1))),n.sub(1),o.sub(1),a.sub(1)),h,u,l)).toVar();return ME(c)})).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),UE=EM([Cp((([e])=>{const t=Up(e).toVar(),s=Op(dE(t)).toVar();return RE(BE(s))})).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),Cp((([e])=>{const t=Vp(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar();return RE(BE(s,i))})).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar(),r=Op(dE(t.z)).toVar();return RE(BE(s,i,r))})).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),Cp((([e])=>{const t=$p(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar(),r=Op(dE(t.z)).toVar(),n=Op(dE(t.w)).toVar();return RE(BE(s,i,r,n))})).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),OE=EM([Cp((([e])=>{const t=Up(e).toVar(),s=Op(dE(t)).toVar();return Wp(RE(BE(s,Op(0))),RE(BE(s,Op(1))),RE(BE(s,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),Cp((([e])=>{const t=Vp(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar();return Wp(RE(BE(s,i,Op(0))),RE(BE(s,i,Op(1))),RE(BE(s,i,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar(),r=Op(dE(t.z)).toVar();return Wp(RE(BE(s,i,r,Op(0))),RE(BE(s,i,r,Op(1))),RE(BE(s,i,r,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Cp((([e])=>{const t=$p(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar(),r=Op(dE(t.z)).toVar(),n=Op(dE(t.w)).toVar();return Wp(RE(BE(s,i,r,n,Op(0))),RE(BE(s,i,r,n,Op(1))),RE(BE(s,i,r,n,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),zE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Up(0).toVar(),u=Up(1).toVar();return xv(o,(()=>{h.addAssign(u.mul(PE(a))),u.mulAssign(r),a.mulAssign(n)})),h})).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"}]}),LE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Wp(0).toVar(),u=Up(1).toVar();return xv(o,(()=>{h.addAssign(u.mul(FE(a))),u.mulAssign(r),a.mulAssign(n)})),h})).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"}]}),VE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar();return Vp(zE(a,o,n,r),zE(a.add(Wp(Op(19),Op(193),Op(17))),o,n,r))})).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"}]}),DE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Wp(LE(a,o,n,r)).toVar(),u=Up(zE(a.add(Wp(Op(19),Op(193),Op(17))),o,n,r)).toVar();return $p(h,u)})).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"}]}),kE=Cp((([e,t,s,i,r,n,o])=>{const a=Op(o).toVar(),h=Up(n).toVar(),u=Op(r).toVar(),l=Op(i).toVar(),c=Op(s).toVar(),d=Op(t).toVar(),p=Vp(e).toVar(),m=Wp(OE(Vp(d.add(l),c.add(u)))).toVar(),g=Vp(m.x,m.y).toVar();g.subAssign(.5),g.mulAssign(h),g.addAssign(.5);const f=Vp(Vp(Up(d),Up(c)).add(g)).toVar(),y=Vp(f.sub(p)).toVar();return Ip(a.equal(Op(2)),(()=>Wg(y.x).add(Wg(y.y)))),Ip(a.equal(Op(3)),(()=>nf(Wg(y.x),Wg(y.y)))),cf(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"}]}),GE=EM([kE,Cp((([e,t,s,i,r,n,o,a,h])=>{const u=Op(h).toVar(),l=Up(a).toVar(),c=Op(o).toVar(),d=Op(n).toVar(),p=Op(r).toVar(),m=Op(i).toVar(),g=Op(s).toVar(),f=Op(t).toVar(),y=Wp(e).toVar(),x=Wp(OE(Wp(f.add(p),g.add(d),m.add(c)))).toVar();x.subAssign(.5),x.mulAssign(l),x.addAssign(.5);const b=Wp(Wp(Up(f),Up(g),Up(m)).add(x)).toVar(),v=Wp(b.sub(y)).toVar();return Ip(u.equal(Op(2)),(()=>Wg(v.x).add(Wg(v.y)).add(Wg(v.z)))),Ip(u.equal(Op(3)),(()=>nf(nf(Wg(v.x),Wg(v.y)),Wg(v.z)))),cf(v,v)})).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"}]})]),WE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(pE(n.x,o),pE(n.y,a)).toVar(),u=Up(1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(GE(h,e,t,o,a,r,i)).toVar();u.assign(rf(u,s))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),jE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(pE(n.x,o),pE(n.y,a)).toVar(),u=Vp(1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(GE(h,e,t,o,a,r,i)).toVar();Ip(s.lessThan(u.x),(()=>{u.y.assign(u.x),u.x.assign(s)})).ElseIf(s.lessThan(u.y),(()=>{u.y.assign(s)}))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),HE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(pE(n.x,o),pE(n.y,a)).toVar(),u=Wp(1e6,1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(GE(h,e,t,o,a,r,i)).toVar();Ip(s.lessThan(u.x),(()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(s)})).ElseIf(s.lessThan(u.y),(()=>{u.z.assign(u.y),u.y.assign(s)})).ElseIf(s.lessThan(u.z),(()=>{u.z.assign(s)}))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),qE=EM([WE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(pE(n.x,o),pE(n.y,a),pE(n.z,h)).toVar(),l=Up(1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(GE(u,e,t,s,o,a,h,r,i)).toVar();l.assign(rf(l,n))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),$E=EM([jE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(pE(n.x,o),pE(n.y,a),pE(n.z,h)).toVar(),l=Vp(1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(GE(u,e,t,s,o,a,h,r,i)).toVar();Ip(n.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(n)})).ElseIf(n.lessThan(l.y),(()=>{l.y.assign(n)}))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),XE=EM([HE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(pE(n.x,o),pE(n.y,a),pE(n.z,h)).toVar(),l=Wp(1e6,1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(GE(u,e,t,s,o,a,h,r,i)).toVar();Ip(n.lessThan(l.x),(()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(n)})).ElseIf(n.lessThan(l.y),(()=>{l.z.assign(l.y),l.y.assign(n)})).ElseIf(n.lessThan(l.z),(()=>{l.z.assign(n)}))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),YE=Cp((([e])=>{const t=e.y,s=e.z,i=Wp().toVar();return Ip(t.lessThan(1e-4),(()=>{i.assign(Wp(s,s,s))})).Else((()=>{let r=e.x;r=r.sub(Pg(r)).mul(6).toVar();const n=Op(Kg(r)),o=r.sub(Up(n)),a=s.mul(t.oneMinus()),h=s.mul(t.mul(o).oneMinus()),u=s.mul(t.mul(o.oneMinus()).oneMinus());Ip(n.equal(Op(0)),(()=>{i.assign(Wp(s,u,a))})).ElseIf(n.equal(Op(1)),(()=>{i.assign(Wp(h,s,a))})).ElseIf(n.equal(Op(2)),(()=>{i.assign(Wp(a,s,u))})).ElseIf(n.equal(Op(3)),(()=>{i.assign(Wp(a,h,s))})).ElseIf(n.equal(Op(4)),(()=>{i.assign(Wp(u,a,s))})).Else((()=>{i.assign(Wp(s,a,h))}))})),i})).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),ZE=Cp((([e])=>{const t=Wp(e).toVar(),s=Up(t.x).toVar(),i=Up(t.y).toVar(),r=Up(t.z).toVar(),n=Up(rf(s,rf(i,r))).toVar(),o=Up(nf(s,nf(i,r))).toVar(),a=Up(o.sub(n)).toVar(),h=Up().toVar(),u=Up().toVar(),l=Up().toVar();return l.assign(o),Ip(o.greaterThan(0),(()=>{u.assign(a.div(o))})).Else((()=>{u.assign(0)})),Ip(u.lessThanEqual(0),(()=>{h.assign(0)})).Else((()=>{Ip(s.greaterThanEqual(o),(()=>{h.assign(i.sub(r).div(a))})).ElseIf(i.greaterThanEqual(o),(()=>{h.assign(Ym(2,r.sub(s).div(a)))})).Else((()=>{h.assign(Ym(4,s.sub(i).div(a)))})),h.mulAssign(1/6),Ip(h.lessThan(0),(()=>{h.addAssign(1)}))})),Wp(h,u,l)})).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),JE=Cp((([e])=>{const t=Wp(e).toVar(),s=qp(ig(t,Wp(.04045))).toVar(),i=Wp(t.div(12.92)).toVar(),r=Wp(pf(nf(t.add(Wp(.055)),Wp(0)).div(1.055),Wp(2.4))).toVar();return vf(i,r,s)})).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),KE=(e,t)=>{e=Up(e),t=Up(t);const s=Vp(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Sf(e.sub(s),e.add(s),t)},QE=(e,t,s,i)=>vf(e,t,s[i].clamp()),eB=(e,t,s=My())=>QE(e,t,s,"x"),tB=(e,t,s=My())=>QE(e,t,s,"y"),sB=(e,t,s,i,r)=>vf(e,t,KE(s,i[r])),iB=(e,t,s,i=My())=>sB(e,t,s,i,"x"),rB=(e,t,s,i=My())=>sB(e,t,s,i,"y"),nB=(e=1,t=0,s=My())=>s.mul(e).add(t),oB=(e,t=1)=>(e=Up(e)).abs().pow(t).mul(e.sign()),aB=(e,t=1,s=.5)=>Up(e).sub(s).mul(t).add(s),hB=(e=My(),t=1,s=0)=>PE(e.convert("vec2|vec3")).mul(t).add(s),uB=(e=My(),t=1,s=0)=>FE(e.convert("vec2|vec3")).mul(t).add(s),lB=(e=My(),t=1,s=0)=>{e=e.convert("vec2|vec3");return $p(FE(e),PE(e.add(Vp(19,73)))).mul(t).add(s)},cB=(e=My(),t=1)=>qE(e.convert("vec2|vec3"),t,Op(1)),dB=(e=My(),t=1)=>$E(e.convert("vec2|vec3"),t,Op(1)),pB=(e=My(),t=1)=>XE(e.convert("vec2|vec3"),t,Op(1)),mB=(e=My())=>UE(e.convert("vec2|vec3")),gB=(e=My(),t=3,s=2,i=.5,r=1)=>zE(e,Op(t),s,i).mul(r),fB=(e=My(),t=3,s=2,i=.5,r=1)=>VE(e,Op(t),s,i).mul(r),yB=(e=My(),t=3,s=2,i=.5,r=1)=>LE(e,Op(t),s,i).mul(r),xB=(e=My(),t=3,s=2,i=.5,r=1)=>DE(e,Op(t),s,i).mul(r),bB=Cp((([e,t])=>{const s=e.x,i=e.y,r=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(i)),n=n.add(t.element(2).mul(1.023328).mul(r)),n=n.add(t.element(3).mul(1.023328).mul(s)),n=n.add(t.element(4).mul(.858086).mul(s).mul(i)),n=n.add(t.element(5).mul(.858086).mul(i).mul(r)),n=n.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(s).mul(r)),n=n.add(t.element(8).mul(.429043).mul(Jm(s,s).sub(Jm(i,i)))),n}));class vB extends PC{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=dm(0).setGroup(um),this.decayExponentNode=dm(0).setGroup(um)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setup(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:r}=this,n=e.context.lightingModel,o=VC(r).sub(lx),a=o.normalize(),h=o.length(),u=FC({lightDistance:h,cutoffDistance:s,decayExponent:i}),l=t.mul(u),c=e.context.reflectedLight;n.direct({lightDirection:a,lightColor:l,reflectedLight:c},e.stack,e)}}class TB extends PC{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,s=this.colorNode,i=DC(this.light),r=e.context.reflectedLight;t.direct({lightDirection:i,lightColor:s,reflectedLight:r},e.stack,e)}}const _B=new sr,wB=new sr;let SB=null;class MB extends PC{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=dm(new Ai).setGroup(um),this.halfWidth=dm(new Ai).setGroup(um)}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;wB.identity(),_B.copy(t.matrixWorld),_B.premultiply(s),wB.extractRotation(_B),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(wB),this.halfHeight.value.applyMatrix4(wB)}setup(e){let t,s;super.setup(e),e.isAvailable("float32Filterable")?(t=By(SB.LTC_FLOAT_1),s=By(SB.LTC_FLOAT_2)):(t=By(SB.LTC_HALF_1),s=By(SB.LTC_HALF_2));const{colorNode:i,light:r}=this,n=e.context.lightingModel,o=VC(r),a=e.context.reflectedLight;n.directRectArea({lightColor:i,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,reflectedLight:a,ltc_1:t,ltc_2:s},e.stack,e)}static setLTC(e){SB=e}}class AB extends PC{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=dm(0).setGroup(um),this.penumbraCosNode=dm(0).setGroup(um),this.cutoffDistanceNode=dm(0).setGroup(um),this.decayExponentNode=dm(0).setGroup(um)}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){const{coneCosNode:t,penumbraCosNode:s}=this;return Sf(t,s,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:s,cutoffDistanceNode:i,decayExponentNode:r,light:n}=this,o=VC(n).sub(lx),a=o.normalize(),h=a.dot(DC(n)),u=this.getSpotAttenuation(h),l=o.length(),c=FC({lightDistance:l,cutoffDistance:i,decayExponent:r}),d=s.mul(u).mul(c),p=e.context.reflectedLight;t.direct({lightDirection:a,lightColor:d,reflectedLight:p},e.stack,e)}}class NB extends AB{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e){const t=this.light.iesMap;let s=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);s=By(t,Vp(i,0),0).r}else s=super.getSpotAttenuation(e);return s}}class CB extends PC{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class RB extends PC{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=zC(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=dm(new Xr).setGroup(um)}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:s,lightDirectionNode:i}=this,r=xx.dot(i).mul(.5).add(.5),n=vf(s,t,r);e.context.irradiance.addAssign(n)}}class EB extends PC{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Ai);this.lightProbe=Ox(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=bB(bx,this.lightProbe);e.context.irradiance.addAssign(t)}}class BB{parseFunction(){console.warn("Abstract function.")}}class IB{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}IB.isNodeFunction=!0;const PB=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,FB=/[a-z_0-9]+/gi,UB="#pragma main";class OB extends IB{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(UB),s=-1!==t?e.slice(t+12):e,i=s.match(PB);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=FB.exec(r));)n.push(o);const a=[];let h=0;for(;h0?this.transparent:this.opaque).push(o)}unshift(e,t,s,i,r,n){const o=this.getNextRenderItem(e,t,s,i,r,n);(!0===s.transparent?this.transparent: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||LB),this.transparent.length>1&&this.transparent.sort(t||VB)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,h=o.height>>t;let u=e.depthTexture||r[t];const l=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===u&&l&&(u=new Xa,u.format=e.stencilBuffer?je:We,u.type=e.stencilBuffer?Oe:Be,u.image.width=a,u.image.height=h,r[t]=u),s.width===o.width&&o.height===s.height||(c=!0,u&&(u.needsUpdate=!0,u.image.width=a,u.image.height=h)),s.width=o.width,s.height=o.height,s.textures=n,s.depthTexture=u||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(c=!0,u&&(u.needsUpdate=!0),s.sampleCount=i);const d={sampleCount:i};for(let e=0;e{e.removeEventListener("dispose",t);for(let e=0;e0){const i=e.image;if(void 0===i)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=i;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(r.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version}if(!0!==s.initialized){s.initialized=!0,s.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}s.version=e.version}getSize(e,t=qB){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),t.width=s.width,t.height=s.height,t.depth=e.isCubeTexture?6:s.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return i=e.isCompressedTexture?e.mipmaps.length:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return!!this.isEnvironmentTexture(e)||(!0===e.isCompressedTexture||e.minFilter!==fe&&e.minFilter!==Te)}isEnvironmentTexture(e){const t=e.mapping;return t===le||t===ce||t===he||t===ue}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class XB extends Xr{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}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)}}const YB=new XB;class ZB extends Xw{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===r)i._clearColor.getRGB(YB,Jt),YB.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(YB,Jt),YB.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;YB.copy(i._clearColor);let o=s.backgroundMesh;if(void 0===o){const e=Pf($p(n).mul(gA),{getUV:()=>bx,getTextureLevel:()=>mA});let t=tv();t=t.setZ(t.w);const i=new pT;i.name="Background.material",i.side=d,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.lights=!1,i.vertexNode=t,i.colorNode=e,s.backgroundMeshNode=e,s.backgroundMesh=o=new On(new cu(1,32,32),i),o.frustumCulled=!1,o.name="Background.mesh",o.onBeforeRender=function(e,t,s){this.matrixWorld.copyPosition(s.matrixWorld)}}const a=n.getCacheKey();s.backgroundCacheKey!==a&&(s.backgroundMeshNode.node=$p(n).mul(gA),s.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null)}else console.error("THREE.Renderer: Unsupported background configuration.",r);if(!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=YB.r,e.g=YB.g,e.b=YB.b,e.a=YB.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(e.r*=e.a,e.g*=e.a,e.b*=e.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,s.clearColor=!0===i.autoClearColor,s.clearDepth=!0===i.autoClearDepth,s.clearStencil=!0===i.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}class JB{constructor(e,t,s,i,r,n,o,a,h,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=o,this.updateAfterNodes=a,this.monitor=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new mM(t.name,[],t.index,t);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}const KB=new WeakMap;class QB extends Xw{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new vM,this.nodeBuilderCache=new Map,this.callHashCache=new kw,this.groupsData=new kw}updateGroup(e){const t=e.groupNode,s=t.name;if(s===lm.name)return!0;if(s===um.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===hm.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}const i=[t,e];let r=this.groupsData.get(i);return void 0===r&&this.groupsData.set(i,r={}),r.version!==t.version&&(r.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const{nodeBuilderCache:i}=this,r=this.getForRenderCacheKey(e);if(s=i.get(r),void 0===s){const t=this.backend.createNodeBuilder(e.object,this.renderer);t.scene=e.scene,t.material=e.material,t.camera=e.camera,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.clippingContext=e.clippingContext,t.build(),s=this._createNodeBuilderState(t),i.set(r,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),s=this._createNodeBuilderState(i),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new JB(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.monitor,e.transforms)}getEnvironmentNode(e){return e.environmentNode||this.get(e).environmentNode||null}getBackgroundNode(e){return e.backgroundNode||this.get(e).backgroundNode||null}getFogNode(e){return e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){const s=[e,t],i=this.renderer.info.calls;let r=this.callHashCache.get(s);if(void 0===r||r.callId!==i){const n=this.getEnvironmentNode(e),o=this.getFogNode(e),a=[];t&&a.push(t.getCacheKey(!0)),n&&a.push(n.getCacheKey()),o&&a.push(o.getCacheKey()),a.push(this.renderer.shadowMap.enabled?1:0),r={callId:i,cacheKey:vd(a)},this.callHashCache.set(s,r)}return r.cacheKey}updateScene(e){this.updateEnvironment(e),this.updateFog(e),this.updateBackground(e)}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),s=e.background;if(s){const i=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==s||i){let i=null;if(!0===s.isCubeTexture||s.mapping===le||s.mapping===ce||s.mapping===de)if(e.backgroundBlurriness>0||s.mapping===de)i=hw(s,bx);else{let e;e=!0===s.isCubeTexture?Bx(s):By(s),i=PT(e)}else!0===s.isTexture?i=By(s,Vv.flipY()).setUpdateMatrix(!0):!0!==s.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",s);t.backgroundNode=i,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){let e=null;if(s.isFogExp2){const t=Dx("color","color",s).setGroup(um),i=Dx("density","float",s).setGroup(um);e=yC(t,i)}else if(s.isFog){const t=Dx("color","color",s).setGroup(um),i=Dx("near","float",s).setGroup(um),r=Dx("far","float",s).setGroup(um);e=gC(t,i,r)}else console.error("WebGPUNodes: Unsupported fog configuration.",s);t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){let e=null;!0===s.isCubeTexture?e=Bx(s):!0===s.isTexture?e=By(s):console.error("Nodes: Unsupported environment configuration.",s),t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,r=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=i,n.material=r,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}hasOutputChange(e){return KB.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=By(e,Vv).renderOutput(t.toneMapping,t.currentColorSpace);return KB.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new vM,this.nodeBuilderCache=new Map}}class eI{constructor(e,t){this.scene=e,this.camera=t}clone(){return Object.assign(new this.constructor,this)}}class tI{constructor(){this.lists=new kw}get(e,t){const s=this.lists,i=[e,t];let r=s.get(i);return void 0===r&&(r=new eI(e,t),s.set(i,r)),r}dispose(){this.lists=new kw}}class sI{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map,this.colorSpaceNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(null!==s){t=new s;for(const s in e)t[s]=e[s]}return t}addColorSpace(e,t){this.addType(e,t,this.colorSpaceNodes)}getColorSpaceFunction(e){return this.colorSpaceNodes.get(e)||null}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t.type,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t))console.warn(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}}addClass(e,t,s){if(s.has(t))console.warn(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}}const iI=new Kn,rI=new Ys,nI=new xi,oI=new Ko,aI=new sr,hI=new xi;class uI{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:r=!0,stencil:n=!1,antialias:o=!1,samples:a=0,getFallback:h=null}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=a||!0===o?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=Zt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=r,this.stencil=n,this.clippingPlanes=[],this.info=new rS,this.nodes={library:new sI,modelViewMatrix:null,modelNormalViewMatrix:null},this._getFallback=h,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new xi(0,0,this._width,this._height),this._scissor=new xi(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new rA(new pT),this._quad.material.type="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const u=!0===this.alpha?0:1;this._clearColor=new XB(0,0,0,u),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr={enabled:!1},this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,s)=>{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(e,t,this._renderTarget),n=e.overrideMaterial||s.material,o=this._objects.get(s,n,e,t,i.lightsNode,r),{fragmentShader:a,vertexShader:h}=o.getNodeBuilderState();return{fragmentShader:a,vertexShader:h}}}}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 s=this.backend;try{await s.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=s=this._getFallback(e),await s.init(this)}catch(e){return void t(e)}}this._nodes=new QB(this,s),this._animation=new Dw(this._nodes,this.info),this._attributes=new eS(s),this._background=new ZB(this,this._nodes),this._geometries=new iS(this._attributes,this.info),this._textures=new $B(this,s,this.info),this._pipelines=new lS(s,this._nodes),this._bindings=new cS(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new $w(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new kB,this._bundles=new tI,this._renderContexts=new HB,this._initialized=!0,e()}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,n=this._currentRenderContext,o=this._currentRenderObjectFunction,a=this._compilationPromises,h=!0===e.isScene?e:iI;null===s&&(s=e);const u=this._renderTarget,l=this._renderContexts.get(s,t,u),c=this._activeMipmapLevel,d=[];this._currentRenderContext=l,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),l.depth=this.depth,l.stencil=this.stencil,l.clippingContext||(l.clippingContext=new Ww),l.clippingContext.updateGlobal(this,t),h.onBeforeRender(this,e,t,u);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p),s!==e&&s.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==u){this._textures.updateRenderTarget(u,c);const e=this._textures.get(u);l.textures=e.textures,l.depthTexture=e.depthTexture}else l.textures=null,l.depthTexture=null;this._nodes.updateScene(h),this._background.update(h,p,l);const m=p.opaque,g=p.transparent,f=p.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,h,f),!0===this.transparent&&g.length>0&&this._renderObjects(g,t,h,f),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=o,this._compilationPromises=a,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init();const s=this._renderScene(e,t);await this.backend.resolveTimestampAsync(s,"render")}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,o=this._currentRenderContext,a=this._bundles.get(i,r),h=this.backend.get(a);void 0===h.renderContexts&&(h.renderContexts=new Set);const u=i.version!==h.version,l=!1===h.renderContexts.has(o)||u;if(h.renderContexts.add(o),l){this.backend.beginBundle(o),(void 0===h.renderObjects||u)&&(h.renderObjects=[]),this._currentRenderBundle=a;const e=n.opaque;e.length>0&&this._renderObjects(e,r,t,s),this._currentRenderBundle=null,this.backend.finishBundle(o,a),h.version=i.version}else{const{renderObjects:e}=h;for(let t=0,s=e.length;t>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=b,p.viewport=!1===p.viewportValue.equals(nI),p.scissorValue.copy(f).multiplyScalar(y).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(nI),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new Ww),p.clippingContext.updateGlobal(this,t),h.onBeforeRender(this,e,t,d),aI.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),oI.setFromProjectionMatrix(aI,m);const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,c);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=l,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,this._nodes.updateScene(h),this._background.update(h,v,p),this.backend.beginRender(p);const{bundles:T,lightsNode:_,transparent:w,opaque:S}=v;if(T.length>0&&this._renderBundles(T,h,_),!0===this.opaque&&S.length>0&&this._renderObjects(S,t,h,_),!0===this.transparent&&w.length>0&&this._renderObjects(w,t,h,_),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=o,this._currentRenderObjectFunction=a,null!==i){this.setRenderTarget(u,l,c);const e=this._quad;this._nodes.hasOutputChange(d.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(d.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}return h.onAfterRender(this,e,t,d),p}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,s){this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,s=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(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,s,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,r=0,n=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,i),o.minDepth=r,o.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,s=!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,s);const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i&&(this._textures.updateRenderTarget(i),r=this._textures.get(i)),this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget){const e=this._quad;this._nodes.hasOutputChange(i.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(i.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}}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,s=!0){!1===this._initialized&&await this.init(),this.clear(e,t,s)}clearColorAsync(){return this.clearAsync(!0,!1,!1)}clearDepthAsync(){return this.clearAsync(!1,!0,!1)}clearStencilAsync(){return this.clearAsync(!1,!1,!0)}get currentToneMapping(){return null!==this._renderTarget?0:this.toneMapping}get currentColorSpace(){return null!==this._renderTarget?Jt:this.outputColorSpace}dispose(){this.info.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(),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,r=this._pipelines,n=this._bindings,o=this._nodes,a=Array.isArray(e)?e:[e];if(void 0===a[0]||!0!==a[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const t of a){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),n.delete(t),o.delete(t)};t.addEventListener("dispose",e);const s=t.onInitFunction;null!==s&&s.call(t,{renderer:this})}o.updateForCompute(t),n.updateForCompute(t);const s=n.getForCompute(t),a=r.getForCompute(t,s);i.compute(e,t,s,a)}i.finishCompute(e),t.renderId=s}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e),await this.backend.resolveTimestampAsync(e,"compute")}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(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)}copyFramebufferToTexture(e,t=null){const s=this._currentRenderContext;this._textures.updateTexture(e),t=null===t?hI.set(0,0,e.image.width,e.image.height):t,this.backend.copyFramebufferToTexture(e,s,t)}copyTextureToTexture(e,t,s=null,i=null,r=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r)}readRenderTargetPixelsAsync(e,t,s,i,r,n=0,o=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,o)}_projectObject(e,t,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||oI.intersectsSprite(e)){!0===this.sortObjects&&hI.setFromMatrixPosition(e.matrixWorld).applyMatrix4(aI);const{geometry:t,material:r}=e;r.visible&&i.push(e,t,r,s,hI.z,null)}}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)&&(!e.frustumCulled||oI.intersectsObject(e))){const{geometry:t,material:r}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),hI.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(aI)),Array.isArray(r)){const n=t.groups;for(let o=0,a=n.length;o0?i:"";t=`${e.name} {\n\t${s} ${r.name}[${n}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,n=!0}const o=r.node.precision;if(null!==o&&(t=SI[o]+" "+t),n){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,s.push(t)}let r="";for(const t in i){const s=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Ee){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let s=0;for(const i of e)t+=`layout( location = ${s++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[],s=e.getMemberTypes();for(let e=0;ee*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,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);!1===i.has(e)&&i.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 s=this.extensions[e];if(void 0!==s)for(const{name:e,behavior:i}of s.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}isAvailable(e){let t=MI[e];if(void 0===t){if("float32Filterable"===e){const e=this.renderer.backend.extensions;e.has("OES_texture_float_linear")?(e.get("OES_texture_float_linear"),t=!0):t=!1}MI[e]=t}return t}isFlipY(){return!0}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${i.code}\n\t`,e===r&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${i.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=s}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);let o=n.uniformGPU;if(void 0===o){const i=e.groupNode,a=i.name,h=this.getBindGroupArray(a,s);if("texture"===t)o=new vI(r.name,r.node,i),h.push(o);else if("cubeTexture"===t)o=new TI(r.name,r.node,i),h.push(o);else if("texture3D"===t)o=new _I(r.name,r.node,i),h.push(o);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,r.name=`buffer${e.id}`;const t=new mI(e,i);t.name=e.name,h.push(t),o=t}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new yI(s+"_"+a,i),e[a]=n,h.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let CI=null,RI=null,EI=null;class BI{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}async init(e){this.renderer=e}begin(){}finish(){}draw(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}createRenderPipeline(){}createComputePipeline(){}destroyPipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}createDefaultTexture(){}createTexture(){}copyTextureToBuffer(){}createAttribute(){}createIndexAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}resolveTimestampAsync(){}hasFeatureAsync(){}hasFeature(){}getInstanceCount(e){const{object:t,geometry:s}=e;return s.isInstancedBufferGeometry?s.instanceCount:t.count>1?t.count:1}getDrawingBufferSize(){return CI=CI||new Ys,this.renderer.getDrawingBufferSize(CI)}getScissor(){return RI=RI||new xi,this.renderer.getScissor(RI)}setScissorTest(){}getClearColor(){const e=this.renderer;return EI=EI||new XB,e.getClearColor(EI),EI.getRGB(EI,this.renderer.currentColorSpace),EI}getDomElement(){let t=this.domElement;return null===t&&(t=void 0!==this.parameters.canvas?this.parameters.canvas:ti(),"setAttribute"in t&&t.setAttribute("data-engine",`three.js r${e} webgpu`),this.domElement=t),t}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)}}let II=0;class PI{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 FI{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,a=s.get(o);let h,u=a.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,n),a.bufferGPU=u,a.bufferType=t,a.version=o.version),r instanceof Float32Array)h=i.FLOAT;else if(r instanceof Uint16Array)h=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)h=i.SHORT;else if(r instanceof Uint32Array)h=i.UNSIGNED_INT;else if(r instanceof Int32Array)h=i.INT;else if(r instanceof Int8Array)h=i.BYTE;else if(r instanceof Uint8Array)h=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);h=i.UNSIGNED_BYTE}let l={bufferGPU:u,bufferType:t,type:h,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===Ee,id:II++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);l=new PI(l,e)}s.set(e,l)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,n=t.get(r),o=n.bufferType,a=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,n.bufferGPU),0===a.length)s.bufferSubData(o,0,i);else{for(let e=0,t=a.length;e1?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE)}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===s||(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t&&(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:s}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const n=e.textures;if(i.length!==n.length||i[0]!==s.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e{!function r(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void i();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(r)}()}))}}let DI,kI,GI,WI=!1;class jI{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===WI&&(this._init(this.gl),WI=!0)}_init(e){DI={[pe]:e.REPEAT,[me]:e.CLAMP_TO_EDGE,[ge]:e.MIRRORED_REPEAT},kI={[fe]:e.NEAREST,[ye]:e.NEAREST_MIPMAP_NEAREST,[be]:e.NEAREST_MIPMAP_LINEAR,[Te]:e.LINEAR,[_e]:e.LINEAR_MIPMAP_NEAREST,[Se]:e.LINEAR_MIPMAP_LINEAR},GI={512:e.NEVER,519:e.ALWAYS,[ys]:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===fe||e===ye||e===be?t.NEAREST:t.LINEAR}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,r=!1){const{gl:n,extensions:o}=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 a=t;return t===n.RED&&(s===n.FLOAT&&(a=n.R32F),s===n.HALF_FLOAT&&(a=n.R16F),s===n.UNSIGNED_BYTE&&(a=n.R8),s===n.UNSIGNED_SHORT&&(a=n.R16),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.R8UI),s===n.UNSIGNED_SHORT&&(a=n.R16UI),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RG&&(s===n.FLOAT&&(a=n.RG32F),s===n.HALF_FLOAT&&(a=n.RG16F),s===n.UNSIGNED_BYTE&&(a=n.RG8),s===n.UNSIGNED_SHORT&&(a=n.RG16),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RG_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RG8UI),s===n.UNSIGNED_SHORT&&(a=n.RG16UI),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RGB&&(s===n.FLOAT&&(a=n.RGB32F),s===n.HALF_FLOAT&&(a=n.RGB16F),s===n.UNSIGNED_BYTE&&(a=n.RGB8),s===n.UNSIGNED_SHORT&&(a=n.RGB16),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I),s===n.UNSIGNED_BYTE&&(a=i===Zt&&!1===r?n.SRGB8:n.RGB8),s===n.UNSIGNED_SHORT_5_6_5&&(a=n.RGB565),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGB4),s===n.UNSIGNED_INT_5_9_9_9_REV&&(a=n.RGB9_E5)),t===n.RGB_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGB8UI),s===n.UNSIGNED_SHORT&&(a=n.RGB16UI),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I)),t===n.RGBA&&(s===n.FLOAT&&(a=n.RGBA32F),s===n.HALF_FLOAT&&(a=n.RGBA16F),s===n.UNSIGNED_BYTE&&(a=n.RGBA8),s===n.UNSIGNED_SHORT&&(a=n.RGBA16),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I),s===n.UNSIGNED_BYTE&&(a=i===Zt&&!1===r?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1)),t===n.RGBA_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGBA8UI),s===n.UNSIGNED_SHORT&&(a=n.RGBA16UI),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_INT&&(a=n.DEPTH24_STENCIL8),s===n.FLOAT&&(a=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(a=n.DEPTH24_STENCIL8),a!==n.R16F&&a!==n.R32F&&a!==n.RG16F&&a!==n.RG32F&&a!==n.RGBA16F&&a!==n.RGBA32F||o.get("EXT_color_buffer_float"),a}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE),s.texParameteri(e,s.TEXTURE_WRAP_S,DI[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,DI[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||s.texParameteri(e,s.TEXTURE_WRAP_R,DI[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,kI[t.magFilter]);const n=void 0!==t.mipmaps&&t.mipmaps.length>0,o=t.minFilter===Te&&n?Se:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,kI[o]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,GI[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===fe)return;if(t.minFilter!==be&&t.minFilter!==Se)return;if(t.type===Ie&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,r=this.getGLTextureType(e);let n=i[r];void 0===n&&(n=t.createTexture(),s.state.bindTexture(r,n),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=n),s.set(e,{textureGPU:n,glTextureType:r,isDefault:!0})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:r,width:n,height:o,depth:a}=t,h=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,h,u,e.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,r,l,n,o,a):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,l,n,o,a):e.isVideoTexture||s.texStorage2D(d,r,l,n,o),i.set(e,{textureGPU:c,glTextureType:d,glFormat:h,glType:u,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:r,glTextureType:n,glFormat:o,glType:a}=i.get(t),{width:h,height:u}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(n,r),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(n,0,0,0,h,u,o,a,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:r}=t,{textureGPU:n,glTextureType:o,glFormat:a,glType:h,glInternalFormat:u}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===n)return;const l=e=>e.isDataTexture?e.image.data:e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLImageElement||e instanceof HTMLCanvasElement?e:e.data;if(this.backend.state.bindTexture(o,n),this.setTextureParameters(o,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t0,c=t.renderTarget?t.renderTarget.height:this.backend.gerDrawingBufferSize().y;if(l){const s=0!==o||0!==a;let l,d;if(!0===e.isDepthTexture?(l=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(l|=i.STENCIL_BUFFER_BIT)):(l=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),s){const e=this.backend.get(t.renderTarget),s=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,s),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=c-a-u;i.blitFramebuffer(o,p,o+h,p+u,o,p,o+h,p+u,l,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,s),r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,p,h,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,n,0),i.blitFramebuffer(0,0,h,u,0,0,h,u,l,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,c-u-a,h,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t){const{gl:s}=this,i=t.renderTarget,{samples:r,depthTexture:n,depthBuffer:o,stencilBuffer:a,width:h,height:u}=i;if(s.bindRenderbuffer(s.RENDERBUFFER,e),o&&!a){let t=s.DEPTH_COMPONENT24;r>0?(n&&n.isDepthTexture&&n.type===s.FLOAT&&(t=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,r,t,h,u)):s.renderbufferStorage(s.RENDERBUFFER,t,h,u),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else o&&a&&(r>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,r,s.DEPTH24_STENCIL8,h,u):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,h,u),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,s,i,r,n){const{backend:o,gl:a}=this,{textureGPU:h,glFormat:u,glType:l}=this.backend.get(e),c=a.createFramebuffer();a.bindFramebuffer(a.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?a.TEXTURE_CUBE_MAP_POSITIVE_X+n:a.TEXTURE_2D;a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,d,h,0);const p=this._getTypedArrayType(l),m=i*r*this._getBytesPerTexel(l,u),g=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.bufferData(a.PIXEL_PACK_BUFFER,m,a.STREAM_READ),a.readPixels(t,s,i,r,u,l,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();const f=new p(m/p.BYTES_PER_ELEMENT);return a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,f),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.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:s}=this;let i=0;return e===s.UNSIGNED_BYTE&&(i=1),e!==s.UNSIGNED_SHORT_4_4_4_4&&e!==s.UNSIGNED_SHORT_5_5_5_1&&e!==s.UNSIGNED_SHORT_5_6_5&&e!==s.UNSIGNED_SHORT&&e!==s.HALF_FLOAT||(i=2),e!==s.UNSIGNED_INT&&e!==s.FLOAT||(i=4),t===s.RGBA?4*i:t===s.RGB?3*i:t===s.ALPHA?i:void 0}}class HI{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 qI{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 s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const $I={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"};class XI{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:s,mode:i,object:r,type:n,info:o,index:a}=this;0!==a?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),o.update(r,t,i,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:o,object:a,info:h}=this;0!==s&&(0!==o?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),h.update(a,t,r,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:o}=this;if(0===s)return;const a=i.get("WEBGL_multi_draw");if(null===a)for(let i=0;i0)){const e=t.queryQueue.shift();this.initTimestampQuery(e)}}async resolveTimestampAsync(e,t="render"){if(!this.disjoint||!this.trackTimestamp)return;const s=this.get(e);s.gpuQueries||(s.gpuQueries=[]);for(let e=0;e0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext,n=e.occlusionQueryCount;n>0&&(n>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const o=e.textures;if(null!==o)for(let e=0;e0){const r=i.framebuffers[e.getCacheKey()],n=t.COLOR_BUFFER_BIT,o=i.msaaFrameBuffer,a=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,o),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,r);for(let s=0;s{let o=0;for(let t=0;t0&&e.add(i[t]),s[t]=null,r.deleteQuery(n),o++))}o1?m.renderInstances(y,g,f):m.render(y,g),o.bindVertexArray(null)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new NI(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,r="fragment"===s?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(){console.warn("Abstract class.")}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:n}=i,o=s.createProgram(),a=this.get(r).shaderGPU,h=this.get(n).shaderGPU;if(s.attachShader(o,a),s.attachShader(o,h),s.linkProgram(o),this.set(i,{programGPU:o,fragmentShader:a,vertexShader:h}),null!==t&&this.parallel){const r=new Promise((t=>{const r=this.parallel,n=()=>{s.getProgramParameter(o,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(n)};n()}));t.push(r)}else this._completeCompile(e,i)}_handleSource(e,t){const s=e.split("\n"),i=[],r=Math.max(t-6,0),n=Math.min(t+6,s.length);for(let e=r;e":" "} ${r}: ${s[e]}`)}return i.join("\n")}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=e.getShaderInfoLog(t).trim();if(i&&""===r)return"";const n=/ERROR: 0:(\d+)/.exec(r);if(n){const i=parseInt(n[1]);return s.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=i.getProgramInfoLog(e).trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,s,t);else{const n=this._getShaderErrors(i,s,"vertex"),o=this._getShaderErrors(i,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+o)}else""!==r&&console.warn("THREE.WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:o,vertexShader:a}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,o,a),s.useProgram(n);const h=e.getBindings();this._setupBindings(h,n),this.set(t,{programGPU:n})}createComputePipeline(e,t){const{state:s,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:n}=e,o=i.createProgram(),a=this.get(r).shaderGPU,h=this.get(n).shaderGPU,u=n.transforms,l=[],c=[];for(let e=0;e$I[t]===e)),s=this.extensions;for(let e=0;e0){if(void 0===l){const i=[];l=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,l);const r=[],u=e.textures;for(let s=0;s,\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:vA,stripIndexFormat:zA},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:vA,stripIndexFormat:zA},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,o=this.getTransferPipeline(i),a=this.getFlipYPipeline(i),h=this.device.createTexture({size:{width:r,height:n,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),u=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:RN,baseArrayLayer:s}),l=h.createView({baseMipLevel:0,mipLevelCount:1,dimension:RN,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),d=(e,t,s)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:s,loadOp:BA,storeOp:RA,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,r),n.draw(4,1,0,0),n.end()};d(o,u,l),d(a,l,u),this.device.queue.submit([c.finish()]),h.destroy()}generateMipmaps(e,t,s=0){const i=this.get(e);void 0===i.useCount&&(i.useCount=0,i.layers=[]);const r=i.layers[s]||this._mipmapCreateBundles(e,t,s),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,r),this.device.queue.submit([n.finish()]),0!==i.useCount&&(i.layers[s]=r),i.useCount++}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:RN,baseArrayLayer:s});const o=[];for(let a=1;a1&&!e.isMultisampleRenderTargetTexture){const e=Object.assign({},p);e.label=e.label+"-msaa",e.sampleCount=l,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=p}destroyTexture(e){const t=this.backend,s=t.get(e);s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else{const s=e.image.depth||1;for(let e=0;e1;for(let o=0;o]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,aP=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,hP={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_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 uP extends IB{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(oP);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=aP.exec(s));)i.push({name:r[1],type:r[2]});const n=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class lP extends BB{parseFunction(e){return new uP(e)}}const cP=self.GPUShaderStage,dP={vertex:cP?cP.VERTEX:1,fragment:cP?cP.FRAGMENT:2,compute:cP?cP.COMPUTE:4},pP={instance:!0,swizzleAssign:!1,storageBuffer:!0},mP={"^^":"tsl_xor"},gP={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",imat2:"mat2x2",umat2:"mat2x2",bmat2:"mat2x2",mat3:"mat3x3",imat3:"mat3x3",umat3:"mat3x3",bmat3:"mat3x3",mat4:"mat4x4",imat4:"mat4x4",umat4:"mat4x4",bmat4:"mat4x4"},fP={tsl_xor:new TS("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new TS("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new TS("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new TS("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new TS("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new TS("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new TS("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new TS("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 TS("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:new TS("\nfn tsl_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 {\n\n\tlet uvScaled = vec2( uv * vec2( dimension ) );\n\n\treturn ( ( uvScaled % dimension ) + dimension ) % dimension;\n\n}\n"),biquadraticTexture:new TS("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, level : i32 ) -> vec4f {\n\n\tlet iRes = vec2i( textureDimensions( map, level ) );\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, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2i( 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")},yP={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"};/Windows/g.test(navigator.userAgent)&&(fP.pow_float=new TS("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),fP.pow_vec2=new TS("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[fP.pow_float]),fP.pow_vec3=new TS("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[fP.pow_float]),fP.pow_vec4=new TS("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[fP.pow_float]),yP.pow_float="tsl_pow_float",yP.pow_vec2="tsl_pow_vec2",yP.pow_vec3="tsl_pow_vec3",yP.pow_vec4="tsl_pow_vec4");let xP="";!0!==/Firefox|Deno/g.test(navigator.userAgent)&&(xP+="diagnostic( off, derivative_uniformity );\n");class bP extends bM{constructor(e,t){super(e,t,new lP),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==Yt}_generateTextureSample(e,t,s,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s):this.generateTextureLod(e,t,s,"0")}_generateVideoSample(e,t,s=this.shaderStage){if("fragment"===s)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${s} shader.`)}_generateTextureSampleLevel(e,t,s,i,r,n=this.shaderStage){return"fragment"===n&&!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,i):this.generateTextureLod(e,t,s,i)}generateFilteredTexture(e,t,s,i="0"){return this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${s}, i32( ${i} ) )`}generateTextureLod(e,t,s,i="0"){this._include("repeatWrapping");return`textureLoad( ${t}, tsl_repeatWrapping( ${s}, ${!0===e.isMultisampleRenderTargetTexture?`textureDimensions( ${t} )`:`textureDimensions( ${t}, 0 )`} ), i32( ${i} ) )`}generateTextureLoad(e,t,s,i,r="0u"){return i?`textureLoad( ${t}, ${s}, ${i}, ${r} )`:`textureLoad( ${t}, ${s}, ${r} )`}generateTextureStore(e,t,s,i){return`textureStore( ${t}, ${s}, ${i} )`}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===Ie||!0===e.isMultisampleRenderTargetTexture}generateTexture(e,t,s,i,r=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,s,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,s,"0",i,r):this._generateTextureSample(e,t,s,i,r),n}generateTextureGrad(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,s,i,r,n=this.shaderStage){let o=null;return o=!0===e.isVideoTexture?this._generateVideoSample(t,s,n):this._generateTextureSampleLevel(e,t,s,i,r,n),o}generateTextureBias(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} 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,s=e.type;return"texture"===s||"cubeTexture"===s||"storageTexture"===s||"texture3D"===s?t:"buffer"===s||"storageBuffer"===s||"indirectStorageBuffer"===s?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=mP[e];return void 0!==t?(this._include(t),t):null}getStorageAccess(e){if(e.isStorageTextureNode)switch(e.access){case TN:return"read";case vN:return"write";default:return"read_write"}else switch(e.access){case xN:return"read_write";case bN:return"read";default:return"write"}}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let i;const o=e.groupNode,a=o.name,h=this.getBindGroupArray(a,s);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let n=null;if("texture"===t||"storageTexture"===t?n=new vI(r.name,r.node,o,e.access?e.access:null):"cubeTexture"===t?n=new TI(r.name,r.node,o,e.access?e.access:null):"texture3D"===t&&(n=new _I(r.name,r.node,o,e.access?e.access:null)),n.store=!0===e.isStorageTextureNode,n.setVisibility(dP[s]),"fragment"===s&&!1===this.isUnfilterable(e.value)&&!1===n.store){const e=new JI(`${r.name}_sampler`,r.node,o);e.setVisibility(dP[s]),h.push(e,n),i=[e,n]}else h.push(n),i=[n]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const r=new("buffer"===t?mI:eP)(e,o);r.setVisibility(dP[s]),h.push(r),i=r}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new yI(a,o),n.setVisibility(dP[s]),e[a]=n,h.push(n)),i=this.getNodeUniform(r,t),n.addUniform(i)}n.uniformGPU=i}return r}getBuiltin(e,t,s,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:s}),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,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n`;return s.result&&(r+=`\treturn ${s.result};\n`),r+="\n}\n",r}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")}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],s=this.directives[e];if(void 0!==s)for(const e of s)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")}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:i,type:r}of s.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,s,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:s,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const n=this.getType(i);t.push(`var<${s}> ${e}: array< ${n}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","id","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 s=this.getAttributesArray();for(let e=0,i=s.length;e`)}const i=this.getBuiltins("output");return i&&t.push("\t"+i),t.join(",\n")}getStructs(e){const t=[],s=this.structs[e];for(let e=0,i=s.length;e output : ${r};\n\n`)}return t.join("\n\n")}getVar(e,t){return`var ${t} : ${this.getType(e)}`}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`\t${this.getVar(e.type,e.name)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];for(let r=0;r";else if(!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array";else if(!0===t.isDepthTexture)i=`texture_depth${n}_2d`;else if(!0===t.isVideoTexture)i="texture_external";else if(!0===t.isData3DTexture)i="texture_3d";else if(!0===r.node.isStorageTextureNode){i=`texture_storage_2d<${nP(t)}, ${this.getStorageAccess(r.node)}>`}else{i=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const e=r.node,t=this.getType(e.bufferType),s=e.bufferCount,n=s>0&&"buffer"===r.type?", "+s:"",a=e.isAtomic?`atomic<${t}>`:`${t}`,h=`\t${r.name} : array< ${a}${n} >\n`,u=e.isStorageBufferNode?`storage, ${this.getStorageAccess(e)}`:"uniform";i.push(this._getWGSLStructBinding("NodeBuffer_"+e.id,h,u,o.binding++,o.group))}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(n[t]||(n[t]={index:o.binding++,id:o.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in n){const t=n[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let o=s.join("\n");return o+=i.join("\n"),o+=r.join("\n"),o}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],n=r[r.length-1],o=n.outputNode,a=void 0!==o&&!0===o.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),h=e.name;if(h&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${h}\n\t`),i+=`${r.code}\n\t`,e===n&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(a)s.returnType=o.nodeType,i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;\n\n",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getType(e){return gP[e]||e}isAvailable(e){let t=pP[e];return void 0===t&&("float32Filterable"===e&&(t=this.renderer.hasFeature("float32-filterable")),pP[e]=t),t}_getWGSLMethod(e){return void 0!==fP[e]&&this._include(e),yP[e]}_include(e){const t=fP[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// 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${xP}\n\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\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){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = id.x + id.y * numWorkgroups.x * u32(${t}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\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,s,i=0,r=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${s}> ${e} : ${n};`}}class vP{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=LA.Depth24PlusStencil8:e.depth&&(t=LA.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}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?fA:e.isLineSegments||e.isMesh&&!0===t.wireframe?yA:e.isLine?xA:e.isMesh?bA:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){return navigator.userAgent.includes("Quest")?LA.BGRA8Unorm:navigator.gpu.getPreferredCanvasFormat()}}const TP=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),_P=new Map([[gn,["float16"]]]),wP=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class SP{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,r=i.get(s);let n=r.buffer;if(void 0===n){const o=i.device;let a=s.array;if(!1===e.normalized&&(a.constructor===Int16Array||a.constructor===Uint16Array)){const e=new Uint32Array(a.length);for(let t=0;t1},layout:u.createPipelineLayout({bindGroupLayouts:d})},A={},N=e.context.depth,C=e.context.stencil;if(!0!==N&&!0!==C||(!0===N&&(A.format=w,A.depthWriteEnabled=i.depthWrite,A.depthCompare=_),!0===C&&(A.stencilFront=f,A.stencilBack={},A.stencilReadMask=i.stencilFuncMask,A.stencilWriteMask=i.stencilWriteMask),M.depthStencil=A),null===t)c.pipeline=u.createRenderPipeline(M);else{const e=new Promise((e=>{u.createRenderPipelineAsync(M).then((t=>{c.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e){const t=this.backend,{utils:s,device:i}=t,r=s.getCurrentDepthStencilFormat(e),n={label:"renderBundleEncoder",colorFormats:[s.getCurrentColorFormat(e)],depthStencilFormat:r,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(n)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),o=[];for(const e of t){const t=s.get(e);o.push(t.layout)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:o})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,o=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,a=null!==e.blendDstAlpha?e.blendDstAlpha:n,h=null!==e.blendEquationAlpha?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(h)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:iN},s={srcFactor:r,dstFactor:n,operation:iN}};if(e.premultipliedAlpha)switch(i){case 1:r(HA,YA,HA,YA);break;case 2:r(HA,HA,HA,HA);break;case 3:r(jA,$A,jA,HA);break;case 4:r(jA,qA,jA,XA)}else switch(i){case 1:r(XA,YA,HA,YA);break;case 2:r(XA,HA,XA,HA);break;case 3:r(jA,$A,jA,HA);break;case 4:r(jA,qA,jA,qA)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case 200:t=jA;break;case 201:t=HA;break;case 202:t=qA;break;case 203:t=$A;break;case R:t=XA;break;case E:t=YA;break;case 208:t=ZA;break;case 209:t=JA;break;case 206:t=KA;break;case 207:t=QA;break;case 210:t=eN;break;case 211:t=tN;break;case 212:t=sN;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=TA;break;case gs:t=CA;break;case 513:t=_A;break;case 515:t=SA;break;case 514:t=wA;break;case 518:t=NA;break;case 516:t=MA;break;case 517:t=AA;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case ts:t=lN;break;case 0:t=cN;break;case 7681:t=dN;break;case 5386:t=pN;break;case 7682:t=mN;break;case 7683:t=gN;break;case 34055:t=fN;break;case 34056:t=yN;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case v:t=iN;break;case 101:t=rN;break;case 102:t=nN;break;case 103:t=oN;break;case 104:t=aN;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?OA:zA),s.side){case c:i.frontFace=IA,i.cullMode=UA;break;case d:i.frontFace=IA,i.cullMode=FA;break;case 2:i.frontFace=IA,i.cullMode=PA;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?uN:hN}_getDepthCompare(e){let t;if(!1===e.depthTest)t=CA;else{const s=e.depthFunc;switch(s){case 0:t=TA;break;case 1:t=CA;break;case 2:t=_A;break;case 3:t=SA;break;case 4:t=wA;break;case 5:t=NA;break;case 6:t=MA;break;case 7:t=AA;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class NP extends BI{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.trackTimestamp=!0===e.trackTimestamp,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new vP(this),this.attributeUtils=new SP(this),this.bindingUtils=new MP(this),this.pipelineUtils=new AP(this),this.textureUtils=new rP(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference},i=await navigator.gpu.requestAdapter(e);if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(ON),n=[];for(const e of r)i.features.has(e)&&n.push(e);const o={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(o)}else s=t.device;const i=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=s,this.context=i;const r=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(ON.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r}),this.updateSize()}get coordinateSystem(){return Os}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 s=e.colorAttachments[0];this.renderer.samples>0?s.view=this.colorBuffer.createView():s.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}_getRenderPassDescriptor(e){const t=e.renderTarget,s=this.get(t);let i=s.descriptors;if(void 0===i||s.width!==t.width||s.height!==t.height||s.activeMipmapLevel!==t.activeMipmapLevel||s.samples!==t.samples){i={},s.descriptors=i;const e=()=>{t.removeEventListener("dispose",e),this.delete(t)};t.addEventListener("dispose",e)}const r=e.getCacheKey();let n=i[r];if(void 0===n){const o=e.textures,a=[];for(let t=0;t0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=s.createQuerySet({type:"occlusion",count:i}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e),this.initTimestampQuery(e,n),n.occlusionQuerySet=r;const o=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),s>0){const i=8*s;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const n=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,n,0,i),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.prepareTimestampBuffer(e,t.encoder),this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eo?(h.x=Math.min(t.dispatchCount,o),h.y=Math.ceil(t.dispatchCount/o)):h.x=t.dispatchCount,r.dispatchWorkgroups(h.x,h.y,h.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.prepareTimestampBuffer(e,t.cmdEncoderGPU),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:s,context:i,pipeline:r}=e,n=e.getBindings(),o=this.get(i),a=this.get(r).pipeline,h=o.currentSets,u=o.currentPass,l=e.getDrawParameters();if(null===l)return;h.pipeline!==a&&(u.setPipeline(a),h.pipeline=a);const c=h.bindingGroups;for(let e=0,t=n.length;e1?0:s;u.drawIndexed(t[s],i,e[s]/n,0,o)}}else if(!0===p){const{vertexCount:i,instanceCount:r,firstVertex:n}=l,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndexedIndirect(e,0)}else u.drawIndexed(i,r,n,0,0);t.update(s,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:n}=l,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndirect(e,0)}else u.draw(i,r,n,0);t.update(s,i,r)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),o=r.getCurrentColorSpace(e.context),a=r.getCurrentColorFormat(e.context),h=r.getCurrentDepthStencilFormat(e.context),u=r.getPrimitiveTopology(s,i);let l=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===o&&t.colorFormat===a&&t.depthStencilFormat===h&&t.primitiveTopology===u&&t.clippingContextCacheKey===e.clippingContext.cacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=n,t.colorSpace=o,t.colorFormat=a,t.depthStencilFormat=h,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContext.cacheKey,l=!0),l}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,r=e.context;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.clippingContext.cacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const s=this.get(e);if(!s.timeStampQuerySet){const e=this.device.createQuerySet({type:"timestamp",count:2}),i={querySet:e,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1};Object.assign(t,{timestampWrites:i}),s.timeStampQuerySet=e}}prepareTimestampBuffer(e,t){if(!this.trackTimestamp)return;const s=this.get(e),i=2*BigInt64Array.BYTES_PER_ELEMENT;void 0===s.currentTimestampQueryBuffers&&(s.currentTimestampQueryBuffers={resolveBuffer:this.device.createBuffer({label:"timestamp resolve buffer",size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),resultBuffer:this.device.createBuffer({label:"timestamp result buffer",size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),isMappingPending:!1});const{resolveBuffer:r,resultBuffer:n,isMappingPending:o}=s.currentTimestampQueryBuffers;!0!==o&&(t.resolveQuerySet(s.timeStampQuerySet,0,2,r,0),t.copyBufferToBuffer(r,0,n,0,i))}async resolveTimestampAsync(e,t="render"){if(!this.trackTimestamp)return;const s=this.get(e);if(void 0===s.currentTimestampQueryBuffers)return;const{resultBuffer:i,isMappingPending:r}=s.currentTimestampQueryBuffers;!0!==r&&(s.currentTimestampQueryBuffers.isMappingPending=!0,i.mapAsync(GPUMapMode.READ).then((()=>{const e=new BigUint64Array(i.getMappedRange()),r=Number(e[1]-e[0])/1e6;this.renderer.info.updateTimestamp(t,r),i.unmap(),s.currentTimestampQueryBuffers.isMappingPending=!1})))}createNodeBuilder(e,t){return new bP(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),i=s.currentPass.finish();this.get(t).bundleGPU=i,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e){this.bindingUtils.createBindings(e)}updateBindings(e){this.bindingUtils.createBindings(e)}updateBinding(e){this.bindingUtils.updateBinding(e)}createIndexAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0){let n=0,o=0,a=0,h=0,u=0,l=0,c=e.image.width,d=e.image.height;null!==s&&(h=s.x,u=s.y,l=s.z||0,c=s.width,d=s.height),null!==i&&(n=i.x,o=i.y,a=i.z||0);const p=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),m=this.get(e).texture,g=this.get(t).texture;p.copyTextureToTexture({texture:m,mipLevel:r,origin:{x:h,y:u,z:l}},{texture:g,mipLevel:r,origin:{x:n,y:o,z:a}},[c,d,1]),this.device.queue.submit([p.finish()])}copyFramebufferToTexture(e,t,s){const i=this.get(t),{encoder:r,descriptor:n}=i;let o=null;o=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const a=this.get(e).texture;if(o.format===a.format){i.currentPass.end(),r.copyTextureToTexture({texture:o,origin:{x:s.x,y:s.y,z:0}},{texture:a},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e);for(let e=0;e(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new YI(e)));super(new t(e),e),this.nodes.library=new RP,this.isWebGPURenderer=!0}}class BP extends ka{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}const IP=new pT,PP=new rA(IP);class FP{constructor(e,t=$p(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0,IP.name="PostProcessing"}render(){this.update();const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;e.toneMapping=0,e.outputColorSpace=Jt,PP.render(e),e.toneMapping=t,e.outputColorSpace=s}update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;PP.material.fragmentNode=!0===this.outputColorTransform?Ty(this.outputNode,t,s):this.outputNode.context({toneMapping:t,outputColorSpace:s}),PP.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){this.update();const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;e.toneMapping=0,e.outputColorSpace=Jt,await PP.renderAsync(e),e.toneMapping=t,e.outputColorSpace=s}}function UP(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new Xr),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}function OP(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 zP(e,t,s={}){return(s=UP(e,s)).background=t.background,s.backgroundNode=t.backgroundNode,s.overrideMaterial=t.overrideMaterial,s}var LP=Object.freeze({__proto__:null,resetRendererAndSceneState:function(e,t,s){return s=zP(e,t,s),t.background=null,t.backgroundNode=null,t.overrideMaterial=null,s},resetRendererState:function(e,t){return t=UP(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t},restoreRendererAndSceneState:function(e,t,s){OP(e,s),t.background=s.background,t.backgroundNode=s.backgroundNode,t.overrideMaterial=s.overrideMaterial},restoreRendererState:OP,saveRendererAndSceneState:zP,saveRendererState:UP});class VP extends yi{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=Te,this.minFilter=Te,this.isStorageTexture=!0}}class DP extends an{constructor(e,t,s=Float32Array){!1===ArrayBuffer.isView(e)&&(e=new s(e*t)),super(e,t),this.isStorageBufferAttribute=!0}}class kP extends zo{constructor(e,t,s=Float32Array){!1===ArrayBuffer.isView(e)&&(e=new s(e*t)),super(e,t),this.isStorageInstancedBufferAttribute=!0}}class GP extends DP{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class WP extends el{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,s,i){const r=new il(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,(s=>{try{t(this.parse(JSON.parse(s)))}catch(t){i?i(t):console.error(t),this.manager.itemError(e)}}),s,i)}parseNodes(e){const t={};if(void 0!==e){for(const s of e){const{uuid:e,type:i}=s;t[e]=this.createNodeFromType(i),t[e].uuid=e}const s={nodes:t,textures:this.textures};for(const i of e){i.meta=s;t[i.uuid].deserialize(i),delete i.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const s={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=s,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),Up()):wp(new this.nodes[e])}}class jP extends El{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),s=this.nodes,i=e.inputNodes;for(const e in i){const r=i[e];t[e]=s[r]}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 HP extends Fl{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 s=super.parse(e,t);return this._nodesJSON=null,s}parseNodes(e,t){if(void 0!==e){const s=new WP;return s.setNodes(this.nodes),s.setTextures(t),s.parseNodes(e)}return{}}parseMaterials(e,t){const s={};if(void 0!==e){const i=this.parseNodes(this._nodesJSON,t),r=new jP;r.setTextures(t),r.setNodes(i),r.setNodeMaterials(this.nodeMaterials);for(let t=0,i=e.length;t>8&255]+Ls[e>>16&255]+Ls[e>>24&255]+"-"+Ls[255&t]+Ls[t>>8&255]+"-"+Ls[t>>16&15|64]+Ls[t>>24&255]+"-"+Ls[63&s|128]+Ls[s>>8&255]+"-"+Ls[s>>16&255]+Ls[s>>24&255]+Ls[255&i]+Ls[i>>8&255]+Ls[i>>16&255]+Ls[i>>24&255]).toLowerCase()}function Ws(e,t,s){return Math.max(t,Math.min(s,e))}function js(e,t){return(e%t+t)%t}function Hs(e,t,s){return(1-s)*e+s*t}function qs(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function $s(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Xs={DEG2RAD:Ds,RAD2DEG:ks,generateUUID:Gs,clamp:Ws,euclideanModulo:js,mapLinear:function(e,t,s,i,r){return i+(e-t)*(r-i)/(s-t)},inverseLerp:function(e,t,s){return e!==t?(s-e)/(t-e):0},lerp:Hs,damp:function(e,t,s,i){return Hs(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(js(e,2*t)-t)},smoothstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*(3-2*e)},smootherstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Vs=e);let t=Vs+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*Ds},radToDeg:function(e){return e*ks},isPowerOfTwo:function(e){return 0==(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,s,i,r){const n=Math.cos,o=Math.sin,a=n(s/2),h=o(s/2),u=n((t+i)/2),l=o((t+i)/2),c=n((t-i)/2),d=o((t-i)/2),p=n((i-t)/2),m=o((i-t)/2);switch(r){case"XYX":e.set(a*l,h*c,h*d,a*u);break;case"YZY":e.set(h*d,a*l,h*c,a*u);break;case"ZXZ":e.set(h*c,h*d,a*l,a*u);break;case"XZX":e.set(a*l,h*m,h*p,a*u);break;case"YXY":e.set(h*p,a*l,h*m,a*u);break;case"ZYZ":e.set(h*m,h*p,a*l,a*u);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:$s,denormalize:qs};class Ys{constructor(e=0,t=0){Ys.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Ws(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const s=Math.cos(t),i=Math.sin(t),r=this.x-e.x,n=this.y-e.y;return this.x=r*s-n*i+e.x,this.y=r*i+n*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Zs{constructor(e,t,s,i,r,n,o,a,h){Zs.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,h)}set(e,t,s,i,r,n,o,a,h){const u=this.elements;return u[0]=e,u[1]=i,u[2]=o,u[3]=t,u[4]=r,u[5]=a,u[6]=s,u[7]=n,u[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[3],a=s[6],h=s[1],u=s[4],l=s[7],c=s[2],d=s[5],p=s[8],m=i[0],g=i[3],f=i[6],y=i[1],x=i[4],b=i[7],v=i[2],T=i[5],_=i[8];return r[0]=n*m+o*y+a*v,r[3]=n*g+o*x+a*T,r[6]=n*f+o*b+a*_,r[1]=h*m+u*y+l*v,r[4]=h*g+u*x+l*T,r[7]=h*f+u*b+l*_,r[2]=c*m+d*y+p*v,r[5]=c*g+d*x+p*T,r[8]=c*f+d*b+p*_,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8];return t*n*u-t*o*h-s*r*u+s*o*a+i*r*h-i*n*a}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8],l=u*n-o*h,c=o*a-u*r,d=h*r-n*a,p=t*l+s*c+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=l*m,e[1]=(i*h-u*s)*m,e[2]=(o*s-i*n)*m,e[3]=c*m,e[4]=(u*t-i*a)*m,e[5]=(i*r-o*t)*m,e[6]=d*m,e[7]=(s*a-h*t)*m,e[8]=(n*t-s*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,s,i,r,n,o){const a=Math.cos(r),h=Math.sin(r);return this.set(s*a,s*h,-s*(a*n+h*o)+n+e,-i*h,i*a,-i*(-h*n+a*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Js.makeScale(e,t)),this}rotate(e){return this.premultiply(Js.makeRotation(-e)),this}translate(e,t){return this.premultiply(Js.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<9;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const Js=new Zs;const Ks={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Qs(e,t){return new Ks[e](t)}function ei(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function ti(){const e=ei("canvas");return e.style.display="block",e}const si={};const ii={enabled:!0,workingColorSpace:Jt,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Qt&&(e.r=ri(e.r),e.g=ri(e.g),e.b=ri(e.b)),this.spaces[t].primaries!==this.spaces[s].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Qt&&(e.r=ni(e.r),e.g=ni(e.g),e.b=ni(e.b)),e):e},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===Yt?Kt:this.spaces[e].transfer},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,s){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace}};function ri(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function ni(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}const oi=[.64,.33,.3,.6,.15,.06],ai=[.2126,.7152,.0722],hi=[.3127,.329],ui=(new Zs).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),li=(new Zs).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);let ci;ii.define({[Jt]:{primaries:oi,whitePoint:hi,transfer:Kt,toXYZ:ui,fromXYZ:li,luminanceCoefficients:ai,workingColorSpaceConfig:{unpackColorSpace:Zt},outputColorSpaceConfig:{drawingBufferColorSpace:Zt}},[Zt]:{primaries:oi,whitePoint:hi,transfer:Qt,toXYZ:ui,fromXYZ:li,luminanceCoefficients:ai,outputColorSpaceConfig:{drawingBufferColorSpace:Zt}}});class di{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===ci&&(ci=ei("canvas")),ci.width=e.width,ci.height=e.height;const s=ci.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),t=ci}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=ei("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==ae)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case pe:e.x=e.x-Math.floor(e.x);break;case me:e.x=e.x<0?0:1;break;case ge:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case pe:e.y=e.y-Math.floor(e.y);break;case me:e.y=e.y<0?0:1;break;case ge:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}yi.DEFAULT_IMAGE=null,yi.DEFAULT_MAPPING=ae,yi.DEFAULT_ANISOTROPY=1;class xi{constructor(e=0,t=0,s=0,i=1){xi.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=this.w,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i+n[12]*r,this.y=n[1]*t+n[5]*s+n[9]*i+n[13]*r,this.z=n[2]*t+n[6]*s+n[10]*i+n[14]*r,this.w=n[3]*t+n[7]*s+n[11]*i+n[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,s,i,r;const n=.01,o=.1,a=e.elements,h=a[0],u=a[4],l=a[8],c=a[1],d=a[5],p=a[9],m=a[2],g=a[6],f=a[10];if(Math.abs(u-c)a&&e>y?ey?a=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),n=Math.atan2(r,t*s);e=Math.sin(e*n)/r,o=Math.sin(o*n)/r}const r=o*s;if(a=a*e+c*r,h=h*e+d*r,u=u*e+p*r,l=l*e+m*r,e===1-o){const e=1/Math.sqrt(a*a+h*h+u*u+l*l);a*=e,h*=e,u*=e,l*=e}}e[t]=a,e[t+1]=h,e[t+2]=u,e[t+3]=l}static multiplyQuaternionsFlat(e,t,s,i,r,n){const o=s[i],a=s[i+1],h=s[i+2],u=s[i+3],l=r[n],c=r[n+1],d=r[n+2],p=r[n+3];return e[t]=o*p+u*l+a*d-h*c,e[t+1]=a*p+u*c+h*l-o*d,e[t+2]=h*p+u*d+o*c-a*l,e[t+3]=u*p-o*l-a*c-h*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,r=e._z,n=e._order,o=Math.cos,a=Math.sin,h=o(s/2),u=o(i/2),l=o(r/2),c=a(s/2),d=a(i/2),p=a(r/2);switch(n){case"XYZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"YXZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"ZXY":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"ZYX":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"YZX":this._x=c*u*l+h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l-c*d*p;break;case"XZY":this._x=c*u*l-h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l+c*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],r=t[8],n=t[1],o=t[5],a=t[9],h=t[2],u=t[6],l=t[10],c=s+o+l;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(u-a)*e,this._y=(r-h)*e,this._z=(n-i)*e}else if(s>o&&s>l){const e=2*Math.sqrt(1+s-o-l);this._w=(u-a)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+h)/e}else if(o>l){const e=2*Math.sqrt(1+o-s-l);this._w=(r-h)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(a+u)/e}else{const e=2*Math.sqrt(1+l-s-o);this._w=(n-i)/e,this._x=(r+h)/e,this._y=(a+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return sMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ws(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(0===s)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,i=e._y,r=e._z,n=e._w,o=t._x,a=t._y,h=t._z,u=t._w;return this._x=s*u+n*o+i*h-r*a,this._y=i*u+n*a+r*o-s*h,this._z=r*u+n*h+s*a-i*o,this._w=n*u-s*o-i*a-r*h,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const s=this._x,i=this._y,r=this._z,n=this._w;let o=n*e._w+s*e._x+i*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=n,this._x=s,this._y=i,this._z=r,this;const a=1-o*o;if(a<=Number.EPSILON){const e=1-t;return this._w=e*n+t*this._w,this._x=e*s+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const h=Math.sqrt(a),u=Math.atan2(h,o),l=Math.sin((1-t)*u)/h,c=Math.sin(t*u)/h;return this._w=n*l+this._w*c,this._x=s*l+this._x*c,this._y=i*l+this._y*c,this._z=r*l+this._z*c,this._onChangeCallback(),this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),r=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ai{constructor(e=0,t=0,s=0){Ai.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return void 0===s&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Ci.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ci.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6]*i,this.y=r[1]*t+r[4]*s+r[7]*i,this.z=r[2]*t+r[5]*s+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=e.elements,n=1/(r[3]*t+r[7]*s+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*s+r[8]*i+r[12])*n,this.y=(r[1]*t+r[5]*s+r[9]*i+r[13])*n,this.z=(r[2]*t+r[6]*s+r[10]*i+r[14])*n,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,r=e.x,n=e.y,o=e.z,a=e.w,h=2*(n*i-o*s),u=2*(o*t-r*i),l=2*(r*s-n*t);return this.x=t+a*h+n*l-o*u,this.y=s+a*u+o*h-r*l,this.z=i+a*l+r*u-n*h,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i,this.y=r[1]*t+r[5]*s+r[9]*i,this.z=r[2]*t+r[6]*s+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,r=e.z,n=t.x,o=t.y,a=t.z;return this.x=i*a-r*o,this.y=r*n-s*a,this.z=s*o-i*n,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Ni.copy(this).projectOnVector(e),this.sub(Ni)}reflect(e){return this.sub(Ni.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Ws(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ni=new Ai,Ci=new Mi;class Ri{constructor(e=new Ai(1/0,1/0,1/0),t=new Ai(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Bi),Bi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Vi),Di.subVectors(this.max,Vi),Pi.subVectors(e.a,Vi),Fi.subVectors(e.b,Vi),Ui.subVectors(e.c,Vi),Oi.subVectors(Fi,Pi),zi.subVectors(Ui,Fi),Li.subVectors(Pi,Ui);let t=[0,-Oi.z,Oi.y,0,-zi.z,zi.y,0,-Li.z,Li.y,Oi.z,0,-Oi.x,zi.z,0,-zi.x,Li.z,0,-Li.x,-Oi.y,Oi.x,0,-zi.y,zi.x,0,-Li.y,Li.x,0];return!!Wi(t,Pi,Fi,Ui,Di)&&(t=[1,0,0,0,1,0,0,0,1],!!Wi(t,Pi,Fi,Ui,Di)&&(ki.crossVectors(Oi,zi),t=[ki.x,ki.y,ki.z],Wi(t,Pi,Fi,Ui,Di)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Bi).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Ei[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ei[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ei[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ei[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ei[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ei[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ei[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ei[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ei)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Ei=[new Ai,new Ai,new Ai,new Ai,new Ai,new Ai,new Ai,new Ai],Bi=new Ai,Ii=new Ri,Pi=new Ai,Fi=new Ai,Ui=new Ai,Oi=new Ai,zi=new Ai,Li=new Ai,Vi=new Ai,Di=new Ai,ki=new Ai,Gi=new Ai;function Wi(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){Gi.fromArray(e,n);const o=r.x*Math.abs(Gi.x)+r.y*Math.abs(Gi.y)+r.z*Math.abs(Gi.z),a=t.dot(Gi),h=s.dot(Gi),u=i.dot(Gi);if(Math.max(-Math.max(a,h,u),Math.min(a,h,u))>o)return!1}return!0}const ji=new Ri,Hi=new Ai,qi=new Ai;class $i{constructor(e=new Ai,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const s=this.center;void 0!==t?s.copy(t):ji.setFromPoints(e).getCenter(s);let i=0;for(let t=0,r=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Hi.subVectors(e,this.center);const t=Hi.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Hi,s/e),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(qi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Hi.copy(e.center).add(qi)),this.expandByPoint(Hi.copy(e.center).sub(qi))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Xi=new Ai,Yi=new Ai,Zi=new Ai,Ji=new Ai,Ki=new Ai,Qi=new Ai,er=new Ai;class tr{constructor(e=new Ai,t=new Ai(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Xi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Xi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Xi.copy(this.origin).addScaledVector(this.direction,t),Xi.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){Yi.copy(e).add(t).multiplyScalar(.5),Zi.copy(t).sub(e).normalize(),Ji.copy(this.origin).sub(Yi);const r=.5*e.distanceTo(t),n=-this.direction.dot(Zi),o=Ji.dot(this.direction),a=-Ji.dot(Zi),h=Ji.lengthSq(),u=Math.abs(1-n*n);let l,c,d,p;if(u>0)if(l=n*a-o,c=n*o-a,p=r*u,l>=0)if(c>=-p)if(c<=p){const e=1/u;l*=e,c*=e,d=l*(l+n*c+2*o)+c*(n*l+c+2*a)+h}else c=r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;else c=-r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;else c<=-p?(l=Math.max(0,-(-n*r+o)),c=l>0?-r:Math.min(Math.max(-r,-a),r),d=-l*l+c*(c+2*a)+h):c<=p?(l=0,c=Math.min(Math.max(-r,-a),r),d=c*(c+2*a)+h):(l=Math.max(0,-(n*r+o)),c=l>0?r:Math.min(Math.max(-r,-a),r),d=-l*l+c*(c+2*a)+h);else c=n>0?-r:r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;return s&&s.copy(this.origin).addScaledVector(this.direction,l),i&&i.copy(Yi).addScaledVector(Zi,c),d}intersectSphere(e,t){Xi.subVectors(e.center,this.origin);const s=Xi.dot(this.direction),i=Xi.dot(Xi)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),o=s-n,a=s+n;return a<0?null:o<0?this.at(a,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return null===s?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,r,n,o,a;const h=1/this.direction.x,u=1/this.direction.y,l=1/this.direction.z,c=this.origin;return h>=0?(s=(e.min.x-c.x)*h,i=(e.max.x-c.x)*h):(s=(e.max.x-c.x)*h,i=(e.min.x-c.x)*h),u>=0?(r=(e.min.y-c.y)*u,n=(e.max.y-c.y)*u):(r=(e.max.y-c.y)*u,n=(e.min.y-c.y)*u),s>n||r>i?null:((r>s||isNaN(s))&&(s=r),(n=0?(o=(e.min.z-c.z)*l,a=(e.max.z-c.z)*l):(o=(e.max.z-c.z)*l,a=(e.min.z-c.z)*l),s>a||o>i?null:((o>s||s!=s)&&(s=o),(a=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Xi)}intersectTriangle(e,t,s,i,r){Ki.subVectors(t,e),Qi.subVectors(s,e),er.crossVectors(Ki,Qi);let n,o=this.direction.dot(er);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}Ji.subVectors(this.origin,e);const a=n*this.direction.dot(Qi.crossVectors(Ji,Qi));if(a<0)return null;const h=n*this.direction.dot(Ki.cross(Ji));if(h<0)return null;if(a+h>o)return null;const u=-n*Ji.dot(er);return u<0?null:this.at(u/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class sr{constructor(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g){sr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g)}set(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g){const f=this.elements;return f[0]=e,f[4]=t,f[8]=s,f[12]=i,f[1]=r,f[5]=n,f[9]=o,f[13]=a,f[2]=h,f[6]=u,f[10]=l,f[14]=c,f[3]=d,f[7]=p,f[11]=m,f[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new sr).fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,s){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,s=e.elements,i=1/ir.setFromMatrixColumn(e,0).length(),r=1/ir.setFromMatrixColumn(e,1).length(),n=1/ir.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*r,t[5]=s[5]*r,t[6]=s[6]*r,t[7]=0,t[8]=s[8]*n,t[9]=s[9]*n,t[10]=s[10]*n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,r=e.z,n=Math.cos(s),o=Math.sin(s),a=Math.cos(i),h=Math.sin(i),u=Math.cos(r),l=Math.sin(r);if("XYZ"===e.order){const e=n*u,s=n*l,i=o*u,r=o*l;t[0]=a*u,t[4]=-a*l,t[8]=h,t[1]=s+i*h,t[5]=e-r*h,t[9]=-o*a,t[2]=r-e*h,t[6]=i+s*h,t[10]=n*a}else if("YXZ"===e.order){const e=a*u,s=a*l,i=h*u,r=h*l;t[0]=e+r*o,t[4]=i*o-s,t[8]=n*h,t[1]=n*l,t[5]=n*u,t[9]=-o,t[2]=s*o-i,t[6]=r+e*o,t[10]=n*a}else if("ZXY"===e.order){const e=a*u,s=a*l,i=h*u,r=h*l;t[0]=e-r*o,t[4]=-n*l,t[8]=i+s*o,t[1]=s+i*o,t[5]=n*u,t[9]=r-e*o,t[2]=-n*h,t[6]=o,t[10]=n*a}else if("ZYX"===e.order){const e=n*u,s=n*l,i=o*u,r=o*l;t[0]=a*u,t[4]=i*h-s,t[8]=e*h+r,t[1]=a*l,t[5]=r*h+e,t[9]=s*h-i,t[2]=-h,t[6]=o*a,t[10]=n*a}else if("YZX"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*u,t[4]=r-e*l,t[8]=i*l+s,t[1]=l,t[5]=n*u,t[9]=-o*u,t[2]=-h*u,t[6]=s*l+i,t[10]=e-r*l}else if("XZY"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*u,t[4]=-l,t[8]=h*u,t[1]=e*l+r,t[5]=n*u,t[9]=s*l-i,t[2]=i*l-s,t[6]=o*u,t[10]=r*l+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(nr,e,or)}lookAt(e,t,s){const i=this.elements;return ur.subVectors(e,t),0===ur.lengthSq()&&(ur.z=1),ur.normalize(),ar.crossVectors(s,ur),0===ar.lengthSq()&&(1===Math.abs(s.z)?ur.x+=1e-4:ur.z+=1e-4,ur.normalize(),ar.crossVectors(s,ur)),ar.normalize(),hr.crossVectors(ur,ar),i[0]=ar.x,i[4]=hr.x,i[8]=ur.x,i[1]=ar.y,i[5]=hr.y,i[9]=ur.y,i[2]=ar.z,i[6]=hr.z,i[10]=ur.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[4],a=s[8],h=s[12],u=s[1],l=s[5],c=s[9],d=s[13],p=s[2],m=s[6],g=s[10],f=s[14],y=s[3],x=s[7],b=s[11],v=s[15],T=i[0],_=i[4],w=i[8],S=i[12],M=i[1],A=i[5],N=i[9],C=i[13],R=i[2],E=i[6],B=i[10],I=i[14],P=i[3],F=i[7],U=i[11],O=i[15];return r[0]=n*T+o*M+a*R+h*P,r[4]=n*_+o*A+a*E+h*F,r[8]=n*w+o*N+a*B+h*U,r[12]=n*S+o*C+a*I+h*O,r[1]=u*T+l*M+c*R+d*P,r[5]=u*_+l*A+c*E+d*F,r[9]=u*w+l*N+c*B+d*U,r[13]=u*S+l*C+c*I+d*O,r[2]=p*T+m*M+g*R+f*P,r[6]=p*_+m*A+g*E+f*F,r[10]=p*w+m*N+g*B+f*U,r[14]=p*S+m*C+g*I+f*O,r[3]=y*T+x*M+b*R+v*P,r[7]=y*_+x*A+b*E+v*F,r[11]=y*w+x*N+b*B+v*U,r[15]=y*S+x*C+b*I+v*O,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[4],i=e[8],r=e[12],n=e[1],o=e[5],a=e[9],h=e[13],u=e[2],l=e[6],c=e[10],d=e[14];return e[3]*(+r*a*l-i*h*l-r*o*c+s*h*c+i*o*d-s*a*d)+e[7]*(+t*a*d-t*h*c+r*n*c-i*n*d+i*h*u-r*a*u)+e[11]*(+t*h*l-t*o*d-r*n*l+s*n*d+r*o*u-s*h*u)+e[15]*(-i*o*u-t*a*l+t*o*c+i*n*l-s*n*c+s*a*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8],l=e[9],c=e[10],d=e[11],p=e[12],m=e[13],g=e[14],f=e[15],y=l*g*h-m*c*h+m*a*d-o*g*d-l*a*f+o*c*f,x=p*c*h-u*g*h-p*a*d+n*g*d+u*a*f-n*c*f,b=u*m*h-p*l*h+p*o*d-n*m*d-u*o*f+n*l*f,v=p*l*a-u*m*a-p*o*c+n*m*c+u*o*g-n*l*g,T=t*y+s*x+i*b+r*v;if(0===T)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const _=1/T;return e[0]=y*_,e[1]=(m*c*r-l*g*r-m*i*d+s*g*d+l*i*f-s*c*f)*_,e[2]=(o*g*r-m*a*r+m*i*h-s*g*h-o*i*f+s*a*f)*_,e[3]=(l*a*r-o*c*r-l*i*h+s*c*h+o*i*d-s*a*d)*_,e[4]=x*_,e[5]=(u*g*r-p*c*r+p*i*d-t*g*d-u*i*f+t*c*f)*_,e[6]=(p*a*r-n*g*r-p*i*h+t*g*h+n*i*f-t*a*f)*_,e[7]=(n*c*r-u*a*r+u*i*h-t*c*h-n*i*d+t*a*d)*_,e[8]=b*_,e[9]=(p*l*r-u*m*r-p*s*d+t*m*d+u*s*f-t*l*f)*_,e[10]=(n*m*r-p*o*r+p*s*h-t*m*h-n*s*f+t*o*f)*_,e[11]=(u*o*r-n*l*r-u*s*h+t*l*h+n*s*d-t*o*d)*_,e[12]=v*_,e[13]=(u*m*i-p*l*i+p*s*c-t*m*c-u*s*g+t*l*g)*_,e[14]=(p*o*i-n*m*i-p*s*a+t*m*a+n*s*g-t*o*g)*_,e[15]=(n*l*i-u*o*i+u*s*a-t*l*a-n*s*c+t*o*c)*_,this}scale(e){const t=this.elements,s=e.x,i=e.y,r=e.z;return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),r=1-s,n=e.x,o=e.y,a=e.z,h=r*n,u=r*o;return this.set(h*n+s,h*o-i*a,h*a+i*o,0,h*o+i*a,u*o+s,u*a-i*n,0,h*a-i*o,u*a+i*n,r*a*a+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,r,n){return this.set(1,s,r,0,e,1,n,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,r=t._x,n=t._y,o=t._z,a=t._w,h=r+r,u=n+n,l=o+o,c=r*h,d=r*u,p=r*l,m=n*u,g=n*l,f=o*l,y=a*h,x=a*u,b=a*l,v=s.x,T=s.y,_=s.z;return i[0]=(1-(m+f))*v,i[1]=(d+b)*v,i[2]=(p-x)*v,i[3]=0,i[4]=(d-b)*T,i[5]=(1-(c+f))*T,i[6]=(g+y)*T,i[7]=0,i[8]=(p+x)*_,i[9]=(g-y)*_,i[10]=(1-(c+m))*_,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;let r=ir.set(i[0],i[1],i[2]).length();const n=ir.set(i[4],i[5],i[6]).length(),o=ir.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],rr.copy(this);const a=1/r,h=1/n,u=1/o;return rr.elements[0]*=a,rr.elements[1]*=a,rr.elements[2]*=a,rr.elements[4]*=h,rr.elements[5]*=h,rr.elements[6]*=h,rr.elements[8]*=u,rr.elements[9]*=u,rr.elements[10]*=u,t.setFromRotationMatrix(rr),s.x=r,s.y=n,s.z=o,this}makePerspective(e,t,s,i,r,n,o=2e3){const a=this.elements,h=2*r/(t-e),u=2*r/(s-i),l=(t+e)/(t-e),c=(s+i)/(s-i);let d,p;if(o===Us)d=-(n+r)/(n-r),p=-2*n*r/(n-r);else{if(o!==Os)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-n/(n-r),p=-n*r/(n-r)}return a[0]=h,a[4]=0,a[8]=l,a[12]=0,a[1]=0,a[5]=u,a[9]=c,a[13]=0,a[2]=0,a[6]=0,a[10]=d,a[14]=p,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(e,t,s,i,r,n,o=2e3){const a=this.elements,h=1/(t-e),u=1/(s-i),l=1/(n-r),c=(t+e)*h,d=(s+i)*u;let p,m;if(o===Us)p=(n+r)*l,m=-2*l;else{if(o!==Os)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);p=r*l,m=-1*l}return a[0]=2*h,a[4]=0,a[8]=0,a[12]=-c,a[1]=0,a[5]=2*u,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=m,a[14]=-p,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<16;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const ir=new Ai,rr=new sr,nr=new Ai(0,0,0),or=new Ai(1,1,1),ar=new Ai,hr=new Ai,ur=new Ai,lr=new sr,cr=new Mi;class dr{constructor(e=0,t=0,s=0,i=dr.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,r=i[0],n=i[4],o=i[8],a=i[1],h=i[5],u=i[9],l=i[2],c=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Ws(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(c,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Ws(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,h)):(this._y=Math.atan2(-l,r),this._z=0);break;case"ZXY":this._x=Math.asin(Ws(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(-l,d),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(a,r));break;case"ZYX":this._y=Math.asin(-Ws(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(a,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(Ws(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,h),this._y=Math.atan2(-l,r)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-Ws(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,h),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-u,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return lr.makeRotationFromQuaternion(e),this.setFromRotationMatrix(lr,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return cr.setFromEuler(this),this.setFromQuaternion(cr,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}dr.DEFAULT_ORDER="XYZ";class pr{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const s=t.shapes;if(Array.isArray(s))for(let t=0,i=s.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(s.geometries=t),i.length>0&&(s.materials=i),r.length>0&&(s.textures=r),o.length>0&&(s.images=o),a.length>0&&(s.shapes=a),h.length>0&&(s.skeletons=h),u.length>0&&(s.animations=u),l.length>0&&(s.nodes=l)}return s.object=i,s;function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,s,i,r){Er.subVectors(i,t),Br.subVectors(s,t),Ir.subVectors(e,t);const n=Er.dot(Er),o=Er.dot(Br),a=Er.dot(Ir),h=Br.dot(Br),u=Br.dot(Ir),l=n*h-o*o;if(0===l)return r.set(0,0,0),null;const c=1/l,d=(h*a-o*u)*c,p=(n*u-o*a)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,Pr)&&(Pr.x>=0&&Pr.y>=0&&Pr.x+Pr.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,Pr)?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(r,Pr.x),a.addScaledVector(n,Pr.y),a.addScaledVector(o,Pr.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return Dr.setScalar(0),kr.setScalar(0),Gr.setScalar(0),Dr.fromBufferAttribute(e,t),kr.fromBufferAttribute(e,s),Gr.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Dr,r.x),n.addScaledVector(kr,r.y),n.addScaledVector(Gr,r.z),n}static isFrontFacing(e,t,s,i){return Er.subVectors(s,t),Br.subVectors(e,t),Er.cross(Br).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Er.subVectors(this.c,this.b),Br.subVectors(this.a,this.b),.5*Er.cross(Br).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Wr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Wr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Wr.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Wr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Wr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,r=this.c;let n,o;Fr.subVectors(i,s),Ur.subVectors(r,s),zr.subVectors(e,s);const a=Fr.dot(zr),h=Ur.dot(zr);if(a<=0&&h<=0)return t.copy(s);Lr.subVectors(e,i);const u=Fr.dot(Lr),l=Ur.dot(Lr);if(u>=0&&l<=u)return t.copy(i);const c=a*l-u*h;if(c<=0&&a>=0&&u<=0)return n=a/(a-u),t.copy(s).addScaledVector(Fr,n);Vr.subVectors(e,r);const d=Fr.dot(Vr),p=Ur.dot(Vr);if(p>=0&&d<=p)return t.copy(r);const m=d*h-a*p;if(m<=0&&h>=0&&p<=0)return o=h/(h-p),t.copy(s).addScaledVector(Ur,o);const g=u*p-d*l;if(g<=0&&l-u>=0&&d-p>=0)return Or.subVectors(r,i),o=(l-u)/(l-u+(d-p)),t.copy(i).addScaledVector(Or,o);const f=1/(g+m+c);return n=m*f,o=c*f,t.copy(s).addScaledVector(Fr,n).addScaledVector(Ur,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const jr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Hr={h:0,s:0,l:0},qr={h:0,s:0,l:0};function $r(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class Xr{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Zt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,ii.toWorkingColorSpace(this,t),this}setRGB(e,t,s,i=ii.workingColorSpace){return this.r=e,this.g=t,this.b=s,ii.toWorkingColorSpace(this,i),this}setHSL(e,t,s,i=ii.workingColorSpace){if(e=js(e,1),t=Ws(t,0,1),s=Ws(s,0,1),0===t)this.r=this.g=this.b=s;else{const i=s<=.5?s*(1+t):s+t-s*t,r=2*s-i;this.r=$r(r,i,e+1/3),this.g=$r(r,i,e),this.b=$r(r,i,e-1/3)}return ii.toWorkingColorSpace(this,i),this}setStyle(e,t=Zt){function s(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],o=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],r=s.length;if(3===r)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Zt){const s=jr[e.toLowerCase()];return void 0!==s?this.setHex(s,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=ri(e.r),this.g=ri(e.g),this.b=ri(e.b),this}copyLinearToSRGB(e){return this.r=ni(e.r),this.g=ni(e.g),this.b=ni(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Zt){return ii.fromWorkingColorSpace(Yr.copy(this),e),65536*Math.round(Ws(255*Yr.r,0,255))+256*Math.round(Ws(255*Yr.g,0,255))+Math.round(Ws(255*Yr.b,0,255))}getHexString(e=Zt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ii.workingColorSpace){ii.fromWorkingColorSpace(Yr.copy(this),t);const s=Yr.r,i=Yr.g,r=Yr.b,n=Math.max(s,i,r),o=Math.min(s,i,r);let a,h;const u=(o+n)/2;if(o===n)a=0,h=0;else{const e=n-o;switch(h=u<=.5?e/(n+o):e/(2-n-o),n){case s:a=(i-r)/e+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const s=e[t];if(void 0===s){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s:console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const s={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),void 0!==this.roughness&&(s.roughness=this.roughness),void 0!==this.metalness&&(s.metalness=this.metalness),void 0!==this.sheen&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(s.shininess=this.shininess),void 0!==this.clearcoat&&(s.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(s.dispersion=this.dispersion),void 0!==this.iridescence&&(s.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(s.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(s.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(s.combine=this.combine)),void 0!==this.envMapRotation&&(s.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(s.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(s.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(s.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(s.size=this.size),null!==this.shadowSide&&(s.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(s.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(s.blending=this.blending),this.side!==c&&(s.side=this.side),!0===this.vertexColors&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),!0===this.transparent&&(s.transparent=!0),this.blendSrc!==R&&(s.blendSrc=this.blendSrc),this.blendDst!==E&&(s.blendDst=this.blendDst),this.blendEquation!==v&&(s.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(s.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(s.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(s.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(s.depthFunc=this.depthFunc),!1===this.depthTest&&(s.depthTest=this.depthTest),!1===this.depthWrite&&(s.depthWrite=this.depthWrite),!1===this.colorWrite&&(s.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==gs&&(s.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(s.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ts&&(s.stencilFail=this.stencilFail),this.stencilZFail!==ts&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==ts&&(s.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(s.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(s.rotation=this.rotation),!0===this.polygonOffset&&(s.polygonOffset=!0),0!==this.polygonOffsetFactor&&(s.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(s.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(s.linewidth=this.linewidth),void 0!==this.dashSize&&(s.dashSize=this.dashSize),void 0!==this.gapSize&&(s.gapSize=this.gapSize),void 0!==this.scale&&(s.scale=this.scale),!0===this.dithering&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),!0===this.alphaHash&&(s.alphaHash=!0),!0===this.alphaToCoverage&&(s.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(s.premultipliedAlpha=!0),!0===this.forceSinglePass&&(s.forceSinglePass=!0),!0===this.wireframe&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(s.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(s.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(s.flatShading=!0),!1===this.visible&&(s.visible=!1),!1===this.toneMapped&&(s.toneMapped=!1),!1===this.fog&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(s.textures=t),r.length>0&&(s.images=r)}return s}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let s=null;if(null!==t){const e=t.length;s=new Array(e);for(let i=0;i!==e;++i)s[i]=t[i].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Kr extends Jr{static get type(){return"MeshBasicMaterial"}constructor(e){super(),this.isMeshBasicMaterial=!0,this.color=new Xr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Qr=en();function en(){const e=new ArrayBuffer(4),t=new Float32Array(e),s=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const n=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,s=0;for(;0==(8388608&t);)t<<=1,s-=8388608;t&=-8388609,s+=947912704,n[e]=t|s}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(a[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:o,offsetTable:a}}function tn(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Ws(e,-65504,65504),Qr.floatView[0]=e;const t=Qr.uint32View[0],s=t>>23&511;return Qr.baseTable[s]+((8388607&t)>>Qr.shiftTable[s])}function sn(e){const t=e>>10;return Qr.uint32View[0]=Qr.mantissaTable[Qr.offsetTable[t]+(1023&e)]+Qr.exponentTable[t],Qr.floatView[0]}const rn={toHalfFloat:tn,fromHalfFloat:sn},nn=new Ai,on=new Ys;class an{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Ss,this.updateRanges=[],this.gpuType=Ie,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,r=this.itemSize;i=0;--t)if(e[t]>=65535)return!0;return!1}(e)?mn:dn)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(void 0!==s){const t=(new Zs).getNormalMatrix(e);s.applyNormalMatrix(t),s.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return xn.makeRotationFromQuaternion(e),this.applyMatrix4(xn),this}rotateX(e){return xn.makeRotationX(e),this.applyMatrix4(xn),this}rotateY(e){return xn.makeRotationY(e),this.applyMatrix4(xn),this}rotateZ(e){return xn.makeRotationZ(e),this.applyMatrix4(xn),this}translate(e,t,s){return xn.makeTranslation(e,t,s),this.applyMatrix4(xn),this}scale(e,t,s){return xn.makeScale(e,t,s),this.applyMatrix4(xn),this}lookAt(e){return bn.lookAt(e),bn.updateMatrix(),this.applyMatrix4(bn.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(vn).negate(),this.translate(vn.x,vn.y,vn.z),this}setFromPoints(e){const t=[];for(let s=0,i=e.length;s0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const s in t)void 0!==t[s]&&(e[s]=t[s]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const t in s){const i=s[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const s=this.morphAttributes[t],n=[];for(let t=0,i=s.length;t0&&(i[t]=n,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(e.data.groups=JSON.parse(JSON.stringify(n)));const o=this.boundingSphere;return null!==o&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const s=e.index;null!==s&&this.setIndex(s.clone(t));const i=e.attributes;for(const e in i){const s=i[e];this.setAttribute(e,s.clone(t))}const r=e.morphAttributes;for(const e in r){const s=[],i=r[e];for(let e=0,r=i.length;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;e(e.far-e.near)**2)return}Mn.copy(r).invert(),An.copy(e.ray).applyMatrix4(Mn),null!==s.boundingBox&&!1===An.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,An)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,o=r.index,a=r.attributes.position,h=r.attributes.uv,u=r.attributes.uv1,l=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==o)if(Array.isArray(n))for(let r=0,a=c.length;rs.far?null:{distance:u,point:Un.clone(),object:e}}(e,t,s,i,Rn,En,Bn,Fn);if(l){const e=new Ai;Wr.getBarycoord(Fn,Rn,En,Bn,e),r&&(l.uv=Wr.getInterpolatedAttribute(r,a,h,u,e,new Ys)),n&&(l.uv1=Wr.getInterpolatedAttribute(n,a,h,u,e,new Ys)),o&&(l.normal=Wr.getInterpolatedAttribute(o,a,h,u,e,new Ai),l.normal.dot(i.direction)>0&&l.normal.multiplyScalar(-1));const t={a:a,b:h,c:u,normal:new Ai,materialIndex:0};Wr.getNormal(Rn,En,Bn,t.normal),l.face=t,l.barycoord=e}return l}class Ln extends Sn{constructor(e=1,t=1,s=1,i=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:r,depthSegments:n};const o=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const a=[],h=[],u=[],l=[];let c=0,d=0;function p(e,t,s,i,r,n,p,m,g,f,y){const x=n/g,b=p/f,v=n/2,T=p/2,_=m/2,w=g+1,S=f+1;let M=0,A=0;const N=new Ai;for(let n=0;n0?1:-1,u.push(N.x,N.y,N.z),l.push(a/g),l.push(1-n/f),M+=1}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const e in this.extensions)!0===this.extensions[e]&&(s[e]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class kn extends Rr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new sr,this.projectionMatrix=new sr,this.projectionMatrixInverse=new sr,this.coordinateSystem=Us}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Gn=new Ai,Wn=new Ys,jn=new Ys;class Hn extends kn{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*ks*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Ds*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*ks*Math.atan(Math.tan(.5*Ds*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,s){Gn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Gn.x,Gn.y).multiplyScalar(-e/Gn.z),Gn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Gn.x,Gn.y).multiplyScalar(-e/Gn.z)}getViewSize(e,t){return this.getViewBounds(e,Wn,jn),t.subVectors(jn,Wn)}setViewOffset(e,t,s,i,r,n){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*Ds*this.fov)/this.zoom,s=2*t,i=this.aspect*s,r=-.5*i;const n=this.view;if(null!==this.view&&this.view.enabled){const e=n.fullWidth,o=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/o,i*=n.width/e,s*=n.height/o}const o=this.filmOffset;0!==o&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-s,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const qn=-90;class $n extends Rr{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Hn(qn,1,e,t);i.layers=this.layers,this.add(i);const r=new Hn(qn,1,e,t);r.layers=this.layers,this.add(r);const n=new Hn(qn,1,e,t);n.layers=this.layers,this.add(n);const o=new Hn(qn,1,e,t);o.layers=this.layers,this.add(o);const a=new Hn(qn,1,e,t);a.layers=this.layers,this.add(a);const h=new Hn(qn,1,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,o,a]=t;for(const e of t)this.remove(e);if(e===Us)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else{if(e!==Os)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,n,o,a,h,u]=this.children,l=e.getRenderTarget(),c=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1,e.setRenderTarget(s,0,i),e.render(t,r),e.setRenderTarget(s,1,i),e.render(t,n),e.setRenderTarget(s,2,i),e.render(t,o),e.setRenderTarget(s,3,i),e.render(t,a),e.setRenderTarget(s,4,i),e.render(t,h),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,u),e.setRenderTarget(l,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Xn extends yi{constructor(e,t,s,i,r,n,o,a,h,u){super(e=void 0!==e?e:[],t=void 0!==t?t:he,s,i,r,n,o,a,h,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Yn extends vi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Xn(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:Te}fromEquirectangularTexture(e,t){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 s={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Ln(5,5,5),r=new Dn({name:"CubemapFromEquirect",uniforms:Vn(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:d,blending:m});r.uniforms.tEquirect.value=t;const n=new On(i,r),o=t.minFilter;t.minFilter===Se&&(t.minFilter=Te);return new $n(1,10,this).update(e,n),t.minFilter=o,n.geometry.dispose(),n.material.dispose(),this}clear(e,t,s,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}class Zn{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new Xr(e),this.density=t}clone(){return new Zn(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Jn{constructor(e,t=1,s=1e3){this.isFog=!0,this.name="",this.color=new Xr(e),this.near=t,this.far=s}clone(){return new Jn(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Kn extends Rr{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new dr,this.environmentIntensity=1,this.environmentRotation=new dr,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Qn{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Ss,this.updateRanges=[],this.version=0,this.uuid=Gs()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,s){e*=this.stride,s*=t.stride;for(let i=0,r=this.stride;ie.far||t.push({distance:a,point:ro.clone(),uv:Wr.getInterpolation(ro,lo,co,po,mo,go,fo,new Ys),face:null,object:this})}copy(e,t){return super.copy(e,t),void 0!==e.center&&this.center.copy(e.center),this.material=e.material,this}}function xo(e,t,s,i,r,n){ao.subVectors(e,s).addScalar(.5).multiply(i),void 0!==r?(ho.x=n*ao.x-r*ao.y,ho.y=r*ao.x+n*ao.y):ho.copy(ao),e.copy(t),e.x+=ho.x,e.y+=ho.y,e.applyMatrix4(uo)}const bo=new Ai,vo=new Ai;class To extends Rr{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let e=0,s=t.length;e0){let s,i;for(s=1,i=t.length;s0){bo.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(bo);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){bo.setFromMatrixPosition(e.matrixWorld),vo.setFromMatrixPosition(this.matrixWorld);const s=bo.distanceTo(vo)/e.zoom;let i,r;for(t[0].object.visible=!0,i=1,r=t.length;i=e))break;t[i-1].object.visible=!1,t[i].object.visible=!0}for(this._currentLevel=i-1;i1?null:t.copy(e.start).addScaledVector(s,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const s=t||Xo.getNormalMatrix(e),i=this.coplanarPoint(qo).applyMatrix4(e),r=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const Zo=new $i,Jo=new Ai;class Ko{constructor(e=new Yo,t=new Yo,s=new Yo,i=new Yo,r=new Yo,n=new Yo){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(s),o[3].copy(i),o[4].copy(r),o[5].copy(n),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=2e3){const s=this.planes,i=e.elements,r=i[0],n=i[1],o=i[2],a=i[3],h=i[4],u=i[5],l=i[6],c=i[7],d=i[8],p=i[9],m=i[10],g=i[11],f=i[12],y=i[13],x=i[14],b=i[15];if(s[0].setComponents(a-r,c-h,g-d,b-f).normalize(),s[1].setComponents(a+r,c+h,g+d,b+f).normalize(),s[2].setComponents(a+n,c+u,g+p,b+y).normalize(),s[3].setComponents(a-n,c-u,g-p,b-y).normalize(),s[4].setComponents(a-o,c-l,g-m,b-x).normalize(),t===Us)s[5].setComponents(a+o,c+l,g+m,b+x).normalize();else{if(t!==Os)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);s[5].setComponents(o,l,m,x).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Zo.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Zo.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Zo)}intersectsSprite(e){return Zo.center.set(0,0,0),Zo.radius=.7071067811865476,Zo.applyMatrix4(e.matrixWorld),this.intersectsSphere(Zo)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(s)0?e.max.x:e.min.x,Jo.y=i.normal.y>0?e.max.y:e.min.y,Jo.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Jo)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function Qo(e,t){return e-t}function ea(e,t){return e.z-t.z}function ta(e,t){return t.z-e.z}class sa{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t,s){const i=this.pool,r=this.list;this.index>=i.length&&i.push({start:-1,count:-1,z:-1,index:-1});const n=i[this.index];r.push(n),this.index++,n.start=e.start,n.count=e.count,n.z=t,n.index=s}reset(){this.list.length=0,this.index=0}}const ia=new sr,ra=new sr,na=new sr,oa=new Xr(1,1,1),aa=new sr,ha=new Ko,ua=new Ri,la=new $i,ca=new Ai,da=new Ai,pa=new Ai,ma=new sa,ga=new On,fa=[];function ya(e,t,s=0){const i=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){const r=e.count;for(let n=0;n65535?new Uint32Array(i):new Uint16Array(i);t.setIndex(new an(e,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(Boolean(e.getIndex())!==Boolean(t.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const s in t.attributes){if(!e.hasAttribute(s))throw new Error(`BatchedMesh: Added geometry missing "${s}". All geometries must have consistent attributes.`);const i=e.getAttribute(s),r=t.getAttribute(s);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ri);const e=this.boundingBox,t=this._drawInfo;e.makeEmpty();for(let s=0,i=t.length;s=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("BatchedMesh: Maximum item count reached.");const t={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(Qo),s=this._availableInstanceIds.shift(),this._drawInfo[s]=t):(s=this._drawInfo.length,this._drawInfo.push(t));const i=this._matricesTexture,r=i.image.data;na.toArray(r,16*s),i.needsUpdate=!0;const n=this._colorsTexture;return n&&(oa.toArray(n.image.data,4*s),n.needsUpdate=!0),s}addGeometry(e,t=-1,s=-1){this._initializeGeometry(e),this._validateGeometry(e);const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let r=null;const n=this._reservedRanges,o=this._drawRanges,a=this._bounds;0!==this._geometryCount&&(r=n[n.length-1]),i.vertexCount=-1===t?e.getAttribute("position").count:t,i.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const h=e.getIndex(),u=null!==h;if(u&&(i.indexCount=-1===s?h.count:s,i.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==i.indexStart&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const l={start:u?i.indexStart:i.vertexStart,count:-1,active:!0},c={boxInitialized:!1,box:new Ri,sphereInitialized:!1,sphere:new $i};let d;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Qo),d=this._availableGeometryIds.shift(),n[d]=i,o[d]=l,a[d]=c):(d=this._geometryCount,this._geometryCount++,n.push(i),o.push(l),a.push(c)),this.setGeometryAt(d,e),d}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const s=this.geometry,i=null!==s.getIndex(),r=s.getIndex(),n=t.getIndex(),o=this._reservedRanges[e];if(i&&n.count>o.indexCount||t.attributes.position.count>o.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const a=o.vertexStart,h=o.vertexCount;for(const e in s.attributes){const i=t.getAttribute(e),r=s.getAttribute(e);ya(i,r,a);const n=i.itemSize;for(let e=i.count,t=h;e=t.length||!1===t[e].active)return this;const s=this._drawInfo;for(let t=0,i=s.length;t=t.length||!1===t[e].active||(t[e].active=!1,this._availableInstanceIds.push(e),this._visibilityChanged=!0),this}optimize(){let e=0,t=0;const s=this._drawRanges,i=this._reservedRanges,r=this.geometry;for(let n=0,o=s.length;n=this._geometryCount)return null;const s=this._bounds[e],i=s.box,r=this.geometry;if(!1===s.boxInitialized){i.makeEmpty();const t=r.index,n=r.attributes.position,o=this._drawRanges[e];for(let e=o.start,s=o.start+o.count;e=this._geometryCount)return null;const s=this._bounds[e],i=s.sphere,r=this.geometry;if(!1===s.sphereInitialized){i.makeEmpty(),this.getBoundingBoxAt(e,ua),ua.getCenter(i.center);const t=r.index,n=r.attributes.position,o=this._drawRanges[e];let a=0;for(let e=o.start,s=o.start+o.count;e=s.length||!1===s[e].active||(t.toArray(r,16*e),i.needsUpdate=!0),this}getMatrixAt(e,t){const s=this._drawInfo,i=this._matricesTexture.image.data;return e>=s.length||!1===s[e].active?null:t.fromArray(i,16*e)}setColorAt(e,t){null===this._colorsTexture&&this._initColorsTexture();const s=this._colorsTexture,i=this._colorsTexture.image.data,r=this._drawInfo;return e>=r.length||!1===r[e].active||(t.toArray(i,4*e),s.needsUpdate=!0),this}getColorAt(e,t){const s=this._colorsTexture.image.data,i=this._drawInfo;return e>=i.length||!1===i[e].active?null:t.fromArray(s,4*e)}setVisibleAt(e,t){const s=this._drawInfo;return e>=s.length||!1===s[e].active||s[e].visible===t||(s[e].visible=t,this._visibilityChanged=!0),this}getVisibleAt(e){const t=this._drawInfo;return!(e>=t.length||!1===t[e].active)&&t[e].visible}setGeometryIdAt(e,t){const s=this._drawInfo;return e>=s.length||!1===s[e].active||t<0||t>=this._geometryCount?null:(s[e].geometryIndex=t,this)}getGeometryIdAt(e){const t=this._drawInfo;return e>=t.length||!1===t[e].active?-1:t[e].geometryIndex}getGeometryRangeAt(e,t={}){if(e<0||e>=this._geometryCount)return null;const s=this._drawRanges[e];return t.start=s.start,t.count=s.count,t}setInstanceCount(e){const t=this._availableInstanceIds,s=this._drawInfo;for(t.sort(Qo);t[t.length-1]===s.length;)s.pop(),t.pop();if(ethis._drawRanges[t].active)),i=Math.max(...s.map((e=>e.vertexStart+e.vertexCount)));if(i>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index){const e=Math.max(...s.map((e=>e.indexStart+e.indexCount)));if(e>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`)}const r=this.geometry;r.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized=!1,this.geometry=new Sn,this._initializeGeometry(r);const n=this.geometry;r.index&&xa(r.index.array,n.index.array);for(const e in r.attributes)xa(r.attributes[e].array,n.attributes[e].array)}raycast(e,t){const s=this._drawInfo,i=this._drawRanges,r=this.matrixWorld,n=this.geometry;ga.material=this.material,ga.geometry.index=n.index,ga.geometry.attributes=n.attributes,null===ga.geometry.boundingBox&&(ga.geometry.boundingBox=new Ri),null===ga.geometry.boundingSphere&&(ga.geometry.boundingSphere=new $i);for(let n=0,o=s.length;n({...e}))),this._reservedRanges=e._reservedRanges.map((e=>({...e}))),this._drawInfo=e._drawInfo.map((e=>({...e}))),this._bounds=e._bounds.map((e=>({boxInitialized:e.boxInitialized,box:e.box.clone(),sphereInitialized:e.sphereInitialized,sphere:e.sphere.clone()}))),this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(e,t,s,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const n=i.getIndex(),o=null===n?1:n.array.BYTES_PER_ELEMENT,a=this._drawInfo,h=this._multiDrawStarts,u=this._multiDrawCounts,l=this._drawRanges,c=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data;c&&(aa.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse).multiply(this.matrixWorld),ha.setFromProjectionMatrix(aa,e.coordinateSystem));let m=0;if(this.sortObjects){ra.copy(this.matrixWorld).invert(),ca.setFromMatrixPosition(s.matrixWorld).applyMatrix4(ra),da.set(0,0,-1).transformDirection(s.matrixWorld).transformDirection(ra);for(let e=0,t=a.length;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;ei)return;Aa.applyMatrix4(e.matrixWorld);const a=t.ray.origin.distanceTo(Aa);return at.far?void 0:{distance:a,point:Na.clone().applyMatrix4(e.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:e}}const Ea=new Ai,Ba=new Ai;class Ia extends Ca{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,s=[];for(let e=0,i=t.count;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;er.far)return;n.push({distance:h,distanceToRay:Math.sqrt(a),point:s,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}class ka extends Rr{constructor(){super(),this.isGroup=!0,this.type="Group"}}class Ga extends yi{constructor(e,t,s,i,r,n,o,a,h){super(e,t,s,i,r,n,o,a,h),this.isVideoTexture=!0,this.minFilter=void 0!==n?n:Te,this.magFilter=void 0!==r?r:Te,this.generateMipmaps=!1;const u=this;"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback((function t(){u.needsUpdate=!0,e.requestVideoFrameCallback(t)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;!1==="requestVideoFrameCallback"in e&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class Wa extends yi{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=fe,this.minFilter=fe,this.generateMipmaps=!1,this.needsUpdate=!0}}class ja extends yi{constructor(e,t,s,i,r,n,o,a,h,u,l,c){super(null,n,o,a,h,u,i,r,l,c),this.isCompressedTexture=!0,this.image={width:t,height:s},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class Ha extends ja{constructor(e,t,s,i,r,n){super(e,t,s,r,n),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=me,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class qa extends ja{constructor(e,t,s){super(void 0,e[0].width,e[0].height,t,s,he),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class $a extends yi{constructor(e,t,s,i,r,n,o,a,h){super(e,t,s,i,r,n,o,a,h),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Xa extends yi{constructor(e,t,s,i,r,n,o,a,h,u=1026){if(u!==We&&u!==je)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===s&&u===We&&(s=Be),void 0===s&&u===je&&(s=Oe),super(null,i,r,n,o,a,u,s,h),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==o?o:fe,this.minFilter=void 0!==a?a:fe,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class Ya{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){const s=this.getUtoTmapping(e);return this.getPoint(s,t)}getPoints(e=5){const t=[];for(let s=0;s<=e;s++)t.push(this.getPoint(s/e));return t}getSpacedPoints(e=5){const t=[];for(let s=0;s<=e;s++)t.push(this.getPointAt(s/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let s,i=this.getPoint(0),r=0;t.push(0);for(let n=1;n<=e;n++)s=this.getPoint(n/e),r+=s.distanceTo(i),t.push(r),i=s;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){const s=this.getLengths();let i=0;const r=s.length;let n;n=t||e*s[r-1];let o,a=0,h=r-1;for(;a<=h;)if(i=Math.floor(a+(h-a)/2),o=s[i]-n,o<0)a=i+1;else{if(!(o>0)){h=i;break}h=i-1}if(i=h,s[i]===n)return i/(r-1);const u=s[i];return(i+(n-u)/(s[i+1]-u))/(r-1)}getTangent(e,t){const s=1e-4;let i=e-s,r=e+s;i<0&&(i=0),r>1&&(r=1);const n=this.getPoint(i),o=this.getPoint(r),a=t||(n.isVector2?new Ys:new Ai);return a.copy(o).sub(n).normalize(),a}getTangentAt(e,t){const s=this.getUtoTmapping(e);return this.getTangent(s,t)}computeFrenetFrames(e,t){const s=new Ai,i=[],r=[],n=[],o=new Ai,a=new sr;for(let t=0;t<=e;t++){const s=t/e;i[t]=this.getTangentAt(s,new Ai)}r[0]=new Ai,n[0]=new Ai;let h=Number.MAX_VALUE;const u=Math.abs(i[0].x),l=Math.abs(i[0].y),c=Math.abs(i[0].z);u<=h&&(h=u,s.set(1,0,0)),l<=h&&(h=l,s.set(0,1,0)),c<=h&&s.set(0,0,1),o.crossVectors(i[0],s).normalize(),r[0].crossVectors(i[0],o),n[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),n[t]=n[t-1].clone(),o.crossVectors(i[t-1],i[t]),o.length()>Number.EPSILON){o.normalize();const e=Math.acos(Ws(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(a.makeRotationAxis(o,e))}n[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(Ws(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(o.crossVectors(r[0],r[e]))>0&&(t=-t);for(let s=1;s<=e;s++)r[s].applyMatrix4(a.makeRotationAxis(i[s],t*s)),n[s].crossVectors(i[s],r[s])}return{tangents:i,normals:r,binormals:n}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Za extends Ya{constructor(e=0,t=0,s=1,i=1,r=0,n=2*Math.PI,o=!1,a=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=s,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=n,this.aClockwise=o,this.aRotation=a}getPoint(e,t=new Ys){const s=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const n=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(h)/r)+1)*r:0===u&&h===r-1&&(h=r-2,u=1),this.closed||h>0?o=i[(h-1)%r]:(Qa.subVectors(i[0],i[1]).add(i[0]),o=Qa);const l=i[h%r],c=i[(h+1)%r];if(this.closed||h+2i.length-2?i.length-1:n+1],l=i[n>i.length-3?i.length-1:n+2];return s.set(rh(o,a.x,h.x,u.x,l.x),rh(o,a.y,h.y,u.y,l.y)),s}copy(e){super.copy(e),this.points=[];for(let t=0,s=e.points.length;t=s){const e=i[r]-s,n=this.curves[r],o=n.getLength(),a=0===o?0:1-e/o;return n.getPointAt(a,t)}r++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let s=0,i=this.curves.length;s1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,s=e.curves.length;t0){const e=h.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y)}this.curves.push(h);const u=h.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class yh extends Sn{constructor(e=[new Ys(0,-.5),new Ys(.5,0),new Ys(0,.5)],t=12,s=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:s,phiLength:i},t=Math.floor(t),i=Ws(i,0,2*Math.PI);const r=[],n=[],o=[],a=[],h=[],u=1/t,l=new Ai,c=new Ys,d=new Ai,p=new Ai,m=new Ai;let g=0,f=0;for(let t=0;t<=e.length-1;t++)switch(t){case 0:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,d.x=1*f,d.y=-g,d.z=0*f,m.copy(d),d.normalize(),a.push(d.x,d.y,d.z);break;case e.length-1:a.push(m.x,m.y,m.z);break;default:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,d.x=1*f,d.y=-g,d.z=0*f,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),a.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=t;r++){const d=s+r*u*i,p=Math.sin(d),m=Math.cos(d);for(let s=0;s<=e.length-1;s++){l.x=e[s].x*p,l.y=e[s].y,l.z=e[s].x*m,n.push(l.x,l.y,l.z),c.x=r/t,c.y=s/(e.length-1),o.push(c.x,c.y);const i=a[3*s+0]*p,u=a[3*s+1],d=a[3*s+0]*m;h.push(i,u,d)}}for(let s=0;s0&&(u.push(r,n,a),x+=3),t>0&&(u.push(n,o,a),x+=3)}h.addGroup(f,x,0),f+=x}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new fn(l,3)),this.setAttribute("normal",new fn(c,3)),this.setAttribute("uv",new fn(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vh(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Th extends vh{constructor(e=1,t=1,s=32,i=1,r=!1,n=0,o=2*Math.PI){super(0,e,t,s,i,r,n,o),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:s,heightSegments:i,openEnded:r,thetaStart:n,thetaLength:o}}static fromJSON(e){return new Th(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class _h extends Sn{constructor(e=[],t=[],s=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:s,detail:i};const r=[],n=[];function o(e,t,s,i){const r=i+1,n=[];for(let i=0;i<=r;i++){n[i]=[];const o=e.clone().lerp(s,i/r),a=t.clone().lerp(s,i/r),h=r-i;for(let e=0;e<=h;e++)n[i][e]=0===e&&i===r?o:o.clone().lerp(a,e/h)}for(let e=0;e.9&&o<.1&&(t<.2&&(n[e+0]+=1),s<.2&&(n[e+2]+=1),i<.2&&(n[e+4]+=1))}}()}(),this.setAttribute("position",new fn(r,3)),this.setAttribute("normal",new fn(r.slice(),3)),this.setAttribute("uv",new fn(n,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new _h(e.vertices,e.indices,e.radius,e.details)}}class wh extends _h{constructor(e=1,t=0){const s=(1+Math.sqrt(5))/2,i=1/s;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-s,0,-i,s,0,i,-s,0,i,s,-i,-s,0,-i,s,0,i,-s,0,i,s,0,-s,0,-i,s,0,-i,-s,0,i,s,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new wh(e.radius,e.detail)}}const Sh=new Ai,Mh=new Ai,Ah=new Ai,Nh=new Wr;class Ch extends Sn{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},null!==e){const s=4,i=Math.pow(10,s),r=Math.cos(Ds*t),n=e.getIndex(),o=e.getAttribute("position"),a=n?n.count:o.count,h=[0,0,0],u=["a","b","c"],l=new Array(3),c={},d=[];for(let e=0;e80*s){a=u=e[0],h=l=e[1];for(let t=s;tu&&(u=c),d>l&&(l=d);p=Math.max(u-a,l-h),p=0!==p?32767/p:0}return Ph(n,o,s,a,h,p,0),o};function Bh(e,t,s,i,r){let n,o;if(r===function(e,t,s,i){let r=0;for(let n=t,o=s-i;n0)for(n=t;n=t;n-=i)o=Kh(n,e[n],e[n+1],o);return o&&qh(o,o.next)&&(Qh(o),o=o.next),o}function Ih(e,t){if(!e)return e;t||(t=e);let s,i=e;do{if(s=!1,i.steiner||!qh(i,i.next)&&0!==Hh(i.prev,i,i.next))i=i.next;else{if(Qh(i),i=t=i.prev,i===i.next)break;s=!0}}while(s||i!==t);return t}function Ph(e,t,s,i,r,n,o){if(!e)return;!o&&n&&function(e,t,s,i){let r=e;do{0===r.z&&(r.z=kh(r.x,r.y,t,s,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,s,i,r,n,o,a,h,u=1;do{for(s=e,e=null,n=null,o=0;s;){for(o++,i=s,a=0,t=0;t0||h>0&&i;)0!==a&&(0===h||!i||s.z<=i.z)?(r=s,s=s.nextZ,a--):(r=i,i=i.nextZ,h--),n?n.nextZ=r:e=r,r.prevZ=n,n=r;s=i}n.nextZ=null,u*=2}while(o>1)}(r)}(e,i,r,n);let a,h,u=e;for(;e.prev!==e.next;)if(a=e.prev,h=e.next,n?Uh(e,i,r,n):Fh(e))t.push(a.i/s|0),t.push(e.i/s|0),t.push(h.i/s|0),Qh(e),e=h.next,u=h.next;else if((e=h)===u){o?1===o?Ph(e=Oh(Ih(e),t,s),t,s,i,r,n,2):2===o&&zh(e,t,s,i,r,n):Ph(Ih(e),t,s,i,r,n,1);break}}function Fh(e){const t=e.prev,s=e,i=e.next;if(Hh(t,s,i)>=0)return!1;const r=t.x,n=s.x,o=i.x,a=t.y,h=s.y,u=i.y,l=rn?r>o?r:o:n>o?n:o,p=a>h?a>u?a:u:h>u?h:u;let m=i.next;for(;m!==t;){if(m.x>=l&&m.x<=d&&m.y>=c&&m.y<=p&&Wh(r,a,n,h,o,u,m.x,m.y)&&Hh(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Uh(e,t,s,i){const r=e.prev,n=e,o=e.next;if(Hh(r,n,o)>=0)return!1;const a=r.x,h=n.x,u=o.x,l=r.y,c=n.y,d=o.y,p=ah?a>u?a:u:h>u?h:u,f=l>c?l>d?l:d:c>d?c:d,y=kh(p,m,t,s,i),x=kh(g,f,t,s,i);let b=e.prevZ,v=e.nextZ;for(;b&&b.z>=y&&v&&v.z<=x;){if(b.x>=p&&b.x<=g&&b.y>=m&&b.y<=f&&b!==r&&b!==o&&Wh(a,l,h,c,u,d,b.x,b.y)&&Hh(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==o&&Wh(a,l,h,c,u,d,v.x,v.y)&&Hh(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;b&&b.z>=y;){if(b.x>=p&&b.x<=g&&b.y>=m&&b.y<=f&&b!==r&&b!==o&&Wh(a,l,h,c,u,d,b.x,b.y)&&Hh(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=x;){if(v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==o&&Wh(a,l,h,c,u,d,v.x,v.y)&&Hh(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function Oh(e,t,s){let i=e;do{const r=i.prev,n=i.next.next;!qh(r,n)&&$h(r,i,i.next,n)&&Zh(r,n)&&Zh(n,r)&&(t.push(r.i/s|0),t.push(i.i/s|0),t.push(n.i/s|0),Qh(i),Qh(i.next),i=e=n),i=i.next}while(i!==e);return Ih(i)}function zh(e,t,s,i,r,n){let o=e;do{let e=o.next.next;for(;e!==o.prev;){if(o.i!==e.i&&jh(o,e)){let a=Jh(o,e);return o=Ih(o,o.next),a=Ih(a,a.next),Ph(o,t,s,i,r,n,0),void Ph(a,t,s,i,r,n,0)}e=e.next}o=o.next}while(o!==e)}function Lh(e,t){return e.x-t.x}function Vh(e,t){const s=function(e,t){let s,i=t,r=-1/0;const n=e.x,o=e.y;do{if(o<=i.y&&o>=i.next.y&&i.next.y!==i.y){const e=i.x+(o-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=n&&e>r&&(r=e,s=i.x=i.x&&i.x>=h&&n!==i.x&&Wh(os.x||i.x===s.x&&Dh(s,i)))&&(s=i,c=l)),i=i.next}while(i!==a);return s}(e,t);if(!s)return t;const i=Jh(s,e);return Ih(i,i.next),Ih(s,s.next)}function Dh(e,t){return Hh(e.prev,e,t.prev)<0&&Hh(t.next,e,e.next)<0}function kh(e,t,s,i,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Gh(e){let t=e,s=e;do{(t.x=(e-o)*(n-a)&&(e-o)*(i-a)>=(s-o)*(t-a)&&(s-o)*(n-a)>=(r-o)*(i-a)}function jh(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let s=e;do{if(s.i!==e.i&&s.next.i!==e.i&&s.i!==t.i&&s.next.i!==t.i&&$h(s,s.next,e,t))return!0;s=s.next}while(s!==e);return!1}(e,t)&&(Zh(e,t)&&Zh(t,e)&&function(e,t){let s=e,i=!1;const r=(e.x+t.x)/2,n=(e.y+t.y)/2;do{s.y>n!=s.next.y>n&&s.next.y!==s.y&&r<(s.next.x-s.x)*(n-s.y)/(s.next.y-s.y)+s.x&&(i=!i),s=s.next}while(s!==e);return i}(e,t)&&(Hh(e.prev,e,t.prev)||Hh(e,t.prev,t))||qh(e,t)&&Hh(e.prev,e,e.next)>0&&Hh(t.prev,t,t.next)>0)}function Hh(e,t,s){return(t.y-e.y)*(s.x-t.x)-(t.x-e.x)*(s.y-t.y)}function qh(e,t){return e.x===t.x&&e.y===t.y}function $h(e,t,s,i){const r=Yh(Hh(e,t,s)),n=Yh(Hh(e,t,i)),o=Yh(Hh(s,i,e)),a=Yh(Hh(s,i,t));return r!==n&&o!==a||(!(0!==r||!Xh(e,s,t))||(!(0!==n||!Xh(e,i,t))||(!(0!==o||!Xh(s,e,i))||!(0!==a||!Xh(s,t,i)))))}function Xh(e,t,s){return t.x<=Math.max(e.x,s.x)&&t.x>=Math.min(e.x,s.x)&&t.y<=Math.max(e.y,s.y)&&t.y>=Math.min(e.y,s.y)}function Yh(e){return e>0?1:e<0?-1:0}function Zh(e,t){return Hh(e.prev,e,e.next)<0?Hh(e,t,e.next)>=0&&Hh(e,e.prev,t)>=0:Hh(e,t,e.prev)<0||Hh(e,e.next,t)<0}function Jh(e,t){const s=new eu(e.i,e.x,e.y),i=new eu(t.i,t.x,t.y),r=e.next,n=t.prev;return e.next=t,t.prev=e,s.next=r,r.prev=s,i.next=s,s.prev=i,n.next=i,i.prev=n,i}function Kh(e,t,s,i){const r=new eu(e,t,s);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Qh(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function eu(e,t,s){this.i=e,this.x=t,this.y=s,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class tu{static area(e){const t=e.length;let s=0;for(let i=t-1,r=0;r2&&e[t-1].equals(e[0])&&e.pop()}function iu(e,t){for(let s=0;sNumber.EPSILON){const c=Math.sqrt(l),d=Math.sqrt(h*h+u*u),p=t.x-a/c,m=t.y+o/c,g=((s.x-u/d-p)*u-(s.y+h/d-m)*h)/(o*u-a*h);i=p+o*g-e.x,r=m+a*g-e.y;const f=i*i+r*r;if(f<=2)return new Ys(i,r);n=Math.sqrt(f/2)}else{let e=!1;o>Number.EPSILON?h>Number.EPSILON&&(e=!0):o<-Number.EPSILON?h<-Number.EPSILON&&(e=!0):Math.sign(a)===Math.sign(u)&&(e=!0),e?(i=-a,r=o,n=Math.sqrt(l)):(i=o,r=a,n=Math.sqrt(l/2))}return new Ys(i/n,r/n)}const B=[];for(let e=0,t=A.length,s=t-1,i=e+1;e=0;e--){const t=e/p,s=l*Math.cos(t*Math.PI/2),i=c*Math.sin(t*Math.PI/2)+d;for(let e=0,t=A.length;e=0;){const i=s;let r=s-1;r<0&&(r=e.length-1);for(let e=0,s=a+2*p;e0)&&d.push(t,r,h),(e!==s-1||a0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class wu extends Jr{static get type(){return"MeshPhongMaterial"}constructor(e){super(),this.isMeshPhongMaterial=!0,this.color=new Xr(16777215),this.specular=new Xr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Su extends Jr{static get type(){return"MeshToonMaterial"}constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.color=new Xr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class Mu extends Jr{static get type(){return"MeshNormalMaterial"}constructor(e){super(),this.isMeshNormalMaterial=!0,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Au extends Jr{static get type(){return"MeshLambertMaterial"}constructor(e){super(),this.isMeshLambertMaterial=!0,this.color=new Xr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Nu extends Jr{static get type(){return"MeshDepthMaterial"}constructor(e){super(),this.isMeshDepthMaterial=!0,this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Cu extends Jr{static get type(){return"MeshDistanceMaterial"}constructor(e){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class Ru extends Jr{static get type(){return"MeshMatcapMaterial"}constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.color=new Xr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Eu extends va{static get type(){return"LineDashedMaterial"}constructor(e){super(),this.isLineDashedMaterial=!0,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function Bu(e,t,s){return!e||!s&&e.constructor===t?e:"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e)}function Iu(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Pu(e){const t=e.length,s=new Array(t);for(let e=0;e!==t;++e)s[e]=e;return s.sort((function(t,s){return e[t]-e[s]})),s}function Fu(e,t,s){const i=e.length,r=new e.constructor(i);for(let n=0,o=0;o!==i;++n){const i=s[n]*t;for(let s=0;s!==t;++s)r[o++]=e[i+s]}return r}function Uu(e,t,s,i){let r=1,n=e[0];for(;void 0!==n&&void 0===n[i];)n=e[r++];if(void 0===n)return;let o=n[i];if(void 0!==o)if(Array.isArray(o))do{o=n[i],void 0!==o&&(t.push(n.time),s.push.apply(s,o)),n=e[r++]}while(void 0!==n);else if(void 0!==o.toArray)do{o=n[i],void 0!==o&&(t.push(n.time),o.toArray(s,s.length)),n=e[r++]}while(void 0!==n);else do{o=n[i],void 0!==o&&(t.push(n.time),s.push(o)),n=e[r++]}while(void 0!==n)}const Ou={convertArray:Bu,isTypedArray:Iu,getKeyframeOrder:Pu,sortedArray:Fu,flattenJSON:Uu,subclip:function(e,t,s,i,r=30){const n=e.clone();n.name=t;const o=[];for(let e=0;e=i)){h.push(t.times[e]);for(let s=0;sn.tracks[e].times[0]&&(a=n.tracks[e].times[0]);for(let e=0;e=i.times[c]){const e=c*h+a,t=e+h-a;d=i.values.slice(e,t)}else{const e=i.createInterpolant(),t=a,s=h-a;e.evaluate(n),d=e.resultBuffer.slice(t,s)}if("quaternion"===r){(new Mi).fromArray(d).normalize().conjugate().toArray(d)}const p=o.times.length;for(let e=0;e=r)break e;{const o=t[1];e=r)break t}n=s,s=0}}for(;s>>1;et;)--n;if(++n,0!==r||n!==i){r>=n&&(n=Math.max(n,1),r=n-1);const e=this.getValueSize();this.times=s.slice(r,n),this.values=this.values.slice(r*e,n*e)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const s=this.times,i=this.values,r=s.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let n=null;for(let t=0;t!==r;t++){const i=s[t];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,t,i),e=!1;break}if(null!==n&&n>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,t,i,n),e=!1;break}n=i}if(void 0!==i&&Iu(i))for(let t=0,s=i.length;t!==s;++t){const s=i[t];if(isNaN(s)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,t,s),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),s=this.getValueSize(),i=this.getInterpolation()===Ft,r=e.length-1;let n=1;for(let o=1;o0){e[n]=e[r];for(let e=r*s,i=n*s,o=0;o!==s;++o)t[i+o]=t[e+o];++n}return n!==e.length?(this.times=e.slice(0,n),this.values=t.slice(0,n*s)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),s=new(0,this.constructor)(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}ku.prototype.TimeBufferType=Float32Array,ku.prototype.ValueBufferType=Float32Array,ku.prototype.DefaultInterpolation=Pt;class Gu extends ku{constructor(e,t,s){super(e,t,s)}}Gu.prototype.ValueTypeName="bool",Gu.prototype.ValueBufferType=Array,Gu.prototype.DefaultInterpolation=It,Gu.prototype.InterpolantFactoryMethodLinear=void 0,Gu.prototype.InterpolantFactoryMethodSmooth=void 0;class Wu extends ku{}Wu.prototype.ValueTypeName="color";class ju extends ku{}ju.prototype.ValueTypeName="number";class Hu extends zu{constructor(e,t,s,i){super(e,t,s,i)}interpolate_(e,t,s,i){const r=this.resultBuffer,n=this.sampleValues,o=this.valueSize,a=(s-t)/(i-t);let h=e*o;for(let e=h+o;h!==e;h+=4)Mi.slerpFlat(r,0,n,h-o,n,h,a);return r}}class qu extends ku{InterpolantFactoryMethodLinear(e){return new Hu(this.times,this.values,this.getValueSize(),e)}}qu.prototype.ValueTypeName="quaternion",qu.prototype.InterpolantFactoryMethodSmooth=void 0;class $u extends ku{constructor(e,t,s){super(e,t,s)}}$u.prototype.ValueTypeName="string",$u.prototype.ValueBufferType=Array,$u.prototype.DefaultInterpolation=It,$u.prototype.InterpolantFactoryMethodLinear=void 0,$u.prototype.InterpolantFactoryMethodSmooth=void 0;class Xu extends ku{}Xu.prototype.ValueTypeName="vector";class Yu{constructor(e="",t=-1,s=[],i=2500){this.name=e,this.tracks=s,this.duration=t,this.blendMode=i,this.uuid=Gs(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],s=e.tracks,i=1/(e.fps||1);for(let e=0,r=s.length;e!==r;++e)t.push(Zu(s[e]).scale(i));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){const t=[],s=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let e=0,i=s.length;e!==i;++e)t.push(ku.toJSON(s[e]));return i}static CreateFromMorphTargetSequence(e,t,s,i){const r=t.length,n=[];for(let e=0;e1){const e=n[1];let t=i[e];t||(i[e]=t=[]),t.push(s)}}const n=[];for(const e in i)n.push(this.CreateFromMorphTargetSequence(e,i[e],t,s));return n}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const s=function(e,t,s,i,r){if(0!==s.length){const n=[],o=[];Uu(s,n,o,i),0!==n.length&&r.push(new e(t,n,o))}},i=[],r=e.name||"default",n=e.fps||30,o=e.blendMode;let a=e.length||-1;const h=e.hierarchy||[];for(let e=0;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==tl[e])return void tl[e].push({onLoad:t,onProgress:s,onError:i});tl[e]=[],tl[e].push({onLoad:t,onProgress:s,onError:i});const n=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),o=this.mimeType,a=this.responseType;fetch(n).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body||void 0===t.body.getReader)return t;const s=tl[e],i=t.body.getReader(),r=t.headers.get("X-File-Size")||t.headers.get("Content-Length"),n=r?parseInt(r):0,o=0!==n;let a=0;const h=new ReadableStream({start(e){!function t(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:o,loaded:a,total:n});for(let e=0,t=s.length;e{e.error(t)}))}()}});return new Response(h)}throw new sl(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)})).then((e=>{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,o)));case"json":return e.json();default:if(void 0===o)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(o),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Ju.add(e,t);const s=tl[e];delete tl[e];for(let e=0,i=s.length;e{const s=tl[e];if(void 0===s)throw this.manager.itemError(e),t;delete tl[e];for(let e=0,i=s.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class rl extends el{constructor(e){super(e)}load(e,t,s,i){const r=this,n=new il(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(e,(function(s){try{t(r.parse(JSON.parse(s)))}catch(t){i?i(t):console.error(t),r.manager.itemError(e)}}),s,i)}parse(e){const t=[];for(let s=0;s0:i.vertexColors=e.vertexColors),void 0!==e.uniforms)for(const t in e.uniforms){const r=e.uniforms[t];switch(i.uniforms[t]={},r.type){case"t":i.uniforms[t].value=s(r.value);break;case"c":i.uniforms[t].value=(new Xr).setHex(r.value);break;case"v2":i.uniforms[t].value=(new Ys).fromArray(r.value);break;case"v3":i.uniforms[t].value=(new Ai).fromArray(r.value);break;case"v4":i.uniforms[t].value=(new xi).fromArray(r.value);break;case"m3":i.uniforms[t].value=(new Zs).fromArray(r.value);break;case"m4":i.uniforms[t].value=(new sr).fromArray(r.value);break;default:i.uniforms[t].value=r.value}}if(void 0!==e.defines&&(i.defines=e.defines),void 0!==e.vertexShader&&(i.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(i.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(i.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)i.extensions[t]=e.extensions[t];if(void 0!==e.lights&&(i.lights=e.lights),void 0!==e.clipping&&(i.clipping=e.clipping),void 0!==e.size&&(i.size=e.size),void 0!==e.sizeAttenuation&&(i.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(i.map=s(e.map)),void 0!==e.matcap&&(i.matcap=s(e.matcap)),void 0!==e.alphaMap&&(i.alphaMap=s(e.alphaMap)),void 0!==e.bumpMap&&(i.bumpMap=s(e.bumpMap)),void 0!==e.bumpScale&&(i.bumpScale=e.bumpScale),void 0!==e.normalMap&&(i.normalMap=s(e.normalMap)),void 0!==e.normalMapType&&(i.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),i.normalScale=(new Ys).fromArray(t)}return void 0!==e.displacementMap&&(i.displacementMap=s(e.displacementMap)),void 0!==e.displacementScale&&(i.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(i.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(i.roughnessMap=s(e.roughnessMap)),void 0!==e.metalnessMap&&(i.metalnessMap=s(e.metalnessMap)),void 0!==e.emissiveMap&&(i.emissiveMap=s(e.emissiveMap)),void 0!==e.emissiveIntensity&&(i.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(i.specularMap=s(e.specularMap)),void 0!==e.specularIntensityMap&&(i.specularIntensityMap=s(e.specularIntensityMap)),void 0!==e.specularColorMap&&(i.specularColorMap=s(e.specularColorMap)),void 0!==e.envMap&&(i.envMap=s(e.envMap)),void 0!==e.envMapRotation&&i.envMapRotation.fromArray(e.envMapRotation),void 0!==e.envMapIntensity&&(i.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(i.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(i.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(i.lightMap=s(e.lightMap)),void 0!==e.lightMapIntensity&&(i.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(i.aoMap=s(e.aoMap)),void 0!==e.aoMapIntensity&&(i.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(i.gradientMap=s(e.gradientMap)),void 0!==e.clearcoatMap&&(i.clearcoatMap=s(e.clearcoatMap)),void 0!==e.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=s(e.clearcoatRoughnessMap)),void 0!==e.clearcoatNormalMap&&(i.clearcoatNormalMap=s(e.clearcoatNormalMap)),void 0!==e.clearcoatNormalScale&&(i.clearcoatNormalScale=(new Ys).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(i.iridescenceMap=s(e.iridescenceMap)),void 0!==e.iridescenceThicknessMap&&(i.iridescenceThicknessMap=s(e.iridescenceThicknessMap)),void 0!==e.transmissionMap&&(i.transmissionMap=s(e.transmissionMap)),void 0!==e.thicknessMap&&(i.thicknessMap=s(e.thicknessMap)),void 0!==e.anisotropyMap&&(i.anisotropyMap=s(e.anisotropyMap)),void 0!==e.sheenColorMap&&(i.sheenColorMap=s(e.sheenColorMap)),void 0!==e.sheenRoughnessMap&&(i.sheenRoughnessMap=s(e.sheenRoughnessMap)),i}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return El.createMaterialFromType(e)}static createMaterialFromType(e){return new{ShadowMaterial:bu,SpriteMaterial:so,RawShaderMaterial:vu,ShaderMaterial:Dn,PointsMaterial:Fa,MeshPhysicalMaterial:_u,MeshStandardMaterial:Tu,MeshPhongMaterial:wu,MeshToonMaterial:Su,MeshNormalMaterial:Mu,MeshLambertMaterial:Au,MeshDepthMaterial:Nu,MeshDistanceMaterial:Cu,MeshBasicMaterial:Kr,MeshMatcapMaterial:Ru,LineDashedMaterial:Eu,LineBasicMaterial:va,Material:Jr}[e]}}class Bl{static decodeText(e){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0,i=e.length;s0){const s=new Ku(t);r=new ol(s),r.setCrossOrigin(this.crossOrigin);for(let t=0,s=e.length;t0){i=new ol(this.manager),i.setCrossOrigin(this.crossOrigin);for(let t=0,i=e.length;t{const t=new Ri;t.min.fromArray(e.boxMin),t.max.fromArray(e.boxMax);const s=new $i;return s.radius=e.sphereRadius,s.center.fromArray(e.sphereCenter),{boxInitialized:e.boxInitialized,box:t,sphereInitialized:e.sphereInitialized,sphere:s}})),n._maxInstanceCount=e.maxInstanceCount,n._maxVertexCount=e.maxVertexCount,n._maxIndexCount=e.maxIndexCount,n._geometryInitialized=e.geometryInitialized,n._geometryCount=e.geometryCount,n._matricesTexture=l(e.matricesTexture.uuid),void 0!==e.colorsTexture&&(n._colorsTexture=l(e.colorsTexture.uuid));break;case"LOD":n=new To;break;case"Line":n=new Ca(h(e.geometry),u(e.material));break;case"LineLoop":n=new Pa(h(e.geometry),u(e.material));break;case"LineSegments":n=new Ia(h(e.geometry),u(e.material));break;case"PointCloud":case"Points":n=new Va(h(e.geometry),u(e.material));break;case"Sprite":n=new yo(u(e.material));break;case"Group":n=new ka;break;case"Bone":n=new Io;break;default:n=new Rr}if(n.uuid=e.uuid,void 0!==e.name&&(n.name=e.name),void 0!==e.matrix?(n.matrix.fromArray(e.matrix),void 0!==e.matrixAutoUpdate&&(n.matrixAutoUpdate=e.matrixAutoUpdate),n.matrixAutoUpdate&&n.matrix.decompose(n.position,n.quaternion,n.scale)):(void 0!==e.position&&n.position.fromArray(e.position),void 0!==e.rotation&&n.rotation.fromArray(e.rotation),void 0!==e.quaternion&&n.quaternion.fromArray(e.quaternion),void 0!==e.scale&&n.scale.fromArray(e.scale)),void 0!==e.up&&n.up.fromArray(e.up),void 0!==e.castShadow&&(n.castShadow=e.castShadow),void 0!==e.receiveShadow&&(n.receiveShadow=e.receiveShadow),e.shadow&&(void 0!==e.shadow.intensity&&(n.shadow.intensity=e.shadow.intensity),void 0!==e.shadow.bias&&(n.shadow.bias=e.shadow.bias),void 0!==e.shadow.normalBias&&(n.shadow.normalBias=e.shadow.normalBias),void 0!==e.shadow.radius&&(n.shadow.radius=e.shadow.radius),void 0!==e.shadow.mapSize&&n.shadow.mapSize.fromArray(e.shadow.mapSize),void 0!==e.shadow.camera&&(n.shadow.camera=this.parseObject(e.shadow.camera))),void 0!==e.visible&&(n.visible=e.visible),void 0!==e.frustumCulled&&(n.frustumCulled=e.frustumCulled),void 0!==e.renderOrder&&(n.renderOrder=e.renderOrder),void 0!==e.userData&&(n.userData=e.userData),void 0!==e.layers&&(n.layers.mask=e.layers),void 0!==e.children){const o=e.children;for(let e=0;e{t&&t(s),r.manager.itemEnd(e)})).catch((e=>{i&&i(e)})):(setTimeout((function(){t&&t(n),r.manager.itemEnd(e)}),0),n);const o={};o.credentials="anonymous"===this.crossOrigin?"same-origin":"include",o.headers=this.requestHeader;const a=fetch(e,o).then((function(e){return e.blob()})).then((function(e){return createImageBitmap(e,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(s){return Ju.add(e,s),t&&t(s),r.manager.itemEnd(e),s})).catch((function(t){i&&i(t),Ju.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)}));Ju.add(e,a),r.manager.itemStart(e)}}let Vl;class Dl{static getContext(){return void 0===Vl&&(Vl=new(window.AudioContext||window.webkitAudioContext)),Vl}static setContext(e){Vl=e}}class kl extends el{constructor(e){super(e)}load(e,t,s,i){const r=this,n=new il(this.manager);function o(t){i?i(t):console.error(t),r.manager.itemError(e)}n.setResponseType("arraybuffer"),n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(e,(function(e){try{const s=e.slice(0);Dl.getContext().decodeAudioData(s,(function(e){t(e)})).catch(o)}catch(e){o(e)}}),s,i)}}const Gl=new sr,Wl=new sr,jl=new sr;class Hl{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Hn,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Hn,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,jl.copy(e.projectionMatrix);const s=t.eyeSep/2,i=s*t.near/t.focus,r=t.near*Math.tan(Ds*t.fov*.5)/t.zoom;let n,o;Wl.elements[12]=-s,Gl.elements[12]=s,n=-r*t.aspect+i,o=r*t.aspect+i,jl.elements[0]=2*t.near/(o-n),jl.elements[8]=(o+n)/(o-n),this.cameraL.projectionMatrix.copy(jl),n=-r*t.aspect-i,o=r*t.aspect-i,jl.elements[0]=2*t.near/(o-n),jl.elements[8]=(o+n)/(o-n),this.cameraR.projectionMatrix.copy(jl)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Wl),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Gl)}}class ql extends Hn{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class $l{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Xl(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=Xl();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Xl(){return performance.now()}const Yl=new Ai,Zl=new Mi,Jl=new Ai,Kl=new Ai;class Ql extends Rr{constructor(){super(),this.type="AudioListener",this.context=Dl.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new $l}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener,s=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Yl,Zl,Jl),Kl.set(0,0,-1).applyQuaternion(Zl),t.positionX){const e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Yl.x,e),t.positionY.linearRampToValueAtTime(Yl.y,e),t.positionZ.linearRampToValueAtTime(Yl.z,e),t.forwardX.linearRampToValueAtTime(Kl.x,e),t.forwardY.linearRampToValueAtTime(Kl.y,e),t.forwardZ.linearRampToValueAtTime(Kl.z,e),t.upX.linearRampToValueAtTime(s.x,e),t.upY.linearRampToValueAtTime(s.y,e),t.upZ.linearRampToValueAtTime(s.z,e)}else t.setPosition(Yl.x,Yl.y,Yl.z),t.setOrientation(Kl.x,Kl.y,Kl.z,s.x,s.y,s.z)}}class ec extends Rr{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(!0===this.isPlaying)return void console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.Audio: this Audio has no playback control.");this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;console.warn("THREE.Audio: this Audio has no playback control.")}stop(e=0){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this;console.warn("THREE.Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(s,i,this._addIndex*t,1,t);for(let e=t,r=t+t;e!==r;++e)if(s[e]!==s[e+t]){o.setValue(s,i);break}}saveOriginalState(){const e=this.binding,t=this.buffer,s=this.valueSize,i=s*this._origIndex;e.getValue(t,i);for(let e=s,r=i;e!==r;++e)t[e]=t[i+e%s];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=3*this.valueSize;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let s=e;s=.5)for(let i=0;i!==r;++i)e[t+i]=e[s+i]}_slerp(e,t,s,i){Mi.slerpFlat(e,t,e,t,e,s,i)}_slerpAdditive(e,t,s,i,r){const n=this._workIndex*r;Mi.multiplyQuaternionsFlat(e,n,e,t,e,s),Mi.slerpFlat(e,t,e,t,e,n,i)}_lerp(e,t,s,i,r){const n=1-i;for(let o=0;o!==r;++o){const r=t+o;e[r]=e[r]*n+e[s+o]*i}}_lerpAdditive(e,t,s,i,r){for(let n=0;n!==r;++n){const r=t+n;e[r]=e[r]+e[s+n]*i}}}const hc="\\[\\]\\.:\\/",uc=new RegExp("["+hc+"]","g"),lc="[^"+hc+"]",cc="[^"+hc.replace("\\.","")+"]",dc=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",lc)+/(WCOD+)?/.source.replace("WCOD",cc)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",lc)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",lc)+"$"),pc=["material","materials","bones","map"];class mc{constructor(e,t,s){this.path=t,this.parsedPath=s||mc.parseTrackName(t),this.node=mc.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,s){return e&&e.isAnimationObjectGroup?new mc.Composite(e,t,s):new mc(e,t,s)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(uc,"")}static parseTrackName(e){const t=dc.exec(e);if(null===t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const s={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=s.nodeName&&s.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const e=s.nodeName.substring(i+1);-1!==pc.indexOf(e)&&(s.nodeName=s.nodeName.substring(0,i),s.objectName=e)}if(null===s.propertyName||0===s.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return s}static findNode(e,t){if(void 0===t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const s=e.skeleton.getBoneByName(t);if(void 0!==s)return s}if(e.children){const s=function(e){for(let i=0;i=r){const n=r++,u=e[n];t[u.uuid]=h,e[h]=u,t[a]=n,e[n]=o;for(let e=0,t=i;e!==t;++e){const t=s[e],i=t[n],r=t[h];t[h]=i,t[n]=r}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,s=this._bindings,i=s.length;let r=this.nCachedObjects_,n=e.length;for(let o=0,a=arguments.length;o!==a;++o){const a=arguments[o].uuid,h=t[a];if(void 0!==h)if(delete t[a],h0&&(t[o.uuid]=h),e[h]=o,e.pop();for(let e=0,t=i;e!==t;++e){const t=s[e];t[h]=t[r],t.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const s=this._bindingsIndicesByPath;let i=s[e];const r=this._bindings;if(void 0!==i)return r[i];const n=this._paths,o=this._parsedPaths,a=this._objects,h=a.length,u=this.nCachedObjects_,l=new Array(h);i=r.length,s[e]=i,n.push(e),o.push(t),r.push(l);for(let s=u,i=a.length;s!==i;++s){const i=a[s];l[s]=new mc(i,e,t)}return l}unsubscribe_(e){const t=this._bindingsIndicesByPath,s=t[e];if(void 0!==s){const i=this._paths,r=this._parsedPaths,n=this._bindings,o=n.length-1,a=n[o];t[e[o]]=s,n[s]=a,n.pop(),r[s]=r[o],r.pop(),i[s]=i[o],i.pop()}}}class fc{constructor(e,t,s=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=s,this.blendMode=i;const r=t.tracks,n=r.length,o=new Array(n),a={endingStart:Ut,endingEnd:Ut};for(let e=0;e!==n;++e){const t=r[e].createInterpolant(null);o[e]=t,t.settings=a}this._interpolantSettings=a,this._interpolants=o,this._propertyBindings=new Array(n),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,s){if(e.fadeOut(t),this.fadeIn(t),s){const s=this._clip.duration,i=e._clip.duration,r=i/s,n=s/i;e.warp(1,r,t),this.warp(n,1,t)}return this}crossFadeTo(e,t,s){return e.crossFadeFrom(this,t,s)}stopFading(){const e=this._weightInterpolant;return null!==e&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,s){const i=this._mixer,r=i.time,n=this.timeScale;let o=this._timeScaleInterpolant;null===o&&(o=i._lendControlInterpolant(),this._timeScaleInterpolant=o);const a=o.parameterPositions,h=o.sampleValues;return a[0]=r,a[1]=r+s,h[0]=e/n,h[1]=t/n,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,s,i){if(!this.enabled)return void this._updateWeight(e);const r=this._startTime;if(null!==r){const i=(e-r)*s;i<0||0===s?t=0:(this._startTime=null,t=s*i)}t*=this._updateTimeScale(e);const n=this._updateTime(t),o=this._updateWeight(e);if(o>0){const e=this._interpolants,t=this._propertyBindings;if(this.blendMode===Vt)for(let s=0,i=e.length;s!==i;++s)e[s].evaluate(n),t[s].accumulateAdditive(o);else for(let s=0,r=e.length;s!==r;++s)e[s].evaluate(n),t[s].accumulate(i,o)}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const s=this._weightInterpolant;if(null!==s){const i=s.evaluate(e)[0];t*=i,e>s.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const s=this._timeScaleInterpolant;if(null!==s){t*=s.evaluate(e)[0],e>s.parameterPositions[1]&&(this.stopWarping(),0===t?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,s=this.loop;let i=this.time+e,r=this._loopCount;const n=2202===s;if(0===e)return-1===r?i:n&&1==(1&r)?t-i:i;if(2200===s){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else{if(!(i<0)){this.time=i;break e}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(-1===r&&(e>=0?(r=0,this._setEndings(!0,0===this.repetitions,n)):this._setEndings(0===this.repetitions,!0,n)),i>=t||i<0){const s=Math.floor(i/t);i-=t*s,r+=Math.abs(s);const o=this.repetitions-r;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(1===o){const t=e<0;this._setEndings(t,!t,n)}else this._setEndings(!1,!1,n);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:s})}}else this.time=i;if(n&&1==(1&r))return t-i}return i}_setEndings(e,t,s){const i=this._interpolantSettings;s?(i.endingStart=Ot,i.endingEnd=Ot):(i.endingStart=e?this.zeroSlopeAtStart?Ot:Ut:zt,i.endingEnd=t?this.zeroSlopeAtEnd?Ot:Ut:zt)}_scheduleFading(e,t,s){const i=this._mixer,r=i.time;let n=this._weightInterpolant;null===n&&(n=i._lendControlInterpolant(),this._weightInterpolant=n);const o=n.parameterPositions,a=n.sampleValues;return o[0]=r,a[0]=t,o[1]=r+e,a[1]=s,this}}const yc=new Float32Array(1);class xc extends zs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const s=e._localRoot||this._root,i=e._clip.tracks,r=i.length,n=e._propertyBindings,o=e._interpolants,a=s.uuid,h=this._bindingsByRootAndName;let u=h[a];void 0===u&&(u={},h[a]=u);for(let e=0;e!==r;++e){const r=i[e],h=r.name;let l=u[h];if(void 0!==l)++l.referenceCount,n[e]=l;else{if(l=n[e],void 0!==l){null===l._cacheIndex&&(++l.referenceCount,this._addInactiveBinding(l,a,h));continue}const i=t&&t._propertyBindings[e].binding.parsedPath;l=new ac(mc.create(s,h,i),r.ValueTypeName,r.getValueSize()),++l.referenceCount,this._addInactiveBinding(l,a,h),n[e]=l}o[e].resultBuffer=l.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,s=e._clip.uuid,i=this._actionsByClip[s];this._bindAction(e,i&&i.knownActions[0]),this._addInactiveAction(e,s,t)}const t=e._propertyBindings;for(let e=0,s=t.length;e!==s;++e){const s=t[e];0==s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,s=t.length;e!==s;++e){const s=t[e];0==--s.useCount&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return null!==t&&t=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,s=this._nActiveActions,i=this.time+=e,r=Math.sign(e),n=this._accuIndex^=1;for(let o=0;o!==s;++o){t[o]._update(i,e,r,n)}const o=this._bindings,a=this._nActiveBindings;for(let e=0;e!==a;++e)o[e].apply(n);return this}setTime(e){this.time=0;for(let e=0;e=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bc).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Pc=new Ai,Fc=new Ai;class Uc{constructor(e=new Ai,t=new Ai){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){Pc.subVectors(e,this.start),Fc.subVectors(this.end,this.start);const s=Fc.dot(Fc);let i=Fc.dot(Pc)/s;return t&&(i=Ws(i,0,1)),i}closestPointToPoint(e,t,s){const i=this.closestPointToPointParameter(e,t);return this.delta(s).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const Oc=new Ai;class zc extends Rr{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const s=new Sn,i=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let e=0,t=1,s=32;e1)for(let s=0;s.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{hd.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(hd,t)}}setLength(e,t=.2*e,s=.2*t){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(s,t,s),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class dd extends Ia{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],s=new Sn;s.setAttribute("position",new fn(t,3)),s.setAttribute("color",new fn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(s,new va({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(e,t,s){const i=new Xr,r=this.geometry.attributes.color.array;return i.set(e),i.toArray(r,0),i.toArray(r,3),i.set(t),i.toArray(r,6),i.toArray(r,9),i.set(s),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class pd{constructor(){this.type="ShapePath",this.color=new Xr,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new fh,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,s,i){return this.currentPath.quadraticCurveTo(e,t,s,i),this}bezierCurveTo(e,t,s,i,r,n){return this.currentPath.bezierCurveTo(e,t,s,i,r,n),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(e,t){const s=t.length;let i=!1;for(let r=s-1,n=0;nNumber.EPSILON){if(h<0&&(s=t[n],a=-a,o=t[r],h=-h),e.yo.y)continue;if(e.y===s.y){if(e.x===s.x)return!0}else{const t=h*(e.x-s.x)-a*(e.y-s.y);if(0===t)return!0;if(t<0)continue;i=!i}}else{if(e.y!==s.y)continue;if(o.x<=e.x&&e.x<=s.x||s.x<=e.x&&e.x<=o.x)return!0}}return i}const s=tu.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,n,o;const a=[];if(1===i.length)return n=i[0],o=new Rh,o.curves=n.curves,a.push(o),a;let h=!s(i[0].getPoints());h=e?!h:h;const u=[],l=[];let c,d,p=[],m=0;l[m]=void 0,p[m]=[];for(let t=0,o=i.length;t1){let e=!1,s=0;for(let e=0,t=l.length;e0&&!1===e&&(p=u)}for(let e=0,t=l.length;e>>16,2246822507),s^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(s^s>>>13,3266489909),4294967296*(2097151&i)+(s>>>0)}const bd=e=>xd(e),vd=e=>xd(e),Td=(...e)=>xd(e);function _d(e,t=!1){const s=[];!0===e.isNode&&(s.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of wd(e))s.push(s,xd(i.slice(0,-4)),r.getCacheKey(t));return xd(s)}function*wd(e,t=!1){for(const s in e){if(!0===s.startsWith("_"))continue;const i=e[s];if(!0===Array.isArray(i))for(let e=0;ee.charCodeAt(0))).buffer}var Cd=Object.freeze({__proto__:null,arrayBufferToBase64:Ad,base64ToArrayBuffer:Nd,getCacheKey:_d,getNodeChildren:wd,getValueFromType:Md,getValueType:Sd,hash:Td,hashArray:vd,hashString:bd});const Rd={VERTEX:"vertex",FRAGMENT:"fragment"},Ed={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Bd={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Id=["fragment","vertex"],Pd=["setup","analyze","generate"],Fd=[...Id,"compute"],Ud=["x","y","z","w"];let Od=0;class zd extends zs{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Ed.NONE,this.updateBeforeType=Ed.NONE,this.updateAfterType=Ed.NONE,this.uuid=Xs.generateUUID(),this.version=0,this._cacheKey=null,this._cacheKeyVersion=0,this.global=!1,this.isNode=!0,Object.defineProperty(this,"id",{value:Od++})}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.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Ed.FRAME)}onRenderUpdate(e){return this.onUpdate(e,Ed.RENDER)}onObjectUpdate(e){return this.onUpdate(e,Ed.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of wd(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=_d(this,e),this._cacheKeyVersion=this.version),this._cacheKey}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)}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}setup(e){const t=e.getNodeProperties(this);let s=0;for(const e of this.getChildren())t["node"+s++]=e;return null}analyze(e){if(1===e.increaseUsage(this)){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){e.stack.nodes.length;t.initialized=!0,t.outputNode=this.setup(e),null!==t.outputNode&&e.stack.nodes.length;for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const s=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i?(i=this.generate(e)||"",r.snippet=i):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),i=e.format(i,s,t)}else i=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),i}getSerializeChildren(){return wd(this)}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:r,childNode:n}of t)void 0!==r?(void 0===s[i]&&(s[i]=Number.isInteger(r)?[]:{}),s[i][r]=n.toJSON(e.meta).uuid):s[i]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const r of e.inputNodes[s])i.push(t[r]);this[s]=i}else if("object"==typeof e.inputNodes[s]){const i={};for(const r in e.inputNodes[s]){const n=e.inputNodes[s][r];i[r]=t[n]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:s,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=n(e.textures),s=n(e.images),i=n(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),i.length>0&&(r.nodes=i)}return r}}class Ld extends zd{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){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}class Vd extends zd{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(i)||(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),r=s.build(e,i);return e.format(r,i,t)}}class Dd extends zd{static get type(){return"TempNode"}constructor(e){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,s,t);if("void"!==s&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,s),n=e.getVarFromNode(this,null,s),o=e.getPropertyName(n);return e.addLineFlowCode(`${o} = ${r}`,this),i.snippet=r,i.propertyName=o,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class kd extends Dd{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,s)=>t+e.getTypeLength(s.getNodeType(e))),0))}generate(e,t){const s=this.getNodeType(e),i=this.nodes,r=e.getComponentType(s),n=[];for(const t of i){let s=t.build(e);const i=e.getComponentType(t.getNodeType(e));i!==r&&(s=e.format(s,i,r)),n.push(s)}const o=`${e.getType(s)}( ${n.join(", ")} )`;return e.format(o,s,t)}}const Gd=Ud.join("");class Wd extends zd{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(Ud.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))}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let r=null;if(i>1){let n=null;this.getVectorLength()>=i&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const o=s.build(e,n);r=this.components.length===i&&this.components===Gd.slice(0,this.components.length)?e.format(o,n,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else r=s.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class jd extends Dd{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,r=this.getNodeType(e),n=e.getTypeFromLength(s.length,i.getNodeType(e)),o=i.build(e,n),a=t.build(e,r),h=e.getTypeLength(r),u=[];for(let e=0;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Kd=e=>Jd(e).split("").sort().join(""),Qd={setup(e,t){const s=t.shift();return e(Sp(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Xd.assign(s,...e),s);if(Yd.has(t)){const i=Yd.get(t);return e.isStackNode?(...e)=>s.add(i(...e)):(...e)=>i(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Yd.has(t.slice(0,t.length-6))){const i=Yd.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>s.assign(e[0],i(...e)):(...e)=>s.assign(i(s,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=Jd(t),wp(new Wd(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Kd(t.slice(3).toLowerCase()),s=>wp(new jd(e,t,s));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Kd(t.slice(4).toLowerCase()),()=>wp(new Hd(wp(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),wp(new Wd(e,t));if(!0===/^\d+$/.test(t))return wp(new Ld(s,new $d(Number(t),"uint")))}return Reflect.get(e,t,s)},set:(e,t,s,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,s,i):(i[t].assign(s),!0)},ep=new WeakMap,tp=new WeakMap,sp=function(e,t=null){for(const s in e)e[s]=wp(e[s],t);return e},ip=function(e,t=null){const s=e.length;for(let i=0;iwp(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...Mp(t))):null!==s?(s=wp(s),(...i)=>r(new e(t,...Mp(i),s))):(...s)=>r(new e(t,...Mp(s)))},np=function(e,...t){return wp(new e(...Mp(t)))};class op extends zd{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}call(e){const{shaderNode:t,inputNodes:s}=this,i=e.getNodeProperties(t);if(i.onceOutput)return i.onceOutput;let r=null;if(t.layout){let i=tp.get(e.constructor);void 0===i&&(i=new WeakMap,tp.set(e.constructor,i));let n=i.get(t);void 0===n&&(n=wp(e.buildFunctionNode(t)),i.set(t,n)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(n),r=wp(n.call(s))}else{const i=t.jsFunc,n=null!==s?i(s,e):i(e);r=wp(n)}return t.once&&(i.onceOutput=r),r}getOutputNode(e){const t=e.getNodeProperties(this);return null===t.outputNode&&(t.outputNode=this.setupOutput(e)),t.outputNode}setup(e){return this.getOutputNode(e)}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){return this.getOutputNode(e).build(e,t)}}class ap extends zd{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 Sp(e),wp(new op(this,e))}setup(){return this.call()}}const hp=[!1,!0],up=[0,1,2,3],lp=[-1,-2],cp=[.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],dp=new Map;for(const e of hp)dp.set(e,new $d(e));const pp=new Map;for(const e of up)pp.set(e,new $d(e,"uint"));const mp=new Map([...pp].map((e=>new $d(e.value,"int"))));for(const e of lp)mp.set(e,new $d(e,"int"));const gp=new Map([...mp].map((e=>new $d(e.value))));for(const e of cp)gp.set(e,new $d(e));for(const e of cp)gp.set(-e,new $d(-e));const fp={bool:dp,uint:pp,ints:mp,float:gp},yp=new Map([...dp,...gp]),xp=(e,t)=>yp.has(e)?yp.get(e):!0===e.isNode?e:new $d(e,t),bp=function(e,t=null){return(...s)=>{if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every((e=>"object"!=typeof e)))&&(s=[Md(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return wp(t.get(s[0]));if(1===s.length){const t=xp(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?wp(t):wp(new Vd(t,e))}const i=s.map((e=>xp(e)));return wp(new kd(i,e))}},vp=e=>"object"==typeof e&&null!==e?e.value:e,Tp=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function _p(e,t){return new Proxy(new ap(e,t),Qd)}const wp=(e,t=null)=>function(e,t=null){const s=Sd(e);if("node"===s){let t=ep.get(e);return void 0===t&&(t=new Proxy(e,Qd),ep.set(e,t),ep.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?wp(xp(e,t)):"shader"===s?Cp(e):e}(e,t),Sp=(e,t=null)=>new sp(e,t),Mp=(e,t=null)=>new ip(e,t),Ap=(...e)=>new rp(...e),Np=(...e)=>new np(...e),Cp=(e,t)=>{const s=new _p(e,t),i=(...e)=>{let t;return Sp(e),t=e[0]&&e[0].isNode?[...e]:e[0],s.call(t)};return i.shaderNode=s,i.setLayout=e=>(s.setLayout(e),i),i.once=()=>(s.once=!0,i),i},Rp=(...e)=>(console.warn("TSL.ShaderNode: tslFn() has been renamed to Fn()."),Cp(...e));Zd("toGlobal",(e=>(e.global=!0,e)));const Ep=e=>{Xd=e},Bp=()=>Xd,Ip=(...e)=>Xd.If(...e);function Pp(e){return Xd&&Xd.add(e),e}Zd("append",Pp);const Fp=new bp("color"),Up=new bp("float",fp.float),Op=new bp("int",fp.ints),zp=new bp("uint",fp.uint),Lp=new bp("bool",fp.bool),Vp=new bp("vec2"),Dp=new bp("ivec2"),kp=new bp("uvec2"),Gp=new bp("bvec2"),Wp=new bp("vec3"),jp=new bp("ivec3"),Hp=new bp("uvec3"),qp=new bp("bvec3"),$p=new bp("vec4"),Xp=new bp("ivec4"),Yp=new bp("uvec4"),Zp=new bp("bvec4"),Jp=new bp("mat2"),Kp=new bp("mat3"),Qp=new bp("mat4"),em=(e="")=>wp(new $d(e,"string")),tm=e=>wp(new $d(e,"ArrayBuffer"));Zd("toColor",Fp),Zd("toFloat",Up),Zd("toInt",Op),Zd("toUint",zp),Zd("toBool",Lp),Zd("toVec2",Vp),Zd("toIVec2",Dp),Zd("toUVec2",kp),Zd("toBVec2",Gp),Zd("toVec3",Wp),Zd("toIVec3",jp),Zd("toUVec3",Hp),Zd("toBVec3",qp),Zd("toVec4",$p),Zd("toIVec4",Xp),Zd("toUVec4",Yp),Zd("toBVec4",Zp),Zd("toMat2",Jp),Zd("toMat3",Kp),Zd("toMat4",Qp);const sm=Ap(Ld),im=(e,t)=>wp(new Vd(wp(e),t)),rm=(e,t)=>wp(new Wd(wp(e),t));Zd("element",sm),Zd("convert",im);class nm extends zd{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.version=0,this.shared=t,this.order=s,this.isUniformGroup=!0}set needsUpdate(e){!0===e&&this.version++}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 om=e=>new nm(e),am=(e,t=0)=>new nm(e,!0,t),hm=am("frame"),um=am("render"),lm=om("object");class cm extends qd{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=lm}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const s=this.getSelf();return e=e.bind(s),super.onUpdate((t=>{const i=e(t,s);void 0!==i&&(this.value=i)}),t)}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const n=r.getInputType(e),o=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.label),a=e.getPropertyName(o);return void 0!==e.context.label&&delete e.context.label,e.format(a,s,t)}}const dm=(e,t)=>{const s=Tp(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return wp(new cm(i,s))};class pm extends zd{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}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 mm=(e,t)=>wp(new pm(e,t)),gm=(e,t)=>wp(new pm(e,t,!0)),fm=Np(pm,"vec4","DiffuseColor"),ym=Np(pm,"vec3","EmissiveColor"),xm=Np(pm,"float","Roughness"),bm=Np(pm,"float","Metalness"),vm=Np(pm,"float","Clearcoat"),Tm=Np(pm,"float","ClearcoatRoughness"),_m=Np(pm,"vec3","Sheen"),wm=Np(pm,"float","SheenRoughness"),Sm=Np(pm,"float","Iridescence"),Mm=Np(pm,"float","IridescenceIOR"),Am=Np(pm,"float","IridescenceThickness"),Nm=Np(pm,"float","AlphaT"),Cm=Np(pm,"float","Anisotropy"),Rm=Np(pm,"vec3","AnisotropyT"),Em=Np(pm,"vec3","AnisotropyB"),Bm=Np(pm,"color","SpecularColor"),Im=Np(pm,"float","SpecularF90"),Pm=Np(pm,"float","Shininess"),Fm=Np(pm,"vec4","Output"),Um=Np(pm,"float","dashSize"),Om=Np(pm,"float","gapSize"),zm=Np(pm,"float","pointWidth"),Lm=Np(pm,"float","IOR"),Vm=Np(pm,"float","Transmission"),Dm=Np(pm,"float","Thickness"),km=Np(pm,"float","AttenuationDistance"),Gm=Np(pm,"color","AttenuationColor"),Wm=Np(pm,"float","Dispersion");class jm extends Dd{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}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 s=e.getTypeLength(t.node.getNodeType(e));return Ud.join("").slice(0,s)!==t.components}return!1}generate(e,t){const{targetNode:s,sourceNode:i}=this,r=this.needsSplitAssign(e),n=s.getNodeType(e),o=s.context({assign:!0}).build(e),a=i.build(e,n),h=i.getNodeType(e),u=e.getDataFromNode(this);let l;if(!0===u.initialized)"void"!==t&&(l=o);else if(r){const i=e.getVarFromNode(this,null,n),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${a}`,this);const h=s.node.context({assign:!0}).build(e);for(let t=0;t{const i=s.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r))for(let e=0;e(t=t.length>1||t[0]&&!0===t[0].isNode?Mp(t):Sp(t[0]),wp(new qm(wp(e),t)));Zd("call",$m);class Xm extends Dd{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new Xm(e,t,s);for(let t=0;t>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"=="===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("<"===s||">"===s||"<="===s||">="===s){const s=t?e.getTypeLength(t):Math.max(e.getTypeLength(n),e.getTypeLength(o));return s>1?`bvec${s}`:"bool"}return"float"===n&&e.isMatrix(o)?o:e.isMatrix(n)&&e.isVector(o)?e.getVectorFromMatrix(n):e.isVector(n)&&e.isMatrix(o)?e.getVectorFromMatrix(o):e.getTypeLength(o)>e.getTypeLength(n)?o:n}generate(e,t){const s=this.op,i=this.aNode,r=this.bNode,n=this.getNodeType(e,t);let o=null,a=null;"void"!==n?(o=i.getNodeType(e),a=void 0!==r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s?e.isVector(o)?a=o:o!==a&&(o=a="float"):">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):e.isMatrix(o)&&e.isVector(a)?a=e.getVectorFromMatrix(o):o=e.isVector(o)&&e.isMatrix(a)?e.getVectorFromMatrix(a):a=n):o=a=n;const h=i.build(e,o),u=void 0!==r?r.build(e,a):null,l=e.getTypeLength(t),c=e.getFunctionOperator(s);return"void"!==t?"<"===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThan",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} < ${u} )`,n,t):"<="===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThanEqual",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} <= ${u} )`,n,t):">"===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThan",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} > ${u} )`,n,t):">="===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThanEqual",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} >= ${u} )`,n,t):"!"===s||"~"===s?e.format(`(${s}${h})`,o,t):c?e.format(`${c}( ${h}, ${u} )`,n,t):e.format(`( ${h} ${s} ${u} )`,n,t):"void"!==o?c?e.format(`${c}( ${h}, ${u} )`,n,t):e.format(`${h} ${s} ${u}`,n,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Ym=Ap(Xm,"+"),Zm=Ap(Xm,"-"),Jm=Ap(Xm,"*"),Km=Ap(Xm,"/"),Qm=Ap(Xm,"%"),eg=Ap(Xm,"=="),tg=Ap(Xm,"!="),sg=Ap(Xm,"<"),ig=Ap(Xm,">"),rg=Ap(Xm,"<="),ng=Ap(Xm,">="),og=Ap(Xm,"&&"),ag=Ap(Xm,"||"),hg=Ap(Xm,"!"),ug=Ap(Xm,"^^"),lg=Ap(Xm,"&"),cg=Ap(Xm,"~"),dg=Ap(Xm,"|"),pg=Ap(Xm,"^"),mg=Ap(Xm,"<<"),gg=Ap(Xm,">>");Zd("add",Ym),Zd("sub",Zm),Zd("mul",Jm),Zd("div",Km),Zd("modInt",Qm),Zd("equal",eg),Zd("notEqual",tg),Zd("lessThan",sg),Zd("greaterThan",ig),Zd("lessThanEqual",rg),Zd("greaterThanEqual",ng),Zd("and",og),Zd("or",ag),Zd("not",hg),Zd("xor",ug),Zd("bitAnd",lg),Zd("bitNot",cg),Zd("bitOr",dg),Zd("bitXor",pg),Zd("shiftLeft",mg),Zd("shiftRight",gg);const fg=(...e)=>(console.warn("TSL.OperatorNode: .remainder() has been renamed to .modInt()."),Qm(...e));Zd("remainder",fg);class yg extends Dd{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=s,this.cNode=i}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>o?t:n>o?s:o>r?i:t}getNodeType(e){const t=this.method;return t===yg.LENGTH||t===yg.DISTANCE||t===yg.DOT?"float":t===yg.CROSS?"vec3":t===yg.ALL?"bool":t===yg.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===yg.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,h=!0===e.renderer.isWebGLRenderer;if(s===yg.TRANSFORM_DIRECTION){let s=n,i=o;e.isMatrix(s.getNodeType(e))?i=$p(Wp(i),0):s=$p(Wp(s),0);const r=Jm(s,i).xyz;return Ug(r).build(e,t)}if(s===yg.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);if(s===yg.ONE_MINUS)return Zm(1,n).build(e,t);if(s===yg.RECIPROCAL)return Km(1,n).build(e,t);if(s===yg.DIFFERENCE)return Wg(Zm(n,o)).build(e,t);{const u=[];return s===yg.CROSS||s===yg.MOD?u.push(n.build(e,i),o.build(e,i)):h&&s===yg.STEP?u.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):h&&(s===yg.MIN||s===yg.MAX)||s===yg.MOD?u.push(n.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):s===yg.REFRACT?u.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===yg.MIX?u.push(n.build(e,r),o.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):(u.push(n.build(e,r)),null!==o&&u.push(o.build(e,r)),null!==a&&u.push(a.build(e,r))),e.format(`${e.getMethod(s,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}yg.ALL="all",yg.ANY="any",yg.EQUALS="equals",yg.RADIANS="radians",yg.DEGREES="degrees",yg.EXP="exp",yg.EXP2="exp2",yg.LOG="log",yg.LOG2="log2",yg.SQRT="sqrt",yg.INVERSE_SQRT="inversesqrt",yg.FLOOR="floor",yg.CEIL="ceil",yg.NORMALIZE="normalize",yg.FRACT="fract",yg.SIN="sin",yg.COS="cos",yg.TAN="tan",yg.ASIN="asin",yg.ACOS="acos",yg.ATAN="atan",yg.ABS="abs",yg.SIGN="sign",yg.LENGTH="length",yg.NEGATE="negate",yg.ONE_MINUS="oneMinus",yg.DFDX="dFdx",yg.DFDY="dFdy",yg.ROUND="round",yg.RECIPROCAL="reciprocal",yg.TRUNC="trunc",yg.FWIDTH="fwidth",yg.BITCAST="bitcast",yg.TRANSPOSE="transpose",yg.ATAN2="atan2",yg.MIN="min",yg.MAX="max",yg.MOD="mod",yg.STEP="step",yg.REFLECT="reflect",yg.DISTANCE="distance",yg.DIFFERENCE="difference",yg.DOT="dot",yg.CROSS="cross",yg.POW="pow",yg.TRANSFORM_DIRECTION="transformDirection",yg.MIX="mix",yg.CLAMP="clamp",yg.REFRACT="refract",yg.SMOOTHSTEP="smoothstep",yg.FACEFORWARD="faceforward";const xg=Up(1e-6),bg=Up(1e6),vg=Up(Math.PI),Tg=Up(2*Math.PI),_g=Ap(yg,yg.ALL),wg=Ap(yg,yg.ANY),Sg=Ap(yg,yg.EQUALS),Mg=Ap(yg,yg.RADIANS),Ag=Ap(yg,yg.DEGREES),Ng=Ap(yg,yg.EXP),Cg=Ap(yg,yg.EXP2),Rg=Ap(yg,yg.LOG),Eg=Ap(yg,yg.LOG2),Bg=Ap(yg,yg.SQRT),Ig=Ap(yg,yg.INVERSE_SQRT),Pg=Ap(yg,yg.FLOOR),Fg=Ap(yg,yg.CEIL),Ug=Ap(yg,yg.NORMALIZE),Og=Ap(yg,yg.FRACT),zg=Ap(yg,yg.SIN),Lg=Ap(yg,yg.COS),Vg=Ap(yg,yg.TAN),Dg=Ap(yg,yg.ASIN),kg=Ap(yg,yg.ACOS),Gg=Ap(yg,yg.ATAN),Wg=Ap(yg,yg.ABS),jg=Ap(yg,yg.SIGN),Hg=Ap(yg,yg.LENGTH),qg=Ap(yg,yg.NEGATE),$g=Ap(yg,yg.ONE_MINUS),Xg=Ap(yg,yg.DFDX),Yg=Ap(yg,yg.DFDY),Zg=Ap(yg,yg.ROUND),Jg=Ap(yg,yg.RECIPROCAL),Kg=Ap(yg,yg.TRUNC),Qg=Ap(yg,yg.FWIDTH),ef=Ap(yg,yg.BITCAST),tf=Ap(yg,yg.TRANSPOSE),sf=Ap(yg,yg.ATAN2),rf=Ap(yg,yg.MIN),nf=Ap(yg,yg.MAX),of=Ap(yg,yg.MOD),af=Ap(yg,yg.STEP),hf=Ap(yg,yg.REFLECT),uf=Ap(yg,yg.DISTANCE),lf=Ap(yg,yg.DIFFERENCE),cf=Ap(yg,yg.DOT),df=Ap(yg,yg.CROSS),pf=Ap(yg,yg.POW),mf=Ap(yg,yg.POW,2),gf=Ap(yg,yg.POW,3),ff=Ap(yg,yg.POW,4),yf=Ap(yg,yg.TRANSFORM_DIRECTION),xf=e=>Jm(jg(e),pf(Wg(e),1/3)),bf=e=>cf(e,e),vf=Ap(yg,yg.MIX),Tf=(e,t=0,s=1)=>wp(new yg(yg.CLAMP,wp(e),wp(t),wp(s))),_f=e=>Tf(e),wf=Ap(yg,yg.REFRACT),Sf=Ap(yg,yg.SMOOTHSTEP),Mf=Ap(yg,yg.FACEFORWARD),Af=Cp((([e])=>{const t=cf(e.xy,Vp(12.9898,78.233)),s=of(t,vg);return Og(zg(s).mul(43758.5453))})),Nf=(e,t,s)=>vf(t,s,e),Cf=(e,t,s)=>Sf(t,s,e);Zd("all",_g),Zd("any",wg),Zd("equals",Sg),Zd("radians",Mg),Zd("degrees",Ag),Zd("exp",Ng),Zd("exp2",Cg),Zd("log",Rg),Zd("log2",Eg),Zd("sqrt",Bg),Zd("inverseSqrt",Ig),Zd("floor",Pg),Zd("ceil",Fg),Zd("normalize",Ug),Zd("fract",Og),Zd("sin",zg),Zd("cos",Lg),Zd("tan",Vg),Zd("asin",Dg),Zd("acos",kg),Zd("atan",Gg),Zd("abs",Wg),Zd("sign",jg),Zd("length",Hg),Zd("lengthSq",bf),Zd("negate",qg),Zd("oneMinus",$g),Zd("dFdx",Xg),Zd("dFdy",Yg),Zd("round",Zg),Zd("reciprocal",Jg),Zd("trunc",Kg),Zd("fwidth",Qg),Zd("atan2",sf),Zd("min",rf),Zd("max",nf),Zd("mod",of),Zd("step",af),Zd("reflect",hf),Zd("distance",uf),Zd("dot",cf),Zd("cross",df),Zd("pow",pf),Zd("pow2",mf),Zd("pow3",gf),Zd("pow4",ff),Zd("transformDirection",yf),Zd("mix",Nf),Zd("clamp",Tf),Zd("refract",wf),Zd("smoothstep",Cf),Zd("faceForward",Mf),Zd("difference",lf),Zd("saturate",_f),Zd("cbrt",xf),Zd("transpose",tf),Zd("rand",Af);class Rf extends zd{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const t=this.ifNode.getNodeType(e);if(null!==this.elseNode){const s=this.elseNode.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(t))return s}return t}setup(e){const t=this.condNode.cache(),s=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=s.context({nodeBlock:s}),n.elseNode=i?i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:n,elseNode:o}=e.getNodeProperties(this),a="void"!==t,h=a?mm(s).build(e):"";i.nodeProperty=h;const u=r.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let l=n.build(e,s);if(l&&(l=a?h+" = "+l+";":"return "+l+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+l+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=o.build(e,s);t&&(t=a?h+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(h,s,t)}}const Ef=Ap(Rf);Zd("select",Ef);const Bf=(...e)=>(console.warn("TSL.ConditionalNode: cond() has been renamed to select()."),Ef(...e));Zd("cond",Bf);class If extends zd{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)}analyze(e){this.node.build(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e);return e.setContext(t),s}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(s),i}}const Pf=Ap(If),Ff=(e,t)=>Pf(e,{label:t});Zd("context",Pf),Zd("label",Ff);class Uf extends zd{static get type(){return"VarNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s}=this,i=e.getVarFromNode(this,s,e.getVectorType(this.getNodeType(e))),r=e.getPropertyName(i),n=t.build(e,i.type);return e.addLineFlowCode(`${r} = ${n}`,this),r}}const Of=Ap(Uf);Zd("toVar",((...e)=>Of(...e).append()));const zf=e=>(console.warn('TSL: "temp" is deprecated. Use ".toVar()" instead.'),Of(e));Zd("temp",zf);class Lf extends zd{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(void 0===s){const i=this.name,r=this.getNodeType(e);t.varying=s=e.getVaryingFromNode(this,i,r),t.node=this.node}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e)}analyze(e){return this.setupVarying(e),this.node.analyze(e)}generate(e){const t=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===t.propertyName){const i=this.getNodeType(e),r=e.getPropertyName(s,Rd.VERTEX);e.flowNodeFromShaderStage(Rd.VERTEX,this.node,i,r),t.propertyName=r}return e.getPropertyName(s)}}const Vf=Ap(Lf);Zd("varying",Vf);const Df="WorkingColorSpace",kf="OutputColorSpace";function Gf(e){let t=null;return e===Jt?t="Linear":e===Zt&&(t="sRGB"),t}function Wf(e,t){return Gf(e)+"To"+Gf(t)}class jf extends Dd{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}getColorSpace(e,t){return t===Df?ii.workingColorSpace:t===kf?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{renderer:t}=e,{colorNode:s}=this,i=this.getColorSpace(e,this.source),r=this.getColorSpace(e,this.target);if(i===r)return s;const n=Wf(i,r);let o=null;const a=t.library.getColorSpaceFunction(n);return null!==a?o=$p(a(s.rgb),s.a):(console.error("ColorSpaceNode: Unsupported Color Space configuration.",n),o=s),o}}const Hf=e=>wp(new jf(wp(e),Df,kf)),qf=e=>wp(new jf(wp(e),kf,Df)),$f=(e,t)=>wp(new jf(wp(e),Df,t)),Xf=(e,t)=>wp(new jf(wp(e),t,Df));Zd("toOutputColorSpace",Hf),Zd("toWorkingColorSpace",qf),Zd("workingToColorSpace",$f),Zd("colorSpaceToWorking",Xf);let Yf=class extends Ld{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),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class Zf extends zd{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=Ed.OBJECT}setGroup(e){return this.group=e,this}element(e){return wp(new Yf(this,wp(e)))}setNodeType(e){const t=dm(null,e).getSelf();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 s=e[t[0]];for(let e=1;ewp(new Jf(e,t,s));class Qf extends Dd{static get type(){return"ToneMappingNode"}constructor(e,t=ty,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}getCacheKey(){return Td(super.getCacheKey(),this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,s=this.toneMapping;if(0===s)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(s);return null!==r?i=$p(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const ey=(e,t,s)=>wp(new Qf(e,wp(t),wp(s))),ty=Kf("toneMappingExposure","float");Zd("toneMapping",((e,t,s)=>ey(t,s,e)));class sy extends qd{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=Ss,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),s=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,n=this.bufferOffset,o=!0===s.isInterleavedBuffer?s:new Qn(s,r),a=new to(o,i,n);o.setUsage(this.usage),this.attribute=a,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=Vf(this).build(e,t)}return r}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 iy=(e,t,s,i)=>wp(new sy(e,t,s,i)),ry=(e,t,s,i)=>iy(e,t,s,i).setUsage(Ms),ny=(e,t,s,i)=>iy(e,t,s,i).setInstanced(!0),oy=(e,t,s,i)=>ry(e,t,s,i).setInstanced(!0);Zd("toAttribute",(e=>iy(e.value)));class ay extends zd{static get type(){return"ComputeNode"}constructor(e,t,s=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=s,this.dispatchCount=0,this.version=1,this.updateBeforeType=Ed.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let s=t[0];for(let e=1;ewp(new ay(wp(e),t,s));Zd("compute",hy);class uy extends zd{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){return this.node.getNodeType(e)}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(s),r}}const ly=(e,...t)=>wp(new uy(wp(e),...t));Zd("cache",ly);class cy extends zd{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 dy=Ap(cy);Zd("bypass",dy);class py extends zd{static get type(){return"RemapNode"}constructor(e,t,s,i=Up(0),r=Up(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:r,doClamp:n}=this;let o=e.sub(t).div(s.sub(t));return!0===n&&(o=o.clamp()),o.mul(r.sub(i)).add(i)}}const my=Ap(py,null,null,{doClamp:!1}),gy=Ap(py);Zd("remap",my),Zd("remapClamp",gy);class fy extends zd{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if("void"!==s)return e.format(`( ${i} )`,s,t);e.addLineFlowCode(i,this)}}const yy=Ap(fy),xy=e=>(e?Ef(e,yy("discard")):yy("discard")).append(),by=()=>yy("return").append();Zd("discard",xy);class vy extends Dd{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutput=!0}setup({context:e}){let t=this.colorNode||e.color;const s=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||Yt;return 0!==s&&(t=t.toneMapping(s)),i!==Yt&&i!==ii.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const Ty=(e,t=null,s=null)=>wp(new vy(wp(e),t,s));function _y(e){console.warn("THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)}Zd("renderOutput",Ty);class wy extends zd{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 s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),n=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(n.name,r,s);return Vf(this).build(e,s)}return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}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 Sy=(e,t)=>wp(new wy(e,t)),My=e=>Sy("uv"+(e>0?e:""),"vec2");class Ay extends zd{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const Ny=Ap(Ay);class Cy extends cm{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Ed.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const Ry=Ap(Cy);class Ey extends cm{static get type(){return"TextureNode"}constructor(e,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=Ed.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===Be?"uvec4":this.value.type===Ee?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return My(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=dm(this.value.matrix)),this._matrixUniform.mul(Wp(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Ed.FRAME:Ed.NONE,this}setupUV(e,t){const s=this.value;return!e.isFlipY()||!0!==s.isRenderTargetTexture&&!0!==s.isFramebufferTexture&&!0!==s.isDepthTexture||(t=this.sampler?t.flipY():t.setY(Op(Ny(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this)),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}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,s,i,r,n,o,a){const h=this.value;let u;return u=i?e.generateTextureLevel(h,t,s,i,n):r?e.generateTextureBias(h,t,s,r,n):a?e.generateTextureGrad(h,t,s,a,n):o?e.generateTextureCompare(h,t,s,o,n):!1===this.sampler?e.generateTextureLoad(h,t,s,n):e.generateTexture(h,t,s,n),u}generate(e,t){const s=e.getNodeProperties(this),i=this.value;if(!i||!0!==i.isTexture)throw new Error("TextureNode: Need a three.js texture.");const r=super.generate(e,"property");if("sampler"===t)return r+"_sampler";if(e.isReference(t))return r;{const n=e.getDataFromNode(this);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:i,biasNode:a,compareNode:h,depthNode:u,gradNode:l}=s,c=this.generateUV(e,t),d=i?i.build(e,"float"):null,p=a?a.build(e,"float"):null,m=u?u.build(e,"int"):null,g=h?h.build(e,"float"):null,f=l?[l[0].build(e,"vec2"),l[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);o=e.getPropertyName(y);const x=this.generateSnippet(e,r,c,d,p,m,g,f);e.addLineFlowCode(`${o} = ${x}`,this),n.snippet=x,n.propertyName=o}let a=o;const h=this.getNodeType(e);return e.needsToWorkingColorSpace(i)&&(a=Xf(yy(a,h),i.colorSpace).setup(e).build(e,h)),e.format(a,h,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){const t=this.clone();return t.uvNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}blur(e){const t=this.clone();return t.biasNode=wp(e).mul(Ry(t)),t.referenceNode=this.getSelf(),wp(t)}level(e){const t=this.clone();return t.levelNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}size(e){return Ny(this,e)}bias(e){const t=this.clone();return t.biasNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}compare(e){const t=this.clone();return t.compareNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}grad(e,t){const s=this.clone();return s.gradNode=[wp(e),wp(t)],s.referenceNode=this.getSelf(),wp(s)}depth(e){const t=this.clone();return t.depthNode=wp(e),t.referenceNode=this.getSelf(),wp(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}}const By=Ap(Ey),Iy=(...e)=>By(...e).setSampler(!1),Py=e=>(!0===e.isNode?e:By(e)).convert("sampler"),Fy=dm("float").label("cameraNear").setGroup(um).onRenderUpdate((({camera:e})=>e.near)),Uy=dm("float").label("cameraFar").setGroup(um).onRenderUpdate((({camera:e})=>e.far)),Oy=dm("mat4").label("cameraProjectionMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.projectionMatrix)),zy=dm("mat4").label("cameraProjectionMatrixInverse").setGroup(um).onRenderUpdate((({camera:e})=>e.projectionMatrixInverse)),Ly=dm("mat4").label("cameraViewMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.matrixWorldInverse)),Vy=dm("mat4").label("cameraWorldMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.matrixWorld)),Dy=dm("mat3").label("cameraNormalMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.normalMatrix)),ky=dm(new Ai).label("cameraPosition").setGroup(um).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld)));class Gy extends zd{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Ed.OBJECT,this._uniformNode=new cm(null)}getNodeType(){const e=this.scope;return e===Gy.WORLD_MATRIX?"mat4":e===Gy.POSITION||e===Gy.VIEW_POSITION||e===Gy.DIRECTION||e===Gy.SCALE?"vec3":void 0}update(e){const t=this.object3d,s=this._uniformNode,i=this.scope;if(i===Gy.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Gy.POSITION)s.value=s.value||new Ai,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Gy.SCALE)s.value=s.value||new Ai,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Gy.DIRECTION)s.value=s.value||new Ai,t.getWorldDirection(s.value);else if(i===Gy.VIEW_POSITION){const i=e.camera;s.value=s.value||new Ai,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}}generate(e){const t=this.scope;return t===Gy.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t!==Gy.POSITION&&t!==Gy.VIEW_POSITION&&t!==Gy.DIRECTION&&t!==Gy.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Gy.WORLD_MATRIX="worldMatrix",Gy.POSITION="position",Gy.SCALE="scale",Gy.VIEW_POSITION="viewPosition",Gy.DIRECTION="direction";const Wy=Ap(Gy,Gy.DIRECTION),jy=Ap(Gy,Gy.WORLD_MATRIX),Hy=Ap(Gy,Gy.POSITION),qy=Ap(Gy,Gy.SCALE),$y=Ap(Gy,Gy.VIEW_POSITION);class Xy extends Gy{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Yy=Np(Xy,Xy.DIRECTION),Zy=Np(Xy,Xy.WORLD_MATRIX),Jy=Np(Xy,Xy.POSITION),Ky=Np(Xy,Xy.SCALE),Qy=Np(Xy,Xy.VIEW_POSITION),ex=dm(new Zs).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),tx=dm(new sr).onObjectUpdate((({object:e},t)=>t.value.copy(e.matrixWorld).invert())),sx=Ly.mul(Zy).toVar("modelViewMatrix"),ix=Cp((e=>(e.context.isHighPrecisionModelViewMatrix=!0,dm("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highPrecisionModelViewMatrix"),rx=Cp((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return dm("mat3").onObjectUpdate((({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highPrecisionModelNormalMatrix"),nx=Sy("position","vec3"),ox=nx.varying("positionLocal"),ax=nx.varying("positionPrevious"),hx=Zy.mul(ox).xyz.varying("v_positionWorld"),ux=ox.transformDirection(Zy).varying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),lx=sx.mul(ox).xyz.varying("v_positionView"),cx=lx.negate().varying("v_positionViewDirection").normalize().toVar("positionViewDirection");class dx extends zd{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Us&&s.side===d?"false":e.getFrontFacing()}}const px=Np(dx),mx=Up(px).mul(2).sub(1),gx=Sy("normal","vec3"),fx=Cp((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('TSL.NormalNode: Vertex attribute "normal" not found on geometry.'),Wp(0,1,0)):gx),"vec3").once()().toVar("normalLocal"),yx=lx.dFdx().cross(lx.dFdy()).normalize().toVar("normalFlat"),xx=Cp((e=>{let t;return t=!0===e.material.flatShading?yx:Vf(Sx(fx),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),bx=Vf(xx.transformDirection(Ly),"v_normalWorld").normalize().toVar("normalWorld"),vx=Cp((e=>e.context.setupNormal()),"vec3").once()().mul(mx).toVar("transformedNormalView"),Tx=vx.transformDirection(Ly).toVar("transformedNormalWorld"),_x=Cp((e=>e.context.setupClearcoatNormal()),"vec3").once()().mul(mx).toVar("transformedClearcoatNormalView"),wx=Cp((([e,t=Zy])=>{const s=Kp(t),i=e.div(Wp(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz})),Sx=Cp((([e],t)=>{const s=t.renderer.nodes.modelNormalViewMatrix;if(null!==s)return s.transformDirection(e);const i=ex.mul(e);return Ly.transformDirection(i)})),Mx=dm(0).onReference((({material:e})=>e)).onRenderUpdate((({material:e})=>e.refractionRatio)),Ax=cx.negate().reflect(vx),Nx=cx.negate().refract(vx,Mx),Cx=Ax.transformDirection(Ly).toVar("reflectVector"),Rx=Nx.transformDirection(Ly).toVar("reflectVector");class Ex extends Ey{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===he?Cx:e.mapping===ue?Rx:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),Wp(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==Os&&s.isRenderTargetTexture?t:Wp(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const Bx=Ap(Ex);class Ix extends cm{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Px=(e,t,s)=>wp(new Ix(e,t,s));class Fx extends Ld{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType();return e.format(t,"vec4",s)}}class Ux extends Ix{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null,"vec4"),this.array=e,this.elementType=t,this._elementType=null,this._elementLength=0,this.updateType=Ed.RENDER,this.isArrayBufferNode=!0}getElementType(){return this.elementType||this._elementType}getElementLength(){return this._elementLength}update(){const{array:e,value:t}=this,s=this.getElementLength(),i=this.getElementType();if(1===s)for(let s=0;swp(new Ux(e,t)),zx=(e,t)=>(console.warn("TSL.UniformArrayNode: uniforms() has been renamed to uniformArray()."),wp(new Ux(e,t)));class Lx extends Ld{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),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class Vx extends zd{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=Ed.OBJECT}element(e){return wp(new Lx(this,wp(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Px(null,e,this.count):Array.isArray(this.getValueFromReference())?Ox(null,e):"texture"===e?By(null):"cubeTexture"===e?Bx(null):dm(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;ewp(new Vx(e,t,s)),kx=(e,t,s,i)=>wp(new Vx(e,t,i,s));class Gx extends Vx{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Wx=(e,t,s)=>wp(new Gx(e,t,s)),jx=Cp((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Sy("tangent","vec4"))))(),Hx=jx.xyz.toVar("tangentLocal"),qx=sx.mul($p(Hx,0)).xyz.varying("v_tangentView").normalize().toVar("tangentView"),$x=qx.transformDirection(Ly).varying("v_tangentWorld").normalize().toVar("tangentWorld"),Xx=qx.toVar("transformedTangentView"),Yx=Xx.transformDirection(Ly).normalize().toVar("transformedTangentWorld"),Zx=e=>e.mul(jx.w).xyz,Jx=Vf(Zx(gx.cross(jx)),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Kx=Vf(Zx(fx.cross(Hx)),"v_bitangentLocal").normalize().toVar("bitangentLocal"),Qx=Vf(Zx(xx.cross(qx)),"v_bitangentView").normalize().toVar("bitangentView"),eb=Vf(Zx(bx.cross($x)),"v_bitangentWorld").normalize().toVar("bitangentWorld"),tb=Zx(vx.cross(Xx)).normalize().toVar("transformedBitangentView"),sb=tb.transformDirection(Ly).normalize().toVar("transformedBitangentWorld"),ib=Kp(qx,Qx,xx),rb=cx.mul(ib),nb=(e,t)=>e.sub(rb.mul(t)),ob=(()=>{let e=Em.cross(cx);return e=e.cross(Em).normalize(),e=vf(e,vx,Cm.mul(xm.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),ab=Cp((e=>{const{eye_pos:t,surf_norm:s,mapN:i,uv:r}=e,n=t.dFdx(),o=t.dFdy(),a=r.dFdx(),h=r.dFdy(),u=s,l=o.cross(u),c=u.cross(n),d=l.mul(a.x).add(c.mul(h.x)),p=l.mul(a.y).add(c.mul(h.y)),m=d.dot(d).max(p.dot(p)),g=mx.mul(m.inverseSqrt());return Ym(d.mul(i.x,g),p.mul(i.y,g),u.mul(i.z)).normalize()}));class hb extends Dd{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:s}=this;let i=this.node.mul(2).sub(1);null!==s&&(i=Wp(i.xy.mul(s),i.z));let r=null;if(1===t)r=Sx(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?ib.mul(i).normalize():ab({eye_pos:lx,surf_norm:xx,mapN:i,uv:My()})}return r}}const ub=Ap(hb),lb=Cp((({textureNode:e,bumpScale:t})=>{const s=t=>e.cache().context({getUV:e=>t(e.uvNode||My()),forceUVContext:!0}),i=Up(s((e=>e)));return Vp(Up(s((e=>e.add(e.dFdx())))).sub(i),Up(s((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),cb=Cp((e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,o=t.dFdy().normalize().cross(n),a=n.cross(r),h=r.dot(o).mul(mx),u=h.sign().mul(i.x.mul(o).add(i.y.mul(a)));return h.abs().mul(s).sub(u).normalize()}));class db extends Dd{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=lb({textureNode:this.textureNode,bumpScale:e});return cb({surf_pos:lx,surf_norm:xx,dHdxy:t})}}const pb=Ap(db),mb=new Map;class gb extends zd{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=mb.get(e);return void 0===s&&(s=Wx(e,t),mb.set(e,s)),s}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,s=this.scope;let i=null;if(s===gb.COLOR){const e=void 0!==t.color?this.getColor(s):Wp();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===gb.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===gb.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Up(1);else if(s===gb.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularMap?e.mul(this.getTexture(s).a):e}else if(s===gb.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===gb.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===gb.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===gb.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(s)):r}else if(s===gb.NORMAL)t.normalMap?(i=ub(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?pb(this.getTexture("bump").r,this.getFloat("bumpScale")):xx;else if(s===gb.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===gb.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===gb.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?ub(this.getTexture(s),this.getCache(s+"Scale","vec2")):xx;else if(s===gb.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===gb.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(.07,1)}else if(s===gb.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=Jp(Qb.x,Qb.y,Qb.y.negate(),Qb.x).mul(e.rg.mul(2).sub(Vp(1)).normalize().mul(e.b))}else i=Qb;else if(s===gb.IRIDESCENCE_THICKNESS){const e=Dx("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Dx("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===gb.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===gb.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===gb.IOR)i=this.getFloat(s);else if(s===gb.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===gb.AO_MAP)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}gb.ALPHA_TEST="alphaTest",gb.COLOR="color",gb.OPACITY="opacity",gb.SHININESS="shininess",gb.SPECULAR="specular",gb.SPECULAR_STRENGTH="specularStrength",gb.SPECULAR_INTENSITY="specularIntensity",gb.SPECULAR_COLOR="specularColor",gb.REFLECTIVITY="reflectivity",gb.ROUGHNESS="roughness",gb.METALNESS="metalness",gb.NORMAL="normal",gb.CLEARCOAT="clearcoat",gb.CLEARCOAT_ROUGHNESS="clearcoatRoughness",gb.CLEARCOAT_NORMAL="clearcoatNormal",gb.EMISSIVE="emissive",gb.ROTATION="rotation",gb.SHEEN="sheen",gb.SHEEN_ROUGHNESS="sheenRoughness",gb.ANISOTROPY="anisotropy",gb.IRIDESCENCE="iridescence",gb.IRIDESCENCE_IOR="iridescenceIOR",gb.IRIDESCENCE_THICKNESS="iridescenceThickness",gb.IOR="ior",gb.TRANSMISSION="transmission",gb.THICKNESS="thickness",gb.ATTENUATION_DISTANCE="attenuationDistance",gb.ATTENUATION_COLOR="attenuationColor",gb.LINE_SCALE="scale",gb.LINE_DASH_SIZE="dashSize",gb.LINE_GAP_SIZE="gapSize",gb.LINE_WIDTH="linewidth",gb.LINE_DASH_OFFSET="dashOffset",gb.POINT_WIDTH="pointWidth",gb.DISPERSION="dispersion",gb.LIGHT_MAP="light",gb.AO_MAP="ao";const fb=Np(gb,gb.ALPHA_TEST),yb=Np(gb,gb.COLOR),xb=Np(gb,gb.SHININESS),bb=Np(gb,gb.EMISSIVE),vb=Np(gb,gb.OPACITY),Tb=Np(gb,gb.SPECULAR),_b=Np(gb,gb.SPECULAR_INTENSITY),wb=Np(gb,gb.SPECULAR_COLOR),Sb=Np(gb,gb.SPECULAR_STRENGTH),Mb=Np(gb,gb.REFLECTIVITY),Ab=Np(gb,gb.ROUGHNESS),Nb=Np(gb,gb.METALNESS),Cb=Np(gb,gb.NORMAL).context({getUV:null}),Rb=Np(gb,gb.CLEARCOAT),Eb=Np(gb,gb.CLEARCOAT_ROUGHNESS),Bb=Np(gb,gb.CLEARCOAT_NORMAL).context({getUV:null}),Ib=Np(gb,gb.ROTATION),Pb=Np(gb,gb.SHEEN),Fb=Np(gb,gb.SHEEN_ROUGHNESS),Ub=Np(gb,gb.ANISOTROPY),Ob=Np(gb,gb.IRIDESCENCE),zb=Np(gb,gb.IRIDESCENCE_IOR),Lb=Np(gb,gb.IRIDESCENCE_THICKNESS),Vb=Np(gb,gb.TRANSMISSION),Db=Np(gb,gb.THICKNESS),kb=Np(gb,gb.IOR),Gb=Np(gb,gb.ATTENUATION_DISTANCE),Wb=Np(gb,gb.ATTENUATION_COLOR),jb=Np(gb,gb.LINE_SCALE),Hb=Np(gb,gb.LINE_DASH_SIZE),qb=Np(gb,gb.LINE_GAP_SIZE),$b=Np(gb,gb.LINE_WIDTH),Xb=Np(gb,gb.LINE_DASH_OFFSET),Yb=Np(gb,gb.POINT_WIDTH),Zb=Np(gb,gb.DISPERSION),Jb=Np(gb,gb.LIGHT_MAP),Kb=Np(gb,gb.AO_MAP),Qb=dm(new Ys).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))}));class ev extends Dd{static get type(){return"ModelViewProjectionNode"}constructor(e=null){super("vec4"),this.positionNode=e}setup(e){if("fragment"===e.shaderStage)return Vf(e.context.mvp);const t=this.positionNode||ox,s=e.renderer.nodes.modelViewMatrix||sx;return Oy.mul(s).mul(t)}}const tv=Ap(ev);class sv extends zd{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isInstanceIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i,r;if(s===sv.VERTEX)i=e.getVertexIndex();else if(s===sv.INSTANCE)i=e.getInstanceIndex();else if(s===sv.DRAW)i=e.getDrawIndex();else if(s===sv.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===sv.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==sv.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Vf(this).build(e,t)}return r}}sv.VERTEX="vertex",sv.INSTANCE="instance",sv.SUBGROUP="subgroup",sv.INVOCATION_LOCAL="invocationLocal",sv.INVOCATION_SUBGROUP="invocationSubgroup",sv.DRAW="draw";const iv=Np(sv,sv.VERTEX),rv=Np(sv,sv.INSTANCE),nv=Np(sv,sv.SUBGROUP),ov=Np(sv,sv.INVOCATION_SUBGROUP),av=Np(sv,sv.INVOCATION_LOCAL),hv=Np(sv,sv.DRAW);class uv extends zd{static get type(){return"InstanceNode"}constructor(e){super("void"),this.instanceMesh=e,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Ed.FRAME,this.buffer=null,this.bufferColor=null}setup(e){let t=this.instanceMatrixNode,s=this.instanceColorNode;const i=this.instanceMesh;if(null===t){const e=i.instanceMatrix;if(i.count<=1e3)t=Px(e.array,"mat4",Math.max(i.count,1)).element(rv);else{const s=new _c(e.array,16,1);this.buffer=s;const i=e.usage===Ms?oy:ny,r=[i(s,"vec4",16,0),i(s,"vec4",16,4),i(s,"vec4",16,8),i(s,"vec4",16,12)];t=Qp(...r)}this.instanceMatrixNode=t}const r=i.instanceColor;if(r&&null===s){const e=new zo(r.array,3),t=r.usage===Ms?oy:ny;this.bufferColor=e,s=Wp(t(e,"vec3",3,0)),this.instanceColorNode=s}const n=t.mul(ox).xyz;if(ox.assign(n),e.hasGeometryAttribute("normal")){const e=wx(fx,t);fx.assign(e)}null!==this.instanceColorNode&&gm("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMesh.instanceMatrix.usage!==Ms&&null!=this.buffer&&this.instanceMesh.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMesh.instanceMatrix.version),this.instanceMesh.instanceColor&&this.instanceMesh.instanceColor.usage!==Ms&&null!=this.bufferColor&&this.instanceMesh.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceMesh.instanceColor.version)}}const lv=Ap(uv);class cv extends zd{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=rv:this.batchingIdNode=hv);const t=Cp((([e])=>{const t=Ny(Iy(this.batchMesh._indirectTexture),0),s=Op(e).modInt(Op(t)),i=Op(e).div(Op(t));return Iy(this.batchMesh._indirectTexture,Dp(s,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(Op(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=Ny(Iy(i),0),n=Up(s).mul(4).toInt().toVar(),o=n.modInt(r),a=n.div(Op(r)),h=Qp(Iy(i,Dp(o,a)),Iy(i,Dp(o.add(1),a)),Iy(i,Dp(o.add(2),a)),Iy(i,Dp(o.add(3),a))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Cp((([e])=>{const t=Ny(Iy(u),0).x,s=e,i=s.modInt(t),r=s.div(t);return Iy(u,Dp(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);gm("vec3","vBatchColor").assign(t)}const l=Kp(h);ox.assign(h.mul(ox));const c=fx.div(Wp(l[0].dot(l[0]),l[1].dot(l[1]),l[2].dot(l[2]))),d=l.mul(c).xyz;fx.assign(d),e.hasGeometryAttribute("tangent")&&Hx.mulAssign(l)}}const dv=Ap(cv),pv=new WeakMap;class mv extends zd{static get type(){return"SkinningNode"}constructor(e,t=!1){let s,i,r;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=Ed.OBJECT,this.skinIndexNode=Sy("skinIndex","uvec4"),this.skinWeightNode=Sy("skinWeight","vec4"),t?(s=Dx("bindMatrix","mat4"),i=Dx("bindMatrixInverse","mat4"),r=kx("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(s=dm(e.bindMatrix,"mat4"),i=dm(e.bindMatrixInverse,"mat4"),r=Px(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=s,this.bindMatrixInverseNode=i,this.boneMatricesNode=r,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=ox){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),u=e.element(s.w),l=r.mul(t),c=Ym(o.mul(i.x).mul(l),a.mul(i.y).mul(l),h.mul(i.z).mul(l),u.mul(i.w).mul(l));return n.mul(c).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=fx){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),u=e.element(s.w);let l=Ym(i.x.mul(o),i.y.mul(a),i.z.mul(h),i.w.mul(u));return l=n.mul(l).mul(r),l.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=kx("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,ax)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")}setup(e){this.needsPreviousBoneMatrices(e)&&ax.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(ox.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();fx.assign(t),e.hasGeometryAttribute("tangent")&&Hx.assign(t)}}generate(e,t){if("void"!==t)return ox.build(e,t)}update(e){const t=(this.useReference?e.object:this.skinnedMesh).skeleton;pv.get(t)!==e.frameId&&(pv.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const gv=e=>wp(new mv(e)),fv=e=>wp(new mv(e,!0));class yv extends zd{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt()+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;eNumber(n)?">=":"<"));const l={start:r,end:n,condition:h},c=l.start,d=l.end;let p="",m="",g="";u||(u="int"===a||"uint"===a?h.includes("<")?"++":"--":h.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(a,o)+" = "+c,m+=o+" "+h+" "+d,g+=o+" "+u;const f=`for ( ${p}; ${m}; ${g} )`;e.addFlowCode((0===t?"\n":"")+e.tab+f+" {\n\n").addFlowTab()}const r=i.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,s=this.params.length-1;twp(new yv(Mp(e,"int"))).append(),bv=()=>yy("continue").append(),vv=()=>yy("break").append(),Tv=(...e)=>(console.warn("TSL.LoopNode: loop() has been renamed to Loop()."),xv(...e)),_v=new WeakMap,wv=new xi,Sv=Cp((({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=Op(iv).mul(s).add(n),a=o.div(i),h=o.sub(a.mul(i));return Iy(e,Dp(h,a)).depth(r).mul(t)}));class Mv extends zd{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=dm(1),this.updateType=Ed.OBJECT}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,n=void 0!==r?r.length:0,{texture:o,stride:a,size:h}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,n=void 0!==r?r.length:0;let o=_v.get(e);if(void 0===o||o.count!==n){void 0!==o&&o.texture.dispose();const a=e.morphAttributes.position||[],h=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let l=0;!0===t&&(l=1),!0===s&&(l=2),!0===i&&(l=3);let c=e.attributes.position.count*l,d=1;const p=4096;c>p&&(d=Math.ceil(c/p),c=p);const m=new Float32Array(c*d*4*n),g=new Ti(m,c,d,n);g.type=Ie,g.needsUpdate=!0;const f=4*l;for(let x=0;x{const t=Up(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Iy(this.mesh.morphTexture,Dp(Op(e).add(1),Op(rv))).r):t.assign(Dx("morphTargetInfluences","float").element(e).toVar()),!0===s&&ox.addAssign(Sv({bufferMap:o,influence:t,stride:a,width:u,depth:e,offset:Op(0)})),!0===i&&fx.addAssign(Sv({bufferMap:o,influence:t,stride:a,width:u,depth:e,offset:Op(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 Av=Ap(Mv);class Nv extends zd{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}generate(){console.warn("Abstract function.")}}class Cv extends Nv{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Rv extends If{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:Wp().toVar("directDiffuse"),directSpecular:Wp().toVar("directSpecular"),indirectDiffuse:Wp().toVar("indirectDiffuse"),indirectSpecular:Wp().toVar("indirectSpecular")};return{radiance:Wp().toVar("radiance"),irradiance:Wp().toVar("irradiance"),iblIrradiance:Wp().toVar("iblIrradiance"),ambientOcclusion:Up(1).toVar("ambientOcclusion"),reflectedLight:s,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 Ev=Ap(Rv);class Bv extends Nv{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Iv,Pv;class Fv extends zd{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Fv.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Ed.NONE;return this.scope!==Fv.SIZE&&this.scope!==Fv.VIEWPORT||(e=Ed.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Fv.VIEWPORT?null!==t?Pv.copy(t.viewport):(e.getViewport(Pv),Pv.multiplyScalar(e.getPixelRatio())):null!==t?(Iv.width=t.width,Iv.height=t.height):e.getDrawingBufferSize(Iv)}setup(){const e=this.scope;let t=null;return t=e===Fv.SIZE?dm(Iv||(Iv=new Ys)):e===Fv.VIEWPORT?dm(Pv||(Pv=new xi)):Vp(zv.div(Ov)),t}generate(e){if(this.scope===Fv.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Ov).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Fv.COORDINATE="coordinate",Fv.VIEWPORT="viewport",Fv.SIZE="size",Fv.UV="uv";const Uv=Np(Fv,Fv.UV),Ov=Np(Fv,Fv.SIZE),zv=Np(Fv,Fv.COORDINATE),Lv=Np(Fv,Fv.VIEWPORT),Vv=Lv.zw,Dv=zv.sub(Lv.xy),kv=Dv.div(Vv),Gv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.'),Ov)),"vec2").once()(),Wv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.'),Uv)),"vec2").once()(),jv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.'),Uv.flipY())),"vec2").once()(),Hv=new Ys;class qv extends Ey{static get type(){return"ViewportTextureNode"}constructor(e=Uv,t=null,s=null){null===s&&((s=new Wa).minFilter=Se),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Ed.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Hv);const s=this.value;s.image.width===Hv.width&&s.image.height===Hv.height||(s.image.width=Hv.width,s.image.height=Hv.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 $v=Ap(qv),Xv=Ap(qv,null,null,{generateMipmaps:!0});let Yv=null;class Zv extends qv{static get type(){return"ViewportDepthTextureNode"}constructor(e=Uv,t=null){null===Yv&&(Yv=new Xa),super(e,t,Yv)}}const Jv=Ap(Zv);class Kv extends zd{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===Kv.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===Kv.DEPTH_BASE)null!==s&&(i=rT().assign(s));else if(t===Kv.DEPTH)i=e.isPerspectiveCamera?tT(lx.z,Fy,Uy):Qv(lx.z,Fy,Uy);else if(t===Kv.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=sT(s,Fy,Uy);i=Qv(e,Fy,Uy)}else i=s;else i=Qv(lx.z,Fy,Uy);return i}}Kv.DEPTH_BASE="depthBase",Kv.DEPTH="depth",Kv.LINEAR_DEPTH="linearDepth";const Qv=(e,t,s)=>e.add(t).div(t.sub(s)),eT=(e,t,s)=>t.sub(s).mul(e).sub(t),tT=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),sT=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),iT=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Eg(e.div(t).add(1)),r=Eg(s.div(t).add(1));return i.div(r)},rT=Ap(Kv,Kv.DEPTH_BASE),nT=Np(Kv,Kv.DEPTH),oT=Ap(Kv,Kv.LINEAR_DEPTH),aT=oT(Jv());nT.assign=e=>rT(e);class hT extends zd{static get type(){return"ClippingNode"}constructor(e=hT.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{localClipIntersection:s,localClippingCount:i,globalClippingCount:r}=t,n=r+i,o=s?n-i:n;return this.scope===hT.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(t.planes,n,o):this.setupDefault(t.planes,n,o)}setupAlphaToCoverage(e,t,s){return Cp((()=>{const i=Ox(e),r=mm("float","distanceToPlane"),n=mm("float","distanceToGradient"),o=mm("float","clipOpacity");let a;if(o.assign(1),xv(s,(({i:e})=>{a=i.element(e),r.assign(lx.dot(a.xyz).negate().add(a.w)),n.assign(r.fwidth().div(2)),o.mulAssign(Sf(n.negate(),n,r)),o.equal(0).discard()})),s{a=i.element(t),r.assign(lx.dot(a.xyz).negate().add(a.w)),n.assign(r.fwidth().div(2)),e.mulAssign(Sf(n.negate(),n,r).oneMinus())})),o.mulAssign(e.oneMinus())}fm.a.mulAssign(o),fm.a.equal(0).discard()}))()}setupDefault(e,t,s){return Cp((()=>{const i=Ox(e);let r;if(xv(s,(({i:e})=>{r=i.element(e),lx.dot(r.xyz).greaterThan(r.w).discard()})),s{r=i.element(t),e.assign(lx.dot(r.xyz).greaterThan(r.w).and(e))})),e.discard()}}))()}}hT.ALPHA_TO_COVERAGE="alphaToCoverage",hT.DEFAULT="default";class uT extends Jr{static get type(){return"NodeMaterial"}constructor(){super(),this.isNodeMaterial=!0,this.type=this.constructor.type,this.forceSinglePass=!1,this.fog=!0,this.lights=!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.positionNode=null,this.geometryNode=null,this.depthNode=null,this.shadowNode=null,this.shadowPositionNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+_d(this)}build(e){this.setup(e)}setupObserver(e){return new yd(e)}setup(e){let t;e.context.setupNormal=()=>this.setupNormal(e),e.addStack(),e.stack.outputNode=this.vertexNode||this.setupPosition(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const s=this.setupClipping(e);if(!0===this.depthWrite&&this.setupDepth(e),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==s&&e.stack.add(s);const r=$p(i,fm.a).max(0);t=this.setupOutput(e,r),Fm.assign(t),null!==this.outputNode&&(t=this.outputNode);if(null!==e.renderer.getRenderTarget()){const s=e.renderer.getMRT(),i=this.mrtNode;null!==s?(t=s,null!==i&&(t=s.merge(i))):null!==i&&(t=i)}}else{let s=this.fragmentNode;!0!==s.isOutputStructNode&&(s=$p(s)),t=this.setupOutput(e,s)}e.stack.outputNode=t,e.addFlow("fragment",e.removeStack()),e.monitor=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{globalClippingCount:t,localClippingCount:s}=e.clippingContext;let i=null;if(t||s){const t=e.renderer.samples;this.alphaToCoverage&&t>1?i=wp(new hT(hT.ALPHA_TO_COVERAGE)):e.stack.add(wp(new hT))}return i}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=s.isPerspectiveCamera?iT(tv().w,Fy,Uy):Qv(lx.z,Fy,Uy))}null!==i&&nT.assign(i).append()}setupPosition(e){const{object:t}=e,s=t.geometry;if(e.addStack(),(s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Av(t).append(),!0===t.isSkinnedMesh&&fv(t).append(),this.displacementMap){const e=Wx("displacementMap","texture"),t=Wx("displacementScale","float"),s=Wx("displacementBias","float");ox.addAssign(fx.normalize().mul(e.x.mul(t).add(s)))}t.isBatchedMesh&&dv(t).append(),t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&lv(t).append(),null!==this.positionNode&&ox.assign(this.positionNode);const i=tv();return e.context.vertex=e.removeStack(),e.context.mvp=i,i}setupDiffuseColor({object:e,geometry:t}){let s=this.colorNode?$p(this.colorNode):yb;if(!0===this.vertexColors&&t.hasAttribute("color")&&(s=$p(s.xyz.mul(Sy("color","vec3")),s.a)),e.instanceColor){s=gm("vec3","vInstanceColor").mul(s)}if(e.isBatchedMesh&&e._colorsTexture){s=gm("vec3","vBatchColor").mul(s)}fm.assign(s);const i=this.opacityNode?Up(this.opacityNode):vb;if(fm.a.assign(fm.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?Up(this.alphaTestNode):fb;fm.a.lessThanEqual(e).discard()}!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&fm.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Wp(0):fm.rgb}setupNormal(){return this.normalNode?Wp(this.normalNode):Cb}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Wx("envMap","cubeTexture"):Wx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Bv(Jb)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Kb;t.push(new Cv(e))}let r=this.lightsNode||e.lightsNode;return t.length>0&&(r=e.renderer.lighting.createNode([...r.getLights(),...t])),r}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:r}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let o=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e);o=Ev(n,t,s,i)}else null!==s&&(o=Wp(null!==i?vf(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(ym.assign(Wp(r||bb)),o=o.add(ym)),o}setupOutput(e,t){if(!0===this.fog){const s=e.fogNode;s&&(t=$p(s.mix(t.rgb,s.colorNode),t.a))}return t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.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 s=Jr.prototype.toJSON.call(this,e),i=wd(this);s.inputNodes={};for(const{property:t,childNode:r}of i)s.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),n=r(e.nodes);t.length>0&&(s.textures=t),i.length>0&&(s.images=i),n.length>0&&(s.nodes=n)}return s}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.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.shadowNode=e.shadowNode,this.shadowPositionNode=e.shadowPositionNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const lT=new Fa;class cT extends uT{static get type(){return"InstancedPointsNodeMaterial"}constructor(e={}){super(),this.lights=!1,this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.pointWidth=1,this.pointColorNode=null,this.pointWidthNode=null,this.setDefaultValues(lT),this.setValues(e)}setup(e){this.setupShaders(e),super.setup(e)}setupShaders({renderer:e}){const t=this.alphaToCoverage,s=this.useColor;this.vertexNode=Cp((()=>{const e=Sy("instancePosition").xyz,t=$p(sx.mul($p(e,1))),s=Lv.z.div(Lv.w),i=Oy.mul(t),r=nx.xy.toVar();return r.mulAssign(this.pointWidthNode?this.pointWidthNode:Yb),r.assign(r.div(Lv.z)),r.y.assign(r.y.mul(s)),r.assign(r.mul(i.w)),i.addAssign($p(r,0,0)),i}))(),this.fragmentNode=Cp((()=>{const i=Up(1).toVar(),r=bf(My().mul(2).sub(1));if(t&&e.samples>1){const e=Up(r.fwidth()).toVar();i.assign(Sf(e.oneMinus(),e.add(1),r).oneMinus())}else r.greaterThan(1).discard();let n;if(this.pointColorNode)n=this.pointColorNode;else if(s){n=Sy("instanceColor").mul(yb)}else n=yb;return i.mulAssign(vb),$p(n,i)}))()}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.needsUpdate=!0)}}const dT=new va;class pT extends uT{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.lights=!1,this.setDefaultValues(dT),this.setValues(e)}}const mT=new Eu;class gT extends uT{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.lights=!1,this.setDefaultValues(mT),this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode,t=this.dashScaleNode?Up(this.dashScaleNode):jb,s=this.dashSizeNode?Up(this.dashSizeNode):Hb,i=this.dashSizeNode?Up(this.dashGapNode):qb;Um.assign(s),Om.assign(i);const r=Vf(Sy("lineDistance").mul(t));(e?r.add(e):r).mod(Um.add(Om)).greaterThan(Um).discard()}}const fT=new Eu;class yT extends uT{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.lights=!1,this.setDefaultValues(fT),this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.useDash=e.dashed,this.useWorldUnits=!1,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setup(e){this.setupShaders(e),super.setup(e)}setupShaders({renderer:e}){const t=this.alphaToCoverage,s=this.useColor,i=this.dashed,r=this.worldUnits,n=Cp((({start:e,end:t})=>{const s=Oy.element(2).element(2),i=Oy.element(3).element(2).mul(-.5).div(s).sub(e.z).div(t.z.sub(e.z));return $p(vf(e.xyz,t.xyz,i),t.w)})).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=Cp((()=>{const e=Sy("instanceStart"),t=Sy("instanceEnd"),s=$p(sx.mul($p(e,1))).toVar("start"),o=$p(sx.mul($p(t,1))).toVar("end");r&&(gm("vec3","worldStart").assign(s.xyz),gm("vec3","worldEnd").assign(o.xyz));const a=Lv.z.div(Lv.w),h=Oy.element(2).element(3).equal(-1);Ip(h,(()=>{Ip(s.z.lessThan(0).and(o.z.greaterThan(0)),(()=>{o.assign(n({start:s,end:o}))})).ElseIf(o.z.lessThan(0).and(s.z.greaterThanEqual(0)),(()=>{s.assign(n({start:o,end:s}))}))}));const u=Oy.mul(s),l=Oy.mul(o),c=u.xyz.div(u.w),d=l.xyz.div(l.w),p=d.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(a)),p.assign(p.normalize());const m=$p().toVar();if(r){const e=o.xyz.sub(s.xyz).normalize(),t=vf(s.xyz,o.xyz,.5).normalize(),r=e.cross(t).normalize(),n=e.cross(r),a=gm("vec4","worldPos");a.assign(nx.y.lessThan(.5).select(s,o));const h=$b.mul(.5);a.addAssign($p(nx.x.lessThan(0).select(r.mul(h),r.mul(h).negate()),0)),i||(a.addAssign($p(nx.y.lessThan(.5).select(e.mul(h).negate(),e.mul(h)),0)),a.addAssign($p(n.mul(h),0)),Ip(nx.y.greaterThan(1).or(nx.y.lessThan(0)),(()=>{a.subAssign($p(n.mul(2).mul(h),0))}))),m.assign(Oy.mul(a));const u=Wp().toVar();u.assign(nx.y.lessThan(.5).select(c,d)),m.z.assign(u.z.mul(m.w))}else{const e=Vp(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(a)),e.x.assign(e.x.div(a)),e.assign(nx.x.lessThan(0).select(e.negate(),e)),Ip(nx.y.lessThan(0),(()=>{e.assign(e.sub(p))})).ElseIf(nx.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul($b)),e.assign(e.div(Lv.w)),m.assign(nx.y.lessThan(.5).select(u,l)),e.assign(e.mul(m.w)),m.assign(m.add($p(e,0,0)))}return m}))();const o=Cp((({p1:e,p2:t,p3:s,p4:i})=>{const r=e.sub(s),n=i.sub(s),o=t.sub(e),a=r.dot(n),h=n.dot(o),u=r.dot(o),l=n.dot(n),c=o.dot(o).mul(l).sub(h.mul(h)),d=a.mul(h).sub(u.mul(l)).div(c).clamp(),p=a.add(h.mul(d)).div(l).clamp();return Vp(d,p)}));this.fragmentNode=Cp((()=>{const n=My();if(i){const e=this.offsetNode?Up(this.offsetNodeNode):Xb,t=this.dashScaleNode?Up(this.dashScaleNode):jb,s=this.dashSizeNode?Up(this.dashSizeNode):Hb,i=this.dashSizeNode?Up(this.dashGapNode):qb;Um.assign(s),Om.assign(i);const r=Sy("instanceDistanceStart"),o=Sy("instanceDistanceEnd"),a=nx.y.lessThan(.5).select(t.mul(r),jb.mul(o)),h=Vf(a.add(Xb)),u=e?h.add(e):h;n.y.lessThan(-1).or(n.y.greaterThan(1)).discard(),u.mod(Um.add(Om)).greaterThan(Um).discard()}const a=Up(1).toVar("alpha");if(r){const s=gm("vec3","worldStart"),r=gm("vec3","worldEnd"),n=gm("vec4","worldPos").xyz.normalize().mul(1e5),h=r.sub(s),u=o({p1:s,p2:r,p3:Wp(0,0,0),p4:n}),l=s.add(h.mul(u.x)),c=n.mul(u.y),d=l.sub(c).length().div($b);if(!i)if(t&&e.samples>1){const e=d.fwidth();a.assign(Sf(e.negate().add(.5),e.add(.5),d).oneMinus())}else d.greaterThan(.5).discard()}else if(t&&e.samples>1){const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1)),s=e.mul(e).add(t.mul(t)),i=Up(s.fwidth()).toVar("dlen");Ip(n.y.abs().greaterThan(1),(()=>{a.assign(Sf(i.oneMinus(),i.add(1),s).oneMinus())}))}else Ip(n.y.abs().greaterThan(1),(()=>{const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()}));let h;if(this.lineColorNode)h=this.lineColorNode;else if(s){const e=Sy("instanceColorStart"),t=Sy("instanceColorEnd");h=nx.y.lessThan(.5).select(e,t).mul(yb)}else h=yb;return $p(h,a)}))()}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 xT=e=>wp(e).mul(.5).add(.5),bT=e=>wp(e).mul(2).sub(1),vT=new Mu;class TT extends uT{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(vT),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Up(this.opacityNode):vb;fm.assign($p(xT(vx),e))}}class _T extends Dd{static get type(){return"EquirectUVNode"}constructor(e=ux){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan2(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Vp(t,s)}}const wT=Ap(_T);class ST extends Yn{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=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 r=new Ln(5,5,5),n=wT(ux),o=new uT;o.colorNode=By(t,n,0),o.side=d,o.blending=m;const a=new On(r,o),h=new Kn;h.add(a),t.minFilter===Se&&(t.minFilter=Te);const u=new $n(1,10,this),l=e.getMRT();return e.setMRT(null),u.update(e,h),e.setMRT(l),t.minFilter=s,t.currentGenerateMipmaps=i,a.geometry.dispose(),a.material.dispose(),this}}const MT=new WeakMap;class AT extends Dd{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Bx();const t=new Xn;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Ed.RENDER}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:s[i.property];if(e&&e.isTexture){const s=e.mapping;if(s===le||s===ce){if(MT.has(e)){const t=MT.get(e);CT(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new ST(s.height);i.fromEquirectangularTexture(t,e),CT(i.texture,e.mapping),this._cubeTexture=i.texture,MT.set(e,i.texture),e.addEventListener("dispose",NT)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function NT(e){const t=e.target;t.removeEventListener("dispose",NT);const s=MT.get(t);void 0!==s&&(MT.delete(t),s.dispose())}function CT(e,t){t===le?e.mapping=he:t===ce&&(e.mapping=ue)}const RT=Ap(AT);class ET extends Nv{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=RT(this.envNode)}}class BT extends Nv{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Up(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class IT{start(){}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class PT extends IT{constructor(){super()}indirect(e,t,s){const i=e.ambientOcclusion,r=e.reflectedLight,n=s.context.irradianceLightMap;r.indirectDiffuse.assign($p(0)),n?r.indirectDiffuse.addAssign(n):r.indirectDiffuse.addAssign($p(1,1,1,0)),r.indirectDiffuse.mulAssign(i),r.indirectDiffuse.mulAssign(fm.rgb)}finish(e,t,s){const i=s.material,r=e.outgoingLight,n=s.context.environment;if(n)switch(i.combine){case 0:r.rgb.assign(vf(r.rgb,r.rgb.mul(n.rgb),Sb.mul(Mb)));break;case 1:r.rgb.assign(vf(r.rgb,n.rgb,Sb.mul(Mb)));break;case 2:r.rgb.addAssign(n.rgb.mul(Sb.mul(Mb)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",i.combine)}}}const FT=new Kr;class UT extends uT{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(FT),this.setValues(e)}setupNormal(){return xx}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new ET(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new BT(Jb)),t}setupOutgoingLight(){return fm.rgb}setupLightingModel(){return new PT}}const OT=Cp((({f0:e,f90:t,dotVH:s})=>{const i=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(i.oneMinus()).add(t.mul(i))})),zT=Cp((e=>e.diffuseColor.mul(1/Math.PI))),LT=Cp((({dotNH:e})=>Pm.mul(Up(.5)).add(1).mul(Up(1/Math.PI)).mul(e.pow(Pm)))),VT=Cp((({lightDirection:e})=>{const t=e.add(cx).normalize(),s=vx.dot(t).clamp(),i=cx.dot(t).clamp(),r=OT({f0:Bm,f90:1,dotVH:i}),n=Up(.25),o=LT({dotNH:s});return r.mul(n).mul(o)}));class DT extends PT{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=vx.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(zT({diffuseColor:fm.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(VT({lightDirection:e})).mul(Sb))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(zT({diffuseColor:fm}))),s.indirectDiffuse.mulAssign(e)}}const kT=new Au;class GT extends uT{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(kT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new ET(t):null}setupLightingModel(){return new DT(!1)}}const WT=new wu;class jT extends uT{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(WT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new ET(t):null}setupLightingModel(){return new DT}setupVariants(){const e=(this.shininessNode?Up(this.shininessNode):xb).max(1e-4);Pm.assign(e);const t=this.specularNode||Tb;Bm.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const HT=Cp((e=>{if(!1===e.geometry.hasAttribute("normal"))return Up(0);const t=xx.dFdx().abs().max(xx.dFdy().abs());return t.x.max(t.y).max(t.z)})),qT=Cp((e=>{const{roughness:t}=e,s=HT();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i})),$T=Cp((({alpha:e,dotNL:t,dotNV:s})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt()),n=s.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return Km(.5,r.add(n).max(xg))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),XT=Cp((({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const h=a.mul(Wp(e.mul(s),t.mul(i),o).length()),u=o.mul(Wp(e.mul(r),t.mul(n),a).length());return Km(.5,h.add(u)).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"}]}),YT=Cp((({alpha:e,dotNH:t})=>{const s=e.pow2(),i=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(i.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),ZT=Up(1/Math.PI),JT=Cp((({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=Wp(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),h=n.div(a);return ZT.mul(n.mul(h.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"}]}),KT=Cp((e=>{const{lightDirection:t,f0:s,f90:i,roughness:r,f:n,USE_IRIDESCENCE:o,USE_ANISOTROPY:a}=e,h=e.normalView||vx,u=r.pow2(),l=t.add(cx).normalize(),c=h.dot(t).clamp(),d=h.dot(cx).clamp(),p=h.dot(l).clamp(),m=cx.dot(l).clamp();let g,f,y=OT({f0:s,f90:i,dotVH:m});if(vp(o)&&(y=Sm.mix(y,n)),vp(a)){const e=Rm.dot(t),s=Rm.dot(cx),i=Rm.dot(l),r=Em.dot(t),n=Em.dot(cx),o=Em.dot(l);g=XT({alphaT:Nm,alphaB:u,dotTV:s,dotBV:n,dotTL:e,dotBL:r,dotNV:d,dotNL:c}),f=JT({alphaT:Nm,alphaB:u,dotNH:p,dotTH:i,dotBH:o})}else g=$T({alpha:u,dotNL:c,dotNV:d}),f=YT({alpha:u,dotNH:p});return y.mul(g).mul(f)})),QT=Cp((({roughness:e,dotNV:t})=>{const s=$p(-1,-.0275,-.572,.022),i=$p(1,.0425,1.04,-.04),r=e.mul(s).add(i),n=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return Vp(-1.04,1.04).mul(n).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),e_=Cp((e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=QT({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))})),t_=Cp((({f:e,f90:t,dotVH:s})=>{const i=s.oneMinus().saturate(),r=i.mul(i),n=i.mul(r,r).clamp(0,.9999);return e.sub(Wp(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"}]}),s_=Cp((({roughness:e,dotNH:t})=>{const s=e.pow2(),i=Up(1).div(s),r=t.pow2().oneMinus().max(.0078125);return Up(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),i_=Cp((({dotNV:e,dotNL:t})=>Up(1).div(Up(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),r_=Cp((({lightDirection:e})=>{const t=e.add(cx).normalize(),s=vx.dot(e).clamp(),i=vx.dot(cx).clamp(),r=vx.dot(t).clamp(),n=s_({roughness:wm,dotNH:r}),o=i_({dotNV:i,dotNL:s});return _m.mul(n).mul(o)})),n_=Cp((({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=Vp(s,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r})).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),o_=Cp((({f:e})=>{const t=e.length();return nf(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),a_=Cp((({v1:e,v2:t})=>{const s=e.dot(t),i=s.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),n=i.add(4.1616724).mul(i).add(3.417594).toVar(),o=r.div(n),a=s.greaterThan(0).select(o,nf(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return e.cross(t).mul(a)})).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),h_=Cp((({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:o,p3:a})=>{const h=n.sub(r).toVar(),u=a.sub(r).toVar(),l=h.cross(u),c=Wp().toVar();return Ip(l.dot(s.sub(r)).greaterThanEqual(0),(()=>{const h=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(h).negate(),l=i.mul(Kp(h,u,e).transpose()).toVar(),d=l.mul(r.sub(s)).normalize().toVar(),p=l.mul(n.sub(s)).normalize().toVar(),m=l.mul(o.sub(s)).normalize().toVar(),g=l.mul(a.sub(s)).normalize().toVar(),f=Wp(0).toVar();f.addAssign(a_({v1:d,v2:p})),f.addAssign(a_({v1:p,v2:m})),f.addAssign(a_({v1:m,v2:g})),f.addAssign(a_({v1:g,v2:d})),c.assign(Wp(o_({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"}]}),u_=1/6,l_=e=>Jm(u_,Jm(e,Jm(e,e.negate().add(3)).sub(3)).add(1)),c_=e=>Jm(u_,Jm(e,Jm(e,Jm(3,e).sub(6))).add(4)),d_=e=>Jm(u_,Jm(e,Jm(e,Jm(-3,e).add(3)).add(3)).add(1)),p_=e=>Jm(u_,pf(e,3)),m_=e=>l_(e).add(c_(e)),g_=e=>d_(e).add(p_(e)),f_=e=>Ym(-1,c_(e).div(l_(e).add(c_(e)))),y_=e=>Ym(1,p_(e).div(d_(e).add(p_(e)))),x_=(e,t,s)=>{const i=e.uvNode,r=Jm(i,t.zw).add(.5),n=Pg(r),o=Og(r),a=m_(o.x),h=g_(o.x),u=f_(o.x),l=y_(o.x),c=f_(o.y),d=y_(o.y),p=Vp(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),m=Vp(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Vp(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),f=Vp(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),y=m_(o.y).mul(Ym(a.mul(e.uv(p).level(s)),h.mul(e.uv(m).level(s)))),x=g_(o.y).mul(Ym(a.mul(e.uv(g).level(s)),h.mul(e.uv(f).level(s))));return y.add(x)},b_=Cp((([e,t=Up(3)])=>{const s=Vp(e.size(Op(t))),i=Vp(e.size(Op(t.add(1)))),r=Km(1,s),n=Km(1,i),o=x_(e,$p(r,s),Pg(t)),a=x_(e,$p(n,i),Fg(t));return Og(t).mix(o,a)})),v_=Cp((([e,t,s,i,r])=>{const n=Wp(wf(t.negate(),Ug(e),Km(1,i))),o=Wp(Hg(r[0].xyz),Hg(r[1].xyz),Hg(r[2].xyz));return Ug(n).mul(s.mul(o))})).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"}]}),T_=Cp((([e,t])=>e.mul(Tf(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),__=Xv(),w_=Cp((([e,t,s])=>{const i=__.uv(e),r=Eg(Up(Ov.x)).mul(T_(t,s));return b_(i,r)})),S_=Cp((([e,t,s])=>(Ip(s.notEqual(0),(()=>{const i=Rg(t).negate().div(s);return Ng(i.negate().mul(e))})),Wp(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),M_=Cp((([e,t,s,i,r,n,o,a,h,u,l,c,d,p,m])=>{let g,f;if(m){g=$p().toVar(),f=Wp().toVar();const r=l.sub(1).mul(m.mul(.025)),n=Wp(l.sub(r),l,l.add(r));xv({start:0,end:3},(({i:r})=>{const l=n.element(r),m=v_(e,t,c,l,a),y=o.add(m),x=u.mul(h.mul($p(y,1))),b=Vp(x.xy.div(x.w)).toVar();b.addAssign(1),b.divAssign(2),b.assign(Vp(b.x,b.y.oneMinus()));const v=w_(b,s,l);g.element(r).assign(v.element(r)),g.a.addAssign(v.a),f.element(r).assign(i.element(r).mul(S_(Hg(m),d,p).element(r)))})),g.a.divAssign(3)}else{const r=v_(e,t,c,l,a),n=o.add(r),m=u.mul(h.mul($p(n,1))),y=Vp(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Vp(y.x,y.y.oneMinus())),g=w_(y,s,l),f=i.mul(S_(Hg(r),d,p))}const y=f.rgb.mul(g.rgb),x=e.dot(t).clamp(),b=Wp(e_({dotNV:x,specularColor:r,specularF90:n,roughness:s})),v=f.r.add(f.g,f.b).div(3);return $p(b.oneMinus().mul(y),g.a.oneMinus().mul(v).oneMinus())})),A_=Kp(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),N_=(e,t)=>e.sub(t).div(e.add(t)).pow2(),C_=(e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=Wp(54856e-17,44201e-17,52481e-17),r=Wp(1681e3,1795300,2208400),n=Wp(43278e5,93046e5,66121e5),o=Up(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let a=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());a=Wp(a.x.add(o),a.y,a.z).div(1.0685e-7);return A_.mul(a)},R_=Cp((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=vf(e,t,Sf(0,.03,i)),o=e.div(n).pow2().mul(Up(1).sub(s.pow2())),a=Up(1).sub(o).sqrt(),h=N_(n,e),u=OT({f0:h,f90:1,dotVH:s}),l=u.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=Up(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Wp(1).add(t).div(Wp(1).sub(t))})(r.clamp(0,.9999)),m=N_(p,n.toVec3()),g=OT({f0:m,f90:1,dotVH:a}),f=Wp(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(i,a,2),x=Wp(d).add(f),b=u.mul(g).clamp(1e-5,.9999),v=b.sqrt(),T=l.pow2().mul(g).div(Wp(1).sub(b));let _=u.add(T),w=T.sub(l);for(let e=1;e<=2;++e){w=w.mul(v);const t=C_(Up(e).mul(y),Up(e).mul(x)).mul(2);_=_.add(w.mul(t))}return _.max(Wp(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"}]}),E_=Cp((({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.pow2(),n=Ef(s.lessThan(.25),Up(-339.2).mul(r).add(Up(161.4).mul(s)).sub(25.9),Up(-8.48).mul(r).add(Up(14.3).mul(s)).sub(9.95)),o=Ef(s.lessThan(.25),Up(44).mul(r).sub(Up(23.7).mul(s)).add(3.26),Up(1.97).mul(r).sub(Up(3.27).mul(s)).add(.72));return Ef(s.lessThan(.25),0,Up(.1).mul(s).sub(.025)).add(n.mul(i).add(o).exp()).mul(1/Math.PI).saturate()})),B_=Wp(.04),I_=Up(1);class P_ extends IT{constructor(e=!1,t=!1,s=!1,i=!1,r=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=r,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=Wp().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Wp().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Wp().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Wp().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Wp().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=vx.dot(cx).clamp();this.iridescenceFresnel=R_({outsideIOR:Up(1),eta2:Mm,cosTheta1:e,thinFilmThickness:Am,baseF0:Bm}),this.iridescenceF0=t_({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=hx,s=ky.sub(hx).normalize(),i=Tx;e.backdrop=M_(i,s,xm,fm,Bm,Im,t,Zy,Ly,Oy,Lm,Dm,Gm,km,this.dispersion?Wm:null),e.backdropAlpha=Vm,fm.a.mulAssign(vf(1,e.backdrop.a,Vm))}}computeMultiscattering(e,t,s){const i=vx.dot(cx).clamp(),r=QT({roughness:xm,dotNV:i}),n=(this.iridescenceF0?Sm.mix(Bm,this.iridescenceF0):Bm).mul(r.x).add(s.mul(r.y)),o=r.x.add(r.y).oneMinus(),a=Bm.add(Bm.oneMinus().mul(.047619)),h=n.mul(a).div(o.mul(a).oneMinus());e.addAssign(n),t.addAssign(h.mul(o))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=vx.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(r_({lightDirection:e}))),!0===this.clearcoat){const s=_x.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(KT({lightDirection:e,f0:B_,f90:I_,roughness:Tm,normalView:_x})))}s.directDiffuse.addAssign(i.mul(zT({diffuseColor:fm.rgb}))),s.directSpecular.addAssign(i.mul(KT({lightDirection:e,f0:Bm,f90:1,roughness:xm,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:r,ltc_1:n,ltc_2:o}){const a=t.add(s).sub(i),h=t.sub(s).sub(i),u=t.sub(s).add(i),l=t.add(s).add(i),c=vx,d=cx,p=lx.toVar(),m=n_({N:c,V:d,roughness:xm}),g=n.uv(m).toVar(),f=o.uv(m).toVar(),y=Kp(Wp(g.x,0,g.y),Wp(0,1,0),Wp(g.z,0,g.w)).toVar(),x=Bm.mul(f.x).add(Bm.oneMinus().mul(f.y)).toVar();r.directSpecular.addAssign(e.mul(x).mul(h_({N:c,V:d,P:p,mInv:y,p0:a,p1:h,p2:u,p3:l}))),r.directDiffuse.addAssign(e.mul(fm).mul(h_({N:c,V:d,P:p,mInv:Kp(1,0,0,0,1,0,0,0,1),p0:a,p1:h,p2:u,p3:l})))}indirect(e,t,s){this.indirectDiffuse(e,t,s),this.indirectSpecular(e,t,s),this.ambientOcclusion(e,t,s)}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(zT({diffuseColor:fm})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:s}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(_m,E_({normal:vx,viewDir:cx,roughness:wm}))),!0===this.clearcoat){const e=_x.dot(cx).clamp(),t=e_({dotNV:e,specularColor:B_,specularF90:I_,roughness:Tm});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=Wp().toVar("singleScattering"),r=Wp().toVar("multiScattering"),n=t.mul(1/Math.PI);this.computeMultiscattering(i,r,Im);const o=i.add(r),a=fm.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(e.mul(i)),s.indirectSpecular.addAssign(r.mul(n)),s.indirectDiffuse.addAssign(a.mul(n))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const s=vx.dot(cx).clamp().add(e),i=xm.mul(-16).oneMinus().negate().exp2(),r=e.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(r)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=_x.dot(cx).clamp(),s=OT({dotVH:e,f0:B_,f90:I_}),i=t.mul(vm.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(vm));t.assign(i)}if(!0===this.sheen){const e=_m.r.max(_m.g).max(_m.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const F_=Up(1),U_=Up(-2),O_=Up(.8),z_=Up(-1),L_=Up(.4),V_=Up(2),D_=Up(.305),k_=Up(3),G_=Up(.21),W_=Up(4),j_=Up(4),H_=Up(16),q_=Cp((([e])=>{const t=Wp(Wg(e)).toVar(),s=Up(-1).toVar();return Ip(t.x.greaterThan(t.z),(()=>{Ip(t.x.greaterThan(t.y),(()=>{s.assign(Ef(e.x.greaterThan(0),0,3))})).Else((()=>{s.assign(Ef(e.y.greaterThan(0),1,4))}))})).Else((()=>{Ip(t.z.greaterThan(t.y),(()=>{s.assign(Ef(e.z.greaterThan(0),2,5))})).Else((()=>{s.assign(Ef(e.y.greaterThan(0),1,4))}))})),s})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),$_=Cp((([e,t])=>{const s=Vp().toVar();return Ip(t.equal(0),(()=>{s.assign(Vp(e.z,e.y).div(Wg(e.x)))})).ElseIf(t.equal(1),(()=>{s.assign(Vp(e.x.negate(),e.z.negate()).div(Wg(e.y)))})).ElseIf(t.equal(2),(()=>{s.assign(Vp(e.x.negate(),e.y).div(Wg(e.z)))})).ElseIf(t.equal(3),(()=>{s.assign(Vp(e.z.negate(),e.y).div(Wg(e.x)))})).ElseIf(t.equal(4),(()=>{s.assign(Vp(e.x.negate(),e.z).div(Wg(e.y)))})).Else((()=>{s.assign(Vp(e.x,e.y).div(Wg(e.z)))})),Jm(.5,s.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),X_=Cp((([e])=>{const t=Up(0).toVar();return Ip(e.greaterThanEqual(O_),(()=>{t.assign(F_.sub(e).mul(z_.sub(U_)).div(F_.sub(O_)).add(U_))})).ElseIf(e.greaterThanEqual(L_),(()=>{t.assign(O_.sub(e).mul(V_.sub(z_)).div(O_.sub(L_)).add(z_))})).ElseIf(e.greaterThanEqual(D_),(()=>{t.assign(L_.sub(e).mul(k_.sub(V_)).div(L_.sub(D_)).add(V_))})).ElseIf(e.greaterThanEqual(G_),(()=>{t.assign(D_.sub(e).mul(W_.sub(k_)).div(D_.sub(G_)).add(k_))})).Else((()=>{t.assign(Up(-2).mul(Eg(Jm(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Y_=Cp((([e,t])=>{const s=e.toVar();s.assign(Jm(2,s).sub(1));const i=Wp(s,1).toVar();return Ip(t.equal(0),(()=>{i.assign(i.zyx)})).ElseIf(t.equal(1),(()=>{i.assign(i.xzy),i.xz.mulAssign(-1)})).ElseIf(t.equal(2),(()=>{i.x.mulAssign(-1)})).ElseIf(t.equal(3),(()=>{i.assign(i.zyx),i.xz.mulAssign(-1)})).ElseIf(t.equal(4),(()=>{i.assign(i.xzy),i.xy.mulAssign(-1)})).ElseIf(t.equal(5),(()=>{i.z.mulAssign(-1)})),i})).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),Z_=Cp((([e,t,s,i,r,n])=>{const o=Up(s),a=Wp(t),h=Tf(X_(o),U_,n),u=Og(h),l=Pg(h),c=Wp(J_(e,a,l,i,r,n)).toVar();return Ip(u.notEqual(0),(()=>{const t=Wp(J_(e,a,l.add(1),i,r,n)).toVar();c.assign(vf(c,t,u))})),c})),J_=Cp((([e,t,s,i,r,n])=>{const o=Up(s).toVar(),a=Wp(t),h=Up(q_(a)).toVar(),u=Up(nf(j_.sub(o),0)).toVar();o.assign(nf(o,j_));const l=Up(Cg(o)).toVar(),c=Vp($_(a,h).mul(l.sub(2)).add(1)).toVar();return Ip(h.greaterThan(2),(()=>{c.y.addAssign(l),h.subAssign(3)})),c.x.addAssign(h.mul(l)),c.x.addAssign(u.mul(Jm(3,H_))),c.y.addAssign(Jm(4,Cg(n).sub(l))),c.x.mulAssign(i),c.y.mulAssign(r),e.uv(c).grad(Vp(),Vp())})),K_=Cp((({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const h=Lg(i),u=s.mul(h).add(r.cross(s).mul(zg(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return J_(e,u,t,n,o,a)})),Q_=Cp((({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:o,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})=>{const d=Wp(Ef(t,s,df(s,i))).toVar();Ip(_g(d.equals(Wp(0))),(()=>{d.assign(Wp(i.z,0,i.x.negate()))})),d.assign(Ug(d));const p=Wp().toVar();return p.addAssign(r.element(Op(0)).mul(K_({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),xv({start:Op(1),end:e},(({i:e})=>{Ip(e.greaterThanEqual(n),(()=>{vv()}));const t=Up(o.mul(Up(e))).toVar();p.addAssign(r.element(e).mul(K_({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(K_({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})))})),$p(p,1)}));let ew=null;const tw=new WeakMap;function sw(e){let t=tw.get(e);if((void 0!==t?t.pmremVersion:-1)!==e.pmremVersion){const s=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const s=6;for(let i=0;i0}(s))return null;t=ew.fromEquirectangular(e,t)}t.pmremVersion=e.pmremVersion,tw.set(e,t)}return t.texture}class iw extends Dd{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new yi;i.isRenderTargetTexture=!0,this._texture=By(i),this._width=dm(0),this._height=dm(0),this._maxMip=dm(0),this.updateBeforeType=Ed.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,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:s,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(){let e=this._pmrem;const t=e?e.pmremVersion:-1,s=this._value;t!==s.pmremVersion&&(e=!0===s.isPMREMTexture?s:sw(s),null!==e&&(this._pmrem=e,this.updateFromTexture(e)))}setup(e){null===ew&&(ew=e.createPMREMGenerator()),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this));const s=this.value;e.renderer.coordinateSystem===Us&&!0!==s.isPMREMTexture&&!0===s.isRenderTargetTexture&&(t=Wp(t.x.negate(),t.yz));let i=this.levelNode;return null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),Z_(this._texture,t,i,this._width,this._height,this._maxMip)}}const rw=Ap(iw),nw=new WeakMap;class ow extends Nv{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:t[s.property];let i=nw.get(e);void 0===i&&(i=rw(e),nw.set(e,i)),s=i}const i=t.envMap?Dx("envMapIntensity","float",e.material):Dx("environmentIntensity","float",e.scene),r=!0===t.useAnisotropy||t.anisotropy>0?ob:vx,n=s.context(aw(xm,r)).mul(i),o=s.context(hw(Tx)).mul(Math.PI).mul(i),a=ly(n),h=ly(o);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(h);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=s.context(aw(Tm,_x)).mul(i),t=ly(e);u.addAssign(t)}}}const aw=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=cx.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(Ly)),s),getTextureLevel:()=>e}},hw=e=>({getUV:()=>e,getTextureLevel:()=>Up(1)}),uw=new Tu;class lw extends uT{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(uw),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new ow(t):null}setupLightingModel(){return new P_}setupSpecular(){const e=vf(Wp(.04),fm.rgb,bm);Bm.assign(e),Im.assign(1)}setupVariants(){const e=this.metalnessNode?Up(this.metalnessNode):Nb;bm.assign(e);let t=this.roughnessNode?Up(this.roughnessNode):Ab;t=qT({roughness:t}),xm.assign(t),this.setupSpecular(),fm.assign($p(fm.rgb.mul(e.oneMinus()),fm.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const cw=new _u;class dw extends lw{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(cw),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?Up(this.iorNode):kb;Lm.assign(e),Bm.assign(vf(rf(mf(Lm.sub(1).div(Lm.add(1))).mul(wb),Wp(1)).mul(_b),fm.rgb,bm)),Im.assign(vf(_b,1,bm))}setupLightingModel(){return new P_(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Up(this.clearcoatNode):Rb,t=this.clearcoatRoughnessNode?Up(this.clearcoatRoughnessNode):Eb;vm.assign(e),Tm.assign(qT({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Wp(this.sheenNode):Pb,t=this.sheenRoughnessNode?Up(this.sheenRoughnessNode):Fb;_m.assign(e),wm.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Up(this.iridescenceNode):Ob,t=this.iridescenceIORNode?Up(this.iridescenceIORNode):zb,s=this.iridescenceThicknessNode?Up(this.iridescenceThicknessNode):Lb;Sm.assign(e),Mm.assign(t),Am.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?Vp(this.anisotropyNode):Ub).toVar();Cm.assign(e.length()),Ip(Cm.equal(0),(()=>{e.assign(Vp(1,0))})).Else((()=>{e.divAssign(Vp(Cm)),Cm.assign(Cm.saturate())})),Nm.assign(Cm.pow2().mix(xm.pow2(),1)),Rm.assign(ib[0].mul(e.x).add(ib[1].mul(e.y))),Em.assign(ib[1].mul(e.x).sub(ib[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Up(this.transmissionNode):Vb,t=this.thicknessNode?Up(this.thicknessNode):Db,s=this.attenuationDistanceNode?Up(this.attenuationDistanceNode):Gb,i=this.attenuationColorNode?Wp(this.attenuationColorNode):Wb;if(Vm.assign(e),Dm.assign(t),km.assign(s),Gm.assign(i),this.useDispersion){const e=this.dispersionNode?Up(this.dispersionNode):Zb;Wm.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Wp(this.clearcoatNormalNode):Bb}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),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 pw extends P_{constructor(e,t,s,i){super(e,t,s),this.useSSS=i}direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){if(!0===this.useSSS){const i=r.material,{thicknessColorNode:n,thicknessDistortionNode:o,thicknessAmbientNode:a,thicknessAttenuationNode:h,thicknessPowerNode:u,thicknessScaleNode:l}=i,c=e.add(vx.mul(o)).normalize(),d=Up(cx.dot(c.negate()).saturate().pow(u).mul(l)),p=Wp(d.add(a).mul(n));s.directDiffuse.addAssign(p.mul(h.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r)}}class mw extends dw{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=Up(.1),this.thicknessAmbientNode=Up(0),this.thicknessAttenuationNode=Up(.1),this.thicknessPowerNode=Up(2),this.thicknessScaleNode=Up(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new pw(this.useClearcoat,this.useSheen,this.useIridescence,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 gw=Cp((({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=Vp(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=Wx("gradientMap","texture").context({getUV:()=>r});return Wp(e.r)}{const e=r.fwidth().mul(.5);return vf(Wp(.7),Wp(1),Sf(Up(.7).sub(e.x),Up(.7).add(e.x),r.x))}}));class fw extends IT{direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){const n=gw({normal:gx,lightDirection:e,builder:r}).mul(t);s.directDiffuse.addAssign(n.mul(zT({diffuseColor:fm.rgb})))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(zT({diffuseColor:fm}))),s.indirectDiffuse.mulAssign(e)}}const yw=new Su;class xw extends uT{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(yw),this.setValues(e)}setupLightingModel(){return new fw}}class bw extends Dd{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=Wp(cx.z,0,cx.x.negate()).normalize(),t=cx.cross(e);return Vp(e.dot(vx),t.dot(vx)).mul(.495).add(.5)}}const vw=Np(bw),Tw=new Ru;class _w extends uT{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Tw),this.setValues(e)}setupVariants(e){const t=vw;let s;s=e.material.matcap?Wx("matcap","texture").context({getUV:()=>t}):Wp(vf(.2,.8,t.y)),fm.rgb.mulAssign(s.rgb)}}const ww=new Fa;class Sw extends uT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.isPointsNodeMaterial=!0,this.lights=!1,this.transparent=!0,this.sizeNode=null,this.setDefaultValues(ww),this.setValues(e)}copy(e){return this.sizeNode=e.sizeNode,super.copy(e)}}class Mw extends Dd{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:s}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return Jp(e,i,i.negate(),e).mul(s)}{const e=t,i=Qp($p(1,0,0,0),$p(0,Lg(e.x),zg(e.x).negate(),0),$p(0,zg(e.x),Lg(e.x),0),$p(0,0,0,1)),r=Qp($p(Lg(e.y),0,zg(e.y),0),$p(0,1,0,0),$p(zg(e.y).negate(),0,Lg(e.y),0),$p(0,0,0,1)),n=Qp($p(Lg(e.z),zg(e.z).negate(),0,0),$p(zg(e.z),Lg(e.z),0,0),$p(0,0,1,0),$p(0,0,0,1));return i.mul(r).mul(n).mul($p(s,1)).xyz}}}const Aw=Ap(Mw),Nw=new so;class Cw extends uT{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this.lights=!1,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.setDefaultValues(Nw),this.setValues(e)}setupPosition({object:e,camera:t,context:s}){const i=this.sizeAttenuation,{positionNode:r,rotationNode:n,scaleNode:o}=this,a=ox;let h=sx.mul(Wp(r||0)),u=Vp(Zy[0].xyz.length(),Zy[1].xyz.length());if(null!==o&&(u=u.mul(o)),!i)if(t.isPerspectiveCamera)u=u.mul(h.z.negate());else{const e=Up(2).div(Oy.element(1).element(1));u=u.mul(e.mul(2))}let l=a.xy;if(e.center&&!0===e.center.isVector2){const e=((e,t,s)=>wp(new Zf(e,t,s)))("center","vec2");l=l.sub(e.sub(.5))}l=l.mul(u);const c=Up(n||Ib),d=Aw(l,c);h=$p(h.xy.add(d),h.zw);const p=Oy.mul(h);return s.vertex=a,p}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)}}class Rw extends IT{constructor(){super(),this.shadowNode=Up(1).toVar("shadowMask")}direct({shadowMask:e}){this.shadowNode.mulAssign(e)}finish(e){fm.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(fm.rgb)}}const Ew=new bu;class Bw extends uT{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Ew),this.setValues(e)}setupLightingModel(){return new Rw}}const Iw=Cp((({texture:e,uv:t})=>{const s=1e-4,i=Wp().toVar();return Ip(t.x.lessThan(s),(()=>{i.assign(Wp(1,0,0))})).ElseIf(t.y.lessThan(s),(()=>{i.assign(Wp(0,1,0))})).ElseIf(t.z.lessThan(s),(()=>{i.assign(Wp(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(Wp(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(Wp(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(Wp(0,0,-1))})).Else((()=>{const s=.01,r=e.uv(t.add(Wp(-.01,0,0))).r.sub(e.uv(t.add(Wp(s,0,0))).r),n=e.uv(t.add(Wp(0,-.01,0))).r.sub(e.uv(t.add(Wp(0,s,0))).r),o=e.uv(t.add(Wp(0,0,-.01))).r.sub(e.uv(t.add(Wp(0,0,s))).r);i.assign(Wp(r,n,o))})),i.normalize()}));class Pw extends Ey{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Wp(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){return t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return Iw({texture:this,uv:e})}}const Fw=Ap(Pw);class Uw extends uT{static get type(){return"VolumeNodeMaterial"}constructor(e={}){super(),this.lights=!1,this.isVolumeNodeMaterial=!0,this.testNode=null,this.setValues(e)}setup(e){const t=Fw(this.map,null,0),s=Cp((({orig:e,dir:t})=>{const s=Wp(-.5),i=Wp(.5),r=t.reciprocal(),n=s.sub(e).mul(r),o=i.sub(e).mul(r),a=rf(n,o),h=nf(n,o),u=nf(a.x,nf(a.y,a.z)),l=rf(h.x,rf(h.y,h.z));return Vp(u,l)}));this.fragmentNode=Cp((()=>{const e=Vf(Wp(tx.mul($p(ky,1)))),i=Vf(nx.sub(e)).normalize(),r=Vp(s({orig:e,dir:i})).toVar();r.x.greaterThan(r.y).discard(),r.assign(Vp(nf(r.x,0),r.y));const n=Wp(e.add(r.x.mul(i))).toVar(),o=Wp(i.abs().reciprocal()).toVar(),a=Up(rf(o.x,rf(o.y,o.z))).toVar("delta");a.divAssign(Wx("steps","float"));const h=$p(Wx("base","color"),0).toVar();return xv({type:"float",start:r.x,end:r.y,update:"+= delta"},(()=>{const e=mm("float","d").assign(t.uv(n.add(.5)).r);null!==this.testNode?this.testNode({map:t,mapValue:e,probe:n,finalColor:h}).append():(h.a.assign(1),vv()),n.addAssign(i.mul(a))})),h.a.equal(0).discard(),$p(h)}))(),super.setup(e)}}class Ow{constructor(e,t){this.nodes=e,this.info=t,this.animationLoop=null,this.requestId=null,this._init()}_init(){const e=(t,s)=>{this.requestId=self.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,s)};e()}dispose(){self.cancelAnimationFrame(this.requestId),this.requestId=null}setAnimationLoop(e){this.animationLoop=e}}class zw{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let s=0;s{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){const t=this.material;let s=this.clippingContext;Array.isArray(t.clippingPlanes)?(s!==e&&s||(s=new Vw,this.clippingContext=s),s.update(e,t)):this.clippingContext!==e&&(this.clippingContext=e)}get clippingNeedsUpdate(){return this.clippingContext.version!==this.clippingContextVersion&&(this.clippingContextVersion=this.clippingContext.version,!0)}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().monitor)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;s.push(e);const n=e.isInterleavedBufferAttribute?e.data:e;i.add(n)}return this.attributes=s,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:r}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),o=this.getIndex(),a=null!==o,h=s.isInstancedBufferGeometry?s.instanceCount:e.count>1?e.count:1;if(0===h)return null;if(n.instanceCount=h,!0===e.isBatchedMesh)return n;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let l=r.start*u,c=(r.start+r.count)*u;null!==i&&(l=Math.max(l,i.start*u),c=Math.min(c,(i.start+i.count)*u));const d=s.attributes.position;let p=1/0;a?p=o.count:null!=d&&(p=d.count),l=Math.max(l,0),c=Math.min(c,p);const m=c-l;return m<0||m===1/0?null:(n.vertexCount=m,n.firstVertex=l,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t}=this;let s=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let s=Object.getPrototypeOf(e);for(;s;){const e=Object.getOwnPropertyDescriptors(s);for(const s in e)if(void 0!==e[s]){const i=e[s];i&&"function"==typeof i.get&&t.push(s)}s=Object.getPrototypeOf(s)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const i=t[e];let r;if(null!==i){const e=typeof i;"number"===e?r=0!==i?"1":"0":"object"===e?(r="{",i.isTexture&&(r+=i.mapping),r+="}"):r=String(i)}else r=String(i);s+=r+","}return s+=this.clippingContext.cacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.morphTargetInfluences&&(s+=e.morphTargetInfluences.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),bd(s)}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=this._nodes.getCacheKey(this.scene,this.lightsNode);return this.object.receiveShadow&&(e+=1),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const Gw=[];class Ww{constructor(e,t,s,i,r,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=r,this.info=n,this.chainMaps={}}get(e,t,s,i,r,n,o){const a=this.getChainMap(o);Gw[0]=e,Gw[1]=t,Gw[2]=n,Gw[3]=r;let h=a.get(Gw);return void 0===h?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o),a.set(Gw,h)):(h.updateClipping(n.clippingContext),(h.version!==t.version||h.needsUpdate)&&(h.initialCacheKey!==h.getCacheKey()?(h.dispose(),h=this.get(e,t,s,i,r,n,o)):h.version=t.version)),h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new zw)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,h,u){const l=this.getChainMap(u),c=new kw(e,t,s,i,r,n,o,a,h);return c.onDispose=()=>{this.pipelines.delete(c),this.bindings.delete(c),this.nodes.delete(c),l.delete(c.getChainArray())},c}}class jw{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;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 Hw=1,qw=2,$w=3,Xw=4,Yw=16;class Zw extends jw{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return void 0!==t&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===Hw?this.backend.createAttribute(e):t===qw?this.backend.createIndexAttribute(e):t===$w?this.backend.createStorageAttribute(e):t===Xw&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version=0;--t)if(e[t]>=65535)return!0;return!1}(t)?mn:dn)(t,1);return r.version=Jw(e),r}class Qw extends jw{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",s)};t.addEventListener("dispose",s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,$w):this.updateAttribute(e,Hw);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,qw);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,Xw)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=Kw(t),e.set(t,s)):s.version!==Jw(t)&&(this.attributes.delete(s),s=Kw(t),e.set(t,s)),i=s}return i}}class eS{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,previousFrameCalls:0,timestampCalls:0},this.compute={calls:0,frameCalls:0,timestamp:0,previousFrameCalls:0,timestampCalls:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}updateTimestamp(e,t){0===this[e].timestampCalls&&(this[e].timestamp=0),this[e].timestamp+=t,this[e].timestampCalls++,this[e].timestampCalls>=this[e].previousFrameCalls&&(this[e].timestampCalls=0)}reset(){const e=this.render.frameCalls;this.render.previousFrameCalls=e;const t=this.compute.frameCalls;this.compute.previousFrameCalls=t,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 tS{constructor(e){this.cacheKey=e,this.usedTimes=0}}class sS extends tS{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class iS extends tS{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let rS=0;class nS{constructor(e,t,s=null,i=null){this.id=rS++,this.code=e,this.stage=t,this.transforms=s,this.attributes=i,this.usedTimes=0}}class oS extends jw{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:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let o=this.programs.compute.get(n.computeShader);void 0===o&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),o=new nS(n.computeShader,"compute",n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,o),s.createProgram(o));const a=this._getComputeCacheKey(e,o);let h=this.caches.get(a);void 0===h&&(r&&0===r.usedTimes&&this._releasePipeline(r),h=this._getComputePipeline(e,o,a,t)),h.usedTimes++,o.usedTimes++,i.version=e.version,i.pipeline=h}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState();let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new nS(n.vertexShader,"vertex"),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o));let a=this.programs.fragment.get(n.fragmentShader);void 0===a&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),a=new nS(n.fragmentShader,"fragment"),this.programs.fragment.set(n.fragmentShader,a),s.createProgram(a));const h=this._getRenderCacheKey(e,o,a);let u=this.caches.get(h);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,o,a,h,t)):e.pipeline=u,u.usedTimes++,o.usedTimes++,a.usedTimes++,i.pipeline=u}return i.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,s,i){s=s||this._getComputeCacheKey(e,t);let r=this.caches.get(s);return void 0===r&&(r=new iS(s,t),this.caches.set(s,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,s,i,r){i=i||this._getRenderCacheKey(e,t,s);let n=this.caches.get(i);return void 0===n&&(n=new sS(i,t,s),this.caches.set(i,n),e.pipeline=n,this.backend.createRenderPipeline(e,r)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].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 aS extends jw{constructor(e,t,s,i,r,n){super(),this.backend=e,this.textures=s,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t),s.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t),s.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,s=e.isIndirectStorageBufferAttribute?Xw:$w;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!this.nodes.updateGroup(t))continue}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){t.needsBindingsUpdate(this.textures.get(t.texture).generation)&&(i=!0);const e=t.update(),r=t.texture;e&&this.textures.updateTexture(r);const n=s.get(r);if(!0===s.isWebGPUBackend&&void 0===n.texture&&void 0===n.externalTexture&&(console.error("Bindings._update: binding should be available:",t,e,r,t.textureNode.value,i),this.textures.updateTexture(r),i=!0),!0===r.isStorageTexture){const e=this.get(r);!0===t.store?e.needsMipmap=!0:!0===r.generateMipmaps&&this.textures.needsMipmaps(r)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(r),e.needsMipmap=!1)}}}!0===i&&this.backend.updateBindings(e,t)}}function hS(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function uS(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}class lS{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,s),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,i,r,n){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:r,group:n},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=s,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=n),this.renderItemsIndex++,o}push(e,t,s,i,r,n){const o=this.getNextRenderItem(e,t,s,i,r,n);!0===e.occlusionTest&&this.occlusionQueryCount++,(!0===s.transparent||s.transmission>0?this.transparent:this.opaque).push(o)}unshift(e,t,s,i,r,n){const o=this.getNextRenderItem(e,t,s,i,r,n);(!0===s.transparent?this.transparent: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||hS),this.transparent.length>1&&this.transparent.sort(t||uS)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,h=o.height>>t;let u=e.depthTexture||r[t];const l=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===u&&l&&(u=new Xa,u.format=e.stencilBuffer?je:We,u.type=e.stencilBuffer?Oe:Be,u.image.width=a,u.image.height=h,r[t]=u),s.width===o.width&&o.height===s.height||(c=!0,u&&(u.needsUpdate=!0,u.image.width=a,u.image.height=h)),s.width=o.width,s.height=o.height,s.textures=n,s.depthTexture=u||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(c=!0,u&&(u.needsUpdate=!0),s.sampleCount=i);const d={sampleCount:i};for(let e=0;e{e.removeEventListener("dispose",t);for(let e=0;e0){const i=e.image;if(void 0===i)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=i;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(r.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version}if(!0!==s.initialized){s.initialized=!0,s.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}s.version=e.version}getSize(e,t=fS){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),t.width=s.width,t.height=s.height,t.depth=e.isCubeTexture?6:s.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return i=e.isCompressedTexture?e.mipmaps.length:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return!!this.isEnvironmentTexture(e)||(!0===e.isCompressedTexture||e.minFilter!==fe&&e.minFilter!==Te)}isEnvironmentTexture(e){const t=e.mapping;return t===le||t===ce||t===he||t===ue}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class xS extends Xr{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}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 bS extends pm{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}const vS=(e,t)=>wp(new bS(e,t));class TS extends zd{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}add(e){return this.nodes.push(e),this}If(e,t){const s=new _p(t);return this._currentCond=Ef(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new _p(t),i=Ef(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new _p(e),this}build(e,...t){const s=Bp();Ep(this);for(const t of this.nodes)t.build(e,"void");return Ep(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("TSL.StackNode: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("TSL.StackNode: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const _S=Ap(TS);class wS extends zd{static get type(){return"StructTypeNode"}constructor(e){super(),this.types=e,this.isStructTypeNode=!0}getMemberTypes(){return this.types}}class SS extends zd{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}setup(e){super.setup(e);const t=this.members,s=[];for(let i=0;i{const t=e.toUint().mul(747796405).add(2891336453),s=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return s.shiftRight(22).bitXor(s).toFloat().mul(1/2**32)})),ES=(e,t)=>pf(Jm(4,e.mul(Zm(1,e))),t),BS=(e,t)=>e.lessThan(.5)?ES(e.mul(2),t).div(2):Zm(1,ES(Jm(Zm(1,e),2),t).div(2)),IS=(e,t,s)=>pf(Km(pf(e,t),Ym(pf(e,t),pf(Zm(1,e),s))),1/t),PS=(e,t)=>zg(vg.mul(t.mul(e).sub(1))).div(vg.mul(t.mul(e).sub(1))),FS=Cp((([e])=>e.fract().sub(.5).abs())).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),US=Cp((([e])=>Wp(FS(e.z.add(FS(e.y.mul(1)))),FS(e.z.add(FS(e.x.mul(1)))),FS(e.y.add(FS(e.x.mul(1))))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),OS=Cp((([e,t,s])=>{const i=Wp(e).toVar(),r=Up(1.4).toVar(),n=Up(0).toVar(),o=Wp(i).toVar();return xv({start:Up(0),end:Up(3),type:"float",condition:"<="},(()=>{const e=Wp(US(o.mul(2))).toVar();i.addAssign(e.add(s.mul(Up(.1).mul(t)))),o.mulAssign(1.8),r.mulAssign(1.5),i.mulAssign(1.2);const a=Up(FS(i.z.add(FS(i.x.add(FS(i.y)))))).toVar();n.addAssign(a.div(r)),o.addAssign(.14)})),n})).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"p",type:"vec3"},{name:"spd",type:"float"},{name:"time",type:"float"}]});class zS extends zd{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 s=this._candidateFnCall;if(null===s){let i=null,r=-1;for(const s of this.functionNodes){const n=s.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const o=n.inputs;if(t.length===o.length){let n=0;for(let s=0;sr&&(i=s,r=n)}}this._candidateFnCall=s=i(...t)}return s}}const LS=Ap(zS),VS=e=>(...t)=>LS(e,...t),DS=dm(0).setGroup(um).onRenderUpdate((e=>e.time)),kS=dm(0).setGroup(um).onRenderUpdate((e=>e.deltaTime)),GS=dm(0,"uint").setGroup(um).onRenderUpdate((e=>e.frameId)),WS=(e=1)=>(console.warn('TSL: timerLocal() is deprecated. Use "time" instead.'),DS.mul(e)),jS=(e=1)=>(console.warn('TSL: timerGlobal() is deprecated. Use "time" instead.'),DS.mul(e)),HS=(e=1)=>(console.warn('TSL: timerDelta() is deprecated. Use "deltaTime" instead.'),kS.mul(e)),qS=(e=DS)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),$S=(e=DS)=>e.fract().round(),XS=(e=DS)=>e.add(.5).fract().mul(2).sub(1).abs(),YS=(e=DS)=>e.fract(),ZS=Cp((([e,t,s=Vp(.5)])=>Aw(e.sub(s),t).add(s))),JS=Cp((([e,t,s=Vp(.5)])=>{const i=e.sub(s),r=i.dot(i),n=r.mul(r).mul(t);return e.add(i.mul(n))})),KS=Cp((({position:e=null,horizontal:t=!0,vertical:s=!1})=>{let i;null!==e?(i=Zy.toVar(),i[3][0]=e.x,i[3][1]=e.y,i[3][2]=e.z):i=Zy;const r=Ly.mul(i);return vp(t)&&(r[0][0]=Zy[0].length(),r[0][1]=0,r[0][2]=0),vp(s)&&(r[1][0]=0,r[1][1]=Zy[1].length(),r[1][2]=0),r[2][0]=0,r[2][1]=0,r[2][2]=1,Oy.mul(r).mul(ox)})),QS=Cp((([e=null])=>{const t=oT();return oT(Jv(e)).sub(t).lessThan(0).select(Uv,e)}));class eM extends zd{static get type(){return"SpriteSheetUVNode"}constructor(e,t=My(),s=Up(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=s}setup(){const{frameNode:e,uvNode:t,countNode:s}=this,{width:i,height:r}=s,n=e.mod(i.mul(r)).floor(),o=n.mod(i),a=r.sub(n.add(1).div(i).ceil()),h=s.reciprocal(),u=Vp(o,a);return t.add(u).mul(h)}}const tM=Ap(eM);class sM extends zd{static get type(){return"TriplanarTexturesNode"}constructor(e,t=null,s=null,i=Up(1),r=ox,n=fx){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=s,this.scaleNode=i,this.positionNode=r,this.normalNode=n}setup(){const{textureXNode:e,textureYNode:t,textureZNode:s,scaleNode:i,positionNode:r,normalNode:n}=this;let o=n.abs().normalize();o=o.div(o.dot(Wp(1)));const a=r.yz.mul(i),h=r.zx.mul(i),u=r.xy.mul(i),l=e.value,c=null!==t?t.value:l,d=null!==s?s.value:l,p=By(l,a).mul(o.x),m=By(c,h).mul(o.y),g=By(d,u).mul(o.z);return Ym(p,m,g)}}const iM=Ap(sM),rM=(...e)=>iM(...e),nM=new Yo,oM=new Ai,aM=new Ai,hM=new Ai,uM=new sr,lM=new Ai(0,0,-1),cM=new xi,dM=new Ai,pM=new Ai,mM=new xi,gM=new Ys,fM=new bi,yM=Uv.flipX();fM.depthTexture=new Xa(1,1);let xM=!1;class bM extends Ey{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||fM.texture,yM),this._reflectorBaseNode=e.reflector||new vM(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=wp(new bM({defaultTexture:fM.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._reflectorBaseNode=this._reflectorBaseNode,e}}class vM extends zd{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:s=new Rr,resolution:i=1,generateMipmaps:r=!1,bounces:n=!0,depth:o=!1}=t;this.textureNode=e,this.target=s,this.resolution=i,this.generateMipmaps=r,this.bounces=n,this.depth=o,this.updateBeforeType=n?Ed.RENDER:Ed.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new WeakMap}_updateResolution(e,t){const s=this.resolution;t.getDrawingBufferSize(gM),e.setSize(Math.round(gM.width*s),Math.round(gM.height*s))}setup(e){return this._updateResolution(fM,e.renderer),super.setup(e)}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 bi(0,0,{type:Pe}),!0===this.generateMipmaps&&(t.texture.minFilter=1008,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new Xa),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&xM)return;xM=!0;const{scene:t,camera:s,renderer:i,material:r}=e,{target:n}=this,o=this.getVirtualCamera(s),a=this.getRenderTarget(o);if(i.getDrawingBufferSize(gM),this._updateResolution(a,i),aM.setFromMatrixPosition(n.matrixWorld),hM.setFromMatrixPosition(s.matrixWorld),uM.extractRotation(n.matrixWorld),oM.set(0,0,1),oM.applyMatrix4(uM),dM.subVectors(aM,hM),dM.dot(oM)>0)return;dM.reflect(oM).negate(),dM.add(aM),uM.extractRotation(s.matrixWorld),lM.set(0,0,-1),lM.applyMatrix4(uM),lM.add(hM),pM.subVectors(aM,lM),pM.reflect(oM).negate(),pM.add(aM),o.coordinateSystem=s.coordinateSystem,o.position.copy(dM),o.up.set(0,1,0),o.up.applyMatrix4(uM),o.up.reflect(oM),o.lookAt(pM),o.near=s.near,o.far=s.far,o.updateMatrixWorld(),o.projectionMatrix.copy(s.projectionMatrix),nM.setFromNormalAndCoplanarPoint(oM,aM),nM.applyMatrix4(o.matrixWorldInverse),cM.set(nM.normal.x,nM.normal.y,nM.normal.z,nM.constant);const h=o.projectionMatrix;mM.x=(Math.sign(cM.x)+h.elements[8])/h.elements[0],mM.y=(Math.sign(cM.y)+h.elements[9])/h.elements[5],mM.z=-1,mM.w=(1+h.elements[10])/h.elements[14],cM.multiplyScalar(1/cM.dot(mM));h.elements[2]=cM.x,h.elements[6]=cM.y,h.elements[10]=i.coordinateSystem===Os?cM.z-0:cM.z+1-0,h.elements[14]=cM.w,this.textureNode.value=a.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=a.depthTexture),r.visible=!1;const u=i.getRenderTarget(),l=i.getMRT();i.setMRT(null),i.setRenderTarget(a),i.render(t,o),i.setMRT(l),i.setRenderTarget(u),r.visible=!0,xM=!1}}const TM=e=>wp(new bM(e)),_M=new wl(-1,1,1,-1,0,1);class wM extends Sn{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new fn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new fn(t,2))}}const SM=new wM;class MM extends On{constructor(e=null){super(SM,e),this.camera=_M,this.isQuadMesh=!0}renderAsync(e){return e.renderAsync(this,_M)}render(e){e.render(this,_M)}}const AM=new Ys;class NM extends Ey{static get type(){return"RTTNode"}constructor(e,t=null,s=null,i={type:Pe}){const r=new bi(t,s,i);super(r.texture,My()),this.node=e,this.width=t,this.height=s,this.renderTarget=r,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this.updateMap=new WeakMap,this._rttNode=null,this._quadMesh=new MM(new uT),this.updateBeforeType=Ed.RENDER}get autoSize(){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 s=e*this.pixelRatio,i=t*this.pixelRatio;this.renderTarget.setSize(s,i),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.autoSize){this.pixelRatio=e.getPixelRatio();const t=e.getSize(AM);this.setSize(t.width,t.height)}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 Ey(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const CM=(e,...t)=>wp(new NM(wp(e),...t)),RM=(e,...t)=>e.isTextureNode?e:CM(e,...t),EM=Cp((([e,t,s],i)=>{let r;i.renderer.coordinateSystem===Os?(e=Vp(e.x,e.y.oneMinus()).mul(2).sub(1),r=$p(Wp(e,t),1)):r=$p(Wp(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=$p(s.mul(r));return n.xyz.div(n.w)})),BM=Cp((([e,t])=>{const s=t.mul($p(e,1)),i=s.xy.div(s.w).mul(.5).add(.5).toVar();return Vp(i.x,i.y.oneMinus())}));class IM extends wy{static get type(){return"VertexColorNode"}constructor(e=0){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 s;return s=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new xi(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const PM=(...e)=>wp(new IM(...e));class FM extends zd{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const UM=Np(FM);class OM extends zd{static get type(){return"SceneNode"}constructor(e=OM.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let i;return t===OM.BACKGROUND_BLURRINESS?i=Dx("backgroundBlurriness","float",s):t===OM.BACKGROUND_INTENSITY?i=Dx("backgroundIntensity","float",s):console.error("THREE.SceneNode: Unknown scope:",t),i}}OM.BACKGROUND_BLURRINESS="backgroundBlurriness",OM.BACKGROUND_INTENSITY="backgroundIntensity";const zM=Np(OM,OM.BACKGROUND_BLURRINESS),LM=Np(OM,OM.BACKGROUND_INTENSITY);class VM extends Ld{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}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.bufferObject&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let s;const i=e.context.assign;if(s=!1===e.isAvailable("storageBuffer")?!0===this.node.bufferObject&&!0!==i?e.generatePBO(this):this.node.build(e):super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}const DM=Ap(VM),kM="point-list",GM="line-list",WM="line-strip",jM="triangle-list",HM="triangle-strip",qM="never",$M="less",XM="equal",YM="less-equal",ZM="greater",JM="not-equal",KM="greater-equal",QM="always",eA="store",tA="load",sA="clear",iA="ccw",rA="none",nA="front",oA="back",aA="uint16",hA="uint32",uA={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10uFloat:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Stencil8:"stencil8",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},lA="clamp-to-edge",cA="repeat",dA="mirror-repeat",pA="linear",mA="nearest",gA="zero",fA="one",yA="src",xA="one-minus-src",bA="src-alpha",vA="one-minus-src-alpha",TA="dst",_A="one-minus-dst",wA="dst-alpha",SA="one-minus-dst-alpha",MA="src-alpha-saturated",AA="constant",NA="one-minus-constant",CA="add",RA="subtract",EA="reverse-subtract",BA="min",IA="max",PA=0,FA=15,UA="keep",OA="zero",zA="replace",LA="invert",VA="increment-clamp",DA="decrement-clamp",kA="increment-wrap",GA="decrement-wrap",WA="storage",jA="read-only-storage",HA="write-only",qA="read-only",$A="float",XA="unfilterable-float",YA="depth",ZA="sint",JA="uint",KA="2d",QA="3d",eN="2d",tN="2d-array",sN="cube",iN="3d",rN="all",nN="vertex",oN="instance",aN={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class hN extends Ix{static get type(){return"StorageBufferNode"}constructor(e,t,s=0){super(e,t,s),this.isStorageBufferNode=!0,this.access=WA,this.isAtomic=!1,this.bufferObject=!1,this.bufferCount=s,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 DM(this,e)}setBufferObject(e){return this.bufferObject=e,this}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(jA)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=iy(this.value),this._varying=Vf(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}generate(e){if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:s}=this.getAttributeData(),i=s.build(e);return e.registerTransform(i,t),i}}const uN=(e,t,s)=>wp(new hN(e,t,s)),lN=(e,t,s)=>wp(new hN(e,t,s).setBufferObject(!0));class cN extends Ey{static get type(){return"StorageTextureNode"}constructor(e,t,s=null){super(e,t),this.storeNode=s,this.isStorageTextureNode=!0,this.access=HA}getInputType(){return"storageTexture"}setup(e){super.setup(e);e.getNodeProperties(this).storeNode=this.storeNode}setAccess(e){return this.access=e,this}generate(e,t){let s;return s=null!==this.storeNode?this.generateStore(e):super.generate(e,t),s}toReadOnly(){return this.setAccess(qA)}toWriteOnly(){return this.setAccess(HA)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:s,storeNode:i}=t,r=super.generate(e,"property"),n=s.build(e,"uvec2"),o=i.build(e,"vec4"),a=e.generateTextureStore(e,r,n,o);e.addLineFlowCode(a,this)}}const dN=Ap(cN),pN=(e,t,s)=>{const i=dN(e,t,s);return null!==s&&i.append(),i};class mN extends Vx{static get type(){return"UserDataNode"}constructor(e,t,s=null){super(e,t,s),this.userData=s}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const gN=(e,t,s)=>wp(new mN(e,t,s)),fN=new WeakMap;class yN extends Dd{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.updateType=Ed.OBJECT,this.updateAfterType=Ed.OBJECT,this.previousModelWorldMatrix=dm(new sr),this.previousProjectionMatrix=dm(new sr).setGroup(um),this.previousCameraViewMatrix=dm(new sr)}update({frameId:e,camera:t,object:s}){const i=bN(s);this.previousModelWorldMatrix.value.copy(i);const r=xN(t);r.frameId!==e&&(r.frameId=e,void 0===r.previousProjectionMatrix?(r.previousProjectionMatrix=new sr,r.previousCameraViewMatrix=new sr,r.currentProjectionMatrix=new sr,r.currentCameraViewMatrix=new sr,r.previousProjectionMatrix.copy(t.projectionMatrix),r.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(r.previousProjectionMatrix.copy(r.currentProjectionMatrix),r.previousCameraViewMatrix.copy(r.currentCameraViewMatrix)),r.currentProjectionMatrix.copy(t.projectionMatrix),r.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(r.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(r.previousCameraViewMatrix))}updateAfter({object:e}){bN(e).copy(e.matrixWorld)}setup(){const e=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),t=Oy.mul(sx).mul(ox),s=this.previousProjectionMatrix.mul(e).mul(ax),i=t.xy.div(t.w),r=s.xy.div(s.w);return Zm(i,r)}}function xN(e){let t=fN.get(e);return void 0===t&&(t={},fN.set(e,t)),t}function bN(e,t=0){const s=xN(e);let i=s[t];return void 0===i&&(s[t]=i=new sr),i}const vN=Np(yN),TN=Cp((([e,t])=>rf(1,e.oneMinus().div(t)).oneMinus())).setLayout({name:"burnBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),_N=Cp((([e,t])=>rf(e.div(t.oneMinus()),1))).setLayout({name:"dodgeBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),wN=Cp((([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus())).setLayout({name:"screenBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),SN=Cp((([e,t])=>vf(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),af(.5,e)))).setLayout({name:"overlayBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),MN=Cp((([e])=>RN(e.rgb))),AN=Cp((([e,t=Up(1)])=>t.mix(RN(e.rgb),e.rgb))),NN=Cp((([e,t=Up(1)])=>{const s=Ym(e.r,e.g,e.b).div(3),i=e.r.max(e.g.max(e.b)),r=i.sub(s).mul(t).mul(-3);return vf(e.rgb,i,r)})),CN=Cp((([e,t=Up(1)])=>{const s=Wp(.57735,.57735,.57735),i=t.cos();return Wp(e.rgb.mul(i).add(s.cross(e.rgb).mul(t.sin()).add(s.mul(cf(s,e.rgb).mul(i.oneMinus())))))})),RN=(e,t=Wp(ii.getLuminanceCoefficients(new Ai)))=>cf(e,t),EN=(e,t)=>vf(Wp(0),e,RN(e).sub(t).max(0)),BN=Cp((([e,t=Wp(1),s=Wp(0),i=Wp(1),r=Up(1),n=Wp(ii.getLuminanceCoefficients(new Ai,Jt))])=>{const o=e.rgb.dot(Wp(n)),a=nf(e.rgb.mul(t).add(s),0).toVar(),h=a.pow(i).toVar();return Ip(a.r.greaterThan(0),(()=>{a.r.assign(h.r)})),Ip(a.g.greaterThan(0),(()=>{a.g.assign(h.g)})),Ip(a.b.greaterThan(0),(()=>{a.b.assign(h.b)})),a.assign(o.add(a.sub(o).mul(r))),$p(a.rgb,e.a)}));class IN extends Dd{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 PN=Ap(IN);let FN=null;class UN extends qv{static get type(){return"ViewportSharedTextureNode"}constructor(e=Uv,t=null){null===FN&&(FN=new Wa),super(e,t,FN)}updateReference(){return this}}const ON=Ap(UN),zN=new Ys;class LN extends Ey{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class VN extends LN{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class DN extends Dd{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new Xa;r.isRenderTargetTexture=!0,r.name="depth";const n=new bi(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Pe,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this.updateBeforeType=Ed.FRAME,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=dm(0),this._cameraFar=dm(0),this._mrt=null,this.isPassNode=!0}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}isGlobal(){return!0}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.isRenderTargetTexture=!0,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(),t.isRenderTargetTexture=!0,this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(this._textureNodes[e]=t=wp(new VN(this,e)),this._textureNodes[e].updateTexture()),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),this._previousTextureNodes[e]=t=wp(new VN(this,e,!0)),this._previousTextureNodes[e].updateTexture()),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=sT(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=Qv(r,s,i)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,!0===e.backend.isWebGLBackend&&(this.renderTarget.samples=0),this.renderTarget.depthTexture.isMultisampleRenderTargetTexture=this.renderTarget.samples>1,this.scope===DN.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s,camera:i}=this;this._pixelRatio=t.getPixelRatio();const r=t.getSize(zN);this.setSize(r.width,r.height);const n=t.getRenderTarget(),o=t.getMRT();this._cameraNear.value=i.near,this._cameraFar.value=i.far;for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(n),t.setMRT(o)}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}DN.COLOR="color",DN.DEPTH="depth";const kN=(e,t,s)=>wp(new DN(DN.COLOR,e,t,s)),GN=(e,t)=>wp(new LN(e,t)),WN=(e,t)=>wp(new DN(DN.DEPTH,e,t));class jN extends DN{static get type(){return"ToonOutlinePassNode"}constructor(e,t,s,i,r){super(DN.COLOR,e,t),this.colorNode=s,this.thicknessNode=i,this.alphaNode=r,this._materialCache=new WeakMap}updateBefore(e){const{renderer:t}=e,s=t.getRenderObjectFunction();t.setRenderObjectFunction(((e,s,i,r,n,o,a)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const h=this._getOutlineMaterial(n);t.renderObject(e,s,i,r,h,o,a)}t.renderObject(e,s,i,r,n,o,a)})),super.updateBefore(e),t.setRenderObjectFunction(s)}_createMaterial(){const e=new uT;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=d;const t=fx.negate(),s=Oy.mul(sx),i=Up(1),r=s.mul($p(ox,1)),n=s.mul($p(ox.add(t),1)),o=Ug(r.sub(n));return e.vertexNode=r.add(o.mul(this.thicknessNode).mul(r.w).mul(i)),e.colorNode=$p(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 HN=(e,t,s=new Xr(0,0,0),i=.003,r=1)=>wp(new jN(e,t,wp(s),wp(i),wp(r))),qN=Cp((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return vf(t,s,i)})).setLayout({name:"sRGBToLinearSRGB",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),$N=Cp((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return vf(t,s,i)})).setLayout({name:"linearSRGBTosRGB",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),XN=Cp((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),YN=Cp((([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"}]}),ZN=Cp((([e,t])=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(i).pow(2.2)})).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),JN=Cp((([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)})),KN=Cp((([e,t])=>{const s=Kp(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Kp(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=JN(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),QN=Kp(Wp(1.6605,-.1246,-.0182),Wp(-.5876,1.1329,-.1006),Wp(-.0728,-.0083,1.1187)),eC=Kp(Wp(.6274,.0691,.0164),Wp(.3293,.9195,.088),Wp(.0433,.0113,.8956)),tC=Cp((([e])=>{const t=Wp(e).toVar(),s=Wp(t.mul(t)).toVar(),i=Wp(s.mul(s)).toVar();return Up(15.5).mul(i.mul(s)).sub(Jm(40.14,i.mul(t))).add(Jm(31.96,i).sub(Jm(6.868,s.mul(t))).add(Jm(.4298,s).add(Jm(.1191,t).sub(.00232))))})),sC=Cp((([e,t])=>{const s=Wp(e).toVar(),i=Kp(Wp(.856627153315983,.137318972929847,.11189821299995),Wp(.0951212405381588,.761241990602591,.0767994186031903),Wp(.0482516061458583,.101439036467562,.811302368396859)),r=Kp(Wp(1.1271005818144368,-.1413297634984383,-.14132976349843826),Wp(-.11060664309660323,1.157823702216272,-.11060664309660294),Wp(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Up(-12.47393),o=Up(4.026069);return s.mulAssign(t),s.assign(eC.mul(s)),s.assign(i.mul(s)),s.assign(nf(s,1e-10)),s.assign(Eg(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(Tf(s,0,1)),s.assign(tC(s)),s.assign(r.mul(s)),s.assign(pf(nf(Wp(0),s),Wp(2.2))),s.assign(QN.mul(s)),s.assign(Tf(s,0,1)),s})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),iC=Cp((([e,t])=>{const s=Up(.76),i=Up(.15);e=e.mul(t);const r=rf(e.r,rf(e.g,e.b)),n=Ef(r.lessThan(.08),r.sub(Jm(6.25,r.mul(r))),.04);e.subAssign(n);const o=nf(e.r,nf(e.g,e.b));Ip(o.lessThan(s),(()=>e));const a=Zm(1,s),h=Zm(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(h.div(o));const u=Zm(1,Km(1,i.mul(o.sub(h)).add(1)));return vf(e,Wp(h),u)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class rC extends zd{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.code=e,this.language=s,this.includes=t}isGlobal(){return!0}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.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 nC=Ap(rC),oC=(e,t)=>nC(e,t,"js"),aC=(e,t)=>nC(e,t,"wgsl"),hC=(e,t)=>nC(e,t,"glsl");class uC extends rC{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,r=s.type,n=e.getCodeFromNode(this,r);""!==i&&(n.name=i);const o=e.getPropertyName(n),a=this.getNodeFunction(e).getCode(o);return n.code=a+"\n","property"===t?o:e.format(`${o}()`,r,t)}}const lC=(e,t=[],s="")=>{for(let e=0;ei.call(...e);return r.functionNode=i,r},cC=(e,t)=>lC(e,t,"glsl"),dC=(e,t)=>lC(e,t,"wgsl");class pC extends zd{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outpuType=null,this.events=new zs,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:Up()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Ad(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?Nd(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 mC=Ap(pC);class gC extends Map{get(e,t=null,...s){if(this.has(e))return super.get(e);if(null!==t){const i=t(...s);return this.set(e,i),i}}}class fC{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 yC=new gC;class xC extends zd{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new gC,this._output=mC(),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 s=this._outputs;return void 0===s[e]?s[e]=mC(t):s[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const s=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),s[e]=t,s[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),s[e]=t,s[e].events.addEventListener("refresh",this.onRefresh)):void 0===s[e]?(s[e]=mC(t),s[e].events.addEventListener("refresh",this.onRefresh)):s[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 s=this.getObject()[e];if("function"==typeof s)return s(...t)}async callAsync(e,...t){const s=this.getObject()[e];if("function"==typeof s)return"AsyncFunction"===s.constructor.name?await s(...t):s(...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 fC(this),t=yC.get("THREE"),s=yC.get("TSL"),i=this.getMethod(this.codeNode),r=[e,this._local,yC,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,s];this._object=i(...r);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:Up()}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+" };",s="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],s),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=[bd(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const s in this.parameters)t.push(this.parameters[s].getCacheKey(e));return vd(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 bC=Ap(xC);class vC extends zd{static get type(){return"FogNode"}constructor(e,t){super("float"),this.isFogNode=!0,this.colorNode=e,this.factorNode=t}getViewZNode(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||lx.z).negate()}setup(){return this.factorNode}}const TC=Ap(vC);class _C extends vC{static get type(){return"FogRangeNode"}constructor(e,t,s){super(e),this.isFogRangeNode=!0,this.nearNode=t,this.farNode=s}setup(e){const t=this.getViewZNode(e);return Sf(this.nearNode,this.farNode,t)}}const wC=Ap(_C);class SC extends vC{static get type(){return"FogExp2Node"}constructor(e,t){super(e),this.isFogExp2Node=!0,this.densityNode=t}setup(e){const t=this.getViewZNode(e),s=this.densityNode;return s.mul(s,t,t).negate().exp().oneMinus()}}const MC=Ap(SC);let AC=null,NC=null;class CC extends zd{static get type(){return"RangeNode"}constructor(e=Up(),t=Up()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Sd(this.minNode.value)),s=e.getTypeLength(Sd(this.maxNode.value));return t>s?t:s}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let s=null;if(t.count>1){const i=this.minNode.value,r=this.maxNode.value,n=e.getTypeLength(Sd(i)),o=e.getTypeLength(Sd(r));AC=AC||new xi,NC=NC||new xi,AC.setScalar(0),NC.setScalar(0),1===n?AC.setScalar(i):i.isColor?AC.set(i.r,i.g,i.b):AC.set(i.x,i.y,i.z||0,i.w||0),1===o?NC.setScalar(r):r.isColor?NC.set(r.r,r.g,r.b):NC.set(r.x,r.y,r.z||0,r.w||0);const a=4,h=a*t.count,u=new Float32Array(h);for(let e=0;ewp(new EC(e,t)),IC=BC("numWorkgroups","uvec3"),PC=BC("workgroupId","uvec3"),FC=BC("localId","uvec3"),UC=BC("subgroupSize","uint");const OC=Ap(class extends zd{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;!0===s.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}}),zC=()=>OC("workgroup").append(),LC=()=>OC("storage").append(),VC=()=>OC("texture").append();class DC extends Ld{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let s;const i=e.context.assign;if(s=super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}class kC extends zd{constructor(e,t,s=0){super(t),this.bufferType=t,this.bufferCount=s,this.isWorkgroupInfoNode=!0,this.scope=e}label(e){return this.name=e,this}getHash(){return this.uuid}setScope(e){return this.scope=e,this}getInputType(){return`${this.scope}Array`}element(e){return wp(new DC(this,e))}generate(e){return e.getScopedArray(this.name||`${this.scope}Array_${this.id}`,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}const GC=(e,t)=>wp(new kC("Workgroup",e,t));class WC extends Dd{static get type(){return"AtomicFunctionNode"}constructor(e,t,s,i=null){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.storeNode=i}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=this.method,s=this.getNodeType(e),i=this.getInputType(e),r=this.pointerNode,n=this.valueNode,o=[];o.push(`&${r.build(e,i)}`),o.push(n.build(e,i));const a=`${e.getMethod(t,s)}( ${o.join(", ")} )`;if(null!==this.storeNode){const t=this.storeNode.build(e,i);e.addLineFlowCode(`${t} = ${a}`,this)}else e.addLineFlowCode(a,this)}}WC.ATOMIC_LOAD="atomicLoad",WC.ATOMIC_STORE="atomicStore",WC.ATOMIC_ADD="atomicAdd",WC.ATOMIC_SUB="atomicSub",WC.ATOMIC_MAX="atomicMax",WC.ATOMIC_MIN="atomicMin",WC.ATOMIC_AND="atomicAnd",WC.ATOMIC_OR="atomicOr",WC.ATOMIC_XOR="atomicXor";const jC=Ap(WC),HC=(e,t,s,i)=>{const r=jC(e,t,s,i);return r.append(),r},qC=(e,t,s=null)=>HC(WC.ATOMIC_STORE,e,t,s),$C=(e,t,s=null)=>HC(WC.ATOMIC_ADD,e,t,s),XC=(e,t,s=null)=>HC(WC.ATOMIC_SUB,e,t,s),YC=(e,t,s=null)=>HC(WC.ATOMIC_MAX,e,t,s),ZC=(e,t,s=null)=>HC(WC.ATOMIC_MIN,e,t,s),JC=(e,t,s=null)=>HC(WC.ATOMIC_AND,e,t,s),KC=(e,t,s=null)=>HC(WC.ATOMIC_OR,e,t,s),QC=(e,t,s=null)=>HC(WC.ATOMIC_XOR,e,t,s);let eR;function tR(e){eR=eR||new WeakMap;let t=eR.get(e);return void 0===t&&eR.set(e,t={}),t}function sR(e){const t=tR(e);return t.position||(t.position=dm(new Ai).setGroup(um).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld))))}function iR(e){const t=tR(e);return t.targetPosition||(t.targetPosition=dm(new Ai).setGroup(um).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld))))}function rR(e){const t=tR(e);return t.viewPosition||(t.viewPosition=dm(new Ai).setGroup(um).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new Ai,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}const nR=e=>Ly.transformDirection(sR(e).sub(iR(e))),oR=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},aR=new WeakMap;class hR extends zd{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Wp().toVar("totalDiffuse"),this.totalSpecularNode=Wp().toVar("totalSpecular"),this.outgoingLightNode=Wp().toVar("outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getSelf().getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getDataFromNode(this);for(const s of t.nodes)s.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=(e=>e.sort(((e,t)=>e.id-t.id)))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(wp(e));else{let i=null;if(null!==s&&(i=oR(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;aR.has(e)?i=aR.get(e):(i=wp(new s(e)),aR.set(e,i)),t.push(i)}}this._lightNodes=t}setupLights(e,t){for(const s of t)s.build(e)}setup(e){null===this._lightNodes&&this.setupLightsNode(e);const t=e.context,s=t.lightingModel;let i=this.outgoingLightNode;if(s){const{_lightNodes:r,totalDiffuseNode:n,totalSpecularNode:o}=this;t.outgoingLight=i;const a=e.addStack();e.getDataFromNode(this).nodes=a.nodes,s.start(t,a,e),this.setupLights(e,r),s.indirect(t,a,e);const{backdrop:h,backdropAlpha:u}=t,{directDiffuse:l,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=t.reflectedLight;let m=l.add(d);null!==h&&(m=Wp(null!==u?u.mix(m,h):h),t.material.transparent=!0),n.assign(m),o.assign(c.add(p)),i.assign(n.add(o)),s.finish(t,a,e),i=i.bypass(e.removeStack())}return i}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}const uR=(e=[])=>wp(new hR).setLights(e),lR=Cp((({depthTexture:e,shadowCoord:t})=>By(e,t.xy).compare(t.z))),cR=Cp((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>By(e,t).compare(s),r=Dx("mapSize","vec2",s).setGroup(um),n=Dx("radius","float",s).setGroup(um),o=Vp(1).div(r),a=o.x.negate().mul(n),h=o.y.negate().mul(n),u=o.x.mul(n),l=o.y.mul(n),c=a.div(2),d=h.div(2),p=u.div(2),m=l.div(2);return Ym(i(t.xy.add(Vp(a,h)),t.z),i(t.xy.add(Vp(0,h)),t.z),i(t.xy.add(Vp(u,h)),t.z),i(t.xy.add(Vp(c,d)),t.z),i(t.xy.add(Vp(0,d)),t.z),i(t.xy.add(Vp(p,d)),t.z),i(t.xy.add(Vp(a,0)),t.z),i(t.xy.add(Vp(c,0)),t.z),i(t.xy,t.z),i(t.xy.add(Vp(p,0)),t.z),i(t.xy.add(Vp(u,0)),t.z),i(t.xy.add(Vp(c,m)),t.z),i(t.xy.add(Vp(0,m)),t.z),i(t.xy.add(Vp(p,m)),t.z),i(t.xy.add(Vp(a,l)),t.z),i(t.xy.add(Vp(0,l)),t.z),i(t.xy.add(Vp(u,l)),t.z)).mul(1/17)})),dR=Cp((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>By(e,t).compare(s),r=Dx("mapSize","vec2",s).setGroup(um),n=Vp(1).div(r),o=n.x,a=n.y,h=t.xy,u=Og(h.mul(r).add(.5));return h.subAssign(u.mul(n)),Ym(i(h,t.z),i(h.add(Vp(o,0)),t.z),i(h.add(Vp(0,a)),t.z),i(h.add(n),t.z),vf(i(h.add(Vp(o.negate(),0)),t.z),i(h.add(Vp(o.mul(2),0)),t.z),u.x),vf(i(h.add(Vp(o.negate(),a)),t.z),i(h.add(Vp(o.mul(2),a)),t.z),u.x),vf(i(h.add(Vp(0,a.negate())),t.z),i(h.add(Vp(0,a.mul(2))),t.z),u.y),vf(i(h.add(Vp(o,a.negate())),t.z),i(h.add(Vp(o,a.mul(2))),t.z),u.y),vf(vf(i(h.add(Vp(o.negate(),a.negate())),t.z),i(h.add(Vp(o.mul(2),a.negate())),t.z),u.x),vf(i(h.add(Vp(o.negate(),a.mul(2))),t.z),i(h.add(Vp(o.mul(2),a.mul(2))),t.z),u.x),u.y)).mul(1/9)})),pR=Cp((({depthTexture:e,shadowCoord:t})=>{const s=Up(1).toVar(),i=By(e).uv(t.xy).rg,r=af(t.z,i.x);return Ip(r.notEqual(Up(1)),(()=>{const e=t.z.sub(i.x),n=nf(0,i.y.mul(i.y));let o=n.div(n.add(e.mul(e)));o=Tf(Zm(o,.3).div(.95-.3)),s.assign(Tf(nf(r,o)))})),s})),mR=Cp((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Up(0).toVar(),n=Up(0).toVar(),o=e.lessThanEqual(Up(1)).select(Up(0),Up(2).div(e.sub(1))),a=e.lessThanEqual(Up(1)).select(Up(0),Up(-1));xv({start:Op(0),end:Op(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Up(e).mul(o)),u=i.uv(Ym(zv.xy,Vp(0,h).mul(t)).div(s)).x;r.addAssign(u),n.addAssign(u.mul(u))})),r.divAssign(e),n.divAssign(e);const h=Bg(n.sub(r.mul(r)));return Vp(r,h)})),gR=Cp((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Up(0).toVar(),n=Up(0).toVar(),o=e.lessThanEqual(Up(1)).select(Up(0),Up(2).div(e.sub(1))),a=e.lessThanEqual(Up(1)).select(Up(0),Up(-1));xv({start:Op(0),end:Op(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Up(e).mul(o)),u=i.uv(Ym(zv.xy,Vp(h,0).mul(t)).div(s));r.addAssign(u.x),n.addAssign(Ym(u.y.mul(u.y),u.x.mul(u.x)))})),r.divAssign(e),n.divAssign(e);const h=Bg(n.sub(r.mul(r)));return Vp(r,h)})),fR=[lR,cR,dR,pR];let yR=null;const xR=new MM;class bR extends zd{static get type(){return"ShadowNode"}constructor(e,t=null){super(),this.light=e,this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this.updateBeforeType=Ed.RENDER,this._node=null,this.isShadowNode=!0}setupShadow(e){const{object:t,renderer:s}=e;null===yR&&(yR=new uT,yR.fragmentNode=$p(0,0,0,1),yR.isShadowNodeMaterial=!0,yR.name="ShadowMaterial");const i=this.shadow,r=s.shadowMap.type,n=new Xa(i.mapSize.width,i.mapSize.height);n.compareFunction=ys;const o=e.createRenderTarget(i.mapSize.width,i.mapSize.height);if(o.depthTexture=n,i.camera.updateProjectionMatrix(),3===r){n.compareFunction=null,this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$e,type:Pe}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$e,type:Pe});const t=By(n),s=By(this.vsmShadowMapVertical.texture),r=Dx("blurSamples","float",i).setGroup(um),o=Dx("radius","float",i).setGroup(um),a=Dx("mapSize","vec2",i).setGroup(um);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new uT);h.fragmentNode=mR({samples:r,radius:o,size:a,shadowPass:t}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new uT),h.fragmentNode=gR({samples:r,radius:o,size:a,shadowPass:s}).context(e.getSharedContext()),h.name="VSMHorizontal"}const a=Dx("intensity","float",i).setGroup(um),h=Dx("bias","float",i).setGroup(um),u=Dx("normalBias","float",i).setGroup(um),l=t.material.shadowPositionNode||hx;let c,d=dm(i.matrix).setGroup(um).mul(l.add(Tx.mul(u)));if(i.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)d=d.xyz.div(d.w),c=d.z,s.coordinateSystem===Os&&(c=c.mul(2).sub(1));else{const e=d.w;d=d.xy.div(e);const t=dm("float").onRenderUpdate((()=>i.camera.near)),s=dm("float").onRenderUpdate((()=>i.camera.far));c=iT(e,t,s)}d=Wp(d.x,d.y.oneMinus(),c.add(h));const p=d.x.greaterThanEqual(0).and(d.x.lessThanEqual(1)).and(d.y.greaterThanEqual(0)).and(d.y.lessThanEqual(1)).and(d.z.lessThanEqual(1)),m=i.filterNode||fR[s.shadowMap.type]||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const g=By(o.texture,d),f=p.select(m({depthTexture:3===r?this.vsmShadowMapHorizontal.texture:n,shadowCoord:d,shadow:i}),Up(1));return this.shadowMap=o,this.shadow.map=o,vf(1,f.rgb.mix(g,1),a.mul(g.a))}setup(e){if(!1!==e.renderer.shadowMap.enabled)return null!==this._node?this._node:this._node=this.setupShadow(e)}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:o}=e,a=r.shadowMap.type,h=t.depthTexture.version;this._depthVersionCached=h;const u=n.overrideMaterial;n.overrideMaterial=yR,t.setSize(i.mapSize.width,i.mapSize.height),i.updateMatrices(s),i.camera.layers.mask=o.layers.mask;const l=r.getRenderTarget(),c=r.getRenderObjectFunction();r.setRenderObjectFunction(((e,...t)=>{(!0===e.castShadow||e.receiveShadow&&3===a)&&r.renderObject(e,...t)})),r.setRenderTarget(t),r.render(n,i.camera),r.setRenderObjectFunction(c),!0!==s.isPointLight&&3===a&&this.vsmPass(r),r.setRenderTarget(l),n.overrideMaterial=u}vsmPass(e){const{shadow:t}=this;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height),e.setRenderTarget(this.vsmShadowMapVertical),xR.material=this.vsmMaterialVertical,xR.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),xR.material=this.vsmMaterialHorizontal,xR.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),this.updateBeforeType=Ed.NONE}updateBefore(e){const{shadow:t}=this;(t.needsUpdate||t.autoUpdate)&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const vR=(e,t)=>wp(new bR(e,t));class TR extends Nv{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.updateType=Ed.FRAME,this.light=e,this.color=new Xr,this.colorNode=dm(this.color).setGroup(um),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0}getCacheKey(){return Td(super.getCacheKey(),this.light.id,this.light.castShadow?1:0)}getHash(){return this.light.uuid}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const e=vR(this.light);this.shadowNode=e,this.shadowColorNode=s=this.colorNode.mul(e),this.baseColorNode=this.colorNode}this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&this.shadowNode.dispose()}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const _R=Cp((e=>{const{lightDistance:t,cutoffDistance:s,decayExponent:i}=e,r=t.pow(i).max(.01).reciprocal();return s.greaterThan(0).select(r.mul(t.div(s).pow4().oneMinus().clamp().pow2()),r)})),wR=Cp((({color:e,lightViewPosition:t,cutoffDistance:s,decayExponent:i},r)=>{const n=r.context.lightingModel,o=t.sub(lx),a=o.normalize(),h=o.length(),u=_R({lightDistance:h,cutoffDistance:s,decayExponent:i}),l=e.mul(u),c=r.context.reflectedLight;n.direct({lightDirection:a,lightColor:l,reflectedLight:c},r.stack,r)}));class SR extends TR{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=dm(0).setGroup(um),this.decayExponentNode=dm(0).setGroup(um)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setup(){wR({color:this.colorNode,lightViewPosition:rR(this.light),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode}).append()}}const MR=Cp((([e=t()])=>{const t=e.mul(2),s=t.x.floor(),i=t.y.floor();return s.add(i).mod(2).sign()})),AR=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=Lp(e).toVar();return Ef(n,r,i)})).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),NR=Cp((([e,t])=>{const s=Lp(t).toVar(),i=Up(e).toVar();return Ef(s,i.negate(),i)})).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),CR=Cp((([e])=>{const t=Up(e).toVar();return Op(Pg(t))})).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),RR=Cp((([e,t])=>{const s=Up(e).toVar();return t.assign(CR(s)),s.sub(Up(t))})),ER=VS([Cp((([e,t,s,i,r,n])=>{const o=Up(n).toVar(),a=Up(r).toVar(),h=Up(i).toVar(),u=Up(s).toVar(),l=Up(t).toVar(),c=Up(e).toVar(),d=Up(Zm(1,a)).toVar();return Zm(1,o).mul(c.mul(d).add(l.mul(a))).add(o.mul(u.mul(d).add(h.mul(a))))})).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"}]}),Cp((([e,t,s,i,r,n])=>{const o=Up(n).toVar(),a=Up(r).toVar(),h=Wp(i).toVar(),u=Wp(s).toVar(),l=Wp(t).toVar(),c=Wp(e).toVar(),d=Up(Zm(1,a)).toVar();return Zm(1,o).mul(c.mul(d).add(l.mul(a))).add(o.mul(u.mul(d).add(h.mul(a))))})).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"}]})]),BR=VS([Cp((([e,t,s,i,r,n,o,a,h,u,l])=>{const c=Up(l).toVar(),d=Up(u).toVar(),p=Up(h).toVar(),m=Up(a).toVar(),g=Up(o).toVar(),f=Up(n).toVar(),y=Up(r).toVar(),x=Up(i).toVar(),b=Up(s).toVar(),v=Up(t).toVar(),T=Up(e).toVar(),_=Up(Zm(1,p)).toVar(),w=Up(Zm(1,d)).toVar();return Up(Zm(1,c)).toVar().mul(w.mul(T.mul(_).add(v.mul(p))).add(d.mul(b.mul(_).add(x.mul(p))))).add(c.mul(w.mul(y.mul(_).add(f.mul(p))).add(d.mul(g.mul(_).add(m.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"}]}),Cp((([e,t,s,i,r,n,o,a,h,u,l])=>{const c=Up(l).toVar(),d=Up(u).toVar(),p=Up(h).toVar(),m=Wp(a).toVar(),g=Wp(o).toVar(),f=Wp(n).toVar(),y=Wp(r).toVar(),x=Wp(i).toVar(),b=Wp(s).toVar(),v=Wp(t).toVar(),T=Wp(e).toVar(),_=Up(Zm(1,p)).toVar(),w=Up(Zm(1,d)).toVar();return Up(Zm(1,c)).toVar().mul(w.mul(T.mul(_).add(v.mul(p))).add(d.mul(b.mul(_).add(x.mul(p))))).add(c.mul(w.mul(y.mul(_).add(f.mul(p))).add(d.mul(g.mul(_).add(m.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"}]})]),IR=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=zp(e).toVar(),o=zp(n.bitAnd(zp(7))).toVar(),a=Up(AR(o.lessThan(zp(4)),r,i)).toVar(),h=Up(Jm(2,AR(o.lessThan(zp(4)),i,r))).toVar();return NR(a,Lp(o.bitAnd(zp(1)))).add(NR(h,Lp(o.bitAnd(zp(2)))))})).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),PR=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Up(t).toVar(),a=zp(e).toVar(),h=zp(a.bitAnd(zp(15))).toVar(),u=Up(AR(h.lessThan(zp(8)),o,n)).toVar(),l=Up(AR(h.lessThan(zp(4)),n,AR(h.equal(zp(12)).or(h.equal(zp(14))),o,r))).toVar();return NR(u,Lp(h.bitAnd(zp(1)))).add(NR(l,Lp(h.bitAnd(zp(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"}]}),FR=VS([IR,PR]),UR=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=Hp(e).toVar();return Wp(FR(n.x,r,i),FR(n.y,r,i),FR(n.z,r,i))})).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),OR=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Up(t).toVar(),a=Hp(e).toVar();return Wp(FR(a.x,o,n,r),FR(a.y,o,n,r),FR(a.z,o,n,r))})).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"}]}),zR=VS([UR,OR]),LR=Cp((([e])=>{const t=Up(e).toVar();return Jm(.6616,t)})).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),VR=Cp((([e])=>{const t=Up(e).toVar();return Jm(.982,t)})).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),DR=VS([LR,Cp((([e])=>{const t=Wp(e).toVar();return Jm(.6616,t)})).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),kR=VS([VR,Cp((([e])=>{const t=Wp(e).toVar();return Jm(.982,t)})).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),GR=Cp((([e,t])=>{const s=Op(t).toVar(),i=zp(e).toVar();return i.shiftLeft(s).bitOr(i.shiftRight(Op(32).sub(s)))})).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),WR=Cp((([e,t,s])=>{e.subAssign(s),e.bitXorAssign(GR(s,Op(4))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(GR(e,Op(6))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(GR(t,Op(8))),t.addAssign(e),e.subAssign(s),e.bitXorAssign(GR(s,Op(16))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(GR(e,Op(19))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(GR(t,Op(4))),t.addAssign(e)})),jR=Cp((([e,t,s])=>{const i=zp(s).toVar(),r=zp(t).toVar(),n=zp(e).toVar();return i.bitXorAssign(r),i.subAssign(GR(r,Op(14))),n.bitXorAssign(i),n.subAssign(GR(i,Op(11))),r.bitXorAssign(n),r.subAssign(GR(n,Op(25))),i.bitXorAssign(r),i.subAssign(GR(r,Op(16))),n.bitXorAssign(i),n.subAssign(GR(i,Op(4))),r.bitXorAssign(n),r.subAssign(GR(n,Op(14))),i.bitXorAssign(r),i.subAssign(GR(r,Op(24))),i})).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),HR=Cp((([e])=>{const t=zp(e).toVar();return Up(t).div(Up(zp(Op(4294967295))))})).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),qR=Cp((([e])=>{const t=Up(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"}]}),$R=VS([Cp((([e])=>{const t=Op(e).toVar(),s=zp(zp(1)).toVar(),i=zp(zp(Op(3735928559)).add(s.shiftLeft(zp(2))).add(zp(13))).toVar();return jR(i.add(zp(t)),i,i)})).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),Cp((([e,t])=>{const s=Op(t).toVar(),i=Op(e).toVar(),r=zp(zp(2)).toVar(),n=zp().toVar(),o=zp().toVar(),a=zp().toVar();return n.assign(o.assign(a.assign(zp(Op(3735928559)).add(r.shiftLeft(zp(2))).add(zp(13))))),n.addAssign(zp(i)),o.addAssign(zp(s)),jR(n,o,a)})).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Op(t).toVar(),n=Op(e).toVar(),o=zp(zp(3)).toVar(),a=zp().toVar(),h=zp().toVar(),u=zp().toVar();return a.assign(h.assign(u.assign(zp(Op(3735928559)).add(o.shiftLeft(zp(2))).add(zp(13))))),a.addAssign(zp(n)),h.addAssign(zp(r)),u.addAssign(zp(i)),jR(a,h,u)})).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Cp((([e,t,s,i])=>{const r=Op(i).toVar(),n=Op(s).toVar(),o=Op(t).toVar(),a=Op(e).toVar(),h=zp(zp(4)).toVar(),u=zp().toVar(),l=zp().toVar(),c=zp().toVar();return u.assign(l.assign(c.assign(zp(Op(3735928559)).add(h.shiftLeft(zp(2))).add(zp(13))))),u.addAssign(zp(a)),l.addAssign(zp(o)),c.addAssign(zp(n)),WR(u,l,c),u.addAssign(zp(r)),jR(u,l,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"}]}),Cp((([e,t,s,i,r])=>{const n=Op(r).toVar(),o=Op(i).toVar(),a=Op(s).toVar(),h=Op(t).toVar(),u=Op(e).toVar(),l=zp(zp(5)).toVar(),c=zp().toVar(),d=zp().toVar(),p=zp().toVar();return c.assign(d.assign(p.assign(zp(Op(3735928559)).add(l.shiftLeft(zp(2))).add(zp(13))))),c.addAssign(zp(u)),d.addAssign(zp(h)),p.addAssign(zp(a)),WR(c,d,p),c.addAssign(zp(o)),d.addAssign(zp(n)),jR(c,d,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"}]})]),XR=VS([Cp((([e,t])=>{const s=Op(t).toVar(),i=Op(e).toVar(),r=zp($R(i,s)).toVar(),n=Hp().toVar();return n.x.assign(r.bitAnd(Op(255))),n.y.assign(r.shiftRight(Op(8)).bitAnd(Op(255))),n.z.assign(r.shiftRight(Op(16)).bitAnd(Op(255))),n})).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Op(t).toVar(),n=Op(e).toVar(),o=zp($R(n,r,i)).toVar(),a=Hp().toVar();return a.x.assign(o.bitAnd(Op(255))),a.y.assign(o.shiftRight(Op(8)).bitAnd(Op(255))),a.z.assign(o.shiftRight(Op(16)).bitAnd(Op(255))),a})).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),YR=VS([Cp((([e])=>{const t=Vp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Up(RR(t.x,s)).toVar(),n=Up(RR(t.y,i)).toVar(),o=Up(qR(r)).toVar(),a=Up(qR(n)).toVar(),h=Up(ER(FR($R(s,i),r,n),FR($R(s.add(Op(1)),i),r.sub(1),n),FR($R(s,i.add(Op(1))),r,n.sub(1)),FR($R(s.add(Op(1)),i.add(Op(1))),r.sub(1),n.sub(1)),o,a)).toVar();return DR(h)})).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Op().toVar(),n=Up(RR(t.x,s)).toVar(),o=Up(RR(t.y,i)).toVar(),a=Up(RR(t.z,r)).toVar(),h=Up(qR(n)).toVar(),u=Up(qR(o)).toVar(),l=Up(qR(a)).toVar(),c=Up(BR(FR($R(s,i,r),n,o,a),FR($R(s.add(Op(1)),i,r),n.sub(1),o,a),FR($R(s,i.add(Op(1)),r),n,o.sub(1),a),FR($R(s.add(Op(1)),i.add(Op(1)),r),n.sub(1),o.sub(1),a),FR($R(s,i,r.add(Op(1))),n,o,a.sub(1)),FR($R(s.add(Op(1)),i,r.add(Op(1))),n.sub(1),o,a.sub(1)),FR($R(s,i.add(Op(1)),r.add(Op(1))),n,o.sub(1),a.sub(1)),FR($R(s.add(Op(1)),i.add(Op(1)),r.add(Op(1))),n.sub(1),o.sub(1),a.sub(1)),h,u,l)).toVar();return kR(c)})).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),ZR=VS([Cp((([e])=>{const t=Vp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Up(RR(t.x,s)).toVar(),n=Up(RR(t.y,i)).toVar(),o=Up(qR(r)).toVar(),a=Up(qR(n)).toVar(),h=Wp(ER(zR(XR(s,i),r,n),zR(XR(s.add(Op(1)),i),r.sub(1),n),zR(XR(s,i.add(Op(1))),r,n.sub(1)),zR(XR(s.add(Op(1)),i.add(Op(1))),r.sub(1),n.sub(1)),o,a)).toVar();return DR(h)})).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Op().toVar(),n=Up(RR(t.x,s)).toVar(),o=Up(RR(t.y,i)).toVar(),a=Up(RR(t.z,r)).toVar(),h=Up(qR(n)).toVar(),u=Up(qR(o)).toVar(),l=Up(qR(a)).toVar(),c=Wp(BR(zR(XR(s,i,r),n,o,a),zR(XR(s.add(Op(1)),i,r),n.sub(1),o,a),zR(XR(s,i.add(Op(1)),r),n,o.sub(1),a),zR(XR(s.add(Op(1)),i.add(Op(1)),r),n.sub(1),o.sub(1),a),zR(XR(s,i,r.add(Op(1))),n,o,a.sub(1)),zR(XR(s.add(Op(1)),i,r.add(Op(1))),n.sub(1),o,a.sub(1)),zR(XR(s,i.add(Op(1)),r.add(Op(1))),n,o.sub(1),a.sub(1)),zR(XR(s.add(Op(1)),i.add(Op(1)),r.add(Op(1))),n.sub(1),o.sub(1),a.sub(1)),h,u,l)).toVar();return kR(c)})).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),JR=VS([Cp((([e])=>{const t=Up(e).toVar(),s=Op(CR(t)).toVar();return HR($R(s))})).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),Cp((([e])=>{const t=Vp(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar();return HR($R(s,i))})).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar(),r=Op(CR(t.z)).toVar();return HR($R(s,i,r))})).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),Cp((([e])=>{const t=$p(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar(),r=Op(CR(t.z)).toVar(),n=Op(CR(t.w)).toVar();return HR($R(s,i,r,n))})).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),KR=VS([Cp((([e])=>{const t=Up(e).toVar(),s=Op(CR(t)).toVar();return Wp(HR($R(s,Op(0))),HR($R(s,Op(1))),HR($R(s,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),Cp((([e])=>{const t=Vp(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar();return Wp(HR($R(s,i,Op(0))),HR($R(s,i,Op(1))),HR($R(s,i,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar(),r=Op(CR(t.z)).toVar();return Wp(HR($R(s,i,r,Op(0))),HR($R(s,i,r,Op(1))),HR($R(s,i,r,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Cp((([e])=>{const t=$p(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar(),r=Op(CR(t.z)).toVar(),n=Op(CR(t.w)).toVar();return Wp(HR($R(s,i,r,n,Op(0))),HR($R(s,i,r,n,Op(1))),HR($R(s,i,r,n,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),QR=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Up(0).toVar(),u=Up(1).toVar();return xv(o,(()=>{h.addAssign(u.mul(YR(a))),u.mulAssign(r),a.mulAssign(n)})),h})).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"}]}),eE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Wp(0).toVar(),u=Up(1).toVar();return xv(o,(()=>{h.addAssign(u.mul(ZR(a))),u.mulAssign(r),a.mulAssign(n)})),h})).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"}]}),tE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar();return Vp(QR(a,o,n,r),QR(a.add(Wp(Op(19),Op(193),Op(17))),o,n,r))})).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"}]}),sE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Wp(eE(a,o,n,r)).toVar(),u=Up(QR(a.add(Wp(Op(19),Op(193),Op(17))),o,n,r)).toVar();return $p(h,u)})).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"}]}),iE=Cp((([e,t,s,i,r,n,o])=>{const a=Op(o).toVar(),h=Up(n).toVar(),u=Op(r).toVar(),l=Op(i).toVar(),c=Op(s).toVar(),d=Op(t).toVar(),p=Vp(e).toVar(),m=Wp(KR(Vp(d.add(l),c.add(u)))).toVar(),g=Vp(m.x,m.y).toVar();g.subAssign(.5),g.mulAssign(h),g.addAssign(.5);const f=Vp(Vp(Up(d),Up(c)).add(g)).toVar(),y=Vp(f.sub(p)).toVar();return Ip(a.equal(Op(2)),(()=>Wg(y.x).add(Wg(y.y)))),Ip(a.equal(Op(3)),(()=>nf(Wg(y.x),Wg(y.y)))),cf(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"}]}),rE=VS([iE,Cp((([e,t,s,i,r,n,o,a,h])=>{const u=Op(h).toVar(),l=Up(a).toVar(),c=Op(o).toVar(),d=Op(n).toVar(),p=Op(r).toVar(),m=Op(i).toVar(),g=Op(s).toVar(),f=Op(t).toVar(),y=Wp(e).toVar(),x=Wp(KR(Wp(f.add(p),g.add(d),m.add(c)))).toVar();x.subAssign(.5),x.mulAssign(l),x.addAssign(.5);const b=Wp(Wp(Up(f),Up(g),Up(m)).add(x)).toVar(),v=Wp(b.sub(y)).toVar();return Ip(u.equal(Op(2)),(()=>Wg(v.x).add(Wg(v.y)).add(Wg(v.z)))),Ip(u.equal(Op(3)),(()=>nf(nf(Wg(v.x),Wg(v.y)),Wg(v.z)))),cf(v,v)})).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"}]})]),nE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(RR(n.x,o),RR(n.y,a)).toVar(),u=Up(1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(rE(h,e,t,o,a,r,i)).toVar();u.assign(rf(u,s))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),oE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(RR(n.x,o),RR(n.y,a)).toVar(),u=Vp(1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(rE(h,e,t,o,a,r,i)).toVar();Ip(s.lessThan(u.x),(()=>{u.y.assign(u.x),u.x.assign(s)})).ElseIf(s.lessThan(u.y),(()=>{u.y.assign(s)}))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),aE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(RR(n.x,o),RR(n.y,a)).toVar(),u=Wp(1e6,1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(rE(h,e,t,o,a,r,i)).toVar();Ip(s.lessThan(u.x),(()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(s)})).ElseIf(s.lessThan(u.y),(()=>{u.z.assign(u.y),u.y.assign(s)})).ElseIf(s.lessThan(u.z),(()=>{u.z.assign(s)}))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),hE=VS([nE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(RR(n.x,o),RR(n.y,a),RR(n.z,h)).toVar(),l=Up(1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(rE(u,e,t,s,o,a,h,r,i)).toVar();l.assign(rf(l,n))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),uE=VS([oE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(RR(n.x,o),RR(n.y,a),RR(n.z,h)).toVar(),l=Vp(1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(rE(u,e,t,s,o,a,h,r,i)).toVar();Ip(n.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(n)})).ElseIf(n.lessThan(l.y),(()=>{l.y.assign(n)}))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),lE=VS([aE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(RR(n.x,o),RR(n.y,a),RR(n.z,h)).toVar(),l=Wp(1e6,1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(rE(u,e,t,s,o,a,h,r,i)).toVar();Ip(n.lessThan(l.x),(()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(n)})).ElseIf(n.lessThan(l.y),(()=>{l.z.assign(l.y),l.y.assign(n)})).ElseIf(n.lessThan(l.z),(()=>{l.z.assign(n)}))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),cE=Cp((([e])=>{const t=e.y,s=e.z,i=Wp().toVar();return Ip(t.lessThan(1e-4),(()=>{i.assign(Wp(s,s,s))})).Else((()=>{let r=e.x;r=r.sub(Pg(r)).mul(6).toVar();const n=Op(Kg(r)),o=r.sub(Up(n)),a=s.mul(t.oneMinus()),h=s.mul(t.mul(o).oneMinus()),u=s.mul(t.mul(o.oneMinus()).oneMinus());Ip(n.equal(Op(0)),(()=>{i.assign(Wp(s,u,a))})).ElseIf(n.equal(Op(1)),(()=>{i.assign(Wp(h,s,a))})).ElseIf(n.equal(Op(2)),(()=>{i.assign(Wp(a,s,u))})).ElseIf(n.equal(Op(3)),(()=>{i.assign(Wp(a,h,s))})).ElseIf(n.equal(Op(4)),(()=>{i.assign(Wp(u,a,s))})).Else((()=>{i.assign(Wp(s,a,h))}))})),i})).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),dE=Cp((([e])=>{const t=Wp(e).toVar(),s=Up(t.x).toVar(),i=Up(t.y).toVar(),r=Up(t.z).toVar(),n=Up(rf(s,rf(i,r))).toVar(),o=Up(nf(s,nf(i,r))).toVar(),a=Up(o.sub(n)).toVar(),h=Up().toVar(),u=Up().toVar(),l=Up().toVar();return l.assign(o),Ip(o.greaterThan(0),(()=>{u.assign(a.div(o))})).Else((()=>{u.assign(0)})),Ip(u.lessThanEqual(0),(()=>{h.assign(0)})).Else((()=>{Ip(s.greaterThanEqual(o),(()=>{h.assign(i.sub(r).div(a))})).ElseIf(i.greaterThanEqual(o),(()=>{h.assign(Ym(2,r.sub(s).div(a)))})).Else((()=>{h.assign(Ym(4,s.sub(i).div(a)))})),h.mulAssign(1/6),Ip(h.lessThan(0),(()=>{h.addAssign(1)}))})),Wp(h,u,l)})).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),pE=Cp((([e])=>{const t=Wp(e).toVar(),s=qp(ig(t,Wp(.04045))).toVar(),i=Wp(t.div(12.92)).toVar(),r=Wp(pf(nf(t.add(Wp(.055)),Wp(0)).div(1.055),Wp(2.4))).toVar();return vf(i,r,s)})).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),mE=(e,t)=>{e=Up(e),t=Up(t);const s=Vp(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Sf(e.sub(s),e.add(s),t)},gE=(e,t,s,i)=>vf(e,t,s[i].clamp()),fE=(e,t,s=My())=>gE(e,t,s,"x"),yE=(e,t,s=My())=>gE(e,t,s,"y"),xE=(e,t,s,i,r)=>vf(e,t,mE(s,i[r])),bE=(e,t,s,i=My())=>xE(e,t,s,i,"x"),vE=(e,t,s,i=My())=>xE(e,t,s,i,"y"),TE=(e=1,t=0,s=My())=>s.mul(e).add(t),_E=(e,t=1)=>(e=Up(e)).abs().pow(t).mul(e.sign()),wE=(e,t=1,s=.5)=>Up(e).sub(s).mul(t).add(s),SE=(e=My(),t=1,s=0)=>YR(e.convert("vec2|vec3")).mul(t).add(s),ME=(e=My(),t=1,s=0)=>ZR(e.convert("vec2|vec3")).mul(t).add(s),AE=(e=My(),t=1,s=0)=>{e=e.convert("vec2|vec3");return $p(ZR(e),YR(e.add(Vp(19,73)))).mul(t).add(s)},NE=(e=My(),t=1)=>hE(e.convert("vec2|vec3"),t,Op(1)),CE=(e=My(),t=1)=>uE(e.convert("vec2|vec3"),t,Op(1)),RE=(e=My(),t=1)=>lE(e.convert("vec2|vec3"),t,Op(1)),EE=(e=My())=>JR(e.convert("vec2|vec3")),BE=(e=My(),t=3,s=2,i=.5,r=1)=>QR(e,Op(t),s,i).mul(r),IE=(e=My(),t=3,s=2,i=.5,r=1)=>tE(e,Op(t),s,i).mul(r),PE=(e=My(),t=3,s=2,i=.5,r=1)=>eE(e,Op(t),s,i).mul(r),FE=(e=My(),t=3,s=2,i=.5,r=1)=>sE(e,Op(t),s,i).mul(r),UE=Cp((([e,t])=>{const s=e.x,i=e.y,r=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(i)),n=n.add(t.element(2).mul(1.023328).mul(r)),n=n.add(t.element(3).mul(1.023328).mul(s)),n=n.add(t.element(4).mul(.858086).mul(s).mul(i)),n=n.add(t.element(5).mul(.858086).mul(i).mul(r)),n=n.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(s).mul(r)),n=n.add(t.element(8).mul(.429043).mul(Jm(s,s).sub(Jm(i,i)))),n})),OE=new xS;class zE extends jw{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===r)i._clearColor.getRGB(OE,Jt),OE.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(OE,Jt),OE.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;OE.copy(i._clearColor);let o=s.backgroundMesh;if(void 0===o){const e=Pf($p(n).mul(LM),{getUV:()=>bx,getTextureLevel:()=>zM});let t=tv();t=t.setZ(t.w);const i=new uT;i.name="Background.material",i.side=d,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.lights=!1,i.vertexNode=t,i.colorNode=e,s.backgroundMeshNode=e,s.backgroundMesh=o=new On(new cu(1,32,32),i),o.frustumCulled=!1,o.name="Background.mesh",o.onBeforeRender=function(e,t,s){this.matrixWorld.copyPosition(s.matrixWorld)}}const a=n.getCacheKey();s.backgroundCacheKey!==a&&(s.backgroundMeshNode.node=$p(n).mul(LM),s.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null)}else console.error("THREE.Renderer: Unsupported background configuration.",r);if(!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=OE.r,e.g=OE.g,e.b=OE.b,e.a=OE.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(e.r*=e.a,e.g*=e.a,e.b*=e.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,s.clearColor=!0===i.autoClearColor,s.clearDepth=!0===i.autoClearDepth,s.clearStencil=!0===i.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let LE=0;class VE{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=LE++}}class DE{constructor(e,t,s,i,r,n,o,a,h,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=o,this.updateAfterNodes=a,this.monitor=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new VE(t.name,[],t.index,t);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class kE{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class GE{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf()}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 WE{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class jE extends WE{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class HE{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let qE=0;class $E{constructor(e=null){this.id=qE++,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 XE{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 YE extends XE{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class ZE extends XE{constructor(e,t=new Ys){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class JE extends XE{constructor(e,t=new Ai){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class KE extends XE{constructor(e,t=new xi){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class QE extends XE{constructor(e,t=new Xr){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class eB extends XE{constructor(e,t=new Zs){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class tB extends XE{constructor(e,t=new sr){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class sB extends YE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class iB extends ZE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class rB extends JE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class nB extends KE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class oB extends QE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class aB extends eB{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class hB extends tB{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}const uB=[.125,.215,.35,.446,.526,.582],lB=20,cB=new wl(-1,1,1,-1,0,1),dB=new Hn(90,1),pB=new Xr;let mB=null,gB=0,fB=0;const yB=(1+Math.sqrt(5))/2,xB=1/yB,bB=[new Ai(-yB,xB,0),new Ai(yB,xB,0),new Ai(-xB,0,yB),new Ai(xB,0,yB),new Ai(0,yB,-xB),new Ai(0,yB,xB),new Ai(-1,1,-1),new Ai(1,1,-1),new Ai(-1,1,1),new Ai(1,1,1)],vB=[3,1,5,0,4,2],TB=Y_(My(),Sy("faceIndex")).normalize(),_B=Wp(TB.x,TB.y.negate(),TB.z);class wB{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}fromScene(e,t=0,s=.1,i=100){mB=this._renderer.getRenderTarget(),gB=this._renderer.getActiveCubeFace(),fB=this._renderer.getActiveMipmapLevel(),this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,s,i,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=NB(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=CB(),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())}_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?h=uB[a-e+4-1]:0===a&&(h=0),i.push(h);const u=1/(o-2),l=-u,c=1+u,d=[l,l,c,l,c,c,l,l,c,c,l,c],p=6,m=6,g=3,f=2,y=1,x=new Float32Array(g*m*p),b=new Float32Array(f*m*p),v=new Float32Array(y*m*p);for(let e=0;e2?0:-1,i=[t,s,0,t+2/3,s,0,t+2/3,s+1,0,t,s,0,t+2/3,s+1,0,t,s+1,0],r=vB[e];x.set(i,g*m*r),b.set(d,f*m*r);const n=[r,r,r,r,r,r];v.set(n,y*m*r)}const T=new Sn;T.setAttribute("position",new an(x,g)),T.setAttribute("uv",new an(b,f)),T.setAttribute("faceIndex",new an(v,y)),t.push(T),r.push(new On(T,null)),n>4&&n--}return{lodPlanes:t,sizeLods:s,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,s){const i=Ox(new Array(lB).fill(0)),r=dm(new Ai(0,1,0)),n=dm(0),o=Up(lB),a=dm(0),h=dm(1),u=By(null),l=dm(0),c=Up(1/t),d=Up(1/s),p=Up(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:_B,dTheta:n,samples:h,envMap:u,mipInt:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=AB("blur");return g.uniforms=m,g.fragmentNode=Q_({...m,latitudinal:a.equal(1)}),g}(i,e,t)}return i}async _compileMaterial(e){const t=new On(this._lodPlanes[0],e);await this._renderer.compile(t,cB)}_sceneToCubeUV(e,t,s,i){const r=dB;r.near=t,r.far=s;const n=[-1,1,-1,-1,-1,-1],o=[1,1,1,-1,-1,-1],a=this._renderer,h=a.autoClear;a.getClearColor(pB),a.autoClear=!1;let u=this._backgroundBox;if(null===u){const e=new Kr({name:"PMREM.Background",side:d,depthWrite:!1,depthTest:!1});u=new On(new Ln,e)}let l=!1;const c=e.background;c?c.isColor&&(u.material.color.copy(c),e.background=null,l=!0):(u.material.color.copy(pB),l=!0),a.setRenderTarget(i),a.clear(),l&&a.render(u,r);for(let t=0;t<6;t++){const s=t%3;0===s?(r.up.set(0,n[t],0),r.lookAt(o[t],0,0)):1===s?(r.up.set(0,0,n[t]),r.lookAt(0,o[t],0)):(r.up.set(0,n[t],0),r.lookAt(0,0,o[t]));const h=this._cubeSize;MB(i,s*h,t>2?h:0,h,h),a.render(e,r)}a.autoClear=h,e.background=c}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===he||e.mapping===ue;i?null===this._cubemapMaterial&&(this._cubemapMaterial=NB(e)):null===this._equirectMaterial&&(this._equirectMaterial=CB(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;MB(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,cB)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;tlB&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const g=[];let f=0;for(let e=0;ey-4?i-y+4:0),4*(this._cubeSize-x),3*x,2*x),a.setRenderTarget(t),a.render(u,cB)}}function SB(e,t,s){const i=new bi(e,t,s);return i.texture.mapping=de,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function MB(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function AB(e){const t=new uT;return t.depthTest=!1,t.depthWrite=!1,t.blending=m,t.name=`PMREM_${e}`,t}function NB(e){const t=AB("cubemap");return t.fragmentNode=Bx(e,_B),t}function CB(e){const t=AB("equirect");return t.fragmentNode=By(e,wT(_B),0),t}const RB=new WeakMap,EB=new Map([[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),BB=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),IB=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class PB{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.monitor=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.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=_S(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new $E,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.useComparisonMethod=!1}getBindGroupsCache(){let e=RB.get(this.renderer);return void 0===e&&(e=new zw,RB.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new bi(e,t,s)}createCubeRenderTarget(e,t){return new ST(e,t)}createPMREMGenerator(){return new wB(this.renderer)}includes(e){return this.nodes.includes(e)}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let r,n=!0;for(const e of t)i.push(e),n=n&&!0!==e.groupNode.shared;return n?(r=s.get(i),void 0===r&&(r=new VE(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new VE(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},s=this.bindings;for(const e of Fd)for(const i in s[e]){const r=s[e][i];(t[i]||(t[i]=[])).push(...r)}e=[];for(const s in t){const i=t[s],r=this._getBindGroup(s,i);e.push(r)}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(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${IB(t.r)}, ${IB(t.g)}, ${IB(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>4&&t&&(t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' 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 s=this.attributes;for(const t of s)if(t.name===e)return t;const i=new kE(e,t);return s.push(i),i}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||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Ee)return"int";if(t===Be)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;const s=EB.get(e);return("float"===t?"":t[0])+s}getTypeFromArray(e){return BB.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof gn||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[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(){return this.stack=_S(this.stack),this.stacks.push(Bp()||this.stack),Ep(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Ep(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let i=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getData(e);return void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e);let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new kE("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeFromNode(e,t=this.shaderStage){const s=this.getDataFromNode(e,t);if(void 0===s.structType){const i=this.structs.index++;e.name=`StructType${i}`,this.structs[t].push(e),s.structType=e}return e}getUniformFromNode(e,t,s=this.shaderStage,i=null){const r=this.getDataFromNode(e,s,this.globalCache);let n=r.uniform;if(void 0===n){const o=this.uniforms.index++;n=new GE(i||"nodeUniform"+o,t,e),this.uniforms[s].push(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage){const r=this.getDataFromNode(e,i);let n=r.variable;if(void 0===n){const e=this.vars[i]||(this.vars[i]=[]);null===t&&(t="nodeVar"+e.length),n=new WE(t,s),e.push(n),r.variable=n}return n}getVaryingFromNode(e,t=null,s=e.getNodeType(this)){const i=this.getDataFromNode(e,"any");let r=i.varying;if(void 0===r){const e=this.varyings,n=e.length;null===t&&(t="nodeVarying"+n),r=new jE(t,s),e.push(r),i.varying=r}return r}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;r=new HE("nodeCode"+n,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,n=t;for(;n;){if(!0===i.get(n)){r=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(r)for(const e of s)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),n=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),n.set(s,!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),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}buildFunctionNode(e){const t=new uC,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[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)s[e.name]=new bS(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,r=this.cache,n=this.buildStage,o=this.stack,a={code:""};this.flow=a,this.vars={},this.cache=new $E,this.stack=_S();for(const s of Pd)this.setBuildStage(s),a.result=e.build(this,t);return a.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.cache=r,this.stack=o,this.setBuildStage(n),a}getFunctionOperator(){return null}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const r=this.shaderStage;this.setShaderStage(e);const n=this.flowChildNode(t,s);return null!==i&&(n.code+=`${this.tab+i} = ${n.result};\n`),this.flowCode[e]=this.flowCode[e]+n.code,this.setShaderStage(r),n}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t){return`${this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(void 0!==s)for(const e of s)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}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.")}build(){const{object:e,material:t,renderer:s}=this;if(null!==t){let e=s.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new uT),e.build(this)}else this.addFlow("compute",e);for(const e of Pd){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of Fd){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"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 sB(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new iB(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new rB(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new nB(e);if("color"===t)return new oB(e);if("mat3"===t)return new aB(e);if("mat4"===t)return new hB(e);throw new Error(`Uniform "${t}" not declared.`)}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const i=this.getTypeLength(t),r=this.getTypeLength(s);return 16===i&&9===r?`${this.getType(s)}(${e}[0].xyz, ${e}[1].xyz, ${e}[2].xyz)`:9===i&&4===r?`${this.getType(s)}(${e}[0].xy, ${e}[1].xy)`:i>4||r>4||0===r?e:i===r?`${this.getType(s)}( ${e} )`:i>r?this.format(`${e}.${"xyz".slice(0,r)}`,this.getTypeFromLength(r,this.getComponentType(t)),s):4===r&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${e} - Node System\n`}}class FB{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.startTime=null,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 s=e.get(t);return void 0===s&&(s={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(s,this.renderId)}else t===Ed.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(s,this.renderId)}else t===Ed.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.frameId&&!1!==e.update(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.renderId&&!1!==e.update(this)&&t.set(s,this.renderId)}else t===Ed.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 UB{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}UB.isNodeFunctionInput=!0;class OB extends TR{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,s=this.colorNode,i=nR(this.light),r=e.context.reflectedLight;t.direct({lightDirection:i,lightColor:s,reflectedLight:r},e.stack,e)}}const zB=new sr,LB=new sr;let VB=null;class DB extends TR{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=dm(new Ai).setGroup(um),this.halfWidth=dm(new Ai).setGroup(um)}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;LB.identity(),zB.copy(t.matrixWorld),zB.premultiply(s),LB.extractRotation(zB),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(LB),this.halfHeight.value.applyMatrix4(LB)}setup(e){let t,s;super.setup(e),e.isAvailable("float32Filterable")?(t=By(VB.LTC_FLOAT_1),s=By(VB.LTC_FLOAT_2)):(t=By(VB.LTC_HALF_1),s=By(VB.LTC_HALF_2));const{colorNode:i,light:r}=this,n=e.context.lightingModel,o=rR(r),a=e.context.reflectedLight;n.directRectArea({lightColor:i,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,reflectedLight:a,ltc_1:t,ltc_2:s},e.stack,e)}static setLTC(e){VB=e}}class kB extends TR{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=dm(0).setGroup(um),this.penumbraCosNode=dm(0).setGroup(um),this.cutoffDistanceNode=dm(0).setGroup(um),this.decayExponentNode=dm(0).setGroup(um)}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){const{coneCosNode:t,penumbraCosNode:s}=this;return Sf(t,s,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:s,cutoffDistanceNode:i,decayExponentNode:r,light:n}=this,o=rR(n).sub(lx),a=o.normalize(),h=a.dot(nR(n)),u=this.getSpotAttenuation(h),l=o.length(),c=_R({lightDistance:l,cutoffDistance:i,decayExponent:r}),d=s.mul(u).mul(c),p=e.context.reflectedLight;t.direct({lightDirection:a,lightColor:d,reflectedLight:p},e.stack,e)}}class GB extends kB{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e){const t=this.light.iesMap;let s=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);s=By(t,Vp(i,0),0).r}else s=super.getSpotAttenuation(e);return s}}class WB extends TR{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class jB extends TR{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=sR(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=dm(new Xr).setGroup(um)}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:s,lightDirectionNode:i}=this,r=xx.dot(i).mul(.5).add(.5),n=vf(s,t,r);e.context.irradiance.addAssign(n)}}class HB extends TR{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Ai);this.lightProbe=Ox(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=UE(bx,this.lightProbe);e.context.irradiance.addAssign(t)}}class qB{parseFunction(){console.warn("Abstract function.")}}class $B{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}$B.isNodeFunction=!0;const XB=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,YB=/[a-z_0-9]+/gi,ZB="#pragma main";class JB extends $B{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(ZB),s=-1!==t?e.slice(t+12):e,i=s.match(XB);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=YB.exec(r));)n.push(o);const a=[];let h=0;for(;h0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==s||i){let i=null;if(!0===s.isCubeTexture||s.mapping===le||s.mapping===ce||s.mapping===de)if(e.backgroundBlurriness>0||s.mapping===de)i=rw(s,bx);else{let e;e=!0===s.isCubeTexture?Bx(s):By(s),i=RT(e)}else!0===s.isTexture?i=By(s,Uv.flipY()).setUpdateMatrix(!0):!0!==s.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",s);t.backgroundNode=i,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){let e=null;if(s.isFogExp2){const t=Dx("color","color",s).setGroup(um),i=Dx("density","float",s).setGroup(um);e=MC(t,i)}else if(s.isFog){const t=Dx("color","color",s).setGroup(um),i=Dx("near","float",s).setGroup(um),r=Dx("far","float",s).setGroup(um);e=wC(t,i,r)}else console.error("WebGPUNodes: Unsupported fog configuration.",s);t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){let e=null;!0===s.isCubeTexture?e=Bx(s):!0===s.isTexture?e=By(s):console.error("Nodes: Unsupported environment configuration.",s),t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,r=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=i,n.material=r,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}hasOutputChange(e){return QB.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=By(e,Uv).renderOutput(t.toneMapping,t.currentColorSpace);return QB.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new FB,this.nodeBuilderCache=new Map}}class tI{constructor(e,t){this.scene=e,this.camera=t}clone(){return Object.assign(new this.constructor,this)}}class sI{constructor(){this.lists=new zw}get(e,t){const s=this.lists,i=[e,t];let r=s.get(i);return void 0===r&&(r=new tI(e,t),s.set(i,r)),r}dispose(){this.lists=new zw}}class iI{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map,this.colorSpaceNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(null!==s){t=new s;for(const s in e)t[s]=e[s]}return t}addColorSpace(e,t){this.addType(e,t,this.colorSpaceNodes)}getColorSpaceFunction(e){return this.colorSpaceNodes.get(e)||null}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t.type,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t))console.warn(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}}addClass(e,t,s){if(s.has(t))console.warn(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}}const rI=new hR;class nI extends zw{constructor(){super()}createNode(e=[]){return(new hR).setLights(e)}getNode(e,t){if(e.isQuadMesh)return rI;const s=[e,t];let i=this.get(s);return void 0===i&&(i=this.createNode(),this.set(s,i)),i}}const oI=new Kn,aI=new Ys,hI=new xi,uI=new Ko,lI=new sr,cI=new xi;class dI{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:r=!0,stencil:n=!1,antialias:o=!1,samples:a=0,getFallback:h=null}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=a||!0===o?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=Zt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=r,this.stencil=n,this.clippingPlanes=[],this.info=new eS,this.nodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new iI,this.lighting=new nI,this._getFallback=h,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new xi(0,0,this._width,this._height),this._scissor=new xi(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new MM(new uT),this._quad.material.type="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const u=!0===this.alpha?0:1;this._clearColor=new xS(0,0,0,u),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr={enabled:!1},this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,s)=>{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(e,t,this._renderTarget),n=e.overrideMaterial||s.material,o=this._objects.get(s,n,e,t,i.lightsNode,r),{fragmentShader:a,vertexShader:h}=o.getNodeBuilderState();return{fragmentShader:a,vertexShader:h}}}}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 s=this.backend;try{await s.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=s=this._getFallback(e),await s.init(this)}catch(e){return void t(e)}}this._nodes=new eI(this,s),this._animation=new Ow(this._nodes,this.info),this._attributes=new Zw(s),this._background=new zE(this,this._nodes),this._geometries=new Qw(this._attributes,this.info),this._textures=new yS(this,s,this.info),this._pipelines=new oS(s,this._nodes),this._bindings=new aS(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Ww(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new cS(this.lighting),this._bundles=new sI,this._renderContexts=new gS,this._initialized=!0,e()}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,n=this._currentRenderContext,o=this._currentRenderObjectFunction,a=this._compilationPromises,h=!0===e.isScene?e:oI;null===s&&(s=e);const u=this._renderTarget,l=this._renderContexts.get(s,t,u),c=this._activeMipmapLevel,d=[];this._currentRenderContext=l,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),l.depth=this.depth,l.stencil=this.stencil,l.clippingContext||(l.clippingContext=new Vw),l.clippingContext.updateGlobal(this,t),h.onBeforeRender(this,e,t,u);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p),s!==e&&s.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==u){this._textures.updateRenderTarget(u,c);const e=this._textures.get(u);l.textures=e.textures,l.depthTexture=e.depthTexture}else l.textures=null,l.depthTexture=null;this._nodes.updateScene(h),this._background.update(h,p,l);const m=p.opaque,g=p.transparent,f=p.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,h,f),!0===this.transparent&&g.length>0&&this._renderObjects(g,t,h,f),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=o,this._compilationPromises=a,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init();const s=this._renderScene(e,t);await this.backend.resolveTimestampAsync(s,"render")}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,o=this._currentRenderContext,a=this._bundles.get(i,r),h=this.backend.get(a);void 0===h.renderContexts&&(h.renderContexts=new Set);const u=i.version!==h.version,l=!1===h.renderContexts.has(o)||u;if(h.renderContexts.add(o),l){this.backend.beginBundle(o),(void 0===h.renderObjects||u)&&(h.renderObjects=[]),this._currentRenderBundle=a;const e=n.opaque;e.length>0&&this._renderObjects(e,r,t,s),this._currentRenderBundle=null,this.backend.finishBundle(o,a),h.version=i.version}else{const{renderObjects:e}=h;for(let t=0,s=e.length;t>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=b,p.viewport=!1===p.viewportValue.equals(hI),p.scissorValue.copy(f).multiplyScalar(y).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(hI),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new Vw),p.clippingContext.updateGlobal(this,t),h.onBeforeRender(this,e,t,d),lI.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),uI.setFromProjectionMatrix(lI,m);const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,c);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=l,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,this._nodes.updateScene(h),this._background.update(h,v,p),this.backend.beginRender(p);const{bundles:T,lightsNode:_,transparent:w,opaque:S}=v;if(T.length>0&&this._renderBundles(T,h,_),!0===this.opaque&&S.length>0&&this._renderObjects(S,t,h,_),!0===this.transparent&&w.length>0&&this._renderObjects(w,t,h,_),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=o,this._currentRenderObjectFunction=a,null!==i){this.setRenderTarget(u,l,c);const e=this._quad;this._nodes.hasOutputChange(d.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(d.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}return h.onAfterRender(this,e,t,d),p}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,s){this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,s=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(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,s,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,r=0,n=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,i),o.minDepth=r,o.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,s=!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,s);const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i&&(this._textures.updateRenderTarget(i),r=this._textures.get(i)),this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget){const e=this._quad;this._nodes.hasOutputChange(i.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(i.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}}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,s=!0){!1===this._initialized&&await this.init(),this.clear(e,t,s)}clearColorAsync(){return this.clearAsync(!0,!1,!1)}clearDepthAsync(){return this.clearAsync(!1,!0,!1)}clearStencilAsync(){return this.clearAsync(!1,!1,!0)}get currentToneMapping(){return null!==this._renderTarget?0:this.toneMapping}get currentColorSpace(){return null!==this._renderTarget?Jt:this.outputColorSpace}dispose(){this.info.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(),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,r=this._pipelines,n=this._bindings,o=this._nodes,a=Array.isArray(e)?e:[e];if(void 0===a[0]||!0!==a[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const t of a){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),n.delete(t),o.delete(t)};t.addEventListener("dispose",e);const s=t.onInitFunction;null!==s&&s.call(t,{renderer:this})}o.updateForCompute(t),n.updateForCompute(t);const s=n.getForCompute(t),a=r.getForCompute(t,s);i.compute(e,t,s,a)}i.finishCompute(e),t.renderId=s}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e),await this.backend.resolveTimestampAsync(e,"compute")}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(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)}copyFramebufferToTexture(e,t=null){const s=this._currentRenderContext;this._textures.updateTexture(e),t=null===t?cI.set(0,0,e.image.width,e.image.height):t,this.backend.copyFramebufferToTexture(e,s,t)}copyTextureToTexture(e,t,s=null,i=null,r=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r)}readRenderTargetPixelsAsync(e,t,s,i,r,n=0,o=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,o)}_projectObject(e,t,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||uI.intersectsSprite(e)){!0===this.sortObjects&&cI.setFromMatrixPosition(e.matrixWorld).applyMatrix4(lI);const{geometry:t,material:r}=e;r.visible&&i.push(e,t,r,s,cI.z,null)}}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)&&(!e.frustumCulled||uI.intersectsObject(e))){const{geometry:t,material:r}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),cI.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(lI)),Array.isArray(r)){const n=t.groups;for(let o=0,a=n.length;o0?i:"";t=`${e.name} {\n\t${s} ${r.name}[${n}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,n=!0}const o=r.node.precision;if(null!==o&&(t=NI[o]+" "+t),n){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,s.push(t)}let r="";for(const t in i){const s=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Ee){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let s=0;for(const i of e)t+=`layout( location = ${s++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[],s=e.getMemberTypes();for(let e=0;ee*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,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);!1===i.has(e)&&i.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 s=this.extensions[e];if(void 0!==s)for(const{name:e,behavior:i}of s.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}isAvailable(e){let t=CI[e];if(void 0===t){if("float32Filterable"===e){const e=this.renderer.backend.extensions;e.has("OES_texture_float_linear")?(e.get("OES_texture_float_linear"),t=!0):t=!1}CI[e]=t}return t}isFlipY(){return!0}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${i.code}\n\t`,e===r&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${i.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=s}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);let o=n.uniformGPU;if(void 0===o){const i=e.groupNode,a=i.name,h=this.getBindGroupArray(a,s);if("texture"===t)o=new wI(r.name,r.node,i),h.push(o);else if("cubeTexture"===t)o=new SI(r.name,r.node,i),h.push(o);else if("texture3D"===t)o=new MI(r.name,r.node,i),h.push(o);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,r.name=`buffer${e.id}`;const t=new yI(e,i);t.name=e.name,h.push(t),o=t}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new vI(s+"_"+a,i),e[a]=n,h.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let BI=null,II=null,PI=null;class FI{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}async init(e){this.renderer=e}begin(){}finish(){}draw(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}createRenderPipeline(){}createComputePipeline(){}destroyPipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}createDefaultTexture(){}createTexture(){}copyTextureToBuffer(){}createAttribute(){}createIndexAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}resolveTimestampAsync(){}hasFeatureAsync(){}hasFeature(){}getInstanceCount(e){const{object:t,geometry:s}=e;return s.isInstancedBufferGeometry?s.instanceCount:t.count>1?t.count:1}getDrawingBufferSize(){return BI=BI||new Ys,this.renderer.getDrawingBufferSize(BI)}getScissor(){return II=II||new xi,this.renderer.getScissor(II)}setScissorTest(){}getClearColor(){const e=this.renderer;return PI=PI||new xS,e.getClearColor(PI),PI.getRGB(PI,this.renderer.currentColorSpace),PI}getDomElement(){let t=this.domElement;return null===t&&(t=void 0!==this.parameters.canvas?this.parameters.canvas:ti(),"setAttribute"in t&&t.setAttribute("data-engine",`three.js r${e} webgpu`),this.domElement=t),t}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)}}let UI=0;class OI{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 zI{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,a=s.get(o);let h,u=a.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,n),a.bufferGPU=u,a.bufferType=t,a.version=o.version),r instanceof Float32Array)h=i.FLOAT;else if(r instanceof Uint16Array)h=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)h=i.SHORT;else if(r instanceof Uint32Array)h=i.UNSIGNED_INT;else if(r instanceof Int32Array)h=i.INT;else if(r instanceof Int8Array)h=i.BYTE;else if(r instanceof Uint8Array)h=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);h=i.UNSIGNED_BYTE}let l={bufferGPU:u,bufferType:t,type:h,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===Ee,id:UI++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);l=new OI(l,e)}s.set(e,l)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,n=t.get(r),o=n.bufferType,a=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,n.bufferGPU),0===a.length)s.bufferSubData(o,0,i);else{for(let e=0,t=a.length;e1?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE)}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===s||(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t&&(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:s}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const n=e.textures;if(i.length!==n.length||i[0]!==s.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e{!function r(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void i();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(r)}()}))}}let WI,jI,HI,qI=!1;class $I{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===qI&&(this._init(this.gl),qI=!0)}_init(e){WI={[pe]:e.REPEAT,[me]:e.CLAMP_TO_EDGE,[ge]:e.MIRRORED_REPEAT},jI={[fe]:e.NEAREST,[ye]:e.NEAREST_MIPMAP_NEAREST,[be]:e.NEAREST_MIPMAP_LINEAR,[Te]:e.LINEAR,[_e]:e.LINEAR_MIPMAP_NEAREST,[Se]:e.LINEAR_MIPMAP_LINEAR},HI={512:e.NEVER,519:e.ALWAYS,[ys]:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===fe||e===ye||e===be?t.NEAREST:t.LINEAR}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,r=!1){const{gl:n,extensions:o}=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 a=t;return t===n.RED&&(s===n.FLOAT&&(a=n.R32F),s===n.HALF_FLOAT&&(a=n.R16F),s===n.UNSIGNED_BYTE&&(a=n.R8),s===n.UNSIGNED_SHORT&&(a=n.R16),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.R8UI),s===n.UNSIGNED_SHORT&&(a=n.R16UI),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RG&&(s===n.FLOAT&&(a=n.RG32F),s===n.HALF_FLOAT&&(a=n.RG16F),s===n.UNSIGNED_BYTE&&(a=n.RG8),s===n.UNSIGNED_SHORT&&(a=n.RG16),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RG_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RG8UI),s===n.UNSIGNED_SHORT&&(a=n.RG16UI),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RGB&&(s===n.FLOAT&&(a=n.RGB32F),s===n.HALF_FLOAT&&(a=n.RGB16F),s===n.UNSIGNED_BYTE&&(a=n.RGB8),s===n.UNSIGNED_SHORT&&(a=n.RGB16),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I),s===n.UNSIGNED_BYTE&&(a=i===Zt&&!1===r?n.SRGB8:n.RGB8),s===n.UNSIGNED_SHORT_5_6_5&&(a=n.RGB565),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGB4),s===n.UNSIGNED_INT_5_9_9_9_REV&&(a=n.RGB9_E5)),t===n.RGB_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGB8UI),s===n.UNSIGNED_SHORT&&(a=n.RGB16UI),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I)),t===n.RGBA&&(s===n.FLOAT&&(a=n.RGBA32F),s===n.HALF_FLOAT&&(a=n.RGBA16F),s===n.UNSIGNED_BYTE&&(a=n.RGBA8),s===n.UNSIGNED_SHORT&&(a=n.RGBA16),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I),s===n.UNSIGNED_BYTE&&(a=i===Zt&&!1===r?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1)),t===n.RGBA_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGBA8UI),s===n.UNSIGNED_SHORT&&(a=n.RGBA16UI),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_INT&&(a=n.DEPTH24_STENCIL8),s===n.FLOAT&&(a=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(a=n.DEPTH24_STENCIL8),a!==n.R16F&&a!==n.R32F&&a!==n.RG16F&&a!==n.RG32F&&a!==n.RGBA16F&&a!==n.RGBA32F||o.get("EXT_color_buffer_float"),a}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE),s.texParameteri(e,s.TEXTURE_WRAP_S,WI[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,WI[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||s.texParameteri(e,s.TEXTURE_WRAP_R,WI[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,jI[t.magFilter]);const n=void 0!==t.mipmaps&&t.mipmaps.length>0,o=t.minFilter===Te&&n?Se:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,jI[o]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,HI[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===fe)return;if(t.minFilter!==be&&t.minFilter!==Se)return;if(t.type===Ie&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,r=this.getGLTextureType(e);let n=i[r];void 0===n&&(n=t.createTexture(),s.state.bindTexture(r,n),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=n),s.set(e,{textureGPU:n,glTextureType:r,isDefault:!0})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:r,width:n,height:o,depth:a}=t,h=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,h,u,e.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,r,l,n,o,a):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,l,n,o,a):e.isVideoTexture||s.texStorage2D(d,r,l,n,o),i.set(e,{textureGPU:c,glTextureType:d,glFormat:h,glType:u,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:r,glTextureType:n,glFormat:o,glType:a}=i.get(t),{width:h,height:u}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(n,r),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(n,0,0,0,h,u,o,a,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:r}=t,{textureGPU:n,glTextureType:o,glFormat:a,glType:h,glInternalFormat:u}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===n)return;const l=e=>e.isDataTexture?e.image.data:e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLImageElement||e instanceof HTMLCanvasElement?e:e.data;if(this.backend.state.bindTexture(o,n),this.setTextureParameters(o,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t0,c=t.renderTarget?t.renderTarget.height:this.backend.gerDrawingBufferSize().y;if(l){const s=0!==o||0!==a;let l,d;if(!0===e.isDepthTexture?(l=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(l|=i.STENCIL_BUFFER_BIT)):(l=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),s){const e=this.backend.get(t.renderTarget),s=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,s),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=c-a-u;i.blitFramebuffer(o,p,o+h,p+u,o,p,o+h,p+u,l,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,s),r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,p,h,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,n,0),i.blitFramebuffer(0,0,h,u,0,0,h,u,l,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,c-u-a,h,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t){const{gl:s}=this,i=t.renderTarget,{samples:r,depthTexture:n,depthBuffer:o,stencilBuffer:a,width:h,height:u}=i;if(s.bindRenderbuffer(s.RENDERBUFFER,e),o&&!a){let t=s.DEPTH_COMPONENT24;r>0?(n&&n.isDepthTexture&&n.type===s.FLOAT&&(t=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,r,t,h,u)):s.renderbufferStorage(s.RENDERBUFFER,t,h,u),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else o&&a&&(r>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,r,s.DEPTH24_STENCIL8,h,u):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,h,u),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,s,i,r,n){const{backend:o,gl:a}=this,{textureGPU:h,glFormat:u,glType:l}=this.backend.get(e),c=a.createFramebuffer();a.bindFramebuffer(a.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?a.TEXTURE_CUBE_MAP_POSITIVE_X+n:a.TEXTURE_2D;a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,d,h,0);const p=this._getTypedArrayType(l),m=i*r*this._getBytesPerTexel(l,u),g=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.bufferData(a.PIXEL_PACK_BUFFER,m,a.STREAM_READ),a.readPixels(t,s,i,r,u,l,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();const f=new p(m/p.BYTES_PER_ELEMENT);return a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,f),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.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:s}=this;let i=0;return e===s.UNSIGNED_BYTE&&(i=1),e!==s.UNSIGNED_SHORT_4_4_4_4&&e!==s.UNSIGNED_SHORT_5_5_5_1&&e!==s.UNSIGNED_SHORT_5_6_5&&e!==s.UNSIGNED_SHORT&&e!==s.HALF_FLOAT||(i=2),e!==s.UNSIGNED_INT&&e!==s.FLOAT||(i=4),t===s.RGBA?4*i:t===s.RGB?3*i:t===s.ALPHA?i:void 0}}class XI{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 YI{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 s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const ZI={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"};class JI{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:s,mode:i,object:r,type:n,info:o,index:a}=this;0!==a?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),o.update(r,t,i,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:o,object:a,info:h}=this;0!==s&&(0!==o?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),h.update(a,t,r,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:o}=this;if(0===s)return;const a=i.get("WEBGL_multi_draw");if(null===a)for(let i=0;i0)){const e=t.queryQueue.shift();this.initTimestampQuery(e)}}async resolveTimestampAsync(e,t="render"){if(!this.disjoint||!this.trackTimestamp)return;const s=this.get(e);s.gpuQueries||(s.gpuQueries=[]);for(let e=0;e0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext,n=e.occlusionQueryCount;n>0&&(n>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const o=e.textures;if(null!==o)for(let e=0;e0){const r=i.framebuffers[e.getCacheKey()],n=t.COLOR_BUFFER_BIT,o=i.msaaFrameBuffer,a=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,o),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,r);for(let s=0;s{let o=0;for(let t=0;t0&&e.add(i[t]),s[t]=null,r.deleteQuery(n),o++))}o1?m.renderInstances(y,g,f):m.render(y,g),o.bindVertexArray(null)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new EI(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,r="fragment"===s?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(){console.warn("Abstract class.")}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:n}=i,o=s.createProgram(),a=this.get(r).shaderGPU,h=this.get(n).shaderGPU;if(s.attachShader(o,a),s.attachShader(o,h),s.linkProgram(o),this.set(i,{programGPU:o,fragmentShader:a,vertexShader:h}),null!==t&&this.parallel){const r=new Promise((t=>{const r=this.parallel,n=()=>{s.getProgramParameter(o,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(n)};n()}));t.push(r)}else this._completeCompile(e,i)}_handleSource(e,t){const s=e.split("\n"),i=[],r=Math.max(t-6,0),n=Math.min(t+6,s.length);for(let e=r;e":" "} ${r}: ${s[e]}`)}return i.join("\n")}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=e.getShaderInfoLog(t).trim();if(i&&""===r)return"";const n=/ERROR: 0:(\d+)/.exec(r);if(n){const i=parseInt(n[1]);return s.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=i.getProgramInfoLog(e).trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,s,t);else{const n=this._getShaderErrors(i,s,"vertex"),o=this._getShaderErrors(i,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+o)}else""!==r&&console.warn("THREE.WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:o,vertexShader:a}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,o,a),s.useProgram(n);const h=e.getBindings();this._setupBindings(h,n),this.set(t,{programGPU:n})}createComputePipeline(e,t){const{state:s,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:n}=e,o=i.createProgram(),a=this.get(r).shaderGPU,h=this.get(n).shaderGPU,u=n.transforms,l=[],c=[];for(let e=0;eZI[t]===e)),s=this.extensions;for(let e=0;e0){if(void 0===l){const i=[];l=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,l);const r=[],u=e.textures;for(let s=0;s,\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:HM,stripIndexFormat:hA},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:HM,stripIndexFormat:hA},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,o=this.getTransferPipeline(i),a=this.getFlipYPipeline(i),h=this.device.createTexture({size:{width:r,height:n,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),u=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:eN,baseArrayLayer:s}),l=h.createView({baseMipLevel:0,mipLevelCount:1,dimension:eN,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),d=(e,t,s)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:s,loadOp:sA,storeOp:eA,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,r),n.draw(4,1,0,0),n.end()};d(o,u,l),d(a,l,u),this.device.queue.submit([c.finish()]),h.destroy()}generateMipmaps(e,t,s=0){const i=this.get(e);void 0===i.useCount&&(i.useCount=0,i.layers=[]);const r=i.layers[s]||this._mipmapCreateBundles(e,t,s),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,r),this.device.queue.submit([n.finish()]),0!==i.useCount&&(i.layers[s]=r),i.useCount++}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:eN,baseArrayLayer:s});const o=[];for(let a=1;a1&&!e.isMultisampleRenderTargetTexture){const e=Object.assign({},p);e.label=e.label+"-msaa",e.sampleCount=l,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=p}destroyTexture(e){const t=this.backend,s=t.get(e);s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else{const s=e.image.depth||1;for(let e=0;e1;for(let o=0;o]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,lP=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,cP={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_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 dP extends $B{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(uP);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=lP.exec(s));)i.push({name:r[1],type:r[2]});const n=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class pP extends qB{parseFunction(e){return new dP(e)}}const mP=self.GPUShaderStage,gP={vertex:mP?mP.VERTEX:1,fragment:mP?mP.FRAGMENT:2,compute:mP?mP.COMPUTE:4},fP={instance:!0,swizzleAssign:!1,storageBuffer:!0},yP={"^^":"tsl_xor"},xP={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"},bP={tsl_xor:new rC("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new rC("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new rC("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new rC("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new rC("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new rC("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new rC("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new rC("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 rC("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:new rC("\nfn tsl_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 {\n\n\tlet uvScaled = vec2( uv * vec2( dimension ) );\n\n\treturn ( ( uvScaled % dimension ) + dimension ) % dimension;\n\n}\n"),biquadraticTexture:new rC("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, level : i32 ) -> vec4f {\n\n\tlet iRes = vec2i( textureDimensions( map, level ) );\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, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2i( 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")},vP={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"};/Windows/g.test(navigator.userAgent)&&(bP.pow_float=new rC("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),bP.pow_vec2=new rC("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[bP.pow_float]),bP.pow_vec3=new rC("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[bP.pow_float]),bP.pow_vec4=new rC("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[bP.pow_float]),vP.pow_float="tsl_pow_float",vP.pow_vec2="tsl_pow_vec2",vP.pow_vec3="tsl_pow_vec3",vP.pow_vec4="tsl_pow_vec4");let TP="";!0!==/Firefox|Deno/g.test(navigator.userAgent)&&(TP+="diagnostic( off, derivative_uniformity );\n");class _P extends PB{constructor(e,t){super(e,t,new pP),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==Yt}_generateTextureSample(e,t,s,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s):this.generateTextureLod(e,t,s,"0")}_generateVideoSample(e,t,s=this.shaderStage){if("fragment"===s)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${s} shader.`)}_generateTextureSampleLevel(e,t,s,i,r,n=this.shaderStage){return"fragment"===n&&!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,i):this.generateTextureLod(e,t,s,i)}generateFilteredTexture(e,t,s,i="0"){return this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${s}, i32( ${i} ) )`}generateTextureLod(e,t,s,i="0"){this._include("repeatWrapping");return`textureLoad( ${t}, tsl_repeatWrapping( ${s}, ${!0===e.isMultisampleRenderTargetTexture?`textureDimensions( ${t} )`:`textureDimensions( ${t}, 0 )`} ), i32( ${i} ) )`}generateTextureLoad(e,t,s,i,r="0u"){return i?`textureLoad( ${t}, ${s}, ${i}, ${r} )`:`textureLoad( ${t}, ${s}, ${r} )`}generateTextureStore(e,t,s,i){return`textureStore( ${t}, ${s}, ${i} )`}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===Ie||!0===e.isMultisampleRenderTargetTexture}generateTexture(e,t,s,i,r=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,s,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,s,"0",i,r):this._generateTextureSample(e,t,s,i,r),n}generateTextureGrad(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,s,i,r,n=this.shaderStage){let o=null;return o=!0===e.isVideoTexture?this._generateVideoSample(t,s,n):this._generateTextureSampleLevel(e,t,s,i,r,n),o}generateTextureBias(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} 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,s=e.type;return"texture"===s||"cubeTexture"===s||"storageTexture"===s||"texture3D"===s?t:"buffer"===s||"storageBuffer"===s||"indirectStorageBuffer"===s?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=yP[e];return void 0!==t?(this._include(t),t):null}getStorageAccess(e){if(e.isStorageTextureNode)switch(e.access){case qA:return"read";case HA:return"write";default:return"read_write"}else switch(e.access){case WA:return"read_write";case jA:return"read";default:return"write"}}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let i;const o=e.groupNode,a=o.name,h=this.getBindGroupArray(a,s);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let n=null;if("texture"===t||"storageTexture"===t?n=new wI(r.name,r.node,o,e.access?e.access:null):"cubeTexture"===t?n=new SI(r.name,r.node,o,e.access?e.access:null):"texture3D"===t&&(n=new MI(r.name,r.node,o,e.access?e.access:null)),n.store=!0===e.isStorageTextureNode,n.setVisibility(gP[s]),"fragment"===s&&!1===this.isUnfilterable(e.value)&&!1===n.store){const e=new eP(`${r.name}_sampler`,r.node,o);e.setVisibility(gP[s]),h.push(e,n),i=[e,n]}else h.push(n),i=[n]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const r=new("buffer"===t?yI:iP)(e,o);r.setVisibility(gP[s]),h.push(r),i=r}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new vI(a,o),n.setVisibility(gP[s]),e[a]=n,h.push(n)),i=this.getNodeUniform(r,t),n.addUniform(i)}n.uniformGPU=i}return r}getBuiltin(e,t,s,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:s}),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,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n`;return s.result&&(r+=`\treturn ${s.result};\n`),r+="\n}\n",r}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")}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],s=this.directives[e];if(void 0!==s)for(const e of s)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")}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:i,type:r}of s.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,s,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:s,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const n=this.getType(i);t.push(`var<${s}> ${e}: array< ${n}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","id","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 s=this.getAttributesArray();for(let e=0,i=s.length;e`)}const i=this.getBuiltins("output");return i&&t.push("\t"+i),t.join(",\n")}getStructs(e){const t=[],s=this.structs[e];for(let e=0,i=s.length;e output : ${r};\n\n`)}return t.join("\n\n")}getVar(e,t){return`var ${t} : ${this.getType(e)}`}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`\t${this.getVar(e.type,e.name)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];for(let r=0;r";else if(!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array";else if(!0===t.isDepthTexture)i=`texture_depth${n}_2d`;else if(!0===t.isVideoTexture)i="texture_external";else if(!0===t.isData3DTexture)i="texture_3d";else if(!0===r.node.isStorageTextureNode){i=`texture_storage_2d<${hP(t)}, ${this.getStorageAccess(r.node)}>`}else{i=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const e=r.node,t=this.getType(e.bufferType),s=e.bufferCount,n=s>0&&"buffer"===r.type?", "+s:"",a=e.isAtomic?`atomic<${t}>`:`${t}`,h=`\t${r.name} : array< ${a}${n} >\n`,u=e.isStorageBufferNode?`storage, ${this.getStorageAccess(e)}`:"uniform";i.push(this._getWGSLStructBinding("NodeBuffer_"+e.id,h,u,o.binding++,o.group))}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(n[t]||(n[t]={index:o.binding++,id:o.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in n){const t=n[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let o=s.join("\n");return o+=i.join("\n"),o+=r.join("\n"),o}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],n=r[r.length-1],o=n.outputNode,a=void 0!==o&&!0===o.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),h=e.name;if(h&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${h}\n\t`),i+=`${r.code}\n\t`,e===n&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(a)s.returnType=o.nodeType,i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;\n\n",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getType(e){return xP[e]||e}isAvailable(e){let t=fP[e];return void 0===t&&("float32Filterable"===e&&(t=this.renderer.hasFeature("float32-filterable")),fP[e]=t),t}_getWGSLMethod(e){return void 0!==bP[e]&&this._include(e),vP[e]}_include(e){const t=bP[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// 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${TP}\n\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\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){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = id.x + id.y * numWorkgroups.x * u32(${t}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\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,s,i=0,r=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${s}> ${e} : ${n};`}}class wP{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=uA.Depth24PlusStencil8:e.depth&&(t=uA.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}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?kM:e.isLineSegments||e.isMesh&&!0===t.wireframe?GM:e.isLine?WM:e.isMesh?jM:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){return navigator.userAgent.includes("Quest")?uA.BGRA8Unorm:navigator.gpu.getPreferredCanvasFormat()}}const SP=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),MP=new Map([[gn,["float16"]]]),AP=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class NP{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,r=i.get(s);let n=r.buffer;if(void 0===n){const o=i.device;let a=s.array;if(!1===e.normalized&&(a.constructor===Int16Array||a.constructor===Uint16Array)){const e=new Uint32Array(a.length);for(let t=0;t1},layout:u.createPipelineLayout({bindGroupLayouts:d})},A={},N=e.context.depth,C=e.context.stencil;if(!0!==N&&!0!==C||(!0===N&&(A.format=w,A.depthWriteEnabled=i.depthWrite,A.depthCompare=_),!0===C&&(A.stencilFront=f,A.stencilBack={},A.stencilReadMask=i.stencilFuncMask,A.stencilWriteMask=i.stencilWriteMask),M.depthStencil=A),null===t)c.pipeline=u.createRenderPipeline(M);else{const e=new Promise((e=>{u.createRenderPipelineAsync(M).then((t=>{c.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e){const t=this.backend,{utils:s,device:i}=t,r=s.getCurrentDepthStencilFormat(e),n={label:"renderBundleEncoder",colorFormats:[s.getCurrentColorFormat(e)],depthStencilFormat:r,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(n)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),o=[];for(const e of t){const t=s.get(e);o.push(t.layout)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:o})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,o=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,a=null!==e.blendDstAlpha?e.blendDstAlpha:n,h=null!==e.blendEquationAlpha?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(h)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:CA},s={srcFactor:r,dstFactor:n,operation:CA}};if(e.premultipliedAlpha)switch(i){case 1:r(fA,vA,fA,vA);break;case 2:r(fA,fA,fA,fA);break;case 3:r(gA,xA,gA,fA);break;case 4:r(gA,yA,gA,bA)}else switch(i){case 1:r(bA,vA,fA,vA);break;case 2:r(bA,fA,bA,fA);break;case 3:r(gA,xA,gA,fA);break;case 4:r(gA,yA,gA,yA)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case 200:t=gA;break;case 201:t=fA;break;case 202:t=yA;break;case 203:t=xA;break;case R:t=bA;break;case E:t=vA;break;case 208:t=TA;break;case 209:t=_A;break;case 206:t=wA;break;case 207:t=SA;break;case 210:t=MA;break;case 211:t=AA;break;case 212:t=NA;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=qM;break;case gs:t=QM;break;case 513:t=$M;break;case 515:t=YM;break;case 514:t=XM;break;case 518:t=KM;break;case 516:t=ZM;break;case 517:t=JM;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case ts:t=UA;break;case 0:t=OA;break;case 7681:t=zA;break;case 5386:t=LA;break;case 7682:t=VA;break;case 7683:t=DA;break;case 34055:t=kA;break;case 34056:t=GA;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case v:t=CA;break;case 101:t=RA;break;case 102:t=EA;break;case 103:t=BA;break;case 104:t=IA;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?aA:hA),s.side){case c:i.frontFace=iA,i.cullMode=oA;break;case d:i.frontFace=iA,i.cullMode=nA;break;case 2:i.frontFace=iA,i.cullMode=rA;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?FA:PA}_getDepthCompare(e){let t;if(!1===e.depthTest)t=QM;else{const s=e.depthFunc;switch(s){case 0:t=qM;break;case 1:t=QM;break;case 2:t=$M;break;case 3:t=YM;break;case 4:t=XM;break;case 5:t=KM;break;case 6:t=ZM;break;case 7:t=JM;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class EP extends FI{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.trackTimestamp=!0===e.trackTimestamp,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new wP(this),this.attributeUtils=new NP(this),this.bindingUtils=new CP(this),this.pipelineUtils=new RP(this),this.textureUtils=new aP(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference},i=await navigator.gpu.requestAdapter(e);if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(aN),n=[];for(const e of r)i.features.has(e)&&n.push(e);const o={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(o)}else s=t.device;const i=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=s,this.context=i;const r=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(aN.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r}),this.updateSize()}get coordinateSystem(){return Os}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 s=e.colorAttachments[0];this.renderer.samples>0?s.view=this.colorBuffer.createView():s.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}_getRenderPassDescriptor(e){const t=e.renderTarget,s=this.get(t);let i=s.descriptors;if(void 0===i||s.width!==t.width||s.height!==t.height||s.activeMipmapLevel!==t.activeMipmapLevel||s.samples!==t.samples){i={},s.descriptors=i;const e=()=>{t.removeEventListener("dispose",e),this.delete(t)};t.addEventListener("dispose",e)}const r=e.getCacheKey();let n=i[r];if(void 0===n){const o=e.textures,a=[];for(let t=0;t0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=s.createQuerySet({type:"occlusion",count:i}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e),this.initTimestampQuery(e,n),n.occlusionQuerySet=r;const o=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),s>0){const i=8*s;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const n=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,n,0,i),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.prepareTimestampBuffer(e,t.encoder),this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eo?(h.x=Math.min(t.dispatchCount,o),h.y=Math.ceil(t.dispatchCount/o)):h.x=t.dispatchCount,r.dispatchWorkgroups(h.x,h.y,h.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.prepareTimestampBuffer(e,t.cmdEncoderGPU),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:s,context:i,pipeline:r}=e,n=e.getBindings(),o=this.get(i),a=this.get(r).pipeline,h=o.currentSets,u=o.currentPass,l=e.getDrawParameters();if(null===l)return;h.pipeline!==a&&(u.setPipeline(a),h.pipeline=a);const c=h.bindingGroups;for(let e=0,t=n.length;e1?0:s;u.drawIndexed(t[s],i,e[s]/n,0,o)}}else if(!0===p){const{vertexCount:i,instanceCount:r,firstVertex:n}=l,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndexedIndirect(e,0)}else u.drawIndexed(i,r,n,0,0);t.update(s,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:n}=l,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndirect(e,0)}else u.draw(i,r,n,0);t.update(s,i,r)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),o=r.getCurrentColorSpace(e.context),a=r.getCurrentColorFormat(e.context),h=r.getCurrentDepthStencilFormat(e.context),u=r.getPrimitiveTopology(s,i);let l=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===o&&t.colorFormat===a&&t.depthStencilFormat===h&&t.primitiveTopology===u&&t.clippingContextCacheKey===e.clippingContext.cacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=n,t.colorSpace=o,t.colorFormat=a,t.depthStencilFormat=h,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContext.cacheKey,l=!0),l}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,r=e.context;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.clippingContext.cacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const s=this.get(e);if(!s.timeStampQuerySet){const e=this.device.createQuerySet({type:"timestamp",count:2}),i={querySet:e,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1};Object.assign(t,{timestampWrites:i}),s.timeStampQuerySet=e}}prepareTimestampBuffer(e,t){if(!this.trackTimestamp)return;const s=this.get(e),i=2*BigInt64Array.BYTES_PER_ELEMENT;void 0===s.currentTimestampQueryBuffers&&(s.currentTimestampQueryBuffers={resolveBuffer:this.device.createBuffer({label:"timestamp resolve buffer",size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),resultBuffer:this.device.createBuffer({label:"timestamp result buffer",size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),isMappingPending:!1});const{resolveBuffer:r,resultBuffer:n,isMappingPending:o}=s.currentTimestampQueryBuffers;!0!==o&&(t.resolveQuerySet(s.timeStampQuerySet,0,2,r,0),t.copyBufferToBuffer(r,0,n,0,i))}async resolveTimestampAsync(e,t="render"){if(!this.trackTimestamp)return;const s=this.get(e);if(void 0===s.currentTimestampQueryBuffers)return;const{resultBuffer:i,isMappingPending:r}=s.currentTimestampQueryBuffers;!0!==r&&(s.currentTimestampQueryBuffers.isMappingPending=!0,i.mapAsync(GPUMapMode.READ).then((()=>{const e=new BigUint64Array(i.getMappedRange()),r=Number(e[1]-e[0])/1e6;this.renderer.info.updateTimestamp(t,r),i.unmap(),s.currentTimestampQueryBuffers.isMappingPending=!1})))}createNodeBuilder(e,t){return new _P(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),i=s.currentPass.finish();this.get(t).bundleGPU=i,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e){this.bindingUtils.createBindings(e)}updateBindings(e){this.bindingUtils.createBindings(e)}updateBinding(e){this.bindingUtils.updateBinding(e)}createIndexAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0){let n=0,o=0,a=0,h=0,u=0,l=0,c=e.image.width,d=e.image.height;null!==s&&(h=s.x,u=s.y,l=s.z||0,c=s.width,d=s.height),null!==i&&(n=i.x,o=i.y,a=i.z||0);const p=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),m=this.get(e).texture,g=this.get(t).texture;p.copyTextureToTexture({texture:m,mipLevel:r,origin:{x:h,y:u,z:l}},{texture:g,mipLevel:r,origin:{x:n,y:o,z:a}},[c,d,1]),this.device.queue.submit([p.finish()])}copyFramebufferToTexture(e,t,s){const i=this.get(t),{encoder:r,descriptor:n}=i;let o=null;o=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const a=this.get(e).texture;if(o.format===a.format){i.currentPass.end(),r.copyTextureToTexture({texture:o,origin:{x:s.x,y:s.y,z:0}},{texture:a},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e);for(let e=0;e(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new KI(e)));super(new t(e),e),this.library=new IP,this.isWebGPURenderer=!0}}class FP extends ka{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}const UP=new uT,OP=new MM(UP);class zP{constructor(e,t=$p(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0,UP.name="PostProcessing"}render(){this.update();const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;e.toneMapping=0,e.outputColorSpace=Jt,OP.render(e),e.toneMapping=t,e.outputColorSpace=s}update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;OP.material.fragmentNode=!0===this.outputColorTransform?Ty(this.outputNode,t,s):this.outputNode.context({toneMapping:t,outputColorSpace:s}),OP.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){this.update();const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;e.toneMapping=0,e.outputColorSpace=Jt,await OP.renderAsync(e),e.toneMapping=t,e.outputColorSpace=s}}function LP(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new Xr),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}function VP(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 DP(e,t,s={}){return(s=LP(e,s)).background=t.background,s.backgroundNode=t.backgroundNode,s.overrideMaterial=t.overrideMaterial,s}var kP=Object.freeze({__proto__:null,resetRendererAndSceneState:function(e,t,s){return s=DP(e,t,s),t.background=null,t.backgroundNode=null,t.overrideMaterial=null,s},resetRendererState:function(e,t){return t=LP(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t},restoreRendererAndSceneState:function(e,t,s){VP(e,s),t.background=s.background,t.backgroundNode=s.backgroundNode,t.overrideMaterial=s.overrideMaterial},restoreRendererState:VP,saveRendererAndSceneState:DP,saveRendererState:LP});class GP extends yi{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=Te,this.minFilter=Te,this.isStorageTexture=!0}}class WP extends an{constructor(e,t,s=Float32Array){!1===ArrayBuffer.isView(e)&&(e=new s(e*t)),super(e,t),this.isStorageBufferAttribute=!0}}class jP extends zo{constructor(e,t,s=Float32Array){!1===ArrayBuffer.isView(e)&&(e=new s(e*t)),super(e,t),this.isStorageInstancedBufferAttribute=!0}}class HP extends WP{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class qP extends el{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,s,i){const r=new il(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,(s=>{try{t(this.parse(JSON.parse(s)))}catch(t){i?i(t):console.error(t),this.manager.itemError(e)}}),s,i)}parseNodes(e){const t={};if(void 0!==e){for(const s of e){const{uuid:e,type:i}=s;t[e]=this.createNodeFromType(i),t[e].uuid=e}const s={nodes:t,textures:this.textures};for(const i of e){i.meta=s;t[i.uuid].deserialize(i),delete i.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const s={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=s,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),Up()):wp(new this.nodes[e])}}class $P extends El{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),s=this.nodes,i=e.inputNodes;for(const e in i){const r=i[e];t[e]=s[r]}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 XP extends Fl{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 s=super.parse(e,t);return this._nodesJSON=null,s}parseNodes(e,t){if(void 0!==e){const s=new qP;return s.setNodes(this.nodes),s.setTextures(t),s.parseNodes(e)}return{}}parseMaterials(e,t){const s={};if(void 0!==e){const i=this.parseNodes(this._nodesJSON,t),r=new $P;r.setTextures(t),r.setNodes(i),r.setNodeMaterials(this.nodeMaterials);for(let t=0,i=e.length;t { - - return lights.sort( ( a, b ) => a.id - b.id ); - -}; - -const getLightNodeById = ( id, lightNodes ) => { - - for ( const lightNode of lightNodes ) { - - if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) { - - return lightNode; - - } - - } - - return null; - -}; - -const _lightsNodeRef = /*@__PURE__*/ new WeakMap(); - -class LightsNode extends Node { - - static get type() { - - return 'LightsNode'; - - } - - constructor( lights = [] ) { - - super( 'vec3' ); - - this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' ); - this.totalSpecularNode = vec3().toVar( 'totalSpecular' ); - - this.outgoingLightNode = vec3().toVar( 'outgoingLight' ); - - this._lights = lights; - - this._lightNodes = null; - this._lightNodesHash = null; - - this.global = true; - - } - - getHash( builder ) { - - if ( this._lightNodesHash === null ) { - - if ( this._lightNodes === null ) this.setupLightsNode( builder ); - - const hash = []; - - for ( const lightNode of this._lightNodes ) { - - hash.push( lightNode.getHash() ); - - } - - this._lightNodesHash = 'lights-' + hash.join( ',' ); - - } - - return this._lightNodesHash; - - } - - analyze( builder ) { - - const properties = builder.getDataFromNode( this ); - - for ( const node of properties.nodes ) { - - node.build( builder ); - - } - - } - - setupLightsNode( builder ) { - - const lightNodes = []; - - const previousLightNodes = this._lightNodes; - - const lights = sortLights( this._lights ); - const nodeLibrary = builder.renderer.nodes.library; - - for ( const light of lights ) { - - if ( light.isNode ) { - - lightNodes.push( nodeObject( light ) ); - - } else { - - let lightNode = null; - - if ( previousLightNodes !== null ) { - - lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node - - } - - if ( lightNode === null ) { - - const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor ); - - if ( lightNodeClass === null ) { - - console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` ); - continue; - - } - - let lightNode = null; - - if ( ! _lightsNodeRef.has( light ) ) { - - lightNode = new lightNodeClass( light ); - _lightsNodeRef.set( light, lightNode ); - - } else { - - lightNode = _lightsNodeRef.get( light ); - - } - - lightNodes.push( lightNode ); - - } - - } - - } - - this._lightNodes = lightNodes; - - } - - setup( builder ) { - - if ( this._lightNodes === null ) this.setupLightsNode( builder ); - - const context = builder.context; - const lightingModel = context.lightingModel; - - let outgoingLightNode = this.outgoingLightNode; - - if ( lightingModel ) { - - const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this; - - context.outgoingLight = outgoingLightNode; - - const stack = builder.addStack(); - - // - - const properties = builder.getDataFromNode( this ); - properties.nodes = stack.nodes; - - // - - lightingModel.start( context, stack, builder ); - - // lights - - for ( const lightNode of _lightNodes ) { - - lightNode.build( builder ); - - } - - // - - lightingModel.indirect( context, stack, builder ); - - // - - const { backdrop, backdropAlpha } = context; - const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight; - - let totalDiffuse = directDiffuse.add( indirectDiffuse ); - - if ( backdrop !== null ) { - - if ( backdropAlpha !== null ) { - - totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) ); - - } else { - - totalDiffuse = vec3( backdrop ); - - } - - context.material.transparent = true; - - } - - totalDiffuseNode.assign( totalDiffuse ); - totalSpecularNode.assign( directSpecular.add( indirectSpecular ) ); - - outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) ); - - // - - lightingModel.finish( context, stack, builder ); - - // - - outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() ); - - } - - return outgoingLightNode; - - } - - setLights( lights ) { - - this._lights = lights; - - this._lightNodes = null; - this._lightNodesHash = null; - - return this; - - } - - getLights() { - - return this._lights; - - } - -} - -const lights = /*@__PURE__*/ nodeProxy( LightsNode ); - class LightingNode extends Node { static get type() { @@ -46073,7 +45827,7 @@ class NodeMaterial extends Material { if ( materialLightsNode.length > 0 ) { - lightsN = lights( [ ...lightsN.getLights(), ...materialLightsNode ] ); + lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] ); } @@ -46100,7 +45854,7 @@ class NodeMaterial extends Material { let outgoingLightNode = this.setupOutgoingLight( builder ); - if ( lightsNode && lightsNode.getScope().getLights().length > 0 ) { + if ( lightsNode && lightsNode.getScope().hasLights ) { const lightingModel = this.setupLightingModel( builder ); @@ -52221,620 +51975,774 @@ class Bindings extends DataMap { } -class NodeAttribute { +function painterSortStable( a, b ) { - constructor( name, type, node = null ) { + if ( a.groupOrder !== b.groupOrder ) { - this.isNodeAttribute = true; + return a.groupOrder - b.groupOrder; - this.name = name; - this.type = type; - this.node = node; + } else if ( a.renderOrder !== b.renderOrder ) { - } + return a.renderOrder - b.renderOrder; -} + } else if ( a.material.id !== b.material.id ) { -class NodeUniform { + return a.material.id - b.material.id; - constructor( name, type, node ) { + } else if ( a.z !== b.z ) { - this.isNodeUniform = true; + return a.z - b.z; - this.name = name; - this.type = type; - this.node = node.getSelf(); + } else { - } + return a.id - b.id; - get value() { + } - return this.node.value; +} - } +function reversePainterSortStable( a, b ) { - set value( val ) { + if ( a.groupOrder !== b.groupOrder ) { - this.node.value = val; + return a.groupOrder - b.groupOrder; - } + } else if ( a.renderOrder !== b.renderOrder ) { - get id() { + return a.renderOrder - b.renderOrder; - return this.node.id; + } else if ( a.z !== b.z ) { - } + return b.z - a.z; - get groupNode() { + } else { - return this.node.groupNode; + return a.id - b.id; } } -class NodeVar { +class RenderList { - constructor( name, type ) { + constructor( lighting, scene, camera ) { - this.isNodeVar = true; + this.renderItems = []; + this.renderItemsIndex = 0; - this.name = name; - this.type = type; + this.opaque = []; + this.transparent = []; + this.bundles = []; + + this.lightsNode = lighting.getNode( scene, camera ); + this.lightsArray = []; + + this.scene = scene; + this.camera = camera; + + this.occlusionQueryCount = 0; } -} + begin() { -class NodeVarying extends NodeVar { + this.renderItemsIndex = 0; - constructor( name, type ) { + this.opaque.length = 0; + this.transparent.length = 0; + this.bundles.length = 0; - super( name, type ); + this.lightsArray.length = 0; - this.needsInterpolation = false; + this.occlusionQueryCount = 0; - this.isNodeVarying = true; + return this; } -} + getNextRenderItem( object, geometry, material, groupOrder, z, group ) { -class NodeCode { + let renderItem = this.renderItems[ this.renderItemsIndex ]; - constructor( name, type, code = '' ) { + if ( renderItem === undefined ) { - this.name = name; - this.type = type; - this.code = code; + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; - Object.defineProperty( this, 'isNodeCode', { value: true } ); + this.renderItems[ this.renderItemsIndex ] = renderItem; - } + } else { -} + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; -let id$1 = 0; + } -class NodeCache { + this.renderItemsIndex ++; - constructor( parent = null ) { + return renderItem; - this.id = id$1 ++; - this.nodesData = new WeakMap(); + } - this.parent = parent; + push( object, geometry, material, groupOrder, z, group ) { - } + const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group ); - getData( node ) { + if ( object.occlusionTest === true ) this.occlusionQueryCount ++; - let data = this.nodesData.get( node ); + ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem ); - if ( data === undefined && this.parent !== null ) { + } - data = this.parent.getData( node ); + unshift( object, geometry, material, groupOrder, z, group ) { - } + const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group ); - return data; + ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem ); } - setData( node, data ) { + pushBundle( group ) { - this.nodesData.set( node, data ); + this.bundles.push( group ); } -} + pushLight( light ) { -class ParameterNode extends PropertyNode { + this.lightsArray.push( light ); - static get type() { + } - return 'ParameterNode'; + sort( customOpaqueSort, customTransparentSort ) { + + if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable ); + if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable ); } - constructor( nodeType, name = null ) { + finish() { - super( nodeType, name ); + // update lights - this.isParameterNode = true; + this.lightsNode.setLights( this.lightsArray ); - } + // Clear references from inactive renderItems in the list - getHash() { + for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) { - return this.uuid; + const renderItem = this.renderItems[ i ]; - } + if ( renderItem.id === null ) break; - generate() { + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.groupOrder = null; + renderItem.renderOrder = null; + renderItem.z = null; + renderItem.group = null; - return this.name; + } } } -const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) ); +class RenderLists { -class CodeNode extends Node { + constructor( lighting ) { - static get type() { + this.lighting = lighting; - return 'CodeNode'; + this.lists = new ChainMap(); } - constructor( code = '', includes = [], language = '' ) { - - super( 'code' ); + get( scene, camera ) { - this.isCodeNode = true; + const lists = this.lists; + const keys = [ scene, camera ]; - this.code = code; - this.language = language; + let list = lists.get( keys ); - this.includes = includes; + if ( list === undefined ) { - } + list = new RenderList( this.lighting, scene, camera ); + lists.set( keys, list ); - isGlobal() { + } - return true; + return list; } - setIncludes( includes ) { - - this.includes = includes; + dispose() { - return this; + this.lists = new ChainMap(); } - getIncludes( /*builder*/ ) { - - return this.includes; +} - } +let id$1 = 0; - generate( builder ) { +class RenderContext { - const includes = this.getIncludes( builder ); + constructor() { - for ( const include of includes ) { + this.id = id$1 ++; - include.build( builder ); + this.color = true; + this.clearColor = true; + this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 }; - } + this.depth = true; + this.clearDepth = true; + this.clearDepthValue = 1; - const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) ); - nodeCode.code = this.code; + this.stencil = false; + this.clearStencil = true; + this.clearStencilValue = 1; - return nodeCode.code; + this.viewport = false; + this.viewportValue = new Vector4(); - } + this.scissor = false; + this.scissorValue = new Vector4(); - serialize( data ) { + this.textures = null; + this.depthTexture = null; + this.activeCubeFace = 0; + this.sampleCount = 1; - super.serialize( data ); + this.width = 0; + this.height = 0; - data.code = this.code; - data.language = this.language; + this.isRenderContext = true; } - deserialize( data ) { - - super.deserialize( data ); + getCacheKey() { - this.code = data.code; - this.language = data.language; + return getCacheKey( this ); } } -const code = /*@__PURE__*/ nodeProxy( CodeNode ); +function getCacheKey( renderContext ) { -const js = ( src, includes ) => code( src, includes, 'js' ); -const wgsl = ( src, includes ) => code( src, includes, 'wgsl' ); -const glsl = ( src, includes ) => code( src, includes, 'glsl' ); + const { textures, activeCubeFace } = renderContext; -class FunctionNode extends CodeNode { + const values = [ activeCubeFace ]; - static get type() { + for ( const texture of textures ) { - return 'FunctionNode'; + values.push( texture.id ); } - constructor( code = '', includes = [], language = '' ) { + return hashArray( values ); - super( code, includes, language ); +} - } +class RenderContexts { - getNodeType( builder ) { + constructor() { - return this.getNodeFunction( builder ).type; + this.chainMaps = {}; } - getInputs( builder ) { + get( scene, camera, renderTarget = null ) { - return this.getNodeFunction( builder ).inputs; + const chainKey = [ scene, camera ]; - } + let attachmentState; - getNodeFunction( builder ) { + if ( renderTarget === null ) { - const nodeData = builder.getDataFromNode( this ); + attachmentState = 'default'; - let nodeFunction = nodeData.nodeFunction; + } else { - if ( nodeFunction === undefined ) { + const format = renderTarget.texture.format; + const count = renderTarget.textures.length; - nodeFunction = builder.parser.parseFunction( this.code ); + attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`; - nodeData.nodeFunction = nodeFunction; + } + + const chainMap = this.getChainMap( attachmentState ); + + let renderState = chainMap.get( chainKey ); + + if ( renderState === undefined ) { + + renderState = new RenderContext(); + + chainMap.set( chainKey, renderState ); } - return nodeFunction; + if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; + + return renderState; } - generate( builder, output ) { + getChainMap( attachmentState ) { - super.generate( builder ); + return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() ); - const nodeFunction = this.getNodeFunction( builder ); + } - const name = nodeFunction.name; - const type = nodeFunction.type; + dispose() { - const nodeCode = builder.getCodeFromNode( this, type ); + this.chainMaps = {}; - if ( name !== '' ) { + } - // use a custom property name +} - nodeCode.name = name; +const _size$3 = /*@__PURE__*/ new Vector3(); + +class Textures extends DataMap { + + constructor( renderer, backend, info ) { + + super(); + + this.renderer = renderer; + this.backend = backend; + this.info = info; + + } + + updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) { + + const renderTargetData = this.get( renderTarget ); + + const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; + const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} ); + + const textures = renderTarget.textures; + + const size = this.getSize( textures[ 0 ] ); + + const mipWidth = size.width >> activeMipmapLevel; + const mipHeight = size.height >> activeMipmapLevel; + + let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ]; + const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true; + + let textureNeedsUpdate = false; + + if ( depthTexture === undefined && useDepthTexture ) { + + depthTexture = new DepthTexture(); + depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat; + depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType + depthTexture.image.width = mipWidth; + depthTexture.image.height = mipHeight; + + depthTextureMips[ activeMipmapLevel ] = depthTexture; } - const propertyName = builder.getPropertyName( nodeCode ); + if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) { - const code = this.getNodeFunction( builder ).getCode( propertyName ); + textureNeedsUpdate = true; - nodeCode.code = code + '\n'; + if ( depthTexture ) { - if ( output === 'property' ) { + depthTexture.needsUpdate = true; + depthTexture.image.width = mipWidth; + depthTexture.image.height = mipHeight; - return propertyName; + } - } else { + } - return builder.format( `${ propertyName }()`, type, output ); + renderTargetData.width = size.width; + renderTargetData.height = size.height; + renderTargetData.textures = textures; + renderTargetData.depthTexture = depthTexture || null; + renderTargetData.depth = renderTarget.depthBuffer; + renderTargetData.stencil = renderTarget.stencilBuffer; + renderTargetData.renderTarget = renderTarget; + + if ( renderTargetData.sampleCount !== sampleCount ) { + + textureNeedsUpdate = true; + + if ( depthTexture ) { + + depthTexture.needsUpdate = true; + + } + + renderTargetData.sampleCount = sampleCount; } - } + // -} + const options = { sampleCount }; -const nativeFn = ( code, includes = [], language = '' ) => { + for ( let i = 0; i < textures.length; i ++ ) { - for ( let i = 0; i < includes.length; i ++ ) { + const texture = textures[ i ]; - const include = includes[ i ]; + if ( textureNeedsUpdate ) texture.needsUpdate = true; - // TSL Function: glslFn, wgslFn + this.updateTexture( texture, options ); - if ( typeof include === 'function' ) { + } - includes[ i ] = include.functionNode; + if ( depthTexture ) { + + this.updateTexture( depthTexture, options ); } - } + // dispose handler - const functionNode = nodeObject( new FunctionNode( code, includes, language ) ); + if ( renderTargetData.initialized !== true ) { - const fn = ( ...params ) => functionNode.call( ...params ); - fn.functionNode = functionNode; + renderTargetData.initialized = true; - return fn; + // dispose -}; + const onDispose = () => { -const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' ); -const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' ); + renderTarget.removeEventListener( 'dispose', onDispose ); -class Uniform { + for ( let i = 0; i < textures.length; i ++ ) { - constructor( name, value ) { + this._destroyTexture( textures[ i ] ); - this.name = name; - this.value = value; + } - this.boundary = 0; // used to build the uniform buffer according to the STD140 layout - this.itemSize = 0; + if ( depthTexture ) { - this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer + this._destroyTexture( depthTexture ); - } + } - setValue( value ) { + this.delete( renderTarget ); - this.value = value; + }; + + renderTarget.addEventListener( 'dispose', onDispose ); + + } } - getValue() { + updateTexture( texture, options = {} ) { - return this.value; + const textureData = this.get( texture ); + if ( textureData.initialized === true && textureData.version === texture.version ) return; - } + const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture; + const backend = this.backend; -} + if ( isRenderTarget && textureData.initialized === true ) { -class NumberUniform extends Uniform { + // it's an update - constructor( name, value = 0 ) { + backend.destroySampler( texture ); + backend.destroyTexture( texture ); - super( name, value ); + } - this.isNumberUniform = true; + // - this.boundary = 4; - this.itemSize = 1; + if ( texture.isFramebufferTexture ) { - } + const renderer = this.renderer; + const renderTarget = renderer.getRenderTarget(); -} + if ( renderTarget ) { -class Vector2Uniform extends Uniform { + texture.type = renderTarget.texture.type; - constructor( name, value = new Vector2() ) { + } else { - super( name, value ); + texture.type = UnsignedByteType; - this.isVector2Uniform = true; + } - this.boundary = 8; - this.itemSize = 2; + } - } + // -} + const { width, height, depth } = this.getSize( texture ); -class Vector3Uniform extends Uniform { + options.width = width; + options.height = height; + options.depth = depth; + options.needsMipmaps = this.needsMipmaps( texture ); + options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1; - constructor( name, value = new Vector3() ) { + // - super( name, value ); + if ( isRenderTarget || texture.isStorageTexture === true ) { - this.isVector3Uniform = true; + backend.createSampler( texture ); + backend.createTexture( texture, options ); - this.boundary = 16; - this.itemSize = 3; + textureData.generation = texture.version; - } + } else { -} + const needsCreate = textureData.initialized !== true; -class Vector4Uniform extends Uniform { + if ( needsCreate ) backend.createSampler( texture ); - constructor( name, value = new Vector4() ) { + if ( texture.version > 0 ) { - super( name, value ); + const image = texture.image; - this.isVector4Uniform = true; + if ( image === undefined ) { - this.boundary = 16; - this.itemSize = 4; + console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' ); - } + } else if ( image.complete === false ) { -} + console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' ); -class ColorUniform extends Uniform { + } else { - constructor( name, value = new Color() ) { + if ( texture.images ) { - super( name, value ); + const images = []; - this.isColorUniform = true; + for ( const image of texture.images ) { - this.boundary = 16; - this.itemSize = 3; + images.push( image ); - } + } -} + options.images = images; -class Matrix3Uniform extends Uniform { + } else { - constructor( name, value = new Matrix3() ) { + options.image = image; - super( name, value ); + } - this.isMatrix3Uniform = true; + if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) { - this.boundary = 48; - this.itemSize = 12; + backend.createTexture( texture, options ); - } + textureData.isDefaultTexture = false; + textureData.generation = texture.version; -} + } -class Matrix4Uniform extends Uniform { + if ( texture.source.dataReady === true ) backend.updateTexture( texture, options ); - constructor( name, value = new Matrix4() ) { + if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture ); - super( name, value ); + } - this.isMatrix4Uniform = true; + } else { - this.boundary = 64; - this.itemSize = 16; + // async update - } + backend.createDefaultTexture( texture ); -} + textureData.isDefaultTexture = true; + textureData.generation = texture.version; -class NumberNodeUniform extends NumberUniform { + } - constructor( nodeUniform ) { + } - super( nodeUniform.name, nodeUniform.value ); + // dispose handler - this.nodeUniform = nodeUniform; + if ( textureData.initialized !== true ) { - } + textureData.initialized = true; + textureData.generation = texture.version; - getValue() { + // - return this.nodeUniform.value; + this.info.memory.textures ++; - } + // dispose -} + const onDispose = () => { -class Vector2NodeUniform extends Vector2Uniform { + texture.removeEventListener( 'dispose', onDispose ); - constructor( nodeUniform ) { + this._destroyTexture( texture ); - super( nodeUniform.name, nodeUniform.value ); + this.info.memory.textures --; - this.nodeUniform = nodeUniform; + }; - } + texture.addEventListener( 'dispose', onDispose ); - getValue() { + } - return this.nodeUniform.value; + // + + textureData.version = texture.version; } -} + getSize( texture, target = _size$3 ) { -class Vector3NodeUniform extends Vector3Uniform { + let image = texture.images ? texture.images[ 0 ] : texture.image; - constructor( nodeUniform ) { + if ( image ) { - super( nodeUniform.name, nodeUniform.value ); + if ( image.image !== undefined ) image = image.image; - this.nodeUniform = nodeUniform; + target.width = image.width; + target.height = image.height; + target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 ); + + } else { + + target.width = target.height = target.depth = 1; + + } + + return target; } - getValue() { + getMipLevels( texture, width, height ) { - return this.nodeUniform.value; + let mipLevelCount; + + if ( texture.isCompressedTexture ) { + + mipLevelCount = texture.mipmaps.length; + + } else { + + mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1; + + } + + return mipLevelCount; } -} + needsMipmaps( texture ) { -class Vector4NodeUniform extends Vector4Uniform { + if ( this.isEnvironmentTexture( texture ) ) return true; - constructor( nodeUniform ) { + return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) ); - super( nodeUniform.name, nodeUniform.value ); + } - this.nodeUniform = nodeUniform; + isEnvironmentTexture( texture ) { + + const mapping = texture.mapping; + + return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); } - getValue() { + _destroyTexture( texture ) { - return this.nodeUniform.value; + this.backend.destroySampler( texture ); + this.backend.destroyTexture( texture ); + + this.delete( texture ); } } -class ColorNodeUniform extends ColorUniform { +class Color4 extends Color { - constructor( nodeUniform ) { + constructor( r, g, b, a = 1 ) { - super( nodeUniform.name, nodeUniform.value ); + super( r, g, b ); - this.nodeUniform = nodeUniform; + this.a = a; } - getValue() { + set( r, g, b, a = 1 ) { - return this.nodeUniform.value; + this.a = a; + + return super.set( r, g, b ); } -} + copy( color ) { -class Matrix3NodeUniform extends Matrix3Uniform { + if ( color.a !== undefined ) this.a = color.a; - constructor( nodeUniform ) { + return super.copy( color ); - super( nodeUniform.name, nodeUniform.value ); + } - this.nodeUniform = nodeUniform; + clone() { + + return new this.constructor( this.r, this.g, this.b, this.a ); } - getValue() { +} - return this.nodeUniform.value; +class ParameterNode extends PropertyNode { + + static get type() { + + return 'ParameterNode'; } -} + constructor( nodeType, name = null ) { -class Matrix4NodeUniform extends Matrix4Uniform { + super( nodeType, name ); - constructor( nodeUniform ) { + this.isParameterNode = true; - super( nodeUniform.name, nodeUniform.value ); + } - this.nodeUniform = nodeUniform; + getHash() { + + return this.uuid; } - getValue() { + generate() { - return this.nodeUniform.value; + return this.name; } } +const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) ); + class StackNode extends Node { static get type() { @@ -52939,10209 +52847,10327 @@ class StackNode extends Node { const stack = /*@__PURE__*/ nodeProxy( StackNode ); -const LOD_MIN = 4; +class StructTypeNode extends Node { -// The standard deviations (radians) associated with the extra mips. These are -// chosen to approximate a Trowbridge-Reitz distribution function times the -// geometric shadowing function. These sigma values squared must match the -// variance #defines in cube_uv_reflection_fragment.glsl.js. -const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; + static get type() { -// The maximum length of the blur for loop. Smaller sigmas will use fewer -// samples and exit early, but not recompile the shader. -const MAX_SAMPLES = 20; + return 'StructTypeNode'; -const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); -const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 ); -const _clearColor$1 = /*@__PURE__*/ new Color(); -let _oldTarget = null; -let _oldActiveCubeFace = 0; -let _oldActiveMipmapLevel = 0; + } -// Golden Ratio -const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; -const INV_PHI = 1 / PHI; + constructor( types ) { -// Vertices of a dodecahedron (except the opposites, which represent the -// same axis), used as axis directions evenly spread on a sphere. -const _axisDirections = [ - /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ), - /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), - /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), - /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), - /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), - /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), - /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), - /*@__PURE__*/ new Vector3( 1, 1, - 1 ), - /*@__PURE__*/ new Vector3( - 1, 1, 1 ), - /*@__PURE__*/ new Vector3( 1, 1, 1 ) -]; + super(); -// + this.types = types; + this.isStructTypeNode = true; -// WebGPU Face indices -const _faceLib = [ - 3, 1, 5, - 0, 4, 2 -]; + } -const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize(); -const outputDirection = vec3( direction.x, direction.y.negate(), direction.z ); + getMemberTypes() { -/** - * This class generates a Prefiltered, Mipmapped Radiance Environment Map - * (PMREM) from a cubeMap environment texture. This allows different levels of - * blur to be quickly accessed based on material roughness. It is packed into a - * special CubeUV format that allows us to perform custom interpolation so that - * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap - * chain, it only goes down to the LOD_MIN level (above), and then creates extra - * even more filtered 'mips' at the same LOD_MIN resolution, associated with - * higher roughness levels. In this way we maintain resolution to smoothly - * interpolate diffuse lighting while limiting sampling computation. - * - * Paper: Fast, Accurate Image-Based Lighting - * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view -*/ + return this.types; -class PMREMGenerator { + } - constructor( renderer ) { +} - this._renderer = renderer; - this._pingPongRenderTarget = null; +class OutputStructNode extends Node { - this._lodMax = 0; - this._cubeSize = 0; - this._lodPlanes = []; - this._sizeLods = []; - this._sigmas = []; - this._lodMeshes = []; + static get type() { - this._blurMaterial = null; - this._cubemapMaterial = null; - this._equirectMaterial = null; - this._backgroundBox = null; + return 'OutputStructNode'; } - /** - * Generates a PMREM from a supplied Scene, which can be faster than using an - * image if networking bandwidth is low. Optional sigma specifies a blur radius - * in radians to be applied to the scene before PMREM generation. Optional near - * and far planes ensure the scene is rendered in its entirety (the cubeCamera - * is placed at the origin). - */ - fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { - - _oldTarget = this._renderer.getRenderTarget(); - _oldActiveCubeFace = this._renderer.getActiveCubeFace(); - _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); - - this._setSize( 256 ); + constructor( ...members ) { - const cubeUVRenderTarget = this._allocateTargets(); - cubeUVRenderTarget.depthBuffer = true; + super(); - this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); + this.members = members; - if ( sigma > 0 ) { + this.isOutputStructNode = true; - this._blur( cubeUVRenderTarget, 0, 0, sigma ); + } - } + setup( builder ) { - this._applyPMREM( cubeUVRenderTarget ); + super.setup( builder ); - this._cleanup( cubeUVRenderTarget ); + const members = this.members; + const types = []; - return cubeUVRenderTarget; + for ( let i = 0; i < members.length; i ++ ) { - } + types.push( members[ i ].getNodeType( builder ) ); - /** - * Generates a PMREM from an equirectangular texture, which can be either LDR - * or HDR. The ideal input image size is 1k (1024 x 512), - * as this matches best with the 256 x 256 cubemap output. - */ - fromEquirectangular( equirectangular, renderTarget = null ) { + } - return this._fromTexture( equirectangular, renderTarget ); + this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name; } - /** - * Generates a PMREM from an cubemap texture, which can be either LDR - * or HDR. The ideal input cube size is 256 x 256, - * as this matches best with the 256 x 256 cubemap output. - */ - fromCubemap( cubemap, renderTarget = null ) { + generate( builder, output ) { - return this._fromTexture( cubemap, renderTarget ); + const propertyName = builder.getOutputStructName(); + const members = this.members; - } + const structPrefix = propertyName !== '' ? propertyName + '.' : ''; - /** - * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - async compileCubemapShader() { + for ( let i = 0; i < members.length; i ++ ) { - if ( this._cubemapMaterial === null ) { + const snippet = members[ i ].build( builder, output ); - this._cubemapMaterial = _getCubemapMaterial(); - await this._compileMaterial( this._cubemapMaterial ); + builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this ); } - } - - /** - * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - async compileEquirectangularShader() { - - if ( this._equirectMaterial === null ) { + return propertyName; - this._equirectMaterial = _getEquirectMaterial(); - await this._compileMaterial( this._equirectMaterial ); + } - } +} - } +const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode ); - /** - * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, - * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on - * one of them will cause any others to also become unusable. - */ - dispose() { +function getTextureIndex( textures, name ) { - this._dispose(); + for ( let i = 0; i < textures.length; i ++ ) { - if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); - if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); - if ( this._backgroundBox !== null ) { + if ( textures[ i ].name === name ) { - this._backgroundBox.geometry.dispose(); - this._backgroundBox.material.dispose(); + return i; } } - // private interface + return - 1; - _setSize( cubeSize ) { +} - this._lodMax = Math.floor( Math.log2( cubeSize ) ); - this._cubeSize = Math.pow( 2, this._lodMax ); +class MRTNode extends OutputStructNode { - } + static get type() { - _dispose() { + return 'MRTNode'; - if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); + } - if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); + constructor( outputNodes ) { - for ( let i = 0; i < this._lodPlanes.length; i ++ ) { + super(); - this._lodPlanes[ i ].dispose(); + this.outputNodes = outputNodes; - } + this.isMRTNode = true; } - _cleanup( outputTarget ) { + has( name ) { - this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel ); - outputTarget.scissorTest = false; - _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + return this.outputNodes[ name ] !== undefined; } - _fromTexture( texture, renderTarget ) { - - if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { - - this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); - - } else { // Equirectangular - - this._setSize( texture.image.width / 4 ); - - } - - _oldTarget = this._renderer.getRenderTarget(); - _oldActiveCubeFace = this._renderer.getActiveCubeFace(); - _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); - - const cubeUVRenderTarget = renderTarget || this._allocateTargets(); - this._textureToCubeUV( texture, cubeUVRenderTarget ); - this._applyPMREM( cubeUVRenderTarget ); - this._cleanup( cubeUVRenderTarget ); + get( name ) { - return cubeUVRenderTarget; + return this.outputNodes[ name ]; } - _allocateTargets() { + merge( mrtNode ) { - const width = 3 * Math.max( this._cubeSize, 16 * 7 ); - const height = 4 * this._cubeSize; + const outputs = { ...this.outputNodes, ...mrtNode.outputNodes }; - const params = { - magFilter: LinearFilter, - minFilter: LinearFilter, - generateMipmaps: false, - type: HalfFloatType, - format: RGBAFormat, - colorSpace: LinearSRGBColorSpace, - //depthBuffer: false - }; + return mrt( outputs ); - const cubeUVRenderTarget = _createRenderTarget( width, height, params ); + } - if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { + setup( builder ) { - if ( this._pingPongRenderTarget !== null ) { + const outputNodes = this.outputNodes; + const mrt = builder.renderer.getRenderTarget(); - this._dispose(); + const members = []; - } + const textures = mrt.textures; - this._pingPongRenderTarget = _createRenderTarget( width, height, params ); + for ( const name in outputNodes ) { - const { _lodMax } = this; - ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) ); + const index = getTextureIndex( textures, name ); - this._blurMaterial = _getBlurShader( _lodMax, width, height ); + members[ index ] = vec4( outputNodes[ name ] ); } - return cubeUVRenderTarget; - - } - - async _compileMaterial( material ) { + this.members = members; - const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); - await this._renderer.compile( tmpMesh, _flatCamera ); + return super.setup( builder ); } - _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { +} - const cubeCamera = _cubeCamera; - cubeCamera.near = near; - cubeCamera.far = far; +const mrt = /*@__PURE__*/ nodeProxy( MRTNode ); - // px, py, pz, nx, ny, nz - const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ]; - const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; +const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => { - const renderer = this._renderer; + // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org - const originalAutoClear = renderer.autoClear; + const state = seed.toUint().mul( 747796405 ).add( 2891336453 ); + const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 ); + const result = word.shiftRight( 22 ).bitXor( word ); - renderer.getClearColor( _clearColor$1 ); + return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1) - renderer.autoClear = false; +} ); - let backgroundBox = this._backgroundBox; +// remapping functions https://iquilezles.org/articles/functions/ +const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k ); +const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) ); +const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a ); +const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) ); - if ( backgroundBox === null ) { +// https://github.com/cabbibo/glsl-tri-noise-3d - const backgroundMaterial = new MeshBasicMaterial( { - name: 'PMREM.Background', - side: BackSide, - depthWrite: false, - depthTest: false - } ); - backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); +const tri = /*@__PURE__*/ Fn( ( [ x ] ) => { - } + return x.fract().sub( .5 ).abs(); - let useSolidColor = false; - const background = scene.background; +} ).setLayout( { + name: 'tri', + type: 'float', + inputs: [ + { name: 'x', type: 'float' } + ] +} ); - if ( background ) { +const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => { - if ( background.isColor ) { + return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) ); - backgroundBox.material.color.copy( background ); - scene.background = null; - useSolidColor = true; +} ).setLayout( { + name: 'tri3', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] +} ); - } +const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => { - } else { + const p = vec3( p_immutable ).toVar(); + const z = float( 1.4 ).toVar(); + const rz = float( 0.0 ).toVar(); + const bp = vec3( p ).toVar(); - backgroundBox.material.color.copy( _clearColor$1 ); - useSolidColor = true; + Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => { - } + const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar(); + p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) ); + bp.mulAssign( 1.8 ); + z.mulAssign( 1.5 ); + p.mulAssign( 1.2 ); - renderer.setRenderTarget( cubeUVRenderTarget ); + const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar(); + rz.addAssign( t.div( z ) ); + bp.addAssign( 0.14 ); - renderer.clear(); + } ); - if ( useSolidColor ) { + return rz; - renderer.render( backgroundBox, cubeCamera ); +} ).setLayout( { + name: 'triNoise3D', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'spd', type: 'float' }, + { name: 'time', type: 'float' } + ] +} ); - } +class FunctionOverloadingNode extends Node { - for ( let i = 0; i < 6; i ++ ) { + static get type() { - const col = i % 3; + return 'FunctionOverloadingNode'; - if ( col === 0 ) { + } - cubeCamera.up.set( 0, upSign[ i ], 0 ); - cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); + constructor( functionNodes = [], ...parametersNodes ) { - } else if ( col === 1 ) { + super(); - cubeCamera.up.set( 0, 0, upSign[ i ] ); - cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); + this.functionNodes = functionNodes; + this.parametersNodes = parametersNodes; - } else { + this._candidateFnCall = null; - cubeCamera.up.set( 0, upSign[ i ], 0 ); - cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); + this.global = true; - } + } - const size = this._cubeSize; + getNodeType() { - _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); + return this.functionNodes[ 0 ].shaderNode.layout.type; - renderer.render( scene, cubeCamera ); + } - } + setup( builder ) { - renderer.autoClear = originalAutoClear; - scene.background = background; + const params = this.parametersNodes; - } + let candidateFnCall = this._candidateFnCall; - _textureToCubeUV( texture, cubeUVRenderTarget ) { + if ( candidateFnCall === null ) { - const renderer = this._renderer; + let candidateFn = null; + let candidateScore = - 1; - const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); + for ( const functionNode of this.functionNodes ) { - if ( isCubeTexture ) { + const shaderNode = functionNode.shaderNode; + const layout = shaderNode.layout; - if ( this._cubemapMaterial === null ) { + if ( layout === null ) { - this._cubemapMaterial = _getCubemapMaterial( texture ); + throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' ); - } + } - } else { + const inputs = layout.inputs; - if ( this._equirectMaterial === null ) { + if ( params.length === inputs.length ) { - this._equirectMaterial = _getEquirectMaterial( texture ); + let score = 0; - } + for ( let i = 0; i < params.length; i ++ ) { - } + const param = params[ i ]; + const input = inputs[ i ]; - const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; - material.fragmentNode.value = texture; + if ( param.getNodeType( builder ) === input.type ) { - const mesh = this._lodMeshes[ 0 ]; - mesh.material = material; + score ++; - const size = this._cubeSize; + } else { - _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); + score = 0; - renderer.setRenderTarget( cubeUVRenderTarget ); - renderer.render( mesh, _flatCamera ); + } - } + } - _applyPMREM( cubeUVRenderTarget ) { + if ( score > candidateScore ) { - const renderer = this._renderer; - const autoClear = renderer.autoClear; - renderer.autoClear = false; - const n = this._lodPlanes.length; + candidateFn = functionNode; + candidateScore = score; - for ( let i = 1; i < n; i ++ ) { + } - const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); + } - const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ]; + } - this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); + this._candidateFnCall = candidateFnCall = candidateFn( ...params ); } - renderer.autoClear = autoClear; + return candidateFnCall; } - /** - * This is a two-pass Gaussian blur for a cubemap. Normally this is done - * vertically and horizontally, but this breaks down on a cube. Here we apply - * the blur latitudinally (around the poles), and then longitudinally (towards - * the poles) to approximate the orthogonally-separable blur. It is least - * accurate at the poles, but still does a decent job. - */ - _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { +} - const pingPongRenderTarget = this._pingPongRenderTarget; +const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode ); - this._halfBlur( - cubeUVRenderTarget, - pingPongRenderTarget, - lodIn, - lodOut, - sigma, - 'latitudinal', - poleAxis ); +const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params ); - this._halfBlur( - pingPongRenderTarget, - cubeUVRenderTarget, - lodOut, - lodOut, - sigma, - 'longitudinal', - poleAxis ); +const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time ); +const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime ); +const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId ); - } +// Deprecated - _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { +const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170 - const renderer = this._renderer; - const blurMaterial = this._blurMaterial; + console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' ); + return time.mul( timeScale ); - if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { +}; - console.error( 'blur direction must be either latitudinal or longitudinal!' ); +const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170 - } + console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' ); + return time.mul( timeScale ); - // Number of standard deviations at which to cut off the discrete approximation. - const STANDARD_DEVIATIONS = 3; +}; - const blurMesh = this._lodMeshes[ lodOut ]; - blurMesh.material = blurMaterial; +const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170 - const blurUniforms = blurMaterial.uniforms; + console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' ); + return deltaTime.mul( timeScale ); - const pixels = this._sizeLods[ lodIn ] - 1; - const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); - const sigmaPixels = sigmaRadians / radiansPerPixel; - const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; +}; - if ( samples > MAX_SAMPLES ) { +const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 ); +const oscSquare = ( t = time ) => t.fract().round(); +const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs(); +const oscSawtooth = ( t = time ) => t.fract(); - console.warn( `sigmaRadians, ${ - sigmaRadians}, is too large and will clip, as it requested ${ - samples} samples when the maximum is set to ${MAX_SAMPLES}` ); +const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => { - } + return rotate( uv.sub( center ), rotation ).add( center ); - const weights = []; - let sum = 0; +} ); - for ( let i = 0; i < MAX_SAMPLES; ++ i ) { +const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => { - const x = i / sigmaPixels; - const weight = Math.exp( - x * x / 2 ); - weights.push( weight ); + const delta = uv.sub( center ); + const delta2 = delta.dot( delta ); + const delta4 = delta2.mul( delta2 ); + const deltaOffset = delta4.mul( strength ); - if ( i === 0 ) { + return uv.add( delta.mul( deltaOffset ) ); - sum += weight; +} ); - } else if ( i < samples ) { +const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => { - sum += 2 * weight; + let worldMatrix; - } + if ( position !== null ) { - } + worldMatrix = modelWorldMatrix.toVar(); + worldMatrix[ 3 ][ 0 ] = position.x; + worldMatrix[ 3 ][ 1 ] = position.y; + worldMatrix[ 3 ][ 2 ] = position.z; - for ( let i = 0; i < weights.length; i ++ ) { + } else { - weights[ i ] = weights[ i ] / sum; + worldMatrix = modelWorldMatrix; - } + } - targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1; + const modelViewMatrix = cameraViewMatrix.mul( worldMatrix ); - blurUniforms.envMap.value = targetIn.texture; - blurUniforms.samples.value = samples; - blurUniforms.weights.array = weights; - blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0; - - if ( poleAxis ) { - - blurUniforms.poleAxis.value = poleAxis; + if ( defined( horizontal ) ) { - } + modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length(); + modelViewMatrix[ 0 ][ 1 ] = 0; + modelViewMatrix[ 0 ][ 2 ] = 0; - const { _lodMax } = this; - blurUniforms.dTheta.value = radiansPerPixel; - blurUniforms.mipInt.value = _lodMax - lodIn; + } - const outputSize = this._sizeLods[ lodOut ]; - const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); - const y = 4 * ( this._cubeSize - outputSize ); + if ( defined( vertical ) ) { - _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); - renderer.setRenderTarget( targetOut ); - renderer.render( blurMesh, _flatCamera ); + modelViewMatrix[ 1 ][ 0 ] = 0; + modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length(); + modelViewMatrix[ 1 ][ 2 ] = 0; } -} - -function _createPlanes( lodMax ) { - - const lodPlanes = []; - const sizeLods = []; - const sigmas = []; - const lodMeshes = []; + modelViewMatrix[ 2 ][ 0 ] = 0; + modelViewMatrix[ 2 ][ 1 ] = 0; + modelViewMatrix[ 2 ][ 2 ] = 1; - let lod = lodMax; + return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal ); - const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; +} ); - for ( let i = 0; i < totalLods; i ++ ) { +const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => { - const sizeLod = Math.pow( 2, lod ); - sizeLods.push( sizeLod ); - let sigma = 1.0 / sizeLod; + const depth = linearDepth(); + const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth ); + const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv ); - if ( i > lodMax - LOD_MIN ) { + return finalUV; - sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; +} ); - } else if ( i === 0 ) { +class SpriteSheetUVNode extends Node { - sigma = 0; + static get type() { - } + return 'SpriteSheetUVNode'; - sigmas.push( sigma ); + } - const texelSize = 1.0 / ( sizeLod - 2 ); - const min = - texelSize; - const max = 1 + texelSize; - const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { - const cubeFaces = 6; - const vertices = 6; - const positionSize = 3; - const uvSize = 2; - const faceIndexSize = 1; + super( 'vec2' ); - const position = new Float32Array( positionSize * vertices * cubeFaces ); - const uv = new Float32Array( uvSize * vertices * cubeFaces ); - const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + this.countNode = countNode; + this.uvNode = uvNode; + this.frameNode = frameNode; - for ( let face = 0; face < cubeFaces; face ++ ) { + } - const x = ( face % 3 ) * 2 / 3 - 1; - const y = face > 2 ? 0 : - 1; - const coordinates = [ - x, y, 0, - x + 2 / 3, y, 0, - x + 2 / 3, y + 1, 0, - x, y, 0, - x + 2 / 3, y + 1, 0, - x, y + 1, 0 - ]; + setup() { - const faceIdx = _faceLib[ face ]; - position.set( coordinates, positionSize * vertices * faceIdx ); - uv.set( uv1, uvSize * vertices * faceIdx ); - const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ]; - faceIndex.set( fill, faceIndexSize * vertices * faceIdx ); + const { frameNode, uvNode, countNode } = this; - } + const { width, height } = countNode; - const planes = new BufferGeometry(); - planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); - planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); - planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); - lodPlanes.push( planes ); - lodMeshes.push( new Mesh( planes, null ) ); + const frameNum = frameNode.mod( width.mul( height ) ).floor(); - if ( lod > LOD_MIN ) { + const column = frameNum.mod( width ); + const row = height.sub( frameNum.add( 1 ).div( width ).ceil() ); - lod --; + const scale = countNode.reciprocal(); + const uvFrameOffset = vec2( column, row ); - } + return uvNode.add( uvFrameOffset ).mul( scale ); } - return { lodPlanes, sizeLods, sigmas, lodMeshes }; - } -function _createRenderTarget( width, height, params ) { +const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ); - const cubeUVRenderTarget = new RenderTarget( width, height, params ); - cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; - cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; - cubeUVRenderTarget.texture.isPMREMTexture = true; - cubeUVRenderTarget.scissorTest = true; - return cubeUVRenderTarget; +class TriplanarTexturesNode extends Node { -} + static get type() { -function _setViewport( target, x, y, width, height ) { + return 'TriplanarTexturesNode'; - target.viewport.set( x, y, width, height ); - target.scissor.set( x, y, width, height ); + } -} + constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { -function _getMaterial( type ) { + super( 'vec4' ); - const material = new NodeMaterial(); - material.depthTest = false; - material.depthWrite = false; - material.blending = NoBlending; - material.name = `PMREM_${ type }`; + this.textureXNode = textureXNode; + this.textureYNode = textureYNode; + this.textureZNode = textureZNode; - return material; + this.scaleNode = scaleNode; -} + this.positionNode = positionNode; + this.normalNode = normalNode; -function _getBlurShader( lodMax, width, height ) { + } - const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) ); - const poleAxis = uniform( new Vector3( 0, 1, 0 ) ); - const dTheta = uniform( 0 ); - const n = float( MAX_SAMPLES ); - const latitudinal = uniform( 0 ); // false, bool - const samples = uniform( 1 ); // int - const envMap = texture( null ); - const mipInt = uniform( 0 ); // int - const CUBEUV_TEXEL_WIDTH = float( 1 / width ); - const CUBEUV_TEXEL_HEIGHT = float( 1 / height ); - const CUBEUV_MAX_MIP = float( lodMax ); + setup() { - const materialUniforms = { - n, - latitudinal, - weights, - poleAxis, - outputDirection, - dTheta, - samples, - envMap, - mipInt, - CUBEUV_TEXEL_WIDTH, - CUBEUV_TEXEL_HEIGHT, - CUBEUV_MAX_MIP - }; + const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this; - const material = _getMaterial( 'blur' ); - material.uniforms = materialUniforms; // TODO: Move to outside of the material - material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } ); + // Ref: https://github.com/keijiro/StandardTriplanar - return material; + // Blending factor of triplanar mapping + let bf = normalNode.abs().normalize(); + bf = bf.div( bf.dot( vec3( 1.0 ) ) ); -} + // Triplanar mapping + const tx = positionNode.yz.mul( scaleNode ); + const ty = positionNode.zx.mul( scaleNode ); + const tz = positionNode.xy.mul( scaleNode ); -function _getCubemapMaterial( envTexture ) { + // Base color + const textureX = textureXNode.value; + const textureY = textureYNode !== null ? textureYNode.value : textureX; + const textureZ = textureZNode !== null ? textureZNode.value : textureX; - const material = _getMaterial( 'cubemap' ); - material.fragmentNode = cubeTexture( envTexture, outputDirection ); + const cx = texture( textureX, tx ).mul( bf.x ); + const cy = texture( textureY, ty ).mul( bf.y ); + const cz = texture( textureZ, tz ).mul( bf.z ); - return material; + return add( cx, cy, cz ); + + } } -function _getEquirectMaterial( envTexture ) { +const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ); +const triplanarTexture = ( ...params ) => triplanarTextures( ...params ); - const material = _getMaterial( 'equirect' ); - material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 ); +const _reflectorPlane = new Plane(); +const _normal = new Vector3(); +const _reflectorWorldPosition = new Vector3(); +const _cameraWorldPosition = new Vector3(); +const _rotationMatrix = new Matrix4(); +const _lookAtPosition = new Vector3( 0, 0, - 1 ); +const clipPlane = new Vector4(); - return material; +const _view = new Vector3(); +const _target = new Vector3(); +const _q = new Vector4(); -} +const _size$2 = new Vector2(); -let _id$5 = 0; +const _defaultRT = new RenderTarget(); +const _defaultUV = screenUV.flipX(); -class BindGroup { +_defaultRT.depthTexture = new DepthTexture( 1, 1 ); - constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) { +let _inReflector = false; - this.name = name; - this.bindings = bindings; - this.index = index; - this.bindingsReference = bindingsReference; +class ReflectorNode extends TextureNode { - this.id = _id$5 ++; + static get type() { + + return 'ReflectorNode'; } -} + constructor( parameters = {} ) { -const rendererCache = new WeakMap(); + super( parameters.defaultTexture || _defaultRT.texture, _defaultUV ); -const typeFromLength = new Map( [ - [ 2, 'vec2' ], - [ 3, 'vec3' ], - [ 4, 'vec4' ], - [ 9, 'mat3' ], - [ 16, 'mat4' ] -] ); + this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters ); + this._depthNode = null; -const typeFromArray = new Map( [ - [ Int8Array, 'int' ], - [ Int16Array, 'int' ], - [ Int32Array, 'int' ], - [ Uint8Array, 'uint' ], - [ Uint16Array, 'uint' ], - [ Uint32Array, 'uint' ], - [ Float32Array, 'float' ] -] ); + this.setUpdateMatrix( false ); -const toFloat = ( value ) => { + } - if ( /e/g.test( value ) ) { + get reflector() { - return String( value ).replace( /\+/g, '' ); + return this._reflectorBaseNode; - } else { + } - value = Number( value ); + get target() { - return value + ( value % 1 ? '' : '.0' ); + return this._reflectorBaseNode.target; } -}; + getDepthNode() { -class NodeBuilder { + if ( this._depthNode === null ) { - constructor( object, renderer, parser ) { + if ( this._reflectorBaseNode.depth !== true ) { - this.object = object; - this.material = ( object && object.material ) || null; - this.geometry = ( object && object.geometry ) || null; - this.renderer = renderer; - this.parser = parser; - this.scene = null; - this.camera = null; + throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' ); - this.nodes = []; - this.sequentialNodes = []; - this.updateNodes = []; - this.updateBeforeNodes = []; - this.updateAfterNodes = []; - this.hashNodes = {}; + } - this.monitor = null; + this._depthNode = nodeObject( new ReflectorNode( { + defaultTexture: _defaultRT.depthTexture, + reflector: this._reflectorBaseNode + } ) ); - this.lightsNode = null; - this.environmentNode = null; - this.fogNode = null; + } - this.clippingContext = null; + return this._depthNode; - 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.bindings = { vertex: {}, fragment: {}, compute: {} }; - this.bindingsIndexes = {}; - this.bindGroups = null; - this.attributes = []; - this.bufferAttributes = []; - this.varyings = []; - this.codes = {}; - this.vars = {}; - this.flow = { code: '' }; - this.chaining = []; - this.stack = stack(); - this.stacks = []; - this.tab = '\t'; + setup( builder ) { - this.currentFunctionNode = null; + // ignore if used in post-processing + if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder ); - this.context = { - material: this.material - }; + return super.setup( builder ); - this.cache = new NodeCache(); - this.globalCache = this.cache; + } - this.flowsData = new WeakMap(); + clone() { - this.shaderStage = null; - this.buildStage = null; + const texture = new this.constructor( this.reflectorNode ); + texture._reflectorBaseNode = this._reflectorBaseNode; - this.useComparisonMethod = false; + return texture; } - getBindGroupsCache() { +} - let bindGroupsCache = rendererCache.get( this.renderer ); - if ( bindGroupsCache === undefined ) { +class ReflectorBaseNode extends Node { - bindGroupsCache = new ChainMap(); + static get type() { - rendererCache.set( this.renderer, bindGroupsCache ); + return 'ReflectorBaseNode'; - } + } - return bindGroupsCache; + constructor( textureNode, parameters = {} ) { - } + super(); - createRenderTarget( width, height, options ) { + const { + target = new Object3D(), + resolution = 1, + generateMipmaps = false, + bounces = true, + depth = false + } = parameters; - return new RenderTarget( width, height, options ); + // - } + this.textureNode = textureNode; - createCubeRenderTarget( size, options ) { + this.target = target; + this.resolution = resolution; + this.generateMipmaps = generateMipmaps; + this.bounces = bounces; + this.depth = depth; - return new CubeRenderTarget( size, options ); + this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME; + + this.virtualCameras = new WeakMap(); + this.renderTargets = new WeakMap(); } - createPMREMGenerator() { + _updateResolution( renderTarget, renderer ) { - // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support + const resolution = this.resolution; - return new PMREMGenerator( this.renderer ); + renderer.getDrawingBufferSize( _size$2 ); + + renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) ); } - includes( node ) { + setup( builder ) { - return this.nodes.includes( node ); + this._updateResolution( _defaultRT, builder.renderer ); + + return super.setup( builder ); } - _getBindGroup( groupName, bindings ) { + getVirtualCamera( camera ) { - const bindGroupsCache = this.getBindGroupsCache(); + let virtualCamera = this.virtualCameras.get( camera ); - // + if ( virtualCamera === undefined ) { - const bindingsArray = []; + virtualCamera = camera.clone(); - let sharedGroup = true; + this.virtualCameras.set( camera, virtualCamera ); - for ( const binding of bindings ) { + } - bindingsArray.push( binding ); + return virtualCamera; - sharedGroup = sharedGroup && binding.groupNode.shared !== true; + } - } + getRenderTarget( camera ) { - // + let renderTarget = this.renderTargets.get( camera ); - let bindGroup; + if ( renderTarget === undefined ) { - if ( sharedGroup ) { + renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } ); - bindGroup = bindGroupsCache.get( bindingsArray ); + if ( this.generateMipmaps === true ) { - if ( bindGroup === undefined ) { + renderTarget.texture.minFilter = LinearMipMapLinearFilter; + renderTarget.texture.generateMipmaps = true; - bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray ); + } - bindGroupsCache.set( bindingsArray, bindGroup ); + if ( this.depth === true ) { - } + renderTarget.depthTexture = new DepthTexture(); - } else { + } - bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray ); + this.renderTargets.set( camera, renderTarget ); } - return bindGroup; + return renderTarget; } - getBindGroupArray( groupName, shaderStage ) { + updateBefore( frame ) { - const bindings = this.bindings[ shaderStage ]; + if ( this.bounces === false && _inReflector ) return; - let bindGroup = bindings[ groupName ]; + _inReflector = true; - if ( bindGroup === undefined ) { + const { scene, camera, renderer, material } = frame; + const { target } = this; - if ( this.bindingsIndexes[ groupName ] === undefined ) { + const virtualCamera = this.getVirtualCamera( camera ); + const renderTarget = this.getRenderTarget( virtualCamera ); - this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length }; + renderer.getDrawingBufferSize( _size$2 ); - } + this._updateResolution( renderTarget, renderer ); - bindings[ groupName ] = bindGroup = []; + // - } + _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld ); + _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); - return bindGroup; + _rotationMatrix.extractRotation( target.matrixWorld ); - } + _normal.set( 0, 0, 1 ); + _normal.applyMatrix4( _rotationMatrix ); - getBindings() { + _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition ); - let bindingsGroups = this.bindGroups; + // Avoid rendering when reflector is facing away - if ( bindingsGroups === null ) { + if ( _view.dot( _normal ) > 0 ) return; - const groups = {}; - const bindings = this.bindings; + _view.reflect( _normal ).negate(); + _view.add( _reflectorWorldPosition ); - for ( const shaderStage of shaderStages ) { + _rotationMatrix.extractRotation( camera.matrixWorld ); - for ( const groupName in bindings[ shaderStage ] ) { + _lookAtPosition.set( 0, 0, - 1 ); + _lookAtPosition.applyMatrix4( _rotationMatrix ); + _lookAtPosition.add( _cameraWorldPosition ); - const uniforms = bindings[ shaderStage ][ groupName ]; + _target.subVectors( _reflectorWorldPosition, _lookAtPosition ); + _target.reflect( _normal ).negate(); + _target.add( _reflectorWorldPosition ); - const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] ); - groupUniforms.push( ...uniforms ); + // - } + virtualCamera.coordinateSystem = camera.coordinateSystem; + virtualCamera.position.copy( _view ); + virtualCamera.up.set( 0, 1, 0 ); + virtualCamera.up.applyMatrix4( _rotationMatrix ); + virtualCamera.up.reflect( _normal ); + virtualCamera.lookAt( _target ); - } + virtualCamera.near = camera.near; + virtualCamera.far = camera.far; - bindingsGroups = []; + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); - for ( const groupName in groups ) { + // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html + // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf + _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition ); + _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); - const group = groups[ groupName ]; + clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant ); - const bindingsGroup = this._getBindGroup( groupName, group ); + const projectionMatrix = virtualCamera.projectionMatrix; - bindingsGroups.push( bindingsGroup ); + _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; + _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; + _q.z = - 1.0; + _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; - } + // Calculate the scaled plane vector + clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) ); - this.bindGroups = bindingsGroups; - - } - - return bindingsGroups; - - } - - sortBindingGroups() { + const clipBias = 0; - const bindingsGroups = this.getBindings(); + // Replacing the third row of the projection matrix + projectionMatrix.elements[ 2 ] = clipPlane.x; + projectionMatrix.elements[ 6 ] = clipPlane.y; + projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias ); + projectionMatrix.elements[ 14 ] = clipPlane.w; - bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) ); + // - for ( let i = 0; i < bindingsGroups.length; i ++ ) { + this.textureNode.value = renderTarget.texture; - const bindingGroup = bindingsGroups[ i ]; - this.bindingsIndexes[ bindingGroup.name ].group = i; + if ( this.depth === true ) { - bindingGroup.index = i; + this.textureNode.getDepthNode().value = renderTarget.depthTexture; } - } - - setHashNode( node, hash ) { - - this.hashNodes[ hash ] = node; + material.visible = false; - } + const currentRenderTarget = renderer.getRenderTarget(); + const currentMRT = renderer.getMRT(); - addNode( node ) { + renderer.setMRT( null ); + renderer.setRenderTarget( renderTarget ); - if ( this.nodes.includes( node ) === false ) { + renderer.render( scene, virtualCamera ); - this.nodes.push( node ); + renderer.setMRT( currentMRT ); + renderer.setRenderTarget( currentRenderTarget ); - this.setHashNode( node, node.getHash( this ) ); + material.visible = true; - } + _inReflector = false; } - addSequentialNode( node ) { - - if ( this.sequentialNodes.includes( node ) === false ) { - - this.sequentialNodes.push( node ); - - } +} - } +const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) ); - buildUpdateNodes() { +// Helper for passes that need to fill the viewport with a single quad. - for ( const node of this.nodes ) { +const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); - const updateType = node.getUpdateType(); +// https://github.com/mrdoob/three.js/pull/21358 - if ( updateType !== NodeUpdateType.NONE ) { +class QuadGeometry extends BufferGeometry { - this.updateNodes.push( node.getSelf() ); + constructor( flipY = false ) { - } + super(); - } + const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ]; - for ( const node of this.sequentialNodes ) { + this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) ); - const updateBeforeType = node.getUpdateBeforeType(); - const updateAfterType = node.getUpdateAfterType(); + } - if ( updateBeforeType !== NodeUpdateType.NONE ) { +} - this.updateBeforeNodes.push( node.getSelf() ); +const _geometry = /*@__PURE__*/ new QuadGeometry(); - } +class QuadMesh extends Mesh { - if ( updateAfterType !== NodeUpdateType.NONE ) { + constructor( material = null ) { - this.updateAfterNodes.push( node.getSelf() ); + super( _geometry, material ); - } + this.camera = _camera; - } + this.isQuadMesh = true; } - get currentNode() { + renderAsync( renderer ) { - return this.chaining[ this.chaining.length - 1 ]; + return renderer.renderAsync( this, _camera ); } - isFilteredTexture( texture ) { + render( renderer ) { - return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || - texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ); + renderer.render( this, _camera ); } - addChain( node ) { +} - /* - if ( this.chaining.indexOf( node ) !== - 1 ) { +const _size$1 = /*@__PURE__*/ new Vector2(); - console.warn( 'Recursive node: ', node ); +class RTTNode extends TextureNode { - } - */ + static get type() { - this.chaining.push( node ); + return 'RTTNode'; } - removeChain( node ) { + constructor( node, width = null, height = null, options = { type: HalfFloatType } ) { - const lastChain = this.chaining.pop(); + const renderTarget = new RenderTarget( width, height, options ); - if ( lastChain !== node ) { + super( renderTarget.texture, uv() ); - throw new Error( 'NodeBuilder: Invalid node chaining!' ); + this.node = node; + this.width = width; + this.height = height; - } + this.renderTarget = renderTarget; - } + this.textureNeedsUpdate = true; + this.autoUpdate = true; - getMethod( method ) { + this.updateMap = new WeakMap(); - return method; + this._rttNode = null; + this._quadMesh = new QuadMesh( new NodeMaterial() ); + + this.updateBeforeType = NodeUpdateType.RENDER; } - getNodeFromHash( hash ) { + get autoSize() { - return this.hashNodes[ hash ]; + return this.width === null; } - addFlow( shaderStage, node ) { + setup( builder ) { - this.flowNodes[ shaderStage ].push( node ); + this._rttNode = this.node.context( builder.getSharedContext() ); + this._quadMesh.material.name = 'RTT'; + this._quadMesh.material.needsUpdate = true; - return node; + return super.setup( builder ); } - setContext( context ) { + setSize( width, height ) { - this.context = context; + this.width = width; + this.height = height; - } + const effectiveWidth = width * this.pixelRatio; + const effectiveHeight = height * this.pixelRatio; - getContext() { + this.renderTarget.setSize( effectiveWidth, effectiveHeight ); - return this.context; + this.textureNeedsUpdate = true; } - getSharedContext() { + setPixelRatio( pixelRatio ) { - ({ ...this.context }); + this.pixelRatio = pixelRatio; - return this.context; + this.setSize( this.width, this.height ); } - setCache( cache ) { - - this.cache = cache; - - } + updateBefore( { renderer } ) { - getCache() { + if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return; - return this.cache; + this.textureNeedsUpdate = false; - } + // - getCacheFromNode( node, parent = true ) { + if ( this.autoSize === true ) { - const data = this.getDataFromNode( node ); - if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null ); + this.pixelRatio = renderer.getPixelRatio(); - return data.cache; + const size = renderer.getSize( _size$1 ); - } + this.setSize( size.width, size.height ); - isAvailable( /*name*/ ) { + } - return false; + // - } + this._quadMesh.material.fragmentNode = this._rttNode; - getVertexIndex() { + // - console.warn( 'Abstract function.' ); + const currentRenderTarget = renderer.getRenderTarget(); - } + renderer.setRenderTarget( this.renderTarget ); - getInstanceIndex() { + this._quadMesh.render( renderer ); - console.warn( 'Abstract function.' ); + renderer.setRenderTarget( currentRenderTarget ); } - getDrawIndex() { + clone() { - console.warn( 'Abstract function.' ); + const newNode = new TextureNode( this.value, this.uvNode, this.levelNode ); + newNode.sampler = this.sampler; + newNode.referenceNode = this; + + return newNode; } - getFrontFacing() { +} - console.warn( 'Abstract function.' ); +const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) ); +const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ); - } +/** +* Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments +* depth value and the camera's inverse projection matrix. +* +* @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates. +* @param {float} depth - The fragment's depth value. +* @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix. +* @return {vec3} The fragments position in view space. +*/ +const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => { - getFragCoord() { + let clipSpacePosition; - console.warn( 'Abstract function.' ); + if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) { - } + screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 ); + clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 ); - isFlipY() { + } else { - return false; + clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 ); } - increaseUsage( node ) { + const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) ); - const nodeData = this.getDataFromNode( node ); - nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1; + return viewSpacePosition.xyz.div( viewSpacePosition.w ); - return nodeData.usageCount; +} ); - } +/** +* Computes a screen position expressed as uv coordinates based on a fragment's position in view space +* and the camera's projection matrix +* +* @param {vec3} viewPosition - The fragments position in view space. +* @param {mat4} projectionMatrix - The camera's projection matrix. +* @return {vec2} Teh fragment's screen position expressed as uv coordinates. +*/ +const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => { - generateTexture( /* texture, textureProperty, uvSnippet */ ) { + const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) ); + const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar(); + return vec2( sampleUv.x, sampleUv.y.oneMinus() ); - console.warn( 'Abstract function.' ); +} ); - } +class VertexColorNode extends AttributeNode { - generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) { + static get type() { - console.warn( 'Abstract function.' ); + return 'VertexColorNode'; } - generateConst( type, value = null ) { - - if ( value === null ) { - - if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0; - else if ( type === 'bool' ) value = false; - else if ( type === 'color' ) value = new Color(); - else if ( type === 'vec2' ) value = new Vector2(); - else if ( type === 'vec3' ) value = new Vector3(); - else if ( type === 'vec4' ) value = new Vector4(); + constructor( index = 0 ) { - } + super( null, 'vec4' ); - if ( type === 'float' ) return toFloat( value ); - if ( type === 'int' ) return `${ Math.round( value ) }`; - if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u'; - if ( type === 'bool' ) return value ? 'true' : 'false'; - if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`; + this.isVertexColorNode = true; - const typeLength = this.getTypeLength( type ); + this.index = index; - const componentType = this.getComponentType( type ); + } - const generateConst = value => this.generateConst( componentType, value ); + getAttributeName( /*builder*/ ) { - if ( typeLength === 2 ) { + const index = this.index; - return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`; + return 'color' + ( index > 0 ? index : '' ); - } else if ( typeLength === 3 ) { + } - return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`; + generate( builder ) { - } else if ( typeLength === 4 ) { + const attributeName = this.getAttributeName( builder ); + const geometryAttribute = builder.hasGeometryAttribute( attributeName ); - return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`; + let result; - } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) { + if ( geometryAttribute === true ) { - return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`; + result = super.generate( builder ); - } else if ( typeLength > 4 ) { + } else { - return `${ this.getType( type ) }()`; + // Vertex color fallback should be white + result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) ); } - throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` ); + return result; } - getType( type ) { + serialize( data ) { - if ( type === 'color' ) return 'vec3'; + super.serialize( data ); - return type; + data.index = this.index; } - hasGeometryAttribute( name ) { - - return this.geometry && this.geometry.getAttribute( name ) !== undefined; - - } + deserialize( data ) { - getAttribute( name, type ) { + super.deserialize( data ); - const attributes = this.attributes; + this.index = data.index; - // find attribute + } - for ( const attribute of attributes ) { +} - if ( attribute.name === name ) { +const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) ); - return attribute; +class PointUVNode extends Node { - } + static get type() { - } + return 'PointUVNode'; - // create a new if no exist + } - const attribute = new NodeAttribute( name, type ); + constructor() { - attributes.push( attribute ); + super( 'vec2' ); - return attribute; + this.isPointUVNode = true; } - getPropertyName( node/*, shaderStage*/ ) { + generate( /*builder*/ ) { - return node.name; + return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )'; } - isVector( type ) { +} - return /vec\d/.test( type ); +const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode ); - } +class SceneNode extends Node { - isMatrix( type ) { + static get type() { - return /mat\d/.test( type ); + return 'SceneNode'; } - isReference( type ) { - - return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D'; - - } + constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) { - needsToWorkingColorSpace( /*texture*/ ) { + super(); - return false; + this.scope = scope; + this.scene = scene; } - getComponentTypeFromTexture( texture ) { + setup( builder ) { - const type = texture.type; + const scope = this.scope; + const scene = this.scene !== null ? this.scene : builder.scene; - if ( texture.isDataTexture ) { + let output; - if ( type === IntType ) return 'int'; - if ( type === UnsignedIntType ) return 'uint'; + if ( scope === SceneNode.BACKGROUND_BLURRINESS ) { - } + output = reference( 'backgroundBlurriness', 'float', scene ); - return 'float'; + } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) { - } + output = reference( 'backgroundIntensity', 'float', scene ); - getElementType( type ) { + } else { - if ( type === 'mat2' ) return 'vec2'; - if ( type === 'mat3' ) return 'vec3'; - if ( type === 'mat4' ) return 'vec4'; + console.error( 'THREE.SceneNode: Unknown scope:', scope ); - return this.getComponentType( type ); + } - } + return output; - getComponentType( type ) { + } - type = this.getVectorType( type ); +} - if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type; +SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness'; +SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity'; - const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type ); +const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS ); +const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY ); - if ( componentType === null ) return null; +class StorageArrayElementNode extends ArrayElementNode { - if ( componentType[ 1 ] === 'b' ) return 'bool'; - if ( componentType[ 1 ] === 'i' ) return 'int'; - if ( componentType[ 1 ] === 'u' ) return 'uint'; + static get type() { - return 'float'; + return 'StorageArrayElementNode'; } - getVectorType( type ) { + constructor( storageBufferNode, indexNode ) { - if ( type === 'color' ) return 'vec3'; - if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4'; + super( storageBufferNode, indexNode ); - return type; + this.isStorageArrayElementNode = true; } - getTypeFromLength( length, componentType = 'float' ) { - - if ( length === 1 ) return componentType; - - const baseType = typeFromLength.get( length ); - const prefix = componentType === 'float' ? '' : componentType[ 0 ]; + set storageBufferNode( value ) { - return prefix + baseType; + this.node = value; } - getTypeFromArray( array ) { + get storageBufferNode() { - return typeFromArray.get( array.constructor ); + return this.node; } - getTypeFromAttribute( attribute ) { - - let dataAttribute = attribute; - - if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data; + setup( builder ) { - const array = dataAttribute.array; - const itemSize = attribute.itemSize; - const normalized = attribute.normalized; + if ( builder.isAvailable( 'storageBuffer' ) === false ) { - let arrayType; + if ( this.node.bufferObject === true ) { - if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) { + builder.setupPBO( this.node ); - arrayType = this.getTypeFromArray( array ); + } } - return this.getTypeFromLength( itemSize, arrayType ); + return super.setup( builder ); } - getTypeLength( type ) { - - const vecType = this.getVectorType( type ); - const vecNum = /vec([2-4])/.exec( vecType ); - - if ( vecNum !== null ) return Number( vecNum[ 1 ] ); - if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1; - if ( /mat2/.test( type ) === true ) return 4; - if ( /mat3/.test( type ) === true ) return 9; - if ( /mat4/.test( type ) === true ) return 16; + generate( builder, output ) { - return 0; + let snippet; - } + const isAssignContext = builder.context.assign; - getVectorFromMatrix( type ) { + // - return type.replace( 'mat', 'vec' ); + if ( builder.isAvailable( 'storageBuffer' ) === false ) { - } + if ( this.node.bufferObject === true && isAssignContext !== true ) { - changeComponentType( type, newComponentType ) { + snippet = builder.generatePBO( this ); - return this.getTypeFromLength( this.getTypeLength( type ), newComponentType ); + } else { - } + snippet = this.node.build( builder ); - getIntegerType( type ) { + } - const componentType = this.getComponentType( type ); + } else { - if ( componentType === 'int' || componentType === 'uint' ) return type; + snippet = super.generate( builder ); - return this.changeComponentType( type, 'int' ); + } - } + if ( isAssignContext !== true ) { - addStack() { + const type = this.getNodeType( builder ); - this.stack = stack( this.stack ); + snippet = builder.format( snippet, type, output ); - this.stacks.push( getCurrentStack() || this.stack ); - setCurrentStack( this.stack ); + } - return this.stack; + return snippet; } - removeStack() { - - const lastStack = this.stack; - this.stack = lastStack.parent; - - setCurrentStack( this.stacks.pop() ); - - return lastStack; +} - } +const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ); - getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) { +const GPUPrimitiveTopology = { + PointList: 'point-list', + LineList: 'line-list', + LineStrip: 'line-strip', + TriangleList: 'triangle-list', + TriangleStrip: 'triangle-strip', +}; - cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache; +const GPUCompareFunction = { + Never: 'never', + Less: 'less', + Equal: 'equal', + LessEqual: 'less-equal', + Greater: 'greater', + NotEqual: 'not-equal', + GreaterEqual: 'greater-equal', + Always: 'always' +}; - let nodeData = cache.getData( node ); +const GPUStoreOp = { + Store: 'store', + Discard: 'discard' +}; - if ( nodeData === undefined ) { +const GPULoadOp = { + Load: 'load', + Clear: 'clear' +}; - nodeData = {}; +const GPUFrontFace = { + CCW: 'ccw', + CW: 'cw' +}; - cache.setData( node, nodeData ); +const GPUCullMode = { + None: 'none', + Front: 'front', + Back: 'back' +}; - } +const GPUIndexFormat = { + Uint16: 'uint16', + Uint32: 'uint32' +}; - if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {}; +const GPUTextureFormat = { - return nodeData[ shaderStage ]; + // 8-bit formats - } + R8Unorm: 'r8unorm', + R8Snorm: 'r8snorm', + R8Uint: 'r8uint', + R8Sint: 'r8sint', - getNodeProperties( node, shaderStage = 'any' ) { + // 16-bit formats - const nodeData = this.getDataFromNode( node, shaderStage ); + R16Uint: 'r16uint', + R16Sint: 'r16sint', + R16Float: 'r16float', + RG8Unorm: 'rg8unorm', + RG8Snorm: 'rg8snorm', + RG8Uint: 'rg8uint', + RG8Sint: 'rg8sint', - return nodeData.properties || ( nodeData.properties = { outputNode: null } ); + // 32-bit formats - } + R32Uint: 'r32uint', + R32Sint: 'r32sint', + R32Float: 'r32float', + RG16Uint: 'rg16uint', + RG16Sint: 'rg16sint', + RG16Float: 'rg16float', + RGBA8Unorm: 'rgba8unorm', + RGBA8UnormSRGB: 'rgba8unorm-srgb', + RGBA8Snorm: 'rgba8snorm', + RGBA8Uint: 'rgba8uint', + RGBA8Sint: 'rgba8sint', + BGRA8Unorm: 'bgra8unorm', + BGRA8UnormSRGB: 'bgra8unorm-srgb', + // Packed 32-bit formats + RGB9E5UFloat: 'rgb9e5ufloat', + RGB10A2Unorm: 'rgb10a2unorm', + RG11B10uFloat: 'rgb10a2unorm', - getBufferAttributeFromNode( node, type ) { + // 64-bit formats - const nodeData = this.getDataFromNode( node ); + RG32Uint: 'rg32uint', + RG32Sint: 'rg32sint', + RG32Float: 'rg32float', + RGBA16Uint: 'rgba16uint', + RGBA16Sint: 'rgba16sint', + RGBA16Float: 'rgba16float', - let bufferAttribute = nodeData.bufferAttribute; + // 128-bit formats - if ( bufferAttribute === undefined ) { + RGBA32Uint: 'rgba32uint', + RGBA32Sint: 'rgba32sint', + RGBA32Float: 'rgba32float', - const index = this.uniforms.index ++; + // Depth and stencil formats - bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node ); + Stencil8: 'stencil8', + Depth16Unorm: 'depth16unorm', + Depth24Plus: 'depth24plus', + Depth24PlusStencil8: 'depth24plus-stencil8', + Depth32Float: 'depth32float', - this.bufferAttributes.push( bufferAttribute ); + // 'depth32float-stencil8' extension - nodeData.bufferAttribute = bufferAttribute; + Depth32FloatStencil8: 'depth32float-stencil8', - } + // BC compressed formats usable if 'texture-compression-bc' is both + // supported by the device/user agent and enabled in requestDevice. - return bufferAttribute; + BC1RGBAUnorm: 'bc1-rgba-unorm', + BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb', + BC2RGBAUnorm: 'bc2-rgba-unorm', + BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb', + BC3RGBAUnorm: 'bc3-rgba-unorm', + BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb', + BC4RUnorm: 'bc4-r-unorm', + BC4RSnorm: 'bc4-r-snorm', + BC5RGUnorm: 'bc5-rg-unorm', + BC5RGSnorm: 'bc5-rg-snorm', + BC6HRGBUFloat: 'bc6h-rgb-ufloat', + BC6HRGBFloat: 'bc6h-rgb-float', + BC7RGBAUnorm: 'bc7-rgba-unorm', + BC7RGBAUnormSRGB: 'bc7-rgba-srgb', - } + // ETC2 compressed formats usable if 'texture-compression-etc2' is both + // supported by the device/user agent and enabled in requestDevice. - getStructTypeFromNode( node, shaderStage = this.shaderStage ) { + ETC2RGB8Unorm: 'etc2-rgb8unorm', + ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb', + ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm', + ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb', + ETC2RGBA8Unorm: 'etc2-rgba8unorm', + ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb', + EACR11Unorm: 'eac-r11unorm', + EACR11Snorm: 'eac-r11snorm', + EACRG11Unorm: 'eac-rg11unorm', + EACRG11Snorm: 'eac-rg11snorm', - const nodeData = this.getDataFromNode( node, shaderStage ); + // ASTC compressed formats usable if 'texture-compression-astc' is both + // supported by the device/user agent and enabled in requestDevice. - if ( nodeData.structType === undefined ) { + ASTC4x4Unorm: 'astc-4x4-unorm', + ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb', + ASTC5x4Unorm: 'astc-5x4-unorm', + ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb', + ASTC5x5Unorm: 'astc-5x5-unorm', + ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb', + ASTC6x5Unorm: 'astc-6x5-unorm', + ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb', + ASTC6x6Unorm: 'astc-6x6-unorm', + ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb', + ASTC8x5Unorm: 'astc-8x5-unorm', + ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb', + ASTC8x6Unorm: 'astc-8x6-unorm', + ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb', + ASTC8x8Unorm: 'astc-8x8-unorm', + ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb', + ASTC10x5Unorm: 'astc-10x5-unorm', + ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb', + ASTC10x6Unorm: 'astc-10x6-unorm', + ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb', + ASTC10x8Unorm: 'astc-10x8-unorm', + ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb', + ASTC10x10Unorm: 'astc-10x10-unorm', + ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb', + ASTC12x10Unorm: 'astc-12x10-unorm', + ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb', + ASTC12x12Unorm: 'astc-12x12-unorm', + ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb', - const index = this.structs.index ++; +}; - node.name = `StructType${ index }`; - this.structs[ shaderStage ].push( node ); +const GPUAddressMode = { + ClampToEdge: 'clamp-to-edge', + Repeat: 'repeat', + MirrorRepeat: 'mirror-repeat' +}; - nodeData.structType = node; +const GPUFilterMode = { + Linear: 'linear', + Nearest: 'nearest' +}; - } +const GPUBlendFactor = { + Zero: 'zero', + One: 'one', + Src: 'src', + OneMinusSrc: 'one-minus-src', + SrcAlpha: 'src-alpha', + OneMinusSrcAlpha: 'one-minus-src-alpha', + Dst: 'dst', + OneMinusDstColor: 'one-minus-dst', + DstAlpha: 'dst-alpha', + OneMinusDstAlpha: 'one-minus-dst-alpha', + SrcAlphaSaturated: 'src-alpha-saturated', + Constant: 'constant', + OneMinusConstant: 'one-minus-constant' +}; - return node; +const GPUBlendOperation = { + Add: 'add', + Subtract: 'subtract', + ReverseSubtract: 'reverse-subtract', + Min: 'min', + Max: 'max' +}; - } +const GPUColorWriteFlags = { + None: 0, + Red: 0x1, + Green: 0x2, + Blue: 0x4, + Alpha: 0x8, + All: 0xF +}; - getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) { +const GPUStencilOperation = { + Keep: 'keep', + Zero: 'zero', + Replace: 'replace', + Invert: 'invert', + IncrementClamp: 'increment-clamp', + DecrementClamp: 'decrement-clamp', + IncrementWrap: 'increment-wrap', + DecrementWrap: 'decrement-wrap' +}; - const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache ); +const GPUBufferBindingType = { + Uniform: 'uniform', + Storage: 'storage', + ReadOnlyStorage: 'read-only-storage' +}; - let nodeUniform = nodeData.uniform; +const GPUStorageTextureAccess = { + WriteOnly: 'write-only', + ReadOnly: 'read-only', + ReadWrite: 'read-write', +}; - if ( nodeUniform === undefined ) { +const GPUTextureSampleType = { + Float: 'float', + UnfilterableFloat: 'unfilterable-float', + Depth: 'depth', + SInt: 'sint', + UInt: 'uint' +}; - const index = this.uniforms.index ++; +const GPUTextureDimension = { + OneD: '1d', + TwoD: '2d', + ThreeD: '3d' +}; - nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node ); +const GPUTextureViewDimension = { + OneD: '1d', + TwoD: '2d', + TwoDArray: '2d-array', + Cube: 'cube', + CubeArray: 'cube-array', + ThreeD: '3d' +}; - this.uniforms[ shaderStage ].push( nodeUniform ); +const GPUTextureAspect = { + All: 'all', + StencilOnly: 'stencil-only', + DepthOnly: 'depth-only' +}; - nodeData.uniform = nodeUniform; +const GPUInputStepMode = { + Vertex: 'vertex', + Instance: 'instance' +}; - } +const GPUFeatureName = { + DepthClipControl: 'depth-clip-control', + Depth32FloatStencil8: 'depth32float-stencil8', + TextureCompressionBC: 'texture-compression-bc', + TextureCompressionETC2: 'texture-compression-etc2', + TextureCompressionASTC: 'texture-compression-astc', + TimestampQuery: 'timestamp-query', + IndirectFirstInstance: 'indirect-first-instance', + ShaderF16: 'shader-f16', + RG11B10UFloat: 'rg11b10ufloat-renderable', + BGRA8UNormStorage: 'bgra8unorm-storage', + Float32Filterable: 'float32-filterable', + ClipDistances: 'clip-distances', + DualSourceBlending: 'dual-source-blending', + Subgroups: 'subgroups' +}; - return nodeUniform; +class StorageBufferNode extends BufferNode { + + static get type() { + + return 'StorageBufferNode'; } - getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) { + constructor( value, bufferType, bufferCount = 0 ) { - const nodeData = this.getDataFromNode( node, shaderStage ); + super( value, bufferType, bufferCount ); - let nodeVar = nodeData.variable; + this.isStorageBufferNode = true; - if ( nodeVar === undefined ) { + this.access = GPUBufferBindingType.Storage; + this.isAtomic = false; - const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] ); + this.bufferObject = false; + this.bufferCount = bufferCount; - if ( name === null ) name = 'nodeVar' + vars.length; + this._attribute = null; + this._varying = null; - nodeVar = new NodeVar( name, type ); + this.global = true; - vars.push( nodeVar ); + if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) { - nodeData.variable = nodeVar; + // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer - } + if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true; + else value.isStorageBufferAttribute = true; - return nodeVar; + } } - getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) { - - const nodeData = this.getDataFromNode( node, 'any' ); + getHash( builder ) { - let nodeVarying = nodeData.varying; + if ( this.bufferCount === 0 ) { - if ( nodeVarying === undefined ) { + let bufferData = builder.globalCache.getData( this.value ); - const varyings = this.varyings; - const index = varyings.length; + if ( bufferData === undefined ) { - if ( name === null ) name = 'nodeVarying' + index; + bufferData = { + node: this + }; - nodeVarying = new NodeVarying( name, type ); + builder.globalCache.setData( this.value, bufferData ); - varyings.push( nodeVarying ); + } - nodeData.varying = nodeVarying; + return bufferData.node.uuid; } - return nodeVarying; + return this.uuid; } - getCodeFromNode( node, type, shaderStage = this.shaderStage ) { + getInputType( /*builder*/ ) { - const nodeData = this.getDataFromNode( node ); + return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer'; - let nodeCode = nodeData.code; + } - if ( nodeCode === undefined ) { + element( indexNode ) { - const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] ); - const index = codes.length; + return storageElement( this, indexNode ); - nodeCode = new NodeCode( 'nodeCode' + index, type ); + } - codes.push( nodeCode ); + setBufferObject( value ) { - nodeData.code = nodeCode; + this.bufferObject = value; - } + return this; - return nodeCode; + } + + setAccess( value ) { + + this.access = value; + + return this; } - addFlowCodeHierarchy( node, nodeBlock ) { + toReadOnly() { - const { flowCodes, flowCodeBlock } = this.getDataFromNode( node ); + return this.setAccess( GPUBufferBindingType.ReadOnlyStorage ); - let needsFlowCode = true; - let nodeBlockHierarchy = nodeBlock; + } - while ( nodeBlockHierarchy ) { + setAtomic( value ) { - if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) { + this.isAtomic = value; - needsFlowCode = false; - break; + return this; - } + } - nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock; + toAtomic() { - } + return this.setAtomic( true ); - if ( needsFlowCode ) { + } - for ( const flowCode of flowCodes ) { + getAttributeData() { - this.addLineFlowCode( flowCode ); + if ( this._attribute === null ) { - } + this._attribute = bufferAttribute( this.value ); + this._varying = varying( this._attribute ); } + return { + attribute: this._attribute, + varying: this._varying + }; + } - addLineFlowCodeBlock( node, code, nodeBlock ) { + getNodeType( builder ) { - const nodeData = this.getDataFromNode( node ); - const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] ); - const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() ); + if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) { - flowCodes.push( code ); - codeBlock.set( nodeBlock, true ); + return super.getNodeType( builder ); - } + } - addLineFlowCode( code, node = null ) { + const { attribute } = this.getAttributeData(); - if ( code === '' ) return this; + return attribute.getNodeType( builder ); - if ( node !== null && this.context.nodeBlock ) { + } - this.addLineFlowCodeBlock( node, code, this.context.nodeBlock ); + generate( builder ) { - } + if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) { - code = this.tab + code; + return super.generate( builder ); - if ( ! /;\s*$/.test( code ) ) { + } - code = code + ';\n'; + const { attribute, varying } = this.getAttributeData(); - } + const output = varying.build( builder ); - this.flow.code += code; + builder.registerTransform( output, attribute ); - return this; + return output; } - addFlowCode( code ) { +} - this.flow.code += code; +// Read-Write Storage +const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) ); +const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) ); - return this; +class StorageTextureNode extends TextureNode { - } + static get type() { - addFlowTab() { + return 'StorageTextureNode'; - this.tab += '\t'; + } - return this; + constructor( value, uvNode, storeNode = null ) { - } + super( value, uvNode ); - removeFlowTab() { + this.storeNode = storeNode; - this.tab = this.tab.slice( 0, - 1 ); + this.isStorageTextureNode = true; - return this; + this.access = GPUStorageTextureAccess.WriteOnly; } - getFlowData( node/*, shaderStage*/ ) { + getInputType( /*builder*/ ) { - return this.flowsData.get( node ); + return 'storageTexture'; } - flowNode( node ) { + setup( builder ) { - const output = node.getNodeType( this ); + super.setup( builder ); - const flowData = this.flowChildNode( node, output ); + const properties = builder.getNodeProperties( this ); + properties.storeNode = this.storeNode; - this.flowsData.set( node, flowData ); + } - return flowData; + setAccess( value ) { + + this.access = value; + return this; } - buildFunctionNode( shaderNode ) { + generate( builder, output ) { - const fn = new FunctionNode(); + let snippet; - const previous = this.currentFunctionNode; + if ( this.storeNode !== null ) { - this.currentFunctionNode = fn; + snippet = this.generateStore( builder ); - fn.code = this.buildFunctionCode( shaderNode ); + } else { - this.currentFunctionNode = previous; + snippet = super.generate( builder, output ); - return fn; + } + + return snippet; } - flowShaderNode( shaderNode ) { + toReadOnly() { - const layout = shaderNode.layout; + return this.setAccess( GPUStorageTextureAccess.ReadOnly ); - const inputs = { - [ Symbol.iterator ]() { + } - let index = 0; - const values = Object.values( this ); - return { - next: () => ( { - value: values[ index ], - done: index ++ >= values.length - } ) - }; - - } - }; + toWriteOnly() { - for ( const input of layout.inputs ) { + return this.setAccess( GPUStorageTextureAccess.WriteOnly ); - inputs[ input.name ] = new ParameterNode( input.type, input.name ); + } - } + generateStore( builder ) { - // + const properties = builder.getNodeProperties( this ); - shaderNode.layout = null; + const { uvNode, storeNode } = properties; - const callNode = shaderNode.call( inputs ); - const flowData = this.flowStagesNode( callNode, layout.type ); + const textureProperty = super.generate( builder, 'property' ); + const uvSnippet = uvNode.build( builder, 'uvec2' ); + const storeSnippet = storeNode.build( builder, 'vec4' ); - shaderNode.layout = layout; + const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet ); - return flowData; + builder.addLineFlowCode( snippet, this ); } - flowStagesNode( node, output = null ) { - - const previousFlow = this.flow; - const previousVars = this.vars; - const previousCache = this.cache; - const previousBuildStage = this.buildStage; - const previousStack = this.stack; - - const flow = { - code: '' - }; - - this.flow = flow; - this.vars = {}; - this.cache = new NodeCache(); - this.stack = stack(); - - for ( const buildStage of defaultBuildStages ) { - - this.setBuildStage( buildStage ); +} - flow.result = node.build( this, output ); +const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ); - } +const textureStore = ( value, uvNode, storeNode ) => { - flow.vars = this.getVars( this.shaderStage ); + const node = storageTexture( value, uvNode, storeNode ); - this.flow = previousFlow; - this.vars = previousVars; - this.cache = previousCache; - this.stack = previousStack; + if ( storeNode !== null ) node.append(); - this.setBuildStage( previousBuildStage ); + return node; - return flow; +}; - } +class UserDataNode extends ReferenceNode { - getFunctionOperator() { + static get type() { - return null; + return 'UserDataNode'; } - flowChildNode( node, output = null ) { + constructor( property, inputType, userData = null ) { - const previousFlow = this.flow; + super( property, inputType, userData ); - const flow = { - code: '' - }; + this.userData = userData; - this.flow = flow; + } - flow.result = node.build( this, output ); + updateReference( state ) { - this.flow = previousFlow; + this.reference = this.userData !== null ? this.userData : state.object.userData; - return flow; + return this.reference; } - flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) { - - const previousShaderStage = this.shaderStage; - - this.setShaderStage( shaderStage ); +} - const flowData = this.flowChildNode( node, output ); +const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) ); - if ( propertyName !== null ) { +const _objectData = new WeakMap(); - flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`; +class VelocityNode extends TempNode { - } + static get type() { - this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code; + return 'VelocityNode'; - this.setShaderStage( previousShaderStage ); + } - return flowData; + constructor() { - } + super( 'vec2' ); - getAttributesArray() { + this.updateType = NodeUpdateType.OBJECT; + this.updateAfterType = NodeUpdateType.OBJECT; - return this.attributes.concat( this.bufferAttributes ); + this.previousModelWorldMatrix = uniform( new Matrix4() ); + this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup ); + this.previousCameraViewMatrix = uniform( new Matrix4() ); } - getAttributes( /*shaderStage*/ ) { + update( { frameId, camera, object } ) { - console.warn( 'Abstract function.' ); + const previousModelMatrix = getPreviousMatrix( object ); - } + this.previousModelWorldMatrix.value.copy( previousModelMatrix ); - getVaryings( /*shaderStage*/ ) { + // - console.warn( 'Abstract function.' ); + const cameraData = getData( camera ); - } + if ( cameraData.frameId !== frameId ) { - getVar( type, name ) { + cameraData.frameId = frameId; - return `${ this.getType( type ) } ${ name }`; + if ( cameraData.previousProjectionMatrix === undefined ) { - } + cameraData.previousProjectionMatrix = new Matrix4(); + cameraData.previousCameraViewMatrix = new Matrix4(); - getVars( shaderStage ) { + cameraData.currentProjectionMatrix = new Matrix4(); + cameraData.currentCameraViewMatrix = new Matrix4(); - let snippet = ''; + cameraData.previousProjectionMatrix.copy( camera.projectionMatrix ); + cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse ); - const vars = this.vars[ shaderStage ]; + } else { - if ( vars !== undefined ) { + cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix ); + cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix ); - for ( const variable of vars ) { + } - snippet += `${ this.getVar( variable.type, variable.name ) }; `; + cameraData.currentProjectionMatrix.copy( camera.projectionMatrix ); + cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse ); - } + this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix ); + this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix ); } - return snippet; - } - getUniforms( /*shaderStage*/ ) { + updateAfter( { object } ) { - console.warn( 'Abstract function.' ); + getPreviousMatrix( object ).copy( object.matrixWorld ); } - getCodes( shaderStage ) { + setup( /*builder*/ ) { - const codes = this.codes[ shaderStage ]; + const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix ); - let code = ''; + const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal ); + const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious ); - if ( codes !== undefined ) { + const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w ); + const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w ); - for ( const nodeCode of codes ) { + const velocity = sub( ndcPositionCurrent, ndcPositionPrevious ); - code += nodeCode.code + '\n'; + return velocity; - } + } - } +} - return code; +function getData( object ) { - } + let objectData = _objectData.get( object ); - getHash() { + if ( objectData === undefined ) { - return this.vertexShader + this.fragmentShader + this.computeShader; + objectData = {}; + _objectData.set( object, objectData ); } - setShaderStage( shaderStage ) { - - this.shaderStage = shaderStage; + return objectData; - } +} - getShaderStage() { +function getPreviousMatrix( object, index = 0 ) { - return this.shaderStage; + const objectData = getData( object ); - } + let matrix = objectData[ index ]; - setBuildStage( buildStage ) { + if ( matrix === undefined ) { - this.buildStage = buildStage; + objectData[ index ] = matrix = new Matrix4(); } - getBuildStage() { + return matrix; - return this.buildStage; +} - } +const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode ); - buildCode() { +const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { - console.warn( 'Abstract function.' ); + return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus(); - } +} ).setLayout( { + name: 'burnBlend', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] +} ); - build() { +const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { - const { object, material, renderer } = this; + return min$1( base.div( blend.oneMinus() ), 1.0 ); - if ( material !== null ) { +} ).setLayout( { + name: 'dodgeBlend', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] +} ); - let nodeMaterial = renderer.nodes.library.fromMaterial( material ); +const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { - if ( nodeMaterial === null ) { + return base.oneMinus().mul( blend.oneMinus() ).oneMinus(); - console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` ); +} ).setLayout( { + name: 'screenBlend', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] +} ); - nodeMaterial = new NodeMaterial(); +const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { - } + return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) ); - nodeMaterial.build( this ); +} ).setLayout( { + name: 'overlayBlend', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] +} ); - } else { +const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => { - this.addFlow( 'compute', object ); + return luminance( color.rgb ); - } +} ); - // setup() -> stage 1: create possible new nodes and returns an output reference node - // analyze() -> stage 2: analyze nodes to possible optimization and validation - // generate() -> stage 3: generate shader +const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { - for ( const buildStage of defaultBuildStages ) { + return adjustment.mix( luminance( color.rgb ), color.rgb ); - this.setBuildStage( buildStage ); +} ); - if ( this.context.vertex && this.context.vertex.isNode ) { +const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { - this.flowNodeFromShaderStage( 'vertex', this.context.vertex ); + const average = add( color.r, color.g, color.b ).div( 3.0 ); - } + const mx = color.r.max( color.g.max( color.b ) ); + const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 ); - for ( const shaderStage of shaderStages ) { + return mix( color.rgb, mx, amt ); - this.setShaderStage( shaderStage ); +} ); - const flowNodes = this.flowNodes[ shaderStage ]; +const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { - for ( const node of flowNodes ) { + const k = vec3( 0.57735, 0.57735, 0.57735 ); - if ( buildStage === 'generate' ) { + const cosAngle = adjustment.cos(); - this.flowNode( node ); + return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) ); - } else { +} ); - node.build( this ); +const luminance = ( + color, + luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) ) +) => dot( color, luminanceCoefficients ); - } +const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) ); - } +/** + * Color Decision List (CDL) v1.2 + * + * Compact representation of color grading information, defined by slope, offset, power, and + * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc, + * or AgX Log), and will return output in the same space. Output may require clamping >=0. + * + * @param {vec4} color Input (-Infinity < input < +Infinity) + * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity) + * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1) + * @param {number | vec3} power Power (0 < power < +Infinity) + * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4) + * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709 + * @return Output, -Infinity < output < +Infinity + * + * References: + * - ASC CDL v1.2 + * - https://blender.stackexchange.com/a/55239/43930 + * - https://docs.acescentral.com/specifications/acescc/ + */ +const cdl = /*@__PURE__*/ Fn( ( [ + color, + slope = vec3( 1 ), + offset = vec3( 0 ), + power = vec3( 1 ), + saturation = float( 1 ), + // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients. + luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) ) +] ) => { - } + // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the + // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support + // values outside [0, 1], requiring a workaround for negative values in the power expression. - } + const luma = color.rgb.dot( vec3( luminanceCoefficients ) ); - this.setBuildStage( null ); - this.setShaderStage( null ); + const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar(); + const pv = v.pow( power ).toVar(); - // stage 4: build code for a specific output + If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line + If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line + If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line - this.buildCode(); - this.buildUpdateNodes(); + v.assign( luma.add( v.sub( luma ).mul( saturation ) ) ); - return this; + return vec4( v.rgb, color.a ); - } +} ); - getNodeUniform( uniformNode, type ) { +class PosterizeNode extends TempNode { - if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode ); - if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode ); - if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode ); - if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode ); - if ( type === 'color' ) return new ColorNodeUniform( uniformNode ); - if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode ); - if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode ); + static get type() { - throw new Error( `Uniform "${type}" not declared.` ); + return 'PosterizeNode'; } - createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168 - - throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` ); + constructor( sourceNode, stepsNode ) { - } + super(); - format( snippet, fromType, toType ) { + this.sourceNode = sourceNode; + this.stepsNode = stepsNode; - fromType = this.getVectorType( fromType ); - toType = this.getVectorType( toType ); + } - if ( fromType === toType || toType === null || this.isReference( toType ) ) { + setup() { - return snippet; + const { sourceNode, stepsNode } = this; - } + return sourceNode.mul( stepsNode ).floor().div( stepsNode ); - const fromTypeLength = this.getTypeLength( fromType ); - const toTypeLength = this.getTypeLength( toType ); + } - if ( fromTypeLength === 16 && toTypeLength === 9 ) { +} - return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`; +const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ); - } +let _sharedFramebuffer = null; - if ( fromTypeLength === 9 && toTypeLength === 4 ) { +class ViewportSharedTextureNode extends ViewportTextureNode { - return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`; + static get type() { - } + return 'ViewportSharedTextureNode'; + } - if ( fromTypeLength > 4 ) { // fromType is matrix-like + constructor( uvNode = screenUV, levelNode = null ) { - // @TODO: ignore for now + if ( _sharedFramebuffer === null ) { - return snippet; + _sharedFramebuffer = new FramebufferTexture(); } - if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown - - // @TODO: ignore for now + super( uvNode, levelNode, _sharedFramebuffer ); - return snippet; + } - } + updateReference() { - if ( fromTypeLength === toTypeLength ) { + return this; - return `${ this.getType( toType ) }( ${ snippet } )`; + } - } +} - if ( fromTypeLength > toTypeLength ) { +const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ); - return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType ); +const _size = /*@__PURE__*/ new Vector2(); - } +class PassTextureNode extends TextureNode { - if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like + static get type() { - return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`; + return 'PassTextureNode'; - } + } - if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like + constructor( passNode, texture ) { - return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`; + super( texture ); - } + this.passNode = passNode; - if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like + this.setUpdateMatrix( false ); - // convert a number value to vector type, e.g: - // vec3( 1u ) -> vec3( float( 1u ) ) + } - snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`; + setup( builder ) { - } + if ( builder.object.isQuadMesh ) this.passNode.build( builder ); - return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like + return super.setup( builder ); } - getSignature() { + clone() { - return `// Three.js r${ REVISION } - Node System\n`; + return new this.constructor( this.passNode, this.value ); } } -class NodeFrame { +class PassMultipleTextureNode extends PassTextureNode { - constructor() { + static get type() { - this.time = 0; - this.deltaTime = 0; + return 'PassMultipleTextureNode'; - this.frameId = 0; - this.renderId = 0; + } - this.startTime = null; + constructor( passNode, textureName, previousTexture = false ) { - this.updateMap = new WeakMap(); - this.updateBeforeMap = new WeakMap(); - this.updateAfterMap = new WeakMap(); + super( passNode, null ); - this.renderer = null; - this.material = null; - this.camera = null; - this.object = null; - this.scene = null; + this.textureName = textureName; + this.previousTexture = previousTexture; } - _getMaps( referenceMap, nodeRef ) { - - let maps = referenceMap.get( nodeRef ); + updateTexture() { - if ( maps === undefined ) { + this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName ); - maps = { - renderMap: new WeakMap(), - frameMap: new WeakMap() - }; + } - referenceMap.set( nodeRef, maps ); + setup( builder ) { - } + this.updateTexture(); - return maps; + return super.setup( builder ); } - updateBeforeNode( node ) { + clone() { - const updateType = node.getUpdateBeforeType(); - const reference = node.updateReference( this ); + return new this.constructor( this.passNode, this.textureName, this.previousTexture ); - if ( updateType === NodeUpdateType.FRAME ) { + } - const { frameMap } = this._getMaps( this.updateBeforeMap, reference ); +} - if ( frameMap.get( reference ) !== this.frameId ) { +class PassNode extends TempNode { - if ( node.updateBefore( this ) !== false ) { + static get type() { - frameMap.set( reference, this.frameId ); + return 'PassNode'; - } + } - } + constructor( scope, scene, camera, options = {} ) { - } else if ( updateType === NodeUpdateType.RENDER ) { + super( 'vec4' ); - const { renderMap } = this._getMaps( this.updateBeforeMap, reference ); - - if ( renderMap.get( reference ) !== this.renderId ) { - - if ( node.updateBefore( this ) !== false ) { - - renderMap.set( reference, this.renderId ); - - } - - } - - } else if ( updateType === NodeUpdateType.OBJECT ) { - - node.updateBefore( this ); - - } - - } - - updateAfterNode( node ) { + this.scope = scope; + this.scene = scene; + this.camera = camera; + this.options = options; - const updateType = node.getUpdateAfterType(); - const reference = node.updateReference( this ); + this._pixelRatio = 1; + this._width = 1; + this._height = 1; - if ( updateType === NodeUpdateType.FRAME ) { + const depthTexture = new DepthTexture(); + depthTexture.isRenderTargetTexture = true; + //depthTexture.type = FloatType; + depthTexture.name = 'depth'; - const { frameMap } = this._getMaps( this.updateAfterMap, reference ); + const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } ); + renderTarget.texture.name = 'output'; + renderTarget.depthTexture = depthTexture; - if ( frameMap.get( reference ) !== this.frameId ) { + this.renderTarget = renderTarget; - if ( node.updateAfter( this ) !== false ) { + this.updateBeforeType = NodeUpdateType.FRAME; - frameMap.set( reference, this.frameId ); + this._textures = { + output: renderTarget.texture, + depth: depthTexture + }; - } + this._textureNodes = {}; + this._linearDepthNodes = {}; + this._viewZNodes = {}; - } + this._previousTextures = {}; + this._previousTextureNodes = {}; - } else if ( updateType === NodeUpdateType.RENDER ) { + this._cameraNear = uniform( 0 ); + this._cameraFar = uniform( 0 ); - const { renderMap } = this._getMaps( this.updateAfterMap, reference ); + this._mrt = null; - if ( renderMap.get( reference ) !== this.renderId ) { + this.isPassNode = true; - if ( node.updateAfter( this ) !== false ) { + } - renderMap.set( reference, this.renderId ); + setMRT( mrt ) { - } + this._mrt = mrt; - } + return this; - } else if ( updateType === NodeUpdateType.OBJECT ) { + } - node.updateAfter( this ); + getMRT() { - } + return this._mrt; } - updateNode( node ) { + isGlobal() { - const updateType = node.getUpdateType(); - const reference = node.updateReference( this ); + return true; - if ( updateType === NodeUpdateType.FRAME ) { + } - const { frameMap } = this._getMaps( this.updateMap, reference ); + getTexture( name ) { - if ( frameMap.get( reference ) !== this.frameId ) { + let texture = this._textures[ name ]; - if ( node.update( this ) !== false ) { + if ( texture === undefined ) { - frameMap.set( reference, this.frameId ); + const refTexture = this.renderTarget.texture; - } + texture = refTexture.clone(); + texture.isRenderTargetTexture = true; + texture.name = name; - } + this._textures[ name ] = texture; - } else if ( updateType === NodeUpdateType.RENDER ) { + this.renderTarget.textures.push( texture ); - const { renderMap } = this._getMaps( this.updateMap, reference ); + } - if ( renderMap.get( reference ) !== this.renderId ) { + return texture; - if ( node.update( this ) !== false ) { + } - renderMap.set( reference, this.renderId ); + getPreviousTexture( name ) { - } + let texture = this._previousTextures[ name ]; - } + if ( texture === undefined ) { - } else if ( updateType === NodeUpdateType.OBJECT ) { + texture = this.getTexture( name ).clone(); + texture.isRenderTargetTexture = true; - node.update( this ); + this._previousTextures[ name ] = texture; } - } - - update() { - - this.frameId ++; - - if ( this.lastTime === undefined ) this.lastTime = performance.now(); - - this.deltaTime = ( performance.now() - this.lastTime ) / 1000; - - this.lastTime = performance.now(); - - this.time += this.deltaTime; + return texture; } -} - -class NodeFunctionInput { - - constructor( type, name, count = null, qualifier = '', isConst = false ) { + toggleTexture( name ) { - this.type = type; - this.name = name; - this.count = count; - this.qualifier = qualifier; - this.isConst = isConst; + const prevTexture = this._previousTextures[ name ]; - } + if ( prevTexture !== undefined ) { -} + const texture = this._textures[ name ]; -NodeFunctionInput.isNodeFunctionInput = true; + const index = this.renderTarget.textures.indexOf( texture ); + this.renderTarget.textures[ index ] = prevTexture; -class StructTypeNode extends Node { + this._textures[ name ] = prevTexture; + this._previousTextures[ name ] = texture; - static get type() { + this._textureNodes[ name ].updateTexture(); + this._previousTextureNodes[ name ].updateTexture(); - return 'StructTypeNode'; + } } - constructor( types ) { + getTextureNode( name = 'output' ) { - super(); + let textureNode = this._textureNodes[ name ]; - this.types = types; - this.isStructTypeNode = true; + if ( textureNode === undefined ) { - } + this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) ); + this._textureNodes[ name ].updateTexture(); - getMemberTypes() { + } - return this.types; + return textureNode; } -} - -class OutputStructNode extends Node { - - static get type() { + getPreviousTextureNode( name = 'output' ) { - return 'OutputStructNode'; + let textureNode = this._previousTextureNodes[ name ]; - } + if ( textureNode === undefined ) { - constructor( ...members ) { + if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name ); - super(); + this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) ); + this._previousTextureNodes[ name ].updateTexture(); - this.members = members; + } - this.isOutputStructNode = true; + return textureNode; } - setup( builder ) { + getViewZNode( name = 'depth' ) { - super.setup( builder ); + let viewZNode = this._viewZNodes[ name ]; - const members = this.members; - const types = []; + if ( viewZNode === undefined ) { - for ( let i = 0; i < members.length; i ++ ) { + const cameraNear = this._cameraNear; + const cameraFar = this._cameraFar; - types.push( members[ i ].getNodeType( builder ) ); + this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar ); } - this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name; + return viewZNode; } - generate( builder, output ) { + getLinearDepthNode( name = 'depth' ) { - const propertyName = builder.getOutputStructName(); - const members = this.members; + let linearDepthNode = this._linearDepthNodes[ name ]; - const structPrefix = propertyName !== '' ? propertyName + '.' : ''; + if ( linearDepthNode === undefined ) { - for ( let i = 0; i < members.length; i ++ ) { + const cameraNear = this._cameraNear; + const cameraFar = this._cameraFar; + const viewZNode = this.getViewZNode( name ); - const snippet = members[ i ].build( builder, output ); + // TODO: just if ( builder.camera.isPerspectiveCamera ) - builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this ); + this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar ); } - return propertyName; + return linearDepthNode; } -} + setup( { renderer } ) { -const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode ); + this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples; -function getTextureIndex( textures, name ) { + // Disable MSAA for WebGL backend for now + if ( renderer.backend.isWebGLBackend === true ) { - for ( let i = 0; i < textures.length; i ++ ) { + this.renderTarget.samples = 0; - if ( textures[ i ].name === name ) { + } - return i; + this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1; - } + return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode(); } - return - 1; + updateBefore( frame ) { -} + const { renderer } = frame; + const { scene, camera } = this; -class MRTNode extends OutputStructNode { + this._pixelRatio = renderer.getPixelRatio(); - static get type() { + const size = renderer.getSize( _size ); - return 'MRTNode'; + this.setSize( size.width, size.height ); - } + const currentRenderTarget = renderer.getRenderTarget(); + const currentMRT = renderer.getMRT(); - constructor( outputNodes ) { + this._cameraNear.value = camera.near; + this._cameraFar.value = camera.far; - super(); + for ( const name in this._previousTextures ) { - this.outputNodes = outputNodes; + this.toggleTexture( name ); - this.isMRTNode = true; + } - } + renderer.setRenderTarget( this.renderTarget ); + renderer.setMRT( this._mrt ); - has( name ) { + renderer.render( scene, camera ); - return this.outputNodes[ name ] !== undefined; + renderer.setRenderTarget( currentRenderTarget ); + renderer.setMRT( currentMRT ); } - get( name ) { - - return this.outputNodes[ name ]; - - } + setSize( width, height ) { - merge( mrtNode ) { + this._width = width; + this._height = height; - const outputs = { ...this.outputNodes, ...mrtNode.outputNodes }; + const effectiveWidth = this._width * this._pixelRatio; + const effectiveHeight = this._height * this._pixelRatio; - return mrt( outputs ); + this.renderTarget.setSize( effectiveWidth, effectiveHeight ); } - setup( builder ) { - - const outputNodes = this.outputNodes; - const mrt = builder.renderer.getRenderTarget(); - - const members = []; - - const textures = mrt.textures; - - for ( const name in outputNodes ) { + setPixelRatio( pixelRatio ) { - const index = getTextureIndex( textures, name ); + this._pixelRatio = pixelRatio; - members[ index ] = vec4( outputNodes[ name ] ); + this.setSize( this._width, this._height ); - } + } - this.members = members; + dispose() { - return super.setup( builder ); + this.renderTarget.dispose(); } + } -const mrt = /*@__PURE__*/ nodeProxy( MRTNode ); +PassNode.COLOR = 'color'; +PassNode.DEPTH = 'depth'; -class FunctionOverloadingNode extends Node { +const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) ); +const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) ); +const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); + +class ToonOutlinePassNode extends PassNode { static get type() { - return 'FunctionOverloadingNode'; + return 'ToonOutlinePassNode'; } - constructor( functionNodes = [], ...parametersNodes ) { - - super(); + constructor( scene, camera, colorNode, thicknessNode, alphaNode ) { - this.functionNodes = functionNodes; - this.parametersNodes = parametersNodes; + super( PassNode.COLOR, scene, camera ); - this._candidateFnCall = null; + this.colorNode = colorNode; + this.thicknessNode = thicknessNode; + this.alphaNode = alphaNode; - this.global = true; + this._materialCache = new WeakMap(); } - getNodeType() { + updateBefore( frame ) { - return this.functionNodes[ 0 ].shaderNode.layout.type; + const { renderer } = frame; - } + const currentRenderObjectFunction = renderer.getRenderObjectFunction(); - setup( builder ) { + renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => { - const params = this.parametersNodes; + // only render outline for supported materials - let candidateFnCall = this._candidateFnCall; + if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) { - if ( candidateFnCall === null ) { + if ( material.wireframe === false ) { - let candidateFn = null; - let candidateScore = - 1; + const outlineMaterial = this._getOutlineMaterial( material ); + renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode ); - for ( const functionNode of this.functionNodes ) { + } - const shaderNode = functionNode.shaderNode; - const layout = shaderNode.layout; + } - if ( layout === null ) { + // default - throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' ); + renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode ); - } + } ); - const inputs = layout.inputs; + super.updateBefore( frame ); - if ( params.length === inputs.length ) { + renderer.setRenderObjectFunction( currentRenderObjectFunction ); - let score = 0; + } - for ( let i = 0; i < params.length; i ++ ) { + _createMaterial() { - const param = params[ i ]; - const input = inputs[ i ]; + const material = new NodeMaterial(); + material.isMeshToonOutlineMaterial = true; + material.name = 'Toon_Outline'; + material.side = BackSide; - if ( param.getNodeType( builder ) === input.type ) { + // vertex node - score ++; + const outlineNormal = normalLocal.negate(); + const mvp = cameraProjectionMatrix.mul( modelViewMatrix ); - } else { + const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex + const pos = mvp.mul( vec4( positionLocal, 1.0 ) ); + const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) ); + const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative - score = 0; + material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) ); - } + // color node - } + material.colorNode = vec4( this.colorNode, this.alphaNode ); - if ( score > candidateScore ) { + return material; - candidateFn = functionNode; - candidateScore = score; + } - } + _getOutlineMaterial( originalMaterial ) { - } + let outlineMaterial = this._materialCache.get( originalMaterial ); - } + if ( outlineMaterial === undefined ) { - this._candidateFnCall = candidateFnCall = candidateFn( ...params ); + outlineMaterial = this._createMaterial(); + + this._materialCache.set( originalMaterial, outlineMaterial ); } - return candidateFnCall; + return outlineMaterial; } } -const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode ); +const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) ); -const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params ); +const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => { -class SpriteSheetUVNode extends Node { + const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 ); + const b = color.mul( 0.0773993808 ); + const factor = color.lessThanEqual( 0.04045 ); - static get type() { + const rgbResult = mix( a, b, factor ); - return 'SpriteSheetUVNode'; + return rgbResult; - } +} ).setLayout( { + name: 'sRGBToLinearSRGB', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' } + ] +} ); - constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { +const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => { - super( 'vec2' ); + const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 ); + const b = color.mul( 12.92 ); + const factor = color.lessThanEqual( 0.0031308 ); - this.countNode = countNode; - this.uvNode = uvNode; - this.frameNode = frameNode; + const rgbResult = mix( a, b, factor ); - } + return rgbResult; - setup() { +} ).setLayout( { + name: 'linearSRGBTosRGB', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' } + ] +} ); - const { frameNode, uvNode, countNode } = this; +// exposure only - const { width, height } = countNode; +const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - const frameNum = frameNode.mod( width.mul( height ) ).floor(); + return color.mul( exposure ).clamp(); - const column = frameNum.mod( width ); - const row = height.sub( frameNum.add( 1 ).div( width ).ceil() ); +} ).setLayout( { + name: 'linearToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); - const scale = countNode.reciprocal(); - const uvFrameOffset = vec2( column, row ); +// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf - return uvNode.add( uvFrameOffset ).mul( scale ); +const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - } + color = color.mul( exposure ); -} + return color.div( color.add( 1.0 ) ).clamp(); -const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ); +} ).setLayout( { + name: 'reinhardToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); -class StorageArrayElementNode extends ArrayElementNode { +// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/ - static get type() { +const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - return 'StorageArrayElementNode'; + // filmic operator by Jim Hejl and Richard Burgess-Dawson + color = color.mul( exposure ); + color = color.sub( 0.004 ).max( 0.0 ); - } + const a = color.mul( color.mul( 6.2 ).add( 0.5 ) ); + const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 ); - constructor( storageBufferNode, indexNode ) { + return a.div( b ).pow( 2.2 ); - super( storageBufferNode, indexNode ); +} ).setLayout( { + name: 'cineonToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); - this.isStorageArrayElementNode = true; +// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs - } +const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => { - set storageBufferNode( value ) { + const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 ); + const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 ); - this.node = value; + return a.div( b ); - } +} ); - get storageBufferNode() { +// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs - return this.node; +const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - } + // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT + const ACESInputMat = mat3( + 0.59719, 0.35458, 0.04823, + 0.07600, 0.90834, 0.01566, + 0.02840, 0.13383, 0.83777 + ); - setup( builder ) { + // ODT_SAT => XYZ => D60_2_D65 => sRGB + const ACESOutputMat = mat3( + 1.60475, - 0.53108, - 0.07367, + - 0.10208, 1.10813, - 0.00605, + - 0.00327, - 0.07276, 1.07602 + ); - if ( builder.isAvailable( 'storageBuffer' ) === false ) { + color = color.mul( exposure ).div( 0.6 ); - if ( this.node.bufferObject === true ) { + color = ACESInputMat.mul( color ); - builder.setupPBO( this.node ); + // Apply RRT and ODT + color = RRTAndODTFit( color ); - } + color = ACESOutputMat.mul( color ); - } + // Clamp to [0, 1] + return color.clamp(); - return super.setup( builder ); +} ).setLayout( { + name: 'acesFilmicToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); - } +const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); +const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); - generate( builder, output ) { +const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { - let snippet; + const x = vec3( x_immutable ).toVar(); + const x2 = vec3( x.mul( x ) ).toVar(); + const x4 = vec3( x2.mul( x2 ) ).toVar(); - const isAssignContext = builder.context.assign; + return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) ); - // +} ); - if ( builder.isAvailable( 'storageBuffer' ) === false ) { +const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - if ( this.node.bufferObject === true && isAssignContext !== true ) { + const colortone = vec3( color ).toVar(); + const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); + const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); + const AgxMinEv = float( - 12.47393 ); + const AgxMaxEv = float( 4.026069 ); + colortone.mulAssign( exposure ); + colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) ); + colortone.assign( AgXInsetMatrix.mul( colortone ) ); + colortone.assign( max$1( colortone, 1e-10 ) ); + colortone.assign( log2( colortone ) ); + colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + colortone.assign( agxDefaultContrastApprox( colortone ) ); + colortone.assign( AgXOutsetMatrix.mul( colortone ) ); + colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) ); + colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); - snippet = builder.generatePBO( this ); + return colortone; - } else { +} ).setLayout( { + name: 'agxToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); - snippet = this.node.build( builder ); +// https://modelviewer.dev/examples/tone-mapping - } +const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { - } else { + const StartCompression = float( 0.8 - 0.04 ); + const Desaturation = float( 0.15 ); - snippet = super.generate( builder ); + color = color.mul( exposure ); - } + const x = min$1( color.r, min$1( color.g, color.b ) ); + const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 ); - if ( isAssignContext !== true ) { + color.subAssign( offset ); - const type = this.getNodeType( builder ); + const peak = max$1( color.r, max$1( color.g, color.b ) ); - snippet = builder.format( snippet, type, output ); + If( peak.lessThan( StartCompression ), () => { - } + return color; - return snippet; + } ); - } + const d = sub( 1, StartCompression ); + const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) ); + color.mulAssign( newPeak.div( peak ) ); + const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) ); -} + return mix( color, vec3( newPeak ), g ); -const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ); +} ).setLayout( { + name: 'neutralToneMapping', + type: 'vec3', + inputs: [ + { name: 'color', type: 'vec3' }, + { name: 'exposure', type: 'float' } + ] +} ); -class TriplanarTexturesNode extends Node { +class CodeNode extends Node { static get type() { - return 'TriplanarTexturesNode'; + return 'CodeNode'; } - constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { + constructor( code = '', includes = [], language = '' ) { - super( 'vec4' ); + super( 'code' ); - this.textureXNode = textureXNode; - this.textureYNode = textureYNode; - this.textureZNode = textureZNode; + this.isCodeNode = true; - this.scaleNode = scaleNode; + this.code = code; + this.language = language; - this.positionNode = positionNode; - this.normalNode = normalNode; + this.includes = includes; } - setup() { + isGlobal() { - const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this; + return true; - // Ref: https://github.com/keijiro/StandardTriplanar + } - // Blending factor of triplanar mapping - let bf = normalNode.abs().normalize(); - bf = bf.div( bf.dot( vec3( 1.0 ) ) ); + setIncludes( includes ) { - // Triplanar mapping - const tx = positionNode.yz.mul( scaleNode ); - const ty = positionNode.zx.mul( scaleNode ); - const tz = positionNode.xy.mul( scaleNode ); + this.includes = includes; - // Base color - const textureX = textureXNode.value; - const textureY = textureYNode !== null ? textureYNode.value : textureX; - const textureZ = textureZNode !== null ? textureZNode.value : textureX; + return this; - const cx = texture( textureX, tx ).mul( bf.x ); - const cy = texture( textureY, ty ).mul( bf.y ); - const cz = texture( textureZ, tz ).mul( bf.z ); + } - return add( cx, cy, cz ); + getIncludes( /*builder*/ ) { + + return this.includes; } -} + generate( builder ) { -const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ); -const triplanarTexture = ( ...params ) => triplanarTextures( ...params ); + const includes = this.getIncludes( builder ); -const _reflectorPlane = new Plane(); -const _normal = new Vector3(); -const _reflectorWorldPosition = new Vector3(); -const _cameraWorldPosition = new Vector3(); -const _rotationMatrix = new Matrix4(); -const _lookAtPosition = new Vector3( 0, 0, - 1 ); -const clipPlane = new Vector4(); + for ( const include of includes ) { -const _view = new Vector3(); -const _target = new Vector3(); -const _q = new Vector4(); + include.build( builder ); -const _size$3 = new Vector2(); + } -const _defaultRT = new RenderTarget(); -const _defaultUV = screenUV.flipX(); + const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) ); + nodeCode.code = this.code; -_defaultRT.depthTexture = new DepthTexture( 1, 1 ); + return nodeCode.code; -let _inReflector = false; + } -class ReflectorNode extends TextureNode { + serialize( data ) { - static get type() { + super.serialize( data ); - return 'ReflectorNode'; + data.code = this.code; + data.language = this.language; } - constructor( parameters = {} ) { - - super( parameters.defaultTexture || _defaultRT.texture, _defaultUV ); + deserialize( data ) { - this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters ); - this._depthNode = null; + super.deserialize( data ); - this.setUpdateMatrix( false ); + this.code = data.code; + this.language = data.language; } - get reflector() { +} - return this._reflectorBaseNode; +const code = /*@__PURE__*/ nodeProxy( CodeNode ); - } +const js = ( src, includes ) => code( src, includes, 'js' ); +const wgsl = ( src, includes ) => code( src, includes, 'wgsl' ); +const glsl = ( src, includes ) => code( src, includes, 'glsl' ); - get target() { +class FunctionNode extends CodeNode { - return this._reflectorBaseNode.target; + static get type() { + + return 'FunctionNode'; } - getDepthNode() { + constructor( code = '', includes = [], language = '' ) { - if ( this._depthNode === null ) { + super( code, includes, language ); - if ( this._reflectorBaseNode.depth !== true ) { + } - throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' ); + getNodeType( builder ) { - } + return this.getNodeFunction( builder ).type; - this._depthNode = nodeObject( new ReflectorNode( { - defaultTexture: _defaultRT.depthTexture, - reflector: this._reflectorBaseNode - } ) ); + } - } + getInputs( builder ) { - return this._depthNode; + return this.getNodeFunction( builder ).inputs; } - setup( builder ) { + getNodeFunction( builder ) { - // ignore if used in post-processing - if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder ); + const nodeData = builder.getDataFromNode( this ); - return super.setup( builder ); + let nodeFunction = nodeData.nodeFunction; - } + if ( nodeFunction === undefined ) { - clone() { + nodeFunction = builder.parser.parseFunction( this.code ); - const texture = new this.constructor( this.reflectorNode ); - texture._reflectorBaseNode = this._reflectorBaseNode; + nodeData.nodeFunction = nodeFunction; - return texture; + } + + return nodeFunction; } -} + generate( builder, output ) { + super.generate( builder ); -class ReflectorBaseNode extends Node { + const nodeFunction = this.getNodeFunction( builder ); - static get type() { + const name = nodeFunction.name; + const type = nodeFunction.type; - return 'ReflectorBaseNode'; + const nodeCode = builder.getCodeFromNode( this, type ); - } + if ( name !== '' ) { - constructor( textureNode, parameters = {} ) { + // use a custom property name - super(); + nodeCode.name = name; - const { - target = new Object3D(), - resolution = 1, - generateMipmaps = false, - bounces = true, - depth = false - } = parameters; + } - // + const propertyName = builder.getPropertyName( nodeCode ); - this.textureNode = textureNode; + const code = this.getNodeFunction( builder ).getCode( propertyName ); - this.target = target; - this.resolution = resolution; - this.generateMipmaps = generateMipmaps; - this.bounces = bounces; - this.depth = depth; + nodeCode.code = code + '\n'; - this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME; + if ( output === 'property' ) { - this.virtualCameras = new WeakMap(); - this.renderTargets = new WeakMap(); + return propertyName; - } + } else { - _updateResolution( renderTarget, renderer ) { + return builder.format( `${ propertyName }()`, type, output ); - const resolution = this.resolution; + } - renderer.getDrawingBufferSize( _size$3 ); + } - renderTarget.setSize( Math.round( _size$3.width * resolution ), Math.round( _size$3.height * resolution ) ); +} - } +const nativeFn = ( code, includes = [], language = '' ) => { - setup( builder ) { + for ( let i = 0; i < includes.length; i ++ ) { - this._updateResolution( _defaultRT, builder.renderer ); + const include = includes[ i ]; - return super.setup( builder ); + // TSL Function: glslFn, wgslFn - } + if ( typeof include === 'function' ) { - getVirtualCamera( camera ) { + includes[ i ] = include.functionNode; - let virtualCamera = this.virtualCameras.get( camera ); + } - if ( virtualCamera === undefined ) { + } - virtualCamera = camera.clone(); + const functionNode = nodeObject( new FunctionNode( code, includes, language ) ); - this.virtualCameras.set( camera, virtualCamera ); + const fn = ( ...params ) => functionNode.call( ...params ); + fn.functionNode = functionNode; - } + return fn; - return virtualCamera; +}; - } +const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' ); +const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' ); - getRenderTarget( camera ) { +class ScriptableValueNode extends Node { - let renderTarget = this.renderTargets.get( camera ); + static get type() { - if ( renderTarget === undefined ) { + return 'ScriptableValueNode'; - renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } ); + } - if ( this.generateMipmaps === true ) { + constructor( value = null ) { - renderTarget.texture.minFilter = LinearMipMapLinearFilter; - renderTarget.texture.generateMipmaps = true; + super(); - } + this._value = value; + this._cache = null; - if ( this.depth === true ) { + this.inputType = null; + this.outpuType = null; - renderTarget.depthTexture = new DepthTexture(); + this.events = new EventDispatcher(); - } + this.isScriptableValueNode = true; - this.renderTargets.set( camera, renderTarget ); + } - } + get isScriptableOutputNode() { - return renderTarget; + return this.outputType !== null; } - updateBefore( frame ) { + set value( val ) { - if ( this.bounces === false && _inReflector ) return; + if ( this._value === val ) return; - _inReflector = true; + if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) { - const { scene, camera, renderer, material } = frame; - const { target } = this; + URL.revokeObjectURL( this._cache ); - const virtualCamera = this.getVirtualCamera( camera ); - const renderTarget = this.getRenderTarget( virtualCamera ); + this._cache = null; - renderer.getDrawingBufferSize( _size$3 ); + } - this._updateResolution( renderTarget, renderer ); + this._value = val; - // + this.events.dispatchEvent( { type: 'change' } ); - _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld ); - _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); + this.refresh(); - _rotationMatrix.extractRotation( target.matrixWorld ); + } - _normal.set( 0, 0, 1 ); - _normal.applyMatrix4( _rotationMatrix ); + get value() { - _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition ); + return this._value; - // Avoid rendering when reflector is facing away + } - if ( _view.dot( _normal ) > 0 ) return; + refresh() { - _view.reflect( _normal ).negate(); - _view.add( _reflectorWorldPosition ); + this.events.dispatchEvent( { type: 'refresh' } ); - _rotationMatrix.extractRotation( camera.matrixWorld ); + } - _lookAtPosition.set( 0, 0, - 1 ); - _lookAtPosition.applyMatrix4( _rotationMatrix ); - _lookAtPosition.add( _cameraWorldPosition ); + getValue() { - _target.subVectors( _reflectorWorldPosition, _lookAtPosition ); - _target.reflect( _normal ).negate(); - _target.add( _reflectorWorldPosition ); + const value = this.value; - // + if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) { - virtualCamera.coordinateSystem = camera.coordinateSystem; - virtualCamera.position.copy( _view ); - virtualCamera.up.set( 0, 1, 0 ); - virtualCamera.up.applyMatrix4( _rotationMatrix ); - virtualCamera.up.reflect( _normal ); - virtualCamera.lookAt( _target ); + this._cache = URL.createObjectURL( new Blob( [ value.value ] ) ); - virtualCamera.near = camera.near; - virtualCamera.far = camera.far; + } else if ( value && value.value !== null && value.value !== undefined && ( + ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) || + ( this.inputType === 'Number' && typeof value.value === 'number' ) || + ( this.inputType === 'Vector2' && value.value.isVector2 ) || + ( this.inputType === 'Vector3' && value.value.isVector3 ) || + ( this.inputType === 'Vector4' && value.value.isVector4 ) || + ( this.inputType === 'Color' && value.value.isColor ) || + ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) || + ( this.inputType === 'Matrix4' && value.value.isMatrix4 ) + ) ) { - virtualCamera.updateMatrixWorld(); - virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); + return value.value; - // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html - // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf - _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition ); - _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); + } - clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant ); + return this._cache || value; - const projectionMatrix = virtualCamera.projectionMatrix; + } - _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; - _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; - _q.z = - 1.0; - _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; + getNodeType( builder ) { - // Calculate the scaled plane vector - clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) ); + return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float'; - const clipBias = 0; + } - // Replacing the third row of the projection matrix - projectionMatrix.elements[ 2 ] = clipPlane.x; - projectionMatrix.elements[ 6 ] = clipPlane.y; - projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias ); - projectionMatrix.elements[ 14 ] = clipPlane.w; + setup() { - // + return this.value && this.value.isNode ? this.value : float(); - this.textureNode.value = renderTarget.texture; + } - if ( this.depth === true ) { + serialize( data ) { - this.textureNode.getDepthNode().value = renderTarget.depthTexture; + super.serialize( data ); - } + if ( this.value !== null ) { - material.visible = false; + if ( this.inputType === 'ArrayBuffer' ) { - const currentRenderTarget = renderer.getRenderTarget(); - const currentMRT = renderer.getMRT(); + data.value = arrayBufferToBase64( this.value ); - renderer.setMRT( null ); - renderer.setRenderTarget( renderTarget ); + } else { - renderer.render( scene, virtualCamera ); + data.value = this.value ? this.value.toJSON( data.meta ).uuid : null; - renderer.setMRT( currentMRT ); - renderer.setRenderTarget( currentRenderTarget ); + } - material.visible = true; + } else { - _inReflector = false; + data.value = null; - } + } -} + data.inputType = this.inputType; + data.outputType = this.outputType; -const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) ); + } -// Helper for passes that need to fill the viewport with a single quad. + deserialize( data ) { -const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + super.deserialize( data ); -// https://github.com/mrdoob/three.js/pull/21358 + let value = null; -class QuadGeometry extends BufferGeometry { + if ( data.value !== null ) { - constructor( flipY = false ) { + if ( data.inputType === 'ArrayBuffer' ) { - super(); + value = base64ToArrayBuffer( data.value ); - const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ]; + } else if ( data.inputType === 'Texture' ) { - this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) ); + value = data.meta.textures[ data.value ]; - } + } else { -} + value = data.meta.nodes[ data.value ] || null; -const _geometry = /*@__PURE__*/ new QuadGeometry(); + } -class QuadMesh extends Mesh { + } - constructor( material = null ) { + this.value = value; - super( _geometry, material ); + this.inputType = data.inputType; + this.outputType = data.outputType; - this.camera = _camera; + } - this.isQuadMesh = true; +} - } +const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ); - renderAsync( renderer ) { +class Resources extends Map { - return renderer.renderAsync( this, _camera ); + get( key, callback = null, ...params ) { - } + if ( this.has( key ) ) return super.get( key ); - render( renderer ) { + if ( callback !== null ) { - renderer.render( this, _camera ); + const value = callback( ...params ); + this.set( key, value ); + return value; + + } } } -const _size$2 = /*@__PURE__*/ new Vector2(); +class Parameters { -class RTTNode extends TextureNode { + constructor( scriptableNode ) { - static get type() { + this.scriptableNode = scriptableNode; - return 'RTTNode'; + } + + get parameters() { + + return this.scriptableNode.parameters; } - constructor( node, width = null, height = null, options = { type: HalfFloatType } ) { + get layout() { - const renderTarget = new RenderTarget( width, height, options ); + return this.scriptableNode.getLayout(); - super( renderTarget.texture, uv() ); + } - this.node = node; - this.width = width; - this.height = height; + getInputLayout( id ) { - this.renderTarget = renderTarget; + return this.scriptableNode.getInputLayout( id ); - this.textureNeedsUpdate = true; - this.autoUpdate = true; + } - this.updateMap = new WeakMap(); + get( name ) { - this._rttNode = null; - this._quadMesh = new QuadMesh( new NodeMaterial() ); + const param = this.parameters[ name ]; + const value = param ? param.getValue() : null; - this.updateBeforeType = NodeUpdateType.RENDER; + return value; } - get autoSize() { +} - return this.width === null; +const global = new Resources(); + +class ScriptableNode extends Node { + + static get type() { + + return 'ScriptableNode'; } - setup( builder ) { + constructor( codeNode = null, parameters = {} ) { - this._rttNode = this.node.context( builder.getSharedContext() ); - this._quadMesh.material.name = 'RTT'; - this._quadMesh.material.needsUpdate = true; + super(); - return super.setup( builder ); + this.codeNode = codeNode; + this.parameters = parameters; - } + this._local = new Resources(); + this._output = scriptableValue(); + this._outputs = {}; + this._source = this.source; + this._method = null; + this._object = null; + this._value = null; + this._needsOutputUpdate = true; - setSize( width, height ) { + this.onRefresh = this.onRefresh.bind( this ); - this.width = width; - this.height = height; + this.isScriptableNode = true; - const effectiveWidth = width * this.pixelRatio; - const effectiveHeight = height * this.pixelRatio; + } - this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + get source() { - this.textureNeedsUpdate = true; + return this.codeNode ? this.codeNode.code : ''; } - setPixelRatio( pixelRatio ) { + setLocal( name, value ) { - this.pixelRatio = pixelRatio; + return this._local.set( name, value ); - this.setSize( this.width, this.height ); + } + + getLocal( name ) { + + return this._local.get( name ); } - updateBefore( { renderer } ) { + onRefresh() { - if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return; + this._refresh(); - this.textureNeedsUpdate = false; + } - // + getInputLayout( id ) { - if ( this.autoSize === true ) { + for ( const element of this.getLayout() ) { - this.pixelRatio = renderer.getPixelRatio(); + if ( element.inputType && ( element.id === id || element.name === id ) ) { - const size = renderer.getSize( _size$2 ); + return element; - this.setSize( size.width, size.height ); + } } - // + } - this._quadMesh.material.fragmentNode = this._rttNode; + getOutputLayout( id ) { - // + for ( const element of this.getLayout() ) { - const currentRenderTarget = renderer.getRenderTarget(); + if ( element.outputType && ( element.id === id || element.name === id ) ) { - renderer.setRenderTarget( this.renderTarget ); + return element; - this._quadMesh.render( renderer ); + } - renderer.setRenderTarget( currentRenderTarget ); + } } - clone() { - - const newNode = new TextureNode( this.value, this.uvNode, this.levelNode ); - newNode.sampler = this.sampler; - newNode.referenceNode = this; + setOutput( name, value ) { - return newNode; + const outputs = this._outputs; - } + if ( outputs[ name ] === undefined ) { -} + outputs[ name ] = scriptableValue( value ); -const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) ); -const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ); + } else { -class VertexColorNode extends AttributeNode { + outputs[ name ].value = value; - static get type() { + } - return 'VertexColorNode'; + return this; } - constructor( index = 0 ) { + getOutput( name ) { - super( null, 'vec4' ); + return this._outputs[ name ]; - this.isVertexColorNode = true; + } - this.index = index; + getParameter( name ) { + + return this.parameters[ name ]; } - getAttributeName( /*builder*/ ) { + setParameter( name, value ) { - const index = this.index; + const parameters = this.parameters; - return 'color' + ( index > 0 ? index : '' ); + if ( value && value.isScriptableNode ) { - } + this.deleteParameter( name ); - generate( builder ) { + parameters[ name ] = value; + parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh ); - const attributeName = this.getAttributeName( builder ); - const geometryAttribute = builder.hasGeometryAttribute( attributeName ); + } else if ( value && value.isScriptableValueNode ) { - let result; + this.deleteParameter( name ); - if ( geometryAttribute === true ) { + parameters[ name ] = value; + parameters[ name ].events.addEventListener( 'refresh', this.onRefresh ); - result = super.generate( builder ); + } else if ( parameters[ name ] === undefined ) { + + parameters[ name ] = scriptableValue( value ); + parameters[ name ].events.addEventListener( 'refresh', this.onRefresh ); } else { - // Vertex color fallback should be white - result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) ); + parameters[ name ].value = value; } - return result; + return this; } - serialize( data ) { - - super.serialize( data ); + getValue() { - data.index = this.index; + return this.getDefaultOutput().getValue(); } - deserialize( data ) { - - super.deserialize( data ); - - this.index = data.index; + deleteParameter( name ) { - } + let valueNode = this.parameters[ name ]; -} + if ( valueNode ) { -const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) ); + if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput(); -class PointUVNode extends Node { + valueNode.events.removeEventListener( 'refresh', this.onRefresh ); - static get type() { + } - return 'PointUVNode'; + return this; } - constructor() { + clearParameters() { - super( 'vec2' ); + for ( const name of Object.keys( this.parameters ) ) { - this.isPointUVNode = true; + this.deleteParameter( name ); - } + } - generate( /*builder*/ ) { + this.needsUpdate = true; - return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )'; + return this; } -} + call( name, ...params ) { -const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode ); + const object = this.getObject(); + const method = object[ name ]; -class SceneNode extends Node { + if ( typeof method === 'function' ) { - static get type() { + return method( ...params ); - return 'SceneNode'; + } } - constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) { + async callAsync( name, ...params ) { - super(); + const object = this.getObject(); + const method = object[ name ]; - this.scope = scope; - this.scene = scene; + if ( typeof method === 'function' ) { - } + return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params ); - setup( builder ) { + } - const scope = this.scope; - const scene = this.scene !== null ? this.scene : builder.scene; + } - let output; + getNodeType( builder ) { - if ( scope === SceneNode.BACKGROUND_BLURRINESS ) { + return this.getDefaultOutputNode().getNodeType( builder ); - output = reference( 'backgroundBlurriness', 'float', scene ); + } - } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) { + refresh( output = null ) { - output = reference( 'backgroundIntensity', 'float', scene ); + if ( output !== null ) { + + this.getOutput( output ).refresh(); } else { - console.error( 'THREE.SceneNode: Unknown scope:', scope ); + this._refresh(); } - return output; - } -} + getObject() { -SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness'; -SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity'; + if ( this.needsUpdate ) this.dispose(); + if ( this._object !== null ) return this._object; -const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS ); -const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY ); + // -const GPUPrimitiveTopology = { - PointList: 'point-list', - LineList: 'line-list', - LineStrip: 'line-strip', - TriangleList: 'triangle-list', - TriangleStrip: 'triangle-strip', -}; + const refresh = () => this.refresh(); + const setOutput = ( id, value ) => this.setOutput( id, value ); -const GPUCompareFunction = { - Never: 'never', - Less: 'less', - Equal: 'equal', - LessEqual: 'less-equal', - Greater: 'greater', - NotEqual: 'not-equal', - GreaterEqual: 'greater-equal', - Always: 'always' -}; + const parameters = new Parameters( this ); -const GPUStoreOp = { - Store: 'store', - Discard: 'discard' -}; + const THREE = global.get( 'THREE' ); + const TSL = global.get( 'TSL' ); -const GPULoadOp = { - Load: 'load', - Clear: 'clear' -}; + const method = this.getMethod( this.codeNode ); + const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ]; -const GPUFrontFace = { - CCW: 'ccw', - CW: 'cw' -}; + this._object = method( ...params ); -const GPUCullMode = { - None: 'none', - Front: 'front', - Back: 'back' -}; + const layout = this._object.layout; -const GPUIndexFormat = { - Uint16: 'uint16', - Uint32: 'uint32' -}; + if ( layout ) { -const GPUTextureFormat = { + if ( layout.cache === false ) { - // 8-bit formats + this._local.clear(); - R8Unorm: 'r8unorm', - R8Snorm: 'r8snorm', - R8Uint: 'r8uint', - R8Sint: 'r8sint', + } - // 16-bit formats + // default output + this._output.outputType = layout.outputType || null; - R16Uint: 'r16uint', - R16Sint: 'r16sint', - R16Float: 'r16float', - RG8Unorm: 'rg8unorm', - RG8Snorm: 'rg8snorm', - RG8Uint: 'rg8uint', - RG8Sint: 'rg8sint', + if ( Array.isArray( layout.elements ) ) { - // 32-bit formats + for ( const element of layout.elements ) { - R32Uint: 'r32uint', - R32Sint: 'r32sint', - R32Float: 'r32float', - RG16Uint: 'rg16uint', - RG16Sint: 'rg16sint', - RG16Float: 'rg16float', - RGBA8Unorm: 'rgba8unorm', - RGBA8UnormSRGB: 'rgba8unorm-srgb', - RGBA8Snorm: 'rgba8snorm', - RGBA8Uint: 'rgba8uint', - RGBA8Sint: 'rgba8sint', - BGRA8Unorm: 'bgra8unorm', - BGRA8UnormSRGB: 'bgra8unorm-srgb', - // Packed 32-bit formats - RGB9E5UFloat: 'rgb9e5ufloat', - RGB10A2Unorm: 'rgb10a2unorm', - RG11B10uFloat: 'rgb10a2unorm', + const id = element.id || element.name; - // 64-bit formats + if ( element.inputType ) { - RG32Uint: 'rg32uint', - RG32Sint: 'rg32sint', - RG32Float: 'rg32float', - RGBA16Uint: 'rgba16uint', - RGBA16Sint: 'rgba16sint', - RGBA16Float: 'rgba16float', + if ( this.getParameter( id ) === undefined ) this.setParameter( id, null ); - // 128-bit formats + this.getParameter( id ).inputType = element.inputType; - RGBA32Uint: 'rgba32uint', - RGBA32Sint: 'rgba32sint', - RGBA32Float: 'rgba32float', + } - // Depth and stencil formats + if ( element.outputType ) { - Stencil8: 'stencil8', - Depth16Unorm: 'depth16unorm', - Depth24Plus: 'depth24plus', - Depth24PlusStencil8: 'depth24plus-stencil8', - Depth32Float: 'depth32float', + if ( this.getOutput( id ) === undefined ) this.setOutput( id, null ); - // 'depth32float-stencil8' extension + this.getOutput( id ).outputType = element.outputType; - Depth32FloatStencil8: 'depth32float-stencil8', + } - // BC compressed formats usable if 'texture-compression-bc' is both - // supported by the device/user agent and enabled in requestDevice. + } - BC1RGBAUnorm: 'bc1-rgba-unorm', - BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb', - BC2RGBAUnorm: 'bc2-rgba-unorm', - BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb', - BC3RGBAUnorm: 'bc3-rgba-unorm', - BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb', - BC4RUnorm: 'bc4-r-unorm', - BC4RSnorm: 'bc4-r-snorm', - BC5RGUnorm: 'bc5-rg-unorm', - BC5RGSnorm: 'bc5-rg-snorm', - BC6HRGBUFloat: 'bc6h-rgb-ufloat', - BC6HRGBFloat: 'bc6h-rgb-float', - BC7RGBAUnorm: 'bc7-rgba-unorm', - BC7RGBAUnormSRGB: 'bc7-rgba-srgb', + } - // ETC2 compressed formats usable if 'texture-compression-etc2' is both - // supported by the device/user agent and enabled in requestDevice. + } - ETC2RGB8Unorm: 'etc2-rgb8unorm', - ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb', - ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm', - ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb', - ETC2RGBA8Unorm: 'etc2-rgba8unorm', - ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb', - EACR11Unorm: 'eac-r11unorm', - EACR11Snorm: 'eac-r11snorm', - EACRG11Unorm: 'eac-rg11unorm', - EACRG11Snorm: 'eac-rg11snorm', + return this._object; - // ASTC compressed formats usable if 'texture-compression-astc' is both - // supported by the device/user agent and enabled in requestDevice. + } - ASTC4x4Unorm: 'astc-4x4-unorm', - ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb', - ASTC5x4Unorm: 'astc-5x4-unorm', - ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb', - ASTC5x5Unorm: 'astc-5x5-unorm', - ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb', - ASTC6x5Unorm: 'astc-6x5-unorm', - ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb', - ASTC6x6Unorm: 'astc-6x6-unorm', - ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb', - ASTC8x5Unorm: 'astc-8x5-unorm', - ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb', - ASTC8x6Unorm: 'astc-8x6-unorm', - ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb', - ASTC8x8Unorm: 'astc-8x8-unorm', - ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb', - ASTC10x5Unorm: 'astc-10x5-unorm', - ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb', - ASTC10x6Unorm: 'astc-10x6-unorm', - ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb', - ASTC10x8Unorm: 'astc-10x8-unorm', - ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb', - ASTC10x10Unorm: 'astc-10x10-unorm', - ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb', - ASTC12x10Unorm: 'astc-12x10-unorm', - ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb', - ASTC12x12Unorm: 'astc-12x12-unorm', - ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb', + deserialize( data ) { -}; + super.deserialize( data ); -const GPUAddressMode = { - ClampToEdge: 'clamp-to-edge', - Repeat: 'repeat', - MirrorRepeat: 'mirror-repeat' -}; + for ( const name in this.parameters ) { -const GPUFilterMode = { - Linear: 'linear', - Nearest: 'nearest' -}; + let valueNode = this.parameters[ name ]; -const GPUBlendFactor = { - Zero: 'zero', - One: 'one', - Src: 'src', - OneMinusSrc: 'one-minus-src', - SrcAlpha: 'src-alpha', - OneMinusSrcAlpha: 'one-minus-src-alpha', - Dst: 'dst', - OneMinusDstColor: 'one-minus-dst', - DstAlpha: 'dst-alpha', - OneMinusDstAlpha: 'one-minus-dst-alpha', - SrcAlphaSaturated: 'src-alpha-saturated', - Constant: 'constant', - OneMinusConstant: 'one-minus-constant' -}; + if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput(); -const GPUBlendOperation = { - Add: 'add', - Subtract: 'subtract', - ReverseSubtract: 'reverse-subtract', - Min: 'min', - Max: 'max' -}; + valueNode.events.addEventListener( 'refresh', this.onRefresh ); -const GPUColorWriteFlags = { - None: 0, - Red: 0x1, - Green: 0x2, - Blue: 0x4, - Alpha: 0x8, - All: 0xF -}; + } -const GPUStencilOperation = { - Keep: 'keep', - Zero: 'zero', - Replace: 'replace', - Invert: 'invert', - IncrementClamp: 'increment-clamp', - DecrementClamp: 'decrement-clamp', - IncrementWrap: 'increment-wrap', - DecrementWrap: 'decrement-wrap' -}; + } -const GPUBufferBindingType = { - Uniform: 'uniform', - Storage: 'storage', - ReadOnlyStorage: 'read-only-storage' -}; + getLayout() { -const GPUStorageTextureAccess = { - WriteOnly: 'write-only', - ReadOnly: 'read-only', - ReadWrite: 'read-write', -}; + return this.getObject().layout; -const GPUTextureSampleType = { - Float: 'float', - UnfilterableFloat: 'unfilterable-float', - Depth: 'depth', - SInt: 'sint', - UInt: 'uint' -}; + } -const GPUTextureDimension = { - OneD: '1d', - TwoD: '2d', - ThreeD: '3d' -}; + getDefaultOutputNode() { -const GPUTextureViewDimension = { - OneD: '1d', - TwoD: '2d', - TwoDArray: '2d-array', - Cube: 'cube', - CubeArray: 'cube-array', - ThreeD: '3d' -}; + const output = this.getDefaultOutput().value; -const GPUTextureAspect = { - All: 'all', - StencilOnly: 'stencil-only', - DepthOnly: 'depth-only' -}; + if ( output && output.isNode ) { -const GPUInputStepMode = { - Vertex: 'vertex', - Instance: 'instance' -}; + return output; -const GPUFeatureName = { - DepthClipControl: 'depth-clip-control', - Depth32FloatStencil8: 'depth32float-stencil8', - TextureCompressionBC: 'texture-compression-bc', - TextureCompressionETC2: 'texture-compression-etc2', - TextureCompressionASTC: 'texture-compression-astc', - TimestampQuery: 'timestamp-query', - IndirectFirstInstance: 'indirect-first-instance', - ShaderF16: 'shader-f16', - RG11B10UFloat: 'rg11b10ufloat-renderable', - BGRA8UNormStorage: 'bgra8unorm-storage', - Float32Filterable: 'float32-filterable', - ClipDistances: 'clip-distances', - DualSourceBlending: 'dual-source-blending', - Subgroups: 'subgroups' -}; + } -class StorageBufferNode extends BufferNode { + return float(); - static get type() { + } - return 'StorageBufferNode'; + getDefaultOutput() { + + return this._exec()._output; } - constructor( value, bufferType, bufferCount = 0 ) { + getMethod() { - super( value, bufferType, bufferCount ); + if ( this.needsUpdate ) this.dispose(); + if ( this._method !== null ) return this._method; - this.isStorageBufferNode = true; + // - this.access = GPUBufferBindingType.Storage; - this.isAtomic = false; + const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ]; + const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ]; - this.bufferObject = false; - this.bufferCount = bufferCount; + const properties = interfaceProps.join( ', ' ); + const declarations = 'var ' + properties + '; var output = {};\n'; + const returns = '\nreturn { ...output, ' + properties + ' };'; - this._attribute = null; - this._varying = null; + const code = declarations + this.codeNode.code + returns; - this.global = true; + // - if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) { + this._method = new Function( ...parametersProps, code ); - // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer + return this._method; - if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true; - else value.isStorageBufferAttribute = true; + } + + dispose() { + + if ( this._method === null ) return; + + if ( this._object && typeof this._object.dispose === 'function' ) { + + this._object.dispose(); } - } + this._method = null; + this._object = null; + this._source = null; + this._value = null; + this._needsOutputUpdate = true; + this._output.value = null; + this._outputs = {}; - getHash( builder ) { + } - if ( this.bufferCount === 0 ) { + setup() { - let bufferData = builder.globalCache.getData( this.value ); + return this.getDefaultOutputNode(); - if ( bufferData === undefined ) { + } - bufferData = { - node: this - }; + getCacheKey( force ) { - builder.globalCache.setData( this.value, bufferData ); + const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ]; - } + for ( const param in this.parameters ) { - return bufferData.node.uuid; + values.push( this.parameters[ param ].getCacheKey( force ) ); } - return this.uuid; + return hashArray( values ); } - getInputType( /*builder*/ ) { + set needsUpdate( value ) { - return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer'; + if ( value === true ) this.dispose(); } - element( indexNode ) { + get needsUpdate() { - return storageElement( this, indexNode ); + return this.source !== this._source; } - setBufferObject( value ) { + _exec() { - this.bufferObject = value; + if ( this.codeNode === null ) return this; - return this; + if ( this._needsOutputUpdate === true ) { - } + this._value = this.call( 'main' ); - setAccess( value ) { + this._needsOutputUpdate = false; - this.access = value; + } + + this._output.value = this._value; return this; } - toReadOnly() { + _refresh() { - return this.setAccess( GPUBufferBindingType.ReadOnlyStorage ); + this.needsUpdate = true; + + this._exec(); + + this._output.refresh(); } - setAtomic( value ) { +} - this.isAtomic = value; +const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ); - return this; +class FogNode extends Node { + + static get type() { + + return 'FogNode'; } - toAtomic() { + constructor( colorNode, factorNode ) { - return this.setAtomic( true ); + super( 'float' ); + + this.isFogNode = true; + + this.colorNode = colorNode; + this.factorNode = factorNode; } - getAttributeData() { + getViewZNode( builder ) { - if ( this._attribute === null ) { + let viewZ; - this._attribute = bufferAttribute( this.value ); - this._varying = varying( this._attribute ); + const getViewZ = builder.context.getViewZ; + + if ( getViewZ !== undefined ) { + + viewZ = getViewZ( this ); } - return { - attribute: this._attribute, - varying: this._varying - }; + return ( viewZ || positionView.z ).negate(); } - getNodeType( builder ) { + setup() { - if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) { + return this.factorNode; - return super.getNodeType( builder ); + } - } +} - const { attribute } = this.getAttributeData(); +const fog = /*@__PURE__*/ nodeProxy( FogNode ); - return attribute.getNodeType( builder ); +class FogRangeNode extends FogNode { + + static get type() { + + return 'FogRangeNode'; } - generate( builder ) { + constructor( colorNode, nearNode, farNode ) { - if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) { + super( colorNode ); - return super.generate( builder ); + this.isFogRangeNode = true; - } + this.nearNode = nearNode; + this.farNode = farNode; - const { attribute, varying } = this.getAttributeData(); + } - const output = varying.build( builder ); + setup( builder ) { - builder.registerTransform( output, attribute ); + const viewZ = this.getViewZNode( builder ); - return output; + return smoothstep( this.nearNode, this.farNode, viewZ ); } } -// Read-Write Storage -const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) ); -const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) ); +const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode ); -class StorageTextureNode extends TextureNode { +class FogExp2Node extends FogNode { static get type() { - return 'StorageTextureNode'; + return 'FogExp2Node'; } - constructor( value, uvNode, storeNode = null ) { - - super( value, uvNode ); + constructor( colorNode, densityNode ) { - this.storeNode = storeNode; + super( colorNode ); - this.isStorageTextureNode = true; + this.isFogExp2Node = true; - this.access = GPUStorageTextureAccess.WriteOnly; + this.densityNode = densityNode; } - getInputType( /*builder*/ ) { + setup( builder ) { - return 'storageTexture'; + const viewZ = this.getViewZNode( builder ); + const density = this.densityNode; + + return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus(); } - setup( builder ) { +} - super.setup( builder ); +const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node ); - const properties = builder.getNodeProperties( this ); - properties.storeNode = this.storeNode; +let min = null; +let max = null; - } +class RangeNode extends Node { - setAccess( value ) { + static get type() { - this.access = value; - return this; + return 'RangeNode'; } - generate( builder, output ) { - - let snippet; + constructor( minNode = float(), maxNode = float() ) { - if ( this.storeNode !== null ) { + super(); - snippet = this.generateStore( builder ); + this.minNode = minNode; + this.maxNode = maxNode; - } else { + } - snippet = super.generate( builder, output ); + getVectorLength( builder ) { - } + const minLength = builder.getTypeLength( getValueType( this.minNode.value ) ); + const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) ); - return snippet; + return minLength > maxLength ? minLength : maxLength; } - toReadOnly() { + getNodeType( builder ) { - return this.setAccess( GPUStorageTextureAccess.ReadOnly ); + return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float'; } - toWriteOnly() { + setup( builder ) { - return this.setAccess( GPUStorageTextureAccess.WriteOnly ); + const object = builder.object; - } + let output = null; - generateStore( builder ) { + if ( object.count > 1 ) { - const properties = builder.getNodeProperties( this ); + const minValue = this.minNode.value; + const maxValue = this.maxNode.value; - const { uvNode, storeNode } = properties; + const minLength = builder.getTypeLength( getValueType( minValue ) ); + const maxLength = builder.getTypeLength( getValueType( maxValue ) ); - const textureProperty = super.generate( builder, 'property' ); - const uvSnippet = uvNode.build( builder, 'uvec2' ); - const storeSnippet = storeNode.build( builder, 'vec4' ); + min = min || new Vector4(); + max = max || new Vector4(); - const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet ); + min.setScalar( 0 ); + max.setScalar( 0 ); - builder.addLineFlowCode( snippet, this ); + if ( minLength === 1 ) min.setScalar( minValue ); + else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b ); + else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 ); - } + if ( maxLength === 1 ) max.setScalar( maxValue ); + else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b ); + else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 ); -} + const stride = 4; -const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ); + const length = stride * object.count; + const array = new Float32Array( length ); -const textureStore = ( value, uvNode, storeNode ) => { + for ( let i = 0; i < length; i ++ ) { - const node = storageTexture( value, uvNode, storeNode ); + const index = i % stride; - if ( storeNode !== null ) node.append(); + const minElementValue = min.getComponent( index ); + const maxElementValue = max.getComponent( index ); - return node; + array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() ); -}; + } -class UserDataNode extends ReferenceNode { + const nodeType = this.getNodeType( builder ); - static get type() { + if ( object.count <= 4096 ) { - return 'UserDataNode'; + output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType ); - } + } else { - constructor( property, inputType, userData = null ) { + // TODO: Improve anonymous buffer attribute creation removing this part + const bufferAttribute = new InstancedBufferAttribute( array, 4 ); + builder.geometry.setAttribute( '__range' + this.id, bufferAttribute ); - super( property, inputType, userData ); + output = instancedBufferAttribute( bufferAttribute ).convert( nodeType ); - this.userData = userData; + } - } + } else { - updateReference( state ) { + output = float( 0 ); - this.reference = this.userData !== null ? this.userData : state.object.userData; + } - return this.reference; + return output; } } -const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) ); +const range = /*@__PURE__*/ nodeProxy( RangeNode ); -class PosterizeNode extends TempNode { +class ComputeBuiltinNode extends Node { static get type() { - return 'PosterizeNode'; + return 'ComputeBuiltinNode'; } - constructor( sourceNode, stepsNode ) { + constructor( builtinName, nodeType ) { - super(); + super( nodeType ); - this.sourceNode = sourceNode; - this.stepsNode = stepsNode; + this._builtinName = builtinName; } - setup() { - - const { sourceNode, stepsNode } = this; + getHash( builder ) { - return sourceNode.mul( stepsNode ).floor().div( stepsNode ); + return this.getBuiltinName( builder ); } -} - -const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ); - -let _sharedFramebuffer = null; - -class ViewportSharedTextureNode extends ViewportTextureNode { - - static get type() { + getNodeType( /*builder*/ ) { - return 'ViewportSharedTextureNode'; + return this.nodeType; } - constructor( uvNode = screenUV, levelNode = null ) { - - if ( _sharedFramebuffer === null ) { - - _sharedFramebuffer = new FramebufferTexture(); + setBuiltinName( builtinName ) { - } + this._builtinName = builtinName; - super( uvNode, levelNode, _sharedFramebuffer ); + return this; } - updateReference() { + getBuiltinName( /*builder*/ ) { - return this; + return this._builtinName; } -} - -const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ); + hasBuiltin( builder ) { -const _size$1 = /*@__PURE__*/ new Vector2(); + builder.hasBuiltin( this._builtinName ); -class PassTextureNode extends TextureNode { + } - static get type() { + generate( builder, output ) { - return 'PassTextureNode'; + const builtinName = this.getBuiltinName( builder ); + const nodeType = this.getNodeType( builder ); - } + if ( builder.shaderStage === 'compute' ) { - constructor( passNode, texture ) { + return builder.format( builtinName, nodeType, output ); - super( texture ); + } else { - this.passNode = passNode; + console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` ); + return builder.generateConst( nodeType ); - this.setUpdateMatrix( false ); + } } - setup( builder ) { + serialize( data ) { - if ( builder.object.isQuadMesh ) this.passNode.build( builder ); + super.serialize( data ); - return super.setup( builder ); + data.global = this.global; + data._builtinName = this._builtinName; } - clone() { + deserialize( data ) { - return new this.constructor( this.passNode, this.value ); + super.deserialize( data ); + + this.global = data.global; + this._builtinName = data._builtinName; } } -class PassMultipleTextureNode extends PassTextureNode { - - static get type() { +const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) ); - return 'PassMultipleTextureNode'; +const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' ); +const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' ); +const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' ); +const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' ); - } +class BarrierNode extends Node { - constructor( passNode, textureName, previousTexture = false ) { + constructor( scope ) { - super( passNode, null ); + super(); - this.textureName = textureName; - this.previousTexture = previousTexture; + this.scope = scope; } - updateTexture() { + generate( builder ) { - this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName ); + const { scope } = this; + const { renderer } = builder; - } + if ( renderer.backend.isWebGLBackend === true ) { - setup( builder ) { + builder.addFlowCode( `\t// ${scope}Barrier \n` ); - this.updateTexture(); + } else { - return super.setup( builder ); + builder.addLineFlowCode( `${scope}Barrier()`, this ); + + } } - clone() { +} - return new this.constructor( this.passNode, this.textureName, this.previousTexture ); +const barrier = nodeProxy( BarrierNode ); - } +const workgroupBarrier = () => barrier( 'workgroup' ).append(); +const storageBarrier = () => barrier( 'storage' ).append(); +const textureBarrier = () => barrier( 'texture' ).append(); -} +class WorkgroupInfoElementNode extends ArrayElementNode { -class PassNode extends TempNode { + constructor( workgroupInfoNode, indexNode ) { - static get type() { + super( workgroupInfoNode, indexNode ); - return 'PassNode'; + this.isWorkgroupInfoElementNode = true; } - constructor( scope, scene, camera, options = {} ) { + generate( builder, output ) { - super( 'vec4' ); + let snippet; - this.scope = scope; - this.scene = scene; - this.camera = camera; - this.options = options; + const isAssignContext = builder.context.assign; + snippet = super.generate( builder ); - this._pixelRatio = 1; - this._width = 1; - this._height = 1; + if ( isAssignContext !== true ) { - const depthTexture = new DepthTexture(); - depthTexture.isRenderTargetTexture = true; - //depthTexture.type = FloatType; - depthTexture.name = 'depth'; + const type = this.getNodeType( builder ); - const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } ); - renderTarget.texture.name = 'output'; - renderTarget.depthTexture = depthTexture; + snippet = builder.format( snippet, type, output ); - this.renderTarget = renderTarget; + } - this.updateBeforeType = NodeUpdateType.FRAME; + // TODO: Possibly activate clip distance index on index access rather than from clipping context - this._textures = { - output: renderTarget.texture, - depth: depthTexture - }; + return snippet; - this._textureNodes = {}; - this._linearDepthNodes = {}; - this._viewZNodes = {}; + } - this._previousTextures = {}; - this._previousTextureNodes = {}; +} - this._cameraNear = uniform( 0 ); - this._cameraFar = uniform( 0 ); - this._mrt = null; +class WorkgroupInfoNode extends Node { - this.isPassNode = true; + constructor( scope, bufferType, bufferCount = 0 ) { - } + super( bufferType ); - setMRT( mrt ) { + this.bufferType = bufferType; + this.bufferCount = bufferCount; - this._mrt = mrt; + this.isWorkgroupInfoNode = true; - return this; + this.scope = scope; } - getMRT() { + label( name ) { - return this._mrt; + this.name = name; + + return this; } - isGlobal() { + getHash() { - return true; + return this.uuid; } - getTexture( name ) { + setScope( scope ) { - let texture = this._textures[ name ]; + this.scope = scope; - if ( texture === undefined ) { + return this; - const refTexture = this.renderTarget.texture; + } - texture = refTexture.clone(); - texture.isRenderTargetTexture = true; - texture.name = name; + getInputType( /*builder*/ ) { - this._textures[ name ] = texture; + return `${this.scope}Array`; - this.renderTarget.textures.push( texture ); + } - } + element( indexNode ) { - return texture; + return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) ); } - getPreviousTexture( name ) { + generate( builder ) { - let texture = this._previousTextures[ name ]; + return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount ); - if ( texture === undefined ) { + } - texture = this.getTexture( name ).clone(); - texture.isRenderTargetTexture = true; +} - this._previousTextures[ name ] = texture; +const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) ); - } +class AtomicFunctionNode extends TempNode { - return texture; + static get type() { + + return 'AtomicFunctionNode'; } - toggleTexture( name ) { + constructor( method, pointerNode, valueNode, storeNode = null ) { - const prevTexture = this._previousTextures[ name ]; + super( 'uint' ); - if ( prevTexture !== undefined ) { + this.method = method; - const texture = this._textures[ name ]; + this.pointerNode = pointerNode; + this.valueNode = valueNode; + this.storeNode = storeNode; - const index = this.renderTarget.textures.indexOf( texture ); - this.renderTarget.textures[ index ] = prevTexture; + } - this._textures[ name ] = prevTexture; - this._previousTextures[ name ] = texture; + getInputType( builder ) { - this._textureNodes[ name ].updateTexture(); - this._previousTextureNodes[ name ].updateTexture(); + return this.pointerNode.getNodeType( builder ); - } + } + + getNodeType( builder ) { + + return this.getInputType( builder ); } - getTextureNode( name = 'output' ) { + generate( builder ) { - let textureNode = this._textureNodes[ name ]; + const method = this.method; - if ( textureNode === undefined ) { + const type = this.getNodeType( builder ); + const inputType = this.getInputType( builder ); - this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) ); - this._textureNodes[ name ].updateTexture(); + const a = this.pointerNode; + const b = this.valueNode; - } + const params = []; - return textureNode; + params.push( `&${ a.build( builder, inputType ) }` ); + params.push( b.build( builder, inputType ) ); - } + const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`; - getPreviousTextureNode( name = 'output' ) { + if ( this.storeNode !== null ) { - let textureNode = this._previousTextureNodes[ name ]; + const varSnippet = this.storeNode.build( builder, inputType ); - if ( textureNode === undefined ) { + builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this ); - if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name ); + } else { - this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) ); - this._previousTextureNodes[ name ].updateTexture(); + builder.addLineFlowCode( methodSnippet, this ); } - return textureNode; - } - getViewZNode( name = 'depth' ) { +} - let viewZNode = this._viewZNodes[ name ]; +AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad'; +AtomicFunctionNode.ATOMIC_STORE = 'atomicStore'; +AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd'; +AtomicFunctionNode.ATOMIC_SUB = 'atomicSub'; +AtomicFunctionNode.ATOMIC_MAX = 'atomicMax'; +AtomicFunctionNode.ATOMIC_MIN = 'atomicMin'; +AtomicFunctionNode.ATOMIC_AND = 'atomicAnd'; +AtomicFunctionNode.ATOMIC_OR = 'atomicOr'; +AtomicFunctionNode.ATOMIC_XOR = 'atomicXor'; - if ( viewZNode === undefined ) { +const atomicNode = nodeProxy( AtomicFunctionNode ); - const cameraNear = this._cameraNear; - const cameraFar = this._cameraFar; +const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => { - this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar ); + const node = atomicNode( method, pointerNode, valueNode, storeNode ); + node.append(); - } + return node; - return viewZNode; +}; - } +const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode ); +const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode ); +const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode ); +const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode ); +const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode ); +const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode ); +const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode ); +const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode ); - getLinearDepthNode( name = 'depth' ) { +let uniformsLib; - let linearDepthNode = this._linearDepthNodes[ name ]; +function getLightData( light ) { - if ( linearDepthNode === undefined ) { + uniformsLib = uniformsLib || new WeakMap(); - const cameraNear = this._cameraNear; - const cameraFar = this._cameraFar; - const viewZNode = this.getViewZNode( name ); + let uniforms = uniformsLib.get( light ); - // TODO: just if ( builder.camera.isPerspectiveCamera ) + if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} ); - this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar ); + return uniforms; - } +} - return linearDepthNode; +function lightPosition( light ) { - } + const data = getLightData( light ); - setup( { renderer } ) { + return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) ); - this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples; +} - // Disable MSAA for WebGL backend for now - if ( renderer.backend.isWebGLBackend === true ) { +function lightTargetPosition( light ) { - this.renderTarget.samples = 0; + const data = getLightData( light ); - } + return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) ); - this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1; +} - return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode(); +function lightViewPosition( light ) { - } + const data = getLightData( light ); - updateBefore( frame ) { + return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => { - const { renderer } = frame; - const { scene, camera } = this; + self.value = self.value || new Vector3(); + self.value.setFromMatrixPosition( light.matrixWorld ); - this._pixelRatio = renderer.getPixelRatio(); + self.value.applyMatrix4( camera.matrixWorldInverse ); - const size = renderer.getSize( _size$1 ); + } ) ); - this.setSize( size.width, size.height ); +} - const currentRenderTarget = renderer.getRenderTarget(); - const currentMRT = renderer.getMRT(); +const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) ); - this._cameraNear.value = camera.near; - this._cameraFar.value = camera.far; +const sortLights = ( lights ) => { - for ( const name in this._previousTextures ) { + return lights.sort( ( a, b ) => a.id - b.id ); - this.toggleTexture( name ); +}; - } +const getLightNodeById = ( id, lightNodes ) => { - renderer.setRenderTarget( this.renderTarget ); - renderer.setMRT( this._mrt ); + for ( const lightNode of lightNodes ) { - renderer.render( scene, camera ); + if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) { - renderer.setRenderTarget( currentRenderTarget ); - renderer.setMRT( currentMRT ); + return lightNode; + + } } - setSize( width, height ) { + return null; - this._width = width; - this._height = height; +}; - const effectiveWidth = this._width * this._pixelRatio; - const effectiveHeight = this._height * this._pixelRatio; +const _lightsNodeRef = /*@__PURE__*/ new WeakMap(); - this.renderTarget.setSize( effectiveWidth, effectiveHeight ); +class LightsNode extends Node { - } + static get type() { - setPixelRatio( pixelRatio ) { + return 'LightsNode'; - this._pixelRatio = pixelRatio; + } - this.setSize( this._width, this._height ); + constructor() { - } + super( 'vec3' ); - dispose() { + this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' ); + this.totalSpecularNode = vec3().toVar( 'totalSpecular' ); - this.renderTarget.dispose(); + this.outgoingLightNode = vec3().toVar( 'outgoingLight' ); - } + this._lights = []; + this._lightNodes = null; + this._lightNodesHash = null; -} + this.global = true; -PassNode.COLOR = 'color'; -PassNode.DEPTH = 'depth'; + } -const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) ); -const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) ); -const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); + getHash( builder ) { -class ToonOutlinePassNode extends PassNode { + if ( this._lightNodesHash === null ) { - static get type() { + if ( this._lightNodes === null ) this.setupLightsNode( builder ); - return 'ToonOutlinePassNode'; + const hash = []; - } + for ( const lightNode of this._lightNodes ) { - constructor( scene, camera, colorNode, thicknessNode, alphaNode ) { + hash.push( lightNode.getSelf().getHash() ); - super( PassNode.COLOR, scene, camera ); + } - this.colorNode = colorNode; - this.thicknessNode = thicknessNode; - this.alphaNode = alphaNode; + this._lightNodesHash = 'lights-' + hash.join( ',' ); - this._materialCache = new WeakMap(); + } + + return this._lightNodesHash; } - updateBefore( frame ) { + analyze( builder ) { - const { renderer } = frame; + const properties = builder.getDataFromNode( this ); - const currentRenderObjectFunction = renderer.getRenderObjectFunction(); + for ( const node of properties.nodes ) { - renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => { + node.build( builder ); - // only render outline for supported materials + } - if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) { + } - if ( material.wireframe === false ) { + setupLightsNode( builder ) { - const outlineMaterial = this._getOutlineMaterial( material ); - renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode ); + const lightNodes = []; - } + const previousLightNodes = this._lightNodes; - } + const lights = sortLights( this._lights ); + const nodeLibrary = builder.renderer.library; - // default + for ( const light of lights ) { - renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode ); + if ( light.isNode ) { - } ); + lightNodes.push( nodeObject( light ) ); - super.updateBefore( frame ); + } else { - renderer.setRenderObjectFunction( currentRenderObjectFunction ); + let lightNode = null; - } + if ( previousLightNodes !== null ) { - _createMaterial() { + lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node - const material = new NodeMaterial(); - material.isMeshToonOutlineMaterial = true; - material.name = 'Toon_Outline'; - material.side = BackSide; + } - // vertex node + if ( lightNode === null ) { - const outlineNormal = normalLocal.negate(); - const mvp = cameraProjectionMatrix.mul( modelViewMatrix ); + const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor ); - const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex - const pos = mvp.mul( vec4( positionLocal, 1.0 ) ); - const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) ); - const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative + if ( lightNodeClass === null ) { - material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) ); + console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` ); + continue; - // color node + } - material.colorNode = vec4( this.colorNode, this.alphaNode ); + let lightNode = null; - return material; + if ( ! _lightsNodeRef.has( light ) ) { - } + lightNode = nodeObject( new lightNodeClass( light ) ); + _lightsNodeRef.set( light, lightNode ); - _getOutlineMaterial( originalMaterial ) { + } else { - let outlineMaterial = this._materialCache.get( originalMaterial ); + lightNode = _lightsNodeRef.get( light ); - if ( outlineMaterial === undefined ) { + } - outlineMaterial = this._createMaterial(); + lightNodes.push( lightNode ); - this._materialCache.set( originalMaterial, outlineMaterial ); + } + + } } - return outlineMaterial; + this._lightNodes = lightNodes; } -} - -const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) ); + setupLights( builder, lightNodes ) { -class ScriptableValueNode extends Node { + for ( const lightNode of lightNodes ) { - static get type() { + lightNode.build( builder ); - return 'ScriptableValueNode'; + } } - constructor( value = null ) { + setup( builder ) { - super(); + if ( this._lightNodes === null ) this.setupLightsNode( builder ); - this._value = value; - this._cache = null; + const context = builder.context; + const lightingModel = context.lightingModel; - this.inputType = null; - this.outpuType = null; + let outgoingLightNode = this.outgoingLightNode; - this.events = new EventDispatcher(); + if ( lightingModel ) { - this.isScriptableValueNode = true; + const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this; - } + context.outgoingLight = outgoingLightNode; - get isScriptableOutputNode() { + const stack = builder.addStack(); - return this.outputType !== null; + // - } + const properties = builder.getDataFromNode( this ); + properties.nodes = stack.nodes; - set value( val ) { + // - if ( this._value === val ) return; + lightingModel.start( context, stack, builder ); - if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) { + // lights - URL.revokeObjectURL( this._cache ); + this.setupLights( builder, _lightNodes ); - this._cache = null; + // - } + lightingModel.indirect( context, stack, builder ); - this._value = val; + // - this.events.dispatchEvent( { type: 'change' } ); + const { backdrop, backdropAlpha } = context; + const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight; - this.refresh(); + let totalDiffuse = directDiffuse.add( indirectDiffuse ); - } + if ( backdrop !== null ) { - get value() { + if ( backdropAlpha !== null ) { - return this._value; + totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) ); - } + } else { - refresh() { + totalDiffuse = vec3( backdrop ); - this.events.dispatchEvent( { type: 'refresh' } ); + } - } + context.material.transparent = true; - getValue() { + } - const value = this.value; + totalDiffuseNode.assign( totalDiffuse ); + totalSpecularNode.assign( directSpecular.add( indirectSpecular ) ); - if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) { + outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) ); - this._cache = URL.createObjectURL( new Blob( [ value.value ] ) ); + // - } else if ( value && value.value !== null && value.value !== undefined && ( - ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) || - ( this.inputType === 'Number' && typeof value.value === 'number' ) || - ( this.inputType === 'Vector2' && value.value.isVector2 ) || - ( this.inputType === 'Vector3' && value.value.isVector3 ) || - ( this.inputType === 'Vector4' && value.value.isVector4 ) || - ( this.inputType === 'Color' && value.value.isColor ) || - ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) || - ( this.inputType === 'Matrix4' && value.value.isMatrix4 ) - ) ) { + lightingModel.finish( context, stack, builder ); - return value.value; + // + + outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() ); } - return this._cache || value; + return outgoingLightNode; } - getNodeType( builder ) { - - return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float'; + setLights( lights ) { - } + this._lights = lights; - setup() { + this._lightNodes = null; + this._lightNodesHash = null; - return this.value && this.value.isNode ? this.value : float(); + return this; } - serialize( data ) { + getLights() { - super.serialize( data ); + return this._lights; - if ( this.value !== null ) { + } - if ( this.inputType === 'ArrayBuffer' ) { + get hasLights() { - data.value = arrayBufferToBase64( this.value ); + return this._lights.length > 0; - } else { + } - data.value = this.value ? this.value.toJSON( data.meta ).uuid : null; +} - } +const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights ); - } else { +const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => { - data.value = null; + return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z ); - } +} ); - data.inputType = this.inputType; - data.outputType = this.outputType; +const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => { - } + const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare ); - deserialize( data ) { + const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); + const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup ); - super.deserialize( data ); + const texelSize = vec2( 1 ).div( mapSize ); + const dx0 = texelSize.x.negate().mul( radius ); + const dy0 = texelSize.y.negate().mul( radius ); + const dx1 = texelSize.x.mul( radius ); + const dy1 = texelSize.y.mul( radius ); + const dx2 = dx0.div( 2 ); + const dy2 = dy0.div( 2 ); + const dx3 = dx1.div( 2 ); + const dy3 = dy1.div( 2 ); - let value = null; + return add( + depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy, shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ), + depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z ) + ).mul( 1 / 17 ); - if ( data.value !== null ) { +} ); - if ( data.inputType === 'ArrayBuffer' ) { +const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => { - value = base64ToArrayBuffer( data.value ); + const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare ); - } else if ( data.inputType === 'Texture' ) { + const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); - value = data.meta.textures[ data.value ]; + const texelSize = vec2( 1 ).div( mapSize ); + const dx = texelSize.x; + const dy = texelSize.y; - } else { + const uv = shadowCoord.xy; + const f = fract( uv.mul( mapSize ).add( 0.5 ) ); + uv.subAssign( f.mul( texelSize ) ); - value = data.meta.nodes[ data.value ] || null; + return add( + depthCompare( uv, shadowCoord.z ), + depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ), + depthCompare( uv.add( texelSize ), shadowCoord.z ), + mix( + depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ), + f.x + ), + mix( + depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ), + f.x + ), + mix( + depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ), + f.y + ), + mix( + depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ), + f.y + ), + mix( + mix( + depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ), + f.x + ), + mix( + depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ), + depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ), + f.x + ), + f.y + ) + ).mul( 1 / 9 ); - } +} ); - } +// VSM - this.value = value; +const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => { - this.inputType = data.inputType; - this.outputType = data.outputType; + const occlusion = float( 1 ).toVar(); - } + const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg; -} + const hardShadow = step( shadowCoord.z, distribution.x ); -const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ); + If( hardShadow.notEqual( float( 1.0 ) ), () => { -class Resources extends Map { + const distance = shadowCoord.z.sub( distribution.x ); + const variance = max$1( 0, distribution.y.mul( distribution.y ) ); + let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality + softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) ); + occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) ); - get( key, callback = null, ...params ) { + } ); - if ( this.has( key ) ) return super.get( key ); + return occlusion; - if ( callback !== null ) { +} ); - const value = callback( ...params ); - this.set( key, value ); - return value; +const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => { - } + const mean = float( 0 ).toVar(); + const squaredMean = float( 0 ).toVar(); - } + const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) ); + const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) ); -} + Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => { -class Parameters { + const uvOffset = uvStart.add( float( i ).mul( uvStride ) ); - constructor( scriptableNode ) { + const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x; + mean.addAssign( depth ); + squaredMean.addAssign( depth.mul( depth ) ); - this.scriptableNode = scriptableNode; + } ); - } + mean.divAssign( samples ); + squaredMean.divAssign( samples ); - get parameters() { + const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) ); + return vec2( mean, std_dev ); - return this.scriptableNode.parameters; +} ); - } +const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => { - get layout() { + const mean = float( 0 ).toVar(); + const squaredMean = float( 0 ).toVar(); - return this.scriptableNode.getLayout(); + const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) ); + const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) ); - } + Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => { - getInputLayout( id ) { + const uvOffset = uvStart.add( float( i ).mul( uvStride ) ); - return this.scriptableNode.getInputLayout( id ); + const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) ); + mean.addAssign( distribution.x ); + squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) ); - } + } ); - get( name ) { + mean.divAssign( samples ); + squaredMean.divAssign( samples ); - const param = this.parameters[ name ]; - const value = param ? param.getValue() : null; + const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) ); + return vec2( mean, std_dev ); - return value; +} ); - } +const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ]; -} +// -const global = new Resources(); +let _overrideMaterial = null; +const _quadMesh$1 = /*@__PURE__*/ new QuadMesh(); -class ScriptableNode extends Node { +class ShadowNode extends Node { static get type() { - return 'ScriptableNode'; + return 'ShadowNode'; } - constructor( codeNode = null, parameters = {} ) { + constructor( light, shadow = null ) { super(); - this.codeNode = codeNode; - this.parameters = parameters; + this.light = light; + this.shadow = shadow || light.shadow; - this._local = new Resources(); - this._output = scriptableValue(); - this._outputs = {}; - this._source = this.source; - this._method = null; - this._object = null; - this._value = null; - this._needsOutputUpdate = true; + this.shadowMap = null; - this.onRefresh = this.onRefresh.bind( this ); + this.vsmShadowMapVertical = null; + this.vsmShadowMapHorizontal = null; - this.isScriptableNode = true; + this.vsmMaterialVertical = null; + this.vsmMaterialHorizontal = null; + + this.updateBeforeType = NodeUpdateType.RENDER; + this._node = null; + + this.isShadowNode = true; } - get source() { + setupShadow( builder ) { - return this.codeNode ? this.codeNode.code : ''; + const { object, renderer } = builder; - } + if ( _overrideMaterial === null ) { - setLocal( name, value ) { + _overrideMaterial = new NodeMaterial(); + _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 ); + _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode + _overrideMaterial.name = 'ShadowMaterial'; - return this._local.set( name, value ); + } - } + const shadow = this.shadow; + const shadowMapType = renderer.shadowMap.type; - getLocal( name ) { + const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height ); + depthTexture.compareFunction = LessCompare; - return this._local.get( name ); + const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height ); + shadowMap.depthTexture = depthTexture; - } + shadow.camera.updateProjectionMatrix(); - onRefresh() { + // VSM - this._refresh(); + if ( shadowMapType === VSMShadowMap ) { - } + depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare() - getInputLayout( id ) { + this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } ); + this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } ); - for ( const element of this.getLayout() ) { + const shadowPassVertical = texture( depthTexture ); + const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture ); - if ( element.inputType && ( element.id === id || element.name === id ) ) { + const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup ); + const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup ); + const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); - return element; + let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() ); + material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() ); + material.name = 'VSMVertical'; - } + material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() ); + material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() ); + material.name = 'VSMHorizontal'; } - } - - getOutputLayout( id ) { + // - for ( const element of this.getLayout() ) { + const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup ); + const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup ); + const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup ); - if ( element.outputType && ( element.id === id || element.name === id ) ) { + const position = object.material.shadowPositionNode || positionWorld; - return element; + let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) ); - } + let coordZ; - } + if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) { - } + shadowCoord = shadowCoord.xyz.div( shadowCoord.w ); - setOutput( name, value ) { + coordZ = shadowCoord.z; - const outputs = this._outputs; + if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) { - if ( outputs[ name ] === undefined ) { + coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ] - outputs[ name ] = scriptableValue( value ); + } } else { - outputs[ name ].value = value; + const w = shadowCoord.w; + shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z + + // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get + // updated to use the shadow camera. So, we have to declare our own "local" ones here. + // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here? + const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near ); + const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far ); + + coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal ); } - return this; + shadowCoord = vec3( + shadowCoord.x, + shadowCoord.y.oneMinus(), // follow webgpu standards + coordZ.add( bias ) + ); - } + const frustumTest = shadowCoord.x.greaterThanEqual( 0 ) + .and( shadowCoord.x.lessThanEqual( 1 ) ) + .and( shadowCoord.y.greaterThanEqual( 0 ) ) + .and( shadowCoord.y.lessThanEqual( 1 ) ) + .and( shadowCoord.z.lessThanEqual( 1 ) ); - getOutput( name ) { + // - return this._outputs[ name ]; + const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null; - } + if ( filterFn === null ) { - getParameter( name ) { + throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' ); - return this.parameters[ name ]; + } + + const shadowColor = texture( shadowMap.texture, shadowCoord ); + const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) ); + + this.shadowMap = shadowMap; + this.shadow.map = shadowMap; + + return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ); } - setParameter( name, value ) { + setup( builder ) { - const parameters = this.parameters; + if ( builder.renderer.shadowMap.enabled === false ) return; - if ( value && value.isScriptableNode ) { + return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) ); - this.deleteParameter( name ); + } - parameters[ name ] = value; - parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh ); + updateShadow( frame ) { - } else if ( value && value.isScriptableValueNode ) { + const { shadowMap, light, shadow } = this; + const { renderer, scene, camera } = frame; - this.deleteParameter( name ); + const shadowType = renderer.shadowMap.type; - parameters[ name ] = value; - parameters[ name ].events.addEventListener( 'refresh', this.onRefresh ); + const depthVersion = shadowMap.depthTexture.version; + this._depthVersionCached = depthVersion; - } else if ( parameters[ name ] === undefined ) { + const currentOverrideMaterial = scene.overrideMaterial; - parameters[ name ] = scriptableValue( value ); - parameters[ name ].events.addEventListener( 'refresh', this.onRefresh ); + scene.overrideMaterial = _overrideMaterial; - } else { + shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height ); - parameters[ name ].value = value; + shadow.updateMatrices( light ); + shadow.camera.layers.mask = camera.layers.mask; - } + const currentRenderTarget = renderer.getRenderTarget(); + const currentRenderObjectFunction = renderer.getRenderObjectFunction(); - return this; + renderer.setRenderObjectFunction( ( object, ...params ) => { - } + if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) { - getValue() { + renderer.renderObject( object, ...params ); - return this.getDefaultOutput().getValue(); + } - } + } ); - deleteParameter( name ) { + renderer.setRenderTarget( shadowMap ); + renderer.render( scene, shadow.camera ); - let valueNode = this.parameters[ name ]; + renderer.setRenderObjectFunction( currentRenderObjectFunction ); - if ( valueNode ) { + // vsm blur pass - if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput(); + if ( light.isPointLight !== true && shadowType === VSMShadowMap ) { - valueNode.events.removeEventListener( 'refresh', this.onRefresh ); + this.vsmPass( renderer ); } - return this; + renderer.setRenderTarget( currentRenderTarget ); - } + scene.overrideMaterial = currentOverrideMaterial; - clearParameters() { + } - for ( const name of Object.keys( this.parameters ) ) { + vsmPass( renderer ) { - this.deleteParameter( name ); + const { shadow } = this; - } + this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height ); + this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height ); - this.needsUpdate = true; + renderer.setRenderTarget( this.vsmShadowMapVertical ); + _quadMesh$1.material = this.vsmMaterialVertical; + _quadMesh$1.render( renderer ); - return this; + renderer.setRenderTarget( this.vsmShadowMapHorizontal ); + _quadMesh$1.material = this.vsmMaterialHorizontal; + _quadMesh$1.render( renderer ); } - call( name, ...params ) { - - const object = this.getObject(); - const method = object[ name ]; + dispose() { - if ( typeof method === 'function' ) { + this.shadowMap.dispose(); + this.shadowMap = null; - return method( ...params ); + if ( this.vsmShadowMapVertical !== null ) { - } + this.vsmShadowMapVertical.dispose(); + this.vsmShadowMapVertical = null; - } + this.vsmMaterialVertical.dispose(); + this.vsmMaterialVertical = null; - async callAsync( name, ...params ) { + } - const object = this.getObject(); - const method = object[ name ]; + if ( this.vsmShadowMapHorizontal !== null ) { - if ( typeof method === 'function' ) { + this.vsmShadowMapHorizontal.dispose(); + this.vsmShadowMapHorizontal = null; - return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params ); + this.vsmMaterialHorizontal.dispose(); + this.vsmMaterialHorizontal = null; } + this.updateBeforeType = NodeUpdateType.NONE; + } - getNodeType( builder ) { + updateBefore( frame ) { - return this.getDefaultOutputNode().getNodeType( builder ); + const { shadow } = this; - } + const needsUpdate = shadow.needsUpdate || shadow.autoUpdate; - refresh( output = null ) { + if ( needsUpdate ) { - if ( output !== null ) { + this.updateShadow( frame ); - this.getOutput( output ).refresh(); + if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) { - } else { + shadow.needsUpdate = false; - this._refresh(); + } } } - getObject() { +} - if ( this.needsUpdate ) this.dispose(); - if ( this._object !== null ) return this._object; +const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) ); - // +class AnalyticLightNode extends LightingNode { - const refresh = () => this.refresh(); - const setOutput = ( id, value ) => this.setOutput( id, value ); + static get type() { - const parameters = new Parameters( this ); + return 'AnalyticLightNode'; - const THREE = global.get( 'THREE' ); - const TSL = global.get( 'TSL' ); + } - const method = this.getMethod( this.codeNode ); - const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ]; + constructor( light = null ) { - this._object = method( ...params ); + super(); - const layout = this._object.layout; + this.updateType = NodeUpdateType.FRAME; - if ( layout ) { + this.light = light; - if ( layout.cache === false ) { + this.color = new Color(); + this.colorNode = uniform( this.color ).setGroup( renderGroup ); - this._local.clear(); + this.baseColorNode = null; - } + this.shadowNode = null; + this.shadowColorNode = null; - // default output - this._output.outputType = layout.outputType || null; + this.isAnalyticLightNode = true; - if ( Array.isArray( layout.elements ) ) { + } - for ( const element of layout.elements ) { + getCacheKey() { - const id = element.id || element.name; + return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 ); - if ( element.inputType ) { + } - if ( this.getParameter( id ) === undefined ) this.setParameter( id, null ); + getHash() { - this.getParameter( id ).inputType = element.inputType; + return this.light.uuid; - } + } - if ( element.outputType ) { + setupShadow( builder ) { - if ( this.getOutput( id ) === undefined ) this.setOutput( id, null ); + const { renderer } = builder; - this.getOutput( id ).outputType = element.outputType; + if ( renderer.shadowMap.enabled === false ) return; - } + let shadowColorNode = this.shadowColorNode; - } + if ( shadowColorNode === null ) { - } + const shadowNode = shadow( this.light ); - } + this.shadowNode = shadowNode; - return this._object; + this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode ); - } + this.baseColorNode = this.colorNode; - deserialize( data ) { + } - super.deserialize( data ); - - for ( const name in this.parameters ) { - - let valueNode = this.parameters[ name ]; - - if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput(); - - valueNode.events.addEventListener( 'refresh', this.onRefresh ); + // - } + this.colorNode = shadowColorNode; } - getLayout() { + setup( builder ) { - return this.getObject().layout; + this.colorNode = this.baseColorNode || this.colorNode; - } + if ( this.light.castShadow ) { - getDefaultOutputNode() { + if ( builder.object.receiveShadow ) { - const output = this.getDefaultOutput().value; + this.setupShadow( builder ); - if ( output && output.isNode ) { + } - return output; + } else if ( this.shadowNode !== null ) { - } + this.shadowNode.dispose(); - return float(); + } } - getDefaultOutput() { + update( /*frame*/ ) { - return this._exec()._output; + const { light } = this; - } + this.color.copy( light.color ).multiplyScalar( light.intensity ); - getMethod() { + } - if ( this.needsUpdate ) this.dispose(); - if ( this._method !== null ) return this._method; +} - // +const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => { - const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ]; - const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ]; + const { lightDistance, cutoffDistance, decayExponent } = inputs; - const properties = interfaceProps.join( ', ' ); - const declarations = 'var ' + properties + '; var output = {};\n'; - const returns = '\nreturn { ...output, ' + properties + ' };'; + // based upon Frostbite 3 Moving to Physically-based Rendering + // page 32, equation 26: E[window1] + // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal(); - const code = declarations + this.codeNode.code + returns; + return cutoffDistance.greaterThan( 0 ).select( + distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ), + distanceFalloff + ); - // +} ); // validated - this._method = new Function( ...parametersProps, code ); +const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => { - return this._method; + const lightingModel = builder.context.lightingModel; - } + const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode - dispose() { + const lightDirection = lVector.normalize(); + const lightDistance = lVector.length(); - if ( this._method === null ) return; + const lightAttenuation = getDistanceAttenuation( { + lightDistance, + cutoffDistance, + decayExponent + } ); - if ( this._object && typeof this._object.dispose === 'function' ) { + const lightColor = color.mul( lightAttenuation ); - this._object.dispose(); + const reflectedLight = builder.context.reflectedLight; - } + lightingModel.direct( { + lightDirection, + lightColor, + reflectedLight + }, builder.stack, builder ); - this._method = null; - this._object = null; - this._source = null; - this._value = null; - this._needsOutputUpdate = true; - this._output.value = null; - this._outputs = {}; +} ); - } +class PointLightNode extends AnalyticLightNode { - setup() { + static get type() { - return this.getDefaultOutputNode(); + return 'PointLightNode'; } - getCacheKey( force ) { - - const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ]; - - for ( const param in this.parameters ) { - - values.push( this.parameters[ param ].getCacheKey( force ) ); + constructor( light = null ) { - } + super( light ); - return hashArray( values ); + this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup ); + this.decayExponentNode = uniform( 0 ).setGroup( renderGroup ); } - set needsUpdate( value ) { - - if ( value === true ) this.dispose(); + update( frame ) { - } + const { light } = this; - get needsUpdate() { + super.update( frame ); - return this.source !== this._source; + this.cutoffDistanceNode.value = light.distance; + this.decayExponentNode.value = light.decay; } - _exec() { + setup() { - if ( this.codeNode === null ) return this; + directPointLight( { + color: this.colorNode, + lightViewPosition: lightViewPosition( this.light ), + cutoffDistance: this.cutoffDistanceNode, + decayExponent: this.decayExponentNode + } ).append(); - if ( this._needsOutputUpdate === true ) { + } - this._value = this.call( 'main' ); +} - this._needsOutputUpdate = false; +const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => { - } + const uv = coord.mul( 2.0 ); - this._output.value = this._value; + const cx = uv.x.floor(); + const cy = uv.y.floor(); + const result = cx.add( cy ).mod( 2.0 ); - return this; + return result.sign(); - } +} ); - _refresh() { +// Three.js Transpiler +// https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl - this.needsUpdate = true; - this._exec(); - this._output.refresh(); +const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => { - } + const f = float( f_immutable ).toVar(); + const t = float( t_immutable ).toVar(); + const b = bool( b_immutable ).toVar(); -} + return select( b, t, f ); -const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ); +} ).setLayout( { + name: 'mx_select', + type: 'float', + inputs: [ + { name: 'b', type: 'bool' }, + { name: 't', type: 'float' }, + { name: 'f', type: 'float' } + ] +} ); -class FogNode extends Node { +const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => { - static get type() { + const b = bool( b_immutable ).toVar(); + const val = float( val_immutable ).toVar(); - return 'FogNode'; + return select( b, val.negate(), val ); - } +} ).setLayout( { + name: 'mx_negate_if', + type: 'float', + inputs: [ + { name: 'val', type: 'float' }, + { name: 'b', type: 'bool' } + ] +} ); - constructor( colorNode, factorNode ) { +const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { - super( 'float' ); + const x = float( x_immutable ).toVar(); - this.isFogNode = true; + return int( floor( x ) ); - this.colorNode = colorNode; - this.factorNode = factorNode; +} ).setLayout( { + name: 'mx_floor', + type: 'int', + inputs: [ + { name: 'x', type: 'float' } + ] +} ); - } +const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => { - getViewZNode( builder ) { + const x = float( x_immutable ).toVar(); + i.assign( mx_floor( x ) ); - let viewZ; + return x.sub( float( i ) ); - const getViewZ = builder.context.getViewZ; +} ); - if ( getViewZ !== undefined ) { +const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => { - viewZ = getViewZ( this ); + const t = float( t_immutable ).toVar(); + const s = float( s_immutable ).toVar(); + const v3 = float( v3_immutable ).toVar(); + const v2 = float( v2_immutable ).toVar(); + const v1 = float( v1_immutable ).toVar(); + const v0 = float( v0_immutable ).toVar(); + const s1 = float( sub( 1.0, s ) ).toVar(); - } + return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ); - return ( viewZ || positionView.z ).negate(); +} ).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' } + ] +} ); - } +const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => { - setup() { + const t = float( t_immutable ).toVar(); + const s = float( s_immutable ).toVar(); + const v3 = vec3( v3_immutable ).toVar(); + const v2 = vec3( v2_immutable ).toVar(); + const v1 = vec3( v1_immutable ).toVar(); + const v0 = vec3( v0_immutable ).toVar(); + const s1 = float( sub( 1.0, s ) ).toVar(); - return this.factorNode; + return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ); - } +} ).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' } + ] +} ); -} +const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] ); -const fog = /*@__PURE__*/ nodeProxy( FogNode ); +const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => { -class FogRangeNode extends FogNode { + const r = float( r_immutable ).toVar(); + const t = float( t_immutable ).toVar(); + const s = float( s_immutable ).toVar(); + const v7 = float( v7_immutable ).toVar(); + const v6 = float( v6_immutable ).toVar(); + const v5 = float( v5_immutable ).toVar(); + const v4 = float( v4_immutable ).toVar(); + const v3 = float( v3_immutable ).toVar(); + const v2 = float( v2_immutable ).toVar(); + const v1 = float( v1_immutable ).toVar(); + const v0 = float( v0_immutable ).toVar(); + const s1 = float( sub( 1.0, s ) ).toVar(); + const t1 = float( sub( 1.0, t ) ).toVar(); + const r1 = float( sub( 1.0, r ) ).toVar(); - static get type() { + return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) ); - return 'FogRangeNode'; +} ).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' } + ] +} ); - } +const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => { - constructor( colorNode, nearNode, farNode ) { + const r = float( r_immutable ).toVar(); + const t = float( t_immutable ).toVar(); + const s = float( s_immutable ).toVar(); + const v7 = vec3( v7_immutable ).toVar(); + const v6 = vec3( v6_immutable ).toVar(); + const v5 = vec3( v5_immutable ).toVar(); + const v4 = vec3( v4_immutable ).toVar(); + const v3 = vec3( v3_immutable ).toVar(); + const v2 = vec3( v2_immutable ).toVar(); + const v1 = vec3( v1_immutable ).toVar(); + const v0 = vec3( v0_immutable ).toVar(); + const s1 = float( sub( 1.0, s ) ).toVar(); + const t1 = float( sub( 1.0, t ) ).toVar(); + const r1 = float( sub( 1.0, r ) ).toVar(); - super( colorNode ); + return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) ); - this.isFogRangeNode = true; +} ).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' } + ] +} ); - this.nearNode = nearNode; - this.farNode = farNode; +const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] ); - } +const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => { - setup( builder ) { + const y = float( y_immutable ).toVar(); + const x = float( x_immutable ).toVar(); + const hash = uint( hash_immutable ).toVar(); + const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar(); + const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar(); + const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar(); - const viewZ = this.getViewZNode( builder ); + return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) ); - return smoothstep( this.nearNode, this.farNode, viewZ ); +} ).setLayout( { + name: 'mx_gradient_float_0', + type: 'float', + inputs: [ + { name: 'hash', type: 'uint' }, + { name: 'x', type: 'float' }, + { name: 'y', type: 'float' } + ] +} ); - } +const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => { -} + const z = float( z_immutable ).toVar(); + const y = float( y_immutable ).toVar(); + const x = float( x_immutable ).toVar(); + const hash = uint( hash_immutable ).toVar(); + const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar(); + const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar(); + const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar(); -const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode ); + return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) ); -class FogExp2Node extends FogNode { +} ).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' } + ] +} ); - static get type() { +const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] ); - return 'FogExp2Node'; +const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => { - } + const y = float( y_immutable ).toVar(); + const x = float( x_immutable ).toVar(); + const hash = uvec3( hash_immutable ).toVar(); - constructor( colorNode, densityNode ) { + return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) ); - super( colorNode ); +} ).setLayout( { + name: 'mx_gradient_vec3_0', + type: 'vec3', + inputs: [ + { name: 'hash', type: 'uvec3' }, + { name: 'x', type: 'float' }, + { name: 'y', type: 'float' } + ] +} ); - this.isFogExp2Node = true; +const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => { - this.densityNode = densityNode; + const z = float( z_immutable ).toVar(); + const y = float( y_immutable ).toVar(); + const x = float( x_immutable ).toVar(); + const hash = uvec3( hash_immutable ).toVar(); - } + return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) ); - setup( builder ) { +} ).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' } + ] +} ); - const viewZ = this.getViewZNode( builder ); - const density = this.densityNode; +const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] ); - return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus(); +const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { - } + const v = float( v_immutable ).toVar(); -} + return mul( 0.6616, v ); -const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node ); +} ).setLayout( { + name: 'mx_gradient_scale2d_0', + type: 'float', + inputs: [ + { name: 'v', type: 'float' } + ] +} ); -let min = null; -let max = null; +const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { -class RangeNode extends Node { + const v = float( v_immutable ).toVar(); - static get type() { + return mul( 0.9820, v ); - return 'RangeNode'; +} ).setLayout( { + name: 'mx_gradient_scale3d_0', + type: 'float', + inputs: [ + { name: 'v', type: 'float' } + ] +} ); - } +const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { - constructor( minNode = float(), maxNode = float() ) { + const v = vec3( v_immutable ).toVar(); - super(); + return mul( 0.6616, v ); - this.minNode = minNode; - this.maxNode = maxNode; +} ).setLayout( { + name: 'mx_gradient_scale2d_1', + type: 'vec3', + inputs: [ + { name: 'v', type: 'vec3' } + ] +} ); - } +const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] ); - getVectorLength( builder ) { +const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { - const minLength = builder.getTypeLength( getValueType( this.minNode.value ) ); - const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) ); + const v = vec3( v_immutable ).toVar(); - return minLength > maxLength ? minLength : maxLength; + return mul( 0.9820, v ); - } +} ).setLayout( { + name: 'mx_gradient_scale3d_1', + type: 'vec3', + inputs: [ + { name: 'v', type: 'vec3' } + ] +} ); - getNodeType( builder ) { +const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] ); - return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float'; +const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => { - } + const k = int( k_immutable ).toVar(); + const x = uint( x_immutable ).toVar(); - setup( builder ) { + return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) ); - const object = builder.object; +} ).setLayout( { + name: 'mx_rotl32', + type: 'uint', + inputs: [ + { name: 'x', type: 'uint' }, + { name: 'k', type: 'int' } + ] +} ); - let output = null; +const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => { - if ( object.count > 1 ) { + a.subAssign( c ); + a.bitXorAssign( mx_rotl32( c, int( 4 ) ) ); + c.addAssign( b ); + b.subAssign( a ); + b.bitXorAssign( mx_rotl32( a, int( 6 ) ) ); + a.addAssign( c ); + c.subAssign( b ); + c.bitXorAssign( mx_rotl32( b, int( 8 ) ) ); + b.addAssign( a ); + a.subAssign( c ); + a.bitXorAssign( mx_rotl32( c, int( 16 ) ) ); + c.addAssign( b ); + b.subAssign( a ); + b.bitXorAssign( mx_rotl32( a, int( 19 ) ) ); + a.addAssign( c ); + c.subAssign( b ); + c.bitXorAssign( mx_rotl32( b, int( 4 ) ) ); + b.addAssign( a ); - const minValue = this.minNode.value; - const maxValue = this.maxNode.value; +} ); - const minLength = builder.getTypeLength( getValueType( minValue ) ); - const maxLength = builder.getTypeLength( getValueType( maxValue ) ); +const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => { - min = min || new Vector4(); - max = max || new Vector4(); - - min.setScalar( 0 ); - max.setScalar( 0 ); + const c = uint( c_immutable ).toVar(); + const b = uint( b_immutable ).toVar(); + const a = uint( a_immutable ).toVar(); + c.bitXorAssign( b ); + c.subAssign( mx_rotl32( b, int( 14 ) ) ); + a.bitXorAssign( c ); + a.subAssign( mx_rotl32( c, int( 11 ) ) ); + b.bitXorAssign( a ); + b.subAssign( mx_rotl32( a, int( 25 ) ) ); + c.bitXorAssign( b ); + c.subAssign( mx_rotl32( b, int( 16 ) ) ); + a.bitXorAssign( c ); + a.subAssign( mx_rotl32( c, int( 4 ) ) ); + b.bitXorAssign( a ); + b.subAssign( mx_rotl32( a, int( 14 ) ) ); + c.bitXorAssign( b ); + c.subAssign( mx_rotl32( b, int( 24 ) ) ); - if ( minLength === 1 ) min.setScalar( minValue ); - else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b ); - else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 ); + return c; - if ( maxLength === 1 ) max.setScalar( maxValue ); - else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b ); - else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 ); +} ).setLayout( { + name: 'mx_bjfinal', + type: 'uint', + inputs: [ + { name: 'a', type: 'uint' }, + { name: 'b', type: 'uint' }, + { name: 'c', type: 'uint' } + ] +} ); - const stride = 4; +const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => { - const length = stride * object.count; - const array = new Float32Array( length ); + const bits = uint( bits_immutable ).toVar(); - for ( let i = 0; i < length; i ++ ) { + return float( bits ).div( float( uint( int( 0xffffffff ) ) ) ); - const index = i % stride; +} ).setLayout( { + name: 'mx_bits_to_01', + type: 'float', + inputs: [ + { name: 'bits', type: 'uint' } + ] +} ); - const minElementValue = min.getComponent( index ); - const maxElementValue = max.getComponent( index ); +const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => { - array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() ); + const t = float( t_immutable ).toVar(); - } + return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) ); - const nodeType = this.getNodeType( builder ); +} ).setLayout( { + name: 'mx_fade', + type: 'float', + inputs: [ + { name: 't', type: 'float' } + ] +} ); - if ( object.count <= 4096 ) { +const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { - output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType ); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 1 ) ).toVar(); + const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar(); - } else { + return mx_bjfinal( seed.add( uint( x ) ), seed, seed ); - // TODO: Improve anonymous buffer attribute creation removing this part - const bufferAttribute = new InstancedBufferAttribute( array, 4 ); - builder.geometry.setAttribute( '__range' + this.id, bufferAttribute ); +} ).setLayout( { + name: 'mx_hash_int_0', + type: 'uint', + inputs: [ + { name: 'x', type: 'int' } + ] +} ); - output = instancedBufferAttribute( bufferAttribute ).convert( nodeType ); +const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => { - } + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 2 ) ).toVar(); + const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); + a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); + a.addAssign( uint( x ) ); + b.addAssign( uint( y ) ); - } else { + return mx_bjfinal( a, b, c ); - output = float( 0 ); +} ).setLayout( { + name: 'mx_hash_int_1', + type: 'uint', + inputs: [ + { name: 'x', type: 'int' }, + { name: 'y', type: 'int' } + ] +} ); - } +const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => { - return output; + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 3 ) ).toVar(); + const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); + a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); + a.addAssign( uint( x ) ); + b.addAssign( uint( y ) ); + c.addAssign( uint( z ) ); - } + return mx_bjfinal( a, b, c ); -} +} ).setLayout( { + name: 'mx_hash_int_2', + type: 'uint', + inputs: [ + { name: 'x', type: 'int' }, + { name: 'y', type: 'int' }, + { name: 'z', type: 'int' } + ] +} ); -const range = /*@__PURE__*/ nodeProxy( RangeNode ); +const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => { -const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => { + const xx = int( xx_immutable ).toVar(); + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 4 ) ).toVar(); + const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); + a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); + a.addAssign( uint( x ) ); + b.addAssign( uint( y ) ); + c.addAssign( uint( z ) ); + mx_bjmix( a, b, c ); + a.addAssign( uint( xx ) ); - return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z ); + return mx_bjfinal( a, b, 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' } + ] } ); -const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => { +const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => { - const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare ); + const yy = int( yy_immutable ).toVar(); + const xx = int( xx_immutable ).toVar(); + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const len = uint( uint( 5 ) ).toVar(); + const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); + a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); + a.addAssign( uint( x ) ); + b.addAssign( uint( y ) ); + c.addAssign( uint( z ) ); + mx_bjmix( a, b, c ); + a.addAssign( uint( xx ) ); + b.addAssign( uint( yy ) ); - const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); - const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup ); + return mx_bjfinal( a, b, c ); - const texelSize = vec2( 1 ).div( mapSize ); - const dx0 = texelSize.x.negate().mul( radius ); - const dy0 = texelSize.y.negate().mul( radius ); - const dx1 = texelSize.x.mul( radius ); - const dy1 = texelSize.y.mul( radius ); - const dx2 = dx0.div( 2 ); - const dy2 = dy0.div( 2 ); - const dx3 = dx1.div( 2 ); - const dy3 = dy1.div( 2 ); +} ).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' } + ] +} ); - return add( - depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy, shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ), - depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z ) - ).mul( 1 / 17 ); +const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] ); -} ); +const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => { -const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => { + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const h = uint( mx_hash_int( x, y ) ).toVar(); + const result = uvec3().toVar(); + result.x.assign( h.bitAnd( int( 0xFF ) ) ); + result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) ); + result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) ); - const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare ); + return result; - const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); +} ).setLayout( { + name: 'mx_hash_vec3_0', + type: 'uvec3', + inputs: [ + { name: 'x', type: 'int' }, + { name: 'y', type: 'int' } + ] +} ); - const texelSize = vec2( 1 ).div( mapSize ); - const dx = texelSize.x; - const dy = texelSize.y; +const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => { - const uv = shadowCoord.xy; - const f = fract( uv.mul( mapSize ).add( 0.5 ) ); - uv.subAssign( f.mul( texelSize ) ); + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const h = uint( mx_hash_int( x, y, z ) ).toVar(); + const result = uvec3().toVar(); + result.x.assign( h.bitAnd( int( 0xFF ) ) ); + result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) ); + result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) ); - return add( - depthCompare( uv, shadowCoord.z ), - depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ), - depthCompare( uv.add( texelSize ), shadowCoord.z ), - mix( - depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ), - f.x - ), - mix( - depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ), - f.x - ), - mix( - depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ), - f.y - ), - mix( - depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ), - f.y - ), - mix( - mix( - depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ), - f.x - ), - mix( - depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ), - depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ), - f.x - ), - f.y - ) - ).mul( 1 / 9 ); + return result; +} ).setLayout( { + name: 'mx_hash_vec3_1', + type: 'uvec3', + inputs: [ + { name: 'x', type: 'int' }, + { name: 'y', type: 'int' }, + { name: 'z', type: 'int' } + ] } ); -// VSM - -const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => { +const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] ); - const occlusion = float( 1 ).toVar(); +const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg; + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const fx = float( mx_floorfrac( p.x, X ) ).toVar(); + const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); + const u = float( mx_fade( fx ) ).toVar(); + const v = float( mx_fade( fy ) ).toVar(); + const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar(); - const hardShadow = step( shadowCoord.z, distribution.x ); + return mx_gradient_scale2d( result ); - If( hardShadow.notEqual( float( 1.0 ) ), () => { +} ).setLayout( { + name: 'mx_perlin_noise_float_0', + type: 'float', + inputs: [ + { name: 'p', type: 'vec2' } + ] +} ); - const distance = shadowCoord.z.sub( distribution.x ); - const variance = max$1( 0, distribution.y.mul( distribution.y ) ); - let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality - softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) ); - occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) ); +const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - } ); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const fx = float( mx_floorfrac( p.x, X ) ).toVar(); + const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); + const fz = float( mx_floorfrac( p.z, Z ) ).toVar(); + const u = float( mx_fade( fx ) ).toVar(); + const v = float( mx_fade( fy ) ).toVar(); + const w = float( mx_fade( fz ) ).toVar(); + const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar(); - return occlusion; + return mx_gradient_scale3d( result ); +} ).setLayout( { + name: 'mx_perlin_noise_float_1', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' } + ] } ); -const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => { - - const mean = float( 0 ).toVar(); - const squaredMean = float( 0 ).toVar(); +const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] ); - const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) ); - const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) ); +const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => { + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const fx = float( mx_floorfrac( p.x, X ) ).toVar(); + const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); + const u = float( mx_fade( fx ) ).toVar(); + const v = float( mx_fade( fy ) ).toVar(); + const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar(); - const uvOffset = uvStart.add( float( i ).mul( uvStride ) ); + return mx_gradient_scale2d( result ); - const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x; - mean.addAssign( depth ); - squaredMean.addAssign( depth.mul( depth ) ); +} ).setLayout( { + name: 'mx_perlin_noise_vec3_0', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec2' } + ] +} ); - } ); +const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - mean.divAssign( samples ); - squaredMean.divAssign( samples ); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const fx = float( mx_floorfrac( p.x, X ) ).toVar(); + const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); + const fz = float( mx_floorfrac( p.z, Z ) ).toVar(); + const u = float( mx_fade( fx ) ).toVar(); + const v = float( mx_fade( fy ) ).toVar(); + const w = float( mx_fade( fz ) ).toVar(); + const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar(); - const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) ); - return vec2( mean, std_dev ); + return mx_gradient_scale3d( result ); +} ).setLayout( { + name: 'mx_perlin_noise_vec3_1', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] } ); -const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => { - - const mean = float( 0 ).toVar(); - const squaredMean = float( 0 ).toVar(); +const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] ); - const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) ); - const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) ); +const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => { + const p = float( p_immutable ).toVar(); + const ix = int( mx_floor( p ) ).toVar(); - const uvOffset = uvStart.add( float( i ).mul( uvStride ) ); + return mx_bits_to_01( mx_hash_int( ix ) ); - const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) ); - mean.addAssign( distribution.x ); - squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) ); +} ).setLayout( { + name: 'mx_cell_noise_float_0', + type: 'float', + inputs: [ + { name: 'p', type: 'float' } + ] +} ); - } ); +const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - mean.divAssign( samples ); - squaredMean.divAssign( samples ); + const p = vec2( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); - const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) ); - return vec2( mean, std_dev ); + return mx_bits_to_01( mx_hash_int( ix, iy ) ); +} ).setLayout( { + name: 'mx_cell_noise_float_1', + type: 'float', + inputs: [ + { name: 'p', type: 'vec2' } + ] } ); -const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ]; +const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { -// + const p = vec3( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); + const iz = int( mx_floor( p.z ) ).toVar(); -let _overrideMaterial = null; -const _quadMesh$1 = /*@__PURE__*/ new QuadMesh(); + return mx_bits_to_01( mx_hash_int( ix, iy, iz ) ); -class ShadowNode extends Node { +} ).setLayout( { + name: 'mx_cell_noise_float_2', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' } + ] +} ); - static get type() { +const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - return 'ShadowNode'; + const p = vec4( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); + const iz = int( mx_floor( p.z ) ).toVar(); + const iw = int( mx_floor( p.w ) ).toVar(); - } + return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) ); - constructor( light, shadow = null ) { +} ).setLayout( { + name: 'mx_cell_noise_float_3', + type: 'float', + inputs: [ + { name: 'p', type: 'vec4' } + ] +} ); - super(); +const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] ); - this.light = light; - this.shadow = shadow || light.shadow; +const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - this.shadowMap = null; + const p = float( p_immutable ).toVar(); + const ix = int( mx_floor( p ) ).toVar(); - this.vsmShadowMapVertical = null; - this.vsmShadowMapHorizontal = null; + return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) ); - this.vsmMaterialVertical = null; - this.vsmMaterialHorizontal = null; +} ).setLayout( { + name: 'mx_cell_noise_vec3_0', + type: 'vec3', + inputs: [ + { name: 'p', type: 'float' } + ] +} ); - this.updateBeforeType = NodeUpdateType.RENDER; - this._node = null; +const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - this.isShadowNode = true; + const p = vec2( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); - } + return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) ); - setupShadow( builder ) { +} ).setLayout( { + name: 'mx_cell_noise_vec3_1', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec2' } + ] +} ); - const { object, renderer } = builder; +const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - if ( _overrideMaterial === null ) { - - _overrideMaterial = new NodeMaterial(); - _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 ); - _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode - _overrideMaterial.name = 'ShadowMaterial'; - - } - - const shadow = this.shadow; - const shadowMapType = renderer.shadowMap.type; - - const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height ); - depthTexture.compareFunction = LessCompare; + const p = vec3( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); + const iz = int( mx_floor( p.z ) ).toVar(); - const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height ); - shadowMap.depthTexture = depthTexture; + return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) ); - shadow.camera.updateProjectionMatrix(); +} ).setLayout( { + name: 'mx_cell_noise_vec3_2', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] +} ); - // VSM +const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { - if ( shadowMapType === VSMShadowMap ) { + const p = vec4( p_immutable ).toVar(); + const ix = int( mx_floor( p.x ) ).toVar(); + const iy = int( mx_floor( p.y ) ).toVar(); + const iz = int( mx_floor( p.z ) ).toVar(); + const iw = int( mx_floor( p.w ) ).toVar(); - depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare() + return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) ); - this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } ); - this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } ); +} ).setLayout( { + name: 'mx_cell_noise_vec3_3', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec4' } + ] +} ); - const shadowPassVertical = texture( depthTexture ); - const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture ); +const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] ); - const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup ); - const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup ); - const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup ); +const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { - let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() ); - material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() ); - material.name = 'VSMVertical'; + const diminish = float( diminish_immutable ).toVar(); + const lacunarity = float( lacunarity_immutable ).toVar(); + const octaves = int( octaves_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const result = float( 0.0 ).toVar(); + const amplitude = float( 1.0 ).toVar(); - material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() ); - material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() ); - material.name = 'VSMHorizontal'; + Loop( octaves, () => { - } + result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) ); + amplitude.mulAssign( diminish ); + p.mulAssign( lacunarity ); - // + } ); - const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup ); - const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup ); - const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup ); + return result; - const position = object.material.shadowPositionNode || positionWorld; +} ).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' } + ] +} ); - let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) ); +const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { - let coordZ; + const diminish = float( diminish_immutable ).toVar(); + const lacunarity = float( lacunarity_immutable ).toVar(); + const octaves = int( octaves_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const result = vec3( 0.0 ).toVar(); + const amplitude = float( 1.0 ).toVar(); - if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) { + Loop( octaves, () => { - shadowCoord = shadowCoord.xyz.div( shadowCoord.w ); + result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) ); + amplitude.mulAssign( diminish ); + p.mulAssign( lacunarity ); - coordZ = shadowCoord.z; + } ); - if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) { + return result; - coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ] +} ).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' } + ] +} ); - } +const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { - } else { + const diminish = float( diminish_immutable ).toVar(); + const lacunarity = float( lacunarity_immutable ).toVar(); + const octaves = int( octaves_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); - const w = shadowCoord.w; - shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z + return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ); - // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get - // updated to use the shadow camera. So, we have to declare our own "local" ones here. - // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here? - const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near ); - const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far ); +} ).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' } + ] +} ); - coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal ); +const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { - } + const diminish = float( diminish_immutable ).toVar(); + const lacunarity = float( lacunarity_immutable ).toVar(); + const octaves = int( octaves_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar(); + const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar(); - shadowCoord = vec3( - shadowCoord.x, - shadowCoord.y.oneMinus(), // follow webgpu standards - coordZ.add( bias ) - ); + return vec4( c, f ); - const frustumTest = shadowCoord.x.greaterThanEqual( 0 ) - .and( shadowCoord.x.lessThanEqual( 1 ) ) - .and( shadowCoord.y.greaterThanEqual( 0 ) ) - .and( shadowCoord.y.lessThanEqual( 1 ) ) - .and( shadowCoord.z.lessThanEqual( 1 ) ); +} ).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' } + ] +} ); - // +const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => { - const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null; + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const yoff = int( yoff_immutable ).toVar(); + const xoff = int( xoff_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const p = vec2( p_immutable ).toVar(); + const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar(); + const off = vec2( tmp.x, tmp.y ).toVar(); + off.subAssign( 0.5 ); + off.mulAssign( jitter ); + off.addAssign( 0.5 ); + const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar(); + const diff = vec2( cellpos.sub( p ) ).toVar(); - if ( filterFn === null ) { + If( metric.equal( int( 2 ) ), () => { - throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' ); + return abs( diff.x ).add( abs( diff.y ) ); - } + } ); - const shadowColor = texture( shadowMap.texture, shadowCoord ); - const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) ); + If( metric.equal( int( 3 ) ), () => { - this.shadowMap = shadowMap; - this.shadow.map = shadowMap; + return max$1( abs( diff.x ), abs( diff.y ) ); - return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ); + } ); - } + return dot( diff, diff ); - setup( builder ) { +} ).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' } + ] +} ); - if ( builder.renderer.shadowMap.enabled === false ) return; +const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => { - return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) ); + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const zoff = int( zoff_immutable ).toVar(); + const yoff = int( yoff_immutable ).toVar(); + const xoff = int( xoff_immutable ).toVar(); + const z = int( z_immutable ).toVar(); + const y = int( y_immutable ).toVar(); + const x = int( x_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar(); + off.subAssign( 0.5 ); + off.mulAssign( jitter ); + off.addAssign( 0.5 ); + const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar(); + const diff = vec3( cellpos.sub( p ) ).toVar(); - } + If( metric.equal( int( 2 ) ), () => { - updateShadow( frame ) { + return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) ); - const { shadowMap, light, shadow } = this; - const { renderer, scene, camera } = frame; + } ); - const shadowType = renderer.shadowMap.type; + If( metric.equal( int( 3 ) ), () => { - const depthVersion = shadowMap.depthTexture.version; - this._depthVersionCached = depthVersion; + return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) ); - const currentOverrideMaterial = scene.overrideMaterial; + } ); - scene.overrideMaterial = _overrideMaterial; + return dot( diff, diff ); - shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height ); +} ).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' } + ] +} ); - shadow.updateMatrices( light ); - shadow.camera.layers.mask = camera.layers.mask; +const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] ); - const currentRenderTarget = renderer.getRenderTarget(); - const currentRenderObjectFunction = renderer.getRenderObjectFunction(); +const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - renderer.setRenderObjectFunction( ( object, ...params ) => { + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); + const sqdist = float( 1e6 ).toVar(); - if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) { + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - renderer.renderObject( object, ...params ); + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - } + const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); + sqdist.assign( min$1( sqdist, dist ) ); } ); - renderer.setRenderTarget( shadowMap ); - renderer.render( scene, shadow.camera ); + } ); - renderer.setRenderObjectFunction( currentRenderObjectFunction ); + If( metric.equal( int( 0 ) ), () => { - // vsm blur pass + sqdist.assign( sqrt( sqdist ) ); - if ( light.isPointLight !== true && shadowType === VSMShadowMap ) { + } ); - this.vsmPass( renderer ); + return sqdist; - } +} ).setLayout( { + name: 'mx_worley_noise_float_0', + type: 'float', + inputs: [ + { name: 'p', type: 'vec2' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - renderer.setRenderTarget( currentRenderTarget ); +const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - scene.overrideMaterial = currentOverrideMaterial; + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); + const sqdist = vec2( 1e6, 1e6 ).toVar(); - } + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - vsmPass( renderer ) { + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - const { shadow } = this; + const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); - this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height ); - this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height ); + If( dist.lessThan( sqdist.x ), () => { - renderer.setRenderTarget( this.vsmShadowMapVertical ); - _quadMesh$1.material = this.vsmMaterialVertical; - _quadMesh$1.render( renderer ); + sqdist.y.assign( sqdist.x ); + sqdist.x.assign( dist ); - renderer.setRenderTarget( this.vsmShadowMapHorizontal ); - _quadMesh$1.material = this.vsmMaterialHorizontal; - _quadMesh$1.render( renderer ); + } ).ElseIf( dist.lessThan( sqdist.y ), () => { - } + sqdist.y.assign( dist ); - dispose() { + } ); - this.shadowMap.dispose(); - this.shadowMap = null; + } ); - if ( this.vsmShadowMapVertical !== null ) { + } ); - this.vsmShadowMapVertical.dispose(); - this.vsmShadowMapVertical = null; + If( metric.equal( int( 0 ) ), () => { - this.vsmMaterialVertical.dispose(); - this.vsmMaterialVertical = null; + sqdist.assign( sqrt( sqdist ) ); - } + } ); - if ( this.vsmShadowMapHorizontal !== null ) { + return sqdist; - this.vsmShadowMapHorizontal.dispose(); - this.vsmShadowMapHorizontal = null; +} ).setLayout( { + name: 'mx_worley_noise_vec2_0', + type: 'vec2', + inputs: [ + { name: 'p', type: 'vec2' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - this.vsmMaterialHorizontal.dispose(); - this.vsmMaterialHorizontal = null; +const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - } + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec2( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(); + const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); + const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar(); - this.updateBeforeType = NodeUpdateType.NONE; + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - } + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - updateBefore( frame ) { + const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); - const { shadow } = this; + If( dist.lessThan( sqdist.x ), () => { - const needsUpdate = shadow.needsUpdate || shadow.autoUpdate; + sqdist.z.assign( sqdist.y ); + sqdist.y.assign( sqdist.x ); + sqdist.x.assign( dist ); - if ( needsUpdate ) { + } ).ElseIf( dist.lessThan( sqdist.y ), () => { - this.updateShadow( frame ); + sqdist.z.assign( sqdist.y ); + sqdist.y.assign( dist ); - if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) { + } ).ElseIf( dist.lessThan( sqdist.z ), () => { - shadow.needsUpdate = false; + sqdist.z.assign( dist ); - } + } ); - } + } ); - } + } ); -} + If( metric.equal( int( 0 ) ), () => { -const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) ); + sqdist.assign( sqrt( sqdist ) ); -class AnalyticLightNode extends LightingNode { + } ); - static get type() { + return sqdist; - return 'AnalyticLightNode'; +} ).setLayout( { + name: 'mx_worley_noise_vec3_0', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec2' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - } +const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - constructor( light = null ) { + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); + const sqdist = float( 1e6 ).toVar(); - super(); + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - this.updateType = NodeUpdateType.FRAME; + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - this.light = light; + Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { - this.color = new Color(); - this.colorNode = uniform( this.color ).setGroup( renderGroup ); + const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); + sqdist.assign( min$1( sqdist, dist ) ); - this.baseColorNode = null; + } ); - this.shadowNode = null; - this.shadowColorNode = null; + } ); - this.isAnalyticLightNode = true; + } ); - } + If( metric.equal( int( 0 ) ), () => { - getCacheKey() { + sqdist.assign( sqrt( sqdist ) ); - return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 ); + } ); - } + return sqdist; - getHash() { +} ).setLayout( { + name: 'mx_worley_noise_float_1', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - return this.light.uuid; +const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] ); - } +const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - setupShadow( builder ) { + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); + const sqdist = vec2( 1e6, 1e6 ).toVar(); - const { renderer } = builder; + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - if ( renderer.shadowMap.enabled === false ) return; + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - let shadowColorNode = this.shadowColorNode; + Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { - if ( shadowColorNode === null ) { + const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); - const shadowNode = shadow( this.light ); + If( dist.lessThan( sqdist.x ), () => { - this.shadowNode = shadowNode; + sqdist.y.assign( sqdist.x ); + sqdist.x.assign( dist ); - this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode ); + } ).ElseIf( dist.lessThan( sqdist.y ), () => { - this.baseColorNode = this.colorNode; + sqdist.y.assign( dist ); - } + } ); - // + } ); - this.colorNode = shadowColorNode; + } ); - } + } ); - setup( builder ) { + If( metric.equal( int( 0 ) ), () => { - this.colorNode = this.baseColorNode || this.colorNode; + sqdist.assign( sqrt( sqdist ) ); - if ( this.light.castShadow ) { + } ); - if ( builder.object.receiveShadow ) { + return sqdist; - this.setupShadow( builder ); - - } +} ).setLayout( { + name: 'mx_worley_noise_vec2_1', + type: 'vec2', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - } else if ( this.shadowNode !== null ) { +const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] ); - this.shadowNode.dispose(); +const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { - } + const metric = int( metric_immutable ).toVar(); + const jitter = float( jitter_immutable ).toVar(); + const p = vec3( p_immutable ).toVar(); + const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); + const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); + const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar(); - } + Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { - update( /*frame*/ ) { + Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { - const { light } = this; + Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { - this.color.copy( light.color ).multiplyScalar( light.intensity ); + const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); - } + If( dist.lessThan( sqdist.x ), () => { -} + sqdist.z.assign( sqdist.y ); + sqdist.y.assign( sqdist.x ); + sqdist.x.assign( dist ); -const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => { + } ).ElseIf( dist.lessThan( sqdist.y ), () => { - const { lightDistance, cutoffDistance, decayExponent } = inputs; + sqdist.z.assign( sqdist.y ); + sqdist.y.assign( dist ); - // based upon Frostbite 3 Moving to Physically-based Rendering - // page 32, equation 26: E[window1] - // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal(); + } ).ElseIf( dist.lessThan( sqdist.z ), () => { - return cutoffDistance.greaterThan( 0 ).select( - distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ), - distanceFalloff - ); + sqdist.z.assign( dist ); -} ); // validated + } ); -let uniformsLib; + } ); -function getLightData( light ) { + } ); - uniformsLib = uniformsLib || new WeakMap(); + } ); - let uniforms = uniformsLib.get( light ); + If( metric.equal( int( 0 ) ), () => { - if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} ); + sqdist.assign( sqrt( sqdist ) ); - return uniforms; + } ); -} + return sqdist; -function lightPosition( light ) { +} ).setLayout( { + name: 'mx_worley_noise_vec3_1', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'jitter', type: 'float' }, + { name: 'metric', type: 'int' } + ] +} ); - const data = getLightData( light ); +const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] ); - return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) ); +// Three.js Transpiler +// https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl -} -function lightTargetPosition( light ) { +const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => { - const data = getLightData( light ); + const s = hsv.y; + const v = hsv.z; - return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) ); + const result = vec3().toVar(); -} + If( s.lessThan( 0.0001 ), () => { -function lightViewPosition( light ) { + result.assign( vec3( v, v, v ) ); - const data = getLightData( light ); + } ).Else( () => { - return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => { + let h = hsv.x; + h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache + const hi = int( trunc( h ) ); + const f = h.sub( float( hi ) ); + const p = v.mul( s.oneMinus() ); + const q = v.mul( s.mul( f ).oneMinus() ); + const t = v.mul( s.mul( f.oneMinus() ).oneMinus() ); - self.value = self.value || new Vector3(); - self.value.setFromMatrixPosition( light.matrixWorld ); + If( hi.equal( int( 0 ) ), () => { - self.value.applyMatrix4( camera.matrixWorldInverse ); + result.assign( vec3( v, t, p ) ); - } ) ); + } ).ElseIf( hi.equal( int( 1 ) ), () => { -} + result.assign( vec3( q, v, p ) ); -const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) ); + } ).ElseIf( hi.equal( int( 2 ) ), () => { -const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => { + result.assign( vec3( p, v, t ) ); - // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org + } ).ElseIf( hi.equal( int( 3 ) ), () => { - const state = seed.toUint().mul( 747796405 ).add( 2891336453 ); - const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 ); - const result = word.shiftRight( 22 ).bitXor( word ); + result.assign( vec3( p, q, v ) ); - return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1) + } ).ElseIf( hi.equal( int( 4 ) ), () => { -} ); + result.assign( vec3( t, p, v ) ); -// remapping functions https://iquilezles.org/articles/functions/ -const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k ); -const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) ); -const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a ); -const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) ); + } ).Else( () => { -// https://github.com/cabbibo/glsl-tri-noise-3d + result.assign( vec3( v, p, q ) ); + } ); -const tri = /*@__PURE__*/ Fn( ( [ x ] ) => { + } ); - return x.fract().sub( .5 ).abs(); + return result; } ).setLayout( { - name: 'tri', - type: 'float', + name: 'mx_hsvtorgb', + type: 'vec3', inputs: [ - { name: 'x', type: 'float' } + { name: 'hsv', type: 'vec3' } ] } ); -const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => { +const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => { - return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) ); + const c = vec3( c_immutable ).toVar(); + const r = float( c.x ).toVar(); + const g = float( c.y ).toVar(); + const b = float( c.z ).toVar(); + const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar(); + const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar(); + const delta = float( maxcomp.sub( mincomp ) ).toVar(); + const h = float().toVar(), s = float().toVar(), v = float().toVar(); + v.assign( maxcomp ); + + If( maxcomp.greaterThan( 0.0 ), () => { + + s.assign( delta.div( maxcomp ) ); + + } ).Else( () => { + + s.assign( 0.0 ); + + } ); + + If( s.lessThanEqual( 0.0 ), () => { + + h.assign( 0.0 ); + + } ).Else( () => { + + If( r.greaterThanEqual( maxcomp ), () => { + + h.assign( g.sub( b ).div( delta ) ); + + } ).ElseIf( g.greaterThanEqual( maxcomp ), () => { + + h.assign( add( 2.0, b.sub( r ).div( delta ) ) ); + + } ).Else( () => { + + h.assign( add( 4.0, r.sub( g ).div( delta ) ) ); + + } ); + + h.mulAssign( 1.0 / 6.0 ); + + If( h.lessThan( 0.0 ), () => { + + h.addAssign( 1.0 ); + + } ); + + } ); + + return vec3( h, s, v ); } ).setLayout( { - name: 'tri3', + name: 'mx_rgbtohsv', type: 'vec3', inputs: [ - { name: 'p', type: 'vec3' } + { name: 'c', type: 'vec3' } ] } ); -const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => { - - const p = vec3( p_immutable ).toVar(); - const z = float( 1.4 ).toVar(); - const rz = float( 0.0 ).toVar(); - const bp = vec3( p ).toVar(); - - Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => { +// Three.js Transpiler +// https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl - const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar(); - p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) ); - bp.mulAssign( 1.8 ); - z.mulAssign( 1.5 ); - p.mulAssign( 1.2 ); - const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar(); - rz.addAssign( t.div( z ) ); - bp.addAssign( 0.14 ); +const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => { - } ); + const color = vec3( color_immutable ).toVar(); + const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar(); + const linSeg = vec3( color.div( 12.92 ) ).toVar(); + const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar(); - return rz; + return mix( linSeg, powSeg, isAbove ); } ).setLayout( { - name: 'triNoise3D', - type: 'float', + name: 'mx_srgb_texture_to_lin_rec709', + type: 'vec3', inputs: [ - { name: 'p', type: 'vec3' }, - { name: 'spd', type: 'float' }, - { name: 'time', type: 'float' } + { name: 'color', type: 'vec3' } ] } ); -const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time ); -const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime ); -const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId ); +const mx_aastep = ( threshold, value ) => { -// Deprecated + threshold = float( threshold ); + value = float( value ); -const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170 + const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 ); - console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' ); - return time.mul( timeScale ); + return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value ); }; -const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170 +const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() ); +const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' ); +const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' ); - console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' ); - return time.mul( timeScale ); +const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) ); +const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' ); +const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' ); -}; +const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset ); -const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170 +const mx_safepower = ( in1, in2 = 1 ) => { - console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' ); - return deltaTime.mul( timeScale ); + in1 = float( in1 ); + + return in1.abs().pow( in2 ).mul( in1.sign() ); }; -const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 ); -const oscSquare = ( t = time ) => t.fract().round(); -const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs(); -const oscSawtooth = ( t = time ) => t.fract(); +const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot ); -const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => { +const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +//export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => { - return rotate( uv.sub( center ), rotation ).add( center ); + texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type -} ); + const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) ); -const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => { + return noise_vec4.mul( amplitude ).add( pivot ); - const delta = uv.sub( center ); - const delta2 = delta.dot( delta ); - const delta4 = delta2.mul( delta2 ); - const deltaOffset = delta4.mul( strength ); +}; - return uv.add( delta.mul( deltaOffset ) ); +const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -} ); +const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) ); -const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => { +const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); - let worldMatrix; +const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => { - if ( position !== null ) { + // normal is assumed to have unit length - worldMatrix = modelWorldMatrix.toVar(); - worldMatrix[ 3 ][ 0 ] = position.x; - worldMatrix[ 3 ][ 1 ] = position.y; - worldMatrix[ 3 ][ 2 ] = position.z; + const x = normal.x, y = normal.y, z = normal.z; - } else { + // band 0 + let result = shCoefficients.element( 0 ).mul( 0.886227 ); - worldMatrix = modelWorldMatrix; + // band 1 + result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) ); + result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) ); + result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) ); - } + // band 2 + result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) ); + result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) ); + result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) ); + result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) ); + result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) ); - const modelViewMatrix = cameraViewMatrix.mul( worldMatrix ); + return result; - if ( defined( horizontal ) ) { +} ); - modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length(); - modelViewMatrix[ 0 ][ 1 ] = 0; - modelViewMatrix[ 0 ][ 2 ] = 0; +const _clearColor$1 = /*@__PURE__*/ new Color4(); - } +class Background extends DataMap { - if ( defined( vertical ) ) { + constructor( renderer, nodes ) { - modelViewMatrix[ 1 ][ 0 ] = 0; - modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length(); - modelViewMatrix[ 1 ][ 2 ] = 0; + super(); + + this.renderer = renderer; + this.nodes = nodes; } - modelViewMatrix[ 2 ][ 0 ] = 0; - modelViewMatrix[ 2 ][ 1 ] = 0; - modelViewMatrix[ 2 ][ 2 ] = 1; + update( scene, renderList, renderContext ) { - return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal ); + const renderer = this.renderer; + const background = this.nodes.getBackgroundNode( scene ) || scene.background; -} ); + let forceClear = false; -const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => { + if ( background === null ) { - const depth = linearDepth(); - const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth ); - const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv ); + // no background settings, use clear color configuration from the renderer - return finalUV; + renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace ); + _clearColor$1.a = renderer._clearColor.a; -} ); + } else if ( background.isColor === true ) { -/** -* Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments -* depth value and the camera's inverse projection matrix. -* -* @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates. -* @param {float} depth - The fragment's depth value. -* @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix. -* @return {vec3} The fragments position in view space. -*/ -const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => { + // background is an opaque color - let clipSpacePosition; + background.getRGB( _clearColor$1, LinearSRGBColorSpace ); + _clearColor$1.a = 1; - if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) { + forceClear = true; - screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 ); - clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 ); + } else if ( background.isNode === true ) { - } else { + const sceneData = this.get( scene ); + const backgroundNode = background; - clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 ); + _clearColor$1.copy( renderer._clearColor ); - } + let backgroundMesh = sceneData.backgroundMesh; - const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) ); + if ( backgroundMesh === undefined ) { - return viewSpacePosition.xyz.div( viewSpacePosition.w ); + const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), { + // @TODO: Add Texture2D support using node context + getUV: () => normalWorld, + getTextureLevel: () => backgroundBlurriness + } ); -} ); + let viewProj = modelViewProjection(); + viewProj = viewProj.setZ( viewProj.w ); -/** -* Computes a screen position expressed as uv coordinates based on a fragment's position in view space -* and the camera's projection matrix -* -* @param {vec3} viewPosition - The fragments position in view space. -* @param {mat4} projectionMatrix - The camera's projection matrix. -* @return {vec2} Teh fragment's screen position expressed as uv coordinates. -*/ -const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => { + const nodeMaterial = new NodeMaterial(); + nodeMaterial.name = 'Background.material'; + nodeMaterial.side = BackSide; + nodeMaterial.depthTest = false; + nodeMaterial.depthWrite = false; + nodeMaterial.fog = false; + nodeMaterial.lights = false; + nodeMaterial.vertexNode = viewProj; + nodeMaterial.colorNode = backgroundMeshNode; - const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) ); - const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar(); - return vec2( sampleUv.x, sampleUv.y.oneMinus() ); + sceneData.backgroundMeshNode = backgroundMeshNode; + sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial ); + backgroundMesh.frustumCulled = false; + backgroundMesh.name = 'Background.mesh'; -} ); + backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) { -const _objectData = new WeakMap(); + this.matrixWorld.copyPosition( camera.matrixWorld ); -class VelocityNode extends TempNode { + }; - static get type() { + } - return 'VelocityNode'; + const backgroundCacheKey = backgroundNode.getCacheKey(); - } + if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) { - constructor() { + sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity ); + sceneData.backgroundMeshNode.needsUpdate = true; - super( 'vec2' ); + backgroundMesh.material.needsUpdate = true; - this.updateType = NodeUpdateType.OBJECT; - this.updateAfterType = NodeUpdateType.OBJECT; + sceneData.backgroundCacheKey = backgroundCacheKey; - this.previousModelWorldMatrix = uniform( new Matrix4() ); - this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup ); - this.previousCameraViewMatrix = uniform( new Matrix4() ); + } - } + renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null ); - update( { frameId, camera, object } ) { + } else { - const previousModelMatrix = getPreviousMatrix( object ); + console.error( 'THREE.Renderer: Unsupported background configuration.', background ); - this.previousModelWorldMatrix.value.copy( previousModelMatrix ); + } // - const cameraData = getData( camera ); - - if ( cameraData.frameId !== frameId ) { - - cameraData.frameId = frameId; - - if ( cameraData.previousProjectionMatrix === undefined ) { + if ( renderer.autoClear === true || forceClear === true ) { - cameraData.previousProjectionMatrix = new Matrix4(); - cameraData.previousCameraViewMatrix = new Matrix4(); + const clearColorValue = renderContext.clearColorValue; - cameraData.currentProjectionMatrix = new Matrix4(); - cameraData.currentCameraViewMatrix = new Matrix4(); + clearColorValue.r = _clearColor$1.r; + clearColorValue.g = _clearColor$1.g; + clearColorValue.b = _clearColor$1.b; + clearColorValue.a = _clearColor$1.a; - cameraData.previousProjectionMatrix.copy( camera.projectionMatrix ); - cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse ); + // premultiply alpha - } else { + if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) { - cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix ); - cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix ); + clearColorValue.r *= clearColorValue.a; + clearColorValue.g *= clearColorValue.a; + clearColorValue.b *= clearColorValue.a; } - cameraData.currentProjectionMatrix.copy( camera.projectionMatrix ); - cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse ); + // - this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix ); - this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix ); + renderContext.depthClearValue = renderer._clearDepth; + renderContext.stencilClearValue = renderer._clearStencil; - } + renderContext.clearColor = renderer.autoClearColor === true; + renderContext.clearDepth = renderer.autoClearDepth === true; + renderContext.clearStencil = renderer.autoClearStencil === true; - } + } else { - updateAfter( { object } ) { + renderContext.clearColor = false; + renderContext.clearDepth = false; + renderContext.clearStencil = false; - getPreviousMatrix( object ).copy( object.matrixWorld ); + } } - setup( /*builder*/ ) { +} - const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix ); +let _id$5 = 0; - const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal ); - const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious ); +class BindGroup { - const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w ); - const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w ); + constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) { - const velocity = sub( ndcPositionCurrent, ndcPositionPrevious ); + this.name = name; + this.bindings = bindings; + this.index = index; + this.bindingsReference = bindingsReference; - return velocity; + this.id = _id$5 ++; } } -function getData( object ) { +class NodeBuilderState { - let objectData = _objectData.get( object ); - - if ( objectData === undefined ) { - - objectData = {}; - _objectData.set( object, objectData ); - - } + constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) { - return objectData; + this.vertexShader = vertexShader; + this.fragmentShader = fragmentShader; + this.computeShader = computeShader; + this.transforms = transforms; -} + this.nodeAttributes = nodeAttributes; + this.bindings = bindings; -function getPreviousMatrix( object, index = 0 ) { + this.updateNodes = updateNodes; + this.updateBeforeNodes = updateBeforeNodes; + this.updateAfterNodes = updateAfterNodes; - const objectData = getData( object ); + this.monitor = monitor; - let matrix = objectData[ index ]; + this.usedTimes = 0; - if ( matrix === undefined ) { + } - objectData[ index ] = matrix = new Matrix4(); + createBindings() { - } + const bindings = []; - return matrix; + for ( const instanceGroup of this.bindings ) { -} + const shared = instanceGroup.bindings[ 0 ].groupNode.shared; -const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode ); + if ( shared !== true ) { -const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { + const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup ); + bindings.push( bindingsGroup ); - return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus(); + for ( const instanceBinding of instanceGroup.bindings ) { -} ).setLayout( { - name: 'burnBlend', - type: 'vec3', - inputs: [ - { name: 'base', type: 'vec3' }, - { name: 'blend', type: 'vec3' } - ] -} ); + bindingsGroup.bindings.push( instanceBinding.clone() ); -const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { + } - return min$1( base.div( blend.oneMinus() ), 1.0 ); + } else { -} ).setLayout( { - name: 'dodgeBlend', - type: 'vec3', - inputs: [ - { name: 'base', type: 'vec3' }, - { name: 'blend', type: 'vec3' } - ] -} ); + bindings.push( instanceGroup ); -const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { + } - return base.oneMinus().mul( blend.oneMinus() ).oneMinus(); + } -} ).setLayout( { - name: 'screenBlend', - type: 'vec3', - inputs: [ - { name: 'base', type: 'vec3' }, - { name: 'blend', type: 'vec3' } - ] -} ); + return bindings; -const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => { + } - return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) ); +} -} ).setLayout( { - name: 'overlayBlend', - type: 'vec3', - inputs: [ - { name: 'base', type: 'vec3' }, - { name: 'blend', type: 'vec3' } - ] -} ); +class NodeAttribute { -const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => { + constructor( name, type, node = null ) { - return luminance( color.rgb ); + this.isNodeAttribute = true; -} ); + this.name = name; + this.type = type; + this.node = node; -const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { + } - return adjustment.mix( luminance( color.rgb ), color.rgb ); +} -} ); +class NodeUniform { -const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { + constructor( name, type, node ) { - const average = add( color.r, color.g, color.b ).div( 3.0 ); + this.isNodeUniform = true; - const mx = color.r.max( color.g.max( color.b ) ); - const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 ); + this.name = name; + this.type = type; + this.node = node.getSelf(); - return mix( color.rgb, mx, amt ); + } -} ); + get value() { -const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => { + return this.node.value; - const k = vec3( 0.57735, 0.57735, 0.57735 ); + } - const cosAngle = adjustment.cos(); + set value( val ) { - return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) ); + this.node.value = val; -} ); + } -const luminance = ( - color, - luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) ) -) => dot( color, luminanceCoefficients ); + get id() { -const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) ); + return this.node.id; -/** - * Color Decision List (CDL) v1.2 - * - * Compact representation of color grading information, defined by slope, offset, power, and - * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc, - * or AgX Log), and will return output in the same space. Output may require clamping >=0. - * - * @param {vec4} color Input (-Infinity < input < +Infinity) - * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity) - * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1) - * @param {number | vec3} power Power (0 < power < +Infinity) - * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4) - * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709 - * @return Output, -Infinity < output < +Infinity - * - * References: - * - ASC CDL v1.2 - * - https://blender.stackexchange.com/a/55239/43930 - * - https://docs.acescentral.com/specifications/acescc/ - */ -const cdl = /*@__PURE__*/ Fn( ( [ - color, - slope = vec3( 1 ), - offset = vec3( 0 ), - power = vec3( 1 ), - saturation = float( 1 ), - // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients. - luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) ) -] ) => { + } - // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the - // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support - // values outside [0, 1], requiring a workaround for negative values in the power expression. + get groupNode() { - const luma = color.rgb.dot( vec3( luminanceCoefficients ) ); + return this.node.groupNode; - const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar(); - const pv = v.pow( power ).toVar(); + } - If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line - If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line - If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line +} - v.assign( luma.add( v.sub( luma ).mul( saturation ) ) ); +class NodeVar { - return vec4( v.rgb, color.a ); + constructor( name, type ) { -} ); + this.isNodeVar = true; -const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => { + this.name = name; + this.type = type; - const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 ); - const b = color.mul( 0.0773993808 ); - const factor = color.lessThanEqual( 0.04045 ); + } - const rgbResult = mix( a, b, factor ); +} - return rgbResult; +class NodeVarying extends NodeVar { -} ).setLayout( { - name: 'sRGBToLinearSRGB', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' } - ] -} ); + constructor( name, type ) { -const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => { + super( name, type ); - const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 ); - const b = color.mul( 12.92 ); - const factor = color.lessThanEqual( 0.0031308 ); + this.needsInterpolation = false; - const rgbResult = mix( a, b, factor ); + this.isNodeVarying = true; - return rgbResult; + } -} ).setLayout( { - name: 'linearSRGBTosRGB', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' } - ] -} ); +} -// exposure only +class NodeCode { -const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { + constructor( name, type, code = '' ) { - return color.mul( exposure ).clamp(); + this.name = name; + this.type = type; + this.code = code; -} ).setLayout( { - name: 'linearToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + Object.defineProperty( this, 'isNodeCode', { value: true } ); -// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf + } -const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { +} - color = color.mul( exposure ); +let id = 0; - return color.div( color.add( 1.0 ) ).clamp(); +class NodeCache { -} ).setLayout( { - name: 'reinhardToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + constructor( parent = null ) { -// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/ + this.id = id ++; + this.nodesData = new WeakMap(); -const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { + this.parent = parent; - // filmic operator by Jim Hejl and Richard Burgess-Dawson - color = color.mul( exposure ); - color = color.sub( 0.004 ).max( 0.0 ); + } - const a = color.mul( color.mul( 6.2 ).add( 0.5 ) ); - const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 ); + getData( node ) { - return a.div( b ).pow( 2.2 ); + let data = this.nodesData.get( node ); -} ).setLayout( { - name: 'cineonToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + if ( data === undefined && this.parent !== null ) { -// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs + data = this.parent.getData( node ); -const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => { + } - const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 ); - const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 ); + return data; - return a.div( b ); + } -} ); + setData( node, data ) { -// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs + this.nodesData.set( node, data ); -const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { + } - // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT - const ACESInputMat = mat3( - 0.59719, 0.35458, 0.04823, - 0.07600, 0.90834, 0.01566, - 0.02840, 0.13383, 0.83777 - ); +} - // ODT_SAT => XYZ => D60_2_D65 => sRGB - const ACESOutputMat = mat3( - 1.60475, - 0.53108, - 0.07367, - - 0.10208, 1.10813, - 0.00605, - - 0.00327, - 0.07276, 1.07602 - ); +class Uniform { - color = color.mul( exposure ).div( 0.6 ); + constructor( name, value ) { - color = ACESInputMat.mul( color ); + this.name = name; + this.value = value; - // Apply RRT and ODT - color = RRTAndODTFit( color ); + this.boundary = 0; // used to build the uniform buffer according to the STD140 layout + this.itemSize = 0; - color = ACESOutputMat.mul( color ); + this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer - // Clamp to [0, 1] - return color.clamp(); + } -} ).setLayout( { - name: 'acesFilmicToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + setValue( value ) { -const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); -const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); + this.value = value; -const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { + } - const x = vec3( x_immutable ).toVar(); - const x2 = vec3( x.mul( x ) ).toVar(); - const x4 = vec3( x2.mul( x2 ) ).toVar(); + getValue() { - return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) ); + return this.value; -} ); + } -const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { +} - const colortone = vec3( color ).toVar(); - const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); - const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); - const AgxMinEv = float( - 12.47393 ); - const AgxMaxEv = float( 4.026069 ); - colortone.mulAssign( exposure ); - colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) ); - colortone.assign( AgXInsetMatrix.mul( colortone ) ); - colortone.assign( max$1( colortone, 1e-10 ) ); - colortone.assign( log2( colortone ) ); - colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) ); - colortone.assign( clamp( colortone, 0.0, 1.0 ) ); - colortone.assign( agxDefaultContrastApprox( colortone ) ); - colortone.assign( AgXOutsetMatrix.mul( colortone ) ); - colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) ); - colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) ); - colortone.assign( clamp( colortone, 0.0, 1.0 ) ); +class NumberUniform extends Uniform { - return colortone; + constructor( name, value = 0 ) { -} ).setLayout( { - name: 'agxToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + super( name, value ); -// https://modelviewer.dev/examples/tone-mapping + this.isNumberUniform = true; -const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => { + this.boundary = 4; + this.itemSize = 1; - const StartCompression = float( 0.8 - 0.04 ); - const Desaturation = float( 0.15 ); + } - color = color.mul( exposure ); +} - const x = min$1( color.r, min$1( color.g, color.b ) ); - const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 ); +class Vector2Uniform extends Uniform { - color.subAssign( offset ); + constructor( name, value = new Vector2() ) { - const peak = max$1( color.r, max$1( color.g, color.b ) ); + super( name, value ); - If( peak.lessThan( StartCompression ), () => { + this.isVector2Uniform = true; - return color; + this.boundary = 8; + this.itemSize = 2; - } ); + } - const d = sub( 1, StartCompression ); - const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) ); - color.mulAssign( newPeak.div( peak ) ); - const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) ); +} - return mix( color, vec3( newPeak ), g ); +class Vector3Uniform extends Uniform { -} ).setLayout( { - name: 'neutralToneMapping', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' }, - { name: 'exposure', type: 'float' } - ] -} ); + constructor( name, value = new Vector3() ) { -class ComputeBuiltinNode extends Node { + super( name, value ); - static get type() { + this.isVector3Uniform = true; - return 'ComputeBuiltinNode'; + this.boundary = 16; + this.itemSize = 3; } - constructor( builtinName, nodeType ) { +} - super( nodeType ); +class Vector4Uniform extends Uniform { - this._builtinName = builtinName; + constructor( name, value = new Vector4() ) { - } + super( name, value ); - getHash( builder ) { + this.isVector4Uniform = true; - return this.getBuiltinName( builder ); + this.boundary = 16; + this.itemSize = 4; } - getNodeType( /*builder*/ ) { +} - return this.nodeType; +class ColorUniform extends Uniform { - } + constructor( name, value = new Color() ) { - setBuiltinName( builtinName ) { + super( name, value ); - this._builtinName = builtinName; + this.isColorUniform = true; - return this; + this.boundary = 16; + this.itemSize = 3; } - getBuiltinName( /*builder*/ ) { +} - return this._builtinName; +class Matrix3Uniform extends Uniform { - } + constructor( name, value = new Matrix3() ) { - hasBuiltin( builder ) { + super( name, value ); - builder.hasBuiltin( this._builtinName ); + this.isMatrix3Uniform = true; - } + this.boundary = 48; + this.itemSize = 12; - generate( builder, output ) { + } - const builtinName = this.getBuiltinName( builder ); - const nodeType = this.getNodeType( builder ); +} - if ( builder.shaderStage === 'compute' ) { +class Matrix4Uniform extends Uniform { - return builder.format( builtinName, nodeType, output ); + constructor( name, value = new Matrix4() ) { - } else { + super( name, value ); - console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` ); - return builder.generateConst( nodeType ); + this.isMatrix4Uniform = true; - } + this.boundary = 64; + this.itemSize = 16; } - serialize( data ) { +} - super.serialize( data ); +class NumberNodeUniform extends NumberUniform { - data.global = this.global; - data._builtinName = this._builtinName; + constructor( nodeUniform ) { - } + super( nodeUniform.name, nodeUniform.value ); - deserialize( data ) { + this.nodeUniform = nodeUniform; - super.deserialize( data ); + } - this.global = data.global; - this._builtinName = data._builtinName; + getValue() { + + return this.nodeUniform.value; } } -const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) ); +class Vector2NodeUniform extends Vector2Uniform { -const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' ); -const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' ); -const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' ); -const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' ); + constructor( nodeUniform ) { -class BarrierNode extends Node { + super( nodeUniform.name, nodeUniform.value ); - constructor( scope ) { + this.nodeUniform = nodeUniform; - super(); + } - this.scope = scope; + getValue() { + + return this.nodeUniform.value; } - generate( builder ) { +} - const { scope } = this; - const { renderer } = builder; +class Vector3NodeUniform extends Vector3Uniform { - if ( renderer.backend.isWebGLBackend === true ) { + constructor( nodeUniform ) { - builder.addFlowCode( `\t// ${scope}Barrier \n` ); + super( nodeUniform.name, nodeUniform.value ); - } else { + this.nodeUniform = nodeUniform; - builder.addLineFlowCode( `${scope}Barrier()`, this ); + } - } + getValue() { + + return this.nodeUniform.value; } } -const barrier = nodeProxy( BarrierNode ); +class Vector4NodeUniform extends Vector4Uniform { -const workgroupBarrier = () => barrier( 'workgroup' ).append(); -const storageBarrier = () => barrier( 'storage' ).append(); -const textureBarrier = () => barrier( 'texture' ).append(); + constructor( nodeUniform ) { -class WorkgroupInfoElementNode extends ArrayElementNode { + super( nodeUniform.name, nodeUniform.value ); - constructor( workgroupInfoNode, indexNode ) { + this.nodeUniform = nodeUniform; - super( workgroupInfoNode, indexNode ); + } - this.isWorkgroupInfoElementNode = true; + getValue() { - } + return this.nodeUniform.value; - generate( builder, output ) { + } - let snippet; +} - const isAssignContext = builder.context.assign; - snippet = super.generate( builder ); +class ColorNodeUniform extends ColorUniform { - if ( isAssignContext !== true ) { + constructor( nodeUniform ) { - const type = this.getNodeType( builder ); + super( nodeUniform.name, nodeUniform.value ); - snippet = builder.format( snippet, type, output ); + this.nodeUniform = nodeUniform; - } + } - // TODO: Possibly activate clip distance index on index access rather than from clipping context + getValue() { - return snippet; + return this.nodeUniform.value; } } +class Matrix3NodeUniform extends Matrix3Uniform { -class WorkgroupInfoNode extends Node { + constructor( nodeUniform ) { - constructor( scope, bufferType, bufferCount = 0 ) { + super( nodeUniform.name, nodeUniform.value ); - super( bufferType ); + this.nodeUniform = nodeUniform; - this.bufferType = bufferType; - this.bufferCount = bufferCount; + } - this.isWorkgroupInfoNode = true; + getValue() { - this.scope = scope; + return this.nodeUniform.value; } - label( name ) { +} - this.name = name; +class Matrix4NodeUniform extends Matrix4Uniform { - return this; + constructor( nodeUniform ) { + + super( nodeUniform.name, nodeUniform.value ); + + this.nodeUniform = nodeUniform; } - getHash() { + getValue() { - return this.uuid; + return this.nodeUniform.value; } - setScope( scope ) { +} - this.scope = scope; +const LOD_MIN = 4; - return this; +// The standard deviations (radians) associated with the extra mips. These are +// chosen to approximate a Trowbridge-Reitz distribution function times the +// geometric shadowing function. These sigma values squared must match the +// variance #defines in cube_uv_reflection_fragment.glsl.js. +const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; - } +// The maximum length of the blur for loop. Smaller sigmas will use fewer +// samples and exit early, but not recompile the shader. +const MAX_SAMPLES = 20; - getInputType( /*builder*/ ) { +const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); +const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 ); +const _clearColor = /*@__PURE__*/ new Color(); +let _oldTarget = null; +let _oldActiveCubeFace = 0; +let _oldActiveMipmapLevel = 0; - return `${this.scope}Array`; +// Golden Ratio +const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; +const INV_PHI = 1 / PHI; - } +// Vertices of a dodecahedron (except the opposites, which represent the +// same axis), used as axis directions evenly spread on a sphere. +const _axisDirections = [ + /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), + /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, 1 ), + /*@__PURE__*/ new Vector3( 1, 1, 1 ) +]; - element( indexNode ) { +// - return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) ); +// WebGPU Face indices +const _faceLib = [ + 3, 1, 5, + 0, 4, 2 +]; - } +const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize(); +const outputDirection = vec3( direction.x, direction.y.negate(), direction.z ); - generate( builder ) { +/** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * Paper: Fast, Accurate Image-Based Lighting + * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view +*/ - return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount ); +class PMREMGenerator { + + constructor( renderer ) { + + this._renderer = renderer; + 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; } -} + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { -const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) ); + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); -class AtomicFunctionNode extends TempNode { + this._setSize( 256 ); - static get type() { + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; - return 'AtomicFunctionNode'; + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); - } + if ( sigma > 0 ) { - constructor( method, pointerNode, valueNode, storeNode = null ) { + this._blur( cubeUVRenderTarget, 0, 0, sigma ); - super( 'uint' ); + } - this.method = method; + this._applyPMREM( cubeUVRenderTarget ); - this.pointerNode = pointerNode; - this.valueNode = valueNode; - this.storeNode = storeNode; + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; } - getInputType( builder ) { + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { - return this.pointerNode.getNodeType( builder ); + return this._fromTexture( equirectangular, renderTarget ); } - getNodeType( builder ) { + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap( cubemap, renderTarget = null ) { - return this.getInputType( builder ); + return this._fromTexture( cubemap, renderTarget ); } - generate( builder ) { + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + async compileCubemapShader() { - const method = this.method; + if ( this._cubemapMaterial === null ) { - const type = this.getNodeType( builder ); - const inputType = this.getInputType( builder ); + this._cubemapMaterial = _getCubemapMaterial(); + await this._compileMaterial( this._cubemapMaterial ); - const a = this.pointerNode; - const b = this.valueNode; + } - const params = []; + } - params.push( `&${ a.build( builder, inputType ) }` ); - params.push( b.build( builder, inputType ) ); + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + async compileEquirectangularShader() { - const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`; + if ( this._equirectMaterial === null ) { - if ( this.storeNode !== null ) { + this._equirectMaterial = _getEquirectMaterial(); + await this._compileMaterial( this._equirectMaterial ); - const varSnippet = this.storeNode.build( builder, inputType ); + } - builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this ); + } - } else { + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { - builder.addLineFlowCode( methodSnippet, this ); + this._dispose(); + + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); + if ( this._backgroundBox !== null ) { + + this._backgroundBox.geometry.dispose(); + this._backgroundBox.material.dispose(); } } -} + // private interface -AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad'; -AtomicFunctionNode.ATOMIC_STORE = 'atomicStore'; -AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd'; -AtomicFunctionNode.ATOMIC_SUB = 'atomicSub'; -AtomicFunctionNode.ATOMIC_MAX = 'atomicMax'; -AtomicFunctionNode.ATOMIC_MIN = 'atomicMin'; -AtomicFunctionNode.ATOMIC_AND = 'atomicAnd'; -AtomicFunctionNode.ATOMIC_OR = 'atomicOr'; -AtomicFunctionNode.ATOMIC_XOR = 'atomicXor'; + _setSize( cubeSize ) { -const atomicNode = nodeProxy( AtomicFunctionNode ); + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); -const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => { + } - const node = atomicNode( method, pointerNode, valueNode, storeNode ); - node.append(); + _dispose() { - return node; + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); -}; + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); -const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode ); -const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode ); -const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode ); -const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode ); -const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode ); -const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode ); -const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode ); -const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode ); + for ( let i = 0; i < this._lodPlanes.length; i ++ ) { -const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => { + this._lodPlanes[ i ].dispose(); - const uv = coord.mul( 2.0 ); + } - const cx = uv.x.floor(); - const cy = uv.y.floor(); - const result = cx.add( cy ).mod( 2.0 ); + } - return result.sign(); + _cleanup( outputTarget ) { -} ); + this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel ); + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); -// Three.js Transpiler -// https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl + } + _fromTexture( texture, renderTarget ) { + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { -const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => { + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); - const f = float( f_immutable ).toVar(); - const t = float( t_immutable ).toVar(); - const b = bool( b_immutable ).toVar(); + } else { // Equirectangular - return select( b, t, f ); + this._setSize( texture.image.width / 4 ); -} ).setLayout( { - name: 'mx_select', - type: 'float', - inputs: [ - { name: 'b', type: 'bool' }, - { name: 't', type: 'float' }, - { name: 'f', type: 'float' } - ] -} ); + } -const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => { + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); - const b = bool( b_immutable ).toVar(); - const val = float( val_immutable ).toVar(); + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); - return select( b, val.negate(), val ); + return cubeUVRenderTarget; -} ).setLayout( { - name: 'mx_negate_if', - type: 'float', - inputs: [ - { name: 'val', type: 'float' }, - { name: 'b', type: 'bool' } - ] -} ); + } -const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { + _allocateTargets() { - const x = float( x_immutable ).toVar(); + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; - return int( floor( x ) ); + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + //depthBuffer: false + }; -} ).setLayout( { - name: 'mx_floor', - type: 'int', - inputs: [ - { name: 'x', type: 'float' } - ] -} ); + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); -const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => { + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { - const x = float( x_immutable ).toVar(); - i.assign( mx_floor( x ) ); + if ( this._pingPongRenderTarget !== null ) { - return x.sub( float( i ) ); + this._dispose(); -} ); + } -const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => { + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); - const t = float( t_immutable ).toVar(); - const s = float( s_immutable ).toVar(); - const v3 = float( v3_immutable ).toVar(); - const v2 = float( v2_immutable ).toVar(); - const v1 = float( v1_immutable ).toVar(); - const v0 = float( v0_immutable ).toVar(); - const s1 = float( sub( 1.0, s ) ).toVar(); + const { _lodMax } = this; + ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) ); - return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ); + this._blurMaterial = _getBlurShader( _lodMax, width, height ); -} ).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' } - ] -} ); + } -const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => { + return cubeUVRenderTarget; - const t = float( t_immutable ).toVar(); - const s = float( s_immutable ).toVar(); - const v3 = vec3( v3_immutable ).toVar(); - const v2 = vec3( v2_immutable ).toVar(); - const v1 = vec3( v1_immutable ).toVar(); - const v0 = vec3( v0_immutable ).toVar(); - const s1 = float( sub( 1.0, s ) ).toVar(); + } - return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ); + async _compileMaterial( material ) { -} ).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' } - ] -} ); + const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); + await this._renderer.compile( tmpMesh, _flatCamera ); -const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] ); + } -const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => { + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { - const r = float( r_immutable ).toVar(); - const t = float( t_immutable ).toVar(); - const s = float( s_immutable ).toVar(); - const v7 = float( v7_immutable ).toVar(); - const v6 = float( v6_immutable ).toVar(); - const v5 = float( v5_immutable ).toVar(); - const v4 = float( v4_immutable ).toVar(); - const v3 = float( v3_immutable ).toVar(); - const v2 = float( v2_immutable ).toVar(); - const v1 = float( v1_immutable ).toVar(); - const v0 = float( v0_immutable ).toVar(); - const s1 = float( sub( 1.0, s ) ).toVar(); - const t1 = float( sub( 1.0, t ) ).toVar(); - const r1 = float( sub( 1.0, r ) ).toVar(); + const cubeCamera = _cubeCamera; + cubeCamera.near = near; + cubeCamera.far = far; - return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) ); + // px, py, pz, nx, ny, nz + const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ]; + const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; -} ).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' } - ] -} ); + const renderer = this._renderer; -const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => { + const originalAutoClear = renderer.autoClear; - const r = float( r_immutable ).toVar(); - const t = float( t_immutable ).toVar(); - const s = float( s_immutable ).toVar(); - const v7 = vec3( v7_immutable ).toVar(); - const v6 = vec3( v6_immutable ).toVar(); - const v5 = vec3( v5_immutable ).toVar(); - const v4 = vec3( v4_immutable ).toVar(); - const v3 = vec3( v3_immutable ).toVar(); - const v2 = vec3( v2_immutable ).toVar(); - const v1 = vec3( v1_immutable ).toVar(); - const v0 = vec3( v0_immutable ).toVar(); - const s1 = float( sub( 1.0, s ) ).toVar(); - const t1 = float( sub( 1.0, t ) ).toVar(); - const r1 = float( sub( 1.0, r ) ).toVar(); + renderer.getClearColor( _clearColor ); - return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) ); + renderer.autoClear = false; -} ).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' } - ] -} ); + let backgroundBox = this._backgroundBox; -const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] ); + if ( backgroundBox === null ) { -const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => { + const backgroundMaterial = new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false + } ); - const y = float( y_immutable ).toVar(); - const x = float( x_immutable ).toVar(); - const hash = uint( hash_immutable ).toVar(); - const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar(); - const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar(); - const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar(); + backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); - return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) ); + } -} ).setLayout( { - name: 'mx_gradient_float_0', - type: 'float', - inputs: [ - { name: 'hash', type: 'uint' }, - { name: 'x', type: 'float' }, - { name: 'y', type: 'float' } - ] -} ); + let useSolidColor = false; + const background = scene.background; -const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => { + if ( background ) { - const z = float( z_immutable ).toVar(); - const y = float( y_immutable ).toVar(); - const x = float( x_immutable ).toVar(); - const hash = uint( hash_immutable ).toVar(); - const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar(); - const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar(); - const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar(); + if ( background.isColor ) { - return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) ); + backgroundBox.material.color.copy( background ); + scene.background = null; + useSolidColor = true; -} ).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' } - ] -} ); + } -const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] ); + } else { -const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => { + backgroundBox.material.color.copy( _clearColor ); + useSolidColor = true; - const y = float( y_immutable ).toVar(); - const x = float( x_immutable ).toVar(); - const hash = uvec3( hash_immutable ).toVar(); + } - return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) ); + renderer.setRenderTarget( cubeUVRenderTarget ); -} ).setLayout( { - name: 'mx_gradient_vec3_0', - type: 'vec3', - inputs: [ - { name: 'hash', type: 'uvec3' }, - { name: 'x', type: 'float' }, - { name: 'y', type: 'float' } - ] -} ); + renderer.clear(); -const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => { + if ( useSolidColor ) { - const z = float( z_immutable ).toVar(); - const y = float( y_immutable ).toVar(); - const x = float( x_immutable ).toVar(); - const hash = uvec3( hash_immutable ).toVar(); + renderer.render( backgroundBox, cubeCamera ); - return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) ); + } -} ).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' } - ] -} ); + for ( let i = 0; i < 6; i ++ ) { -const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] ); + const col = i % 3; -const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { + if ( col === 0 ) { - const v = float( v_immutable ).toVar(); + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); - return mul( 0.6616, v ); + } else if ( col === 1 ) { -} ).setLayout( { - name: 'mx_gradient_scale2d_0', - type: 'float', - inputs: [ - { name: 'v', type: 'float' } - ] -} ); + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); -const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { + } else { - const v = float( v_immutable ).toVar(); + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); - return mul( 0.9820, v ); + } -} ).setLayout( { - name: 'mx_gradient_scale3d_0', - type: 'float', - inputs: [ - { name: 'v', type: 'float' } - ] -} ); + const size = this._cubeSize; -const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); - const v = vec3( v_immutable ).toVar(); + renderer.render( scene, cubeCamera ); - return mul( 0.6616, v ); + } -} ).setLayout( { - name: 'mx_gradient_scale2d_1', - type: 'vec3', - inputs: [ - { name: 'v', type: 'vec3' } - ] -} ); + renderer.autoClear = originalAutoClear; + scene.background = background; -const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] ); + } -const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => { + _textureToCubeUV( texture, cubeUVRenderTarget ) { - const v = vec3( v_immutable ).toVar(); + const renderer = this._renderer; - return mul( 0.9820, v ); + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); -} ).setLayout( { - name: 'mx_gradient_scale3d_1', - type: 'vec3', - inputs: [ - { name: 'v', type: 'vec3' } - ] -} ); + if ( isCubeTexture ) { -const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] ); + if ( this._cubemapMaterial === null ) { -const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => { + this._cubemapMaterial = _getCubemapMaterial( texture ); - const k = int( k_immutable ).toVar(); - const x = uint( x_immutable ).toVar(); + } - return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) ); + } else { -} ).setLayout( { - name: 'mx_rotl32', - type: 'uint', - inputs: [ - { name: 'x', type: 'uint' }, - { name: 'k', type: 'int' } - ] -} ); + if ( this._equirectMaterial === null ) { -const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => { + this._equirectMaterial = _getEquirectMaterial( texture ); - a.subAssign( c ); - a.bitXorAssign( mx_rotl32( c, int( 4 ) ) ); - c.addAssign( b ); - b.subAssign( a ); - b.bitXorAssign( mx_rotl32( a, int( 6 ) ) ); - a.addAssign( c ); - c.subAssign( b ); - c.bitXorAssign( mx_rotl32( b, int( 8 ) ) ); - b.addAssign( a ); - a.subAssign( c ); - a.bitXorAssign( mx_rotl32( c, int( 16 ) ) ); - c.addAssign( b ); - b.subAssign( a ); - b.bitXorAssign( mx_rotl32( a, int( 19 ) ) ); - a.addAssign( c ); - c.subAssign( b ); - c.bitXorAssign( mx_rotl32( b, int( 4 ) ) ); - b.addAssign( a ); + } -} ); + } -const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => { + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + material.fragmentNode.value = texture; - const c = uint( c_immutable ).toVar(); - const b = uint( b_immutable ).toVar(); - const a = uint( a_immutable ).toVar(); - c.bitXorAssign( b ); - c.subAssign( mx_rotl32( b, int( 14 ) ) ); - a.bitXorAssign( c ); - a.subAssign( mx_rotl32( c, int( 11 ) ) ); - b.bitXorAssign( a ); - b.subAssign( mx_rotl32( a, int( 25 ) ) ); - c.bitXorAssign( b ); - c.subAssign( mx_rotl32( b, int( 16 ) ) ); - a.bitXorAssign( c ); - a.subAssign( mx_rotl32( c, int( 4 ) ) ); - b.bitXorAssign( a ); - b.subAssign( mx_rotl32( a, int( 14 ) ) ); - c.bitXorAssign( b ); - c.subAssign( mx_rotl32( b, int( 24 ) ) ); + const mesh = this._lodMeshes[ 0 ]; + mesh.material = material; - return c; + const size = this._cubeSize; -} ).setLayout( { - name: 'mx_bjfinal', - type: 'uint', - inputs: [ - { name: 'a', type: 'uint' }, - { name: 'b', type: 'uint' }, - { name: 'c', type: 'uint' } - ] -} ); + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); -const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => { + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); - const bits = uint( bits_immutable ).toVar(); + } - return float( bits ).div( float( uint( int( 0xffffffff ) ) ) ); + _applyPMREM( cubeUVRenderTarget ) { -} ).setLayout( { - name: 'mx_bits_to_01', - type: 'float', - inputs: [ - { name: 'bits', type: 'uint' } - ] -} ); + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + const n = this._lodPlanes.length; -const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => { + for ( let i = 1; i < n; i ++ ) { - const t = float( t_immutable ).toVar(); + const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); - return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) ); + const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ]; -} ).setLayout( { - name: 'mx_fade', - type: 'float', - inputs: [ - { name: 't', type: 'float' } - ] -} ); + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); -const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => { + } - const x = int( x_immutable ).toVar(); - const len = uint( uint( 1 ) ).toVar(); - const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar(); + renderer.autoClear = autoClear; - return mx_bjfinal( seed.add( uint( x ) ), seed, seed ); + } -} ).setLayout( { - name: 'mx_hash_int_0', - type: 'uint', - inputs: [ - { name: 'x', type: 'int' } - ] -} ); + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { -const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => { + const pingPongRenderTarget = this._pingPongRenderTarget; - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const len = uint( uint( 2 ) ).toVar(); - const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); - a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); - a.addAssign( uint( x ) ); - b.addAssign( uint( y ) ); + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); - return mx_bjfinal( a, b, c ); + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); -} ).setLayout( { - name: 'mx_hash_int_1', - type: 'uint', - inputs: [ - { name: 'x', type: 'int' }, - { name: 'y', type: 'int' } - ] -} ); + } -const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => { + _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const len = uint( uint( 3 ) ).toVar(); - const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); - a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); - a.addAssign( uint( x ) ); - b.addAssign( uint( y ) ); - c.addAssign( uint( z ) ); + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; - return mx_bjfinal( a, b, c ); + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { -} ).setLayout( { - name: 'mx_hash_int_2', - type: 'uint', - inputs: [ - { name: 'x', type: 'int' }, - { name: 'y', type: 'int' }, - { name: 'z', type: 'int' } - ] -} ); + console.error( 'blur direction must be either latitudinal or longitudinal!' ); -const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => { + } - const xx = int( xx_immutable ).toVar(); - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const len = uint( uint( 4 ) ).toVar(); - const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); - a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); - a.addAssign( uint( x ) ); - b.addAssign( uint( y ) ); - c.addAssign( uint( z ) ); - mx_bjmix( a, b, c ); - a.addAssign( uint( xx ) ); + // Number of standard deviations at which to cut off the discrete approximation. + const STANDARD_DEVIATIONS = 3; - return mx_bjfinal( a, b, c ); + const blurMesh = this._lodMeshes[ lodOut ]; + blurMesh.material = blurMaterial; -} ).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' } - ] -} ); + const blurUniforms = blurMaterial.uniforms; -const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => { + const pixels = this._sizeLods[ lodIn ] - 1; + const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; - const yy = int( yy_immutable ).toVar(); - const xx = int( xx_immutable ).toVar(); - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const len = uint( uint( 5 ) ).toVar(); - const a = uint().toVar(), b = uint().toVar(), c = uint().toVar(); - a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) ); - a.addAssign( uint( x ) ); - b.addAssign( uint( y ) ); - c.addAssign( uint( z ) ); - mx_bjmix( a, b, c ); - a.addAssign( uint( xx ) ); - b.addAssign( uint( yy ) ); + if ( samples > MAX_SAMPLES ) { - return mx_bjfinal( a, b, c ); + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); -} ).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' } - ] -} ); + } -const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] ); + const weights = []; + let sum = 0; -const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => { + for ( let i = 0; i < MAX_SAMPLES; ++ i ) { - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const h = uint( mx_hash_int( x, y ) ).toVar(); - const result = uvec3().toVar(); - result.x.assign( h.bitAnd( int( 0xFF ) ) ); - result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) ); - result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) ); + const x = i / sigmaPixels; + const weight = Math.exp( - x * x / 2 ); + weights.push( weight ); - return result; + if ( i === 0 ) { -} ).setLayout( { - name: 'mx_hash_vec3_0', - type: 'uvec3', - inputs: [ - { name: 'x', type: 'int' }, - { name: 'y', type: 'int' } - ] -} ); + sum += weight; -const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => { + } else if ( i < samples ) { - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const h = uint( mx_hash_int( x, y, z ) ).toVar(); - const result = uvec3().toVar(); - result.x.assign( h.bitAnd( int( 0xFF ) ) ); - result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) ); - result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) ); + sum += 2 * weight; - return result; + } -} ).setLayout( { - name: 'mx_hash_vec3_1', - type: 'uvec3', - inputs: [ - { name: 'x', type: 'int' }, - { name: 'y', type: 'int' }, - { name: 'z', type: 'int' } - ] -} ); + } -const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] ); + for ( let i = 0; i < weights.length; i ++ ) { -const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + weights[ i ] = weights[ i ] / sum; - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const fx = float( mx_floorfrac( p.x, X ) ).toVar(); - const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); - const u = float( mx_fade( fx ) ).toVar(); - const v = float( mx_fade( fy ) ).toVar(); - const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar(); + } - return mx_gradient_scale2d( result ); + targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1; -} ).setLayout( { - name: 'mx_perlin_noise_float_0', - type: 'float', - inputs: [ - { name: 'p', type: 'vec2' } - ] -} ); + blurUniforms.envMap.value = targetIn.texture; + blurUniforms.samples.value = samples; + blurUniforms.weights.array = weights; + blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0; -const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + if ( poleAxis ) { - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const fx = float( mx_floorfrac( p.x, X ) ).toVar(); - const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); - const fz = float( mx_floorfrac( p.z, Z ) ).toVar(); - const u = float( mx_fade( fx ) ).toVar(); - const v = float( mx_fade( fy ) ).toVar(); - const w = float( mx_fade( fz ) ).toVar(); - const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar(); + blurUniforms.poleAxis.value = poleAxis; - return mx_gradient_scale3d( result ); + } -} ).setLayout( { - name: 'mx_perlin_noise_float_1', - type: 'float', - inputs: [ - { name: 'p', type: 'vec3' } - ] -} ); + const { _lodMax } = this; + blurUniforms.dTheta.value = radiansPerPixel; + blurUniforms.mipInt.value = _lodMax - lodIn; -const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] ); + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); + + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); + + } + +} + +function _createPlanes( lodMax ) { + + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + const lodMeshes = []; + + let lod = lodMax; + + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + + for ( let i = 0; i < totalLods; i ++ ) { + + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + let sigma = 1.0 / sizeLod; + + if ( i > lodMax - LOD_MIN ) { + + sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; + + } else if ( i === 0 ) { + + sigma = 0; + + } + + sigmas.push( sigma ); + + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const uv = new Float32Array( uvSize * vertices * cubeFaces ); + const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + + for ( let face = 0; face < cubeFaces; face ++ ) { + + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : - 1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + + const faceIdx = _faceLib[ face ]; + position.set( coordinates, positionSize * vertices * faceIdx ); + uv.set( uv1, uvSize * vertices * faceIdx ); + const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ]; + faceIndex.set( fill, faceIndexSize * vertices * faceIdx ); + + } + + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + lodPlanes.push( planes ); + lodMeshes.push( new Mesh( planes, null ) ); + + if ( lod > LOD_MIN ) { + + lod --; + + } + + } + + return { lodPlanes, sizeLods, sigmas, lodMeshes }; + +} + +function _createRenderTarget( width, height, params ) { + + const cubeUVRenderTarget = new RenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.texture.isPMREMTexture = true; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + +} + +function _setViewport( target, x, y, width, height ) { + + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); + +} + +function _getMaterial( type ) { + + const material = new NodeMaterial(); + material.depthTest = false; + material.depthWrite = false; + material.blending = NoBlending; + material.name = `PMREM_${ type }`; + + return material; + +} + +function _getBlurShader( lodMax, width, height ) { + + const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) ); + const poleAxis = uniform( new Vector3( 0, 1, 0 ) ); + const dTheta = uniform( 0 ); + const n = float( MAX_SAMPLES ); + const latitudinal = uniform( 0 ); // false, bool + const samples = uniform( 1 ); // int + const envMap = texture( null ); + const mipInt = uniform( 0 ); // int + const CUBEUV_TEXEL_WIDTH = float( 1 / width ); + const CUBEUV_TEXEL_HEIGHT = float( 1 / height ); + const CUBEUV_MAX_MIP = float( lodMax ); + + const materialUniforms = { + n, + latitudinal, + weights, + poleAxis, + outputDirection, + dTheta, + samples, + envMap, + mipInt, + CUBEUV_TEXEL_WIDTH, + CUBEUV_TEXEL_HEIGHT, + CUBEUV_MAX_MIP + }; + + const material = _getMaterial( 'blur' ); + material.uniforms = materialUniforms; // TODO: Move to outside of the material + material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } ); + + return material; + +} + +function _getCubemapMaterial( envTexture ) { + + const material = _getMaterial( 'cubemap' ); + material.fragmentNode = cubeTexture( envTexture, outputDirection ); + + return material; + +} + +function _getEquirectMaterial( envTexture ) { + + const material = _getMaterial( 'equirect' ); + material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 ); + + return material; + +} + +const rendererCache = new WeakMap(); + +const typeFromLength = new Map( [ + [ 2, 'vec2' ], + [ 3, 'vec3' ], + [ 4, 'vec4' ], + [ 9, 'mat3' ], + [ 16, 'mat4' ] +] ); + +const typeFromArray = new Map( [ + [ Int8Array, 'int' ], + [ Int16Array, 'int' ], + [ Int32Array, 'int' ], + [ Uint8Array, 'uint' ], + [ Uint16Array, 'uint' ], + [ Uint32Array, 'uint' ], + [ Float32Array, 'float' ] +] ); + +const toFloat = ( value ) => { + + if ( /e/g.test( value ) ) { + + return String( value ).replace( /\+/g, '' ); + + } else { + + value = Number( value ); + + return value + ( value % 1 ? '' : '.0' ); + + } + +}; + +class NodeBuilder { + + constructor( object, renderer, parser ) { + + this.object = object; + this.material = ( object && object.material ) || null; + this.geometry = ( object && object.geometry ) || null; + this.renderer = renderer; + this.parser = parser; + this.scene = null; + this.camera = null; + + this.nodes = []; + this.sequentialNodes = []; + this.updateNodes = []; + this.updateBeforeNodes = []; + this.updateAfterNodes = []; + this.hashNodes = {}; + + this.monitor = 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.bindings = { vertex: {}, fragment: {}, compute: {} }; + this.bindingsIndexes = {}; + this.bindGroups = null; + this.attributes = []; + this.bufferAttributes = []; + this.varyings = []; + this.codes = {}; + this.vars = {}; + this.flow = { code: '' }; + this.chaining = []; + this.stack = stack(); + this.stacks = []; + this.tab = '\t'; + + this.currentFunctionNode = null; + + this.context = { + material: this.material + }; + + this.cache = new NodeCache(); + this.globalCache = this.cache; + + this.flowsData = new WeakMap(); + + this.shaderStage = null; + this.buildStage = null; + + this.useComparisonMethod = false; + + } + + getBindGroupsCache() { + + let bindGroupsCache = rendererCache.get( this.renderer ); + + if ( bindGroupsCache === undefined ) { + + bindGroupsCache = new ChainMap(); + + rendererCache.set( this.renderer, bindGroupsCache ); + + } + + return bindGroupsCache; + + } + + createRenderTarget( width, height, options ) { + + return new RenderTarget( width, height, options ); -const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + } - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const fx = float( mx_floorfrac( p.x, X ) ).toVar(); - const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); - const u = float( mx_fade( fx ) ).toVar(); - const v = float( mx_fade( fy ) ).toVar(); - const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar(); + createCubeRenderTarget( size, options ) { - return mx_gradient_scale2d( result ); + return new CubeRenderTarget( size, options ); -} ).setLayout( { - name: 'mx_perlin_noise_vec3_0', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec2' } - ] -} ); + } -const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + createPMREMGenerator() { - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const fx = float( mx_floorfrac( p.x, X ) ).toVar(); - const fy = float( mx_floorfrac( p.y, Y ) ).toVar(); - const fz = float( mx_floorfrac( p.z, Z ) ).toVar(); - const u = float( mx_fade( fx ) ).toVar(); - const v = float( mx_fade( fy ) ).toVar(); - const w = float( mx_fade( fz ) ).toVar(); - const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar(); + // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support - return mx_gradient_scale3d( result ); + return new PMREMGenerator( this.renderer ); -} ).setLayout( { - name: 'mx_perlin_noise_vec3_1', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec3' } - ] -} ); + } -const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] ); + includes( node ) { -const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + return this.nodes.includes( node ); - const p = float( p_immutable ).toVar(); - const ix = int( mx_floor( p ) ).toVar(); + } - return mx_bits_to_01( mx_hash_int( ix ) ); + _getBindGroup( groupName, bindings ) { -} ).setLayout( { - name: 'mx_cell_noise_float_0', - type: 'float', - inputs: [ - { name: 'p', type: 'float' } - ] -} ); + const bindGroupsCache = this.getBindGroupsCache(); -const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + // - const p = vec2( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); + const bindingsArray = []; - return mx_bits_to_01( mx_hash_int( ix, iy ) ); + let sharedGroup = true; -} ).setLayout( { - name: 'mx_cell_noise_float_1', - type: 'float', - inputs: [ - { name: 'p', type: 'vec2' } - ] -} ); + for ( const binding of bindings ) { -const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + bindingsArray.push( binding ); - const p = vec3( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); - const iz = int( mx_floor( p.z ) ).toVar(); + sharedGroup = sharedGroup && binding.groupNode.shared !== true; - return mx_bits_to_01( mx_hash_int( ix, iy, iz ) ); + } -} ).setLayout( { - name: 'mx_cell_noise_float_2', - type: 'float', - inputs: [ - { name: 'p', type: 'vec3' } - ] -} ); + // -const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + let bindGroup; - const p = vec4( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); - const iz = int( mx_floor( p.z ) ).toVar(); - const iw = int( mx_floor( p.w ) ).toVar(); + if ( sharedGroup ) { - return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) ); + bindGroup = bindGroupsCache.get( bindingsArray ); -} ).setLayout( { - name: 'mx_cell_noise_float_3', - type: 'float', - inputs: [ - { name: 'p', type: 'vec4' } - ] -} ); + if ( bindGroup === undefined ) { -const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] ); + bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray ); -const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + bindGroupsCache.set( bindingsArray, bindGroup ); - const p = float( p_immutable ).toVar(); - const ix = int( mx_floor( p ) ).toVar(); + } - return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) ); + } else { -} ).setLayout( { - name: 'mx_cell_noise_vec3_0', - type: 'vec3', - inputs: [ - { name: 'p', type: 'float' } - ] -} ); + bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray ); -const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + } - const p = vec2( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); + return bindGroup; - return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) ); + } -} ).setLayout( { - name: 'mx_cell_noise_vec3_1', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec2' } - ] -} ); + getBindGroupArray( groupName, shaderStage ) { -const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + const bindings = this.bindings[ shaderStage ]; - const p = vec3( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); - const iz = int( mx_floor( p.z ) ).toVar(); + let bindGroup = bindings[ groupName ]; - return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) ); + if ( bindGroup === undefined ) { -} ).setLayout( { - name: 'mx_cell_noise_vec3_2', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec3' } - ] -} ); + if ( this.bindingsIndexes[ groupName ] === undefined ) { -const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => { + this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length }; - const p = vec4( p_immutable ).toVar(); - const ix = int( mx_floor( p.x ) ).toVar(); - const iy = int( mx_floor( p.y ) ).toVar(); - const iz = int( mx_floor( p.z ) ).toVar(); - const iw = int( mx_floor( p.w ) ).toVar(); + } - return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) ); + bindings[ groupName ] = bindGroup = []; -} ).setLayout( { - name: 'mx_cell_noise_vec3_3', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec4' } - ] -} ); + } -const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] ); + return bindGroup; -const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { + } - const diminish = float( diminish_immutable ).toVar(); - const lacunarity = float( lacunarity_immutable ).toVar(); - const octaves = int( octaves_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const result = float( 0.0 ).toVar(); - const amplitude = float( 1.0 ).toVar(); + getBindings() { - Loop( octaves, () => { + let bindingsGroups = this.bindGroups; - result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) ); - amplitude.mulAssign( diminish ); - p.mulAssign( lacunarity ); + if ( bindingsGroups === null ) { - } ); + const groups = {}; + const bindings = this.bindings; - return result; + for ( const shaderStage of shaderStages ) { -} ).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' } - ] -} ); + for ( const groupName in bindings[ shaderStage ] ) { -const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { + const uniforms = bindings[ shaderStage ][ groupName ]; - const diminish = float( diminish_immutable ).toVar(); - const lacunarity = float( lacunarity_immutable ).toVar(); - const octaves = int( octaves_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const result = vec3( 0.0 ).toVar(); - const amplitude = float( 1.0 ).toVar(); + const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] ); + groupUniforms.push( ...uniforms ); - Loop( octaves, () => { + } - result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) ); - amplitude.mulAssign( diminish ); - p.mulAssign( lacunarity ); + } - } ); + bindingsGroups = []; - return result; + for ( const groupName in groups ) { -} ).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' } - ] -} ); + const group = groups[ groupName ]; -const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { + const bindingsGroup = this._getBindGroup( groupName, group ); - const diminish = float( diminish_immutable ).toVar(); - const lacunarity = float( lacunarity_immutable ).toVar(); - const octaves = int( octaves_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); + bindingsGroups.push( bindingsGroup ); - return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ); + } -} ).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' } - ] -} ); + this.bindGroups = bindingsGroups; -const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => { + } - const diminish = float( diminish_immutable ).toVar(); - const lacunarity = float( lacunarity_immutable ).toVar(); - const octaves = int( octaves_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar(); - const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar(); + return bindingsGroups; - return vec4( c, f ); + } -} ).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' } - ] -} ); + sortBindingGroups() { -const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => { + const bindingsGroups = this.getBindings(); - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const yoff = int( yoff_immutable ).toVar(); - const xoff = int( xoff_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const p = vec2( p_immutable ).toVar(); - const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar(); - const off = vec2( tmp.x, tmp.y ).toVar(); - off.subAssign( 0.5 ); - off.mulAssign( jitter ); - off.addAssign( 0.5 ); - const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar(); - const diff = vec2( cellpos.sub( p ) ).toVar(); + bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) ); - If( metric.equal( int( 2 ) ), () => { + for ( let i = 0; i < bindingsGroups.length; i ++ ) { - return abs( diff.x ).add( abs( diff.y ) ); + const bindingGroup = bindingsGroups[ i ]; + this.bindingsIndexes[ bindingGroup.name ].group = i; - } ); + bindingGroup.index = i; - If( metric.equal( int( 3 ) ), () => { + } - return max$1( abs( diff.x ), abs( diff.y ) ); + } - } ); + setHashNode( node, hash ) { - return dot( diff, diff ); + this.hashNodes[ hash ] = node; -} ).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' } - ] -} ); + } -const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => { + addNode( node ) { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const zoff = int( zoff_immutable ).toVar(); - const yoff = int( yoff_immutable ).toVar(); - const xoff = int( xoff_immutable ).toVar(); - const z = int( z_immutable ).toVar(); - const y = int( y_immutable ).toVar(); - const x = int( x_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar(); - off.subAssign( 0.5 ); - off.mulAssign( jitter ); - off.addAssign( 0.5 ); - const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar(); - const diff = vec3( cellpos.sub( p ) ).toVar(); + if ( this.nodes.includes( node ) === false ) { - If( metric.equal( int( 2 ) ), () => { + this.nodes.push( node ); - return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) ); + this.setHashNode( node, node.getHash( this ) ); - } ); + } - If( metric.equal( int( 3 ) ), () => { + } - return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) ); + addSequentialNode( node ) { - } ); + if ( this.sequentialNodes.includes( node ) === false ) { - return dot( diff, diff ); + this.sequentialNodes.push( node ); -} ).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' } - ] -} ); + } -const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] ); + } -const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + buildUpdateNodes() { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); - const sqdist = float( 1e6 ).toVar(); + for ( const node of this.nodes ) { - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + const updateType = node.getUpdateType(); - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + if ( updateType !== NodeUpdateType.NONE ) { - const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); - sqdist.assign( min$1( sqdist, dist ) ); + this.updateNodes.push( node.getSelf() ); - } ); + } - } ); + } - If( metric.equal( int( 0 ) ), () => { + for ( const node of this.sequentialNodes ) { - sqdist.assign( sqrt( sqdist ) ); + const updateBeforeType = node.getUpdateBeforeType(); + const updateAfterType = node.getUpdateAfterType(); - } ); + if ( updateBeforeType !== NodeUpdateType.NONE ) { - return sqdist; + this.updateBeforeNodes.push( node.getSelf() ); -} ).setLayout( { - name: 'mx_worley_noise_float_0', - type: 'float', - inputs: [ - { name: 'p', type: 'vec2' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + } -const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + if ( updateAfterType !== NodeUpdateType.NONE ) { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); - const sqdist = vec2( 1e6, 1e6 ).toVar(); + this.updateAfterNodes.push( node.getSelf() ); - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + } - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + } - const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); + } - If( dist.lessThan( sqdist.x ), () => { + get currentNode() { - sqdist.y.assign( sqdist.x ); - sqdist.x.assign( dist ); + return this.chaining[ this.chaining.length - 1 ]; - } ).ElseIf( dist.lessThan( sqdist.y ), () => { + } - sqdist.y.assign( dist ); + isFilteredTexture( texture ) { - } ); + return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || + texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ); - } ); + } - } ); + addChain( node ) { - If( metric.equal( int( 0 ) ), () => { + /* + if ( this.chaining.indexOf( node ) !== - 1 ) { - sqdist.assign( sqrt( sqdist ) ); + console.warn( 'Recursive node: ', node ); - } ); + } + */ - return sqdist; + this.chaining.push( node ); -} ).setLayout( { - name: 'mx_worley_noise_vec2_0', - type: 'vec2', - inputs: [ - { name: 'p', type: 'vec2' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + } -const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + removeChain( node ) { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec2( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(); - const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar(); - const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar(); + const lastChain = this.chaining.pop(); - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + if ( lastChain !== node ) { - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + throw new Error( 'NodeBuilder: Invalid node chaining!' ); - const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar(); + } - If( dist.lessThan( sqdist.x ), () => { + } - sqdist.z.assign( sqdist.y ); - sqdist.y.assign( sqdist.x ); - sqdist.x.assign( dist ); + getMethod( method ) { - } ).ElseIf( dist.lessThan( sqdist.y ), () => { + return method; - sqdist.z.assign( sqdist.y ); - sqdist.y.assign( dist ); + } - } ).ElseIf( dist.lessThan( sqdist.z ), () => { + getNodeFromHash( hash ) { - sqdist.z.assign( dist ); + return this.hashNodes[ hash ]; - } ); + } - } ); + addFlow( shaderStage, node ) { - } ); + this.flowNodes[ shaderStage ].push( node ); - If( metric.equal( int( 0 ) ), () => { + return node; - sqdist.assign( sqrt( sqdist ) ); + } - } ); + setContext( context ) { - return sqdist; + this.context = context; -} ).setLayout( { - name: 'mx_worley_noise_vec3_0', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec2' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + } -const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + getContext() { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); - const sqdist = float( 1e6 ).toVar(); + return this.context; - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + } - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + getSharedContext() { - Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { + ({ ...this.context }); - const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); - sqdist.assign( min$1( sqdist, dist ) ); + return this.context; - } ); + } - } ); + setCache( cache ) { - } ); + this.cache = cache; - If( metric.equal( int( 0 ) ), () => { + } - sqdist.assign( sqrt( sqdist ) ); + getCache() { - } ); + return this.cache; - return sqdist; + } -} ).setLayout( { - name: 'mx_worley_noise_float_1', - type: 'float', - inputs: [ - { name: 'p', type: 'vec3' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + getCacheFromNode( node, parent = true ) { -const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] ); + const data = this.getDataFromNode( node ); + if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null ); -const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + return data.cache; - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); - const sqdist = vec2( 1e6, 1e6 ).toVar(); + } - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + isAvailable( /*name*/ ) { - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + return false; - Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { + } - const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); + getVertexIndex() { - If( dist.lessThan( sqdist.x ), () => { + console.warn( 'Abstract function.' ); - sqdist.y.assign( sqdist.x ); - sqdist.x.assign( dist ); + } - } ).ElseIf( dist.lessThan( sqdist.y ), () => { + getInstanceIndex() { - sqdist.y.assign( dist ); + console.warn( 'Abstract function.' ); - } ); + } - } ); + getDrawIndex() { - } ); + console.warn( 'Abstract function.' ); - } ); + } - If( metric.equal( int( 0 ) ), () => { + getFrontFacing() { - sqdist.assign( sqrt( sqdist ) ); + console.warn( 'Abstract function.' ); - } ); + } - return sqdist; + getFragCoord() { -} ).setLayout( { - name: 'mx_worley_noise_vec2_1', - type: 'vec2', - inputs: [ - { name: 'p', type: 'vec3' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + console.warn( 'Abstract function.' ); -const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] ); + } -const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => { + isFlipY() { - const metric = int( metric_immutable ).toVar(); - const jitter = float( jitter_immutable ).toVar(); - const p = vec3( p_immutable ).toVar(); - const X = int().toVar(), Y = int().toVar(), Z = int().toVar(); - const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar(); - const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar(); + return false; - Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => { + } - Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => { + increaseUsage( node ) { - Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => { + const nodeData = this.getDataFromNode( node ); + nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1; - const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar(); + return nodeData.usageCount; - If( dist.lessThan( sqdist.x ), () => { + } - sqdist.z.assign( sqdist.y ); - sqdist.y.assign( sqdist.x ); - sqdist.x.assign( dist ); + generateTexture( /* texture, textureProperty, uvSnippet */ ) { - } ).ElseIf( dist.lessThan( sqdist.y ), () => { + console.warn( 'Abstract function.' ); - sqdist.z.assign( sqdist.y ); - sqdist.y.assign( dist ); + } - } ).ElseIf( dist.lessThan( sqdist.z ), () => { + generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) { - sqdist.z.assign( dist ); + console.warn( 'Abstract function.' ); - } ); + } - } ); + generateConst( type, value = null ) { - } ); + if ( value === null ) { - } ); + if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0; + else if ( type === 'bool' ) value = false; + else if ( type === 'color' ) value = new Color(); + else if ( type === 'vec2' ) value = new Vector2(); + else if ( type === 'vec3' ) value = new Vector3(); + else if ( type === 'vec4' ) value = new Vector4(); - If( metric.equal( int( 0 ) ), () => { + } - sqdist.assign( sqrt( sqdist ) ); + if ( type === 'float' ) return toFloat( value ); + if ( type === 'int' ) return `${ Math.round( value ) }`; + if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u'; + if ( type === 'bool' ) return value ? 'true' : 'false'; + if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`; - } ); + const typeLength = this.getTypeLength( type ); - return sqdist; + const componentType = this.getComponentType( type ); -} ).setLayout( { - name: 'mx_worley_noise_vec3_1', - type: 'vec3', - inputs: [ - { name: 'p', type: 'vec3' }, - { name: 'jitter', type: 'float' }, - { name: 'metric', type: 'int' } - ] -} ); + const generateConst = value => this.generateConst( componentType, value ); -const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] ); + if ( typeLength === 2 ) { -// Three.js Transpiler -// https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl + return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`; + } else if ( typeLength === 3 ) { -const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => { + return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`; - const s = hsv.y; - const v = hsv.z; + } else if ( typeLength === 4 ) { - const result = vec3().toVar(); + return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`; - If( s.lessThan( 0.0001 ), () => { + } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) { - result.assign( vec3( v, v, v ) ); + return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`; - } ).Else( () => { + } else if ( typeLength > 4 ) { - let h = hsv.x; - h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache - const hi = int( trunc( h ) ); - const f = h.sub( float( hi ) ); - const p = v.mul( s.oneMinus() ); - const q = v.mul( s.mul( f ).oneMinus() ); - const t = v.mul( s.mul( f.oneMinus() ).oneMinus() ); + return `${ this.getType( type ) }()`; - If( hi.equal( int( 0 ) ), () => { + } - result.assign( vec3( v, t, p ) ); + throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` ); - } ).ElseIf( hi.equal( int( 1 ) ), () => { + } - result.assign( vec3( q, v, p ) ); + getType( type ) { - } ).ElseIf( hi.equal( int( 2 ) ), () => { + if ( type === 'color' ) return 'vec3'; - result.assign( vec3( p, v, t ) ); + return type; - } ).ElseIf( hi.equal( int( 3 ) ), () => { + } - result.assign( vec3( p, q, v ) ); + hasGeometryAttribute( name ) { - } ).ElseIf( hi.equal( int( 4 ) ), () => { + return this.geometry && this.geometry.getAttribute( name ) !== undefined; - result.assign( vec3( t, p, v ) ); + } - } ).Else( () => { + getAttribute( name, type ) { - result.assign( vec3( v, p, q ) ); + const attributes = this.attributes; - } ); + // find attribute - } ); + for ( const attribute of attributes ) { - return result; + if ( attribute.name === name ) { -} ).setLayout( { - name: 'mx_hsvtorgb', - type: 'vec3', - inputs: [ - { name: 'hsv', type: 'vec3' } - ] -} ); + return attribute; -const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => { + } - const c = vec3( c_immutable ).toVar(); - const r = float( c.x ).toVar(); - const g = float( c.y ).toVar(); - const b = float( c.z ).toVar(); - const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar(); - const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar(); - const delta = float( maxcomp.sub( mincomp ) ).toVar(); - const h = float().toVar(), s = float().toVar(), v = float().toVar(); - v.assign( maxcomp ); + } - If( maxcomp.greaterThan( 0.0 ), () => { + // create a new if no exist - s.assign( delta.div( maxcomp ) ); + const attribute = new NodeAttribute( name, type ); - } ).Else( () => { + attributes.push( attribute ); - s.assign( 0.0 ); + return attribute; - } ); + } - If( s.lessThanEqual( 0.0 ), () => { + getPropertyName( node/*, shaderStage*/ ) { - h.assign( 0.0 ); + return node.name; - } ).Else( () => { + } - If( r.greaterThanEqual( maxcomp ), () => { + isVector( type ) { - h.assign( g.sub( b ).div( delta ) ); + return /vec\d/.test( type ); - } ).ElseIf( g.greaterThanEqual( maxcomp ), () => { + } - h.assign( add( 2.0, b.sub( r ).div( delta ) ) ); + isMatrix( type ) { - } ).Else( () => { + return /mat\d/.test( type ); - h.assign( add( 4.0, r.sub( g ).div( delta ) ) ); + } - } ); + isReference( type ) { - h.mulAssign( 1.0 / 6.0 ); + return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D'; - If( h.lessThan( 0.0 ), () => { + } - h.addAssign( 1.0 ); + needsToWorkingColorSpace( /*texture*/ ) { - } ); + return false; - } ); + } - return vec3( h, s, v ); + getComponentTypeFromTexture( texture ) { -} ).setLayout( { - name: 'mx_rgbtohsv', - type: 'vec3', - inputs: [ - { name: 'c', type: 'vec3' } - ] -} ); + const type = texture.type; -// Three.js Transpiler -// https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl + if ( texture.isDataTexture ) { + if ( type === IntType ) return 'int'; + if ( type === UnsignedIntType ) return 'uint'; -const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => { + } - const color = vec3( color_immutable ).toVar(); - const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar(); - const linSeg = vec3( color.div( 12.92 ) ).toVar(); - const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar(); + return 'float'; - return mix( linSeg, powSeg, isAbove ); + } -} ).setLayout( { - name: 'mx_srgb_texture_to_lin_rec709', - type: 'vec3', - inputs: [ - { name: 'color', type: 'vec3' } - ] -} ); + getElementType( type ) { -const mx_aastep = ( threshold, value ) => { + if ( type === 'mat2' ) return 'vec2'; + if ( type === 'mat3' ) return 'vec3'; + if ( type === 'mat4' ) return 'vec4'; - threshold = float( threshold ); - value = float( value ); + return this.getComponentType( type ); - const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 ); + } - return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value ); + getComponentType( type ) { -}; + type = this.getVectorType( type ); -const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() ); -const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' ); -const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' ); + if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type; -const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) ); -const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' ); -const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' ); + const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type ); -const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset ); + if ( componentType === null ) return null; -const mx_safepower = ( in1, in2 = 1 ) => { + if ( componentType[ 1 ] === 'b' ) return 'bool'; + if ( componentType[ 1 ] === 'i' ) return 'int'; + if ( componentType[ 1 ] === 'u' ) return 'uint'; - in1 = float( in1 ); + return 'float'; - return in1.abs().pow( in2 ).mul( in1.sign() ); + } -}; + getVectorType( type ) { -const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot ); + if ( type === 'color' ) return 'vec3'; + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4'; -const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -//export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => { + return type; - texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type + } - const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) ); + getTypeFromLength( length, componentType = 'float' ) { - return noise_vec4.mul( amplitude ).add( pivot ); + if ( length === 1 ) return componentType; -}; + const baseType = typeFromLength.get( length ); + const prefix = componentType === 'float' ? '' : componentType[ 0 ]; -const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); + return prefix + baseType; -const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) ); + } -const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); + getTypeFromArray( array ) { -const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => { + return typeFromArray.get( array.constructor ); - // normal is assumed to have unit length + } - const x = normal.x, y = normal.y, z = normal.z; + getTypeFromAttribute( attribute ) { - // band 0 - let result = shCoefficients.element( 0 ).mul( 0.886227 ); + let dataAttribute = attribute; - // band 1 - result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) ); - result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) ); - result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) ); + if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data; - // band 2 - result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) ); - result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) ); - result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) ); - result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) ); - result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) ); + const array = dataAttribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; - return result; + let arrayType; -} ); + if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) { -class PointLightNode extends AnalyticLightNode { + arrayType = this.getTypeFromArray( array ); - static get type() { + } - return 'PointLightNode'; + return this.getTypeFromLength( itemSize, arrayType ); } - constructor( light = null ) { + getTypeLength( type ) { - super( light ); + const vecType = this.getVectorType( type ); + const vecNum = /vec([2-4])/.exec( vecType ); - this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup ); - this.decayExponentNode = uniform( 0 ).setGroup( renderGroup ); + if ( vecNum !== null ) return Number( vecNum[ 1 ] ); + if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1; + if ( /mat2/.test( type ) === true ) return 4; + if ( /mat3/.test( type ) === true ) return 9; + if ( /mat4/.test( type ) === true ) return 16; + + return 0; } - update( frame ) { + getVectorFromMatrix( type ) { - const { light } = this; + return type.replace( 'mat', 'vec' ); - super.update( frame ); + } - this.cutoffDistanceNode.value = light.distance; - this.decayExponentNode.value = light.decay; + changeComponentType( type, newComponentType ) { + + return this.getTypeFromLength( this.getTypeLength( type ), newComponentType ); } - setup( builder ) { + getIntegerType( type ) { - const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this; + const componentType = this.getComponentType( type ); - const lightingModel = builder.context.lightingModel; + if ( componentType === 'int' || componentType === 'uint' ) return type; - const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode + return this.changeComponentType( type, 'int' ); - const lightDirection = lVector.normalize(); - const lightDistance = lVector.length(); + } - const lightAttenuation = getDistanceAttenuation( { - lightDistance, - cutoffDistance: cutoffDistanceNode, - decayExponent: decayExponentNode - } ); + addStack() { - const lightColor = colorNode.mul( lightAttenuation ); + this.stack = stack( this.stack ); - const reflectedLight = builder.context.reflectedLight; + this.stacks.push( getCurrentStack() || this.stack ); + setCurrentStack( this.stack ); - lightingModel.direct( { - lightDirection, - lightColor, - reflectedLight - }, builder.stack, builder ); + return this.stack; } -} + removeStack() { -class DirectionalLightNode extends AnalyticLightNode { + const lastStack = this.stack; + this.stack = lastStack.parent; - static get type() { + setCurrentStack( this.stacks.pop() ); - return 'DirectionalLightNode'; + return lastStack; } - constructor( light = null ) { + getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) { - super( light ); + cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache; - } + let nodeData = cache.getData( node ); - setup( builder ) { + if ( nodeData === undefined ) { - super.setup( builder ); + nodeData = {}; - const lightingModel = builder.context.lightingModel; + cache.setData( node, nodeData ); - const lightColor = this.colorNode; - const lightDirection = lightTargetDirection( this.light ); - const reflectedLight = builder.context.reflectedLight; + } - lightingModel.direct( { - lightDirection, - lightColor, - reflectedLight - }, builder.stack, builder ); + if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {}; + + return nodeData[ shaderStage ]; + + } + + getNodeProperties( node, shaderStage = 'any' ) { + + const nodeData = this.getDataFromNode( node, shaderStage ); + + return nodeData.properties || ( nodeData.properties = { outputNode: null } ); } -} + getBufferAttributeFromNode( node, type ) { -const _matrix41 = /*@__PURE__*/ new Matrix4(); -const _matrix42 = /*@__PURE__*/ new Matrix4(); + const nodeData = this.getDataFromNode( node ); -let ltcLib = null; + let bufferAttribute = nodeData.bufferAttribute; -class RectAreaLightNode extends AnalyticLightNode { + if ( bufferAttribute === undefined ) { - static get type() { + const index = this.uniforms.index ++; - return 'RectAreaLightNode'; + bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node ); - } + this.bufferAttributes.push( bufferAttribute ); - constructor( light = null ) { + nodeData.bufferAttribute = bufferAttribute; - super( light ); + } - this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup ); - this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup ); + return bufferAttribute; } - update( frame ) { + getStructTypeFromNode( node, shaderStage = this.shaderStage ) { - super.update( frame ); + const nodeData = this.getDataFromNode( node, shaderStage ); - const { light } = this; + if ( nodeData.structType === undefined ) { - const viewMatrix = frame.camera.matrixWorldInverse; + const index = this.structs.index ++; - _matrix42.identity(); - _matrix41.copy( light.matrixWorld ); - _matrix41.premultiply( viewMatrix ); - _matrix42.extractRotation( _matrix41 ); + node.name = `StructType${ index }`; + this.structs[ shaderStage ].push( node ); - this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 ); - this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 ); + nodeData.structType = node; - this.halfWidth.value.applyMatrix4( _matrix42 ); - this.halfHeight.value.applyMatrix4( _matrix42 ); + } - } + return node; - setup( builder ) { + } - super.setup( builder ); + getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) { - let ltc_1, ltc_2; + const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache ); - if ( builder.isAvailable( 'float32Filterable' ) ) { + let nodeUniform = nodeData.uniform; - ltc_1 = texture( ltcLib.LTC_FLOAT_1 ); - ltc_2 = texture( ltcLib.LTC_FLOAT_2 ); + if ( nodeUniform === undefined ) { - } else { + const index = this.uniforms.index ++; - ltc_1 = texture( ltcLib.LTC_HALF_1 ); - ltc_2 = texture( ltcLib.LTC_HALF_2 ); + nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node ); - } + this.uniforms[ shaderStage ].push( nodeUniform ); - const { colorNode, light } = this; - const lightingModel = builder.context.lightingModel; + nodeData.uniform = nodeUniform; - const lightPosition = lightViewPosition( light ); - const reflectedLight = builder.context.reflectedLight; + } - lightingModel.directRectArea( { - lightColor: colorNode, - lightPosition, - halfWidth: this.halfWidth, - halfHeight: this.halfHeight, - reflectedLight, - ltc_1, - ltc_2 - }, builder.stack, builder ); + return nodeUniform; } - static setLTC( ltc ) { - - ltcLib = ltc; + getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) { - } + const nodeData = this.getDataFromNode( node, shaderStage ); -} + let nodeVar = nodeData.variable; -class SpotLightNode extends AnalyticLightNode { + if ( nodeVar === undefined ) { - static get type() { + const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] ); - return 'SpotLightNode'; + if ( name === null ) name = 'nodeVar' + vars.length; - } + nodeVar = new NodeVar( name, type ); - constructor( light = null ) { + vars.push( nodeVar ); - super( light ); + nodeData.variable = nodeVar; - this.coneCosNode = uniform( 0 ).setGroup( renderGroup ); - this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup ); + } - this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup ); - this.decayExponentNode = uniform( 0 ).setGroup( renderGroup ); + return nodeVar; } - update( frame ) { + getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) { - super.update( frame ); + const nodeData = this.getDataFromNode( node, 'any' ); - const { light } = this; + let nodeVarying = nodeData.varying; - this.coneCosNode.value = Math.cos( light.angle ); - this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) ); + if ( nodeVarying === undefined ) { - this.cutoffDistanceNode.value = light.distance; - this.decayExponentNode.value = light.decay; + const varyings = this.varyings; + const index = varyings.length; - } + if ( name === null ) name = 'nodeVarying' + index; - getSpotAttenuation( angleCosine ) { + nodeVarying = new NodeVarying( name, type ); - const { coneCosNode, penumbraCosNode } = this; + varyings.push( nodeVarying ); - return smoothstep( coneCosNode, penumbraCosNode, angleCosine ); + nodeData.varying = nodeVarying; - } + } - setup( builder ) { + return nodeVarying; - super.setup( builder ); + } - const lightingModel = builder.context.lightingModel; + getCodeFromNode( node, type, shaderStage = this.shaderStage ) { - const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this; + const nodeData = this.getDataFromNode( node ); - const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode + let nodeCode = nodeData.code; - const lightDirection = lVector.normalize(); - const angleCos = lightDirection.dot( lightTargetDirection( light ) ); - const spotAttenuation = this.getSpotAttenuation( angleCos ); + if ( nodeCode === undefined ) { - const lightDistance = lVector.length(); + const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] ); + const index = codes.length; - const lightAttenuation = getDistanceAttenuation( { - lightDistance, - cutoffDistance: cutoffDistanceNode, - decayExponent: decayExponentNode - } ); + nodeCode = new NodeCode( 'nodeCode' + index, type ); - const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation ); + codes.push( nodeCode ); - const reflectedLight = builder.context.reflectedLight; + nodeData.code = nodeCode; - lightingModel.direct( { - lightDirection, - lightColor, - reflectedLight - }, builder.stack, builder ); + } + + return nodeCode; } -} + addFlowCodeHierarchy( node, nodeBlock ) { -class IESSpotLightNode extends SpotLightNode { + const { flowCodes, flowCodeBlock } = this.getDataFromNode( node ); - static get type() { + let needsFlowCode = true; + let nodeBlockHierarchy = nodeBlock; - return 'IESSpotLightNode'; + while ( nodeBlockHierarchy ) { - } + if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) { - getSpotAttenuation( angleCosine ) { + needsFlowCode = false; + break; - const iesMap = this.light.iesMap; + } - let spotAttenuation = null; + nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock; - if ( iesMap && iesMap.isTexture === true ) { + } - const angle = angleCosine.acos().mul( 1.0 / Math.PI ); + if ( needsFlowCode ) { - spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r; + for ( const flowCode of flowCodes ) { - } else { + this.addLineFlowCode( flowCode ); - spotAttenuation = super.getSpotAttenuation( angleCosine ); + } } - return spotAttenuation; - } -} - -class AmbientLightNode extends AnalyticLightNode { + addLineFlowCodeBlock( node, code, nodeBlock ) { - static get type() { + const nodeData = this.getDataFromNode( node ); + const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] ); + const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() ); - return 'AmbientLightNode'; + flowCodes.push( code ); + codeBlock.set( nodeBlock, true ); } - constructor( light = null ) { + addLineFlowCode( code, node = null ) { - super( light ); + if ( code === '' ) return this; - } + if ( node !== null && this.context.nodeBlock ) { - setup( { context } ) { + this.addLineFlowCodeBlock( node, code, this.context.nodeBlock ); - context.irradiance.addAssign( this.colorNode ); + } - } + code = this.tab + code; -} + if ( ! /;\s*$/.test( code ) ) { -class HemisphereLightNode extends AnalyticLightNode { + code = code + ';\n'; - static get type() { + } - return 'HemisphereLightNode'; + this.flow.code += code; - } + return this; - constructor( light = null ) { + } - super( light ); + addFlowCode( code ) { - this.lightPositionNode = lightPosition( light ); - this.lightDirectionNode = this.lightPositionNode.normalize(); + this.flow.code += code; - this.groundColorNode = uniform( new Color() ).setGroup( renderGroup ); + return this; } - update( frame ) { - - const { light } = this; - - super.update( frame ); + addFlowTab() { - this.lightPositionNode.object3d = light; + this.tab += '\t'; - this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity ); + return this; } - setup( builder ) { + removeFlowTab() { - const { colorNode, groundColorNode, lightDirectionNode } = this; + this.tab = this.tab.slice( 0, - 1 ); - const dotNL = normalView.dot( lightDirectionNode ); - const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 ); + return this; - const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight ); + } - builder.context.irradiance.addAssign( irradiance ); + getFlowData( node/*, shaderStage*/ ) { + + return this.flowsData.get( node ); } -} + flowNode( node ) { -class LightProbeNode extends AnalyticLightNode { + const output = node.getNodeType( this ); - static get type() { + const flowData = this.flowChildNode( node, output ); - return 'LightProbeNode'; + this.flowsData.set( node, flowData ); + + return flowData; } - constructor( light = null ) { + buildFunctionNode( shaderNode ) { - super( light ); + const fn = new FunctionNode(); - const array = []; + const previous = this.currentFunctionNode; - for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() ); + this.currentFunctionNode = fn; - this.lightProbe = uniformArray( array ); + fn.code = this.buildFunctionCode( shaderNode ); + + this.currentFunctionNode = previous; + + return fn; } - update( frame ) { + flowShaderNode( shaderNode ) { - const { light } = this; + const layout = shaderNode.layout; - super.update( frame ); + const inputs = { + [ Symbol.iterator ]() { - // + let index = 0; + const values = Object.values( this ); + return { + next: () => ( { + value: values[ index ], + done: index ++ >= values.length + } ) + }; - for ( let i = 0; i < 9; i ++ ) { + } + }; - this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity ); + for ( const input of layout.inputs ) { + + inputs[ input.name ] = new ParameterNode( input.type, input.name ); } - } + // - setup( builder ) { + shaderNode.layout = null; - const irradiance = getShIrradianceAt( normalWorld, this.lightProbe ); + const callNode = shaderNode.call( inputs ); + const flowData = this.flowStagesNode( callNode, layout.type ); - builder.context.irradiance.addAssign( irradiance ); + shaderNode.layout = layout; + + return flowData; } -} + flowStagesNode( node, output = null ) { -class NodeParser { + const previousFlow = this.flow; + const previousVars = this.vars; + const previousCache = this.cache; + const previousBuildStage = this.buildStage; + const previousStack = this.stack; - parseFunction( /*source*/ ) { + const flow = { + code: '' + }; - console.warn( 'Abstract function.' ); + this.flow = flow; + this.vars = {}; + this.cache = new NodeCache(); + this.stack = stack(); - } + for ( const buildStage of defaultBuildStages ) { -} + this.setBuildStage( buildStage ); -class NodeFunction { + flow.result = node.build( this, output ); - constructor( type, inputs, name = '', precision = '' ) { + } - this.type = type; - this.inputs = inputs; - this.name = name; - this.precision = precision; + flow.vars = this.getVars( this.shaderStage ); - } + this.flow = previousFlow; + this.vars = previousVars; + this.cache = previousCache; + this.stack = previousStack; - getCode( /*name = this.name*/ ) { + this.setBuildStage( previousBuildStage ); - console.warn( 'Abstract function.' ); + return flow; } -} + getFunctionOperator() { -NodeFunction.isNodeFunction = true; + return null; -const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i; -const propertiesRegexp$1 = /[a-z_0-9]+/ig; + } -const pragmaMain = '#pragma main'; + flowChildNode( node, output = null ) { -const parse$1 = ( source ) => { + const previousFlow = this.flow; - source = source.trim(); + const flow = { + code: '' + }; - const pragmaMainIndex = source.indexOf( pragmaMain ); + this.flow = flow; - const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source; + flow.result = node.build( this, output ); - const declaration = mainCode.match( declarationRegexp$1 ); + this.flow = previousFlow; - if ( declaration !== null && declaration.length === 5 ) { + return flow; - // tokenizer + } - const inputsCode = declaration[ 4 ]; - const propsMatches = []; + flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) { - let nameMatch = null; + const previousShaderStage = this.shaderStage; - while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) { + this.setShaderStage( shaderStage ); - propsMatches.push( nameMatch ); + const flowData = this.flowChildNode( node, output ); + + if ( propertyName !== null ) { + + flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`; } - // parser + this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code; - const inputs = []; + this.setShaderStage( previousShaderStage ); - let i = 0; + return flowData; - while ( i < propsMatches.length ) { + } - const isConst = propsMatches[ i ][ 0 ] === 'const'; + getAttributesArray() { - if ( isConst === true ) { + return this.attributes.concat( this.bufferAttributes ); - i ++; + } - } + getAttributes( /*shaderStage*/ ) { - let qualifier = propsMatches[ i ][ 0 ]; + console.warn( 'Abstract function.' ); - if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) { + } - i ++; + getVaryings( /*shaderStage*/ ) { - } else { + console.warn( 'Abstract function.' ); - qualifier = ''; + } - } + getVar( type, name ) { - const type = propsMatches[ i ++ ][ 0 ]; + return `${ this.getType( type ) } ${ name }`; - let count = Number.parseInt( propsMatches[ i ][ 0 ] ); + } - if ( Number.isNaN( count ) === false ) i ++; - else count = null; + getVars( shaderStage ) { - const name = propsMatches[ i ++ ][ 0 ]; + let snippet = ''; - inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) ); + const vars = this.vars[ shaderStage ]; - } + if ( vars !== undefined ) { - // + for ( const variable of vars ) { - const blockCode = mainCode.substring( declaration[ 0 ].length ); + snippet += `${ this.getVar( variable.type, variable.name ) }; `; - const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : ''; - const type = declaration[ 2 ]; + } - const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : ''; + } - const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : ''; + return snippet; - return { - type, - inputs, - name, - precision, - inputsCode, - blockCode, - headerCode - }; + } - } else { + getUniforms( /*shaderStage*/ ) { - throw new Error( 'FunctionNode: Function is not a GLSL code.' ); + console.warn( 'Abstract function.' ); } -}; - -class GLSLNodeFunction extends NodeFunction { + getCodes( shaderStage ) { - constructor( source ) { + const codes = this.codes[ shaderStage ]; - const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source ); + let code = ''; - super( type, inputs, name, precision ); + if ( codes !== undefined ) { - this.inputsCode = inputsCode; - this.blockCode = blockCode; - this.headerCode = headerCode; + for ( const nodeCode of codes ) { - } + code += nodeCode.code + '\n'; - getCode( name = this.name ) { + } - let code; + } - const blockCode = this.blockCode; + return code; - if ( blockCode !== '' ) { + } - const { type, inputsCode, headerCode, precision } = this; + getHash() { - let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`; + return this.vertexShader + this.fragmentShader + this.computeShader; - if ( precision !== '' ) { + } - declarationCode = `${ precision } ${ declarationCode }`; + setShaderStage( shaderStage ) { - } + this.shaderStage = shaderStage; - code = headerCode + declarationCode + blockCode; + } - } else { + getShaderStage() { - // interface function + return this.shaderStage; - code = ''; + } - } + setBuildStage( buildStage ) { - return code; + this.buildStage = buildStage; } -} + getBuildStage() { + + return this.buildStage; -class GLSLNodeParser extends NodeParser { + } - parseFunction( source ) { + buildCode() { - return new GLSLNodeFunction( source ); + console.warn( 'Abstract function.' ); } -} + build() { -function painterSortStable( a, b ) { + const { object, material, renderer } = this; - if ( a.groupOrder !== b.groupOrder ) { + if ( material !== null ) { - return a.groupOrder - b.groupOrder; + let nodeMaterial = renderer.library.fromMaterial( material ); - } else if ( a.renderOrder !== b.renderOrder ) { + if ( nodeMaterial === null ) { - return a.renderOrder - b.renderOrder; + console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` ); - } else if ( a.material.id !== b.material.id ) { + nodeMaterial = new NodeMaterial(); - return a.material.id - b.material.id; + } - } else if ( a.z !== b.z ) { + nodeMaterial.build( this ); - return a.z - b.z; + } else { - } else { + this.addFlow( 'compute', object ); - return a.id - b.id; + } - } + // setup() -> stage 1: create possible new nodes and returns an output reference node + // analyze() -> stage 2: analyze nodes to possible optimization and validation + // generate() -> stage 3: generate shader -} + for ( const buildStage of defaultBuildStages ) { -function reversePainterSortStable( a, b ) { + this.setBuildStage( buildStage ); - if ( a.groupOrder !== b.groupOrder ) { + if ( this.context.vertex && this.context.vertex.isNode ) { - return a.groupOrder - b.groupOrder; + this.flowNodeFromShaderStage( 'vertex', this.context.vertex ); - } else if ( a.renderOrder !== b.renderOrder ) { + } - return a.renderOrder - b.renderOrder; + for ( const shaderStage of shaderStages ) { - } else if ( a.z !== b.z ) { + this.setShaderStage( shaderStage ); - return b.z - a.z; + const flowNodes = this.flowNodes[ shaderStage ]; - } else { + for ( const node of flowNodes ) { - return a.id - b.id; + if ( buildStage === 'generate' ) { - } + this.flowNode( node ); -} + } else { -class RenderList { + node.build( this ); - constructor() { + } - this.renderItems = []; - this.renderItemsIndex = 0; + } - this.opaque = []; - this.transparent = []; - this.bundles = []; + } - this.lightsNode = new LightsNode( [] ); - this.lightsArray = []; + } - this.occlusionQueryCount = 0; + this.setBuildStage( null ); + this.setShaderStage( null ); - } + // stage 4: build code for a specific output - begin() { + this.buildCode(); + this.buildUpdateNodes(); - this.renderItemsIndex = 0; + return this; - this.opaque.length = 0; - this.transparent.length = 0; - this.bundles.length = 0; + } - this.lightsArray.length = 0; + getNodeUniform( uniformNode, type ) { - this.occlusionQueryCount = 0; + if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode ); + if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode ); + if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode ); + if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode ); + if ( type === 'color' ) return new ColorNodeUniform( uniformNode ); + if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode ); + if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode ); - return this; + throw new Error( `Uniform "${type}" not declared.` ); } - getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168 - let renderItem = this.renderItems[ this.renderItemsIndex ]; + throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` ); - if ( renderItem === undefined ) { + } - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - groupOrder: groupOrder, - renderOrder: object.renderOrder, - z: z, - group: group - }; + format( snippet, fromType, toType ) { - this.renderItems[ this.renderItemsIndex ] = renderItem; + fromType = this.getVectorType( fromType ); + toType = this.getVectorType( toType ); - } else { + if ( fromType === toType || toType === null || this.isReference( toType ) ) { - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.groupOrder = groupOrder; - renderItem.renderOrder = object.renderOrder; - renderItem.z = z; - renderItem.group = group; + return snippet; } - this.renderItemsIndex ++; - - return renderItem; - - } + const fromTypeLength = this.getTypeLength( fromType ); + const toTypeLength = this.getTypeLength( toType ); - push( object, geometry, material, groupOrder, z, group ) { + if ( fromTypeLength === 16 && toTypeLength === 9 ) { - const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group ); + return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`; - if ( object.occlusionTest === true ) this.occlusionQueryCount ++; + } - ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem ); + if ( fromTypeLength === 9 && toTypeLength === 4 ) { - } + return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`; - unshift( object, geometry, material, groupOrder, z, group ) { + } - const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group ); - ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem ); + if ( fromTypeLength > 4 ) { // fromType is matrix-like - } + // @TODO: ignore for now - pushBundle( group ) { + return snippet; - this.bundles.push( group ); + } - } + if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown - pushLight( light ) { + // @TODO: ignore for now - this.lightsArray.push( light ); + return snippet; - } + } - sort( customOpaqueSort, customTransparentSort ) { + if ( fromTypeLength === toTypeLength ) { - if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable ); - if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable ); + return `${ this.getType( toType ) }( ${ snippet } )`; - } + } - finish() { + if ( fromTypeLength > toTypeLength ) { - // update lights + return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType ); - this.lightsNode.setLights( this.lightsArray ); + } - // Clear references from inactive renderItems in the list + if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like - for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) { + return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`; - const renderItem = this.renderItems[ i ]; + } - if ( renderItem.id === null ) break; + if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like - renderItem.id = null; - renderItem.object = null; - renderItem.geometry = null; - renderItem.material = null; - renderItem.groupOrder = null; - renderItem.renderOrder = null; - renderItem.z = null; - renderItem.group = null; + return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`; } - } + if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like -} + // convert a number value to vector type, e.g: + // vec3( 1u ) -> vec3( float( 1u ) ) -class RenderLists { + snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`; - constructor() { + } - this.lists = new ChainMap(); + return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like } - get( scene, camera ) { + getSignature() { - const lists = this.lists; - const keys = [ scene, camera ]; + return `// Three.js r${ REVISION } - Node System\n`; - let list = lists.get( keys ); + } - if ( list === undefined ) { +} - list = new RenderList(); - lists.set( keys, list ); +class NodeFrame { - } + constructor() { - return list; + this.time = 0; + this.deltaTime = 0; - } + this.frameId = 0; + this.renderId = 0; - dispose() { + this.startTime = null; - this.lists = new ChainMap(); + 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( referenceMap, nodeRef ) { -let id = 0; + let maps = referenceMap.get( nodeRef ); -class RenderContext { + if ( maps === undefined ) { - constructor() { + maps = { + renderMap: new WeakMap(), + frameMap: new WeakMap() + }; - this.id = id ++; + referenceMap.set( nodeRef, maps ); - this.color = true; - this.clearColor = true; - this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 }; + } - this.depth = true; - this.clearDepth = true; - this.clearDepthValue = 1; + return maps; - this.stencil = false; - this.clearStencil = true; - this.clearStencilValue = 1; + } - this.viewport = false; - this.viewportValue = new Vector4(); + updateBeforeNode( node ) { - this.scissor = false; - this.scissorValue = new Vector4(); + const updateType = node.getUpdateBeforeType(); + const reference = node.updateReference( this ); - this.textures = null; - this.depthTexture = null; - this.activeCubeFace = 0; - this.sampleCount = 1; + if ( updateType === NodeUpdateType.FRAME ) { - this.width = 0; - this.height = 0; + const { frameMap } = this._getMaps( this.updateBeforeMap, reference ); - this.isRenderContext = true; + if ( frameMap.get( reference ) !== this.frameId ) { - } + if ( node.updateBefore( this ) !== false ) { - getCacheKey() { + frameMap.set( reference, this.frameId ); - return getCacheKey( this ); + } - } + } -} + } else if ( updateType === NodeUpdateType.RENDER ) { -function getCacheKey( renderContext ) { + const { renderMap } = this._getMaps( this.updateBeforeMap, reference ); - const { textures, activeCubeFace } = renderContext; + if ( renderMap.get( reference ) !== this.renderId ) { - const values = [ activeCubeFace ]; + if ( node.updateBefore( this ) !== false ) { - for ( const texture of textures ) { + renderMap.set( reference, this.renderId ); - values.push( texture.id ); + } - } + } - return hashArray( values ); + } else if ( updateType === NodeUpdateType.OBJECT ) { -} + node.updateBefore( this ); -class RenderContexts { + } - constructor() { + } - this.chainMaps = {}; + updateAfterNode( node ) { - } + const updateType = node.getUpdateAfterType(); + const reference = node.updateReference( this ); - get( scene, camera, renderTarget = null ) { + if ( updateType === NodeUpdateType.FRAME ) { - const chainKey = [ scene, camera ]; + const { frameMap } = this._getMaps( this.updateAfterMap, reference ); - let attachmentState; + if ( frameMap.get( reference ) !== this.frameId ) { - if ( renderTarget === null ) { + if ( node.updateAfter( this ) !== false ) { - attachmentState = 'default'; + frameMap.set( reference, this.frameId ); - } else { + } - const format = renderTarget.texture.format; - const count = renderTarget.textures.length; + } - attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`; + } else if ( updateType === NodeUpdateType.RENDER ) { - } + const { renderMap } = this._getMaps( this.updateAfterMap, reference ); - const chainMap = this.getChainMap( attachmentState ); + if ( renderMap.get( reference ) !== this.renderId ) { - let renderState = chainMap.get( chainKey ); + if ( node.updateAfter( this ) !== false ) { - if ( renderState === undefined ) { + renderMap.set( reference, this.renderId ); - renderState = new RenderContext(); + } - chainMap.set( chainKey, renderState ); + } - } + } else if ( updateType === NodeUpdateType.OBJECT ) { - if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; + node.updateAfter( this ); - return renderState; + } } - getChainMap( attachmentState ) { + updateNode( node ) { - return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() ); + const updateType = node.getUpdateType(); + const reference = node.updateReference( this ); - } + if ( updateType === NodeUpdateType.FRAME ) { - dispose() { + const { frameMap } = this._getMaps( this.updateMap, reference ); - this.chainMaps = {}; + if ( frameMap.get( reference ) !== this.frameId ) { - } + if ( node.update( this ) !== false ) { -} + frameMap.set( reference, this.frameId ); -const _size = /*@__PURE__*/ new Vector3(); + } -class Textures extends DataMap { + } - constructor( renderer, backend, info ) { + } else if ( updateType === NodeUpdateType.RENDER ) { - super(); + const { renderMap } = this._getMaps( this.updateMap, reference ); - this.renderer = renderer; - this.backend = backend; - this.info = info; + if ( renderMap.get( reference ) !== this.renderId ) { - } + if ( node.update( this ) !== false ) { - updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) { + renderMap.set( reference, this.renderId ); - const renderTargetData = this.get( renderTarget ); + } - const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; - const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} ); + } - const textures = renderTarget.textures; + } else if ( updateType === NodeUpdateType.OBJECT ) { - const size = this.getSize( textures[ 0 ] ); + node.update( this ); - const mipWidth = size.width >> activeMipmapLevel; - const mipHeight = size.height >> activeMipmapLevel; + } - let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ]; - const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true; + } - let textureNeedsUpdate = false; + update() { - if ( depthTexture === undefined && useDepthTexture ) { + this.frameId ++; - depthTexture = new DepthTexture(); - depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat; - depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType - depthTexture.image.width = mipWidth; - depthTexture.image.height = mipHeight; + if ( this.lastTime === undefined ) this.lastTime = performance.now(); - depthTextureMips[ activeMipmapLevel ] = depthTexture; + this.deltaTime = ( performance.now() - this.lastTime ) / 1000; - } + this.lastTime = performance.now(); - if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) { + this.time += this.deltaTime; - textureNeedsUpdate = true; + } - if ( depthTexture ) { +} - depthTexture.needsUpdate = true; - depthTexture.image.width = mipWidth; - depthTexture.image.height = mipHeight; +class NodeFunctionInput { - } + constructor( type, name, count = null, qualifier = '', isConst = false ) { - } + this.type = type; + this.name = name; + this.count = count; + this.qualifier = qualifier; + this.isConst = isConst; - renderTargetData.width = size.width; - renderTargetData.height = size.height; - renderTargetData.textures = textures; - renderTargetData.depthTexture = depthTexture || null; - renderTargetData.depth = renderTarget.depthBuffer; - renderTargetData.stencil = renderTarget.stencilBuffer; - renderTargetData.renderTarget = renderTarget; + } - if ( renderTargetData.sampleCount !== sampleCount ) { +} - textureNeedsUpdate = true; +NodeFunctionInput.isNodeFunctionInput = true; - if ( depthTexture ) { +class DirectionalLightNode extends AnalyticLightNode { - depthTexture.needsUpdate = true; + static get type() { - } + return 'DirectionalLightNode'; - renderTargetData.sampleCount = sampleCount; + } - } + constructor( light = null ) { - // + super( light ); - const options = { sampleCount }; + } - for ( let i = 0; i < textures.length; i ++ ) { + setup( builder ) { - const texture = textures[ i ]; + super.setup( builder ); - if ( textureNeedsUpdate ) texture.needsUpdate = true; + const lightingModel = builder.context.lightingModel; - this.updateTexture( texture, options ); + const lightColor = this.colorNode; + const lightDirection = lightTargetDirection( this.light ); + const reflectedLight = builder.context.reflectedLight; - } + lightingModel.direct( { + lightDirection, + lightColor, + reflectedLight + }, builder.stack, builder ); - if ( depthTexture ) { + } - this.updateTexture( depthTexture, options ); +} - } +const _matrix41 = /*@__PURE__*/ new Matrix4(); +const _matrix42 = /*@__PURE__*/ new Matrix4(); - // dispose handler +let ltcLib = null; - if ( renderTargetData.initialized !== true ) { +class RectAreaLightNode extends AnalyticLightNode { - renderTargetData.initialized = true; + static get type() { - // dispose + return 'RectAreaLightNode'; - const onDispose = () => { + } - renderTarget.removeEventListener( 'dispose', onDispose ); + constructor( light = null ) { - for ( let i = 0; i < textures.length; i ++ ) { + super( light ); - this._destroyTexture( textures[ i ] ); + this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup ); + this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup ); - } + } - if ( depthTexture ) { + update( frame ) { - this._destroyTexture( depthTexture ); + super.update( frame ); - } + const { light } = this; - this.delete( renderTarget ); + const viewMatrix = frame.camera.matrixWorldInverse; - }; + _matrix42.identity(); + _matrix41.copy( light.matrixWorld ); + _matrix41.premultiply( viewMatrix ); + _matrix42.extractRotation( _matrix41 ); - renderTarget.addEventListener( 'dispose', onDispose ); + this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 ); + this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 ); - } + this.halfWidth.value.applyMatrix4( _matrix42 ); + this.halfHeight.value.applyMatrix4( _matrix42 ); } - updateTexture( texture, options = {} ) { + setup( builder ) { + + super.setup( builder ); - const textureData = this.get( texture ); - if ( textureData.initialized === true && textureData.version === texture.version ) return; + let ltc_1, ltc_2; - const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture; - const backend = this.backend; + if ( builder.isAvailable( 'float32Filterable' ) ) { - if ( isRenderTarget && textureData.initialized === true ) { + ltc_1 = texture( ltcLib.LTC_FLOAT_1 ); + ltc_2 = texture( ltcLib.LTC_FLOAT_2 ); - // it's an update + } else { - backend.destroySampler( texture ); - backend.destroyTexture( texture ); + ltc_1 = texture( ltcLib.LTC_HALF_1 ); + ltc_2 = texture( ltcLib.LTC_HALF_2 ); } - // - - if ( texture.isFramebufferTexture ) { + const { colorNode, light } = this; + const lightingModel = builder.context.lightingModel; - const renderer = this.renderer; - const renderTarget = renderer.getRenderTarget(); + const lightPosition = lightViewPosition( light ); + const reflectedLight = builder.context.reflectedLight; - if ( renderTarget ) { + lightingModel.directRectArea( { + lightColor: colorNode, + lightPosition, + halfWidth: this.halfWidth, + halfHeight: this.halfHeight, + reflectedLight, + ltc_1, + ltc_2 + }, builder.stack, builder ); - texture.type = renderTarget.texture.type; + } - } else { + static setLTC( ltc ) { - texture.type = UnsignedByteType; + ltcLib = ltc; - } + } - } +} - // +class SpotLightNode extends AnalyticLightNode { - const { width, height, depth } = this.getSize( texture ); + static get type() { - options.width = width; - options.height = height; - options.depth = depth; - options.needsMipmaps = this.needsMipmaps( texture ); - options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1; + return 'SpotLightNode'; - // + } - if ( isRenderTarget || texture.isStorageTexture === true ) { + constructor( light = null ) { - backend.createSampler( texture ); - backend.createTexture( texture, options ); + super( light ); - textureData.generation = texture.version; + this.coneCosNode = uniform( 0 ).setGroup( renderGroup ); + this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup ); - } else { + this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup ); + this.decayExponentNode = uniform( 0 ).setGroup( renderGroup ); - const needsCreate = textureData.initialized !== true; + } - if ( needsCreate ) backend.createSampler( texture ); + update( frame ) { - if ( texture.version > 0 ) { + super.update( frame ); - const image = texture.image; + const { light } = this; - if ( image === undefined ) { + this.coneCosNode.value = Math.cos( light.angle ); + this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) ); - console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' ); + this.cutoffDistanceNode.value = light.distance; + this.decayExponentNode.value = light.decay; - } else if ( image.complete === false ) { + } - console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' ); + getSpotAttenuation( angleCosine ) { - } else { + const { coneCosNode, penumbraCosNode } = this; - if ( texture.images ) { + return smoothstep( coneCosNode, penumbraCosNode, angleCosine ); - const images = []; + } - for ( const image of texture.images ) { + setup( builder ) { - images.push( image ); + super.setup( builder ); - } + const lightingModel = builder.context.lightingModel; - options.images = images; + const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this; - } else { + const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode - options.image = image; + const lightDirection = lVector.normalize(); + const angleCos = lightDirection.dot( lightTargetDirection( light ) ); + const spotAttenuation = this.getSpotAttenuation( angleCos ); - } + const lightDistance = lVector.length(); - if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) { + const lightAttenuation = getDistanceAttenuation( { + lightDistance, + cutoffDistance: cutoffDistanceNode, + decayExponent: decayExponentNode + } ); - backend.createTexture( texture, options ); + const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation ); - textureData.isDefaultTexture = false; - textureData.generation = texture.version; + const reflectedLight = builder.context.reflectedLight; - } + lightingModel.direct( { + lightDirection, + lightColor, + reflectedLight + }, builder.stack, builder ); - if ( texture.source.dataReady === true ) backend.updateTexture( texture, options ); + } - if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture ); +} - } +class IESSpotLightNode extends SpotLightNode { - } else { + static get type() { - // async update + return 'IESSpotLightNode'; - backend.createDefaultTexture( texture ); + } - textureData.isDefaultTexture = true; - textureData.generation = texture.version; + getSpotAttenuation( angleCosine ) { - } + const iesMap = this.light.iesMap; - } + let spotAttenuation = null; - // dispose handler + if ( iesMap && iesMap.isTexture === true ) { - if ( textureData.initialized !== true ) { + const angle = angleCosine.acos().mul( 1.0 / Math.PI ); - textureData.initialized = true; - textureData.generation = texture.version; + spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r; - // + } else { - this.info.memory.textures ++; + spotAttenuation = super.getSpotAttenuation( angleCosine ); - // dispose + } - const onDispose = () => { + return spotAttenuation; - texture.removeEventListener( 'dispose', onDispose ); + } - this._destroyTexture( texture ); +} - this.info.memory.textures --; +class AmbientLightNode extends AnalyticLightNode { - }; + static get type() { - texture.addEventListener( 'dispose', onDispose ); + return 'AmbientLightNode'; - } + } - // + constructor( light = null ) { - textureData.version = texture.version; + super( light ); } - getSize( texture, target = _size ) { + setup( { context } ) { - let image = texture.images ? texture.images[ 0 ] : texture.image; + context.irradiance.addAssign( this.colorNode ); - if ( image ) { + } - if ( image.image !== undefined ) image = image.image; +} - target.width = image.width; - target.height = image.height; - target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 ); +class HemisphereLightNode extends AnalyticLightNode { - } else { + static get type() { - target.width = target.height = target.depth = 1; + return 'HemisphereLightNode'; - } + } - return target; + constructor( light = null ) { - } + super( light ); - getMipLevels( texture, width, height ) { + this.lightPositionNode = lightPosition( light ); + this.lightDirectionNode = this.lightPositionNode.normalize(); - let mipLevelCount; + this.groundColorNode = uniform( new Color() ).setGroup( renderGroup ); - if ( texture.isCompressedTexture ) { + } - mipLevelCount = texture.mipmaps.length; + update( frame ) { - } else { + const { light } = this; - mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1; + super.update( frame ); - } + this.lightPositionNode.object3d = light; - return mipLevelCount; + this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity ); } - needsMipmaps( texture ) { + setup( builder ) { - if ( this.isEnvironmentTexture( texture ) ) return true; + const { colorNode, groundColorNode, lightDirectionNode } = this; - return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) ); + const dotNL = normalView.dot( lightDirectionNode ); + const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 ); + + const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight ); + + builder.context.irradiance.addAssign( irradiance ); } - isEnvironmentTexture( texture ) { +} - const mapping = texture.mapping; +class LightProbeNode extends AnalyticLightNode { - return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); + static get type() { + + return 'LightProbeNode'; } - _destroyTexture( texture ) { + constructor( light = null ) { - this.backend.destroySampler( texture ); - this.backend.destroyTexture( texture ); + super( light ); - this.delete( texture ); + const array = []; - } + for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() ); -} + this.lightProbe = uniformArray( array ); -class Color4 extends Color { + } - constructor( r, g, b, a = 1 ) { + update( frame ) { - super( r, g, b ); + const { light } = this; - this.a = a; + super.update( frame ); - } + // - set( r, g, b, a = 1 ) { + for ( let i = 0; i < 9; i ++ ) { - this.a = a; + this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity ); - return super.set( r, g, b ); + } } - copy( color ) { + setup( builder ) { - if ( color.a !== undefined ) this.a = color.a; + const irradiance = getShIrradianceAt( normalWorld, this.lightProbe ); - return super.copy( color ); + builder.context.irradiance.addAssign( irradiance ); } - clone() { +} - return new this.constructor( this.r, this.g, this.b, this.a ); +class NodeParser { + + parseFunction( /*source*/ ) { + + console.warn( 'Abstract function.' ); } } -const _clearColor = /*@__PURE__*/ new Color4(); +class NodeFunction { -class Background extends DataMap { + constructor( type, inputs, name = '', precision = '' ) { - constructor( renderer, nodes ) { + this.type = type; + this.inputs = inputs; + this.name = name; + this.precision = precision; - super(); + } - this.renderer = renderer; - this.nodes = nodes; + getCode( /*name = this.name*/ ) { + + console.warn( 'Abstract function.' ); } - update( scene, renderList, renderContext ) { +} - const renderer = this.renderer; - const background = this.nodes.getBackgroundNode( scene ) || scene.background; +NodeFunction.isNodeFunction = true; - let forceClear = false; +const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i; +const propertiesRegexp$1 = /[a-z_0-9]+/ig; - if ( background === null ) { +const pragmaMain = '#pragma main'; - // no background settings, use clear color configuration from the renderer +const parse$1 = ( source ) => { - renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace ); - _clearColor.a = renderer._clearColor.a; + source = source.trim(); - } else if ( background.isColor === true ) { + const pragmaMainIndex = source.indexOf( pragmaMain ); - // background is an opaque color + const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source; - background.getRGB( _clearColor, LinearSRGBColorSpace ); - _clearColor.a = 1; + const declaration = mainCode.match( declarationRegexp$1 ); - forceClear = true; + if ( declaration !== null && declaration.length === 5 ) { - } else if ( background.isNode === true ) { + // tokenizer - const sceneData = this.get( scene ); - const backgroundNode = background; + const inputsCode = declaration[ 4 ]; + const propsMatches = []; - _clearColor.copy( renderer._clearColor ); + let nameMatch = null; - let backgroundMesh = sceneData.backgroundMesh; + while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) { - if ( backgroundMesh === undefined ) { + propsMatches.push( nameMatch ); - const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), { - // @TODO: Add Texture2D support using node context - getUV: () => normalWorld, - getTextureLevel: () => backgroundBlurriness - } ); + } - let viewProj = modelViewProjection(); - viewProj = viewProj.setZ( viewProj.w ); + // parser - const nodeMaterial = new NodeMaterial(); - nodeMaterial.name = 'Background.material'; - nodeMaterial.side = BackSide; - nodeMaterial.depthTest = false; - nodeMaterial.depthWrite = false; - nodeMaterial.fog = false; - nodeMaterial.lights = false; - nodeMaterial.vertexNode = viewProj; - nodeMaterial.colorNode = backgroundMeshNode; + const inputs = []; - sceneData.backgroundMeshNode = backgroundMeshNode; - sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial ); - backgroundMesh.frustumCulled = false; - backgroundMesh.name = 'Background.mesh'; + let i = 0; - backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) { + while ( i < propsMatches.length ) { - this.matrixWorld.copyPosition( camera.matrixWorld ); + const isConst = propsMatches[ i ][ 0 ] === 'const'; - }; + if ( isConst === true ) { + + i ++; } - const backgroundCacheKey = backgroundNode.getCacheKey(); + let qualifier = propsMatches[ i ][ 0 ]; - if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) { + if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) { - sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity ); - sceneData.backgroundMeshNode.needsUpdate = true; + i ++; - backgroundMesh.material.needsUpdate = true; + } else { - sceneData.backgroundCacheKey = backgroundCacheKey; + qualifier = ''; } - renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null ); + const type = propsMatches[ i ++ ][ 0 ]; - } else { + let count = Number.parseInt( propsMatches[ i ][ 0 ] ); - console.error( 'THREE.Renderer: Unsupported background configuration.', background ); + if ( Number.isNaN( count ) === false ) i ++; + else count = null; - } + const name = propsMatches[ i ++ ][ 0 ]; - // + inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) ); - if ( renderer.autoClear === true || forceClear === true ) { + } - const clearColorValue = renderContext.clearColorValue; + // - clearColorValue.r = _clearColor.r; - clearColorValue.g = _clearColor.g; - clearColorValue.b = _clearColor.b; - clearColorValue.a = _clearColor.a; + const blockCode = mainCode.substring( declaration[ 0 ].length ); - // premultiply alpha + const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : ''; + const type = declaration[ 2 ]; - if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) { + const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : ''; - clearColorValue.r *= clearColorValue.a; - clearColorValue.g *= clearColorValue.a; - clearColorValue.b *= clearColorValue.a; + const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : ''; - } + return { + type, + inputs, + name, + precision, + inputsCode, + blockCode, + headerCode + }; - // + } else { - renderContext.depthClearValue = renderer._clearDepth; - renderContext.stencilClearValue = renderer._clearStencil; + throw new Error( 'FunctionNode: Function is not a GLSL code.' ); - renderContext.clearColor = renderer.autoClearColor === true; - renderContext.clearDepth = renderer.autoClearDepth === true; - renderContext.clearStencil = renderer.autoClearStencil === true; + } - } else { +}; - renderContext.clearColor = false; - renderContext.clearDepth = false; - renderContext.clearStencil = false; +class GLSLNodeFunction extends NodeFunction { - } + constructor( source ) { - } + const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source ); -} + super( type, inputs, name, precision ); -class NodeBuilderState { + this.inputsCode = inputsCode; + this.blockCode = blockCode; + this.headerCode = headerCode; - constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) { + } - this.vertexShader = vertexShader; - this.fragmentShader = fragmentShader; - this.computeShader = computeShader; - this.transforms = transforms; + getCode( name = this.name ) { - this.nodeAttributes = nodeAttributes; - this.bindings = bindings; + let code; - this.updateNodes = updateNodes; - this.updateBeforeNodes = updateBeforeNodes; - this.updateAfterNodes = updateAfterNodes; + const blockCode = this.blockCode; - this.monitor = monitor; + if ( blockCode !== '' ) { - this.usedTimes = 0; + const { type, inputsCode, headerCode, precision } = this; - } + let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`; - createBindings() { + if ( precision !== '' ) { - const bindings = []; + declarationCode = `${ precision } ${ declarationCode }`; - for ( const instanceGroup of this.bindings ) { + } - const shared = instanceGroup.bindings[ 0 ].groupNode.shared; + code = headerCode + declarationCode + blockCode; - if ( shared !== true ) { + } else { - const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup ); - bindings.push( bindingsGroup ); + // interface function - for ( const instanceBinding of instanceGroup.bindings ) { + code = ''; - bindingsGroup.bindings.push( instanceBinding.clone() ); + } - } + return code; - } else { + } - bindings.push( instanceGroup ); +} - } +class GLSLNodeParser extends NodeParser { - } + parseFunction( source ) { - return bindings; + return new GLSLNodeFunction( source ); } @@ -63838,6 +63864,47 @@ class NodeLibrary { } +const _defaultLights = /*@__PURE__*/ new LightsNode(); + +class Lighting extends ChainMap { + + constructor() { + + super(); + + } + + createNode( lights = [] ) { + + return new LightsNode().setLights( lights ); + + } + + getNode( scene, camera ) { + + // ignore post-processing + + if ( scene.isQuadMesh ) return _defaultLights; + + // tiled lighting + + const keys = [ scene, camera ]; + + let node = this.get( keys ); + + if ( node === undefined ) { + + node = this.createNode(); + this.set( keys, node ); + + } + + return node; + + } + +} + const _scene = /*@__PURE__*/ new Scene(); const _drawingBufferSize = /*@__PURE__*/ new Vector2(); const _screen = /*@__PURE__*/ new Vector4(); @@ -63894,11 +63961,13 @@ class Renderer { this.info = new Info(); this.nodes = { - library: new NodeLibrary(), modelViewMatrix: null, modelNormalViewMatrix: null }; + this.library = new NodeLibrary(); + this.lighting = new Lighting(); + // internals this._getFallback = getFallback; @@ -64050,7 +64119,7 @@ class Renderer { this._pipelines = new Pipelines( backend, this._nodes ); this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info ); this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info ); - this._renderLists = new RenderLists(); + this._renderLists = new RenderLists( this.lighting ); this._bundles = new RenderBundles(); this._renderContexts = new RenderContexts(); @@ -70730,8 +70799,6 @@ class WebGLBackend extends Backend { // Bindings - this.createBindings( null, bindings ); - this._setupBindings( bindings, programGPU ); const attributeNodes = computeProgram.attributes; @@ -70803,8 +70870,6 @@ class WebGLBackend extends Backend { updateBindings( bindGroup /*, bindings*/ ) { - if ( bindGroup === null ) return; - const { gl } = this; const bindGroupData = this.get( bindGroup ); @@ -71754,9 +71819,17 @@ class WebGPUTextureUtils { magFilter: this._convertFilterMode( texture.magFilter ), minFilter: this._convertFilterMode( texture.minFilter ), mipmapFilter: this._convertFilterMode( texture.minFilter ), - maxAnisotropy: texture.anisotropy + maxAnisotropy: 1 }; + // anisotropy can only be used when all filter modes are set to linear. + + if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) { + + samplerDescriptorGPU.maxAnisotropy = texture.anisotropy; + + } + if ( texture.isDepthTexture && texture.compareFunction !== null ) { samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ]; @@ -73104,19 +73177,8 @@ const wgslTypeLib = { bvec4: 'vec4', mat2: 'mat2x2', - imat2: 'mat2x2', - umat2: 'mat2x2', - bmat2: 'mat2x2', - mat3: 'mat3x3', - imat3: 'mat3x3', - umat3: 'mat3x3', - bmat3: 'mat3x3', - - mat4: 'mat4x4', - imat4: 'mat4x4', - umat4: 'mat4x4', - bmat4: 'mat4x4' + mat4: 'mat4x4' }; const wgslPolyfill = { @@ -77417,7 +77479,7 @@ class WebGPURenderer extends Renderer { super( backend, parameters ); - this.nodes.library = new BasicNodeLibrary(); + this.library = new BasicNodeLibrary(); this.isWebGPURenderer = true; @@ -77951,4 +78013,4 @@ if ( typeof window !== 'undefined' ) { } -export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicEnvironmentNode, BasicShadowMap$1 as BasicShadowMap, BatchNode, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, Controls, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, Discard, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightProbeNode, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, Loop, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureLoader, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformArrayNode, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getColorSpaceMethod, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, global, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearSRGBTosRGB, linearToneMapping, localId, log, log2, loop, luminance, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToLogarithmicDepth, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rotate, rotateUV, roughness, round, rtt, sRGBToLinearSRGB, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor }; +export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicEnvironmentNode, BasicShadowMap$1 as BasicShadowMap, BatchNode, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, Controls, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, Discard, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, Loop, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureLoader, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformArrayNode, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directPointLight, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getColorSpaceMethod, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, global, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearSRGBTosRGB, linearToneMapping, localId, log, log2, loop, luminance, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToLogarithmicDepth, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rotate, rotateUV, roughness, round, rtt, sRGBToLinearSRGB, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor }; diff --git a/build/three.webgpu.nodes.min.js b/build/three.webgpu.nodes.min.js index 42da26dedf8ab1..75d3526d5458ea 100644 --- a/build/three.webgpu.nodes.min.js +++ b/build/three.webgpu.nodes.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2024 Three.js Authors * SPDX-License-Identifier: MIT */ -const e="170dev",t={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},s={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},i=0,r=1,n=2,o=3,a=0,h=1,u=2,l=3,c=0,d=1,p=2,m=0,g=1,f=2,y=3,x=4,b=5,v=100,T=101,_=102,w=103,S=104,M=200,A=201,N=202,C=203,R=204,E=205,B=206,I=207,P=208,F=209,U=210,O=211,z=212,L=213,V=214,D=0,k=1,G=2,W=3,j=4,H=5,q=6,$=7,X=0,Y=1,Z=2,J=0,K=1,Q=2,ee=3,te=4,se=5,ie=6,re=7,ne="attached",oe="detached",ae=300,he=301,ue=302,le=303,ce=304,de=306,pe=1e3,me=1001,ge=1002,fe=1003,ye=1004,xe=1004,be=1005,ve=1005,Te=1006,_e=1007,we=1007,Se=1008,Me=1008,Ae=1009,Ne=1010,Ce=1011,Re=1012,Ee=1013,Be=1014,Ie=1015,Pe=1016,Fe=1017,Ue=1018,Oe=1020,ze=35902,Le=1021,Ve=1022,De=1023,ke=1024,Ge=1025,We=1026,je=1027,He=1028,qe=1029,$e=1030,Xe=1031,Ye=1032,Ze=1033,Je=33776,Ke=33777,Qe=33778,et=33779,tt=35840,st=35841,it=35842,rt=35843,nt=36196,ot=37492,at=37496,ht=37808,ut=37809,lt=37810,ct=37811,dt=37812,pt=37813,mt=37814,gt=37815,ft=37816,yt=37817,xt=37818,bt=37819,vt=37820,Tt=37821,_t=36492,wt=36494,St=36495,Mt=36283,At=36284,Nt=36285,Ct=36286,Rt=2200,Et=2201,Bt=2202,It=2300,Pt=2301,Ft=2302,Ut=2400,Ot=2401,zt=2402,Lt=2500,Vt=2501,Dt=0,kt=1,Gt=2,Wt=3200,jt=3201,Ht=3202,qt=3203,$t=0,Xt=1,Yt="",Zt="srgb",Jt="srgb-linear",Kt="linear",Qt="srgb",es=0,ts=7680,ss=7681,is=7682,rs=7683,ns=34055,os=34056,as=5386,hs=512,us=513,ls=514,cs=515,ds=516,ps=517,ms=518,gs=519,fs=512,ys=513,xs=514,bs=515,vs=516,Ts=517,_s=518,ws=519,Ss=35044,Ms=35048,As=35040,Ns=35045,Cs=35049,Rs=35041,Es=35046,Bs=35050,Is=35042,Ps="100",Fs="300 es",Us=2e3,Os=2001;class zs{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const s=this._listeners;void 0===s[e]&&(s[e]=[]),-1===s[e].indexOf(t)&&s[e].push(t)}hasEventListener(e,t){if(void 0===this._listeners)return!1;const s=this._listeners;return void 0!==s[e]&&-1!==s[e].indexOf(t)}removeEventListener(e,t){if(void 0===this._listeners)return;const s=this._listeners[e];if(void 0!==s){const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}dispatchEvent(e){if(void 0===this._listeners)return;const t=this._listeners[e.type];if(void 0!==t){e.target=this;const s=t.slice(0);for(let t=0,i=s.length;t>8&255]+Ls[e>>16&255]+Ls[e>>24&255]+"-"+Ls[255&t]+Ls[t>>8&255]+"-"+Ls[t>>16&15|64]+Ls[t>>24&255]+"-"+Ls[63&s|128]+Ls[s>>8&255]+"-"+Ls[s>>16&255]+Ls[s>>24&255]+Ls[255&i]+Ls[i>>8&255]+Ls[i>>16&255]+Ls[i>>24&255]).toLowerCase()}function Ws(e,t,s){return Math.max(t,Math.min(s,e))}function js(e,t){return(e%t+t)%t}function Hs(e,t,s){return(1-s)*e+s*t}function qs(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function $s(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Xs={DEG2RAD:Ds,RAD2DEG:ks,generateUUID:Gs,clamp:Ws,euclideanModulo:js,mapLinear:function(e,t,s,i,r){return i+(e-t)*(r-i)/(s-t)},inverseLerp:function(e,t,s){return e!==t?(s-e)/(t-e):0},lerp:Hs,damp:function(e,t,s,i){return Hs(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(js(e,2*t)-t)},smoothstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*(3-2*e)},smootherstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Vs=e);let t=Vs+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*Ds},radToDeg:function(e){return e*ks},isPowerOfTwo:function(e){return 0==(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,s,i,r){const n=Math.cos,o=Math.sin,a=n(s/2),h=o(s/2),u=n((t+i)/2),l=o((t+i)/2),c=n((t-i)/2),d=o((t-i)/2),p=n((i-t)/2),m=o((i-t)/2);switch(r){case"XYX":e.set(a*l,h*c,h*d,a*u);break;case"YZY":e.set(h*d,a*l,h*c,a*u);break;case"ZXZ":e.set(h*c,h*d,a*l,a*u);break;case"XZX":e.set(a*l,h*m,h*p,a*u);break;case"YXY":e.set(h*p,a*l,h*m,a*u);break;case"ZYZ":e.set(h*m,h*p,a*l,a*u);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:$s,denormalize:qs};class Ys{constructor(e=0,t=0){Ys.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Ws(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const s=Math.cos(t),i=Math.sin(t),r=this.x-e.x,n=this.y-e.y;return this.x=r*s-n*i+e.x,this.y=r*i+n*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Zs{constructor(e,t,s,i,r,n,o,a,h){Zs.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,h)}set(e,t,s,i,r,n,o,a,h){const u=this.elements;return u[0]=e,u[1]=i,u[2]=o,u[3]=t,u[4]=r,u[5]=a,u[6]=s,u[7]=n,u[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[3],a=s[6],h=s[1],u=s[4],l=s[7],c=s[2],d=s[5],p=s[8],m=i[0],g=i[3],f=i[6],y=i[1],x=i[4],b=i[7],v=i[2],T=i[5],_=i[8];return r[0]=n*m+o*y+a*v,r[3]=n*g+o*x+a*T,r[6]=n*f+o*b+a*_,r[1]=h*m+u*y+l*v,r[4]=h*g+u*x+l*T,r[7]=h*f+u*b+l*_,r[2]=c*m+d*y+p*v,r[5]=c*g+d*x+p*T,r[8]=c*f+d*b+p*_,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8];return t*n*u-t*o*h-s*r*u+s*o*a+i*r*h-i*n*a}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8],l=u*n-o*h,c=o*a-u*r,d=h*r-n*a,p=t*l+s*c+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=l*m,e[1]=(i*h-u*s)*m,e[2]=(o*s-i*n)*m,e[3]=c*m,e[4]=(u*t-i*a)*m,e[5]=(i*r-o*t)*m,e[6]=d*m,e[7]=(s*a-h*t)*m,e[8]=(n*t-s*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,s,i,r,n,o){const a=Math.cos(r),h=Math.sin(r);return this.set(s*a,s*h,-s*(a*n+h*o)+n+e,-i*h,i*a,-i*(-h*n+a*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Js.makeScale(e,t)),this}rotate(e){return this.premultiply(Js.makeRotation(-e)),this}translate(e,t){return this.premultiply(Js.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<9;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const Js=new Zs;const Ks={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Qs(e,t){return new Ks[e](t)}function ei(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function ti(){const e=ei("canvas");return e.style.display="block",e}const si={};const ii={enabled:!0,workingColorSpace:Jt,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Qt&&(e.r=ri(e.r),e.g=ri(e.g),e.b=ri(e.b)),this.spaces[t].primaries!==this.spaces[s].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Qt&&(e.r=ni(e.r),e.g=ni(e.g),e.b=ni(e.b)),e):e},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===Yt?Kt:this.spaces[e].transfer},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,s){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace}};function ri(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function ni(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}const oi=[.64,.33,.3,.6,.15,.06],ai=[.2126,.7152,.0722],hi=[.3127,.329],ui=(new Zs).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),li=(new Zs).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);let ci;ii.define({[Jt]:{primaries:oi,whitePoint:hi,transfer:Kt,toXYZ:ui,fromXYZ:li,luminanceCoefficients:ai,workingColorSpaceConfig:{unpackColorSpace:Zt},outputColorSpaceConfig:{drawingBufferColorSpace:Zt}},[Zt]:{primaries:oi,whitePoint:hi,transfer:Qt,toXYZ:ui,fromXYZ:li,luminanceCoefficients:ai,outputColorSpaceConfig:{drawingBufferColorSpace:Zt}}});class di{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===ci&&(ci=ei("canvas")),ci.width=e.width,ci.height=e.height;const s=ci.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),t=ci}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=ei("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==ae)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case pe:e.x=e.x-Math.floor(e.x);break;case me:e.x=e.x<0?0:1;break;case ge:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case pe:e.y=e.y-Math.floor(e.y);break;case me:e.y=e.y<0?0:1;break;case ge:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}yi.DEFAULT_IMAGE=null,yi.DEFAULT_MAPPING=ae,yi.DEFAULT_ANISOTROPY=1;class xi{constructor(e=0,t=0,s=0,i=1){xi.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=this.w,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i+n[12]*r,this.y=n[1]*t+n[5]*s+n[9]*i+n[13]*r,this.z=n[2]*t+n[6]*s+n[10]*i+n[14]*r,this.w=n[3]*t+n[7]*s+n[11]*i+n[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,s,i,r;const n=.01,o=.1,a=e.elements,h=a[0],u=a[4],l=a[8],c=a[1],d=a[5],p=a[9],m=a[2],g=a[6],f=a[10];if(Math.abs(u-c)a&&e>y?ey?a=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),n=Math.atan2(r,t*s);e=Math.sin(e*n)/r,o=Math.sin(o*n)/r}const r=o*s;if(a=a*e+c*r,h=h*e+d*r,u=u*e+p*r,l=l*e+m*r,e===1-o){const e=1/Math.sqrt(a*a+h*h+u*u+l*l);a*=e,h*=e,u*=e,l*=e}}e[t]=a,e[t+1]=h,e[t+2]=u,e[t+3]=l}static multiplyQuaternionsFlat(e,t,s,i,r,n){const o=s[i],a=s[i+1],h=s[i+2],u=s[i+3],l=r[n],c=r[n+1],d=r[n+2],p=r[n+3];return e[t]=o*p+u*l+a*d-h*c,e[t+1]=a*p+u*c+h*l-o*d,e[t+2]=h*p+u*d+o*c-a*l,e[t+3]=u*p-o*l-a*c-h*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,r=e._z,n=e._order,o=Math.cos,a=Math.sin,h=o(s/2),u=o(i/2),l=o(r/2),c=a(s/2),d=a(i/2),p=a(r/2);switch(n){case"XYZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"YXZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"ZXY":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"ZYX":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"YZX":this._x=c*u*l+h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l-c*d*p;break;case"XZY":this._x=c*u*l-h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l+c*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],r=t[8],n=t[1],o=t[5],a=t[9],h=t[2],u=t[6],l=t[10],c=s+o+l;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(u-a)*e,this._y=(r-h)*e,this._z=(n-i)*e}else if(s>o&&s>l){const e=2*Math.sqrt(1+s-o-l);this._w=(u-a)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+h)/e}else if(o>l){const e=2*Math.sqrt(1+o-s-l);this._w=(r-h)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(a+u)/e}else{const e=2*Math.sqrt(1+l-s-o);this._w=(n-i)/e,this._x=(r+h)/e,this._y=(a+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return sMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ws(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(0===s)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,i=e._y,r=e._z,n=e._w,o=t._x,a=t._y,h=t._z,u=t._w;return this._x=s*u+n*o+i*h-r*a,this._y=i*u+n*a+r*o-s*h,this._z=r*u+n*h+s*a-i*o,this._w=n*u-s*o-i*a-r*h,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const s=this._x,i=this._y,r=this._z,n=this._w;let o=n*e._w+s*e._x+i*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=n,this._x=s,this._y=i,this._z=r,this;const a=1-o*o;if(a<=Number.EPSILON){const e=1-t;return this._w=e*n+t*this._w,this._x=e*s+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const h=Math.sqrt(a),u=Math.atan2(h,o),l=Math.sin((1-t)*u)/h,c=Math.sin(t*u)/h;return this._w=n*l+this._w*c,this._x=s*l+this._x*c,this._y=i*l+this._y*c,this._z=r*l+this._z*c,this._onChangeCallback(),this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),r=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ai{constructor(e=0,t=0,s=0){Ai.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return void 0===s&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Ci.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ci.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6]*i,this.y=r[1]*t+r[4]*s+r[7]*i,this.z=r[2]*t+r[5]*s+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=e.elements,n=1/(r[3]*t+r[7]*s+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*s+r[8]*i+r[12])*n,this.y=(r[1]*t+r[5]*s+r[9]*i+r[13])*n,this.z=(r[2]*t+r[6]*s+r[10]*i+r[14])*n,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,r=e.x,n=e.y,o=e.z,a=e.w,h=2*(n*i-o*s),u=2*(o*t-r*i),l=2*(r*s-n*t);return this.x=t+a*h+n*l-o*u,this.y=s+a*u+o*h-r*l,this.z=i+a*l+r*u-n*h,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i,this.y=r[1]*t+r[5]*s+r[9]*i,this.z=r[2]*t+r[6]*s+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,r=e.z,n=t.x,o=t.y,a=t.z;return this.x=i*a-r*o,this.y=r*n-s*a,this.z=s*o-i*n,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Ni.copy(this).projectOnVector(e),this.sub(Ni)}reflect(e){return this.sub(Ni.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Ws(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ni=new Ai,Ci=new Mi;class Ri{constructor(e=new Ai(1/0,1/0,1/0),t=new Ai(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Bi),Bi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Vi),Di.subVectors(this.max,Vi),Pi.subVectors(e.a,Vi),Fi.subVectors(e.b,Vi),Ui.subVectors(e.c,Vi),Oi.subVectors(Fi,Pi),zi.subVectors(Ui,Fi),Li.subVectors(Pi,Ui);let t=[0,-Oi.z,Oi.y,0,-zi.z,zi.y,0,-Li.z,Li.y,Oi.z,0,-Oi.x,zi.z,0,-zi.x,Li.z,0,-Li.x,-Oi.y,Oi.x,0,-zi.y,zi.x,0,-Li.y,Li.x,0];return!!Wi(t,Pi,Fi,Ui,Di)&&(t=[1,0,0,0,1,0,0,0,1],!!Wi(t,Pi,Fi,Ui,Di)&&(ki.crossVectors(Oi,zi),t=[ki.x,ki.y,ki.z],Wi(t,Pi,Fi,Ui,Di)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Bi).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Ei[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ei[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ei[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ei[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ei[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ei[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ei[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ei[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ei)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Ei=[new Ai,new Ai,new Ai,new Ai,new Ai,new Ai,new Ai,new Ai],Bi=new Ai,Ii=new Ri,Pi=new Ai,Fi=new Ai,Ui=new Ai,Oi=new Ai,zi=new Ai,Li=new Ai,Vi=new Ai,Di=new Ai,ki=new Ai,Gi=new Ai;function Wi(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){Gi.fromArray(e,n);const o=r.x*Math.abs(Gi.x)+r.y*Math.abs(Gi.y)+r.z*Math.abs(Gi.z),a=t.dot(Gi),h=s.dot(Gi),u=i.dot(Gi);if(Math.max(-Math.max(a,h,u),Math.min(a,h,u))>o)return!1}return!0}const ji=new Ri,Hi=new Ai,qi=new Ai;class $i{constructor(e=new Ai,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const s=this.center;void 0!==t?s.copy(t):ji.setFromPoints(e).getCenter(s);let i=0;for(let t=0,r=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Hi.subVectors(e,this.center);const t=Hi.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Hi,s/e),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(qi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Hi.copy(e.center).add(qi)),this.expandByPoint(Hi.copy(e.center).sub(qi))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Xi=new Ai,Yi=new Ai,Zi=new Ai,Ji=new Ai,Ki=new Ai,Qi=new Ai,er=new Ai;class tr{constructor(e=new Ai,t=new Ai(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Xi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Xi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Xi.copy(this.origin).addScaledVector(this.direction,t),Xi.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){Yi.copy(e).add(t).multiplyScalar(.5),Zi.copy(t).sub(e).normalize(),Ji.copy(this.origin).sub(Yi);const r=.5*e.distanceTo(t),n=-this.direction.dot(Zi),o=Ji.dot(this.direction),a=-Ji.dot(Zi),h=Ji.lengthSq(),u=Math.abs(1-n*n);let l,c,d,p;if(u>0)if(l=n*a-o,c=n*o-a,p=r*u,l>=0)if(c>=-p)if(c<=p){const e=1/u;l*=e,c*=e,d=l*(l+n*c+2*o)+c*(n*l+c+2*a)+h}else c=r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;else c=-r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;else c<=-p?(l=Math.max(0,-(-n*r+o)),c=l>0?-r:Math.min(Math.max(-r,-a),r),d=-l*l+c*(c+2*a)+h):c<=p?(l=0,c=Math.min(Math.max(-r,-a),r),d=c*(c+2*a)+h):(l=Math.max(0,-(n*r+o)),c=l>0?r:Math.min(Math.max(-r,-a),r),d=-l*l+c*(c+2*a)+h);else c=n>0?-r:r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;return s&&s.copy(this.origin).addScaledVector(this.direction,l),i&&i.copy(Yi).addScaledVector(Zi,c),d}intersectSphere(e,t){Xi.subVectors(e.center,this.origin);const s=Xi.dot(this.direction),i=Xi.dot(Xi)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),o=s-n,a=s+n;return a<0?null:o<0?this.at(a,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return null===s?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,r,n,o,a;const h=1/this.direction.x,u=1/this.direction.y,l=1/this.direction.z,c=this.origin;return h>=0?(s=(e.min.x-c.x)*h,i=(e.max.x-c.x)*h):(s=(e.max.x-c.x)*h,i=(e.min.x-c.x)*h),u>=0?(r=(e.min.y-c.y)*u,n=(e.max.y-c.y)*u):(r=(e.max.y-c.y)*u,n=(e.min.y-c.y)*u),s>n||r>i?null:((r>s||isNaN(s))&&(s=r),(n=0?(o=(e.min.z-c.z)*l,a=(e.max.z-c.z)*l):(o=(e.max.z-c.z)*l,a=(e.min.z-c.z)*l),s>a||o>i?null:((o>s||s!=s)&&(s=o),(a=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Xi)}intersectTriangle(e,t,s,i,r){Ki.subVectors(t,e),Qi.subVectors(s,e),er.crossVectors(Ki,Qi);let n,o=this.direction.dot(er);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}Ji.subVectors(this.origin,e);const a=n*this.direction.dot(Qi.crossVectors(Ji,Qi));if(a<0)return null;const h=n*this.direction.dot(Ki.cross(Ji));if(h<0)return null;if(a+h>o)return null;const u=-n*Ji.dot(er);return u<0?null:this.at(u/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class sr{constructor(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g){sr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g)}set(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g){const f=this.elements;return f[0]=e,f[4]=t,f[8]=s,f[12]=i,f[1]=r,f[5]=n,f[9]=o,f[13]=a,f[2]=h,f[6]=u,f[10]=l,f[14]=c,f[3]=d,f[7]=p,f[11]=m,f[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new sr).fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,s){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,s=e.elements,i=1/ir.setFromMatrixColumn(e,0).length(),r=1/ir.setFromMatrixColumn(e,1).length(),n=1/ir.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*r,t[5]=s[5]*r,t[6]=s[6]*r,t[7]=0,t[8]=s[8]*n,t[9]=s[9]*n,t[10]=s[10]*n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,r=e.z,n=Math.cos(s),o=Math.sin(s),a=Math.cos(i),h=Math.sin(i),u=Math.cos(r),l=Math.sin(r);if("XYZ"===e.order){const e=n*u,s=n*l,i=o*u,r=o*l;t[0]=a*u,t[4]=-a*l,t[8]=h,t[1]=s+i*h,t[5]=e-r*h,t[9]=-o*a,t[2]=r-e*h,t[6]=i+s*h,t[10]=n*a}else if("YXZ"===e.order){const e=a*u,s=a*l,i=h*u,r=h*l;t[0]=e+r*o,t[4]=i*o-s,t[8]=n*h,t[1]=n*l,t[5]=n*u,t[9]=-o,t[2]=s*o-i,t[6]=r+e*o,t[10]=n*a}else if("ZXY"===e.order){const e=a*u,s=a*l,i=h*u,r=h*l;t[0]=e-r*o,t[4]=-n*l,t[8]=i+s*o,t[1]=s+i*o,t[5]=n*u,t[9]=r-e*o,t[2]=-n*h,t[6]=o,t[10]=n*a}else if("ZYX"===e.order){const e=n*u,s=n*l,i=o*u,r=o*l;t[0]=a*u,t[4]=i*h-s,t[8]=e*h+r,t[1]=a*l,t[5]=r*h+e,t[9]=s*h-i,t[2]=-h,t[6]=o*a,t[10]=n*a}else if("YZX"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*u,t[4]=r-e*l,t[8]=i*l+s,t[1]=l,t[5]=n*u,t[9]=-o*u,t[2]=-h*u,t[6]=s*l+i,t[10]=e-r*l}else if("XZY"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*u,t[4]=-l,t[8]=h*u,t[1]=e*l+r,t[5]=n*u,t[9]=s*l-i,t[2]=i*l-s,t[6]=o*u,t[10]=r*l+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(nr,e,or)}lookAt(e,t,s){const i=this.elements;return ur.subVectors(e,t),0===ur.lengthSq()&&(ur.z=1),ur.normalize(),ar.crossVectors(s,ur),0===ar.lengthSq()&&(1===Math.abs(s.z)?ur.x+=1e-4:ur.z+=1e-4,ur.normalize(),ar.crossVectors(s,ur)),ar.normalize(),hr.crossVectors(ur,ar),i[0]=ar.x,i[4]=hr.x,i[8]=ur.x,i[1]=ar.y,i[5]=hr.y,i[9]=ur.y,i[2]=ar.z,i[6]=hr.z,i[10]=ur.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[4],a=s[8],h=s[12],u=s[1],l=s[5],c=s[9],d=s[13],p=s[2],m=s[6],g=s[10],f=s[14],y=s[3],x=s[7],b=s[11],v=s[15],T=i[0],_=i[4],w=i[8],S=i[12],M=i[1],A=i[5],N=i[9],C=i[13],R=i[2],E=i[6],B=i[10],I=i[14],P=i[3],F=i[7],U=i[11],O=i[15];return r[0]=n*T+o*M+a*R+h*P,r[4]=n*_+o*A+a*E+h*F,r[8]=n*w+o*N+a*B+h*U,r[12]=n*S+o*C+a*I+h*O,r[1]=u*T+l*M+c*R+d*P,r[5]=u*_+l*A+c*E+d*F,r[9]=u*w+l*N+c*B+d*U,r[13]=u*S+l*C+c*I+d*O,r[2]=p*T+m*M+g*R+f*P,r[6]=p*_+m*A+g*E+f*F,r[10]=p*w+m*N+g*B+f*U,r[14]=p*S+m*C+g*I+f*O,r[3]=y*T+x*M+b*R+v*P,r[7]=y*_+x*A+b*E+v*F,r[11]=y*w+x*N+b*B+v*U,r[15]=y*S+x*C+b*I+v*O,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[4],i=e[8],r=e[12],n=e[1],o=e[5],a=e[9],h=e[13],u=e[2],l=e[6],c=e[10],d=e[14];return e[3]*(+r*a*l-i*h*l-r*o*c+s*h*c+i*o*d-s*a*d)+e[7]*(+t*a*d-t*h*c+r*n*c-i*n*d+i*h*u-r*a*u)+e[11]*(+t*h*l-t*o*d-r*n*l+s*n*d+r*o*u-s*h*u)+e[15]*(-i*o*u-t*a*l+t*o*c+i*n*l-s*n*c+s*a*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8],l=e[9],c=e[10],d=e[11],p=e[12],m=e[13],g=e[14],f=e[15],y=l*g*h-m*c*h+m*a*d-o*g*d-l*a*f+o*c*f,x=p*c*h-u*g*h-p*a*d+n*g*d+u*a*f-n*c*f,b=u*m*h-p*l*h+p*o*d-n*m*d-u*o*f+n*l*f,v=p*l*a-u*m*a-p*o*c+n*m*c+u*o*g-n*l*g,T=t*y+s*x+i*b+r*v;if(0===T)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const _=1/T;return e[0]=y*_,e[1]=(m*c*r-l*g*r-m*i*d+s*g*d+l*i*f-s*c*f)*_,e[2]=(o*g*r-m*a*r+m*i*h-s*g*h-o*i*f+s*a*f)*_,e[3]=(l*a*r-o*c*r-l*i*h+s*c*h+o*i*d-s*a*d)*_,e[4]=x*_,e[5]=(u*g*r-p*c*r+p*i*d-t*g*d-u*i*f+t*c*f)*_,e[6]=(p*a*r-n*g*r-p*i*h+t*g*h+n*i*f-t*a*f)*_,e[7]=(n*c*r-u*a*r+u*i*h-t*c*h-n*i*d+t*a*d)*_,e[8]=b*_,e[9]=(p*l*r-u*m*r-p*s*d+t*m*d+u*s*f-t*l*f)*_,e[10]=(n*m*r-p*o*r+p*s*h-t*m*h-n*s*f+t*o*f)*_,e[11]=(u*o*r-n*l*r-u*s*h+t*l*h+n*s*d-t*o*d)*_,e[12]=v*_,e[13]=(u*m*i-p*l*i+p*s*c-t*m*c-u*s*g+t*l*g)*_,e[14]=(p*o*i-n*m*i-p*s*a+t*m*a+n*s*g-t*o*g)*_,e[15]=(n*l*i-u*o*i+u*s*a-t*l*a-n*s*c+t*o*c)*_,this}scale(e){const t=this.elements,s=e.x,i=e.y,r=e.z;return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),r=1-s,n=e.x,o=e.y,a=e.z,h=r*n,u=r*o;return this.set(h*n+s,h*o-i*a,h*a+i*o,0,h*o+i*a,u*o+s,u*a-i*n,0,h*a-i*o,u*a+i*n,r*a*a+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,r,n){return this.set(1,s,r,0,e,1,n,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,r=t._x,n=t._y,o=t._z,a=t._w,h=r+r,u=n+n,l=o+o,c=r*h,d=r*u,p=r*l,m=n*u,g=n*l,f=o*l,y=a*h,x=a*u,b=a*l,v=s.x,T=s.y,_=s.z;return i[0]=(1-(m+f))*v,i[1]=(d+b)*v,i[2]=(p-x)*v,i[3]=0,i[4]=(d-b)*T,i[5]=(1-(c+f))*T,i[6]=(g+y)*T,i[7]=0,i[8]=(p+x)*_,i[9]=(g-y)*_,i[10]=(1-(c+m))*_,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;let r=ir.set(i[0],i[1],i[2]).length();const n=ir.set(i[4],i[5],i[6]).length(),o=ir.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],rr.copy(this);const a=1/r,h=1/n,u=1/o;return rr.elements[0]*=a,rr.elements[1]*=a,rr.elements[2]*=a,rr.elements[4]*=h,rr.elements[5]*=h,rr.elements[6]*=h,rr.elements[8]*=u,rr.elements[9]*=u,rr.elements[10]*=u,t.setFromRotationMatrix(rr),s.x=r,s.y=n,s.z=o,this}makePerspective(e,t,s,i,r,n,o=2e3){const a=this.elements,h=2*r/(t-e),u=2*r/(s-i),l=(t+e)/(t-e),c=(s+i)/(s-i);let d,p;if(o===Us)d=-(n+r)/(n-r),p=-2*n*r/(n-r);else{if(o!==Os)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-n/(n-r),p=-n*r/(n-r)}return a[0]=h,a[4]=0,a[8]=l,a[12]=0,a[1]=0,a[5]=u,a[9]=c,a[13]=0,a[2]=0,a[6]=0,a[10]=d,a[14]=p,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(e,t,s,i,r,n,o=2e3){const a=this.elements,h=1/(t-e),u=1/(s-i),l=1/(n-r),c=(t+e)*h,d=(s+i)*u;let p,m;if(o===Us)p=(n+r)*l,m=-2*l;else{if(o!==Os)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);p=r*l,m=-1*l}return a[0]=2*h,a[4]=0,a[8]=0,a[12]=-c,a[1]=0,a[5]=2*u,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=m,a[14]=-p,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<16;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const ir=new Ai,rr=new sr,nr=new Ai(0,0,0),or=new Ai(1,1,1),ar=new Ai,hr=new Ai,ur=new Ai,lr=new sr,cr=new Mi;class dr{constructor(e=0,t=0,s=0,i=dr.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,r=i[0],n=i[4],o=i[8],a=i[1],h=i[5],u=i[9],l=i[2],c=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Ws(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(c,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Ws(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,h)):(this._y=Math.atan2(-l,r),this._z=0);break;case"ZXY":this._x=Math.asin(Ws(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(-l,d),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(a,r));break;case"ZYX":this._y=Math.asin(-Ws(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(a,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(Ws(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,h),this._y=Math.atan2(-l,r)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-Ws(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,h),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-u,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return lr.makeRotationFromQuaternion(e),this.setFromRotationMatrix(lr,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return cr.setFromEuler(this),this.setFromQuaternion(cr,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}dr.DEFAULT_ORDER="XYZ";class pr{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const s=t.shapes;if(Array.isArray(s))for(let t=0,i=s.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(s.geometries=t),i.length>0&&(s.materials=i),r.length>0&&(s.textures=r),o.length>0&&(s.images=o),a.length>0&&(s.shapes=a),h.length>0&&(s.skeletons=h),u.length>0&&(s.animations=u),l.length>0&&(s.nodes=l)}return s.object=i,s;function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,s,i,r){Er.subVectors(i,t),Br.subVectors(s,t),Ir.subVectors(e,t);const n=Er.dot(Er),o=Er.dot(Br),a=Er.dot(Ir),h=Br.dot(Br),u=Br.dot(Ir),l=n*h-o*o;if(0===l)return r.set(0,0,0),null;const c=1/l,d=(h*a-o*u)*c,p=(n*u-o*a)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,Pr)&&(Pr.x>=0&&Pr.y>=0&&Pr.x+Pr.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,Pr)?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(r,Pr.x),a.addScaledVector(n,Pr.y),a.addScaledVector(o,Pr.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return Dr.setScalar(0),kr.setScalar(0),Gr.setScalar(0),Dr.fromBufferAttribute(e,t),kr.fromBufferAttribute(e,s),Gr.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Dr,r.x),n.addScaledVector(kr,r.y),n.addScaledVector(Gr,r.z),n}static isFrontFacing(e,t,s,i){return Er.subVectors(s,t),Br.subVectors(e,t),Er.cross(Br).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Er.subVectors(this.c,this.b),Br.subVectors(this.a,this.b),.5*Er.cross(Br).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Wr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Wr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Wr.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Wr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Wr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,r=this.c;let n,o;Fr.subVectors(i,s),Ur.subVectors(r,s),zr.subVectors(e,s);const a=Fr.dot(zr),h=Ur.dot(zr);if(a<=0&&h<=0)return t.copy(s);Lr.subVectors(e,i);const u=Fr.dot(Lr),l=Ur.dot(Lr);if(u>=0&&l<=u)return t.copy(i);const c=a*l-u*h;if(c<=0&&a>=0&&u<=0)return n=a/(a-u),t.copy(s).addScaledVector(Fr,n);Vr.subVectors(e,r);const d=Fr.dot(Vr),p=Ur.dot(Vr);if(p>=0&&d<=p)return t.copy(r);const m=d*h-a*p;if(m<=0&&h>=0&&p<=0)return o=h/(h-p),t.copy(s).addScaledVector(Ur,o);const g=u*p-d*l;if(g<=0&&l-u>=0&&d-p>=0)return Or.subVectors(r,i),o=(l-u)/(l-u+(d-p)),t.copy(i).addScaledVector(Or,o);const f=1/(g+m+c);return n=m*f,o=c*f,t.copy(s).addScaledVector(Fr,n).addScaledVector(Ur,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const jr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Hr={h:0,s:0,l:0},qr={h:0,s:0,l:0};function $r(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class Xr{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Zt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,ii.toWorkingColorSpace(this,t),this}setRGB(e,t,s,i=ii.workingColorSpace){return this.r=e,this.g=t,this.b=s,ii.toWorkingColorSpace(this,i),this}setHSL(e,t,s,i=ii.workingColorSpace){if(e=js(e,1),t=Ws(t,0,1),s=Ws(s,0,1),0===t)this.r=this.g=this.b=s;else{const i=s<=.5?s*(1+t):s+t-s*t,r=2*s-i;this.r=$r(r,i,e+1/3),this.g=$r(r,i,e),this.b=$r(r,i,e-1/3)}return ii.toWorkingColorSpace(this,i),this}setStyle(e,t=Zt){function s(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],o=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],r=s.length;if(3===r)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Zt){const s=jr[e.toLowerCase()];return void 0!==s?this.setHex(s,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=ri(e.r),this.g=ri(e.g),this.b=ri(e.b),this}copyLinearToSRGB(e){return this.r=ni(e.r),this.g=ni(e.g),this.b=ni(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Zt){return ii.fromWorkingColorSpace(Yr.copy(this),e),65536*Math.round(Ws(255*Yr.r,0,255))+256*Math.round(Ws(255*Yr.g,0,255))+Math.round(Ws(255*Yr.b,0,255))}getHexString(e=Zt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ii.workingColorSpace){ii.fromWorkingColorSpace(Yr.copy(this),t);const s=Yr.r,i=Yr.g,r=Yr.b,n=Math.max(s,i,r),o=Math.min(s,i,r);let a,h;const u=(o+n)/2;if(o===n)a=0,h=0;else{const e=n-o;switch(h=u<=.5?e/(n+o):e/(2-n-o),n){case s:a=(i-r)/e+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const s=e[t];if(void 0===s){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s:console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const s={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),void 0!==this.roughness&&(s.roughness=this.roughness),void 0!==this.metalness&&(s.metalness=this.metalness),void 0!==this.sheen&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(s.shininess=this.shininess),void 0!==this.clearcoat&&(s.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(s.dispersion=this.dispersion),void 0!==this.iridescence&&(s.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(s.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(s.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(s.combine=this.combine)),void 0!==this.envMapRotation&&(s.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(s.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(s.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(s.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(s.size=this.size),null!==this.shadowSide&&(s.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(s.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(s.blending=this.blending),this.side!==c&&(s.side=this.side),!0===this.vertexColors&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),!0===this.transparent&&(s.transparent=!0),this.blendSrc!==R&&(s.blendSrc=this.blendSrc),this.blendDst!==E&&(s.blendDst=this.blendDst),this.blendEquation!==v&&(s.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(s.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(s.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(s.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(s.depthFunc=this.depthFunc),!1===this.depthTest&&(s.depthTest=this.depthTest),!1===this.depthWrite&&(s.depthWrite=this.depthWrite),!1===this.colorWrite&&(s.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==gs&&(s.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(s.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ts&&(s.stencilFail=this.stencilFail),this.stencilZFail!==ts&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==ts&&(s.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(s.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(s.rotation=this.rotation),!0===this.polygonOffset&&(s.polygonOffset=!0),0!==this.polygonOffsetFactor&&(s.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(s.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(s.linewidth=this.linewidth),void 0!==this.dashSize&&(s.dashSize=this.dashSize),void 0!==this.gapSize&&(s.gapSize=this.gapSize),void 0!==this.scale&&(s.scale=this.scale),!0===this.dithering&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),!0===this.alphaHash&&(s.alphaHash=!0),!0===this.alphaToCoverage&&(s.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(s.premultipliedAlpha=!0),!0===this.forceSinglePass&&(s.forceSinglePass=!0),!0===this.wireframe&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(s.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(s.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(s.flatShading=!0),!1===this.visible&&(s.visible=!1),!1===this.toneMapped&&(s.toneMapped=!1),!1===this.fog&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(s.textures=t),r.length>0&&(s.images=r)}return s}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let s=null;if(null!==t){const e=t.length;s=new Array(e);for(let i=0;i!==e;++i)s[i]=t[i].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Kr extends Jr{static get type(){return"MeshBasicMaterial"}constructor(e){super(),this.isMeshBasicMaterial=!0,this.color=new Xr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Qr=en();function en(){const e=new ArrayBuffer(4),t=new Float32Array(e),s=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const n=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,s=0;for(;0==(8388608&t);)t<<=1,s-=8388608;t&=-8388609,s+=947912704,n[e]=t|s}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(a[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:o,offsetTable:a}}function tn(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Ws(e,-65504,65504),Qr.floatView[0]=e;const t=Qr.uint32View[0],s=t>>23&511;return Qr.baseTable[s]+((8388607&t)>>Qr.shiftTable[s])}function sn(e){const t=e>>10;return Qr.uint32View[0]=Qr.mantissaTable[Qr.offsetTable[t]+(1023&e)]+Qr.exponentTable[t],Qr.floatView[0]}const rn={toHalfFloat:tn,fromHalfFloat:sn},nn=new Ai,on=new Ys;class an{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Ss,this.updateRanges=[],this.gpuType=Ie,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,r=this.itemSize;i=0;--t)if(e[t]>=65535)return!0;return!1}(e)?mn:dn)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(void 0!==s){const t=(new Zs).getNormalMatrix(e);s.applyNormalMatrix(t),s.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return xn.makeRotationFromQuaternion(e),this.applyMatrix4(xn),this}rotateX(e){return xn.makeRotationX(e),this.applyMatrix4(xn),this}rotateY(e){return xn.makeRotationY(e),this.applyMatrix4(xn),this}rotateZ(e){return xn.makeRotationZ(e),this.applyMatrix4(xn),this}translate(e,t,s){return xn.makeTranslation(e,t,s),this.applyMatrix4(xn),this}scale(e,t,s){return xn.makeScale(e,t,s),this.applyMatrix4(xn),this}lookAt(e){return bn.lookAt(e),bn.updateMatrix(),this.applyMatrix4(bn.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(vn).negate(),this.translate(vn.x,vn.y,vn.z),this}setFromPoints(e){const t=[];for(let s=0,i=e.length;s0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const s in t)void 0!==t[s]&&(e[s]=t[s]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const t in s){const i=s[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const s=this.morphAttributes[t],n=[];for(let t=0,i=s.length;t0&&(i[t]=n,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(e.data.groups=JSON.parse(JSON.stringify(n)));const o=this.boundingSphere;return null!==o&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const s=e.index;null!==s&&this.setIndex(s.clone(t));const i=e.attributes;for(const e in i){const s=i[e];this.setAttribute(e,s.clone(t))}const r=e.morphAttributes;for(const e in r){const s=[],i=r[e];for(let e=0,r=i.length;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;e(e.far-e.near)**2)return}Mn.copy(r).invert(),An.copy(e.ray).applyMatrix4(Mn),null!==s.boundingBox&&!1===An.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,An)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,o=r.index,a=r.attributes.position,h=r.attributes.uv,u=r.attributes.uv1,l=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==o)if(Array.isArray(n))for(let r=0,a=c.length;rs.far?null:{distance:u,point:Un.clone(),object:e}}(e,t,s,i,Rn,En,Bn,Fn);if(l){const e=new Ai;Wr.getBarycoord(Fn,Rn,En,Bn,e),r&&(l.uv=Wr.getInterpolatedAttribute(r,a,h,u,e,new Ys)),n&&(l.uv1=Wr.getInterpolatedAttribute(n,a,h,u,e,new Ys)),o&&(l.normal=Wr.getInterpolatedAttribute(o,a,h,u,e,new Ai),l.normal.dot(i.direction)>0&&l.normal.multiplyScalar(-1));const t={a:a,b:h,c:u,normal:new Ai,materialIndex:0};Wr.getNormal(Rn,En,Bn,t.normal),l.face=t,l.barycoord=e}return l}class Ln extends Sn{constructor(e=1,t=1,s=1,i=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:r,depthSegments:n};const o=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const a=[],h=[],u=[],l=[];let c=0,d=0;function p(e,t,s,i,r,n,p,m,g,f,y){const x=n/g,b=p/f,v=n/2,T=p/2,_=m/2,w=g+1,S=f+1;let M=0,A=0;const N=new Ai;for(let n=0;n0?1:-1,u.push(N.x,N.y,N.z),l.push(a/g),l.push(1-n/f),M+=1}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const e in this.extensions)!0===this.extensions[e]&&(s[e]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class kn extends Rr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new sr,this.projectionMatrix=new sr,this.projectionMatrixInverse=new sr,this.coordinateSystem=Us}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Gn=new Ai,Wn=new Ys,jn=new Ys;class Hn extends kn{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*ks*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Ds*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*ks*Math.atan(Math.tan(.5*Ds*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,s){Gn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Gn.x,Gn.y).multiplyScalar(-e/Gn.z),Gn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Gn.x,Gn.y).multiplyScalar(-e/Gn.z)}getViewSize(e,t){return this.getViewBounds(e,Wn,jn),t.subVectors(jn,Wn)}setViewOffset(e,t,s,i,r,n){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*Ds*this.fov)/this.zoom,s=2*t,i=this.aspect*s,r=-.5*i;const n=this.view;if(null!==this.view&&this.view.enabled){const e=n.fullWidth,o=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/o,i*=n.width/e,s*=n.height/o}const o=this.filmOffset;0!==o&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-s,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const qn=-90;class $n extends Rr{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Hn(qn,1,e,t);i.layers=this.layers,this.add(i);const r=new Hn(qn,1,e,t);r.layers=this.layers,this.add(r);const n=new Hn(qn,1,e,t);n.layers=this.layers,this.add(n);const o=new Hn(qn,1,e,t);o.layers=this.layers,this.add(o);const a=new Hn(qn,1,e,t);a.layers=this.layers,this.add(a);const h=new Hn(qn,1,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,o,a]=t;for(const e of t)this.remove(e);if(e===Us)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else{if(e!==Os)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,n,o,a,h,u]=this.children,l=e.getRenderTarget(),c=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1,e.setRenderTarget(s,0,i),e.render(t,r),e.setRenderTarget(s,1,i),e.render(t,n),e.setRenderTarget(s,2,i),e.render(t,o),e.setRenderTarget(s,3,i),e.render(t,a),e.setRenderTarget(s,4,i),e.render(t,h),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,u),e.setRenderTarget(l,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Xn extends yi{constructor(e,t,s,i,r,n,o,a,h,u){super(e=void 0!==e?e:[],t=void 0!==t?t:he,s,i,r,n,o,a,h,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Yn extends vi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Xn(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:Te}fromEquirectangularTexture(e,t){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 s={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Ln(5,5,5),r=new Dn({name:"CubemapFromEquirect",uniforms:Vn(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:d,blending:m});r.uniforms.tEquirect.value=t;const n=new On(i,r),o=t.minFilter;t.minFilter===Se&&(t.minFilter=Te);return new $n(1,10,this).update(e,n),t.minFilter=o,n.geometry.dispose(),n.material.dispose(),this}clear(e,t,s,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}class Zn{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new Xr(e),this.density=t}clone(){return new Zn(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Jn{constructor(e,t=1,s=1e3){this.isFog=!0,this.name="",this.color=new Xr(e),this.near=t,this.far=s}clone(){return new Jn(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Kn extends Rr{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new dr,this.environmentIntensity=1,this.environmentRotation=new dr,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Qn{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Ss,this.updateRanges=[],this.version=0,this.uuid=Gs()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,s){e*=this.stride,s*=t.stride;for(let i=0,r=this.stride;ie.far||t.push({distance:a,point:ro.clone(),uv:Wr.getInterpolation(ro,lo,co,po,mo,go,fo,new Ys),face:null,object:this})}copy(e,t){return super.copy(e,t),void 0!==e.center&&this.center.copy(e.center),this.material=e.material,this}}function xo(e,t,s,i,r,n){ao.subVectors(e,s).addScalar(.5).multiply(i),void 0!==r?(ho.x=n*ao.x-r*ao.y,ho.y=r*ao.x+n*ao.y):ho.copy(ao),e.copy(t),e.x+=ho.x,e.y+=ho.y,e.applyMatrix4(uo)}const bo=new Ai,vo=new Ai;class To extends Rr{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let e=0,s=t.length;e0){let s,i;for(s=1,i=t.length;s0){bo.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(bo);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){bo.setFromMatrixPosition(e.matrixWorld),vo.setFromMatrixPosition(this.matrixWorld);const s=bo.distanceTo(vo)/e.zoom;let i,r;for(t[0].object.visible=!0,i=1,r=t.length;i=e))break;t[i-1].object.visible=!1,t[i].object.visible=!0}for(this._currentLevel=i-1;i1?null:t.copy(e.start).addScaledVector(s,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const s=t||Xo.getNormalMatrix(e),i=this.coplanarPoint(qo).applyMatrix4(e),r=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const Zo=new $i,Jo=new Ai;class Ko{constructor(e=new Yo,t=new Yo,s=new Yo,i=new Yo,r=new Yo,n=new Yo){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(s),o[3].copy(i),o[4].copy(r),o[5].copy(n),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=2e3){const s=this.planes,i=e.elements,r=i[0],n=i[1],o=i[2],a=i[3],h=i[4],u=i[5],l=i[6],c=i[7],d=i[8],p=i[9],m=i[10],g=i[11],f=i[12],y=i[13],x=i[14],b=i[15];if(s[0].setComponents(a-r,c-h,g-d,b-f).normalize(),s[1].setComponents(a+r,c+h,g+d,b+f).normalize(),s[2].setComponents(a+n,c+u,g+p,b+y).normalize(),s[3].setComponents(a-n,c-u,g-p,b-y).normalize(),s[4].setComponents(a-o,c-l,g-m,b-x).normalize(),t===Us)s[5].setComponents(a+o,c+l,g+m,b+x).normalize();else{if(t!==Os)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);s[5].setComponents(o,l,m,x).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Zo.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Zo.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Zo)}intersectsSprite(e){return Zo.center.set(0,0,0),Zo.radius=.7071067811865476,Zo.applyMatrix4(e.matrixWorld),this.intersectsSphere(Zo)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(s)0?e.max.x:e.min.x,Jo.y=i.normal.y>0?e.max.y:e.min.y,Jo.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Jo)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function Qo(e,t){return e-t}function ea(e,t){return e.z-t.z}function ta(e,t){return t.z-e.z}class sa{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t,s){const i=this.pool,r=this.list;this.index>=i.length&&i.push({start:-1,count:-1,z:-1,index:-1});const n=i[this.index];r.push(n),this.index++,n.start=e.start,n.count=e.count,n.z=t,n.index=s}reset(){this.list.length=0,this.index=0}}const ia=new sr,ra=new sr,na=new sr,oa=new Xr(1,1,1),aa=new sr,ha=new Ko,ua=new Ri,la=new $i,ca=new Ai,da=new Ai,pa=new Ai,ma=new sa,ga=new On,fa=[];function ya(e,t,s=0){const i=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){const r=e.count;for(let n=0;n65535?new Uint32Array(i):new Uint16Array(i);t.setIndex(new an(e,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(Boolean(e.getIndex())!==Boolean(t.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const s in t.attributes){if(!e.hasAttribute(s))throw new Error(`BatchedMesh: Added geometry missing "${s}". All geometries must have consistent attributes.`);const i=e.getAttribute(s),r=t.getAttribute(s);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ri);const e=this.boundingBox,t=this._drawInfo;e.makeEmpty();for(let s=0,i=t.length;s=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("BatchedMesh: Maximum item count reached.");const t={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(Qo),s=this._availableInstanceIds.shift(),this._drawInfo[s]=t):(s=this._drawInfo.length,this._drawInfo.push(t));const i=this._matricesTexture,r=i.image.data;na.toArray(r,16*s),i.needsUpdate=!0;const n=this._colorsTexture;return n&&(oa.toArray(n.image.data,4*s),n.needsUpdate=!0),s}addGeometry(e,t=-1,s=-1){this._initializeGeometry(e),this._validateGeometry(e);const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let r=null;const n=this._reservedRanges,o=this._drawRanges,a=this._bounds;0!==this._geometryCount&&(r=n[n.length-1]),i.vertexCount=-1===t?e.getAttribute("position").count:t,i.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const h=e.getIndex(),u=null!==h;if(u&&(i.indexCount=-1===s?h.count:s,i.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==i.indexStart&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const l={start:u?i.indexStart:i.vertexStart,count:-1,active:!0},c={boxInitialized:!1,box:new Ri,sphereInitialized:!1,sphere:new $i};let d;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Qo),d=this._availableGeometryIds.shift(),n[d]=i,o[d]=l,a[d]=c):(d=this._geometryCount,this._geometryCount++,n.push(i),o.push(l),a.push(c)),this.setGeometryAt(d,e),d}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const s=this.geometry,i=null!==s.getIndex(),r=s.getIndex(),n=t.getIndex(),o=this._reservedRanges[e];if(i&&n.count>o.indexCount||t.attributes.position.count>o.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const a=o.vertexStart,h=o.vertexCount;for(const e in s.attributes){const i=t.getAttribute(e),r=s.getAttribute(e);ya(i,r,a);const n=i.itemSize;for(let e=i.count,t=h;e=t.length||!1===t[e].active)return this;const s=this._drawInfo;for(let t=0,i=s.length;t=t.length||!1===t[e].active||(t[e].active=!1,this._availableInstanceIds.push(e),this._visibilityChanged=!0),this}optimize(){let e=0,t=0;const s=this._drawRanges,i=this._reservedRanges,r=this.geometry;for(let n=0,o=s.length;n=this._geometryCount)return null;const s=this._bounds[e],i=s.box,r=this.geometry;if(!1===s.boxInitialized){i.makeEmpty();const t=r.index,n=r.attributes.position,o=this._drawRanges[e];for(let e=o.start,s=o.start+o.count;e=this._geometryCount)return null;const s=this._bounds[e],i=s.sphere,r=this.geometry;if(!1===s.sphereInitialized){i.makeEmpty(),this.getBoundingBoxAt(e,ua),ua.getCenter(i.center);const t=r.index,n=r.attributes.position,o=this._drawRanges[e];let a=0;for(let e=o.start,s=o.start+o.count;e=s.length||!1===s[e].active||(t.toArray(r,16*e),i.needsUpdate=!0),this}getMatrixAt(e,t){const s=this._drawInfo,i=this._matricesTexture.image.data;return e>=s.length||!1===s[e].active?null:t.fromArray(i,16*e)}setColorAt(e,t){null===this._colorsTexture&&this._initColorsTexture();const s=this._colorsTexture,i=this._colorsTexture.image.data,r=this._drawInfo;return e>=r.length||!1===r[e].active||(t.toArray(i,4*e),s.needsUpdate=!0),this}getColorAt(e,t){const s=this._colorsTexture.image.data,i=this._drawInfo;return e>=i.length||!1===i[e].active?null:t.fromArray(s,4*e)}setVisibleAt(e,t){const s=this._drawInfo;return e>=s.length||!1===s[e].active||s[e].visible===t||(s[e].visible=t,this._visibilityChanged=!0),this}getVisibleAt(e){const t=this._drawInfo;return!(e>=t.length||!1===t[e].active)&&t[e].visible}setGeometryIdAt(e,t){const s=this._drawInfo;return e>=s.length||!1===s[e].active||t<0||t>=this._geometryCount?null:(s[e].geometryIndex=t,this)}getGeometryIdAt(e){const t=this._drawInfo;return e>=t.length||!1===t[e].active?-1:t[e].geometryIndex}getGeometryRangeAt(e,t={}){if(e<0||e>=this._geometryCount)return null;const s=this._drawRanges[e];return t.start=s.start,t.count=s.count,t}setInstanceCount(e){const t=this._availableInstanceIds,s=this._drawInfo;for(t.sort(Qo);t[t.length-1]===s.length;)s.pop(),t.pop();if(ethis._drawRanges[t].active)),i=Math.max(...s.map((e=>e.vertexStart+e.vertexCount)));if(i>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index){const e=Math.max(...s.map((e=>e.indexStart+e.indexCount)));if(e>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`)}const r=this.geometry;r.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized=!1,this.geometry=new Sn,this._initializeGeometry(r);const n=this.geometry;r.index&&xa(r.index.array,n.index.array);for(const e in r.attributes)xa(r.attributes[e].array,n.attributes[e].array)}raycast(e,t){const s=this._drawInfo,i=this._drawRanges,r=this.matrixWorld,n=this.geometry;ga.material=this.material,ga.geometry.index=n.index,ga.geometry.attributes=n.attributes,null===ga.geometry.boundingBox&&(ga.geometry.boundingBox=new Ri),null===ga.geometry.boundingSphere&&(ga.geometry.boundingSphere=new $i);for(let n=0,o=s.length;n({...e}))),this._reservedRanges=e._reservedRanges.map((e=>({...e}))),this._drawInfo=e._drawInfo.map((e=>({...e}))),this._bounds=e._bounds.map((e=>({boxInitialized:e.boxInitialized,box:e.box.clone(),sphereInitialized:e.sphereInitialized,sphere:e.sphere.clone()}))),this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(e,t,s,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const n=i.getIndex(),o=null===n?1:n.array.BYTES_PER_ELEMENT,a=this._drawInfo,h=this._multiDrawStarts,u=this._multiDrawCounts,l=this._drawRanges,c=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data;c&&(aa.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse).multiply(this.matrixWorld),ha.setFromProjectionMatrix(aa,e.coordinateSystem));let m=0;if(this.sortObjects){ra.copy(this.matrixWorld).invert(),ca.setFromMatrixPosition(s.matrixWorld).applyMatrix4(ra),da.set(0,0,-1).transformDirection(s.matrixWorld).transformDirection(ra);for(let e=0,t=a.length;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;ei)return;Aa.applyMatrix4(e.matrixWorld);const a=t.ray.origin.distanceTo(Aa);return at.far?void 0:{distance:a,point:Na.clone().applyMatrix4(e.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:e}}const Ea=new Ai,Ba=new Ai;class Ia extends Ca{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,s=[];for(let e=0,i=t.count;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;er.far)return;n.push({distance:h,distanceToRay:Math.sqrt(a),point:s,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}class ka extends Rr{constructor(){super(),this.isGroup=!0,this.type="Group"}}class Ga extends yi{constructor(e,t,s,i,r,n,o,a,h){super(e,t,s,i,r,n,o,a,h),this.isVideoTexture=!0,this.minFilter=void 0!==n?n:Te,this.magFilter=void 0!==r?r:Te,this.generateMipmaps=!1;const u=this;"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback((function t(){u.needsUpdate=!0,e.requestVideoFrameCallback(t)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;!1==="requestVideoFrameCallback"in e&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class Wa extends yi{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=fe,this.minFilter=fe,this.generateMipmaps=!1,this.needsUpdate=!0}}class ja extends yi{constructor(e,t,s,i,r,n,o,a,h,u,l,c){super(null,n,o,a,h,u,i,r,l,c),this.isCompressedTexture=!0,this.image={width:t,height:s},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class Ha extends ja{constructor(e,t,s,i,r,n){super(e,t,s,r,n),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=me,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class qa extends ja{constructor(e,t,s){super(void 0,e[0].width,e[0].height,t,s,he),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class $a extends yi{constructor(e,t,s,i,r,n,o,a,h){super(e,t,s,i,r,n,o,a,h),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Xa extends yi{constructor(e,t,s,i,r,n,o,a,h,u=1026){if(u!==We&&u!==je)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===s&&u===We&&(s=Be),void 0===s&&u===je&&(s=Oe),super(null,i,r,n,o,a,u,s,h),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==o?o:fe,this.minFilter=void 0!==a?a:fe,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class Ya{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){const s=this.getUtoTmapping(e);return this.getPoint(s,t)}getPoints(e=5){const t=[];for(let s=0;s<=e;s++)t.push(this.getPoint(s/e));return t}getSpacedPoints(e=5){const t=[];for(let s=0;s<=e;s++)t.push(this.getPointAt(s/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let s,i=this.getPoint(0),r=0;t.push(0);for(let n=1;n<=e;n++)s=this.getPoint(n/e),r+=s.distanceTo(i),t.push(r),i=s;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){const s=this.getLengths();let i=0;const r=s.length;let n;n=t||e*s[r-1];let o,a=0,h=r-1;for(;a<=h;)if(i=Math.floor(a+(h-a)/2),o=s[i]-n,o<0)a=i+1;else{if(!(o>0)){h=i;break}h=i-1}if(i=h,s[i]===n)return i/(r-1);const u=s[i];return(i+(n-u)/(s[i+1]-u))/(r-1)}getTangent(e,t){const s=1e-4;let i=e-s,r=e+s;i<0&&(i=0),r>1&&(r=1);const n=this.getPoint(i),o=this.getPoint(r),a=t||(n.isVector2?new Ys:new Ai);return a.copy(o).sub(n).normalize(),a}getTangentAt(e,t){const s=this.getUtoTmapping(e);return this.getTangent(s,t)}computeFrenetFrames(e,t){const s=new Ai,i=[],r=[],n=[],o=new Ai,a=new sr;for(let t=0;t<=e;t++){const s=t/e;i[t]=this.getTangentAt(s,new Ai)}r[0]=new Ai,n[0]=new Ai;let h=Number.MAX_VALUE;const u=Math.abs(i[0].x),l=Math.abs(i[0].y),c=Math.abs(i[0].z);u<=h&&(h=u,s.set(1,0,0)),l<=h&&(h=l,s.set(0,1,0)),c<=h&&s.set(0,0,1),o.crossVectors(i[0],s).normalize(),r[0].crossVectors(i[0],o),n[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),n[t]=n[t-1].clone(),o.crossVectors(i[t-1],i[t]),o.length()>Number.EPSILON){o.normalize();const e=Math.acos(Ws(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(a.makeRotationAxis(o,e))}n[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(Ws(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(o.crossVectors(r[0],r[e]))>0&&(t=-t);for(let s=1;s<=e;s++)r[s].applyMatrix4(a.makeRotationAxis(i[s],t*s)),n[s].crossVectors(i[s],r[s])}return{tangents:i,normals:r,binormals:n}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Za extends Ya{constructor(e=0,t=0,s=1,i=1,r=0,n=2*Math.PI,o=!1,a=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=s,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=n,this.aClockwise=o,this.aRotation=a}getPoint(e,t=new Ys){const s=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const n=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(h)/r)+1)*r:0===u&&h===r-1&&(h=r-2,u=1),this.closed||h>0?o=i[(h-1)%r]:(Qa.subVectors(i[0],i[1]).add(i[0]),o=Qa);const l=i[h%r],c=i[(h+1)%r];if(this.closed||h+2i.length-2?i.length-1:n+1],l=i[n>i.length-3?i.length-1:n+2];return s.set(rh(o,a.x,h.x,u.x,l.x),rh(o,a.y,h.y,u.y,l.y)),s}copy(e){super.copy(e),this.points=[];for(let t=0,s=e.points.length;t=s){const e=i[r]-s,n=this.curves[r],o=n.getLength(),a=0===o?0:1-e/o;return n.getPointAt(a,t)}r++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let s=0,i=this.curves.length;s1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,s=e.curves.length;t0){const e=h.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y)}this.curves.push(h);const u=h.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class yh extends Sn{constructor(e=[new Ys(0,-.5),new Ys(.5,0),new Ys(0,.5)],t=12,s=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:s,phiLength:i},t=Math.floor(t),i=Ws(i,0,2*Math.PI);const r=[],n=[],o=[],a=[],h=[],u=1/t,l=new Ai,c=new Ys,d=new Ai,p=new Ai,m=new Ai;let g=0,f=0;for(let t=0;t<=e.length-1;t++)switch(t){case 0:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,d.x=1*f,d.y=-g,d.z=0*f,m.copy(d),d.normalize(),a.push(d.x,d.y,d.z);break;case e.length-1:a.push(m.x,m.y,m.z);break;default:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,d.x=1*f,d.y=-g,d.z=0*f,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),a.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=t;r++){const d=s+r*u*i,p=Math.sin(d),m=Math.cos(d);for(let s=0;s<=e.length-1;s++){l.x=e[s].x*p,l.y=e[s].y,l.z=e[s].x*m,n.push(l.x,l.y,l.z),c.x=r/t,c.y=s/(e.length-1),o.push(c.x,c.y);const i=a[3*s+0]*p,u=a[3*s+1],d=a[3*s+0]*m;h.push(i,u,d)}}for(let s=0;s0&&(u.push(r,n,a),x+=3),t>0&&(u.push(n,o,a),x+=3)}h.addGroup(f,x,0),f+=x}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new fn(l,3)),this.setAttribute("normal",new fn(c,3)),this.setAttribute("uv",new fn(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vh(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Th extends vh{constructor(e=1,t=1,s=32,i=1,r=!1,n=0,o=2*Math.PI){super(0,e,t,s,i,r,n,o),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:s,heightSegments:i,openEnded:r,thetaStart:n,thetaLength:o}}static fromJSON(e){return new Th(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class _h extends Sn{constructor(e=[],t=[],s=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:s,detail:i};const r=[],n=[];function o(e,t,s,i){const r=i+1,n=[];for(let i=0;i<=r;i++){n[i]=[];const o=e.clone().lerp(s,i/r),a=t.clone().lerp(s,i/r),h=r-i;for(let e=0;e<=h;e++)n[i][e]=0===e&&i===r?o:o.clone().lerp(a,e/h)}for(let e=0;e.9&&o<.1&&(t<.2&&(n[e+0]+=1),s<.2&&(n[e+2]+=1),i<.2&&(n[e+4]+=1))}}()}(),this.setAttribute("position",new fn(r,3)),this.setAttribute("normal",new fn(r.slice(),3)),this.setAttribute("uv",new fn(n,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new _h(e.vertices,e.indices,e.radius,e.details)}}class wh extends _h{constructor(e=1,t=0){const s=(1+Math.sqrt(5))/2,i=1/s;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-s,0,-i,s,0,i,-s,0,i,s,-i,-s,0,-i,s,0,i,-s,0,i,s,0,-s,0,-i,s,0,-i,-s,0,i,s,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new wh(e.radius,e.detail)}}const Sh=new Ai,Mh=new Ai,Ah=new Ai,Nh=new Wr;class Ch extends Sn{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},null!==e){const s=4,i=Math.pow(10,s),r=Math.cos(Ds*t),n=e.getIndex(),o=e.getAttribute("position"),a=n?n.count:o.count,h=[0,0,0],u=["a","b","c"],l=new Array(3),c={},d=[];for(let e=0;e80*s){a=u=e[0],h=l=e[1];for(let t=s;tu&&(u=c),d>l&&(l=d);p=Math.max(u-a,l-h),p=0!==p?32767/p:0}return Ph(n,o,s,a,h,p,0),o};function Bh(e,t,s,i,r){let n,o;if(r===function(e,t,s,i){let r=0;for(let n=t,o=s-i;n0)for(n=t;n=t;n-=i)o=Kh(n,e[n],e[n+1],o);return o&&qh(o,o.next)&&(Qh(o),o=o.next),o}function Ih(e,t){if(!e)return e;t||(t=e);let s,i=e;do{if(s=!1,i.steiner||!qh(i,i.next)&&0!==Hh(i.prev,i,i.next))i=i.next;else{if(Qh(i),i=t=i.prev,i===i.next)break;s=!0}}while(s||i!==t);return t}function Ph(e,t,s,i,r,n,o){if(!e)return;!o&&n&&function(e,t,s,i){let r=e;do{0===r.z&&(r.z=kh(r.x,r.y,t,s,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,s,i,r,n,o,a,h,u=1;do{for(s=e,e=null,n=null,o=0;s;){for(o++,i=s,a=0,t=0;t0||h>0&&i;)0!==a&&(0===h||!i||s.z<=i.z)?(r=s,s=s.nextZ,a--):(r=i,i=i.nextZ,h--),n?n.nextZ=r:e=r,r.prevZ=n,n=r;s=i}n.nextZ=null,u*=2}while(o>1)}(r)}(e,i,r,n);let a,h,u=e;for(;e.prev!==e.next;)if(a=e.prev,h=e.next,n?Uh(e,i,r,n):Fh(e))t.push(a.i/s|0),t.push(e.i/s|0),t.push(h.i/s|0),Qh(e),e=h.next,u=h.next;else if((e=h)===u){o?1===o?Ph(e=Oh(Ih(e),t,s),t,s,i,r,n,2):2===o&&zh(e,t,s,i,r,n):Ph(Ih(e),t,s,i,r,n,1);break}}function Fh(e){const t=e.prev,s=e,i=e.next;if(Hh(t,s,i)>=0)return!1;const r=t.x,n=s.x,o=i.x,a=t.y,h=s.y,u=i.y,l=rn?r>o?r:o:n>o?n:o,p=a>h?a>u?a:u:h>u?h:u;let m=i.next;for(;m!==t;){if(m.x>=l&&m.x<=d&&m.y>=c&&m.y<=p&&Wh(r,a,n,h,o,u,m.x,m.y)&&Hh(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Uh(e,t,s,i){const r=e.prev,n=e,o=e.next;if(Hh(r,n,o)>=0)return!1;const a=r.x,h=n.x,u=o.x,l=r.y,c=n.y,d=o.y,p=ah?a>u?a:u:h>u?h:u,f=l>c?l>d?l:d:c>d?c:d,y=kh(p,m,t,s,i),x=kh(g,f,t,s,i);let b=e.prevZ,v=e.nextZ;for(;b&&b.z>=y&&v&&v.z<=x;){if(b.x>=p&&b.x<=g&&b.y>=m&&b.y<=f&&b!==r&&b!==o&&Wh(a,l,h,c,u,d,b.x,b.y)&&Hh(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==o&&Wh(a,l,h,c,u,d,v.x,v.y)&&Hh(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;b&&b.z>=y;){if(b.x>=p&&b.x<=g&&b.y>=m&&b.y<=f&&b!==r&&b!==o&&Wh(a,l,h,c,u,d,b.x,b.y)&&Hh(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=x;){if(v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==o&&Wh(a,l,h,c,u,d,v.x,v.y)&&Hh(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function Oh(e,t,s){let i=e;do{const r=i.prev,n=i.next.next;!qh(r,n)&&$h(r,i,i.next,n)&&Zh(r,n)&&Zh(n,r)&&(t.push(r.i/s|0),t.push(i.i/s|0),t.push(n.i/s|0),Qh(i),Qh(i.next),i=e=n),i=i.next}while(i!==e);return Ih(i)}function zh(e,t,s,i,r,n){let o=e;do{let e=o.next.next;for(;e!==o.prev;){if(o.i!==e.i&&jh(o,e)){let a=Jh(o,e);return o=Ih(o,o.next),a=Ih(a,a.next),Ph(o,t,s,i,r,n,0),void Ph(a,t,s,i,r,n,0)}e=e.next}o=o.next}while(o!==e)}function Lh(e,t){return e.x-t.x}function Vh(e,t){const s=function(e,t){let s,i=t,r=-1/0;const n=e.x,o=e.y;do{if(o<=i.y&&o>=i.next.y&&i.next.y!==i.y){const e=i.x+(o-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=n&&e>r&&(r=e,s=i.x=i.x&&i.x>=h&&n!==i.x&&Wh(os.x||i.x===s.x&&Dh(s,i)))&&(s=i,c=l)),i=i.next}while(i!==a);return s}(e,t);if(!s)return t;const i=Jh(s,e);return Ih(i,i.next),Ih(s,s.next)}function Dh(e,t){return Hh(e.prev,e,t.prev)<0&&Hh(t.next,e,e.next)<0}function kh(e,t,s,i,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Gh(e){let t=e,s=e;do{(t.x=(e-o)*(n-a)&&(e-o)*(i-a)>=(s-o)*(t-a)&&(s-o)*(n-a)>=(r-o)*(i-a)}function jh(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let s=e;do{if(s.i!==e.i&&s.next.i!==e.i&&s.i!==t.i&&s.next.i!==t.i&&$h(s,s.next,e,t))return!0;s=s.next}while(s!==e);return!1}(e,t)&&(Zh(e,t)&&Zh(t,e)&&function(e,t){let s=e,i=!1;const r=(e.x+t.x)/2,n=(e.y+t.y)/2;do{s.y>n!=s.next.y>n&&s.next.y!==s.y&&r<(s.next.x-s.x)*(n-s.y)/(s.next.y-s.y)+s.x&&(i=!i),s=s.next}while(s!==e);return i}(e,t)&&(Hh(e.prev,e,t.prev)||Hh(e,t.prev,t))||qh(e,t)&&Hh(e.prev,e,e.next)>0&&Hh(t.prev,t,t.next)>0)}function Hh(e,t,s){return(t.y-e.y)*(s.x-t.x)-(t.x-e.x)*(s.y-t.y)}function qh(e,t){return e.x===t.x&&e.y===t.y}function $h(e,t,s,i){const r=Yh(Hh(e,t,s)),n=Yh(Hh(e,t,i)),o=Yh(Hh(s,i,e)),a=Yh(Hh(s,i,t));return r!==n&&o!==a||(!(0!==r||!Xh(e,s,t))||(!(0!==n||!Xh(e,i,t))||(!(0!==o||!Xh(s,e,i))||!(0!==a||!Xh(s,t,i)))))}function Xh(e,t,s){return t.x<=Math.max(e.x,s.x)&&t.x>=Math.min(e.x,s.x)&&t.y<=Math.max(e.y,s.y)&&t.y>=Math.min(e.y,s.y)}function Yh(e){return e>0?1:e<0?-1:0}function Zh(e,t){return Hh(e.prev,e,e.next)<0?Hh(e,t,e.next)>=0&&Hh(e,e.prev,t)>=0:Hh(e,t,e.prev)<0||Hh(e,e.next,t)<0}function Jh(e,t){const s=new eu(e.i,e.x,e.y),i=new eu(t.i,t.x,t.y),r=e.next,n=t.prev;return e.next=t,t.prev=e,s.next=r,r.prev=s,i.next=s,s.prev=i,n.next=i,i.prev=n,i}function Kh(e,t,s,i){const r=new eu(e,t,s);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Qh(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function eu(e,t,s){this.i=e,this.x=t,this.y=s,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class tu{static area(e){const t=e.length;let s=0;for(let i=t-1,r=0;r2&&e[t-1].equals(e[0])&&e.pop()}function iu(e,t){for(let s=0;sNumber.EPSILON){const c=Math.sqrt(l),d=Math.sqrt(h*h+u*u),p=t.x-a/c,m=t.y+o/c,g=((s.x-u/d-p)*u-(s.y+h/d-m)*h)/(o*u-a*h);i=p+o*g-e.x,r=m+a*g-e.y;const f=i*i+r*r;if(f<=2)return new Ys(i,r);n=Math.sqrt(f/2)}else{let e=!1;o>Number.EPSILON?h>Number.EPSILON&&(e=!0):o<-Number.EPSILON?h<-Number.EPSILON&&(e=!0):Math.sign(a)===Math.sign(u)&&(e=!0),e?(i=-a,r=o,n=Math.sqrt(l)):(i=o,r=a,n=Math.sqrt(l/2))}return new Ys(i/n,r/n)}const B=[];for(let e=0,t=A.length,s=t-1,i=e+1;e=0;e--){const t=e/p,s=l*Math.cos(t*Math.PI/2),i=c*Math.sin(t*Math.PI/2)+d;for(let e=0,t=A.length;e=0;){const i=s;let r=s-1;r<0&&(r=e.length-1);for(let e=0,s=a+2*p;e0)&&d.push(t,r,h),(e!==s-1||a0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class wu extends Jr{static get type(){return"MeshPhongMaterial"}constructor(e){super(),this.isMeshPhongMaterial=!0,this.color=new Xr(16777215),this.specular=new Xr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Su extends Jr{static get type(){return"MeshToonMaterial"}constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.color=new Xr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class Mu extends Jr{static get type(){return"MeshNormalMaterial"}constructor(e){super(),this.isMeshNormalMaterial=!0,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Au extends Jr{static get type(){return"MeshLambertMaterial"}constructor(e){super(),this.isMeshLambertMaterial=!0,this.color=new Xr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Nu extends Jr{static get type(){return"MeshDepthMaterial"}constructor(e){super(),this.isMeshDepthMaterial=!0,this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Cu extends Jr{static get type(){return"MeshDistanceMaterial"}constructor(e){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class Ru extends Jr{static get type(){return"MeshMatcapMaterial"}constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.color=new Xr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Eu extends va{static get type(){return"LineDashedMaterial"}constructor(e){super(),this.isLineDashedMaterial=!0,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function Bu(e,t,s){return!e||!s&&e.constructor===t?e:"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e)}function Iu(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Pu(e){const t=e.length,s=new Array(t);for(let e=0;e!==t;++e)s[e]=e;return s.sort((function(t,s){return e[t]-e[s]})),s}function Fu(e,t,s){const i=e.length,r=new e.constructor(i);for(let n=0,o=0;o!==i;++n){const i=s[n]*t;for(let s=0;s!==t;++s)r[o++]=e[i+s]}return r}function Uu(e,t,s,i){let r=1,n=e[0];for(;void 0!==n&&void 0===n[i];)n=e[r++];if(void 0===n)return;let o=n[i];if(void 0!==o)if(Array.isArray(o))do{o=n[i],void 0!==o&&(t.push(n.time),s.push.apply(s,o)),n=e[r++]}while(void 0!==n);else if(void 0!==o.toArray)do{o=n[i],void 0!==o&&(t.push(n.time),o.toArray(s,s.length)),n=e[r++]}while(void 0!==n);else do{o=n[i],void 0!==o&&(t.push(n.time),s.push(o)),n=e[r++]}while(void 0!==n)}const Ou={convertArray:Bu,isTypedArray:Iu,getKeyframeOrder:Pu,sortedArray:Fu,flattenJSON:Uu,subclip:function(e,t,s,i,r=30){const n=e.clone();n.name=t;const o=[];for(let e=0;e=i)){h.push(t.times[e]);for(let s=0;sn.tracks[e].times[0]&&(a=n.tracks[e].times[0]);for(let e=0;e=i.times[c]){const e=c*h+a,t=e+h-a;d=i.values.slice(e,t)}else{const e=i.createInterpolant(),t=a,s=h-a;e.evaluate(n),d=e.resultBuffer.slice(t,s)}if("quaternion"===r){(new Mi).fromArray(d).normalize().conjugate().toArray(d)}const p=o.times.length;for(let e=0;e=r)break e;{const o=t[1];e=r)break t}n=s,s=0}}for(;s>>1;et;)--n;if(++n,0!==r||n!==i){r>=n&&(n=Math.max(n,1),r=n-1);const e=this.getValueSize();this.times=s.slice(r,n),this.values=this.values.slice(r*e,n*e)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const s=this.times,i=this.values,r=s.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let n=null;for(let t=0;t!==r;t++){const i=s[t];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,t,i),e=!1;break}if(null!==n&&n>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,t,i,n),e=!1;break}n=i}if(void 0!==i&&Iu(i))for(let t=0,s=i.length;t!==s;++t){const s=i[t];if(isNaN(s)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,t,s),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),s=this.getValueSize(),i=this.getInterpolation()===Ft,r=e.length-1;let n=1;for(let o=1;o0){e[n]=e[r];for(let e=r*s,i=n*s,o=0;o!==s;++o)t[i+o]=t[e+o];++n}return n!==e.length?(this.times=e.slice(0,n),this.values=t.slice(0,n*s)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),s=new(0,this.constructor)(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}ku.prototype.TimeBufferType=Float32Array,ku.prototype.ValueBufferType=Float32Array,ku.prototype.DefaultInterpolation=Pt;class Gu extends ku{constructor(e,t,s){super(e,t,s)}}Gu.prototype.ValueTypeName="bool",Gu.prototype.ValueBufferType=Array,Gu.prototype.DefaultInterpolation=It,Gu.prototype.InterpolantFactoryMethodLinear=void 0,Gu.prototype.InterpolantFactoryMethodSmooth=void 0;class Wu extends ku{}Wu.prototype.ValueTypeName="color";class ju extends ku{}ju.prototype.ValueTypeName="number";class Hu extends zu{constructor(e,t,s,i){super(e,t,s,i)}interpolate_(e,t,s,i){const r=this.resultBuffer,n=this.sampleValues,o=this.valueSize,a=(s-t)/(i-t);let h=e*o;for(let e=h+o;h!==e;h+=4)Mi.slerpFlat(r,0,n,h-o,n,h,a);return r}}class qu extends ku{InterpolantFactoryMethodLinear(e){return new Hu(this.times,this.values,this.getValueSize(),e)}}qu.prototype.ValueTypeName="quaternion",qu.prototype.InterpolantFactoryMethodSmooth=void 0;class $u extends ku{constructor(e,t,s){super(e,t,s)}}$u.prototype.ValueTypeName="string",$u.prototype.ValueBufferType=Array,$u.prototype.DefaultInterpolation=It,$u.prototype.InterpolantFactoryMethodLinear=void 0,$u.prototype.InterpolantFactoryMethodSmooth=void 0;class Xu extends ku{}Xu.prototype.ValueTypeName="vector";class Yu{constructor(e="",t=-1,s=[],i=2500){this.name=e,this.tracks=s,this.duration=t,this.blendMode=i,this.uuid=Gs(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],s=e.tracks,i=1/(e.fps||1);for(let e=0,r=s.length;e!==r;++e)t.push(Zu(s[e]).scale(i));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){const t=[],s=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let e=0,i=s.length;e!==i;++e)t.push(ku.toJSON(s[e]));return i}static CreateFromMorphTargetSequence(e,t,s,i){const r=t.length,n=[];for(let e=0;e1){const e=n[1];let t=i[e];t||(i[e]=t=[]),t.push(s)}}const n=[];for(const e in i)n.push(this.CreateFromMorphTargetSequence(e,i[e],t,s));return n}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const s=function(e,t,s,i,r){if(0!==s.length){const n=[],o=[];Uu(s,n,o,i),0!==n.length&&r.push(new e(t,n,o))}},i=[],r=e.name||"default",n=e.fps||30,o=e.blendMode;let a=e.length||-1;const h=e.hierarchy||[];for(let e=0;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==tl[e])return void tl[e].push({onLoad:t,onProgress:s,onError:i});tl[e]=[],tl[e].push({onLoad:t,onProgress:s,onError:i});const n=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),o=this.mimeType,a=this.responseType;fetch(n).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body||void 0===t.body.getReader)return t;const s=tl[e],i=t.body.getReader(),r=t.headers.get("X-File-Size")||t.headers.get("Content-Length"),n=r?parseInt(r):0,o=0!==n;let a=0;const h=new ReadableStream({start(e){!function t(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:o,loaded:a,total:n});for(let e=0,t=s.length;e{e.error(t)}))}()}});return new Response(h)}throw new sl(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)})).then((e=>{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,o)));case"json":return e.json();default:if(void 0===o)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(o),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Ju.add(e,t);const s=tl[e];delete tl[e];for(let e=0,i=s.length;e{const s=tl[e];if(void 0===s)throw this.manager.itemError(e),t;delete tl[e];for(let e=0,i=s.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class rl extends el{constructor(e){super(e)}load(e,t,s,i){const r=this,n=new il(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(e,(function(s){try{t(r.parse(JSON.parse(s)))}catch(t){i?i(t):console.error(t),r.manager.itemError(e)}}),s,i)}parse(e){const t=[];for(let s=0;s0:i.vertexColors=e.vertexColors),void 0!==e.uniforms)for(const t in e.uniforms){const r=e.uniforms[t];switch(i.uniforms[t]={},r.type){case"t":i.uniforms[t].value=s(r.value);break;case"c":i.uniforms[t].value=(new Xr).setHex(r.value);break;case"v2":i.uniforms[t].value=(new Ys).fromArray(r.value);break;case"v3":i.uniforms[t].value=(new Ai).fromArray(r.value);break;case"v4":i.uniforms[t].value=(new xi).fromArray(r.value);break;case"m3":i.uniforms[t].value=(new Zs).fromArray(r.value);break;case"m4":i.uniforms[t].value=(new sr).fromArray(r.value);break;default:i.uniforms[t].value=r.value}}if(void 0!==e.defines&&(i.defines=e.defines),void 0!==e.vertexShader&&(i.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(i.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(i.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)i.extensions[t]=e.extensions[t];if(void 0!==e.lights&&(i.lights=e.lights),void 0!==e.clipping&&(i.clipping=e.clipping),void 0!==e.size&&(i.size=e.size),void 0!==e.sizeAttenuation&&(i.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(i.map=s(e.map)),void 0!==e.matcap&&(i.matcap=s(e.matcap)),void 0!==e.alphaMap&&(i.alphaMap=s(e.alphaMap)),void 0!==e.bumpMap&&(i.bumpMap=s(e.bumpMap)),void 0!==e.bumpScale&&(i.bumpScale=e.bumpScale),void 0!==e.normalMap&&(i.normalMap=s(e.normalMap)),void 0!==e.normalMapType&&(i.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),i.normalScale=(new Ys).fromArray(t)}return void 0!==e.displacementMap&&(i.displacementMap=s(e.displacementMap)),void 0!==e.displacementScale&&(i.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(i.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(i.roughnessMap=s(e.roughnessMap)),void 0!==e.metalnessMap&&(i.metalnessMap=s(e.metalnessMap)),void 0!==e.emissiveMap&&(i.emissiveMap=s(e.emissiveMap)),void 0!==e.emissiveIntensity&&(i.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(i.specularMap=s(e.specularMap)),void 0!==e.specularIntensityMap&&(i.specularIntensityMap=s(e.specularIntensityMap)),void 0!==e.specularColorMap&&(i.specularColorMap=s(e.specularColorMap)),void 0!==e.envMap&&(i.envMap=s(e.envMap)),void 0!==e.envMapRotation&&i.envMapRotation.fromArray(e.envMapRotation),void 0!==e.envMapIntensity&&(i.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(i.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(i.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(i.lightMap=s(e.lightMap)),void 0!==e.lightMapIntensity&&(i.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(i.aoMap=s(e.aoMap)),void 0!==e.aoMapIntensity&&(i.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(i.gradientMap=s(e.gradientMap)),void 0!==e.clearcoatMap&&(i.clearcoatMap=s(e.clearcoatMap)),void 0!==e.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=s(e.clearcoatRoughnessMap)),void 0!==e.clearcoatNormalMap&&(i.clearcoatNormalMap=s(e.clearcoatNormalMap)),void 0!==e.clearcoatNormalScale&&(i.clearcoatNormalScale=(new Ys).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(i.iridescenceMap=s(e.iridescenceMap)),void 0!==e.iridescenceThicknessMap&&(i.iridescenceThicknessMap=s(e.iridescenceThicknessMap)),void 0!==e.transmissionMap&&(i.transmissionMap=s(e.transmissionMap)),void 0!==e.thicknessMap&&(i.thicknessMap=s(e.thicknessMap)),void 0!==e.anisotropyMap&&(i.anisotropyMap=s(e.anisotropyMap)),void 0!==e.sheenColorMap&&(i.sheenColorMap=s(e.sheenColorMap)),void 0!==e.sheenRoughnessMap&&(i.sheenRoughnessMap=s(e.sheenRoughnessMap)),i}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return El.createMaterialFromType(e)}static createMaterialFromType(e){return new{ShadowMaterial:bu,SpriteMaterial:so,RawShaderMaterial:vu,ShaderMaterial:Dn,PointsMaterial:Fa,MeshPhysicalMaterial:_u,MeshStandardMaterial:Tu,MeshPhongMaterial:wu,MeshToonMaterial:Su,MeshNormalMaterial:Mu,MeshLambertMaterial:Au,MeshDepthMaterial:Nu,MeshDistanceMaterial:Cu,MeshBasicMaterial:Kr,MeshMatcapMaterial:Ru,LineDashedMaterial:Eu,LineBasicMaterial:va,Material:Jr}[e]}}class Bl{static decodeText(e){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0,i=e.length;s0){const s=new Ku(t);r=new ol(s),r.setCrossOrigin(this.crossOrigin);for(let t=0,s=e.length;t0){i=new ol(this.manager),i.setCrossOrigin(this.crossOrigin);for(let t=0,i=e.length;t{const t=new Ri;t.min.fromArray(e.boxMin),t.max.fromArray(e.boxMax);const s=new $i;return s.radius=e.sphereRadius,s.center.fromArray(e.sphereCenter),{boxInitialized:e.boxInitialized,box:t,sphereInitialized:e.sphereInitialized,sphere:s}})),n._maxInstanceCount=e.maxInstanceCount,n._maxVertexCount=e.maxVertexCount,n._maxIndexCount=e.maxIndexCount,n._geometryInitialized=e.geometryInitialized,n._geometryCount=e.geometryCount,n._matricesTexture=l(e.matricesTexture.uuid),void 0!==e.colorsTexture&&(n._colorsTexture=l(e.colorsTexture.uuid));break;case"LOD":n=new To;break;case"Line":n=new Ca(h(e.geometry),u(e.material));break;case"LineLoop":n=new Pa(h(e.geometry),u(e.material));break;case"LineSegments":n=new Ia(h(e.geometry),u(e.material));break;case"PointCloud":case"Points":n=new Va(h(e.geometry),u(e.material));break;case"Sprite":n=new yo(u(e.material));break;case"Group":n=new ka;break;case"Bone":n=new Io;break;default:n=new Rr}if(n.uuid=e.uuid,void 0!==e.name&&(n.name=e.name),void 0!==e.matrix?(n.matrix.fromArray(e.matrix),void 0!==e.matrixAutoUpdate&&(n.matrixAutoUpdate=e.matrixAutoUpdate),n.matrixAutoUpdate&&n.matrix.decompose(n.position,n.quaternion,n.scale)):(void 0!==e.position&&n.position.fromArray(e.position),void 0!==e.rotation&&n.rotation.fromArray(e.rotation),void 0!==e.quaternion&&n.quaternion.fromArray(e.quaternion),void 0!==e.scale&&n.scale.fromArray(e.scale)),void 0!==e.up&&n.up.fromArray(e.up),void 0!==e.castShadow&&(n.castShadow=e.castShadow),void 0!==e.receiveShadow&&(n.receiveShadow=e.receiveShadow),e.shadow&&(void 0!==e.shadow.intensity&&(n.shadow.intensity=e.shadow.intensity),void 0!==e.shadow.bias&&(n.shadow.bias=e.shadow.bias),void 0!==e.shadow.normalBias&&(n.shadow.normalBias=e.shadow.normalBias),void 0!==e.shadow.radius&&(n.shadow.radius=e.shadow.radius),void 0!==e.shadow.mapSize&&n.shadow.mapSize.fromArray(e.shadow.mapSize),void 0!==e.shadow.camera&&(n.shadow.camera=this.parseObject(e.shadow.camera))),void 0!==e.visible&&(n.visible=e.visible),void 0!==e.frustumCulled&&(n.frustumCulled=e.frustumCulled),void 0!==e.renderOrder&&(n.renderOrder=e.renderOrder),void 0!==e.userData&&(n.userData=e.userData),void 0!==e.layers&&(n.layers.mask=e.layers),void 0!==e.children){const o=e.children;for(let e=0;e{t&&t(s),r.manager.itemEnd(e)})).catch((e=>{i&&i(e)})):(setTimeout((function(){t&&t(n),r.manager.itemEnd(e)}),0),n);const o={};o.credentials="anonymous"===this.crossOrigin?"same-origin":"include",o.headers=this.requestHeader;const a=fetch(e,o).then((function(e){return e.blob()})).then((function(e){return createImageBitmap(e,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(s){return Ju.add(e,s),t&&t(s),r.manager.itemEnd(e),s})).catch((function(t){i&&i(t),Ju.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)}));Ju.add(e,a),r.manager.itemStart(e)}}let Vl;class Dl{static getContext(){return void 0===Vl&&(Vl=new(window.AudioContext||window.webkitAudioContext)),Vl}static setContext(e){Vl=e}}class kl extends el{constructor(e){super(e)}load(e,t,s,i){const r=this,n=new il(this.manager);function o(t){i?i(t):console.error(t),r.manager.itemError(e)}n.setResponseType("arraybuffer"),n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(e,(function(e){try{const s=e.slice(0);Dl.getContext().decodeAudioData(s,(function(e){t(e)})).catch(o)}catch(e){o(e)}}),s,i)}}const Gl=new sr,Wl=new sr,jl=new sr;class Hl{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Hn,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Hn,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,jl.copy(e.projectionMatrix);const s=t.eyeSep/2,i=s*t.near/t.focus,r=t.near*Math.tan(Ds*t.fov*.5)/t.zoom;let n,o;Wl.elements[12]=-s,Gl.elements[12]=s,n=-r*t.aspect+i,o=r*t.aspect+i,jl.elements[0]=2*t.near/(o-n),jl.elements[8]=(o+n)/(o-n),this.cameraL.projectionMatrix.copy(jl),n=-r*t.aspect-i,o=r*t.aspect-i,jl.elements[0]=2*t.near/(o-n),jl.elements[8]=(o+n)/(o-n),this.cameraR.projectionMatrix.copy(jl)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Wl),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Gl)}}class ql extends Hn{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class $l{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Xl(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=Xl();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Xl(){return performance.now()}const Yl=new Ai,Zl=new Mi,Jl=new Ai,Kl=new Ai;class Ql extends Rr{constructor(){super(),this.type="AudioListener",this.context=Dl.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new $l}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener,s=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Yl,Zl,Jl),Kl.set(0,0,-1).applyQuaternion(Zl),t.positionX){const e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Yl.x,e),t.positionY.linearRampToValueAtTime(Yl.y,e),t.positionZ.linearRampToValueAtTime(Yl.z,e),t.forwardX.linearRampToValueAtTime(Kl.x,e),t.forwardY.linearRampToValueAtTime(Kl.y,e),t.forwardZ.linearRampToValueAtTime(Kl.z,e),t.upX.linearRampToValueAtTime(s.x,e),t.upY.linearRampToValueAtTime(s.y,e),t.upZ.linearRampToValueAtTime(s.z,e)}else t.setPosition(Yl.x,Yl.y,Yl.z),t.setOrientation(Kl.x,Kl.y,Kl.z,s.x,s.y,s.z)}}class ec extends Rr{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(!0===this.isPlaying)return void console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.Audio: this Audio has no playback control.");this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;console.warn("THREE.Audio: this Audio has no playback control.")}stop(e=0){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this;console.warn("THREE.Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(s,i,this._addIndex*t,1,t);for(let e=t,r=t+t;e!==r;++e)if(s[e]!==s[e+t]){o.setValue(s,i);break}}saveOriginalState(){const e=this.binding,t=this.buffer,s=this.valueSize,i=s*this._origIndex;e.getValue(t,i);for(let e=s,r=i;e!==r;++e)t[e]=t[i+e%s];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=3*this.valueSize;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let s=e;s=.5)for(let i=0;i!==r;++i)e[t+i]=e[s+i]}_slerp(e,t,s,i){Mi.slerpFlat(e,t,e,t,e,s,i)}_slerpAdditive(e,t,s,i,r){const n=this._workIndex*r;Mi.multiplyQuaternionsFlat(e,n,e,t,e,s),Mi.slerpFlat(e,t,e,t,e,n,i)}_lerp(e,t,s,i,r){const n=1-i;for(let o=0;o!==r;++o){const r=t+o;e[r]=e[r]*n+e[s+o]*i}}_lerpAdditive(e,t,s,i,r){for(let n=0;n!==r;++n){const r=t+n;e[r]=e[r]+e[s+n]*i}}}const hc="\\[\\]\\.:\\/",uc=new RegExp("["+hc+"]","g"),lc="[^"+hc+"]",cc="[^"+hc.replace("\\.","")+"]",dc=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",lc)+/(WCOD+)?/.source.replace("WCOD",cc)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",lc)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",lc)+"$"),pc=["material","materials","bones","map"];class mc{constructor(e,t,s){this.path=t,this.parsedPath=s||mc.parseTrackName(t),this.node=mc.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,s){return e&&e.isAnimationObjectGroup?new mc.Composite(e,t,s):new mc(e,t,s)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(uc,"")}static parseTrackName(e){const t=dc.exec(e);if(null===t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const s={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=s.nodeName&&s.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const e=s.nodeName.substring(i+1);-1!==pc.indexOf(e)&&(s.nodeName=s.nodeName.substring(0,i),s.objectName=e)}if(null===s.propertyName||0===s.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return s}static findNode(e,t){if(void 0===t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const s=e.skeleton.getBoneByName(t);if(void 0!==s)return s}if(e.children){const s=function(e){for(let i=0;i=r){const n=r++,u=e[n];t[u.uuid]=h,e[h]=u,t[a]=n,e[n]=o;for(let e=0,t=i;e!==t;++e){const t=s[e],i=t[n],r=t[h];t[h]=i,t[n]=r}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,s=this._bindings,i=s.length;let r=this.nCachedObjects_,n=e.length;for(let o=0,a=arguments.length;o!==a;++o){const a=arguments[o].uuid,h=t[a];if(void 0!==h)if(delete t[a],h0&&(t[o.uuid]=h),e[h]=o,e.pop();for(let e=0,t=i;e!==t;++e){const t=s[e];t[h]=t[r],t.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const s=this._bindingsIndicesByPath;let i=s[e];const r=this._bindings;if(void 0!==i)return r[i];const n=this._paths,o=this._parsedPaths,a=this._objects,h=a.length,u=this.nCachedObjects_,l=new Array(h);i=r.length,s[e]=i,n.push(e),o.push(t),r.push(l);for(let s=u,i=a.length;s!==i;++s){const i=a[s];l[s]=new mc(i,e,t)}return l}unsubscribe_(e){const t=this._bindingsIndicesByPath,s=t[e];if(void 0!==s){const i=this._paths,r=this._parsedPaths,n=this._bindings,o=n.length-1,a=n[o];t[e[o]]=s,n[s]=a,n.pop(),r[s]=r[o],r.pop(),i[s]=i[o],i.pop()}}}class fc{constructor(e,t,s=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=s,this.blendMode=i;const r=t.tracks,n=r.length,o=new Array(n),a={endingStart:Ut,endingEnd:Ut};for(let e=0;e!==n;++e){const t=r[e].createInterpolant(null);o[e]=t,t.settings=a}this._interpolantSettings=a,this._interpolants=o,this._propertyBindings=new Array(n),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,s){if(e.fadeOut(t),this.fadeIn(t),s){const s=this._clip.duration,i=e._clip.duration,r=i/s,n=s/i;e.warp(1,r,t),this.warp(n,1,t)}return this}crossFadeTo(e,t,s){return e.crossFadeFrom(this,t,s)}stopFading(){const e=this._weightInterpolant;return null!==e&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,s){const i=this._mixer,r=i.time,n=this.timeScale;let o=this._timeScaleInterpolant;null===o&&(o=i._lendControlInterpolant(),this._timeScaleInterpolant=o);const a=o.parameterPositions,h=o.sampleValues;return a[0]=r,a[1]=r+s,h[0]=e/n,h[1]=t/n,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,s,i){if(!this.enabled)return void this._updateWeight(e);const r=this._startTime;if(null!==r){const i=(e-r)*s;i<0||0===s?t=0:(this._startTime=null,t=s*i)}t*=this._updateTimeScale(e);const n=this._updateTime(t),o=this._updateWeight(e);if(o>0){const e=this._interpolants,t=this._propertyBindings;if(this.blendMode===Vt)for(let s=0,i=e.length;s!==i;++s)e[s].evaluate(n),t[s].accumulateAdditive(o);else for(let s=0,r=e.length;s!==r;++s)e[s].evaluate(n),t[s].accumulate(i,o)}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const s=this._weightInterpolant;if(null!==s){const i=s.evaluate(e)[0];t*=i,e>s.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const s=this._timeScaleInterpolant;if(null!==s){t*=s.evaluate(e)[0],e>s.parameterPositions[1]&&(this.stopWarping(),0===t?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,s=this.loop;let i=this.time+e,r=this._loopCount;const n=2202===s;if(0===e)return-1===r?i:n&&1==(1&r)?t-i:i;if(2200===s){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else{if(!(i<0)){this.time=i;break e}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(-1===r&&(e>=0?(r=0,this._setEndings(!0,0===this.repetitions,n)):this._setEndings(0===this.repetitions,!0,n)),i>=t||i<0){const s=Math.floor(i/t);i-=t*s,r+=Math.abs(s);const o=this.repetitions-r;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(1===o){const t=e<0;this._setEndings(t,!t,n)}else this._setEndings(!1,!1,n);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:s})}}else this.time=i;if(n&&1==(1&r))return t-i}return i}_setEndings(e,t,s){const i=this._interpolantSettings;s?(i.endingStart=Ot,i.endingEnd=Ot):(i.endingStart=e?this.zeroSlopeAtStart?Ot:Ut:zt,i.endingEnd=t?this.zeroSlopeAtEnd?Ot:Ut:zt)}_scheduleFading(e,t,s){const i=this._mixer,r=i.time;let n=this._weightInterpolant;null===n&&(n=i._lendControlInterpolant(),this._weightInterpolant=n);const o=n.parameterPositions,a=n.sampleValues;return o[0]=r,a[0]=t,o[1]=r+e,a[1]=s,this}}const yc=new Float32Array(1);class xc extends zs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const s=e._localRoot||this._root,i=e._clip.tracks,r=i.length,n=e._propertyBindings,o=e._interpolants,a=s.uuid,h=this._bindingsByRootAndName;let u=h[a];void 0===u&&(u={},h[a]=u);for(let e=0;e!==r;++e){const r=i[e],h=r.name;let l=u[h];if(void 0!==l)++l.referenceCount,n[e]=l;else{if(l=n[e],void 0!==l){null===l._cacheIndex&&(++l.referenceCount,this._addInactiveBinding(l,a,h));continue}const i=t&&t._propertyBindings[e].binding.parsedPath;l=new ac(mc.create(s,h,i),r.ValueTypeName,r.getValueSize()),++l.referenceCount,this._addInactiveBinding(l,a,h),n[e]=l}o[e].resultBuffer=l.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,s=e._clip.uuid,i=this._actionsByClip[s];this._bindAction(e,i&&i.knownActions[0]),this._addInactiveAction(e,s,t)}const t=e._propertyBindings;for(let e=0,s=t.length;e!==s;++e){const s=t[e];0==s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,s=t.length;e!==s;++e){const s=t[e];0==--s.useCount&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return null!==t&&t=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,s=this._nActiveActions,i=this.time+=e,r=Math.sign(e),n=this._accuIndex^=1;for(let o=0;o!==s;++o){t[o]._update(i,e,r,n)}const o=this._bindings,a=this._nActiveBindings;for(let e=0;e!==a;++e)o[e].apply(n);return this}setTime(e){this.time=0;for(let e=0;e=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bc).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Pc=new Ai,Fc=new Ai;class Uc{constructor(e=new Ai,t=new Ai){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){Pc.subVectors(e,this.start),Fc.subVectors(this.end,this.start);const s=Fc.dot(Fc);let i=Fc.dot(Pc)/s;return t&&(i=Ws(i,0,1)),i}closestPointToPoint(e,t,s){const i=this.closestPointToPointParameter(e,t);return this.delta(s).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const Oc=new Ai;class zc extends Rr{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const s=new Sn,i=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let e=0,t=1,s=32;e1)for(let s=0;s.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{hd.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(hd,t)}}setLength(e,t=.2*e,s=.2*t){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(s,t,s),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class dd extends Ia{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],s=new Sn;s.setAttribute("position",new fn(t,3)),s.setAttribute("color",new fn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(s,new va({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(e,t,s){const i=new Xr,r=this.geometry.attributes.color.array;return i.set(e),i.toArray(r,0),i.toArray(r,3),i.set(t),i.toArray(r,6),i.toArray(r,9),i.set(s),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class pd{constructor(){this.type="ShapePath",this.color=new Xr,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new fh,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,s,i){return this.currentPath.quadraticCurveTo(e,t,s,i),this}bezierCurveTo(e,t,s,i,r,n){return this.currentPath.bezierCurveTo(e,t,s,i,r,n),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(e,t){const s=t.length;let i=!1;for(let r=s-1,n=0;nNumber.EPSILON){if(h<0&&(s=t[n],a=-a,o=t[r],h=-h),e.yo.y)continue;if(e.y===s.y){if(e.x===s.x)return!0}else{const t=h*(e.x-s.x)-a*(e.y-s.y);if(0===t)return!0;if(t<0)continue;i=!i}}else{if(e.y!==s.y)continue;if(o.x<=e.x&&e.x<=s.x||s.x<=e.x&&e.x<=o.x)return!0}}return i}const s=tu.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,n,o;const a=[];if(1===i.length)return n=i[0],o=new Rh,o.curves=n.curves,a.push(o),a;let h=!s(i[0].getPoints());h=e?!h:h;const u=[],l=[];let c,d,p=[],m=0;l[m]=void 0,p[m]=[];for(let t=0,o=i.length;t1){let e=!1,s=0;for(let e=0,t=l.length;e0&&!1===e&&(p=u)}for(let e=0,t=l.length;e>>16,2246822507),s^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(s^s>>>13,3266489909),4294967296*(2097151&i)+(s>>>0)}const bd=e=>xd(e),vd=e=>xd(e),Td=(...e)=>xd(e);function _d(e,t=!1){const s=[];!0===e.isNode&&(s.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of wd(e))s.push(s,xd(i.slice(0,-4)),r.getCacheKey(t));return xd(s)}function*wd(e,t=!1){for(const s in e){if(!0===s.startsWith("_"))continue;const i=e[s];if(!0===Array.isArray(i))for(let e=0;ee.charCodeAt(0))).buffer}var Cd=Object.freeze({__proto__:null,arrayBufferToBase64:Ad,base64ToArrayBuffer:Nd,getCacheKey:_d,getNodeChildren:wd,getValueFromType:Md,getValueType:Sd,hash:Td,hashArray:vd,hashString:bd});const Rd={VERTEX:"vertex",FRAGMENT:"fragment"},Ed={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Bd={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Id=["fragment","vertex"],Pd=["setup","analyze","generate"],Fd=[...Id,"compute"],Ud=["x","y","z","w"];let Od=0;class zd extends zs{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Ed.NONE,this.updateBeforeType=Ed.NONE,this.updateAfterType=Ed.NONE,this.uuid=Xs.generateUUID(),this.version=0,this._cacheKey=null,this._cacheKeyVersion=0,this.global=!1,this.isNode=!0,Object.defineProperty(this,"id",{value:Od++})}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.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Ed.FRAME)}onRenderUpdate(e){return this.onUpdate(e,Ed.RENDER)}onObjectUpdate(e){return this.onUpdate(e,Ed.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of wd(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=_d(this,e),this._cacheKeyVersion=this.version),this._cacheKey}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)}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}setup(e){const t=e.getNodeProperties(this);let s=0;for(const e of this.getChildren())t["node"+s++]=e;return null}analyze(e){if(1===e.increaseUsage(this)){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){e.stack.nodes.length;t.initialized=!0,t.outputNode=this.setup(e),null!==t.outputNode&&e.stack.nodes.length;for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const s=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i?(i=this.generate(e)||"",r.snippet=i):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),i=e.format(i,s,t)}else i=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),i}getSerializeChildren(){return wd(this)}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:r,childNode:n}of t)void 0!==r?(void 0===s[i]&&(s[i]=Number.isInteger(r)?[]:{}),s[i][r]=n.toJSON(e.meta).uuid):s[i]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const r of e.inputNodes[s])i.push(t[r]);this[s]=i}else if("object"==typeof e.inputNodes[s]){const i={};for(const r in e.inputNodes[s]){const n=e.inputNodes[s][r];i[r]=t[n]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:s,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=n(e.textures),s=n(e.images),i=n(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),i.length>0&&(r.nodes=i)}return r}}class Ld extends zd{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){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}class Vd extends zd{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(i)||(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),r=s.build(e,i);return e.format(r,i,t)}}class Dd extends zd{static get type(){return"TempNode"}constructor(e){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,s,t);if("void"!==s&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,s),n=e.getVarFromNode(this,null,s),o=e.getPropertyName(n);return e.addLineFlowCode(`${o} = ${r}`,this),i.snippet=r,i.propertyName=o,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class kd extends Dd{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,s)=>t+e.getTypeLength(s.getNodeType(e))),0))}generate(e,t){const s=this.getNodeType(e),i=this.nodes,r=e.getComponentType(s),n=[];for(const t of i){let s=t.build(e);const i=e.getComponentType(t.getNodeType(e));i!==r&&(s=e.format(s,i,r)),n.push(s)}const o=`${e.getType(s)}( ${n.join(", ")} )`;return e.format(o,s,t)}}const Gd=Ud.join("");class Wd extends zd{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(Ud.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))}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let r=null;if(i>1){let n=null;this.getVectorLength()>=i&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const o=s.build(e,n);r=this.components.length===i&&this.components===Gd.slice(0,this.components.length)?e.format(o,n,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else r=s.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class jd extends Dd{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,r=this.getNodeType(e),n=e.getTypeFromLength(s.length,i.getNodeType(e)),o=i.build(e,n),a=t.build(e,r),h=e.getTypeLength(r),u=[];for(let e=0;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Kd=e=>Jd(e).split("").sort().join(""),Qd={setup(e,t){const s=t.shift();return e(Sp(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Xd.assign(s,...e),s);if(Yd.has(t)){const i=Yd.get(t);return e.isStackNode?(...e)=>s.add(i(...e)):(...e)=>i(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Yd.has(t.slice(0,t.length-6))){const i=Yd.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>s.assign(e[0],i(...e)):(...e)=>s.assign(i(s,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=Jd(t),wp(new Wd(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Kd(t.slice(3).toLowerCase()),s=>wp(new jd(e,t,s));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Kd(t.slice(4).toLowerCase()),()=>wp(new Hd(wp(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),wp(new Wd(e,t));if(!0===/^\d+$/.test(t))return wp(new Ld(s,new $d(Number(t),"uint")))}return Reflect.get(e,t,s)},set:(e,t,s,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,s,i):(i[t].assign(s),!0)},ep=new WeakMap,tp=new WeakMap,sp=function(e,t=null){for(const s in e)e[s]=wp(e[s],t);return e},ip=function(e,t=null){const s=e.length;for(let i=0;iwp(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...Mp(t))):null!==s?(s=wp(s),(...i)=>r(new e(t,...Mp(i),s))):(...s)=>r(new e(t,...Mp(s)))},np=function(e,...t){return wp(new e(...Mp(t)))};class op extends zd{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}call(e){const{shaderNode:t,inputNodes:s}=this,i=e.getNodeProperties(t);if(i.onceOutput)return i.onceOutput;let r=null;if(t.layout){let i=tp.get(e.constructor);void 0===i&&(i=new WeakMap,tp.set(e.constructor,i));let n=i.get(t);void 0===n&&(n=wp(e.buildFunctionNode(t)),i.set(t,n)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(n),r=wp(n.call(s))}else{const i=t.jsFunc,n=null!==s?i(s,e):i(e);r=wp(n)}return t.once&&(i.onceOutput=r),r}getOutputNode(e){const t=e.getNodeProperties(this);return null===t.outputNode&&(t.outputNode=this.setupOutput(e)),t.outputNode}setup(e){return this.getOutputNode(e)}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){return this.getOutputNode(e).build(e,t)}}class ap extends zd{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 Sp(e),wp(new op(this,e))}setup(){return this.call()}}const hp=[!1,!0],up=[0,1,2,3],lp=[-1,-2],cp=[.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],dp=new Map;for(const e of hp)dp.set(e,new $d(e));const pp=new Map;for(const e of up)pp.set(e,new $d(e,"uint"));const mp=new Map([...pp].map((e=>new $d(e.value,"int"))));for(const e of lp)mp.set(e,new $d(e,"int"));const gp=new Map([...mp].map((e=>new $d(e.value))));for(const e of cp)gp.set(e,new $d(e));for(const e of cp)gp.set(-e,new $d(-e));const fp={bool:dp,uint:pp,ints:mp,float:gp},yp=new Map([...dp,...gp]),xp=(e,t)=>yp.has(e)?yp.get(e):!0===e.isNode?e:new $d(e,t),bp=function(e,t=null){return(...s)=>{if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every((e=>"object"!=typeof e)))&&(s=[Md(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return wp(t.get(s[0]));if(1===s.length){const t=xp(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?wp(t):wp(new Vd(t,e))}const i=s.map((e=>xp(e)));return wp(new kd(i,e))}},vp=e=>"object"==typeof e&&null!==e?e.value:e,Tp=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function _p(e,t){return new Proxy(new ap(e,t),Qd)}const wp=(e,t=null)=>function(e,t=null){const s=Sd(e);if("node"===s){let t=ep.get(e);return void 0===t&&(t=new Proxy(e,Qd),ep.set(e,t),ep.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?wp(xp(e,t)):"shader"===s?Cp(e):e}(e,t),Sp=(e,t=null)=>new sp(e,t),Mp=(e,t=null)=>new ip(e,t),Ap=(...e)=>new rp(...e),Np=(...e)=>new np(...e),Cp=(e,t)=>{const s=new _p(e,t),i=(...e)=>{let t;return Sp(e),t=e[0]&&e[0].isNode?[...e]:e[0],s.call(t)};return i.shaderNode=s,i.setLayout=e=>(s.setLayout(e),i),i.once=()=>(s.once=!0,i),i},Rp=(...e)=>(console.warn("TSL.ShaderNode: tslFn() has been renamed to Fn()."),Cp(...e));Zd("toGlobal",(e=>(e.global=!0,e)));const Ep=e=>{Xd=e},Bp=()=>Xd,Ip=(...e)=>Xd.If(...e);function Pp(e){return Xd&&Xd.add(e),e}Zd("append",Pp);const Fp=new bp("color"),Up=new bp("float",fp.float),Op=new bp("int",fp.ints),zp=new bp("uint",fp.uint),Lp=new bp("bool",fp.bool),Vp=new bp("vec2"),Dp=new bp("ivec2"),kp=new bp("uvec2"),Gp=new bp("bvec2"),Wp=new bp("vec3"),jp=new bp("ivec3"),Hp=new bp("uvec3"),qp=new bp("bvec3"),$p=new bp("vec4"),Xp=new bp("ivec4"),Yp=new bp("uvec4"),Zp=new bp("bvec4"),Jp=new bp("mat2"),Kp=new bp("mat3"),Qp=new bp("mat4"),em=(e="")=>wp(new $d(e,"string")),tm=e=>wp(new $d(e,"ArrayBuffer"));Zd("toColor",Fp),Zd("toFloat",Up),Zd("toInt",Op),Zd("toUint",zp),Zd("toBool",Lp),Zd("toVec2",Vp),Zd("toIVec2",Dp),Zd("toUVec2",kp),Zd("toBVec2",Gp),Zd("toVec3",Wp),Zd("toIVec3",jp),Zd("toUVec3",Hp),Zd("toBVec3",qp),Zd("toVec4",$p),Zd("toIVec4",Xp),Zd("toUVec4",Yp),Zd("toBVec4",Zp),Zd("toMat2",Jp),Zd("toMat3",Kp),Zd("toMat4",Qp);const sm=Ap(Ld),im=(e,t)=>wp(new Vd(wp(e),t)),rm=(e,t)=>wp(new Wd(wp(e),t));Zd("element",sm),Zd("convert",im);class nm extends zd{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.version=0,this.shared=t,this.order=s,this.isUniformGroup=!0}set needsUpdate(e){!0===e&&this.version++}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 om=e=>new nm(e),am=(e,t=0)=>new nm(e,!0,t),hm=am("frame"),um=am("render"),lm=om("object");class cm extends qd{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=lm}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const s=this.getSelf();return e=e.bind(s),super.onUpdate((t=>{const i=e(t,s);void 0!==i&&(this.value=i)}),t)}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const n=r.getInputType(e),o=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.label),a=e.getPropertyName(o);return void 0!==e.context.label&&delete e.context.label,e.format(a,s,t)}}const dm=(e,t)=>{const s=Tp(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return wp(new cm(i,s))};class pm extends zd{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}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 mm=(e,t)=>wp(new pm(e,t)),gm=(e,t)=>wp(new pm(e,t,!0)),fm=Np(pm,"vec4","DiffuseColor"),ym=Np(pm,"vec3","EmissiveColor"),xm=Np(pm,"float","Roughness"),bm=Np(pm,"float","Metalness"),vm=Np(pm,"float","Clearcoat"),Tm=Np(pm,"float","ClearcoatRoughness"),_m=Np(pm,"vec3","Sheen"),wm=Np(pm,"float","SheenRoughness"),Sm=Np(pm,"float","Iridescence"),Mm=Np(pm,"float","IridescenceIOR"),Am=Np(pm,"float","IridescenceThickness"),Nm=Np(pm,"float","AlphaT"),Cm=Np(pm,"float","Anisotropy"),Rm=Np(pm,"vec3","AnisotropyT"),Em=Np(pm,"vec3","AnisotropyB"),Bm=Np(pm,"color","SpecularColor"),Im=Np(pm,"float","SpecularF90"),Pm=Np(pm,"float","Shininess"),Fm=Np(pm,"vec4","Output"),Um=Np(pm,"float","dashSize"),Om=Np(pm,"float","gapSize"),zm=Np(pm,"float","pointWidth"),Lm=Np(pm,"float","IOR"),Vm=Np(pm,"float","Transmission"),Dm=Np(pm,"float","Thickness"),km=Np(pm,"float","AttenuationDistance"),Gm=Np(pm,"color","AttenuationColor"),Wm=Np(pm,"float","Dispersion");class jm extends Dd{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}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 s=e.getTypeLength(t.node.getNodeType(e));return Ud.join("").slice(0,s)!==t.components}return!1}generate(e,t){const{targetNode:s,sourceNode:i}=this,r=this.needsSplitAssign(e),n=s.getNodeType(e),o=s.context({assign:!0}).build(e),a=i.build(e,n),h=i.getNodeType(e),u=e.getDataFromNode(this);let l;if(!0===u.initialized)"void"!==t&&(l=o);else if(r){const i=e.getVarFromNode(this,null,n),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${a}`,this);const h=s.node.context({assign:!0}).build(e);for(let t=0;t{const i=s.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r))for(let e=0;e(t=t.length>1||t[0]&&!0===t[0].isNode?Mp(t):Sp(t[0]),wp(new qm(wp(e),t)));Zd("call",$m);class Xm extends Dd{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new Xm(e,t,s);for(let t=0;t>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"=="===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("<"===s||">"===s||"<="===s||">="===s){const s=t?e.getTypeLength(t):Math.max(e.getTypeLength(n),e.getTypeLength(o));return s>1?`bvec${s}`:"bool"}return"float"===n&&e.isMatrix(o)?o:e.isMatrix(n)&&e.isVector(o)?e.getVectorFromMatrix(n):e.isVector(n)&&e.isMatrix(o)?e.getVectorFromMatrix(o):e.getTypeLength(o)>e.getTypeLength(n)?o:n}generate(e,t){const s=this.op,i=this.aNode,r=this.bNode,n=this.getNodeType(e,t);let o=null,a=null;"void"!==n?(o=i.getNodeType(e),a=void 0!==r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s?e.isVector(o)?a=o:o!==a&&(o=a="float"):">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):e.isMatrix(o)&&e.isVector(a)?a=e.getVectorFromMatrix(o):o=e.isVector(o)&&e.isMatrix(a)?e.getVectorFromMatrix(a):a=n):o=a=n;const h=i.build(e,o),u=void 0!==r?r.build(e,a):null,l=e.getTypeLength(t),c=e.getFunctionOperator(s);return"void"!==t?"<"===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThan",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} < ${u} )`,n,t):"<="===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThanEqual",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} <= ${u} )`,n,t):">"===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThan",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} > ${u} )`,n,t):">="===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThanEqual",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} >= ${u} )`,n,t):"!"===s||"~"===s?e.format(`(${s}${h})`,o,t):c?e.format(`${c}( ${h}, ${u} )`,n,t):e.format(`( ${h} ${s} ${u} )`,n,t):"void"!==o?c?e.format(`${c}( ${h}, ${u} )`,n,t):e.format(`${h} ${s} ${u}`,n,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Ym=Ap(Xm,"+"),Zm=Ap(Xm,"-"),Jm=Ap(Xm,"*"),Km=Ap(Xm,"/"),Qm=Ap(Xm,"%"),eg=Ap(Xm,"=="),tg=Ap(Xm,"!="),sg=Ap(Xm,"<"),ig=Ap(Xm,">"),rg=Ap(Xm,"<="),ng=Ap(Xm,">="),og=Ap(Xm,"&&"),ag=Ap(Xm,"||"),hg=Ap(Xm,"!"),ug=Ap(Xm,"^^"),lg=Ap(Xm,"&"),cg=Ap(Xm,"~"),dg=Ap(Xm,"|"),pg=Ap(Xm,"^"),mg=Ap(Xm,"<<"),gg=Ap(Xm,">>");Zd("add",Ym),Zd("sub",Zm),Zd("mul",Jm),Zd("div",Km),Zd("modInt",Qm),Zd("equal",eg),Zd("notEqual",tg),Zd("lessThan",sg),Zd("greaterThan",ig),Zd("lessThanEqual",rg),Zd("greaterThanEqual",ng),Zd("and",og),Zd("or",ag),Zd("not",hg),Zd("xor",ug),Zd("bitAnd",lg),Zd("bitNot",cg),Zd("bitOr",dg),Zd("bitXor",pg),Zd("shiftLeft",mg),Zd("shiftRight",gg);const fg=(...e)=>(console.warn("TSL.OperatorNode: .remainder() has been renamed to .modInt()."),Qm(...e));Zd("remainder",fg);class yg extends Dd{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=s,this.cNode=i}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>o?t:n>o?s:o>r?i:t}getNodeType(e){const t=this.method;return t===yg.LENGTH||t===yg.DISTANCE||t===yg.DOT?"float":t===yg.CROSS?"vec3":t===yg.ALL?"bool":t===yg.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===yg.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,h=!0===e.renderer.isWebGLRenderer;if(s===yg.TRANSFORM_DIRECTION){let s=n,i=o;e.isMatrix(s.getNodeType(e))?i=$p(Wp(i),0):s=$p(Wp(s),0);const r=Jm(s,i).xyz;return Ug(r).build(e,t)}if(s===yg.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);if(s===yg.ONE_MINUS)return Zm(1,n).build(e,t);if(s===yg.RECIPROCAL)return Km(1,n).build(e,t);if(s===yg.DIFFERENCE)return Wg(Zm(n,o)).build(e,t);{const u=[];return s===yg.CROSS||s===yg.MOD?u.push(n.build(e,i),o.build(e,i)):h&&s===yg.STEP?u.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):h&&(s===yg.MIN||s===yg.MAX)||s===yg.MOD?u.push(n.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):s===yg.REFRACT?u.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===yg.MIX?u.push(n.build(e,r),o.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):(u.push(n.build(e,r)),null!==o&&u.push(o.build(e,r)),null!==a&&u.push(a.build(e,r))),e.format(`${e.getMethod(s,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}yg.ALL="all",yg.ANY="any",yg.EQUALS="equals",yg.RADIANS="radians",yg.DEGREES="degrees",yg.EXP="exp",yg.EXP2="exp2",yg.LOG="log",yg.LOG2="log2",yg.SQRT="sqrt",yg.INVERSE_SQRT="inversesqrt",yg.FLOOR="floor",yg.CEIL="ceil",yg.NORMALIZE="normalize",yg.FRACT="fract",yg.SIN="sin",yg.COS="cos",yg.TAN="tan",yg.ASIN="asin",yg.ACOS="acos",yg.ATAN="atan",yg.ABS="abs",yg.SIGN="sign",yg.LENGTH="length",yg.NEGATE="negate",yg.ONE_MINUS="oneMinus",yg.DFDX="dFdx",yg.DFDY="dFdy",yg.ROUND="round",yg.RECIPROCAL="reciprocal",yg.TRUNC="trunc",yg.FWIDTH="fwidth",yg.BITCAST="bitcast",yg.TRANSPOSE="transpose",yg.ATAN2="atan2",yg.MIN="min",yg.MAX="max",yg.MOD="mod",yg.STEP="step",yg.REFLECT="reflect",yg.DISTANCE="distance",yg.DIFFERENCE="difference",yg.DOT="dot",yg.CROSS="cross",yg.POW="pow",yg.TRANSFORM_DIRECTION="transformDirection",yg.MIX="mix",yg.CLAMP="clamp",yg.REFRACT="refract",yg.SMOOTHSTEP="smoothstep",yg.FACEFORWARD="faceforward";const xg=Up(1e-6),bg=Up(1e6),vg=Up(Math.PI),Tg=Up(2*Math.PI),_g=Ap(yg,yg.ALL),wg=Ap(yg,yg.ANY),Sg=Ap(yg,yg.EQUALS),Mg=Ap(yg,yg.RADIANS),Ag=Ap(yg,yg.DEGREES),Ng=Ap(yg,yg.EXP),Cg=Ap(yg,yg.EXP2),Rg=Ap(yg,yg.LOG),Eg=Ap(yg,yg.LOG2),Bg=Ap(yg,yg.SQRT),Ig=Ap(yg,yg.INVERSE_SQRT),Pg=Ap(yg,yg.FLOOR),Fg=Ap(yg,yg.CEIL),Ug=Ap(yg,yg.NORMALIZE),Og=Ap(yg,yg.FRACT),zg=Ap(yg,yg.SIN),Lg=Ap(yg,yg.COS),Vg=Ap(yg,yg.TAN),Dg=Ap(yg,yg.ASIN),kg=Ap(yg,yg.ACOS),Gg=Ap(yg,yg.ATAN),Wg=Ap(yg,yg.ABS),jg=Ap(yg,yg.SIGN),Hg=Ap(yg,yg.LENGTH),qg=Ap(yg,yg.NEGATE),$g=Ap(yg,yg.ONE_MINUS),Xg=Ap(yg,yg.DFDX),Yg=Ap(yg,yg.DFDY),Zg=Ap(yg,yg.ROUND),Jg=Ap(yg,yg.RECIPROCAL),Kg=Ap(yg,yg.TRUNC),Qg=Ap(yg,yg.FWIDTH),ef=Ap(yg,yg.BITCAST),tf=Ap(yg,yg.TRANSPOSE),sf=Ap(yg,yg.ATAN2),rf=Ap(yg,yg.MIN),nf=Ap(yg,yg.MAX),of=Ap(yg,yg.MOD),af=Ap(yg,yg.STEP),hf=Ap(yg,yg.REFLECT),uf=Ap(yg,yg.DISTANCE),lf=Ap(yg,yg.DIFFERENCE),cf=Ap(yg,yg.DOT),df=Ap(yg,yg.CROSS),pf=Ap(yg,yg.POW),mf=Ap(yg,yg.POW,2),gf=Ap(yg,yg.POW,3),ff=Ap(yg,yg.POW,4),yf=Ap(yg,yg.TRANSFORM_DIRECTION),xf=e=>Jm(jg(e),pf(Wg(e),1/3)),bf=e=>cf(e,e),vf=Ap(yg,yg.MIX),Tf=(e,t=0,s=1)=>wp(new yg(yg.CLAMP,wp(e),wp(t),wp(s))),_f=e=>Tf(e),wf=Ap(yg,yg.REFRACT),Sf=Ap(yg,yg.SMOOTHSTEP),Mf=Ap(yg,yg.FACEFORWARD),Af=Cp((([e])=>{const t=cf(e.xy,Vp(12.9898,78.233)),s=of(t,vg);return Og(zg(s).mul(43758.5453))})),Nf=(e,t,s)=>vf(t,s,e),Cf=(e,t,s)=>Sf(t,s,e);Zd("all",_g),Zd("any",wg),Zd("equals",Sg),Zd("radians",Mg),Zd("degrees",Ag),Zd("exp",Ng),Zd("exp2",Cg),Zd("log",Rg),Zd("log2",Eg),Zd("sqrt",Bg),Zd("inverseSqrt",Ig),Zd("floor",Pg),Zd("ceil",Fg),Zd("normalize",Ug),Zd("fract",Og),Zd("sin",zg),Zd("cos",Lg),Zd("tan",Vg),Zd("asin",Dg),Zd("acos",kg),Zd("atan",Gg),Zd("abs",Wg),Zd("sign",jg),Zd("length",Hg),Zd("lengthSq",bf),Zd("negate",qg),Zd("oneMinus",$g),Zd("dFdx",Xg),Zd("dFdy",Yg),Zd("round",Zg),Zd("reciprocal",Jg),Zd("trunc",Kg),Zd("fwidth",Qg),Zd("atan2",sf),Zd("min",rf),Zd("max",nf),Zd("mod",of),Zd("step",af),Zd("reflect",hf),Zd("distance",uf),Zd("dot",cf),Zd("cross",df),Zd("pow",pf),Zd("pow2",mf),Zd("pow3",gf),Zd("pow4",ff),Zd("transformDirection",yf),Zd("mix",Nf),Zd("clamp",Tf),Zd("refract",wf),Zd("smoothstep",Cf),Zd("faceForward",Mf),Zd("difference",lf),Zd("saturate",_f),Zd("cbrt",xf),Zd("transpose",tf),Zd("rand",Af);class Rf extends zd{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const t=this.ifNode.getNodeType(e);if(null!==this.elseNode){const s=this.elseNode.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(t))return s}return t}setup(e){const t=this.condNode.cache(),s=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=s.context({nodeBlock:s}),n.elseNode=i?i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:n,elseNode:o}=e.getNodeProperties(this),a="void"!==t,h=a?mm(s).build(e):"";i.nodeProperty=h;const u=r.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let l=n.build(e,s);if(l&&(l=a?h+" = "+l+";":"return "+l+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+l+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=o.build(e,s);t&&(t=a?h+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(h,s,t)}}const Ef=Ap(Rf);Zd("select",Ef);const Bf=(...e)=>(console.warn("TSL.ConditionalNode: cond() has been renamed to select()."),Ef(...e));Zd("cond",Bf);class If extends zd{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)}analyze(e){this.node.build(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e);return e.setContext(t),s}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(s),i}}const Pf=Ap(If),Ff=(e,t)=>Pf(e,{label:t});Zd("context",Pf),Zd("label",Ff);class Uf extends zd{static get type(){return"VarNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s}=this,i=e.getVarFromNode(this,s,e.getVectorType(this.getNodeType(e))),r=e.getPropertyName(i),n=t.build(e,i.type);return e.addLineFlowCode(`${r} = ${n}`,this),r}}const Of=Ap(Uf);Zd("toVar",((...e)=>Of(...e).append()));const zf=e=>(console.warn('TSL: "temp" is deprecated. Use ".toVar()" instead.'),Of(e));Zd("temp",zf);class Lf extends zd{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(void 0===s){const i=this.name,r=this.getNodeType(e);t.varying=s=e.getVaryingFromNode(this,i,r),t.node=this.node}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e)}analyze(e){return this.setupVarying(e),this.node.analyze(e)}generate(e){const t=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===t.propertyName){const i=this.getNodeType(e),r=e.getPropertyName(s,Rd.VERTEX);e.flowNodeFromShaderStage(Rd.VERTEX,this.node,i,r),t.propertyName=r}return e.getPropertyName(s)}}const Vf=Ap(Lf);Zd("varying",Vf);const Df="WorkingColorSpace",kf="OutputColorSpace";function Gf(e){let t=null;return e===Jt?t="Linear":e===Zt&&(t="sRGB"),t}function Wf(e,t){return Gf(e)+"To"+Gf(t)}class jf extends Dd{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}getColorSpace(e,t){return t===Df?ii.workingColorSpace:t===kf?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{renderer:t}=e,{colorNode:s}=this,i=this.getColorSpace(e,this.source),r=this.getColorSpace(e,this.target);if(i===r)return s;const n=Wf(i,r);let o=null;const a=t.nodes.library.getColorSpaceFunction(n);return null!==a?o=$p(a(s.rgb),s.a):(console.error("ColorSpaceNode: Unsupported Color Space configuration.",n),o=s),o}}const Hf=e=>wp(new jf(wp(e),Df,kf)),qf=e=>wp(new jf(wp(e),kf,Df)),$f=(e,t)=>wp(new jf(wp(e),Df,t)),Xf=(e,t)=>wp(new jf(wp(e),t,Df));Zd("toOutputColorSpace",Hf),Zd("toWorkingColorSpace",qf),Zd("workingToColorSpace",$f),Zd("colorSpaceToWorking",Xf);let Yf=class extends Ld{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),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class Zf extends zd{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=Ed.OBJECT}setGroup(e){return this.group=e,this}element(e){return wp(new Yf(this,wp(e)))}setNodeType(e){const t=dm(null,e).getSelf();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 s=e[t[0]];for(let e=1;ewp(new Jf(e,t,s));class Qf extends Dd{static get type(){return"ToneMappingNode"}constructor(e,t=ty,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}getCacheKey(){return Td(super.getCacheKey(),this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,s=this.toneMapping;if(0===s)return t;let i=null;const r=e.renderer.nodes.library.getToneMappingFunction(s);return null!==r?i=$p(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const ey=(e,t,s)=>wp(new Qf(e,wp(t),wp(s))),ty=Kf("toneMappingExposure","float");Zd("toneMapping",((e,t,s)=>ey(t,s,e)));class sy extends qd{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=Ss,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),s=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,n=this.bufferOffset,o=!0===s.isInterleavedBuffer?s:new Qn(s,r),a=new to(o,i,n);o.setUsage(this.usage),this.attribute=a,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=Vf(this).build(e,t)}return r}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 iy=(e,t,s,i)=>wp(new sy(e,t,s,i)),ry=(e,t,s,i)=>iy(e,t,s,i).setUsage(Ms),ny=(e,t,s,i)=>iy(e,t,s,i).setInstanced(!0),oy=(e,t,s,i)=>ry(e,t,s,i).setInstanced(!0);Zd("toAttribute",(e=>iy(e.value)));class ay extends zd{static get type(){return"ComputeNode"}constructor(e,t,s=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=s,this.dispatchCount=0,this.version=1,this.updateBeforeType=Ed.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let s=t[0];for(let e=1;ewp(new ay(wp(e),t,s));Zd("compute",hy);class uy extends zd{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){return this.node.getNodeType(e)}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(s),r}}const ly=(e,...t)=>wp(new uy(wp(e),...t));Zd("cache",ly);class cy extends zd{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 dy=Ap(cy);Zd("bypass",dy);class py extends zd{static get type(){return"RemapNode"}constructor(e,t,s,i=Up(0),r=Up(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:r,doClamp:n}=this;let o=e.sub(t).div(s.sub(t));return!0===n&&(o=o.clamp()),o.mul(r.sub(i)).add(i)}}const my=Ap(py,null,null,{doClamp:!1}),gy=Ap(py);Zd("remap",my),Zd("remapClamp",gy);class fy extends zd{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if("void"!==s)return e.format(`( ${i} )`,s,t);e.addLineFlowCode(i,this)}}const yy=Ap(fy),xy=e=>(e?Ef(e,yy("discard")):yy("discard")).append(),by=()=>yy("return").append();Zd("discard",xy);class vy extends Dd{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutput=!0}setup({context:e}){let t=this.colorNode||e.color;const s=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||Yt;return 0!==s&&(t=t.toneMapping(s)),i!==Yt&&i!==ii.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const Ty=(e,t=null,s=null)=>wp(new vy(wp(e),t,s));function _y(e){console.warn("THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)}Zd("renderOutput",Ty);class wy extends zd{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 s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),n=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(n.name,r,s);return Vf(this).build(e,s)}return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}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 Sy=(e,t)=>wp(new wy(e,t)),My=e=>Sy("uv"+(e>0?e:""),"vec2");class Ay extends zd{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const Ny=Ap(Ay);class Cy extends cm{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Ed.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const Ry=Ap(Cy);class Ey extends cm{static get type(){return"TextureNode"}constructor(e,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=Ed.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===Be?"uvec4":this.value.type===Ee?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return My(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=dm(this.value.matrix)),this._matrixUniform.mul(Wp(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Ed.FRAME:Ed.NONE,this}setupUV(e,t){const s=this.value;return!e.isFlipY()||!0!==s.isRenderTargetTexture&&!0!==s.isFramebufferTexture&&!0!==s.isDepthTexture||(t=this.sampler?t.flipY():t.setY(Op(Ny(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this)),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}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,s,i,r,n,o,a){const h=this.value;let u;return u=i?e.generateTextureLevel(h,t,s,i,n):r?e.generateTextureBias(h,t,s,r,n):a?e.generateTextureGrad(h,t,s,a,n):o?e.generateTextureCompare(h,t,s,o,n):!1===this.sampler?e.generateTextureLoad(h,t,s,n):e.generateTexture(h,t,s,n),u}generate(e,t){const s=e.getNodeProperties(this),i=this.value;if(!i||!0!==i.isTexture)throw new Error("TextureNode: Need a three.js texture.");const r=super.generate(e,"property");if("sampler"===t)return r+"_sampler";if(e.isReference(t))return r;{const n=e.getDataFromNode(this);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:i,biasNode:a,compareNode:h,depthNode:u,gradNode:l}=s,c=this.generateUV(e,t),d=i?i.build(e,"float"):null,p=a?a.build(e,"float"):null,m=u?u.build(e,"int"):null,g=h?h.build(e,"float"):null,f=l?[l[0].build(e,"vec2"),l[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);o=e.getPropertyName(y);const x=this.generateSnippet(e,r,c,d,p,m,g,f);e.addLineFlowCode(`${o} = ${x}`,this),n.snippet=x,n.propertyName=o}let a=o;const h=this.getNodeType(e);return e.needsToWorkingColorSpace(i)&&(a=Xf(yy(a,h),i.colorSpace).setup(e).build(e,h)),e.format(a,h,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){const t=this.clone();return t.uvNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}blur(e){const t=this.clone();return t.biasNode=wp(e).mul(Ry(t)),t.referenceNode=this.getSelf(),wp(t)}level(e){const t=this.clone();return t.levelNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}size(e){return Ny(this,e)}bias(e){const t=this.clone();return t.biasNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}compare(e){const t=this.clone();return t.compareNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}grad(e,t){const s=this.clone();return s.gradNode=[wp(e),wp(t)],s.referenceNode=this.getSelf(),wp(s)}depth(e){const t=this.clone();return t.depthNode=wp(e),t.referenceNode=this.getSelf(),wp(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}}const By=Ap(Ey),Iy=(...e)=>By(...e).setSampler(!1),Py=e=>(!0===e.isNode?e:By(e)).convert("sampler"),Fy=dm("float").label("cameraNear").setGroup(um).onRenderUpdate((({camera:e})=>e.near)),Uy=dm("float").label("cameraFar").setGroup(um).onRenderUpdate((({camera:e})=>e.far)),Oy=dm("mat4").label("cameraProjectionMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.projectionMatrix)),zy=dm("mat4").label("cameraProjectionMatrixInverse").setGroup(um).onRenderUpdate((({camera:e})=>e.projectionMatrixInverse)),Ly=dm("mat4").label("cameraViewMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.matrixWorldInverse)),Vy=dm("mat4").label("cameraWorldMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.matrixWorld)),Dy=dm("mat3").label("cameraNormalMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.normalMatrix)),ky=dm(new Ai).label("cameraPosition").setGroup(um).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld)));class Gy extends zd{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Ed.OBJECT,this._uniformNode=new cm(null)}getNodeType(){const e=this.scope;return e===Gy.WORLD_MATRIX?"mat4":e===Gy.POSITION||e===Gy.VIEW_POSITION||e===Gy.DIRECTION||e===Gy.SCALE?"vec3":void 0}update(e){const t=this.object3d,s=this._uniformNode,i=this.scope;if(i===Gy.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Gy.POSITION)s.value=s.value||new Ai,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Gy.SCALE)s.value=s.value||new Ai,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Gy.DIRECTION)s.value=s.value||new Ai,t.getWorldDirection(s.value);else if(i===Gy.VIEW_POSITION){const i=e.camera;s.value=s.value||new Ai,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}}generate(e){const t=this.scope;return t===Gy.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t!==Gy.POSITION&&t!==Gy.VIEW_POSITION&&t!==Gy.DIRECTION&&t!==Gy.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Gy.WORLD_MATRIX="worldMatrix",Gy.POSITION="position",Gy.SCALE="scale",Gy.VIEW_POSITION="viewPosition",Gy.DIRECTION="direction";const Wy=Ap(Gy,Gy.DIRECTION),jy=Ap(Gy,Gy.WORLD_MATRIX),Hy=Ap(Gy,Gy.POSITION),qy=Ap(Gy,Gy.SCALE),$y=Ap(Gy,Gy.VIEW_POSITION);class Xy extends Gy{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Yy=Np(Xy,Xy.DIRECTION),Zy=Np(Xy,Xy.WORLD_MATRIX),Jy=Np(Xy,Xy.POSITION),Ky=Np(Xy,Xy.SCALE),Qy=Np(Xy,Xy.VIEW_POSITION),ex=dm(new Zs).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),tx=dm(new sr).onObjectUpdate((({object:e},t)=>t.value.copy(e.matrixWorld).invert())),sx=Ly.mul(Zy).toVar("modelViewMatrix"),ix=Cp((e=>(e.context.isHighPrecisionModelViewMatrix=!0,dm("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highPrecisionModelViewMatrix"),rx=Cp((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return dm("mat3").onObjectUpdate((({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highPrecisionModelNormalMatrix"),nx=Sy("position","vec3"),ox=nx.varying("positionLocal"),ax=nx.varying("positionPrevious"),hx=Zy.mul(ox).xyz.varying("v_positionWorld"),ux=ox.transformDirection(Zy).varying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),lx=sx.mul(ox).xyz.varying("v_positionView"),cx=lx.negate().varying("v_positionViewDirection").normalize().toVar("positionViewDirection");class dx extends zd{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Us&&s.side===d?"false":e.getFrontFacing()}}const px=Np(dx),mx=Up(px).mul(2).sub(1),gx=Sy("normal","vec3"),fx=Cp((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('TSL.NormalNode: Vertex attribute "normal" not found on geometry.'),Wp(0,1,0)):gx),"vec3").once()().toVar("normalLocal"),yx=lx.dFdx().cross(lx.dFdy()).normalize().toVar("normalFlat"),xx=Cp((e=>{let t;return t=!0===e.material.flatShading?yx:Vf(Sx(fx),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),bx=Vf(xx.transformDirection(Ly),"v_normalWorld").normalize().toVar("normalWorld"),vx=Cp((e=>e.context.setupNormal()),"vec3").once()().mul(mx).toVar("transformedNormalView"),Tx=vx.transformDirection(Ly).toVar("transformedNormalWorld"),_x=Cp((e=>e.context.setupClearcoatNormal()),"vec3").once()().mul(mx).toVar("transformedClearcoatNormalView"),wx=Cp((([e,t=Zy])=>{const s=Kp(t),i=e.div(Wp(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz})),Sx=Cp((([e],t)=>{const s=t.renderer.nodes.modelNormalViewMatrix;if(null!==s)return s.transformDirection(e);const i=ex.mul(e);return Ly.transformDirection(i)})),Mx=dm(0).onReference((({material:e})=>e)).onRenderUpdate((({material:e})=>e.refractionRatio)),Ax=cx.negate().reflect(vx),Nx=cx.negate().refract(vx,Mx),Cx=Ax.transformDirection(Ly).toVar("reflectVector"),Rx=Nx.transformDirection(Ly).toVar("reflectVector");class Ex extends Ey{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===he?Cx:e.mapping===ue?Rx:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),Wp(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==Os&&s.isRenderTargetTexture?t:Wp(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const Bx=Ap(Ex);class Ix extends cm{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Px=(e,t,s)=>wp(new Ix(e,t,s));class Fx extends Ld{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType();return e.format(t,"vec4",s)}}class Ux extends Ix{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null,"vec4"),this.array=e,this.elementType=t,this._elementType=null,this._elementLength=0,this.updateType=Ed.RENDER,this.isArrayBufferNode=!0}getElementType(){return this.elementType||this._elementType}getElementLength(){return this._elementLength}update(){const{array:e,value:t}=this,s=this.getElementLength(),i=this.getElementType();if(1===s)for(let s=0;swp(new Ux(e,t)),zx=(e,t)=>(console.warn("TSL.UniformArrayNode: uniforms() has been renamed to uniformArray()."),wp(new Ux(e,t)));class Lx extends Ld{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),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class Vx extends zd{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=Ed.OBJECT}element(e){return wp(new Lx(this,wp(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Px(null,e,this.count):Array.isArray(this.getValueFromReference())?Ox(null,e):"texture"===e?By(null):"cubeTexture"===e?Bx(null):dm(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;ewp(new Vx(e,t,s)),kx=(e,t,s,i)=>wp(new Vx(e,t,i,s));class Gx extends Vx{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Wx=(e,t,s)=>wp(new Gx(e,t,s)),jx=Cp((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Sy("tangent","vec4"))))(),Hx=jx.xyz.toVar("tangentLocal"),qx=sx.mul($p(Hx,0)).xyz.varying("v_tangentView").normalize().toVar("tangentView"),$x=qx.transformDirection(Ly).varying("v_tangentWorld").normalize().toVar("tangentWorld"),Xx=qx.toVar("transformedTangentView"),Yx=Xx.transformDirection(Ly).normalize().toVar("transformedTangentWorld"),Zx=e=>e.mul(jx.w).xyz,Jx=Vf(Zx(gx.cross(jx)),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Kx=Vf(Zx(fx.cross(Hx)),"v_bitangentLocal").normalize().toVar("bitangentLocal"),Qx=Vf(Zx(xx.cross(qx)),"v_bitangentView").normalize().toVar("bitangentView"),eb=Vf(Zx(bx.cross($x)),"v_bitangentWorld").normalize().toVar("bitangentWorld"),tb=Zx(vx.cross(Xx)).normalize().toVar("transformedBitangentView"),sb=tb.transformDirection(Ly).normalize().toVar("transformedBitangentWorld"),ib=Kp(qx,Qx,xx),rb=cx.mul(ib),nb=(e,t)=>e.sub(rb.mul(t)),ob=(()=>{let e=Em.cross(cx);return e=e.cross(Em).normalize(),e=vf(e,vx,Cm.mul(xm.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),ab=Cp((e=>{const{eye_pos:t,surf_norm:s,mapN:i,uv:r}=e,n=t.dFdx(),o=t.dFdy(),a=r.dFdx(),h=r.dFdy(),u=s,l=o.cross(u),c=u.cross(n),d=l.mul(a.x).add(c.mul(h.x)),p=l.mul(a.y).add(c.mul(h.y)),m=d.dot(d).max(p.dot(p)),g=mx.mul(m.inverseSqrt());return Ym(d.mul(i.x,g),p.mul(i.y,g),u.mul(i.z)).normalize()}));class hb extends Dd{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:s}=this;let i=this.node.mul(2).sub(1);null!==s&&(i=Wp(i.xy.mul(s),i.z));let r=null;if(1===t)r=Sx(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?ib.mul(i).normalize():ab({eye_pos:lx,surf_norm:xx,mapN:i,uv:My()})}return r}}const ub=Ap(hb),lb=Cp((({textureNode:e,bumpScale:t})=>{const s=t=>e.cache().context({getUV:e=>t(e.uvNode||My()),forceUVContext:!0}),i=Up(s((e=>e)));return Vp(Up(s((e=>e.add(e.dFdx())))).sub(i),Up(s((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),cb=Cp((e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,o=t.dFdy().normalize().cross(n),a=n.cross(r),h=r.dot(o).mul(mx),u=h.sign().mul(i.x.mul(o).add(i.y.mul(a)));return h.abs().mul(s).sub(u).normalize()}));class db extends Dd{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=lb({textureNode:this.textureNode,bumpScale:e});return cb({surf_pos:lx,surf_norm:xx,dHdxy:t})}}const pb=Ap(db),mb=new Map;class gb extends zd{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=mb.get(e);return void 0===s&&(s=Wx(e,t),mb.set(e,s)),s}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,s=this.scope;let i=null;if(s===gb.COLOR){const e=void 0!==t.color?this.getColor(s):Wp();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===gb.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===gb.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Up(1);else if(s===gb.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularMap?e.mul(this.getTexture(s).a):e}else if(s===gb.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===gb.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===gb.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===gb.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(s)):r}else if(s===gb.NORMAL)t.normalMap?(i=ub(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?pb(this.getTexture("bump").r,this.getFloat("bumpScale")):xx;else if(s===gb.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===gb.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===gb.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?ub(this.getTexture(s),this.getCache(s+"Scale","vec2")):xx;else if(s===gb.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===gb.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(.07,1)}else if(s===gb.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=Jp(Qb.x,Qb.y,Qb.y.negate(),Qb.x).mul(e.rg.mul(2).sub(Vp(1)).normalize().mul(e.b))}else i=Qb;else if(s===gb.IRIDESCENCE_THICKNESS){const e=Dx("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Dx("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===gb.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===gb.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===gb.IOR)i=this.getFloat(s);else if(s===gb.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===gb.AO_MAP)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}gb.ALPHA_TEST="alphaTest",gb.COLOR="color",gb.OPACITY="opacity",gb.SHININESS="shininess",gb.SPECULAR="specular",gb.SPECULAR_STRENGTH="specularStrength",gb.SPECULAR_INTENSITY="specularIntensity",gb.SPECULAR_COLOR="specularColor",gb.REFLECTIVITY="reflectivity",gb.ROUGHNESS="roughness",gb.METALNESS="metalness",gb.NORMAL="normal",gb.CLEARCOAT="clearcoat",gb.CLEARCOAT_ROUGHNESS="clearcoatRoughness",gb.CLEARCOAT_NORMAL="clearcoatNormal",gb.EMISSIVE="emissive",gb.ROTATION="rotation",gb.SHEEN="sheen",gb.SHEEN_ROUGHNESS="sheenRoughness",gb.ANISOTROPY="anisotropy",gb.IRIDESCENCE="iridescence",gb.IRIDESCENCE_IOR="iridescenceIOR",gb.IRIDESCENCE_THICKNESS="iridescenceThickness",gb.IOR="ior",gb.TRANSMISSION="transmission",gb.THICKNESS="thickness",gb.ATTENUATION_DISTANCE="attenuationDistance",gb.ATTENUATION_COLOR="attenuationColor",gb.LINE_SCALE="scale",gb.LINE_DASH_SIZE="dashSize",gb.LINE_GAP_SIZE="gapSize",gb.LINE_WIDTH="linewidth",gb.LINE_DASH_OFFSET="dashOffset",gb.POINT_WIDTH="pointWidth",gb.DISPERSION="dispersion",gb.LIGHT_MAP="light",gb.AO_MAP="ao";const fb=Np(gb,gb.ALPHA_TEST),yb=Np(gb,gb.COLOR),xb=Np(gb,gb.SHININESS),bb=Np(gb,gb.EMISSIVE),vb=Np(gb,gb.OPACITY),Tb=Np(gb,gb.SPECULAR),_b=Np(gb,gb.SPECULAR_INTENSITY),wb=Np(gb,gb.SPECULAR_COLOR),Sb=Np(gb,gb.SPECULAR_STRENGTH),Mb=Np(gb,gb.REFLECTIVITY),Ab=Np(gb,gb.ROUGHNESS),Nb=Np(gb,gb.METALNESS),Cb=Np(gb,gb.NORMAL).context({getUV:null}),Rb=Np(gb,gb.CLEARCOAT),Eb=Np(gb,gb.CLEARCOAT_ROUGHNESS),Bb=Np(gb,gb.CLEARCOAT_NORMAL).context({getUV:null}),Ib=Np(gb,gb.ROTATION),Pb=Np(gb,gb.SHEEN),Fb=Np(gb,gb.SHEEN_ROUGHNESS),Ub=Np(gb,gb.ANISOTROPY),Ob=Np(gb,gb.IRIDESCENCE),zb=Np(gb,gb.IRIDESCENCE_IOR),Lb=Np(gb,gb.IRIDESCENCE_THICKNESS),Vb=Np(gb,gb.TRANSMISSION),Db=Np(gb,gb.THICKNESS),kb=Np(gb,gb.IOR),Gb=Np(gb,gb.ATTENUATION_DISTANCE),Wb=Np(gb,gb.ATTENUATION_COLOR),jb=Np(gb,gb.LINE_SCALE),Hb=Np(gb,gb.LINE_DASH_SIZE),qb=Np(gb,gb.LINE_GAP_SIZE),$b=Np(gb,gb.LINE_WIDTH),Xb=Np(gb,gb.LINE_DASH_OFFSET),Yb=Np(gb,gb.POINT_WIDTH),Zb=Np(gb,gb.DISPERSION),Jb=Np(gb,gb.LIGHT_MAP),Kb=Np(gb,gb.AO_MAP),Qb=dm(new Ys).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))}));class ev extends Dd{static get type(){return"ModelViewProjectionNode"}constructor(e=null){super("vec4"),this.positionNode=e}setup(e){if("fragment"===e.shaderStage)return Vf(e.context.mvp);const t=this.positionNode||ox,s=e.renderer.nodes.modelViewMatrix||sx;return Oy.mul(s).mul(t)}}const tv=Ap(ev);class sv extends zd{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isInstanceIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i,r;if(s===sv.VERTEX)i=e.getVertexIndex();else if(s===sv.INSTANCE)i=e.getInstanceIndex();else if(s===sv.DRAW)i=e.getDrawIndex();else if(s===sv.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===sv.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==sv.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Vf(this).build(e,t)}return r}}sv.VERTEX="vertex",sv.INSTANCE="instance",sv.SUBGROUP="subgroup",sv.INVOCATION_LOCAL="invocationLocal",sv.INVOCATION_SUBGROUP="invocationSubgroup",sv.DRAW="draw";const iv=Np(sv,sv.VERTEX),rv=Np(sv,sv.INSTANCE),nv=Np(sv,sv.SUBGROUP),ov=Np(sv,sv.INVOCATION_SUBGROUP),av=Np(sv,sv.INVOCATION_LOCAL),hv=Np(sv,sv.DRAW);class uv extends zd{static get type(){return"InstanceNode"}constructor(e){super("void"),this.instanceMesh=e,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Ed.FRAME,this.buffer=null,this.bufferColor=null}setup(e){let t=this.instanceMatrixNode,s=this.instanceColorNode;const i=this.instanceMesh;if(null===t){const e=i.instanceMatrix;if(i.count<=1e3)t=Px(e.array,"mat4",Math.max(i.count,1)).element(rv);else{const s=new _c(e.array,16,1);this.buffer=s;const i=e.usage===Ms?oy:ny,r=[i(s,"vec4",16,0),i(s,"vec4",16,4),i(s,"vec4",16,8),i(s,"vec4",16,12)];t=Qp(...r)}this.instanceMatrixNode=t}const r=i.instanceColor;if(r&&null===s){const e=new zo(r.array,3),t=r.usage===Ms?oy:ny;this.bufferColor=e,s=Wp(t(e,"vec3",3,0)),this.instanceColorNode=s}const n=t.mul(ox).xyz;if(ox.assign(n),e.hasGeometryAttribute("normal")){const e=wx(fx,t);fx.assign(e)}null!==this.instanceColorNode&&gm("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMesh.instanceMatrix.usage!==Ms&&null!=this.buffer&&this.instanceMesh.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMesh.instanceMatrix.version),this.instanceMesh.instanceColor&&this.instanceMesh.instanceColor.usage!==Ms&&null!=this.bufferColor&&this.instanceMesh.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceMesh.instanceColor.version)}}const lv=Ap(uv);class cv extends zd{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=rv:this.batchingIdNode=hv);const t=Cp((([e])=>{const t=Ny(Iy(this.batchMesh._indirectTexture),0),s=Op(e).modInt(Op(t)),i=Op(e).div(Op(t));return Iy(this.batchMesh._indirectTexture,Dp(s,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(Op(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=Ny(Iy(i),0),n=Up(s).mul(4).toInt().toVar(),o=n.modInt(r),a=n.div(Op(r)),h=Qp(Iy(i,Dp(o,a)),Iy(i,Dp(o.add(1),a)),Iy(i,Dp(o.add(2),a)),Iy(i,Dp(o.add(3),a))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Cp((([e])=>{const t=Ny(Iy(u),0).x,s=e,i=s.modInt(t),r=s.div(t);return Iy(u,Dp(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);gm("vec3","vBatchColor").assign(t)}const l=Kp(h);ox.assign(h.mul(ox));const c=fx.div(Wp(l[0].dot(l[0]),l[1].dot(l[1]),l[2].dot(l[2]))),d=l.mul(c).xyz;fx.assign(d),e.hasGeometryAttribute("tangent")&&Hx.mulAssign(l)}}const dv=Ap(cv),pv=new WeakMap;class mv extends zd{static get type(){return"SkinningNode"}constructor(e,t=!1){let s,i,r;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=Ed.OBJECT,this.skinIndexNode=Sy("skinIndex","uvec4"),this.skinWeightNode=Sy("skinWeight","vec4"),t?(s=Dx("bindMatrix","mat4"),i=Dx("bindMatrixInverse","mat4"),r=kx("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(s=dm(e.bindMatrix,"mat4"),i=dm(e.bindMatrixInverse,"mat4"),r=Px(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=s,this.bindMatrixInverseNode=i,this.boneMatricesNode=r,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=ox){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),u=e.element(s.w),l=r.mul(t),c=Ym(o.mul(i.x).mul(l),a.mul(i.y).mul(l),h.mul(i.z).mul(l),u.mul(i.w).mul(l));return n.mul(c).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=fx){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),u=e.element(s.w);let l=Ym(i.x.mul(o),i.y.mul(a),i.z.mul(h),i.w.mul(u));return l=n.mul(l).mul(r),l.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=kx("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,ax)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")}setup(e){this.needsPreviousBoneMatrices(e)&&ax.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(ox.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();fx.assign(t),e.hasGeometryAttribute("tangent")&&Hx.assign(t)}}generate(e,t){if("void"!==t)return ox.build(e,t)}update(e){const t=(this.useReference?e.object:this.skinnedMesh).skeleton;pv.get(t)!==e.frameId&&(pv.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const gv=e=>wp(new mv(e)),fv=e=>wp(new mv(e,!0));class yv extends zd{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt()+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;eNumber(n)?">=":"<"));const l={start:r,end:n,condition:h},c=l.start,d=l.end;let p="",m="",g="";u||(u="int"===a||"uint"===a?h.includes("<")?"++":"--":h.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(a,o)+" = "+c,m+=o+" "+h+" "+d,g+=o+" "+u;const f=`for ( ${p}; ${m}; ${g} )`;e.addFlowCode((0===t?"\n":"")+e.tab+f+" {\n\n").addFlowTab()}const r=i.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,s=this.params.length-1;twp(new yv(Mp(e,"int"))).append(),bv=()=>yy("continue").append(),vv=()=>yy("break").append(),Tv=(...e)=>(console.warn("TSL.LoopNode: loop() has been renamed to Loop()."),xv(...e)),_v=new WeakMap,wv=new xi,Sv=Cp((({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=Op(iv).mul(s).add(n),a=o.div(i),h=o.sub(a.mul(i));return Iy(e,Dp(h,a)).depth(r).mul(t)}));class Mv extends zd{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=dm(1),this.updateType=Ed.OBJECT}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,n=void 0!==r?r.length:0,{texture:o,stride:a,size:h}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,n=void 0!==r?r.length:0;let o=_v.get(e);if(void 0===o||o.count!==n){void 0!==o&&o.texture.dispose();const a=e.morphAttributes.position||[],h=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let l=0;!0===t&&(l=1),!0===s&&(l=2),!0===i&&(l=3);let c=e.attributes.position.count*l,d=1;const p=4096;c>p&&(d=Math.ceil(c/p),c=p);const m=new Float32Array(c*d*4*n),g=new Ti(m,c,d,n);g.type=Ie,g.needsUpdate=!0;const f=4*l;for(let x=0;x{const t=Up(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Iy(this.mesh.morphTexture,Dp(Op(e).add(1),Op(rv))).r):t.assign(Dx("morphTargetInfluences","float").element(e).toVar()),!0===s&&ox.addAssign(Sv({bufferMap:o,influence:t,stride:a,width:u,depth:e,offset:Op(0)})),!0===i&&fx.addAssign(Sv({bufferMap:o,influence:t,stride:a,width:u,depth:e,offset:Op(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 Av=Ap(Mv),Nv=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},Cv=new WeakMap;class Rv extends zd{static get type(){return"LightsNode"}constructor(e=[]){super("vec3"),this.totalDiffuseNode=Wp().toVar("totalDiffuse"),this.totalSpecularNode=Wp().toVar("totalSpecular"),this.outgoingLightNode=Wp().toVar("outgoingLight"),this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this.global=!0}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getDataFromNode(this);for(const s of t.nodes)s.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=(e=>e.sort(((e,t)=>e.id-t.id)))(this._lights),r=e.renderer.nodes.library;for(const e of i)if(e.isNode)t.push(wp(e));else{let i=null;if(null!==s&&(i=Nv(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;Cv.has(e)?i=Cv.get(e):(i=new s(e),Cv.set(e,i)),t.push(i)}}this._lightNodes=t}setup(e){null===this._lightNodes&&this.setupLightsNode(e);const t=e.context,s=t.lightingModel;let i=this.outgoingLightNode;if(s){const{_lightNodes:r,totalDiffuseNode:n,totalSpecularNode:o}=this;t.outgoingLight=i;const a=e.addStack();e.getDataFromNode(this).nodes=a.nodes,s.start(t,a,e);for(const t of r)t.build(e);s.indirect(t,a,e);const{backdrop:h,backdropAlpha:u}=t,{directDiffuse:l,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=t.reflectedLight;let m=l.add(d);null!==h&&(m=Wp(null!==u?u.mix(m,h):h),t.material.transparent=!0),n.assign(m),o.assign(c.add(p)),i.assign(n.add(o)),s.finish(t,a,e),i=i.bypass(e.removeStack())}return i}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}}const Ev=Ap(Rv);class Bv extends zd{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}generate(){console.warn("Abstract function.")}}class Iv extends Bv{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Pv extends If{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:Wp().toVar("directDiffuse"),directSpecular:Wp().toVar("directSpecular"),indirectDiffuse:Wp().toVar("indirectDiffuse"),indirectSpecular:Wp().toVar("indirectSpecular")};return{radiance:Wp().toVar("radiance"),irradiance:Wp().toVar("irradiance"),iblIrradiance:Wp().toVar("iblIrradiance"),ambientOcclusion:Up(1).toVar("ambientOcclusion"),reflectedLight:s,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 Fv=Ap(Pv);class Uv extends Bv{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Ov,zv;class Lv extends zd{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Lv.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Ed.NONE;return this.scope!==Lv.SIZE&&this.scope!==Lv.VIEWPORT||(e=Ed.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Lv.VIEWPORT?null!==t?zv.copy(t.viewport):(e.getViewport(zv),zv.multiplyScalar(e.getPixelRatio())):null!==t?(Ov.width=t.width,Ov.height=t.height):e.getDrawingBufferSize(Ov)}setup(){const e=this.scope;let t=null;return t=e===Lv.SIZE?dm(Ov||(Ov=new Ys)):e===Lv.VIEWPORT?dm(zv||(zv=new xi)):Vp(kv.div(Dv)),t}generate(e){if(this.scope===Lv.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Dv).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Lv.COORDINATE="coordinate",Lv.VIEWPORT="viewport",Lv.SIZE="size",Lv.UV="uv";const Vv=Np(Lv,Lv.UV),Dv=Np(Lv,Lv.SIZE),kv=Np(Lv,Lv.COORDINATE),Gv=Np(Lv,Lv.VIEWPORT),Wv=Gv.zw,jv=kv.sub(Gv.xy),Hv=jv.div(Wv),qv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.'),Dv)),"vec2").once()(),$v=Cp((()=>(console.warn('TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.'),Vv)),"vec2").once()(),Xv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.'),Vv.flipY())),"vec2").once()(),Yv=new Ys;class Zv extends Ey{static get type(){return"ViewportTextureNode"}constructor(e=Vv,t=null,s=null){null===s&&((s=new Wa).minFilter=Se),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Ed.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Yv);const s=this.value;s.image.width===Yv.width&&s.image.height===Yv.height||(s.image.width=Yv.width,s.image.height=Yv.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 Jv=Ap(Zv),Kv=Ap(Zv,null,null,{generateMipmaps:!0});let Qv=null;class eT extends Zv{static get type(){return"ViewportDepthTextureNode"}constructor(e=Vv,t=null){null===Qv&&(Qv=new Xa),super(e,t,Qv)}}const tT=Ap(eT);class sT extends zd{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===sT.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===sT.DEPTH_BASE)null!==s&&(i=hT().assign(s));else if(t===sT.DEPTH)i=e.isPerspectiveCamera?nT(lx.z,Fy,Uy):iT(lx.z,Fy,Uy);else if(t===sT.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=oT(s,Fy,Uy);i=iT(e,Fy,Uy)}else i=s;else i=iT(lx.z,Fy,Uy);return i}}sT.DEPTH_BASE="depthBase",sT.DEPTH="depth",sT.LINEAR_DEPTH="linearDepth";const iT=(e,t,s)=>e.add(t).div(t.sub(s)),rT=(e,t,s)=>t.sub(s).mul(e).sub(t),nT=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),oT=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),aT=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Eg(e.div(t).add(1)),r=Eg(s.div(t).add(1));return i.div(r)},hT=Ap(sT,sT.DEPTH_BASE),uT=Np(sT,sT.DEPTH),lT=Ap(sT,sT.LINEAR_DEPTH),cT=lT(tT());uT.assign=e=>hT(e);class dT extends zd{static get type(){return"ClippingNode"}constructor(e=dT.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{localClipIntersection:s,localClippingCount:i,globalClippingCount:r}=t,n=r+i,o=s?n-i:n;return this.scope===dT.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(t.planes,n,o):this.setupDefault(t.planes,n,o)}setupAlphaToCoverage(e,t,s){return Cp((()=>{const i=Ox(e),r=mm("float","distanceToPlane"),n=mm("float","distanceToGradient"),o=mm("float","clipOpacity");let a;if(o.assign(1),xv(s,(({i:e})=>{a=i.element(e),r.assign(lx.dot(a.xyz).negate().add(a.w)),n.assign(r.fwidth().div(2)),o.mulAssign(Sf(n.negate(),n,r)),o.equal(0).discard()})),s{a=i.element(t),r.assign(lx.dot(a.xyz).negate().add(a.w)),n.assign(r.fwidth().div(2)),e.mulAssign(Sf(n.negate(),n,r).oneMinus())})),o.mulAssign(e.oneMinus())}fm.a.mulAssign(o),fm.a.equal(0).discard()}))()}setupDefault(e,t,s){return Cp((()=>{const i=Ox(e);let r;if(xv(s,(({i:e})=>{r=i.element(e),lx.dot(r.xyz).greaterThan(r.w).discard()})),s{r=i.element(t),e.assign(lx.dot(r.xyz).greaterThan(r.w).and(e))})),e.discard()}}))()}}dT.ALPHA_TO_COVERAGE="alphaToCoverage",dT.DEFAULT="default";class pT extends Jr{static get type(){return"NodeMaterial"}constructor(){super(),this.isNodeMaterial=!0,this.type=this.constructor.type,this.forceSinglePass=!1,this.fog=!0,this.lights=!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.positionNode=null,this.geometryNode=null,this.depthNode=null,this.shadowNode=null,this.shadowPositionNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+_d(this)}build(e){this.setup(e)}setupObserver(e){return new yd(e)}setup(e){let t;e.context.setupNormal=()=>this.setupNormal(e),e.addStack(),e.stack.outputNode=this.vertexNode||this.setupPosition(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const s=this.setupClipping(e);if(!0===this.depthWrite&&this.setupDepth(e),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==s&&e.stack.add(s);const r=$p(i,fm.a).max(0);t=this.setupOutput(e,r),Fm.assign(t),null!==this.outputNode&&(t=this.outputNode);if(null!==e.renderer.getRenderTarget()){const s=e.renderer.getMRT(),i=this.mrtNode;null!==s?(t=s,null!==i&&(t=s.merge(i))):null!==i&&(t=i)}}else{let s=this.fragmentNode;!0!==s.isOutputStructNode&&(s=$p(s)),t=this.setupOutput(e,s)}e.stack.outputNode=t,e.addFlow("fragment",e.removeStack()),e.monitor=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{globalClippingCount:t,localClippingCount:s}=e.clippingContext;let i=null;if(t||s){const t=e.renderer.samples;this.alphaToCoverage&&t>1?i=wp(new dT(dT.ALPHA_TO_COVERAGE)):e.stack.add(wp(new dT))}return i}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=s.isPerspectiveCamera?aT(tv().w,Fy,Uy):iT(lx.z,Fy,Uy))}null!==i&&uT.assign(i).append()}setupPosition(e){const{object:t}=e,s=t.geometry;if(e.addStack(),(s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Av(t).append(),!0===t.isSkinnedMesh&&fv(t).append(),this.displacementMap){const e=Wx("displacementMap","texture"),t=Wx("displacementScale","float"),s=Wx("displacementBias","float");ox.addAssign(fx.normalize().mul(e.x.mul(t).add(s)))}t.isBatchedMesh&&dv(t).append(),t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&lv(t).append(),null!==this.positionNode&&ox.assign(this.positionNode);const i=tv();return e.context.vertex=e.removeStack(),e.context.mvp=i,i}setupDiffuseColor({object:e,geometry:t}){let s=this.colorNode?$p(this.colorNode):yb;if(!0===this.vertexColors&&t.hasAttribute("color")&&(s=$p(s.xyz.mul(Sy("color","vec3")),s.a)),e.instanceColor){s=gm("vec3","vInstanceColor").mul(s)}if(e.isBatchedMesh&&e._colorsTexture){s=gm("vec3","vBatchColor").mul(s)}fm.assign(s);const i=this.opacityNode?Up(this.opacityNode):vb;if(fm.a.assign(fm.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?Up(this.alphaTestNode):fb;fm.a.lessThanEqual(e).discard()}!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&fm.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Wp(0):fm.rgb}setupNormal(){return this.normalNode?Wp(this.normalNode):Cb}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Wx("envMap","cubeTexture"):Wx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Uv(Jb)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Kb;t.push(new Iv(e))}let r=this.lightsNode||e.lightsNode;return t.length>0&&(r=Ev([...r.getLights(),...t])),r}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:r}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let o=this.setupOutgoingLight(e);if(n&&n.getScope().getLights().length>0){const t=this.setupLightingModel(e);o=Fv(n,t,s,i)}else null!==s&&(o=Wp(null!==i?vf(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(ym.assign(Wp(r||bb)),o=o.add(ym)),o}setupOutput(e,t){if(!0===this.fog){const s=e.fogNode;s&&(t=$p(s.mix(t.rgb,s.colorNode),t.a))}return t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.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 s=Jr.prototype.toJSON.call(this,e),i=wd(this);s.inputNodes={};for(const{property:t,childNode:r}of i)s.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),n=r(e.nodes);t.length>0&&(s.textures=t),i.length>0&&(s.images=i),n.length>0&&(s.nodes=n)}return s}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.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.shadowNode=e.shadowNode,this.shadowPositionNode=e.shadowPositionNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const mT=new Fa;class gT extends pT{static get type(){return"InstancedPointsNodeMaterial"}constructor(e={}){super(),this.lights=!1,this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.pointWidth=1,this.pointColorNode=null,this.pointWidthNode=null,this.setDefaultValues(mT),this.setValues(e)}setup(e){this.setupShaders(e),super.setup(e)}setupShaders({renderer:e}){const t=this.alphaToCoverage,s=this.useColor;this.vertexNode=Cp((()=>{const e=Sy("instancePosition").xyz,t=$p(sx.mul($p(e,1))),s=Gv.z.div(Gv.w),i=Oy.mul(t),r=nx.xy.toVar();return r.mulAssign(this.pointWidthNode?this.pointWidthNode:Yb),r.assign(r.div(Gv.z)),r.y.assign(r.y.mul(s)),r.assign(r.mul(i.w)),i.addAssign($p(r,0,0)),i}))(),this.fragmentNode=Cp((()=>{const i=Up(1).toVar(),r=bf(My().mul(2).sub(1));if(t&&e.samples>1){const e=Up(r.fwidth()).toVar();i.assign(Sf(e.oneMinus(),e.add(1),r).oneMinus())}else r.greaterThan(1).discard();let n;if(this.pointColorNode)n=this.pointColorNode;else if(s){n=Sy("instanceColor").mul(yb)}else n=yb;return i.mulAssign(vb),$p(n,i)}))()}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.needsUpdate=!0)}}const fT=new va;class yT extends pT{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.lights=!1,this.setDefaultValues(fT),this.setValues(e)}}const xT=new Eu;class bT extends pT{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.lights=!1,this.setDefaultValues(xT),this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode,t=this.dashScaleNode?Up(this.dashScaleNode):jb,s=this.dashSizeNode?Up(this.dashSizeNode):Hb,i=this.dashSizeNode?Up(this.dashGapNode):qb;Um.assign(s),Om.assign(i);const r=Vf(Sy("lineDistance").mul(t));(e?r.add(e):r).mod(Um.add(Om)).greaterThan(Um).discard()}}const vT=new Eu;class TT extends pT{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.lights=!1,this.setDefaultValues(vT),this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.useDash=e.dashed,this.useWorldUnits=!1,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setup(e){this.setupShaders(e),super.setup(e)}setupShaders({renderer:e}){const t=this.alphaToCoverage,s=this.useColor,i=this.dashed,r=this.worldUnits,n=Cp((({start:e,end:t})=>{const s=Oy.element(2).element(2),i=Oy.element(3).element(2).mul(-.5).div(s).sub(e.z).div(t.z.sub(e.z));return $p(vf(e.xyz,t.xyz,i),t.w)})).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=Cp((()=>{const e=Sy("instanceStart"),t=Sy("instanceEnd"),s=$p(sx.mul($p(e,1))).toVar("start"),o=$p(sx.mul($p(t,1))).toVar("end");r&&(gm("vec3","worldStart").assign(s.xyz),gm("vec3","worldEnd").assign(o.xyz));const a=Gv.z.div(Gv.w),h=Oy.element(2).element(3).equal(-1);Ip(h,(()=>{Ip(s.z.lessThan(0).and(o.z.greaterThan(0)),(()=>{o.assign(n({start:s,end:o}))})).ElseIf(o.z.lessThan(0).and(s.z.greaterThanEqual(0)),(()=>{s.assign(n({start:o,end:s}))}))}));const u=Oy.mul(s),l=Oy.mul(o),c=u.xyz.div(u.w),d=l.xyz.div(l.w),p=d.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(a)),p.assign(p.normalize());const m=$p().toVar();if(r){const e=o.xyz.sub(s.xyz).normalize(),t=vf(s.xyz,o.xyz,.5).normalize(),r=e.cross(t).normalize(),n=e.cross(r),a=gm("vec4","worldPos");a.assign(nx.y.lessThan(.5).select(s,o));const h=$b.mul(.5);a.addAssign($p(nx.x.lessThan(0).select(r.mul(h),r.mul(h).negate()),0)),i||(a.addAssign($p(nx.y.lessThan(.5).select(e.mul(h).negate(),e.mul(h)),0)),a.addAssign($p(n.mul(h),0)),Ip(nx.y.greaterThan(1).or(nx.y.lessThan(0)),(()=>{a.subAssign($p(n.mul(2).mul(h),0))}))),m.assign(Oy.mul(a));const u=Wp().toVar();u.assign(nx.y.lessThan(.5).select(c,d)),m.z.assign(u.z.mul(m.w))}else{const e=Vp(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(a)),e.x.assign(e.x.div(a)),e.assign(nx.x.lessThan(0).select(e.negate(),e)),Ip(nx.y.lessThan(0),(()=>{e.assign(e.sub(p))})).ElseIf(nx.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul($b)),e.assign(e.div(Gv.w)),m.assign(nx.y.lessThan(.5).select(u,l)),e.assign(e.mul(m.w)),m.assign(m.add($p(e,0,0)))}return m}))();const o=Cp((({p1:e,p2:t,p3:s,p4:i})=>{const r=e.sub(s),n=i.sub(s),o=t.sub(e),a=r.dot(n),h=n.dot(o),u=r.dot(o),l=n.dot(n),c=o.dot(o).mul(l).sub(h.mul(h)),d=a.mul(h).sub(u.mul(l)).div(c).clamp(),p=a.add(h.mul(d)).div(l).clamp();return Vp(d,p)}));this.fragmentNode=Cp((()=>{const n=My();if(i){const e=this.offsetNode?Up(this.offsetNodeNode):Xb,t=this.dashScaleNode?Up(this.dashScaleNode):jb,s=this.dashSizeNode?Up(this.dashSizeNode):Hb,i=this.dashSizeNode?Up(this.dashGapNode):qb;Um.assign(s),Om.assign(i);const r=Sy("instanceDistanceStart"),o=Sy("instanceDistanceEnd"),a=nx.y.lessThan(.5).select(t.mul(r),jb.mul(o)),h=Vf(a.add(Xb)),u=e?h.add(e):h;n.y.lessThan(-1).or(n.y.greaterThan(1)).discard(),u.mod(Um.add(Om)).greaterThan(Um).discard()}const a=Up(1).toVar("alpha");if(r){const s=gm("vec3","worldStart"),r=gm("vec3","worldEnd"),n=gm("vec4","worldPos").xyz.normalize().mul(1e5),h=r.sub(s),u=o({p1:s,p2:r,p3:Wp(0,0,0),p4:n}),l=s.add(h.mul(u.x)),c=n.mul(u.y),d=l.sub(c).length().div($b);if(!i)if(t&&e.samples>1){const e=d.fwidth();a.assign(Sf(e.negate().add(.5),e.add(.5),d).oneMinus())}else d.greaterThan(.5).discard()}else if(t&&e.samples>1){const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1)),s=e.mul(e).add(t.mul(t)),i=Up(s.fwidth()).toVar("dlen");Ip(n.y.abs().greaterThan(1),(()=>{a.assign(Sf(i.oneMinus(),i.add(1),s).oneMinus())}))}else Ip(n.y.abs().greaterThan(1),(()=>{const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()}));let h;if(this.lineColorNode)h=this.lineColorNode;else if(s){const e=Sy("instanceColorStart"),t=Sy("instanceColorEnd");h=nx.y.lessThan(.5).select(e,t).mul(yb)}else h=yb;return $p(h,a)}))()}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 _T=e=>wp(e).mul(.5).add(.5),wT=e=>wp(e).mul(2).sub(1),ST=new Mu;class MT extends pT{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(ST),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Up(this.opacityNode):vb;fm.assign($p(_T(vx),e))}}class AT extends Dd{static get type(){return"EquirectUVNode"}constructor(e=ux){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan2(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Vp(t,s)}}const NT=Ap(AT);class CT extends Yn{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=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 r=new Ln(5,5,5),n=NT(ux),o=new pT;o.colorNode=By(t,n,0),o.side=d,o.blending=m;const a=new On(r,o),h=new Kn;h.add(a),t.minFilter===Se&&(t.minFilter=Te);const u=new $n(1,10,this),l=e.getMRT();return e.setMRT(null),u.update(e,h),e.setMRT(l),t.minFilter=s,t.currentGenerateMipmaps=i,a.geometry.dispose(),a.material.dispose(),this}}const RT=new WeakMap;class ET extends Dd{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Bx();const t=new Xn;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Ed.RENDER}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:s[i.property];if(e&&e.isTexture){const s=e.mapping;if(s===le||s===ce){if(RT.has(e)){const t=RT.get(e);IT(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new CT(s.height);i.fromEquirectangularTexture(t,e),IT(i.texture,e.mapping),this._cubeTexture=i.texture,RT.set(e,i.texture),e.addEventListener("dispose",BT)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function BT(e){const t=e.target;t.removeEventListener("dispose",BT);const s=RT.get(t);void 0!==s&&(RT.delete(t),s.dispose())}function IT(e,t){t===le?e.mapping=he:t===ce&&(e.mapping=ue)}const PT=Ap(ET);class FT extends Bv{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=PT(this.envNode)}}class UT extends Bv{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Up(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class OT{start(){}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class zT extends OT{constructor(){super()}indirect(e,t,s){const i=e.ambientOcclusion,r=e.reflectedLight,n=s.context.irradianceLightMap;r.indirectDiffuse.assign($p(0)),n?r.indirectDiffuse.addAssign(n):r.indirectDiffuse.addAssign($p(1,1,1,0)),r.indirectDiffuse.mulAssign(i),r.indirectDiffuse.mulAssign(fm.rgb)}finish(e,t,s){const i=s.material,r=e.outgoingLight,n=s.context.environment;if(n)switch(i.combine){case 0:r.rgb.assign(vf(r.rgb,r.rgb.mul(n.rgb),Sb.mul(Mb)));break;case 1:r.rgb.assign(vf(r.rgb,n.rgb,Sb.mul(Mb)));break;case 2:r.rgb.addAssign(n.rgb.mul(Sb.mul(Mb)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",i.combine)}}}const LT=new Kr;class VT extends pT{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(LT),this.setValues(e)}setupNormal(){return xx}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new FT(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new UT(Jb)),t}setupOutgoingLight(){return fm.rgb}setupLightingModel(){return new zT}}const DT=Cp((({f0:e,f90:t,dotVH:s})=>{const i=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(i.oneMinus()).add(t.mul(i))})),kT=Cp((e=>e.diffuseColor.mul(1/Math.PI))),GT=Cp((({dotNH:e})=>Pm.mul(Up(.5)).add(1).mul(Up(1/Math.PI)).mul(e.pow(Pm)))),WT=Cp((({lightDirection:e})=>{const t=e.add(cx).normalize(),s=vx.dot(t).clamp(),i=cx.dot(t).clamp(),r=DT({f0:Bm,f90:1,dotVH:i}),n=Up(.25),o=GT({dotNH:s});return r.mul(n).mul(o)}));class jT extends zT{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=vx.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(kT({diffuseColor:fm.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(WT({lightDirection:e})).mul(Sb))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(kT({diffuseColor:fm}))),s.indirectDiffuse.mulAssign(e)}}const HT=new Au;class qT extends pT{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(HT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new FT(t):null}setupLightingModel(){return new jT(!1)}}const $T=new wu;class XT extends pT{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues($T),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new FT(t):null}setupLightingModel(){return new jT}setupVariants(){const e=(this.shininessNode?Up(this.shininessNode):xb).max(1e-4);Pm.assign(e);const t=this.specularNode||Tb;Bm.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const YT=Cp((e=>{if(!1===e.geometry.hasAttribute("normal"))return Up(0);const t=xx.dFdx().abs().max(xx.dFdy().abs());return t.x.max(t.y).max(t.z)})),ZT=Cp((e=>{const{roughness:t}=e,s=YT();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i})),JT=Cp((({alpha:e,dotNL:t,dotNV:s})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt()),n=s.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return Km(.5,r.add(n).max(xg))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),KT=Cp((({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const h=a.mul(Wp(e.mul(s),t.mul(i),o).length()),u=o.mul(Wp(e.mul(r),t.mul(n),a).length());return Km(.5,h.add(u)).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"}]}),QT=Cp((({alpha:e,dotNH:t})=>{const s=e.pow2(),i=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(i.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),e_=Up(1/Math.PI),t_=Cp((({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=Wp(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),h=n.div(a);return e_.mul(n.mul(h.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"}]}),s_=Cp((e=>{const{lightDirection:t,f0:s,f90:i,roughness:r,f:n,USE_IRIDESCENCE:o,USE_ANISOTROPY:a}=e,h=e.normalView||vx,u=r.pow2(),l=t.add(cx).normalize(),c=h.dot(t).clamp(),d=h.dot(cx).clamp(),p=h.dot(l).clamp(),m=cx.dot(l).clamp();let g,f,y=DT({f0:s,f90:i,dotVH:m});if(vp(o)&&(y=Sm.mix(y,n)),vp(a)){const e=Rm.dot(t),s=Rm.dot(cx),i=Rm.dot(l),r=Em.dot(t),n=Em.dot(cx),o=Em.dot(l);g=KT({alphaT:Nm,alphaB:u,dotTV:s,dotBV:n,dotTL:e,dotBL:r,dotNV:d,dotNL:c}),f=t_({alphaT:Nm,alphaB:u,dotNH:p,dotTH:i,dotBH:o})}else g=JT({alpha:u,dotNL:c,dotNV:d}),f=QT({alpha:u,dotNH:p});return y.mul(g).mul(f)})),i_=Cp((({roughness:e,dotNV:t})=>{const s=$p(-1,-.0275,-.572,.022),i=$p(1,.0425,1.04,-.04),r=e.mul(s).add(i),n=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return Vp(-1.04,1.04).mul(n).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),r_=Cp((e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=i_({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))})),n_=Cp((({f:e,f90:t,dotVH:s})=>{const i=s.oneMinus().saturate(),r=i.mul(i),n=i.mul(r,r).clamp(0,.9999);return e.sub(Wp(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"}]}),o_=Cp((({roughness:e,dotNH:t})=>{const s=e.pow2(),i=Up(1).div(s),r=t.pow2().oneMinus().max(.0078125);return Up(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),a_=Cp((({dotNV:e,dotNL:t})=>Up(1).div(Up(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),h_=Cp((({lightDirection:e})=>{const t=e.add(cx).normalize(),s=vx.dot(e).clamp(),i=vx.dot(cx).clamp(),r=vx.dot(t).clamp(),n=o_({roughness:wm,dotNH:r}),o=a_({dotNV:i,dotNL:s});return _m.mul(n).mul(o)})),u_=Cp((({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=Vp(s,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r})).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),l_=Cp((({f:e})=>{const t=e.length();return nf(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),c_=Cp((({v1:e,v2:t})=>{const s=e.dot(t),i=s.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),n=i.add(4.1616724).mul(i).add(3.417594).toVar(),o=r.div(n),a=s.greaterThan(0).select(o,nf(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return e.cross(t).mul(a)})).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),d_=Cp((({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:o,p3:a})=>{const h=n.sub(r).toVar(),u=a.sub(r).toVar(),l=h.cross(u),c=Wp().toVar();return Ip(l.dot(s.sub(r)).greaterThanEqual(0),(()=>{const h=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(h).negate(),l=i.mul(Kp(h,u,e).transpose()).toVar(),d=l.mul(r.sub(s)).normalize().toVar(),p=l.mul(n.sub(s)).normalize().toVar(),m=l.mul(o.sub(s)).normalize().toVar(),g=l.mul(a.sub(s)).normalize().toVar(),f=Wp(0).toVar();f.addAssign(c_({v1:d,v2:p})),f.addAssign(c_({v1:p,v2:m})),f.addAssign(c_({v1:m,v2:g})),f.addAssign(c_({v1:g,v2:d})),c.assign(Wp(l_({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"}]}),p_=1/6,m_=e=>Jm(p_,Jm(e,Jm(e,e.negate().add(3)).sub(3)).add(1)),g_=e=>Jm(p_,Jm(e,Jm(e,Jm(3,e).sub(6))).add(4)),f_=e=>Jm(p_,Jm(e,Jm(e,Jm(-3,e).add(3)).add(3)).add(1)),y_=e=>Jm(p_,pf(e,3)),x_=e=>m_(e).add(g_(e)),b_=e=>f_(e).add(y_(e)),v_=e=>Ym(-1,g_(e).div(m_(e).add(g_(e)))),T_=e=>Ym(1,y_(e).div(f_(e).add(y_(e)))),__=(e,t,s)=>{const i=e.uvNode,r=Jm(i,t.zw).add(.5),n=Pg(r),o=Og(r),a=x_(o.x),h=b_(o.x),u=v_(o.x),l=T_(o.x),c=v_(o.y),d=T_(o.y),p=Vp(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),m=Vp(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Vp(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),f=Vp(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),y=x_(o.y).mul(Ym(a.mul(e.uv(p).level(s)),h.mul(e.uv(m).level(s)))),x=b_(o.y).mul(Ym(a.mul(e.uv(g).level(s)),h.mul(e.uv(f).level(s))));return y.add(x)},w_=Cp((([e,t=Up(3)])=>{const s=Vp(e.size(Op(t))),i=Vp(e.size(Op(t.add(1)))),r=Km(1,s),n=Km(1,i),o=__(e,$p(r,s),Pg(t)),a=__(e,$p(n,i),Fg(t));return Og(t).mix(o,a)})),S_=Cp((([e,t,s,i,r])=>{const n=Wp(wf(t.negate(),Ug(e),Km(1,i))),o=Wp(Hg(r[0].xyz),Hg(r[1].xyz),Hg(r[2].xyz));return Ug(n).mul(s.mul(o))})).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"}]}),M_=Cp((([e,t])=>e.mul(Tf(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),A_=Kv(),N_=Cp((([e,t,s])=>{const i=A_.uv(e),r=Eg(Up(Dv.x)).mul(M_(t,s));return w_(i,r)})),C_=Cp((([e,t,s])=>(Ip(s.notEqual(0),(()=>{const i=Rg(t).negate().div(s);return Ng(i.negate().mul(e))})),Wp(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),R_=Cp((([e,t,s,i,r,n,o,a,h,u,l,c,d,p,m])=>{let g,f;if(m){g=$p().toVar(),f=Wp().toVar();const r=l.sub(1).mul(m.mul(.025)),n=Wp(l.sub(r),l,l.add(r));xv({start:0,end:3},(({i:r})=>{const l=n.element(r),m=S_(e,t,c,l,a),y=o.add(m),x=u.mul(h.mul($p(y,1))),b=Vp(x.xy.div(x.w)).toVar();b.addAssign(1),b.divAssign(2),b.assign(Vp(b.x,b.y.oneMinus()));const v=N_(b,s,l);g.element(r).assign(v.element(r)),g.a.addAssign(v.a),f.element(r).assign(i.element(r).mul(C_(Hg(m),d,p).element(r)))})),g.a.divAssign(3)}else{const r=S_(e,t,c,l,a),n=o.add(r),m=u.mul(h.mul($p(n,1))),y=Vp(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Vp(y.x,y.y.oneMinus())),g=N_(y,s,l),f=i.mul(C_(Hg(r),d,p))}const y=f.rgb.mul(g.rgb),x=e.dot(t).clamp(),b=Wp(r_({dotNV:x,specularColor:r,specularF90:n,roughness:s})),v=f.r.add(f.g,f.b).div(3);return $p(b.oneMinus().mul(y),g.a.oneMinus().mul(v).oneMinus())})),E_=Kp(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),B_=(e,t)=>e.sub(t).div(e.add(t)).pow2(),I_=(e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=Wp(54856e-17,44201e-17,52481e-17),r=Wp(1681e3,1795300,2208400),n=Wp(43278e5,93046e5,66121e5),o=Up(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let a=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());a=Wp(a.x.add(o),a.y,a.z).div(1.0685e-7);return E_.mul(a)},P_=Cp((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=vf(e,t,Sf(0,.03,i)),o=e.div(n).pow2().mul(Up(1).sub(s.pow2())),a=Up(1).sub(o).sqrt(),h=B_(n,e),u=DT({f0:h,f90:1,dotVH:s}),l=u.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=Up(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Wp(1).add(t).div(Wp(1).sub(t))})(r.clamp(0,.9999)),m=B_(p,n.toVec3()),g=DT({f0:m,f90:1,dotVH:a}),f=Wp(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(i,a,2),x=Wp(d).add(f),b=u.mul(g).clamp(1e-5,.9999),v=b.sqrt(),T=l.pow2().mul(g).div(Wp(1).sub(b));let _=u.add(T),w=T.sub(l);for(let e=1;e<=2;++e){w=w.mul(v);const t=I_(Up(e).mul(y),Up(e).mul(x)).mul(2);_=_.add(w.mul(t))}return _.max(Wp(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"}]}),F_=Cp((({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.pow2(),n=Ef(s.lessThan(.25),Up(-339.2).mul(r).add(Up(161.4).mul(s)).sub(25.9),Up(-8.48).mul(r).add(Up(14.3).mul(s)).sub(9.95)),o=Ef(s.lessThan(.25),Up(44).mul(r).sub(Up(23.7).mul(s)).add(3.26),Up(1.97).mul(r).sub(Up(3.27).mul(s)).add(.72));return Ef(s.lessThan(.25),0,Up(.1).mul(s).sub(.025)).add(n.mul(i).add(o).exp()).mul(1/Math.PI).saturate()})),U_=Wp(.04),O_=Up(1);class z_ extends OT{constructor(e=!1,t=!1,s=!1,i=!1,r=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=r,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=Wp().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Wp().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Wp().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Wp().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Wp().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=vx.dot(cx).clamp();this.iridescenceFresnel=P_({outsideIOR:Up(1),eta2:Mm,cosTheta1:e,thinFilmThickness:Am,baseF0:Bm}),this.iridescenceF0=n_({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=hx,s=ky.sub(hx).normalize(),i=Tx;e.backdrop=R_(i,s,xm,fm,Bm,Im,t,Zy,Ly,Oy,Lm,Dm,Gm,km,this.dispersion?Wm:null),e.backdropAlpha=Vm,fm.a.mulAssign(vf(1,e.backdrop.a,Vm))}}computeMultiscattering(e,t,s){const i=vx.dot(cx).clamp(),r=i_({roughness:xm,dotNV:i}),n=(this.iridescenceF0?Sm.mix(Bm,this.iridescenceF0):Bm).mul(r.x).add(s.mul(r.y)),o=r.x.add(r.y).oneMinus(),a=Bm.add(Bm.oneMinus().mul(.047619)),h=n.mul(a).div(o.mul(a).oneMinus());e.addAssign(n),t.addAssign(h.mul(o))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=vx.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(h_({lightDirection:e}))),!0===this.clearcoat){const s=_x.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(s_({lightDirection:e,f0:U_,f90:O_,roughness:Tm,normalView:_x})))}s.directDiffuse.addAssign(i.mul(kT({diffuseColor:fm.rgb}))),s.directSpecular.addAssign(i.mul(s_({lightDirection:e,f0:Bm,f90:1,roughness:xm,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:r,ltc_1:n,ltc_2:o}){const a=t.add(s).sub(i),h=t.sub(s).sub(i),u=t.sub(s).add(i),l=t.add(s).add(i),c=vx,d=cx,p=lx.toVar(),m=u_({N:c,V:d,roughness:xm}),g=n.uv(m).toVar(),f=o.uv(m).toVar(),y=Kp(Wp(g.x,0,g.y),Wp(0,1,0),Wp(g.z,0,g.w)).toVar(),x=Bm.mul(f.x).add(Bm.oneMinus().mul(f.y)).toVar();r.directSpecular.addAssign(e.mul(x).mul(d_({N:c,V:d,P:p,mInv:y,p0:a,p1:h,p2:u,p3:l}))),r.directDiffuse.addAssign(e.mul(fm).mul(d_({N:c,V:d,P:p,mInv:Kp(1,0,0,0,1,0,0,0,1),p0:a,p1:h,p2:u,p3:l})))}indirect(e,t,s){this.indirectDiffuse(e,t,s),this.indirectSpecular(e,t,s),this.ambientOcclusion(e,t,s)}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(kT({diffuseColor:fm})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:s}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(_m,F_({normal:vx,viewDir:cx,roughness:wm}))),!0===this.clearcoat){const e=_x.dot(cx).clamp(),t=r_({dotNV:e,specularColor:U_,specularF90:O_,roughness:Tm});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=Wp().toVar("singleScattering"),r=Wp().toVar("multiScattering"),n=t.mul(1/Math.PI);this.computeMultiscattering(i,r,Im);const o=i.add(r),a=fm.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(e.mul(i)),s.indirectSpecular.addAssign(r.mul(n)),s.indirectDiffuse.addAssign(a.mul(n))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const s=vx.dot(cx).clamp().add(e),i=xm.mul(-16).oneMinus().negate().exp2(),r=e.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(r)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=_x.dot(cx).clamp(),s=DT({dotVH:e,f0:U_,f90:O_}),i=t.mul(vm.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(vm));t.assign(i)}if(!0===this.sheen){const e=_m.r.max(_m.g).max(_m.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const L_=Up(1),V_=Up(-2),D_=Up(.8),k_=Up(-1),G_=Up(.4),W_=Up(2),j_=Up(.305),H_=Up(3),q_=Up(.21),$_=Up(4),X_=Up(4),Y_=Up(16),Z_=Cp((([e])=>{const t=Wp(Wg(e)).toVar(),s=Up(-1).toVar();return Ip(t.x.greaterThan(t.z),(()=>{Ip(t.x.greaterThan(t.y),(()=>{s.assign(Ef(e.x.greaterThan(0),0,3))})).Else((()=>{s.assign(Ef(e.y.greaterThan(0),1,4))}))})).Else((()=>{Ip(t.z.greaterThan(t.y),(()=>{s.assign(Ef(e.z.greaterThan(0),2,5))})).Else((()=>{s.assign(Ef(e.y.greaterThan(0),1,4))}))})),s})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),J_=Cp((([e,t])=>{const s=Vp().toVar();return Ip(t.equal(0),(()=>{s.assign(Vp(e.z,e.y).div(Wg(e.x)))})).ElseIf(t.equal(1),(()=>{s.assign(Vp(e.x.negate(),e.z.negate()).div(Wg(e.y)))})).ElseIf(t.equal(2),(()=>{s.assign(Vp(e.x.negate(),e.y).div(Wg(e.z)))})).ElseIf(t.equal(3),(()=>{s.assign(Vp(e.z.negate(),e.y).div(Wg(e.x)))})).ElseIf(t.equal(4),(()=>{s.assign(Vp(e.x.negate(),e.z).div(Wg(e.y)))})).Else((()=>{s.assign(Vp(e.x,e.y).div(Wg(e.z)))})),Jm(.5,s.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),K_=Cp((([e])=>{const t=Up(0).toVar();return Ip(e.greaterThanEqual(D_),(()=>{t.assign(L_.sub(e).mul(k_.sub(V_)).div(L_.sub(D_)).add(V_))})).ElseIf(e.greaterThanEqual(G_),(()=>{t.assign(D_.sub(e).mul(W_.sub(k_)).div(D_.sub(G_)).add(k_))})).ElseIf(e.greaterThanEqual(j_),(()=>{t.assign(G_.sub(e).mul(H_.sub(W_)).div(G_.sub(j_)).add(W_))})).ElseIf(e.greaterThanEqual(q_),(()=>{t.assign(j_.sub(e).mul($_.sub(H_)).div(j_.sub(q_)).add(H_))})).Else((()=>{t.assign(Up(-2).mul(Eg(Jm(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Q_=Cp((([e,t])=>{const s=e.toVar();s.assign(Jm(2,s).sub(1));const i=Wp(s,1).toVar();return Ip(t.equal(0),(()=>{i.assign(i.zyx)})).ElseIf(t.equal(1),(()=>{i.assign(i.xzy),i.xz.mulAssign(-1)})).ElseIf(t.equal(2),(()=>{i.x.mulAssign(-1)})).ElseIf(t.equal(3),(()=>{i.assign(i.zyx),i.xz.mulAssign(-1)})).ElseIf(t.equal(4),(()=>{i.assign(i.xzy),i.xy.mulAssign(-1)})).ElseIf(t.equal(5),(()=>{i.z.mulAssign(-1)})),i})).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),ew=Cp((([e,t,s,i,r,n])=>{const o=Up(s),a=Wp(t),h=Tf(K_(o),V_,n),u=Og(h),l=Pg(h),c=Wp(tw(e,a,l,i,r,n)).toVar();return Ip(u.notEqual(0),(()=>{const t=Wp(tw(e,a,l.add(1),i,r,n)).toVar();c.assign(vf(c,t,u))})),c})),tw=Cp((([e,t,s,i,r,n])=>{const o=Up(s).toVar(),a=Wp(t),h=Up(Z_(a)).toVar(),u=Up(nf(X_.sub(o),0)).toVar();o.assign(nf(o,X_));const l=Up(Cg(o)).toVar(),c=Vp(J_(a,h).mul(l.sub(2)).add(1)).toVar();return Ip(h.greaterThan(2),(()=>{c.y.addAssign(l),h.subAssign(3)})),c.x.addAssign(h.mul(l)),c.x.addAssign(u.mul(Jm(3,Y_))),c.y.addAssign(Jm(4,Cg(n).sub(l))),c.x.mulAssign(i),c.y.mulAssign(r),e.uv(c).grad(Vp(),Vp())})),sw=Cp((({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const h=Lg(i),u=s.mul(h).add(r.cross(s).mul(zg(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return tw(e,u,t,n,o,a)})),iw=Cp((({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:o,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})=>{const d=Wp(Ef(t,s,df(s,i))).toVar();Ip(_g(d.equals(Wp(0))),(()=>{d.assign(Wp(i.z,0,i.x.negate()))})),d.assign(Ug(d));const p=Wp().toVar();return p.addAssign(r.element(Op(0)).mul(sw({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),xv({start:Op(1),end:e},(({i:e})=>{Ip(e.greaterThanEqual(n),(()=>{vv()}));const t=Up(o.mul(Up(e))).toVar();p.addAssign(r.element(e).mul(sw({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(sw({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})))})),$p(p,1)}));let rw=null;const nw=new WeakMap;function ow(e){let t=nw.get(e);if((void 0!==t?t.pmremVersion:-1)!==e.pmremVersion){const s=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const s=6;for(let i=0;i0}(s))return null;t=rw.fromEquirectangular(e,t)}t.pmremVersion=e.pmremVersion,nw.set(e,t)}return t.texture}class aw extends Dd{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new yi;i.isRenderTargetTexture=!0,this._texture=By(i),this._width=dm(0),this._height=dm(0),this._maxMip=dm(0),this.updateBeforeType=Ed.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,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:s,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(){let e=this._pmrem;const t=e?e.pmremVersion:-1,s=this._value;t!==s.pmremVersion&&(e=!0===s.isPMREMTexture?s:ow(s),null!==e&&(this._pmrem=e,this.updateFromTexture(e)))}setup(e){null===rw&&(rw=e.createPMREMGenerator()),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this));const s=this.value;e.renderer.coordinateSystem===Us&&!0!==s.isPMREMTexture&&!0===s.isRenderTargetTexture&&(t=Wp(t.x.negate(),t.yz));let i=this.levelNode;return null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),ew(this._texture,t,i,this._width,this._height,this._maxMip)}}const hw=Ap(aw),uw=new WeakMap;class lw extends Bv{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:t[s.property];let i=uw.get(e);void 0===i&&(i=hw(e),uw.set(e,i)),s=i}const i=t.envMap?Dx("envMapIntensity","float",e.material):Dx("environmentIntensity","float",e.scene),r=!0===t.useAnisotropy||t.anisotropy>0?ob:vx,n=s.context(cw(xm,r)).mul(i),o=s.context(dw(Tx)).mul(Math.PI).mul(i),a=ly(n),h=ly(o);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(h);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=s.context(cw(Tm,_x)).mul(i),t=ly(e);u.addAssign(t)}}}const cw=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=cx.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(Ly)),s),getTextureLevel:()=>e}},dw=e=>({getUV:()=>e,getTextureLevel:()=>Up(1)}),pw=new Tu;class mw extends pT{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(pw),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new lw(t):null}setupLightingModel(){return new z_}setupSpecular(){const e=vf(Wp(.04),fm.rgb,bm);Bm.assign(e),Im.assign(1)}setupVariants(){const e=this.metalnessNode?Up(this.metalnessNode):Nb;bm.assign(e);let t=this.roughnessNode?Up(this.roughnessNode):Ab;t=ZT({roughness:t}),xm.assign(t),this.setupSpecular(),fm.assign($p(fm.rgb.mul(e.oneMinus()),fm.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const gw=new _u;class fw extends mw{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(gw),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?Up(this.iorNode):kb;Lm.assign(e),Bm.assign(vf(rf(mf(Lm.sub(1).div(Lm.add(1))).mul(wb),Wp(1)).mul(_b),fm.rgb,bm)),Im.assign(vf(_b,1,bm))}setupLightingModel(){return new z_(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Up(this.clearcoatNode):Rb,t=this.clearcoatRoughnessNode?Up(this.clearcoatRoughnessNode):Eb;vm.assign(e),Tm.assign(ZT({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Wp(this.sheenNode):Pb,t=this.sheenRoughnessNode?Up(this.sheenRoughnessNode):Fb;_m.assign(e),wm.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Up(this.iridescenceNode):Ob,t=this.iridescenceIORNode?Up(this.iridescenceIORNode):zb,s=this.iridescenceThicknessNode?Up(this.iridescenceThicknessNode):Lb;Sm.assign(e),Mm.assign(t),Am.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?Vp(this.anisotropyNode):Ub).toVar();Cm.assign(e.length()),Ip(Cm.equal(0),(()=>{e.assign(Vp(1,0))})).Else((()=>{e.divAssign(Vp(Cm)),Cm.assign(Cm.saturate())})),Nm.assign(Cm.pow2().mix(xm.pow2(),1)),Rm.assign(ib[0].mul(e.x).add(ib[1].mul(e.y))),Em.assign(ib[1].mul(e.x).sub(ib[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Up(this.transmissionNode):Vb,t=this.thicknessNode?Up(this.thicknessNode):Db,s=this.attenuationDistanceNode?Up(this.attenuationDistanceNode):Gb,i=this.attenuationColorNode?Wp(this.attenuationColorNode):Wb;if(Vm.assign(e),Dm.assign(t),km.assign(s),Gm.assign(i),this.useDispersion){const e=this.dispersionNode?Up(this.dispersionNode):Zb;Wm.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Wp(this.clearcoatNormalNode):Bb}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),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 yw extends z_{constructor(e,t,s,i){super(e,t,s),this.useSSS=i}direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){if(!0===this.useSSS){const i=r.material,{thicknessColorNode:n,thicknessDistortionNode:o,thicknessAmbientNode:a,thicknessAttenuationNode:h,thicknessPowerNode:u,thicknessScaleNode:l}=i,c=e.add(vx.mul(o)).normalize(),d=Up(cx.dot(c.negate()).saturate().pow(u).mul(l)),p=Wp(d.add(a).mul(n));s.directDiffuse.addAssign(p.mul(h.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r)}}class xw extends fw{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=Up(.1),this.thicknessAmbientNode=Up(0),this.thicknessAttenuationNode=Up(.1),this.thicknessPowerNode=Up(2),this.thicknessScaleNode=Up(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new yw(this.useClearcoat,this.useSheen,this.useIridescence,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 bw=Cp((({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=Vp(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=Wx("gradientMap","texture").context({getUV:()=>r});return Wp(e.r)}{const e=r.fwidth().mul(.5);return vf(Wp(.7),Wp(1),Sf(Up(.7).sub(e.x),Up(.7).add(e.x),r.x))}}));class vw extends OT{direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){const n=bw({normal:gx,lightDirection:e,builder:r}).mul(t);s.directDiffuse.addAssign(n.mul(kT({diffuseColor:fm.rgb})))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(kT({diffuseColor:fm}))),s.indirectDiffuse.mulAssign(e)}}const Tw=new Su;class _w extends pT{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Tw),this.setValues(e)}setupLightingModel(){return new vw}}class ww extends Dd{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=Wp(cx.z,0,cx.x.negate()).normalize(),t=cx.cross(e);return Vp(e.dot(vx),t.dot(vx)).mul(.495).add(.5)}}const Sw=Np(ww),Mw=new Ru;class Aw extends pT{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Mw),this.setValues(e)}setupVariants(e){const t=Sw;let s;s=e.material.matcap?Wx("matcap","texture").context({getUV:()=>t}):Wp(vf(.2,.8,t.y)),fm.rgb.mulAssign(s.rgb)}}const Nw=new Fa;class Cw extends pT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.isPointsNodeMaterial=!0,this.lights=!1,this.transparent=!0,this.sizeNode=null,this.setDefaultValues(Nw),this.setValues(e)}copy(e){return this.sizeNode=e.sizeNode,super.copy(e)}}class Rw extends Dd{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:s}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return Jp(e,i,i.negate(),e).mul(s)}{const e=t,i=Qp($p(1,0,0,0),$p(0,Lg(e.x),zg(e.x).negate(),0),$p(0,zg(e.x),Lg(e.x),0),$p(0,0,0,1)),r=Qp($p(Lg(e.y),0,zg(e.y),0),$p(0,1,0,0),$p(zg(e.y).negate(),0,Lg(e.y),0),$p(0,0,0,1)),n=Qp($p(Lg(e.z),zg(e.z).negate(),0,0),$p(zg(e.z),Lg(e.z),0,0),$p(0,0,1,0),$p(0,0,0,1));return i.mul(r).mul(n).mul($p(s,1)).xyz}}}const Ew=Ap(Rw),Bw=new so;class Iw extends pT{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this.lights=!1,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.setDefaultValues(Bw),this.setValues(e)}setupPosition({object:e,camera:t,context:s}){const i=this.sizeAttenuation,{positionNode:r,rotationNode:n,scaleNode:o}=this,a=ox;let h=sx.mul(Wp(r||0)),u=Vp(Zy[0].xyz.length(),Zy[1].xyz.length());if(null!==o&&(u=u.mul(o)),!i)if(t.isPerspectiveCamera)u=u.mul(h.z.negate());else{const e=Up(2).div(Oy.element(1).element(1));u=u.mul(e.mul(2))}let l=a.xy;if(e.center&&!0===e.center.isVector2){const e=((e,t,s)=>wp(new Zf(e,t,s)))("center","vec2");l=l.sub(e.sub(.5))}l=l.mul(u);const c=Up(n||Ib),d=Ew(l,c);h=$p(h.xy.add(d),h.zw);const p=Oy.mul(h);return s.vertex=a,p}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)}}class Pw extends OT{constructor(){super(),this.shadowNode=Up(1).toVar("shadowMask")}direct({shadowMask:e}){this.shadowNode.mulAssign(e)}finish(e){fm.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(fm.rgb)}}const Fw=new bu;class Uw extends pT{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Fw),this.setValues(e)}setupLightingModel(){return new Pw}}const Ow=Cp((({texture:e,uv:t})=>{const s=1e-4,i=Wp().toVar();return Ip(t.x.lessThan(s),(()=>{i.assign(Wp(1,0,0))})).ElseIf(t.y.lessThan(s),(()=>{i.assign(Wp(0,1,0))})).ElseIf(t.z.lessThan(s),(()=>{i.assign(Wp(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(Wp(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(Wp(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(Wp(0,0,-1))})).Else((()=>{const s=.01,r=e.uv(t.add(Wp(-.01,0,0))).r.sub(e.uv(t.add(Wp(s,0,0))).r),n=e.uv(t.add(Wp(0,-.01,0))).r.sub(e.uv(t.add(Wp(0,s,0))).r),o=e.uv(t.add(Wp(0,0,-.01))).r.sub(e.uv(t.add(Wp(0,0,s))).r);i.assign(Wp(r,n,o))})),i.normalize()}));class zw extends Ey{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Wp(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){return t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return Ow({texture:this,uv:e})}}const Lw=Ap(zw);class Vw extends pT{static get type(){return"VolumeNodeMaterial"}constructor(e={}){super(),this.lights=!1,this.isVolumeNodeMaterial=!0,this.testNode=null,this.setValues(e)}setup(e){const t=Lw(this.map,null,0),s=Cp((({orig:e,dir:t})=>{const s=Wp(-.5),i=Wp(.5),r=t.reciprocal(),n=s.sub(e).mul(r),o=i.sub(e).mul(r),a=rf(n,o),h=nf(n,o),u=nf(a.x,nf(a.y,a.z)),l=rf(h.x,rf(h.y,h.z));return Vp(u,l)}));this.fragmentNode=Cp((()=>{const e=Vf(Wp(tx.mul($p(ky,1)))),i=Vf(nx.sub(e)).normalize(),r=Vp(s({orig:e,dir:i})).toVar();r.x.greaterThan(r.y).discard(),r.assign(Vp(nf(r.x,0),r.y));const n=Wp(e.add(r.x.mul(i))).toVar(),o=Wp(i.abs().reciprocal()).toVar(),a=Up(rf(o.x,rf(o.y,o.z))).toVar("delta");a.divAssign(Wx("steps","float"));const h=$p(Wx("base","color"),0).toVar();return xv({type:"float",start:r.x,end:r.y,update:"+= delta"},(()=>{const e=mm("float","d").assign(t.uv(n.add(.5)).r);null!==this.testNode?this.testNode({map:t,mapValue:e,probe:n,finalColor:h}).append():(h.a.assign(1),vv()),n.addAssign(i.mul(a))})),h.a.equal(0).discard(),$p(h)}))(),super.setup(e)}}class Dw{constructor(e,t){this.nodes=e,this.info=t,this.animationLoop=null,this.requestId=null,this._init()}_init(){const e=(t,s)=>{this.requestId=self.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,s)};e()}dispose(){self.cancelAnimationFrame(this.requestId),this.requestId=null}setAnimationLoop(e){this.animationLoop=e}}class kw{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let s=0;s{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){const t=this.material;let s=this.clippingContext;Array.isArray(t.clippingPlanes)?(s!==e&&s||(s=new Ww,this.clippingContext=s),s.update(e,t)):this.clippingContext!==e&&(this.clippingContext=e)}get clippingNeedsUpdate(){return this.clippingContext.version!==this.clippingContextVersion&&(this.clippingContextVersion=this.clippingContext.version,!0)}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().monitor)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;s.push(e);const n=e.isInterleavedBufferAttribute?e.data:e;i.add(n)}return this.attributes=s,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:r}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),o=this.getIndex(),a=null!==o,h=s.isInstancedBufferGeometry?s.instanceCount:e.count>1?e.count:1;if(0===h)return null;if(n.instanceCount=h,!0===e.isBatchedMesh)return n;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let l=r.start*u,c=(r.start+r.count)*u;null!==i&&(l=Math.max(l,i.start*u),c=Math.min(c,(i.start+i.count)*u));const d=s.attributes.position;let p=1/0;a?p=o.count:null!=d&&(p=d.count),l=Math.max(l,0),c=Math.min(c,p);const m=c-l;return m<0||m===1/0?null:(n.vertexCount=m,n.firstVertex=l,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t}=this;let s=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let s=Object.getPrototypeOf(e);for(;s;){const e=Object.getOwnPropertyDescriptors(s);for(const s in e)if(void 0!==e[s]){const i=e[s];i&&"function"==typeof i.get&&t.push(s)}s=Object.getPrototypeOf(s)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const i=t[e];let r;if(null!==i){const e=typeof i;"number"===e?r=0!==i?"1":"0":"object"===e?(r="{",i.isTexture&&(r+=i.mapping),r+="}"):r=String(i)}else r=String(i);s+=r+","}return s+=this.clippingContext.cacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.morphTargetInfluences&&(s+=e.morphTargetInfluences.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),bd(s)}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=this._nodes.getCacheKey(this.scene,this.lightsNode);return this.object.receiveShadow&&(e+=1),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const qw=[];class $w{constructor(e,t,s,i,r,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=r,this.info=n,this.chainMaps={}}get(e,t,s,i,r,n,o){const a=this.getChainMap(o);qw[0]=e,qw[1]=t,qw[2]=n,qw[3]=r;let h=a.get(qw);return void 0===h?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o),a.set(qw,h)):(h.updateClipping(n.clippingContext),(h.version!==t.version||h.needsUpdate)&&(h.initialCacheKey!==h.getCacheKey()?(h.dispose(),h=this.get(e,t,s,i,r,n,o)):h.version=t.version)),h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new kw)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,h,u){const l=this.getChainMap(u),c=new Hw(e,t,s,i,r,n,o,a,h);return c.onDispose=()=>{this.pipelines.delete(c),this.bindings.delete(c),this.nodes.delete(c),l.delete(c.getChainArray())},c}}class Xw{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;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 Yw=1,Zw=2,Jw=3,Kw=4,Qw=16;class eS extends Xw{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return void 0!==t&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===Yw?this.backend.createAttribute(e):t===Zw?this.backend.createIndexAttribute(e):t===Jw?this.backend.createStorageAttribute(e):t===Kw&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version=0;--t)if(e[t]>=65535)return!0;return!1}(t)?mn:dn)(t,1);return r.version=tS(e),r}class iS extends Xw{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",s)};t.addEventListener("dispose",s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,Jw):this.updateAttribute(e,Yw);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,Zw);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,Kw)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=sS(t),e.set(t,s)):s.version!==tS(t)&&(this.attributes.delete(s),s=sS(t),e.set(t,s)),i=s}return i}}class rS{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,previousFrameCalls:0,timestampCalls:0},this.compute={calls:0,frameCalls:0,timestamp:0,previousFrameCalls:0,timestampCalls:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}updateTimestamp(e,t){0===this[e].timestampCalls&&(this[e].timestamp=0),this[e].timestamp+=t,this[e].timestampCalls++,this[e].timestampCalls>=this[e].previousFrameCalls&&(this[e].timestampCalls=0)}reset(){const e=this.render.frameCalls;this.render.previousFrameCalls=e;const t=this.compute.frameCalls;this.compute.previousFrameCalls=t,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 nS{constructor(e){this.cacheKey=e,this.usedTimes=0}}class oS extends nS{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class aS extends nS{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let hS=0;class uS{constructor(e,t,s=null,i=null){this.id=hS++,this.code=e,this.stage=t,this.transforms=s,this.attributes=i,this.usedTimes=0}}class lS extends Xw{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:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let o=this.programs.compute.get(n.computeShader);void 0===o&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),o=new uS(n.computeShader,"compute",n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,o),s.createProgram(o));const a=this._getComputeCacheKey(e,o);let h=this.caches.get(a);void 0===h&&(r&&0===r.usedTimes&&this._releasePipeline(r),h=this._getComputePipeline(e,o,a,t)),h.usedTimes++,o.usedTimes++,i.version=e.version,i.pipeline=h}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState();let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new uS(n.vertexShader,"vertex"),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o));let a=this.programs.fragment.get(n.fragmentShader);void 0===a&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),a=new uS(n.fragmentShader,"fragment"),this.programs.fragment.set(n.fragmentShader,a),s.createProgram(a));const h=this._getRenderCacheKey(e,o,a);let u=this.caches.get(h);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,o,a,h,t)):e.pipeline=u,u.usedTimes++,o.usedTimes++,a.usedTimes++,i.pipeline=u}return i.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,s,i){s=s||this._getComputeCacheKey(e,t);let r=this.caches.get(s);return void 0===r&&(r=new aS(s,t),this.caches.set(s,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,s,i,r){i=i||this._getRenderCacheKey(e,t,s);let n=this.caches.get(i);return void 0===n&&(n=new oS(i,t,s),this.caches.set(i,n),e.pipeline=n,this.backend.createRenderPipeline(e,r)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].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 cS extends Xw{constructor(e,t,s,i,r,n){super(),this.backend=e,this.textures=s,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t),s.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t),s.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,s=e.isIndirectStorageBufferAttribute?Kw:Jw;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!this.nodes.updateGroup(t))continue}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){t.needsBindingsUpdate(this.textures.get(t.texture).generation)&&(i=!0);const e=t.update(),r=t.texture;e&&this.textures.updateTexture(r);const n=s.get(r);if(!0===s.isWebGPUBackend&&void 0===n.texture&&void 0===n.externalTexture&&(console.error("Bindings._update: binding should be available:",t,e,r,t.textureNode.value,i),this.textures.updateTexture(r),i=!0),!0===r.isStorageTexture){const e=this.get(r);!0===t.store?e.needsMipmap=!0:!0===r.generateMipmaps&&this.textures.needsMipmaps(r)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(r),e.needsMipmap=!1)}}}!0===i&&this.backend.updateBindings(e,t)}}class dS{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class pS{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf()}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 mS{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class gS extends mS{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class fS{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let yS=0;class xS{constructor(e=null){this.id=yS++,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 bS extends pm{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}const vS=(e,t)=>wp(new bS(e,t));class TS extends zd{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.code=e,this.language=s,this.includes=t}isGlobal(){return!0}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.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 _S=Ap(TS),wS=(e,t)=>_S(e,t,"js"),SS=(e,t)=>_S(e,t,"wgsl"),MS=(e,t)=>_S(e,t,"glsl");class AS extends TS{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,r=s.type,n=e.getCodeFromNode(this,r);""!==i&&(n.name=i);const o=e.getPropertyName(n),a=this.getNodeFunction(e).getCode(o);return n.code=a+"\n","property"===t?o:e.format(`${o}()`,r,t)}}const NS=(e,t=[],s="")=>{for(let e=0;ei.call(...e);return r.functionNode=i,r},CS=(e,t)=>NS(e,t,"glsl"),RS=(e,t)=>NS(e,t,"wgsl");class ES{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 BS extends ES{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class IS extends ES{constructor(e,t=new Ys){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class PS extends ES{constructor(e,t=new Ai){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class FS extends ES{constructor(e,t=new xi){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class US extends ES{constructor(e,t=new Xr){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class OS extends ES{constructor(e,t=new Zs){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class zS extends ES{constructor(e,t=new sr){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class LS extends BS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class VS extends IS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class DS extends PS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class kS extends FS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class GS extends US{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class WS extends OS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class jS extends zS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class HS extends zd{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}add(e){return this.nodes.push(e),this}If(e,t){const s=new _p(t);return this._currentCond=Ef(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new _p(t),i=Ef(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new _p(e),this}build(e,...t){const s=Bp();Ep(this);for(const t of this.nodes)t.build(e,"void");return Ep(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("TSL.StackNode: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("TSL.StackNode: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const qS=Ap(HS),$S=[.125,.215,.35,.446,.526,.582],XS=20,YS=new wl(-1,1,1,-1,0,1),ZS=new Hn(90,1),JS=new Xr;let KS=null,QS=0,eM=0;const tM=(1+Math.sqrt(5))/2,sM=1/tM,iM=[new Ai(-tM,sM,0),new Ai(tM,sM,0),new Ai(-sM,0,tM),new Ai(sM,0,tM),new Ai(0,tM,-sM),new Ai(0,tM,sM),new Ai(-1,1,-1),new Ai(1,1,-1),new Ai(-1,1,1),new Ai(1,1,1)],rM=[3,1,5,0,4,2],nM=Q_(My(),Sy("faceIndex")).normalize(),oM=Wp(nM.x,nM.y.negate(),nM.z);class aM{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}fromScene(e,t=0,s=.1,i=100){KS=this._renderer.getRenderTarget(),QS=this._renderer.getActiveCubeFace(),eM=this._renderer.getActiveMipmapLevel(),this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,s,i,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=cM(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=dM(),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())}_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?h=$S[a-e+4-1]:0===a&&(h=0),i.push(h);const u=1/(o-2),l=-u,c=1+u,d=[l,l,c,l,c,c,l,l,c,c,l,c],p=6,m=6,g=3,f=2,y=1,x=new Float32Array(g*m*p),b=new Float32Array(f*m*p),v=new Float32Array(y*m*p);for(let e=0;e2?0:-1,i=[t,s,0,t+2/3,s,0,t+2/3,s+1,0,t,s,0,t+2/3,s+1,0,t,s+1,0],r=rM[e];x.set(i,g*m*r),b.set(d,f*m*r);const n=[r,r,r,r,r,r];v.set(n,y*m*r)}const T=new Sn;T.setAttribute("position",new an(x,g)),T.setAttribute("uv",new an(b,f)),T.setAttribute("faceIndex",new an(v,y)),t.push(T),r.push(new On(T,null)),n>4&&n--}return{lodPlanes:t,sizeLods:s,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,s){const i=Ox(new Array(XS).fill(0)),r=dm(new Ai(0,1,0)),n=dm(0),o=Up(XS),a=dm(0),h=dm(1),u=By(null),l=dm(0),c=Up(1/t),d=Up(1/s),p=Up(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:oM,dTheta:n,samples:h,envMap:u,mipInt:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=lM("blur");return g.uniforms=m,g.fragmentNode=iw({...m,latitudinal:a.equal(1)}),g}(i,e,t)}return i}async _compileMaterial(e){const t=new On(this._lodPlanes[0],e);await this._renderer.compile(t,YS)}_sceneToCubeUV(e,t,s,i){const r=ZS;r.near=t,r.far=s;const n=[-1,1,-1,-1,-1,-1],o=[1,1,1,-1,-1,-1],a=this._renderer,h=a.autoClear;a.getClearColor(JS),a.autoClear=!1;let u=this._backgroundBox;if(null===u){const e=new Kr({name:"PMREM.Background",side:d,depthWrite:!1,depthTest:!1});u=new On(new Ln,e)}let l=!1;const c=e.background;c?c.isColor&&(u.material.color.copy(c),e.background=null,l=!0):(u.material.color.copy(JS),l=!0),a.setRenderTarget(i),a.clear(),l&&a.render(u,r);for(let t=0;t<6;t++){const s=t%3;0===s?(r.up.set(0,n[t],0),r.lookAt(o[t],0,0)):1===s?(r.up.set(0,0,n[t]),r.lookAt(0,o[t],0)):(r.up.set(0,n[t],0),r.lookAt(0,0,o[t]));const h=this._cubeSize;uM(i,s*h,t>2?h:0,h,h),a.render(e,r)}a.autoClear=h,e.background=c}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===he||e.mapping===ue;i?null===this._cubemapMaterial&&(this._cubemapMaterial=cM(e)):null===this._equirectMaterial&&(this._equirectMaterial=dM(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;uM(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,YS)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;tXS&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const g=[];let f=0;for(let e=0;ey-4?i-y+4:0),4*(this._cubeSize-x),3*x,2*x),a.setRenderTarget(t),a.render(u,YS)}}function hM(e,t,s){const i=new bi(e,t,s);return i.texture.mapping=de,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function uM(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function lM(e){const t=new pT;return t.depthTest=!1,t.depthWrite=!1,t.blending=m,t.name=`PMREM_${e}`,t}function cM(e){const t=lM("cubemap");return t.fragmentNode=Bx(e,oM),t}function dM(e){const t=lM("equirect");return t.fragmentNode=By(e,NT(oM),0),t}let pM=0;class mM{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=pM++}}const gM=new WeakMap,fM=new Map([[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),yM=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),xM=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class bM{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.monitor=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.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=qS(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new xS,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.useComparisonMethod=!1}getBindGroupsCache(){let e=gM.get(this.renderer);return void 0===e&&(e=new kw,gM.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new bi(e,t,s)}createCubeRenderTarget(e,t){return new CT(e,t)}createPMREMGenerator(){return new aM(this.renderer)}includes(e){return this.nodes.includes(e)}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let r,n=!0;for(const e of t)i.push(e),n=n&&!0!==e.groupNode.shared;return n?(r=s.get(i),void 0===r&&(r=new mM(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new mM(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},s=this.bindings;for(const e of Fd)for(const i in s[e]){const r=s[e][i];(t[i]||(t[i]=[])).push(...r)}e=[];for(const s in t){const i=t[s],r=this._getBindGroup(s,i);e.push(r)}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(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${xM(t.r)}, ${xM(t.g)}, ${xM(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>4&&t&&(t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' 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 s=this.attributes;for(const t of s)if(t.name===e)return t;const i=new dS(e,t);return s.push(i),i}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||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Ee)return"int";if(t===Be)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;const s=fM.get(e);return("float"===t?"":t[0])+s}getTypeFromArray(e){return yM.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof gn||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[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(){return this.stack=qS(this.stack),this.stacks.push(Bp()||this.stack),Ep(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Ep(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let i=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getData(e);return void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e);let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new dS("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeFromNode(e,t=this.shaderStage){const s=this.getDataFromNode(e,t);if(void 0===s.structType){const i=this.structs.index++;e.name=`StructType${i}`,this.structs[t].push(e),s.structType=e}return e}getUniformFromNode(e,t,s=this.shaderStage,i=null){const r=this.getDataFromNode(e,s,this.globalCache);let n=r.uniform;if(void 0===n){const o=this.uniforms.index++;n=new pS(i||"nodeUniform"+o,t,e),this.uniforms[s].push(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage){const r=this.getDataFromNode(e,i);let n=r.variable;if(void 0===n){const e=this.vars[i]||(this.vars[i]=[]);null===t&&(t="nodeVar"+e.length),n=new mS(t,s),e.push(n),r.variable=n}return n}getVaryingFromNode(e,t=null,s=e.getNodeType(this)){const i=this.getDataFromNode(e,"any");let r=i.varying;if(void 0===r){const e=this.varyings,n=e.length;null===t&&(t="nodeVarying"+n),r=new gS(t,s),e.push(r),i.varying=r}return r}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;r=new fS("nodeCode"+n,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,n=t;for(;n;){if(!0===i.get(n)){r=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(r)for(const e of s)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),n=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),n.set(s,!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),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}buildFunctionNode(e){const t=new AS,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[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)s[e.name]=new bS(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,r=this.cache,n=this.buildStage,o=this.stack,a={code:""};this.flow=a,this.vars={},this.cache=new xS,this.stack=qS();for(const s of Pd)this.setBuildStage(s),a.result=e.build(this,t);return a.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.cache=r,this.stack=o,this.setBuildStage(n),a}getFunctionOperator(){return null}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const r=this.shaderStage;this.setShaderStage(e);const n=this.flowChildNode(t,s);return null!==i&&(n.code+=`${this.tab+i} = ${n.result};\n`),this.flowCode[e]=this.flowCode[e]+n.code,this.setShaderStage(r),n}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t){return`${this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(void 0!==s)for(const e of s)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}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.")}build(){const{object:e,material:t,renderer:s}=this;if(null!==t){let e=s.nodes.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new pT),e.build(this)}else this.addFlow("compute",e);for(const e of Pd){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of Fd){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"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 LS(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new VS(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new DS(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new kS(e);if("color"===t)return new GS(e);if("mat3"===t)return new WS(e);if("mat4"===t)return new jS(e);throw new Error(`Uniform "${t}" not declared.`)}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const i=this.getTypeLength(t),r=this.getTypeLength(s);return 16===i&&9===r?`${this.getType(s)}(${e}[0].xyz, ${e}[1].xyz, ${e}[2].xyz)`:9===i&&4===r?`${this.getType(s)}(${e}[0].xy, ${e}[1].xy)`:i>4||r>4||0===r?e:i===r?`${this.getType(s)}( ${e} )`:i>r?this.format(`${e}.${"xyz".slice(0,r)}`,this.getTypeFromLength(r,this.getComponentType(t)),s):4===r&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${e} - Node System\n`}}class vM{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.startTime=null,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 s=e.get(t);return void 0===s&&(s={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(s,this.renderId)}else t===Ed.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(s,this.renderId)}else t===Ed.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.frameId&&!1!==e.update(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.renderId&&!1!==e.update(this)&&t.set(s,this.renderId)}else t===Ed.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 TM{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}TM.isNodeFunctionInput=!0;class _M extends zd{static get type(){return"StructTypeNode"}constructor(e){super(),this.types=e,this.isStructTypeNode=!0}getMemberTypes(){return this.types}}class wM extends zd{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}setup(e){super.setup(e);const t=this.members,s=[];for(let i=0;ir&&(i=s,r=n)}}this._candidateFnCall=s=i(...t)}return s}}const RM=Ap(CM),EM=e=>(...t)=>RM(e,...t);class BM extends zd{static get type(){return"SpriteSheetUVNode"}constructor(e,t=My(),s=Up(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=s}setup(){const{frameNode:e,uvNode:t,countNode:s}=this,{width:i,height:r}=s,n=e.mod(i.mul(r)).floor(),o=n.mod(i),a=r.sub(n.add(1).div(i).ceil()),h=s.reciprocal(),u=Vp(o,a);return t.add(u).mul(h)}}const IM=Ap(BM);class PM extends Ld{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}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.bufferObject&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let s;const i=e.context.assign;if(s=!1===e.isAvailable("storageBuffer")?!0===this.node.bufferObject&&!0!==i?e.generatePBO(this):this.node.build(e):super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}const FM=Ap(PM);class UM extends zd{static get type(){return"TriplanarTexturesNode"}constructor(e,t=null,s=null,i=Up(1),r=ox,n=fx){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=s,this.scaleNode=i,this.positionNode=r,this.normalNode=n}setup(){const{textureXNode:e,textureYNode:t,textureZNode:s,scaleNode:i,positionNode:r,normalNode:n}=this;let o=n.abs().normalize();o=o.div(o.dot(Wp(1)));const a=r.yz.mul(i),h=r.zx.mul(i),u=r.xy.mul(i),l=e.value,c=null!==t?t.value:l,d=null!==s?s.value:l,p=By(l,a).mul(o.x),m=By(c,h).mul(o.y),g=By(d,u).mul(o.z);return Ym(p,m,g)}}const OM=Ap(UM),zM=(...e)=>OM(...e),LM=new Yo,VM=new Ai,DM=new Ai,kM=new Ai,GM=new sr,WM=new Ai(0,0,-1),jM=new xi,HM=new Ai,qM=new Ai,$M=new xi,XM=new Ys,YM=new bi,ZM=Vv.flipX();YM.depthTexture=new Xa(1,1);let JM=!1;class KM extends Ey{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||YM.texture,ZM),this._reflectorBaseNode=e.reflector||new QM(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=wp(new KM({defaultTexture:YM.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._reflectorBaseNode=this._reflectorBaseNode,e}}class QM extends zd{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:s=new Rr,resolution:i=1,generateMipmaps:r=!1,bounces:n=!0,depth:o=!1}=t;this.textureNode=e,this.target=s,this.resolution=i,this.generateMipmaps=r,this.bounces=n,this.depth=o,this.updateBeforeType=n?Ed.RENDER:Ed.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new WeakMap}_updateResolution(e,t){const s=this.resolution;t.getDrawingBufferSize(XM),e.setSize(Math.round(XM.width*s),Math.round(XM.height*s))}setup(e){return this._updateResolution(YM,e.renderer),super.setup(e)}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 bi(0,0,{type:Pe}),!0===this.generateMipmaps&&(t.texture.minFilter=1008,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new Xa),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&JM)return;JM=!0;const{scene:t,camera:s,renderer:i,material:r}=e,{target:n}=this,o=this.getVirtualCamera(s),a=this.getRenderTarget(o);if(i.getDrawingBufferSize(XM),this._updateResolution(a,i),DM.setFromMatrixPosition(n.matrixWorld),kM.setFromMatrixPosition(s.matrixWorld),GM.extractRotation(n.matrixWorld),VM.set(0,0,1),VM.applyMatrix4(GM),HM.subVectors(DM,kM),HM.dot(VM)>0)return;HM.reflect(VM).negate(),HM.add(DM),GM.extractRotation(s.matrixWorld),WM.set(0,0,-1),WM.applyMatrix4(GM),WM.add(kM),qM.subVectors(DM,WM),qM.reflect(VM).negate(),qM.add(DM),o.coordinateSystem=s.coordinateSystem,o.position.copy(HM),o.up.set(0,1,0),o.up.applyMatrix4(GM),o.up.reflect(VM),o.lookAt(qM),o.near=s.near,o.far=s.far,o.updateMatrixWorld(),o.projectionMatrix.copy(s.projectionMatrix),LM.setFromNormalAndCoplanarPoint(VM,DM),LM.applyMatrix4(o.matrixWorldInverse),jM.set(LM.normal.x,LM.normal.y,LM.normal.z,LM.constant);const h=o.projectionMatrix;$M.x=(Math.sign(jM.x)+h.elements[8])/h.elements[0],$M.y=(Math.sign(jM.y)+h.elements[9])/h.elements[5],$M.z=-1,$M.w=(1+h.elements[10])/h.elements[14],jM.multiplyScalar(1/jM.dot($M));h.elements[2]=jM.x,h.elements[6]=jM.y,h.elements[10]=i.coordinateSystem===Os?jM.z-0:jM.z+1-0,h.elements[14]=jM.w,this.textureNode.value=a.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=a.depthTexture),r.visible=!1;const u=i.getRenderTarget(),l=i.getMRT();i.setMRT(null),i.setRenderTarget(a),i.render(t,o),i.setMRT(l),i.setRenderTarget(u),r.visible=!0,JM=!1}}const eA=e=>wp(new KM(e)),tA=new wl(-1,1,1,-1,0,1);class sA extends Sn{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new fn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new fn(t,2))}}const iA=new sA;class rA extends On{constructor(e=null){super(iA,e),this.camera=tA,this.isQuadMesh=!0}renderAsync(e){return e.renderAsync(this,tA)}render(e){e.render(this,tA)}}const nA=new Ys;class oA extends Ey{static get type(){return"RTTNode"}constructor(e,t=null,s=null,i={type:Pe}){const r=new bi(t,s,i);super(r.texture,My()),this.node=e,this.width=t,this.height=s,this.renderTarget=r,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this.updateMap=new WeakMap,this._rttNode=null,this._quadMesh=new rA(new pT),this.updateBeforeType=Ed.RENDER}get autoSize(){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 s=e*this.pixelRatio,i=t*this.pixelRatio;this.renderTarget.setSize(s,i),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.autoSize){this.pixelRatio=e.getPixelRatio();const t=e.getSize(nA);this.setSize(t.width,t.height)}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 Ey(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const aA=(e,...t)=>wp(new oA(wp(e),...t)),hA=(e,...t)=>e.isTextureNode?e:aA(e,...t);class uA extends wy{static get type(){return"VertexColorNode"}constructor(e=0){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 s;return s=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new xi(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const lA=(...e)=>wp(new uA(...e));class cA extends zd{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const dA=Np(cA);class pA extends zd{static get type(){return"SceneNode"}constructor(e=pA.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let i;return t===pA.BACKGROUND_BLURRINESS?i=Dx("backgroundBlurriness","float",s):t===pA.BACKGROUND_INTENSITY?i=Dx("backgroundIntensity","float",s):console.error("THREE.SceneNode: Unknown scope:",t),i}}pA.BACKGROUND_BLURRINESS="backgroundBlurriness",pA.BACKGROUND_INTENSITY="backgroundIntensity";const mA=Np(pA,pA.BACKGROUND_BLURRINESS),gA=Np(pA,pA.BACKGROUND_INTENSITY),fA="point-list",yA="line-list",xA="line-strip",bA="triangle-list",vA="triangle-strip",TA="never",_A="less",wA="equal",SA="less-equal",MA="greater",AA="not-equal",NA="greater-equal",CA="always",RA="store",EA="load",BA="clear",IA="ccw",PA="none",FA="front",UA="back",OA="uint16",zA="uint32",LA={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10uFloat:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Stencil8:"stencil8",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},VA="clamp-to-edge",DA="repeat",kA="mirror-repeat",GA="linear",WA="nearest",jA="zero",HA="one",qA="src",$A="one-minus-src",XA="src-alpha",YA="one-minus-src-alpha",ZA="dst",JA="one-minus-dst",KA="dst-alpha",QA="one-minus-dst-alpha",eN="src-alpha-saturated",tN="constant",sN="one-minus-constant",iN="add",rN="subtract",nN="reverse-subtract",oN="min",aN="max",hN=0,uN=15,lN="keep",cN="zero",dN="replace",pN="invert",mN="increment-clamp",gN="decrement-clamp",fN="increment-wrap",yN="decrement-wrap",xN="storage",bN="read-only-storage",vN="write-only",TN="read-only",_N="float",wN="unfilterable-float",SN="depth",MN="sint",AN="uint",NN="2d",CN="3d",RN="2d",EN="2d-array",BN="cube",IN="3d",PN="all",FN="vertex",UN="instance",ON={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class zN extends Ix{static get type(){return"StorageBufferNode"}constructor(e,t,s=0){super(e,t,s),this.isStorageBufferNode=!0,this.access=xN,this.isAtomic=!1,this.bufferObject=!1,this.bufferCount=s,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 FM(this,e)}setBufferObject(e){return this.bufferObject=e,this}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(bN)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=iy(this.value),this._varying=Vf(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}generate(e){if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:s}=this.getAttributeData(),i=s.build(e);return e.registerTransform(i,t),i}}const LN=(e,t,s)=>wp(new zN(e,t,s)),VN=(e,t,s)=>wp(new zN(e,t,s).setBufferObject(!0));class DN extends Ey{static get type(){return"StorageTextureNode"}constructor(e,t,s=null){super(e,t),this.storeNode=s,this.isStorageTextureNode=!0,this.access=vN}getInputType(){return"storageTexture"}setup(e){super.setup(e);e.getNodeProperties(this).storeNode=this.storeNode}setAccess(e){return this.access=e,this}generate(e,t){let s;return s=null!==this.storeNode?this.generateStore(e):super.generate(e,t),s}toReadOnly(){return this.setAccess(TN)}toWriteOnly(){return this.setAccess(vN)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:s,storeNode:i}=t,r=super.generate(e,"property"),n=s.build(e,"uvec2"),o=i.build(e,"vec4"),a=e.generateTextureStore(e,r,n,o);e.addLineFlowCode(a,this)}}const kN=Ap(DN),GN=(e,t,s)=>{const i=kN(e,t,s);return null!==s&&i.append(),i};class WN extends Vx{static get type(){return"UserDataNode"}constructor(e,t,s=null){super(e,t,s),this.userData=s}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const jN=(e,t,s)=>wp(new WN(e,t,s));class HN extends Dd{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 qN=Ap(HN);let $N=null;class XN extends Zv{static get type(){return"ViewportSharedTextureNode"}constructor(e=Vv,t=null){null===$N&&($N=new Wa),super(e,t,$N)}updateReference(){return this}}const YN=Ap(XN),ZN=new Ys;class JN extends Ey{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class KN extends JN{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class QN extends Dd{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new Xa;r.isRenderTargetTexture=!0,r.name="depth";const n=new bi(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Pe,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this.updateBeforeType=Ed.FRAME,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=dm(0),this._cameraFar=dm(0),this._mrt=null,this.isPassNode=!0}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}isGlobal(){return!0}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.isRenderTargetTexture=!0,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(),t.isRenderTargetTexture=!0,this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(this._textureNodes[e]=t=wp(new KN(this,e)),this._textureNodes[e].updateTexture()),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),this._previousTextureNodes[e]=t=wp(new KN(this,e,!0)),this._previousTextureNodes[e].updateTexture()),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=oT(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=iT(r,s,i)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,!0===e.backend.isWebGLBackend&&(this.renderTarget.samples=0),this.renderTarget.depthTexture.isMultisampleRenderTargetTexture=this.renderTarget.samples>1,this.scope===QN.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s,camera:i}=this;this._pixelRatio=t.getPixelRatio();const r=t.getSize(ZN);this.setSize(r.width,r.height);const n=t.getRenderTarget(),o=t.getMRT();this._cameraNear.value=i.near,this._cameraFar.value=i.far;for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(n),t.setMRT(o)}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}QN.COLOR="color",QN.DEPTH="depth";const eC=(e,t,s)=>wp(new QN(QN.COLOR,e,t,s)),tC=(e,t)=>wp(new JN(e,t)),sC=(e,t)=>wp(new QN(QN.DEPTH,e,t));class iC extends QN{static get type(){return"ToonOutlinePassNode"}constructor(e,t,s,i,r){super(QN.COLOR,e,t),this.colorNode=s,this.thicknessNode=i,this.alphaNode=r,this._materialCache=new WeakMap}updateBefore(e){const{renderer:t}=e,s=t.getRenderObjectFunction();t.setRenderObjectFunction(((e,s,i,r,n,o,a)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const h=this._getOutlineMaterial(n);t.renderObject(e,s,i,r,h,o,a)}t.renderObject(e,s,i,r,n,o,a)})),super.updateBefore(e),t.setRenderObjectFunction(s)}_createMaterial(){const e=new pT;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=d;const t=fx.negate(),s=Oy.mul(sx),i=Up(1),r=s.mul($p(ox,1)),n=s.mul($p(ox.add(t),1)),o=Ug(r.sub(n));return e.vertexNode=r.add(o.mul(this.thicknessNode).mul(r.w).mul(i)),e.colorNode=$p(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 rC=(e,t,s=new Xr(0,0,0),i=.003,r=1)=>wp(new iC(e,t,wp(s),wp(i),wp(r)));class nC extends zd{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outpuType=null,this.events=new zs,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:Up()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Ad(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?Nd(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 oC=Ap(nC);class aC extends Map{get(e,t=null,...s){if(this.has(e))return super.get(e);if(null!==t){const i=t(...s);return this.set(e,i),i}}}class hC{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 uC=new aC;class lC extends zd{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new aC,this._output=oC(),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 s=this._outputs;return void 0===s[e]?s[e]=oC(t):s[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const s=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),s[e]=t,s[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),s[e]=t,s[e].events.addEventListener("refresh",this.onRefresh)):void 0===s[e]?(s[e]=oC(t),s[e].events.addEventListener("refresh",this.onRefresh)):s[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 s=this.getObject()[e];if("function"==typeof s)return s(...t)}async callAsync(e,...t){const s=this.getObject()[e];if("function"==typeof s)return"AsyncFunction"===s.constructor.name?await s(...t):s(...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 hC(this),t=uC.get("THREE"),s=uC.get("TSL"),i=this.getMethod(this.codeNode),r=[e,this._local,uC,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,s];this._object=i(...r);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:Up()}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+" };",s="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],s),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=[bd(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const s in this.parameters)t.push(this.parameters[s].getCacheKey(e));return vd(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 cC=Ap(lC);class dC extends zd{static get type(){return"FogNode"}constructor(e,t){super("float"),this.isFogNode=!0,this.colorNode=e,this.factorNode=t}getViewZNode(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||lx.z).negate()}setup(){return this.factorNode}}const pC=Ap(dC);class mC extends dC{static get type(){return"FogRangeNode"}constructor(e,t,s){super(e),this.isFogRangeNode=!0,this.nearNode=t,this.farNode=s}setup(e){const t=this.getViewZNode(e);return Sf(this.nearNode,this.farNode,t)}}const gC=Ap(mC);class fC extends dC{static get type(){return"FogExp2Node"}constructor(e,t){super(e),this.isFogExp2Node=!0,this.densityNode=t}setup(e){const t=this.getViewZNode(e),s=this.densityNode;return s.mul(s,t,t).negate().exp().oneMinus()}}const yC=Ap(fC);let xC=null,bC=null;class vC extends zd{static get type(){return"RangeNode"}constructor(e=Up(),t=Up()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Sd(this.minNode.value)),s=e.getTypeLength(Sd(this.maxNode.value));return t>s?t:s}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let s=null;if(t.count>1){const i=this.minNode.value,r=this.maxNode.value,n=e.getTypeLength(Sd(i)),o=e.getTypeLength(Sd(r));xC=xC||new xi,bC=bC||new xi,xC.setScalar(0),bC.setScalar(0),1===n?xC.setScalar(i):i.isColor?xC.set(i.r,i.g,i.b):xC.set(i.x,i.y,i.z||0,i.w||0),1===o?bC.setScalar(r):r.isColor?bC.set(r.r,r.g,r.b):bC.set(r.x,r.y,r.z||0,r.w||0);const a=4,h=a*t.count,u=new Float32Array(h);for(let e=0;eBy(e,t.xy).compare(t.z))),wC=Cp((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>By(e,t).compare(s),r=Dx("mapSize","vec2",s).setGroup(um),n=Dx("radius","float",s).setGroup(um),o=Vp(1).div(r),a=o.x.negate().mul(n),h=o.y.negate().mul(n),u=o.x.mul(n),l=o.y.mul(n),c=a.div(2),d=h.div(2),p=u.div(2),m=l.div(2);return Ym(i(t.xy.add(Vp(a,h)),t.z),i(t.xy.add(Vp(0,h)),t.z),i(t.xy.add(Vp(u,h)),t.z),i(t.xy.add(Vp(c,d)),t.z),i(t.xy.add(Vp(0,d)),t.z),i(t.xy.add(Vp(p,d)),t.z),i(t.xy.add(Vp(a,0)),t.z),i(t.xy.add(Vp(c,0)),t.z),i(t.xy,t.z),i(t.xy.add(Vp(p,0)),t.z),i(t.xy.add(Vp(u,0)),t.z),i(t.xy.add(Vp(c,m)),t.z),i(t.xy.add(Vp(0,m)),t.z),i(t.xy.add(Vp(p,m)),t.z),i(t.xy.add(Vp(a,l)),t.z),i(t.xy.add(Vp(0,l)),t.z),i(t.xy.add(Vp(u,l)),t.z)).mul(1/17)})),SC=Cp((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>By(e,t).compare(s),r=Dx("mapSize","vec2",s).setGroup(um),n=Vp(1).div(r),o=n.x,a=n.y,h=t.xy,u=Og(h.mul(r).add(.5));return h.subAssign(u.mul(n)),Ym(i(h,t.z),i(h.add(Vp(o,0)),t.z),i(h.add(Vp(0,a)),t.z),i(h.add(n),t.z),vf(i(h.add(Vp(o.negate(),0)),t.z),i(h.add(Vp(o.mul(2),0)),t.z),u.x),vf(i(h.add(Vp(o.negate(),a)),t.z),i(h.add(Vp(o.mul(2),a)),t.z),u.x),vf(i(h.add(Vp(0,a.negate())),t.z),i(h.add(Vp(0,a.mul(2))),t.z),u.y),vf(i(h.add(Vp(o,a.negate())),t.z),i(h.add(Vp(o,a.mul(2))),t.z),u.y),vf(vf(i(h.add(Vp(o.negate(),a.negate())),t.z),i(h.add(Vp(o.mul(2),a.negate())),t.z),u.x),vf(i(h.add(Vp(o.negate(),a.mul(2))),t.z),i(h.add(Vp(o.mul(2),a.mul(2))),t.z),u.x),u.y)).mul(1/9)})),MC=Cp((({depthTexture:e,shadowCoord:t})=>{const s=Up(1).toVar(),i=By(e).uv(t.xy).rg,r=af(t.z,i.x);return Ip(r.notEqual(Up(1)),(()=>{const e=t.z.sub(i.x),n=nf(0,i.y.mul(i.y));let o=n.div(n.add(e.mul(e)));o=Tf(Zm(o,.3).div(.95-.3)),s.assign(Tf(nf(r,o)))})),s})),AC=Cp((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Up(0).toVar(),n=Up(0).toVar(),o=e.lessThanEqual(Up(1)).select(Up(0),Up(2).div(e.sub(1))),a=e.lessThanEqual(Up(1)).select(Up(0),Up(-1));xv({start:Op(0),end:Op(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Up(e).mul(o)),u=i.uv(Ym(kv.xy,Vp(0,h).mul(t)).div(s)).x;r.addAssign(u),n.addAssign(u.mul(u))})),r.divAssign(e),n.divAssign(e);const h=Bg(n.sub(r.mul(r)));return Vp(r,h)})),NC=Cp((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Up(0).toVar(),n=Up(0).toVar(),o=e.lessThanEqual(Up(1)).select(Up(0),Up(2).div(e.sub(1))),a=e.lessThanEqual(Up(1)).select(Up(0),Up(-1));xv({start:Op(0),end:Op(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Up(e).mul(o)),u=i.uv(Ym(kv.xy,Vp(h,0).mul(t)).div(s));r.addAssign(u.x),n.addAssign(Ym(u.y.mul(u.y),u.x.mul(u.x)))})),r.divAssign(e),n.divAssign(e);const h=Bg(n.sub(r.mul(r)));return Vp(r,h)})),CC=[_C,wC,SC,MC];let RC=null;const EC=new rA;class BC extends zd{static get type(){return"ShadowNode"}constructor(e,t=null){super(),this.light=e,this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this.updateBeforeType=Ed.RENDER,this._node=null,this.isShadowNode=!0}setupShadow(e){const{object:t,renderer:s}=e;null===RC&&(RC=new pT,RC.fragmentNode=$p(0,0,0,1),RC.isShadowNodeMaterial=!0,RC.name="ShadowMaterial");const i=this.shadow,r=s.shadowMap.type,n=new Xa(i.mapSize.width,i.mapSize.height);n.compareFunction=ys;const o=e.createRenderTarget(i.mapSize.width,i.mapSize.height);if(o.depthTexture=n,i.camera.updateProjectionMatrix(),3===r){n.compareFunction=null,this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$e,type:Pe}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$e,type:Pe});const t=By(n),s=By(this.vsmShadowMapVertical.texture),r=Dx("blurSamples","float",i).setGroup(um),o=Dx("radius","float",i).setGroup(um),a=Dx("mapSize","vec2",i).setGroup(um);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new pT);h.fragmentNode=AC({samples:r,radius:o,size:a,shadowPass:t}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new pT),h.fragmentNode=NC({samples:r,radius:o,size:a,shadowPass:s}).context(e.getSharedContext()),h.name="VSMHorizontal"}const a=Dx("intensity","float",i).setGroup(um),h=Dx("bias","float",i).setGroup(um),u=Dx("normalBias","float",i).setGroup(um),l=t.material.shadowPositionNode||hx;let c,d=dm(i.matrix).setGroup(um).mul(l.add(Tx.mul(u)));if(i.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)d=d.xyz.div(d.w),c=d.z,s.coordinateSystem===Os&&(c=c.mul(2).sub(1));else{const e=d.w;d=d.xy.div(e);const t=dm("float").onRenderUpdate((()=>i.camera.near)),s=dm("float").onRenderUpdate((()=>i.camera.far));c=aT(e,t,s)}d=Wp(d.x,d.y.oneMinus(),c.add(h));const p=d.x.greaterThanEqual(0).and(d.x.lessThanEqual(1)).and(d.y.greaterThanEqual(0)).and(d.y.lessThanEqual(1)).and(d.z.lessThanEqual(1)),m=i.filterNode||CC[s.shadowMap.type]||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const g=By(o.texture,d),f=p.select(m({depthTexture:3===r?this.vsmShadowMapHorizontal.texture:n,shadowCoord:d,shadow:i}),Up(1));return this.shadowMap=o,this.shadow.map=o,vf(1,f.rgb.mix(g,1),a.mul(g.a))}setup(e){if(!1!==e.renderer.shadowMap.enabled)return null!==this._node?this._node:this._node=this.setupShadow(e)}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:o}=e,a=r.shadowMap.type,h=t.depthTexture.version;this._depthVersionCached=h;const u=n.overrideMaterial;n.overrideMaterial=RC,t.setSize(i.mapSize.width,i.mapSize.height),i.updateMatrices(s),i.camera.layers.mask=o.layers.mask;const l=r.getRenderTarget(),c=r.getRenderObjectFunction();r.setRenderObjectFunction(((e,...t)=>{(!0===e.castShadow||e.receiveShadow&&3===a)&&r.renderObject(e,...t)})),r.setRenderTarget(t),r.render(n,i.camera),r.setRenderObjectFunction(c),!0!==s.isPointLight&&3===a&&this.vsmPass(r),r.setRenderTarget(l),n.overrideMaterial=u}vsmPass(e){const{shadow:t}=this;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height),e.setRenderTarget(this.vsmShadowMapVertical),EC.material=this.vsmMaterialVertical,EC.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),EC.material=this.vsmMaterialHorizontal,EC.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),this.updateBeforeType=Ed.NONE}updateBefore(e){const{shadow:t}=this;(t.needsUpdate||t.autoUpdate)&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const IC=(e,t)=>wp(new BC(e,t));class PC extends Bv{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.updateType=Ed.FRAME,this.light=e,this.color=new Xr,this.colorNode=dm(this.color).setGroup(um),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0}getCacheKey(){return Td(super.getCacheKey(),this.light.id,this.light.castShadow?1:0)}getHash(){return this.light.uuid}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const e=IC(this.light);this.shadowNode=e,this.shadowColorNode=s=this.colorNode.mul(e),this.baseColorNode=this.colorNode}this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&this.shadowNode.dispose()}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const FC=Cp((e=>{const{lightDistance:t,cutoffDistance:s,decayExponent:i}=e,r=t.pow(i).max(.01).reciprocal();return s.greaterThan(0).select(r.mul(t.div(s).pow4().oneMinus().clamp().pow2()),r)}));let UC;function OC(e){UC=UC||new WeakMap;let t=UC.get(e);return void 0===t&&UC.set(e,t={}),t}function zC(e){const t=OC(e);return t.position||(t.position=dm(new Ai).setGroup(um).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld))))}function LC(e){const t=OC(e);return t.targetPosition||(t.targetPosition=dm(new Ai).setGroup(um).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld))))}function VC(e){const t=OC(e);return t.viewPosition||(t.viewPosition=dm(new Ai).setGroup(um).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new Ai,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}const DC=e=>Ly.transformDirection(zC(e).sub(LC(e))),kC=Cp((([e])=>{const t=e.toUint().mul(747796405).add(2891336453),s=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return s.shiftRight(22).bitXor(s).toFloat().mul(1/2**32)})),GC=(e,t)=>pf(Jm(4,e.mul(Zm(1,e))),t),WC=(e,t)=>e.lessThan(.5)?GC(e.mul(2),t).div(2):Zm(1,GC(Jm(Zm(1,e),2),t).div(2)),jC=(e,t,s)=>pf(Km(pf(e,t),Ym(pf(e,t),pf(Zm(1,e),s))),1/t),HC=(e,t)=>zg(vg.mul(t.mul(e).sub(1))).div(vg.mul(t.mul(e).sub(1))),qC=Cp((([e])=>e.fract().sub(.5).abs())).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),$C=Cp((([e])=>Wp(qC(e.z.add(qC(e.y.mul(1)))),qC(e.z.add(qC(e.x.mul(1)))),qC(e.y.add(qC(e.x.mul(1))))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),XC=Cp((([e,t,s])=>{const i=Wp(e).toVar(),r=Up(1.4).toVar(),n=Up(0).toVar(),o=Wp(i).toVar();return xv({start:Up(0),end:Up(3),type:"float",condition:"<="},(()=>{const e=Wp($C(o.mul(2))).toVar();i.addAssign(e.add(s.mul(Up(.1).mul(t)))),o.mulAssign(1.8),r.mulAssign(1.5),i.mulAssign(1.2);const a=Up(qC(i.z.add(qC(i.x.add(qC(i.y)))))).toVar();n.addAssign(a.div(r)),o.addAssign(.14)})),n})).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"p",type:"vec3"},{name:"spd",type:"float"},{name:"time",type:"float"}]}),YC=dm(0).setGroup(um).onRenderUpdate((e=>e.time)),ZC=dm(0).setGroup(um).onRenderUpdate((e=>e.deltaTime)),JC=dm(0,"uint").setGroup(um).onRenderUpdate((e=>e.frameId)),KC=(e=1)=>(console.warn('TSL: timerLocal() is deprecated. Use "time" instead.'),YC.mul(e)),QC=(e=1)=>(console.warn('TSL: timerGlobal() is deprecated. Use "time" instead.'),YC.mul(e)),eR=(e=1)=>(console.warn('TSL: timerDelta() is deprecated. Use "deltaTime" instead.'),ZC.mul(e)),tR=(e=YC)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),sR=(e=YC)=>e.fract().round(),iR=(e=YC)=>e.add(.5).fract().mul(2).sub(1).abs(),rR=(e=YC)=>e.fract(),nR=Cp((([e,t,s=Vp(.5)])=>Ew(e.sub(s),t).add(s))),oR=Cp((([e,t,s=Vp(.5)])=>{const i=e.sub(s),r=i.dot(i),n=r.mul(r).mul(t);return e.add(i.mul(n))})),aR=Cp((({position:e=null,horizontal:t=!0,vertical:s=!1})=>{let i;null!==e?(i=Zy.toVar(),i[3][0]=e.x,i[3][1]=e.y,i[3][2]=e.z):i=Zy;const r=Ly.mul(i);return vp(t)&&(r[0][0]=Zy[0].length(),r[0][1]=0,r[0][2]=0),vp(s)&&(r[1][0]=0,r[1][1]=Zy[1].length(),r[1][2]=0),r[2][0]=0,r[2][1]=0,r[2][2]=1,Oy.mul(r).mul(ox)})),hR=Cp((([e=null])=>{const t=lT();return lT(tT(e)).sub(t).lessThan(0).select(Vv,e)})),uR=Cp((([e,t,s],i)=>{let r;i.renderer.coordinateSystem===Os?(e=Vp(e.x,e.y.oneMinus()).mul(2).sub(1),r=$p(Wp(e,t),1)):r=$p(Wp(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=$p(s.mul(r));return n.xyz.div(n.w)})),lR=Cp((([e,t])=>{const s=t.mul($p(e,1)),i=s.xy.div(s.w).mul(.5).add(.5).toVar();return Vp(i.x,i.y.oneMinus())})),cR=new WeakMap;class dR extends Dd{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.updateType=Ed.OBJECT,this.updateAfterType=Ed.OBJECT,this.previousModelWorldMatrix=dm(new sr),this.previousProjectionMatrix=dm(new sr).setGroup(um),this.previousCameraViewMatrix=dm(new sr)}update({frameId:e,camera:t,object:s}){const i=mR(s);this.previousModelWorldMatrix.value.copy(i);const r=pR(t);r.frameId!==e&&(r.frameId=e,void 0===r.previousProjectionMatrix?(r.previousProjectionMatrix=new sr,r.previousCameraViewMatrix=new sr,r.currentProjectionMatrix=new sr,r.currentCameraViewMatrix=new sr,r.previousProjectionMatrix.copy(t.projectionMatrix),r.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(r.previousProjectionMatrix.copy(r.currentProjectionMatrix),r.previousCameraViewMatrix.copy(r.currentCameraViewMatrix)),r.currentProjectionMatrix.copy(t.projectionMatrix),r.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(r.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(r.previousCameraViewMatrix))}updateAfter({object:e}){mR(e).copy(e.matrixWorld)}setup(){const e=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),t=Oy.mul(sx).mul(ox),s=this.previousProjectionMatrix.mul(e).mul(ax),i=t.xy.div(t.w),r=s.xy.div(s.w);return Zm(i,r)}}function pR(e){let t=cR.get(e);return void 0===t&&(t={},cR.set(e,t)),t}function mR(e,t=0){const s=pR(e);let i=s[t];return void 0===i&&(s[t]=i=new sr),i}const gR=Np(dR),fR=Cp((([e,t])=>rf(1,e.oneMinus().div(t)).oneMinus())).setLayout({name:"burnBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),yR=Cp((([e,t])=>rf(e.div(t.oneMinus()),1))).setLayout({name:"dodgeBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),xR=Cp((([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus())).setLayout({name:"screenBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),bR=Cp((([e,t])=>vf(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),af(.5,e)))).setLayout({name:"overlayBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),vR=Cp((([e])=>SR(e.rgb))),TR=Cp((([e,t=Up(1)])=>t.mix(SR(e.rgb),e.rgb))),_R=Cp((([e,t=Up(1)])=>{const s=Ym(e.r,e.g,e.b).div(3),i=e.r.max(e.g.max(e.b)),r=i.sub(s).mul(t).mul(-3);return vf(e.rgb,i,r)})),wR=Cp((([e,t=Up(1)])=>{const s=Wp(.57735,.57735,.57735),i=t.cos();return Wp(e.rgb.mul(i).add(s.cross(e.rgb).mul(t.sin()).add(s.mul(cf(s,e.rgb).mul(i.oneMinus())))))})),SR=(e,t=Wp(ii.getLuminanceCoefficients(new Ai)))=>cf(e,t),MR=(e,t)=>vf(Wp(0),e,SR(e).sub(t).max(0)),AR=Cp((([e,t=Wp(1),s=Wp(0),i=Wp(1),r=Up(1),n=Wp(ii.getLuminanceCoefficients(new Ai,Jt))])=>{const o=e.rgb.dot(Wp(n)),a=nf(e.rgb.mul(t).add(s),0).toVar(),h=a.pow(i).toVar();return Ip(a.r.greaterThan(0),(()=>{a.r.assign(h.r)})),Ip(a.g.greaterThan(0),(()=>{a.g.assign(h.g)})),Ip(a.b.greaterThan(0),(()=>{a.b.assign(h.b)})),a.assign(o.add(a.sub(o).mul(r))),$p(a.rgb,e.a)})),NR=Cp((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return vf(t,s,i)})).setLayout({name:"sRGBToLinearSRGB",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),CR=Cp((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return vf(t,s,i)})).setLayout({name:"linearSRGBTosRGB",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),RR=Cp((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),ER=Cp((([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"}]}),BR=Cp((([e,t])=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(i).pow(2.2)})).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),IR=Cp((([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)})),PR=Cp((([e,t])=>{const s=Kp(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Kp(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=IR(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),FR=Kp(Wp(1.6605,-.1246,-.0182),Wp(-.5876,1.1329,-.1006),Wp(-.0728,-.0083,1.1187)),UR=Kp(Wp(.6274,.0691,.0164),Wp(.3293,.9195,.088),Wp(.0433,.0113,.8956)),OR=Cp((([e])=>{const t=Wp(e).toVar(),s=Wp(t.mul(t)).toVar(),i=Wp(s.mul(s)).toVar();return Up(15.5).mul(i.mul(s)).sub(Jm(40.14,i.mul(t))).add(Jm(31.96,i).sub(Jm(6.868,s.mul(t))).add(Jm(.4298,s).add(Jm(.1191,t).sub(.00232))))})),zR=Cp((([e,t])=>{const s=Wp(e).toVar(),i=Kp(Wp(.856627153315983,.137318972929847,.11189821299995),Wp(.0951212405381588,.761241990602591,.0767994186031903),Wp(.0482516061458583,.101439036467562,.811302368396859)),r=Kp(Wp(1.1271005818144368,-.1413297634984383,-.14132976349843826),Wp(-.11060664309660323,1.157823702216272,-.11060664309660294),Wp(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Up(-12.47393),o=Up(4.026069);return s.mulAssign(t),s.assign(UR.mul(s)),s.assign(i.mul(s)),s.assign(nf(s,1e-10)),s.assign(Eg(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(Tf(s,0,1)),s.assign(OR(s)),s.assign(r.mul(s)),s.assign(pf(nf(Wp(0),s),Wp(2.2))),s.assign(FR.mul(s)),s.assign(Tf(s,0,1)),s})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),LR=Cp((([e,t])=>{const s=Up(.76),i=Up(.15);e=e.mul(t);const r=rf(e.r,rf(e.g,e.b)),n=Ef(r.lessThan(.08),r.sub(Jm(6.25,r.mul(r))),.04);e.subAssign(n);const o=nf(e.r,nf(e.g,e.b));Ip(o.lessThan(s),(()=>e));const a=Zm(1,s),h=Zm(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(h.div(o));const u=Zm(1,Km(1,i.mul(o.sub(h)).add(1)));return vf(e,Wp(h),u)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class VR extends zd{static get type(){return"ComputeBuiltinNode"}constructor(e,t){super(t),this._builtinName=e}getHash(e){return this.getBuiltinName(e)}getNodeType(){return this.nodeType}setBuiltinName(e){return this._builtinName=e,this}getBuiltinName(){return this._builtinName}hasBuiltin(e){e.hasBuiltin(this._builtinName)}generate(e,t){const s=this.getBuiltinName(e),i=this.getNodeType(e);return"compute"===e.shaderStage?e.format(s,i,t):(console.warn(`ComputeBuiltinNode: Compute built-in value ${s} can not be accessed in the ${e.shaderStage} stage`),e.generateConst(i))}serialize(e){super.serialize(e),e.global=this.global,e._builtinName=this._builtinName}deserialize(e){super.deserialize(e),this.global=e.global,this._builtinName=e._builtinName}}const DR=(e,t)=>wp(new VR(e,t)),kR=DR("numWorkgroups","uvec3"),GR=DR("workgroupId","uvec3"),WR=DR("localId","uvec3"),jR=DR("subgroupSize","uint");const HR=Ap(class extends zd{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;!0===s.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}}),qR=()=>HR("workgroup").append(),$R=()=>HR("storage").append(),XR=()=>HR("texture").append();class YR extends Ld{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let s;const i=e.context.assign;if(s=super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}class ZR extends zd{constructor(e,t,s=0){super(t),this.bufferType=t,this.bufferCount=s,this.isWorkgroupInfoNode=!0,this.scope=e}label(e){return this.name=e,this}getHash(){return this.uuid}setScope(e){return this.scope=e,this}getInputType(){return`${this.scope}Array`}element(e){return wp(new YR(this,e))}generate(e){return e.getScopedArray(this.name||`${this.scope}Array_${this.id}`,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}const JR=(e,t)=>wp(new ZR("Workgroup",e,t));class KR extends Dd{static get type(){return"AtomicFunctionNode"}constructor(e,t,s,i=null){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.storeNode=i}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=this.method,s=this.getNodeType(e),i=this.getInputType(e),r=this.pointerNode,n=this.valueNode,o=[];o.push(`&${r.build(e,i)}`),o.push(n.build(e,i));const a=`${e.getMethod(t,s)}( ${o.join(", ")} )`;if(null!==this.storeNode){const t=this.storeNode.build(e,i);e.addLineFlowCode(`${t} = ${a}`,this)}else e.addLineFlowCode(a,this)}}KR.ATOMIC_LOAD="atomicLoad",KR.ATOMIC_STORE="atomicStore",KR.ATOMIC_ADD="atomicAdd",KR.ATOMIC_SUB="atomicSub",KR.ATOMIC_MAX="atomicMax",KR.ATOMIC_MIN="atomicMin",KR.ATOMIC_AND="atomicAnd",KR.ATOMIC_OR="atomicOr",KR.ATOMIC_XOR="atomicXor";const QR=Ap(KR),eE=(e,t,s,i)=>{const r=QR(e,t,s,i);return r.append(),r},tE=(e,t,s=null)=>eE(KR.ATOMIC_STORE,e,t,s),sE=(e,t,s=null)=>eE(KR.ATOMIC_ADD,e,t,s),iE=(e,t,s=null)=>eE(KR.ATOMIC_SUB,e,t,s),rE=(e,t,s=null)=>eE(KR.ATOMIC_MAX,e,t,s),nE=(e,t,s=null)=>eE(KR.ATOMIC_MIN,e,t,s),oE=(e,t,s=null)=>eE(KR.ATOMIC_AND,e,t,s),aE=(e,t,s=null)=>eE(KR.ATOMIC_OR,e,t,s),hE=(e,t,s=null)=>eE(KR.ATOMIC_XOR,e,t,s),uE=Cp((([e=t()])=>{const t=e.mul(2),s=t.x.floor(),i=t.y.floor();return s.add(i).mod(2).sign()})),lE=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=Lp(e).toVar();return Ef(n,r,i)})).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),cE=Cp((([e,t])=>{const s=Lp(t).toVar(),i=Up(e).toVar();return Ef(s,i.negate(),i)})).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),dE=Cp((([e])=>{const t=Up(e).toVar();return Op(Pg(t))})).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),pE=Cp((([e,t])=>{const s=Up(e).toVar();return t.assign(dE(s)),s.sub(Up(t))})),mE=EM([Cp((([e,t,s,i,r,n])=>{const o=Up(n).toVar(),a=Up(r).toVar(),h=Up(i).toVar(),u=Up(s).toVar(),l=Up(t).toVar(),c=Up(e).toVar(),d=Up(Zm(1,a)).toVar();return Zm(1,o).mul(c.mul(d).add(l.mul(a))).add(o.mul(u.mul(d).add(h.mul(a))))})).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"}]}),Cp((([e,t,s,i,r,n])=>{const o=Up(n).toVar(),a=Up(r).toVar(),h=Wp(i).toVar(),u=Wp(s).toVar(),l=Wp(t).toVar(),c=Wp(e).toVar(),d=Up(Zm(1,a)).toVar();return Zm(1,o).mul(c.mul(d).add(l.mul(a))).add(o.mul(u.mul(d).add(h.mul(a))))})).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"}]})]),gE=EM([Cp((([e,t,s,i,r,n,o,a,h,u,l])=>{const c=Up(l).toVar(),d=Up(u).toVar(),p=Up(h).toVar(),m=Up(a).toVar(),g=Up(o).toVar(),f=Up(n).toVar(),y=Up(r).toVar(),x=Up(i).toVar(),b=Up(s).toVar(),v=Up(t).toVar(),T=Up(e).toVar(),_=Up(Zm(1,p)).toVar(),w=Up(Zm(1,d)).toVar();return Up(Zm(1,c)).toVar().mul(w.mul(T.mul(_).add(v.mul(p))).add(d.mul(b.mul(_).add(x.mul(p))))).add(c.mul(w.mul(y.mul(_).add(f.mul(p))).add(d.mul(g.mul(_).add(m.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"}]}),Cp((([e,t,s,i,r,n,o,a,h,u,l])=>{const c=Up(l).toVar(),d=Up(u).toVar(),p=Up(h).toVar(),m=Wp(a).toVar(),g=Wp(o).toVar(),f=Wp(n).toVar(),y=Wp(r).toVar(),x=Wp(i).toVar(),b=Wp(s).toVar(),v=Wp(t).toVar(),T=Wp(e).toVar(),_=Up(Zm(1,p)).toVar(),w=Up(Zm(1,d)).toVar();return Up(Zm(1,c)).toVar().mul(w.mul(T.mul(_).add(v.mul(p))).add(d.mul(b.mul(_).add(x.mul(p))))).add(c.mul(w.mul(y.mul(_).add(f.mul(p))).add(d.mul(g.mul(_).add(m.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"}]})]),fE=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=zp(e).toVar(),o=zp(n.bitAnd(zp(7))).toVar(),a=Up(lE(o.lessThan(zp(4)),r,i)).toVar(),h=Up(Jm(2,lE(o.lessThan(zp(4)),i,r))).toVar();return cE(a,Lp(o.bitAnd(zp(1)))).add(cE(h,Lp(o.bitAnd(zp(2)))))})).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),yE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Up(t).toVar(),a=zp(e).toVar(),h=zp(a.bitAnd(zp(15))).toVar(),u=Up(lE(h.lessThan(zp(8)),o,n)).toVar(),l=Up(lE(h.lessThan(zp(4)),n,lE(h.equal(zp(12)).or(h.equal(zp(14))),o,r))).toVar();return cE(u,Lp(h.bitAnd(zp(1)))).add(cE(l,Lp(h.bitAnd(zp(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"}]}),xE=EM([fE,yE]),bE=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=Hp(e).toVar();return Wp(xE(n.x,r,i),xE(n.y,r,i),xE(n.z,r,i))})).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),vE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Up(t).toVar(),a=Hp(e).toVar();return Wp(xE(a.x,o,n,r),xE(a.y,o,n,r),xE(a.z,o,n,r))})).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"}]}),TE=EM([bE,vE]),_E=Cp((([e])=>{const t=Up(e).toVar();return Jm(.6616,t)})).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),wE=Cp((([e])=>{const t=Up(e).toVar();return Jm(.982,t)})).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),SE=EM([_E,Cp((([e])=>{const t=Wp(e).toVar();return Jm(.6616,t)})).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),ME=EM([wE,Cp((([e])=>{const t=Wp(e).toVar();return Jm(.982,t)})).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),AE=Cp((([e,t])=>{const s=Op(t).toVar(),i=zp(e).toVar();return i.shiftLeft(s).bitOr(i.shiftRight(Op(32).sub(s)))})).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),NE=Cp((([e,t,s])=>{e.subAssign(s),e.bitXorAssign(AE(s,Op(4))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(AE(e,Op(6))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(AE(t,Op(8))),t.addAssign(e),e.subAssign(s),e.bitXorAssign(AE(s,Op(16))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(AE(e,Op(19))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(AE(t,Op(4))),t.addAssign(e)})),CE=Cp((([e,t,s])=>{const i=zp(s).toVar(),r=zp(t).toVar(),n=zp(e).toVar();return i.bitXorAssign(r),i.subAssign(AE(r,Op(14))),n.bitXorAssign(i),n.subAssign(AE(i,Op(11))),r.bitXorAssign(n),r.subAssign(AE(n,Op(25))),i.bitXorAssign(r),i.subAssign(AE(r,Op(16))),n.bitXorAssign(i),n.subAssign(AE(i,Op(4))),r.bitXorAssign(n),r.subAssign(AE(n,Op(14))),i.bitXorAssign(r),i.subAssign(AE(r,Op(24))),i})).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),RE=Cp((([e])=>{const t=zp(e).toVar();return Up(t).div(Up(zp(Op(4294967295))))})).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),EE=Cp((([e])=>{const t=Up(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"}]}),BE=EM([Cp((([e])=>{const t=Op(e).toVar(),s=zp(zp(1)).toVar(),i=zp(zp(Op(3735928559)).add(s.shiftLeft(zp(2))).add(zp(13))).toVar();return CE(i.add(zp(t)),i,i)})).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),Cp((([e,t])=>{const s=Op(t).toVar(),i=Op(e).toVar(),r=zp(zp(2)).toVar(),n=zp().toVar(),o=zp().toVar(),a=zp().toVar();return n.assign(o.assign(a.assign(zp(Op(3735928559)).add(r.shiftLeft(zp(2))).add(zp(13))))),n.addAssign(zp(i)),o.addAssign(zp(s)),CE(n,o,a)})).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Op(t).toVar(),n=Op(e).toVar(),o=zp(zp(3)).toVar(),a=zp().toVar(),h=zp().toVar(),u=zp().toVar();return a.assign(h.assign(u.assign(zp(Op(3735928559)).add(o.shiftLeft(zp(2))).add(zp(13))))),a.addAssign(zp(n)),h.addAssign(zp(r)),u.addAssign(zp(i)),CE(a,h,u)})).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Cp((([e,t,s,i])=>{const r=Op(i).toVar(),n=Op(s).toVar(),o=Op(t).toVar(),a=Op(e).toVar(),h=zp(zp(4)).toVar(),u=zp().toVar(),l=zp().toVar(),c=zp().toVar();return u.assign(l.assign(c.assign(zp(Op(3735928559)).add(h.shiftLeft(zp(2))).add(zp(13))))),u.addAssign(zp(a)),l.addAssign(zp(o)),c.addAssign(zp(n)),NE(u,l,c),u.addAssign(zp(r)),CE(u,l,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"}]}),Cp((([e,t,s,i,r])=>{const n=Op(r).toVar(),o=Op(i).toVar(),a=Op(s).toVar(),h=Op(t).toVar(),u=Op(e).toVar(),l=zp(zp(5)).toVar(),c=zp().toVar(),d=zp().toVar(),p=zp().toVar();return c.assign(d.assign(p.assign(zp(Op(3735928559)).add(l.shiftLeft(zp(2))).add(zp(13))))),c.addAssign(zp(u)),d.addAssign(zp(h)),p.addAssign(zp(a)),NE(c,d,p),c.addAssign(zp(o)),d.addAssign(zp(n)),CE(c,d,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"}]})]),IE=EM([Cp((([e,t])=>{const s=Op(t).toVar(),i=Op(e).toVar(),r=zp(BE(i,s)).toVar(),n=Hp().toVar();return n.x.assign(r.bitAnd(Op(255))),n.y.assign(r.shiftRight(Op(8)).bitAnd(Op(255))),n.z.assign(r.shiftRight(Op(16)).bitAnd(Op(255))),n})).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Op(t).toVar(),n=Op(e).toVar(),o=zp(BE(n,r,i)).toVar(),a=Hp().toVar();return a.x.assign(o.bitAnd(Op(255))),a.y.assign(o.shiftRight(Op(8)).bitAnd(Op(255))),a.z.assign(o.shiftRight(Op(16)).bitAnd(Op(255))),a})).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),PE=EM([Cp((([e])=>{const t=Vp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Up(pE(t.x,s)).toVar(),n=Up(pE(t.y,i)).toVar(),o=Up(EE(r)).toVar(),a=Up(EE(n)).toVar(),h=Up(mE(xE(BE(s,i),r,n),xE(BE(s.add(Op(1)),i),r.sub(1),n),xE(BE(s,i.add(Op(1))),r,n.sub(1)),xE(BE(s.add(Op(1)),i.add(Op(1))),r.sub(1),n.sub(1)),o,a)).toVar();return SE(h)})).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Op().toVar(),n=Up(pE(t.x,s)).toVar(),o=Up(pE(t.y,i)).toVar(),a=Up(pE(t.z,r)).toVar(),h=Up(EE(n)).toVar(),u=Up(EE(o)).toVar(),l=Up(EE(a)).toVar(),c=Up(gE(xE(BE(s,i,r),n,o,a),xE(BE(s.add(Op(1)),i,r),n.sub(1),o,a),xE(BE(s,i.add(Op(1)),r),n,o.sub(1),a),xE(BE(s.add(Op(1)),i.add(Op(1)),r),n.sub(1),o.sub(1),a),xE(BE(s,i,r.add(Op(1))),n,o,a.sub(1)),xE(BE(s.add(Op(1)),i,r.add(Op(1))),n.sub(1),o,a.sub(1)),xE(BE(s,i.add(Op(1)),r.add(Op(1))),n,o.sub(1),a.sub(1)),xE(BE(s.add(Op(1)),i.add(Op(1)),r.add(Op(1))),n.sub(1),o.sub(1),a.sub(1)),h,u,l)).toVar();return ME(c)})).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),FE=EM([Cp((([e])=>{const t=Vp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Up(pE(t.x,s)).toVar(),n=Up(pE(t.y,i)).toVar(),o=Up(EE(r)).toVar(),a=Up(EE(n)).toVar(),h=Wp(mE(TE(IE(s,i),r,n),TE(IE(s.add(Op(1)),i),r.sub(1),n),TE(IE(s,i.add(Op(1))),r,n.sub(1)),TE(IE(s.add(Op(1)),i.add(Op(1))),r.sub(1),n.sub(1)),o,a)).toVar();return SE(h)})).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Op().toVar(),n=Up(pE(t.x,s)).toVar(),o=Up(pE(t.y,i)).toVar(),a=Up(pE(t.z,r)).toVar(),h=Up(EE(n)).toVar(),u=Up(EE(o)).toVar(),l=Up(EE(a)).toVar(),c=Wp(gE(TE(IE(s,i,r),n,o,a),TE(IE(s.add(Op(1)),i,r),n.sub(1),o,a),TE(IE(s,i.add(Op(1)),r),n,o.sub(1),a),TE(IE(s.add(Op(1)),i.add(Op(1)),r),n.sub(1),o.sub(1),a),TE(IE(s,i,r.add(Op(1))),n,o,a.sub(1)),TE(IE(s.add(Op(1)),i,r.add(Op(1))),n.sub(1),o,a.sub(1)),TE(IE(s,i.add(Op(1)),r.add(Op(1))),n,o.sub(1),a.sub(1)),TE(IE(s.add(Op(1)),i.add(Op(1)),r.add(Op(1))),n.sub(1),o.sub(1),a.sub(1)),h,u,l)).toVar();return ME(c)})).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),UE=EM([Cp((([e])=>{const t=Up(e).toVar(),s=Op(dE(t)).toVar();return RE(BE(s))})).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),Cp((([e])=>{const t=Vp(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar();return RE(BE(s,i))})).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar(),r=Op(dE(t.z)).toVar();return RE(BE(s,i,r))})).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),Cp((([e])=>{const t=$p(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar(),r=Op(dE(t.z)).toVar(),n=Op(dE(t.w)).toVar();return RE(BE(s,i,r,n))})).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),OE=EM([Cp((([e])=>{const t=Up(e).toVar(),s=Op(dE(t)).toVar();return Wp(RE(BE(s,Op(0))),RE(BE(s,Op(1))),RE(BE(s,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),Cp((([e])=>{const t=Vp(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar();return Wp(RE(BE(s,i,Op(0))),RE(BE(s,i,Op(1))),RE(BE(s,i,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar(),r=Op(dE(t.z)).toVar();return Wp(RE(BE(s,i,r,Op(0))),RE(BE(s,i,r,Op(1))),RE(BE(s,i,r,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Cp((([e])=>{const t=$p(e).toVar(),s=Op(dE(t.x)).toVar(),i=Op(dE(t.y)).toVar(),r=Op(dE(t.z)).toVar(),n=Op(dE(t.w)).toVar();return Wp(RE(BE(s,i,r,n,Op(0))),RE(BE(s,i,r,n,Op(1))),RE(BE(s,i,r,n,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),zE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Up(0).toVar(),u=Up(1).toVar();return xv(o,(()=>{h.addAssign(u.mul(PE(a))),u.mulAssign(r),a.mulAssign(n)})),h})).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"}]}),LE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Wp(0).toVar(),u=Up(1).toVar();return xv(o,(()=>{h.addAssign(u.mul(FE(a))),u.mulAssign(r),a.mulAssign(n)})),h})).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"}]}),VE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar();return Vp(zE(a,o,n,r),zE(a.add(Wp(Op(19),Op(193),Op(17))),o,n,r))})).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"}]}),DE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Wp(LE(a,o,n,r)).toVar(),u=Up(zE(a.add(Wp(Op(19),Op(193),Op(17))),o,n,r)).toVar();return $p(h,u)})).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"}]}),kE=Cp((([e,t,s,i,r,n,o])=>{const a=Op(o).toVar(),h=Up(n).toVar(),u=Op(r).toVar(),l=Op(i).toVar(),c=Op(s).toVar(),d=Op(t).toVar(),p=Vp(e).toVar(),m=Wp(OE(Vp(d.add(l),c.add(u)))).toVar(),g=Vp(m.x,m.y).toVar();g.subAssign(.5),g.mulAssign(h),g.addAssign(.5);const f=Vp(Vp(Up(d),Up(c)).add(g)).toVar(),y=Vp(f.sub(p)).toVar();return Ip(a.equal(Op(2)),(()=>Wg(y.x).add(Wg(y.y)))),Ip(a.equal(Op(3)),(()=>nf(Wg(y.x),Wg(y.y)))),cf(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"}]}),GE=EM([kE,Cp((([e,t,s,i,r,n,o,a,h])=>{const u=Op(h).toVar(),l=Up(a).toVar(),c=Op(o).toVar(),d=Op(n).toVar(),p=Op(r).toVar(),m=Op(i).toVar(),g=Op(s).toVar(),f=Op(t).toVar(),y=Wp(e).toVar(),x=Wp(OE(Wp(f.add(p),g.add(d),m.add(c)))).toVar();x.subAssign(.5),x.mulAssign(l),x.addAssign(.5);const b=Wp(Wp(Up(f),Up(g),Up(m)).add(x)).toVar(),v=Wp(b.sub(y)).toVar();return Ip(u.equal(Op(2)),(()=>Wg(v.x).add(Wg(v.y)).add(Wg(v.z)))),Ip(u.equal(Op(3)),(()=>nf(nf(Wg(v.x),Wg(v.y)),Wg(v.z)))),cf(v,v)})).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"}]})]),WE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(pE(n.x,o),pE(n.y,a)).toVar(),u=Up(1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(GE(h,e,t,o,a,r,i)).toVar();u.assign(rf(u,s))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),jE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(pE(n.x,o),pE(n.y,a)).toVar(),u=Vp(1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(GE(h,e,t,o,a,r,i)).toVar();Ip(s.lessThan(u.x),(()=>{u.y.assign(u.x),u.x.assign(s)})).ElseIf(s.lessThan(u.y),(()=>{u.y.assign(s)}))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),HE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(pE(n.x,o),pE(n.y,a)).toVar(),u=Wp(1e6,1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(GE(h,e,t,o,a,r,i)).toVar();Ip(s.lessThan(u.x),(()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(s)})).ElseIf(s.lessThan(u.y),(()=>{u.z.assign(u.y),u.y.assign(s)})).ElseIf(s.lessThan(u.z),(()=>{u.z.assign(s)}))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),qE=EM([WE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(pE(n.x,o),pE(n.y,a),pE(n.z,h)).toVar(),l=Up(1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(GE(u,e,t,s,o,a,h,r,i)).toVar();l.assign(rf(l,n))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),$E=EM([jE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(pE(n.x,o),pE(n.y,a),pE(n.z,h)).toVar(),l=Vp(1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(GE(u,e,t,s,o,a,h,r,i)).toVar();Ip(n.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(n)})).ElseIf(n.lessThan(l.y),(()=>{l.y.assign(n)}))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),XE=EM([HE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(pE(n.x,o),pE(n.y,a),pE(n.z,h)).toVar(),l=Wp(1e6,1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(GE(u,e,t,s,o,a,h,r,i)).toVar();Ip(n.lessThan(l.x),(()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(n)})).ElseIf(n.lessThan(l.y),(()=>{l.z.assign(l.y),l.y.assign(n)})).ElseIf(n.lessThan(l.z),(()=>{l.z.assign(n)}))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),YE=Cp((([e])=>{const t=e.y,s=e.z,i=Wp().toVar();return Ip(t.lessThan(1e-4),(()=>{i.assign(Wp(s,s,s))})).Else((()=>{let r=e.x;r=r.sub(Pg(r)).mul(6).toVar();const n=Op(Kg(r)),o=r.sub(Up(n)),a=s.mul(t.oneMinus()),h=s.mul(t.mul(o).oneMinus()),u=s.mul(t.mul(o.oneMinus()).oneMinus());Ip(n.equal(Op(0)),(()=>{i.assign(Wp(s,u,a))})).ElseIf(n.equal(Op(1)),(()=>{i.assign(Wp(h,s,a))})).ElseIf(n.equal(Op(2)),(()=>{i.assign(Wp(a,s,u))})).ElseIf(n.equal(Op(3)),(()=>{i.assign(Wp(a,h,s))})).ElseIf(n.equal(Op(4)),(()=>{i.assign(Wp(u,a,s))})).Else((()=>{i.assign(Wp(s,a,h))}))})),i})).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),ZE=Cp((([e])=>{const t=Wp(e).toVar(),s=Up(t.x).toVar(),i=Up(t.y).toVar(),r=Up(t.z).toVar(),n=Up(rf(s,rf(i,r))).toVar(),o=Up(nf(s,nf(i,r))).toVar(),a=Up(o.sub(n)).toVar(),h=Up().toVar(),u=Up().toVar(),l=Up().toVar();return l.assign(o),Ip(o.greaterThan(0),(()=>{u.assign(a.div(o))})).Else((()=>{u.assign(0)})),Ip(u.lessThanEqual(0),(()=>{h.assign(0)})).Else((()=>{Ip(s.greaterThanEqual(o),(()=>{h.assign(i.sub(r).div(a))})).ElseIf(i.greaterThanEqual(o),(()=>{h.assign(Ym(2,r.sub(s).div(a)))})).Else((()=>{h.assign(Ym(4,s.sub(i).div(a)))})),h.mulAssign(1/6),Ip(h.lessThan(0),(()=>{h.addAssign(1)}))})),Wp(h,u,l)})).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),JE=Cp((([e])=>{const t=Wp(e).toVar(),s=qp(ig(t,Wp(.04045))).toVar(),i=Wp(t.div(12.92)).toVar(),r=Wp(pf(nf(t.add(Wp(.055)),Wp(0)).div(1.055),Wp(2.4))).toVar();return vf(i,r,s)})).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),KE=(e,t)=>{e=Up(e),t=Up(t);const s=Vp(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Sf(e.sub(s),e.add(s),t)},QE=(e,t,s,i)=>vf(e,t,s[i].clamp()),eB=(e,t,s=My())=>QE(e,t,s,"x"),tB=(e,t,s=My())=>QE(e,t,s,"y"),sB=(e,t,s,i,r)=>vf(e,t,KE(s,i[r])),iB=(e,t,s,i=My())=>sB(e,t,s,i,"x"),rB=(e,t,s,i=My())=>sB(e,t,s,i,"y"),nB=(e=1,t=0,s=My())=>s.mul(e).add(t),oB=(e,t=1)=>(e=Up(e)).abs().pow(t).mul(e.sign()),aB=(e,t=1,s=.5)=>Up(e).sub(s).mul(t).add(s),hB=(e=My(),t=1,s=0)=>PE(e.convert("vec2|vec3")).mul(t).add(s),uB=(e=My(),t=1,s=0)=>FE(e.convert("vec2|vec3")).mul(t).add(s),lB=(e=My(),t=1,s=0)=>{e=e.convert("vec2|vec3");return $p(FE(e),PE(e.add(Vp(19,73)))).mul(t).add(s)},cB=(e=My(),t=1)=>qE(e.convert("vec2|vec3"),t,Op(1)),dB=(e=My(),t=1)=>$E(e.convert("vec2|vec3"),t,Op(1)),pB=(e=My(),t=1)=>XE(e.convert("vec2|vec3"),t,Op(1)),mB=(e=My())=>UE(e.convert("vec2|vec3")),gB=(e=My(),t=3,s=2,i=.5,r=1)=>zE(e,Op(t),s,i).mul(r),fB=(e=My(),t=3,s=2,i=.5,r=1)=>VE(e,Op(t),s,i).mul(r),yB=(e=My(),t=3,s=2,i=.5,r=1)=>LE(e,Op(t),s,i).mul(r),xB=(e=My(),t=3,s=2,i=.5,r=1)=>DE(e,Op(t),s,i).mul(r),bB=Cp((([e,t])=>{const s=e.x,i=e.y,r=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(i)),n=n.add(t.element(2).mul(1.023328).mul(r)),n=n.add(t.element(3).mul(1.023328).mul(s)),n=n.add(t.element(4).mul(.858086).mul(s).mul(i)),n=n.add(t.element(5).mul(.858086).mul(i).mul(r)),n=n.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(s).mul(r)),n=n.add(t.element(8).mul(.429043).mul(Jm(s,s).sub(Jm(i,i)))),n}));class vB extends PC{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=dm(0).setGroup(um),this.decayExponentNode=dm(0).setGroup(um)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setup(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:r}=this,n=e.context.lightingModel,o=VC(r).sub(lx),a=o.normalize(),h=o.length(),u=FC({lightDistance:h,cutoffDistance:s,decayExponent:i}),l=t.mul(u),c=e.context.reflectedLight;n.direct({lightDirection:a,lightColor:l,reflectedLight:c},e.stack,e)}}class TB extends PC{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,s=this.colorNode,i=DC(this.light),r=e.context.reflectedLight;t.direct({lightDirection:i,lightColor:s,reflectedLight:r},e.stack,e)}}const _B=new sr,wB=new sr;let SB=null;class MB extends PC{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=dm(new Ai).setGroup(um),this.halfWidth=dm(new Ai).setGroup(um)}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;wB.identity(),_B.copy(t.matrixWorld),_B.premultiply(s),wB.extractRotation(_B),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(wB),this.halfHeight.value.applyMatrix4(wB)}setup(e){let t,s;super.setup(e),e.isAvailable("float32Filterable")?(t=By(SB.LTC_FLOAT_1),s=By(SB.LTC_FLOAT_2)):(t=By(SB.LTC_HALF_1),s=By(SB.LTC_HALF_2));const{colorNode:i,light:r}=this,n=e.context.lightingModel,o=VC(r),a=e.context.reflectedLight;n.directRectArea({lightColor:i,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,reflectedLight:a,ltc_1:t,ltc_2:s},e.stack,e)}static setLTC(e){SB=e}}class AB extends PC{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=dm(0).setGroup(um),this.penumbraCosNode=dm(0).setGroup(um),this.cutoffDistanceNode=dm(0).setGroup(um),this.decayExponentNode=dm(0).setGroup(um)}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){const{coneCosNode:t,penumbraCosNode:s}=this;return Sf(t,s,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:s,cutoffDistanceNode:i,decayExponentNode:r,light:n}=this,o=VC(n).sub(lx),a=o.normalize(),h=a.dot(DC(n)),u=this.getSpotAttenuation(h),l=o.length(),c=FC({lightDistance:l,cutoffDistance:i,decayExponent:r}),d=s.mul(u).mul(c),p=e.context.reflectedLight;t.direct({lightDirection:a,lightColor:d,reflectedLight:p},e.stack,e)}}class NB extends AB{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e){const t=this.light.iesMap;let s=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);s=By(t,Vp(i,0),0).r}else s=super.getSpotAttenuation(e);return s}}class CB extends PC{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class RB extends PC{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=zC(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=dm(new Xr).setGroup(um)}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:s,lightDirectionNode:i}=this,r=xx.dot(i).mul(.5).add(.5),n=vf(s,t,r);e.context.irradiance.addAssign(n)}}class EB extends PC{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Ai);this.lightProbe=Ox(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=bB(bx,this.lightProbe);e.context.irradiance.addAssign(t)}}class BB{parseFunction(){console.warn("Abstract function.")}}class IB{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}IB.isNodeFunction=!0;const PB=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,FB=/[a-z_0-9]+/gi,UB="#pragma main";class OB extends IB{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(UB),s=-1!==t?e.slice(t+12):e,i=s.match(PB);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=FB.exec(r));)n.push(o);const a=[];let h=0;for(;h0?this.transparent:this.opaque).push(o)}unshift(e,t,s,i,r,n){const o=this.getNextRenderItem(e,t,s,i,r,n);(!0===s.transparent?this.transparent: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||LB),this.transparent.length>1&&this.transparent.sort(t||VB)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,h=o.height>>t;let u=e.depthTexture||r[t];const l=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===u&&l&&(u=new Xa,u.format=e.stencilBuffer?je:We,u.type=e.stencilBuffer?Oe:Be,u.image.width=a,u.image.height=h,r[t]=u),s.width===o.width&&o.height===s.height||(c=!0,u&&(u.needsUpdate=!0,u.image.width=a,u.image.height=h)),s.width=o.width,s.height=o.height,s.textures=n,s.depthTexture=u||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(c=!0,u&&(u.needsUpdate=!0),s.sampleCount=i);const d={sampleCount:i};for(let e=0;e{e.removeEventListener("dispose",t);for(let e=0;e0){const i=e.image;if(void 0===i)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=i;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(r.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version}if(!0!==s.initialized){s.initialized=!0,s.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}s.version=e.version}getSize(e,t=qB){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),t.width=s.width,t.height=s.height,t.depth=e.isCubeTexture?6:s.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return i=e.isCompressedTexture?e.mipmaps.length:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return!!this.isEnvironmentTexture(e)||(!0===e.isCompressedTexture||e.minFilter!==fe&&e.minFilter!==Te)}isEnvironmentTexture(e){const t=e.mapping;return t===le||t===ce||t===he||t===ue}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class XB extends Xr{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}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)}}const YB=new XB;class ZB extends Xw{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===r)i._clearColor.getRGB(YB,Jt),YB.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(YB,Jt),YB.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;YB.copy(i._clearColor);let o=s.backgroundMesh;if(void 0===o){const e=Pf($p(n).mul(gA),{getUV:()=>bx,getTextureLevel:()=>mA});let t=tv();t=t.setZ(t.w);const i=new pT;i.name="Background.material",i.side=d,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.lights=!1,i.vertexNode=t,i.colorNode=e,s.backgroundMeshNode=e,s.backgroundMesh=o=new On(new cu(1,32,32),i),o.frustumCulled=!1,o.name="Background.mesh",o.onBeforeRender=function(e,t,s){this.matrixWorld.copyPosition(s.matrixWorld)}}const a=n.getCacheKey();s.backgroundCacheKey!==a&&(s.backgroundMeshNode.node=$p(n).mul(gA),s.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null)}else console.error("THREE.Renderer: Unsupported background configuration.",r);if(!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=YB.r,e.g=YB.g,e.b=YB.b,e.a=YB.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(e.r*=e.a,e.g*=e.a,e.b*=e.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,s.clearColor=!0===i.autoClearColor,s.clearDepth=!0===i.autoClearDepth,s.clearStencil=!0===i.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}class JB{constructor(e,t,s,i,r,n,o,a,h,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=o,this.updateAfterNodes=a,this.monitor=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new mM(t.name,[],t.index,t);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}const KB=new WeakMap;class QB extends Xw{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new vM,this.nodeBuilderCache=new Map,this.callHashCache=new kw,this.groupsData=new kw}updateGroup(e){const t=e.groupNode,s=t.name;if(s===lm.name)return!0;if(s===um.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===hm.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}const i=[t,e];let r=this.groupsData.get(i);return void 0===r&&this.groupsData.set(i,r={}),r.version!==t.version&&(r.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const{nodeBuilderCache:i}=this,r=this.getForRenderCacheKey(e);if(s=i.get(r),void 0===s){const t=this.backend.createNodeBuilder(e.object,this.renderer);t.scene=e.scene,t.material=e.material,t.camera=e.camera,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.clippingContext=e.clippingContext,t.build(),s=this._createNodeBuilderState(t),i.set(r,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),s=this._createNodeBuilderState(i),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new JB(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.monitor,e.transforms)}getEnvironmentNode(e){return e.environmentNode||this.get(e).environmentNode||null}getBackgroundNode(e){return e.backgroundNode||this.get(e).backgroundNode||null}getFogNode(e){return e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){const s=[e,t],i=this.renderer.info.calls;let r=this.callHashCache.get(s);if(void 0===r||r.callId!==i){const n=this.getEnvironmentNode(e),o=this.getFogNode(e),a=[];t&&a.push(t.getCacheKey(!0)),n&&a.push(n.getCacheKey()),o&&a.push(o.getCacheKey()),a.push(this.renderer.shadowMap.enabled?1:0),r={callId:i,cacheKey:vd(a)},this.callHashCache.set(s,r)}return r.cacheKey}updateScene(e){this.updateEnvironment(e),this.updateFog(e),this.updateBackground(e)}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),s=e.background;if(s){const i=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==s||i){let i=null;if(!0===s.isCubeTexture||s.mapping===le||s.mapping===ce||s.mapping===de)if(e.backgroundBlurriness>0||s.mapping===de)i=hw(s,bx);else{let e;e=!0===s.isCubeTexture?Bx(s):By(s),i=PT(e)}else!0===s.isTexture?i=By(s,Vv.flipY()).setUpdateMatrix(!0):!0!==s.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",s);t.backgroundNode=i,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){let e=null;if(s.isFogExp2){const t=Dx("color","color",s).setGroup(um),i=Dx("density","float",s).setGroup(um);e=yC(t,i)}else if(s.isFog){const t=Dx("color","color",s).setGroup(um),i=Dx("near","float",s).setGroup(um),r=Dx("far","float",s).setGroup(um);e=gC(t,i,r)}else console.error("WebGPUNodes: Unsupported fog configuration.",s);t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){let e=null;!0===s.isCubeTexture?e=Bx(s):!0===s.isTexture?e=By(s):console.error("Nodes: Unsupported environment configuration.",s),t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,r=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=i,n.material=r,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}hasOutputChange(e){return KB.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=By(e,Vv).renderOutput(t.toneMapping,t.currentColorSpace);return KB.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new vM,this.nodeBuilderCache=new Map}}class eI{constructor(e,t){this.scene=e,this.camera=t}clone(){return Object.assign(new this.constructor,this)}}class tI{constructor(){this.lists=new kw}get(e,t){const s=this.lists,i=[e,t];let r=s.get(i);return void 0===r&&(r=new eI(e,t),s.set(i,r)),r}dispose(){this.lists=new kw}}class sI{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map,this.colorSpaceNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(null!==s){t=new s;for(const s in e)t[s]=e[s]}return t}addColorSpace(e,t){this.addType(e,t,this.colorSpaceNodes)}getColorSpaceFunction(e){return this.colorSpaceNodes.get(e)||null}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t.type,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t))console.warn(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}}addClass(e,t,s){if(s.has(t))console.warn(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}}const iI=new Kn,rI=new Ys,nI=new xi,oI=new Ko,aI=new sr,hI=new xi;class uI{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:r=!0,stencil:n=!1,antialias:o=!1,samples:a=0,getFallback:h=null}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=a||!0===o?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=Zt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=r,this.stencil=n,this.clippingPlanes=[],this.info=new rS,this.nodes={library:new sI,modelViewMatrix:null,modelNormalViewMatrix:null},this._getFallback=h,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new xi(0,0,this._width,this._height),this._scissor=new xi(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new rA(new pT),this._quad.material.type="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const u=!0===this.alpha?0:1;this._clearColor=new XB(0,0,0,u),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr={enabled:!1},this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,s)=>{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(e,t,this._renderTarget),n=e.overrideMaterial||s.material,o=this._objects.get(s,n,e,t,i.lightsNode,r),{fragmentShader:a,vertexShader:h}=o.getNodeBuilderState();return{fragmentShader:a,vertexShader:h}}}}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 s=this.backend;try{await s.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=s=this._getFallback(e),await s.init(this)}catch(e){return void t(e)}}this._nodes=new QB(this,s),this._animation=new Dw(this._nodes,this.info),this._attributes=new eS(s),this._background=new ZB(this,this._nodes),this._geometries=new iS(this._attributes,this.info),this._textures=new $B(this,s,this.info),this._pipelines=new lS(s,this._nodes),this._bindings=new cS(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new $w(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new kB,this._bundles=new tI,this._renderContexts=new HB,this._initialized=!0,e()}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,n=this._currentRenderContext,o=this._currentRenderObjectFunction,a=this._compilationPromises,h=!0===e.isScene?e:iI;null===s&&(s=e);const u=this._renderTarget,l=this._renderContexts.get(s,t,u),c=this._activeMipmapLevel,d=[];this._currentRenderContext=l,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),l.depth=this.depth,l.stencil=this.stencil,l.clippingContext||(l.clippingContext=new Ww),l.clippingContext.updateGlobal(this,t),h.onBeforeRender(this,e,t,u);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p),s!==e&&s.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==u){this._textures.updateRenderTarget(u,c);const e=this._textures.get(u);l.textures=e.textures,l.depthTexture=e.depthTexture}else l.textures=null,l.depthTexture=null;this._nodes.updateScene(h),this._background.update(h,p,l);const m=p.opaque,g=p.transparent,f=p.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,h,f),!0===this.transparent&&g.length>0&&this._renderObjects(g,t,h,f),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=o,this._compilationPromises=a,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init();const s=this._renderScene(e,t);await this.backend.resolveTimestampAsync(s,"render")}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,o=this._currentRenderContext,a=this._bundles.get(i,r),h=this.backend.get(a);void 0===h.renderContexts&&(h.renderContexts=new Set);const u=i.version!==h.version,l=!1===h.renderContexts.has(o)||u;if(h.renderContexts.add(o),l){this.backend.beginBundle(o),(void 0===h.renderObjects||u)&&(h.renderObjects=[]),this._currentRenderBundle=a;const e=n.opaque;e.length>0&&this._renderObjects(e,r,t,s),this._currentRenderBundle=null,this.backend.finishBundle(o,a),h.version=i.version}else{const{renderObjects:e}=h;for(let t=0,s=e.length;t>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=b,p.viewport=!1===p.viewportValue.equals(nI),p.scissorValue.copy(f).multiplyScalar(y).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(nI),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new Ww),p.clippingContext.updateGlobal(this,t),h.onBeforeRender(this,e,t,d),aI.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),oI.setFromProjectionMatrix(aI,m);const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,c);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=l,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,this._nodes.updateScene(h),this._background.update(h,v,p),this.backend.beginRender(p);const{bundles:T,lightsNode:_,transparent:w,opaque:S}=v;if(T.length>0&&this._renderBundles(T,h,_),!0===this.opaque&&S.length>0&&this._renderObjects(S,t,h,_),!0===this.transparent&&w.length>0&&this._renderObjects(w,t,h,_),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=o,this._currentRenderObjectFunction=a,null!==i){this.setRenderTarget(u,l,c);const e=this._quad;this._nodes.hasOutputChange(d.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(d.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}return h.onAfterRender(this,e,t,d),p}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,s){this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,s=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(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,s,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,r=0,n=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,i),o.minDepth=r,o.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,s=!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,s);const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i&&(this._textures.updateRenderTarget(i),r=this._textures.get(i)),this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget){const e=this._quad;this._nodes.hasOutputChange(i.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(i.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}}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,s=!0){!1===this._initialized&&await this.init(),this.clear(e,t,s)}clearColorAsync(){return this.clearAsync(!0,!1,!1)}clearDepthAsync(){return this.clearAsync(!1,!0,!1)}clearStencilAsync(){return this.clearAsync(!1,!1,!0)}get currentToneMapping(){return null!==this._renderTarget?0:this.toneMapping}get currentColorSpace(){return null!==this._renderTarget?Jt:this.outputColorSpace}dispose(){this.info.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(),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,r=this._pipelines,n=this._bindings,o=this._nodes,a=Array.isArray(e)?e:[e];if(void 0===a[0]||!0!==a[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const t of a){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),n.delete(t),o.delete(t)};t.addEventListener("dispose",e);const s=t.onInitFunction;null!==s&&s.call(t,{renderer:this})}o.updateForCompute(t),n.updateForCompute(t);const s=n.getForCompute(t),a=r.getForCompute(t,s);i.compute(e,t,s,a)}i.finishCompute(e),t.renderId=s}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e),await this.backend.resolveTimestampAsync(e,"compute")}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(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)}copyFramebufferToTexture(e,t=null){const s=this._currentRenderContext;this._textures.updateTexture(e),t=null===t?hI.set(0,0,e.image.width,e.image.height):t,this.backend.copyFramebufferToTexture(e,s,t)}copyTextureToTexture(e,t,s=null,i=null,r=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r)}readRenderTargetPixelsAsync(e,t,s,i,r,n=0,o=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,o)}_projectObject(e,t,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||oI.intersectsSprite(e)){!0===this.sortObjects&&hI.setFromMatrixPosition(e.matrixWorld).applyMatrix4(aI);const{geometry:t,material:r}=e;r.visible&&i.push(e,t,r,s,hI.z,null)}}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)&&(!e.frustumCulled||oI.intersectsObject(e))){const{geometry:t,material:r}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),hI.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(aI)),Array.isArray(r)){const n=t.groups;for(let o=0,a=n.length;o0?i:"";t=`${e.name} {\n\t${s} ${r.name}[${n}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,n=!0}const o=r.node.precision;if(null!==o&&(t=SI[o]+" "+t),n){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,s.push(t)}let r="";for(const t in i){const s=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Ee){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let s=0;for(const i of e)t+=`layout( location = ${s++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[],s=e.getMemberTypes();for(let e=0;ee*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,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);!1===i.has(e)&&i.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 s=this.extensions[e];if(void 0!==s)for(const{name:e,behavior:i}of s.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}isAvailable(e){let t=MI[e];if(void 0===t){if("float32Filterable"===e){const e=this.renderer.backend.extensions;e.has("OES_texture_float_linear")?(e.get("OES_texture_float_linear"),t=!0):t=!1}MI[e]=t}return t}isFlipY(){return!0}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${i.code}\n\t`,e===r&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${i.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=s}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);let o=n.uniformGPU;if(void 0===o){const i=e.groupNode,a=i.name,h=this.getBindGroupArray(a,s);if("texture"===t)o=new vI(r.name,r.node,i),h.push(o);else if("cubeTexture"===t)o=new TI(r.name,r.node,i),h.push(o);else if("texture3D"===t)o=new _I(r.name,r.node,i),h.push(o);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,r.name=`buffer${e.id}`;const t=new mI(e,i);t.name=e.name,h.push(t),o=t}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new yI(s+"_"+a,i),e[a]=n,h.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let CI=null,RI=null,EI=null;class BI{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}async init(e){this.renderer=e}begin(){}finish(){}draw(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}createRenderPipeline(){}createComputePipeline(){}destroyPipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}createDefaultTexture(){}createTexture(){}copyTextureToBuffer(){}createAttribute(){}createIndexAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}resolveTimestampAsync(){}hasFeatureAsync(){}hasFeature(){}getInstanceCount(e){const{object:t,geometry:s}=e;return s.isInstancedBufferGeometry?s.instanceCount:t.count>1?t.count:1}getDrawingBufferSize(){return CI=CI||new Ys,this.renderer.getDrawingBufferSize(CI)}getScissor(){return RI=RI||new xi,this.renderer.getScissor(RI)}setScissorTest(){}getClearColor(){const e=this.renderer;return EI=EI||new XB,e.getClearColor(EI),EI.getRGB(EI,this.renderer.currentColorSpace),EI}getDomElement(){let t=this.domElement;return null===t&&(t=void 0!==this.parameters.canvas?this.parameters.canvas:ti(),"setAttribute"in t&&t.setAttribute("data-engine",`three.js r${e} webgpu`),this.domElement=t),t}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)}}let II=0;class PI{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 FI{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,a=s.get(o);let h,u=a.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,n),a.bufferGPU=u,a.bufferType=t,a.version=o.version),r instanceof Float32Array)h=i.FLOAT;else if(r instanceof Uint16Array)h=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)h=i.SHORT;else if(r instanceof Uint32Array)h=i.UNSIGNED_INT;else if(r instanceof Int32Array)h=i.INT;else if(r instanceof Int8Array)h=i.BYTE;else if(r instanceof Uint8Array)h=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);h=i.UNSIGNED_BYTE}let l={bufferGPU:u,bufferType:t,type:h,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===Ee,id:II++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);l=new PI(l,e)}s.set(e,l)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,n=t.get(r),o=n.bufferType,a=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,n.bufferGPU),0===a.length)s.bufferSubData(o,0,i);else{for(let e=0,t=a.length;e1?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE)}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===s||(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t&&(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:s}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const n=e.textures;if(i.length!==n.length||i[0]!==s.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e{!function r(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void i();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(r)}()}))}}let DI,kI,GI,WI=!1;class jI{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===WI&&(this._init(this.gl),WI=!0)}_init(e){DI={[pe]:e.REPEAT,[me]:e.CLAMP_TO_EDGE,[ge]:e.MIRRORED_REPEAT},kI={[fe]:e.NEAREST,[ye]:e.NEAREST_MIPMAP_NEAREST,[be]:e.NEAREST_MIPMAP_LINEAR,[Te]:e.LINEAR,[_e]:e.LINEAR_MIPMAP_NEAREST,[Se]:e.LINEAR_MIPMAP_LINEAR},GI={512:e.NEVER,519:e.ALWAYS,[ys]:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===fe||e===ye||e===be?t.NEAREST:t.LINEAR}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,r=!1){const{gl:n,extensions:o}=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 a=t;return t===n.RED&&(s===n.FLOAT&&(a=n.R32F),s===n.HALF_FLOAT&&(a=n.R16F),s===n.UNSIGNED_BYTE&&(a=n.R8),s===n.UNSIGNED_SHORT&&(a=n.R16),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.R8UI),s===n.UNSIGNED_SHORT&&(a=n.R16UI),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RG&&(s===n.FLOAT&&(a=n.RG32F),s===n.HALF_FLOAT&&(a=n.RG16F),s===n.UNSIGNED_BYTE&&(a=n.RG8),s===n.UNSIGNED_SHORT&&(a=n.RG16),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RG_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RG8UI),s===n.UNSIGNED_SHORT&&(a=n.RG16UI),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RGB&&(s===n.FLOAT&&(a=n.RGB32F),s===n.HALF_FLOAT&&(a=n.RGB16F),s===n.UNSIGNED_BYTE&&(a=n.RGB8),s===n.UNSIGNED_SHORT&&(a=n.RGB16),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I),s===n.UNSIGNED_BYTE&&(a=i===Zt&&!1===r?n.SRGB8:n.RGB8),s===n.UNSIGNED_SHORT_5_6_5&&(a=n.RGB565),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGB4),s===n.UNSIGNED_INT_5_9_9_9_REV&&(a=n.RGB9_E5)),t===n.RGB_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGB8UI),s===n.UNSIGNED_SHORT&&(a=n.RGB16UI),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I)),t===n.RGBA&&(s===n.FLOAT&&(a=n.RGBA32F),s===n.HALF_FLOAT&&(a=n.RGBA16F),s===n.UNSIGNED_BYTE&&(a=n.RGBA8),s===n.UNSIGNED_SHORT&&(a=n.RGBA16),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I),s===n.UNSIGNED_BYTE&&(a=i===Zt&&!1===r?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1)),t===n.RGBA_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGBA8UI),s===n.UNSIGNED_SHORT&&(a=n.RGBA16UI),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_INT&&(a=n.DEPTH24_STENCIL8),s===n.FLOAT&&(a=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(a=n.DEPTH24_STENCIL8),a!==n.R16F&&a!==n.R32F&&a!==n.RG16F&&a!==n.RG32F&&a!==n.RGBA16F&&a!==n.RGBA32F||o.get("EXT_color_buffer_float"),a}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE),s.texParameteri(e,s.TEXTURE_WRAP_S,DI[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,DI[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||s.texParameteri(e,s.TEXTURE_WRAP_R,DI[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,kI[t.magFilter]);const n=void 0!==t.mipmaps&&t.mipmaps.length>0,o=t.minFilter===Te&&n?Se:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,kI[o]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,GI[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===fe)return;if(t.minFilter!==be&&t.minFilter!==Se)return;if(t.type===Ie&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,r=this.getGLTextureType(e);let n=i[r];void 0===n&&(n=t.createTexture(),s.state.bindTexture(r,n),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=n),s.set(e,{textureGPU:n,glTextureType:r,isDefault:!0})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:r,width:n,height:o,depth:a}=t,h=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,h,u,e.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,r,l,n,o,a):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,l,n,o,a):e.isVideoTexture||s.texStorage2D(d,r,l,n,o),i.set(e,{textureGPU:c,glTextureType:d,glFormat:h,glType:u,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:r,glTextureType:n,glFormat:o,glType:a}=i.get(t),{width:h,height:u}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(n,r),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(n,0,0,0,h,u,o,a,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:r}=t,{textureGPU:n,glTextureType:o,glFormat:a,glType:h,glInternalFormat:u}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===n)return;const l=e=>e.isDataTexture?e.image.data:e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLImageElement||e instanceof HTMLCanvasElement?e:e.data;if(this.backend.state.bindTexture(o,n),this.setTextureParameters(o,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t0,c=t.renderTarget?t.renderTarget.height:this.backend.gerDrawingBufferSize().y;if(l){const s=0!==o||0!==a;let l,d;if(!0===e.isDepthTexture?(l=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(l|=i.STENCIL_BUFFER_BIT)):(l=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),s){const e=this.backend.get(t.renderTarget),s=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,s),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=c-a-u;i.blitFramebuffer(o,p,o+h,p+u,o,p,o+h,p+u,l,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,s),r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,p,h,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,n,0),i.blitFramebuffer(0,0,h,u,0,0,h,u,l,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,c-u-a,h,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t){const{gl:s}=this,i=t.renderTarget,{samples:r,depthTexture:n,depthBuffer:o,stencilBuffer:a,width:h,height:u}=i;if(s.bindRenderbuffer(s.RENDERBUFFER,e),o&&!a){let t=s.DEPTH_COMPONENT24;r>0?(n&&n.isDepthTexture&&n.type===s.FLOAT&&(t=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,r,t,h,u)):s.renderbufferStorage(s.RENDERBUFFER,t,h,u),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else o&&a&&(r>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,r,s.DEPTH24_STENCIL8,h,u):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,h,u),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,s,i,r,n){const{backend:o,gl:a}=this,{textureGPU:h,glFormat:u,glType:l}=this.backend.get(e),c=a.createFramebuffer();a.bindFramebuffer(a.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?a.TEXTURE_CUBE_MAP_POSITIVE_X+n:a.TEXTURE_2D;a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,d,h,0);const p=this._getTypedArrayType(l),m=i*r*this._getBytesPerTexel(l,u),g=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.bufferData(a.PIXEL_PACK_BUFFER,m,a.STREAM_READ),a.readPixels(t,s,i,r,u,l,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();const f=new p(m/p.BYTES_PER_ELEMENT);return a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,f),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.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:s}=this;let i=0;return e===s.UNSIGNED_BYTE&&(i=1),e!==s.UNSIGNED_SHORT_4_4_4_4&&e!==s.UNSIGNED_SHORT_5_5_5_1&&e!==s.UNSIGNED_SHORT_5_6_5&&e!==s.UNSIGNED_SHORT&&e!==s.HALF_FLOAT||(i=2),e!==s.UNSIGNED_INT&&e!==s.FLOAT||(i=4),t===s.RGBA?4*i:t===s.RGB?3*i:t===s.ALPHA?i:void 0}}class HI{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 qI{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 s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const $I={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"};class XI{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:s,mode:i,object:r,type:n,info:o,index:a}=this;0!==a?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),o.update(r,t,i,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:o,object:a,info:h}=this;0!==s&&(0!==o?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),h.update(a,t,r,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:o}=this;if(0===s)return;const a=i.get("WEBGL_multi_draw");if(null===a)for(let i=0;i0)){const e=t.queryQueue.shift();this.initTimestampQuery(e)}}async resolveTimestampAsync(e,t="render"){if(!this.disjoint||!this.trackTimestamp)return;const s=this.get(e);s.gpuQueries||(s.gpuQueries=[]);for(let e=0;e0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext,n=e.occlusionQueryCount;n>0&&(n>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const o=e.textures;if(null!==o)for(let e=0;e0){const r=i.framebuffers[e.getCacheKey()],n=t.COLOR_BUFFER_BIT,o=i.msaaFrameBuffer,a=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,o),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,r);for(let s=0;s{let o=0;for(let t=0;t0&&e.add(i[t]),s[t]=null,r.deleteQuery(n),o++))}o1?m.renderInstances(y,g,f):m.render(y,g),o.bindVertexArray(null)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new NI(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,r="fragment"===s?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(){console.warn("Abstract class.")}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:n}=i,o=s.createProgram(),a=this.get(r).shaderGPU,h=this.get(n).shaderGPU;if(s.attachShader(o,a),s.attachShader(o,h),s.linkProgram(o),this.set(i,{programGPU:o,fragmentShader:a,vertexShader:h}),null!==t&&this.parallel){const r=new Promise((t=>{const r=this.parallel,n=()=>{s.getProgramParameter(o,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(n)};n()}));t.push(r)}else this._completeCompile(e,i)}_handleSource(e,t){const s=e.split("\n"),i=[],r=Math.max(t-6,0),n=Math.min(t+6,s.length);for(let e=r;e":" "} ${r}: ${s[e]}`)}return i.join("\n")}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=e.getShaderInfoLog(t).trim();if(i&&""===r)return"";const n=/ERROR: 0:(\d+)/.exec(r);if(n){const i=parseInt(n[1]);return s.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=i.getProgramInfoLog(e).trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,s,t);else{const n=this._getShaderErrors(i,s,"vertex"),o=this._getShaderErrors(i,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+o)}else""!==r&&console.warn("THREE.WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:o,vertexShader:a}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,o,a),s.useProgram(n);const h=e.getBindings();this._setupBindings(h,n),this.set(t,{programGPU:n})}createComputePipeline(e,t){const{state:s,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:n}=e,o=i.createProgram(),a=this.get(r).shaderGPU,h=this.get(n).shaderGPU,u=n.transforms,l=[],c=[];for(let e=0;e$I[t]===e)),s=this.extensions;for(let e=0;e0){if(void 0===l){const i=[];l=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,l);const r=[],u=e.textures;for(let s=0;s,\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:vA,stripIndexFormat:zA},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:vA,stripIndexFormat:zA},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,o=this.getTransferPipeline(i),a=this.getFlipYPipeline(i),h=this.device.createTexture({size:{width:r,height:n,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),u=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:RN,baseArrayLayer:s}),l=h.createView({baseMipLevel:0,mipLevelCount:1,dimension:RN,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),d=(e,t,s)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:s,loadOp:BA,storeOp:RA,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,r),n.draw(4,1,0,0),n.end()};d(o,u,l),d(a,l,u),this.device.queue.submit([c.finish()]),h.destroy()}generateMipmaps(e,t,s=0){const i=this.get(e);void 0===i.useCount&&(i.useCount=0,i.layers=[]);const r=i.layers[s]||this._mipmapCreateBundles(e,t,s),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,r),this.device.queue.submit([n.finish()]),0!==i.useCount&&(i.layers[s]=r),i.useCount++}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:RN,baseArrayLayer:s});const o=[];for(let a=1;a1&&!e.isMultisampleRenderTargetTexture){const e=Object.assign({},p);e.label=e.label+"-msaa",e.sampleCount=l,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=p}destroyTexture(e){const t=this.backend,s=t.get(e);s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else{const s=e.image.depth||1;for(let e=0;e1;for(let o=0;o]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,aP=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,hP={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_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 uP extends IB{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(oP);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=aP.exec(s));)i.push({name:r[1],type:r[2]});const n=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class lP extends BB{parseFunction(e){return new uP(e)}}const cP=self.GPUShaderStage,dP={vertex:cP?cP.VERTEX:1,fragment:cP?cP.FRAGMENT:2,compute:cP?cP.COMPUTE:4},pP={instance:!0,swizzleAssign:!1,storageBuffer:!0},mP={"^^":"tsl_xor"},gP={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",imat2:"mat2x2",umat2:"mat2x2",bmat2:"mat2x2",mat3:"mat3x3",imat3:"mat3x3",umat3:"mat3x3",bmat3:"mat3x3",mat4:"mat4x4",imat4:"mat4x4",umat4:"mat4x4",bmat4:"mat4x4"},fP={tsl_xor:new TS("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new TS("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new TS("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new TS("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new TS("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new TS("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new TS("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new TS("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 TS("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:new TS("\nfn tsl_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 {\n\n\tlet uvScaled = vec2( uv * vec2( dimension ) );\n\n\treturn ( ( uvScaled % dimension ) + dimension ) % dimension;\n\n}\n"),biquadraticTexture:new TS("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, level : i32 ) -> vec4f {\n\n\tlet iRes = vec2i( textureDimensions( map, level ) );\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, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2i( 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")},yP={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"};/Windows/g.test(navigator.userAgent)&&(fP.pow_float=new TS("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),fP.pow_vec2=new TS("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[fP.pow_float]),fP.pow_vec3=new TS("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[fP.pow_float]),fP.pow_vec4=new TS("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[fP.pow_float]),yP.pow_float="tsl_pow_float",yP.pow_vec2="tsl_pow_vec2",yP.pow_vec3="tsl_pow_vec3",yP.pow_vec4="tsl_pow_vec4");let xP="";!0!==/Firefox|Deno/g.test(navigator.userAgent)&&(xP+="diagnostic( off, derivative_uniformity );\n");class bP extends bM{constructor(e,t){super(e,t,new lP),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==Yt}_generateTextureSample(e,t,s,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s):this.generateTextureLod(e,t,s,"0")}_generateVideoSample(e,t,s=this.shaderStage){if("fragment"===s)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${s} shader.`)}_generateTextureSampleLevel(e,t,s,i,r,n=this.shaderStage){return"fragment"===n&&!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,i):this.generateTextureLod(e,t,s,i)}generateFilteredTexture(e,t,s,i="0"){return this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${s}, i32( ${i} ) )`}generateTextureLod(e,t,s,i="0"){this._include("repeatWrapping");return`textureLoad( ${t}, tsl_repeatWrapping( ${s}, ${!0===e.isMultisampleRenderTargetTexture?`textureDimensions( ${t} )`:`textureDimensions( ${t}, 0 )`} ), i32( ${i} ) )`}generateTextureLoad(e,t,s,i,r="0u"){return i?`textureLoad( ${t}, ${s}, ${i}, ${r} )`:`textureLoad( ${t}, ${s}, ${r} )`}generateTextureStore(e,t,s,i){return`textureStore( ${t}, ${s}, ${i} )`}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===Ie||!0===e.isMultisampleRenderTargetTexture}generateTexture(e,t,s,i,r=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,s,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,s,"0",i,r):this._generateTextureSample(e,t,s,i,r),n}generateTextureGrad(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,s,i,r,n=this.shaderStage){let o=null;return o=!0===e.isVideoTexture?this._generateVideoSample(t,s,n):this._generateTextureSampleLevel(e,t,s,i,r,n),o}generateTextureBias(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} 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,s=e.type;return"texture"===s||"cubeTexture"===s||"storageTexture"===s||"texture3D"===s?t:"buffer"===s||"storageBuffer"===s||"indirectStorageBuffer"===s?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=mP[e];return void 0!==t?(this._include(t),t):null}getStorageAccess(e){if(e.isStorageTextureNode)switch(e.access){case TN:return"read";case vN:return"write";default:return"read_write"}else switch(e.access){case xN:return"read_write";case bN:return"read";default:return"write"}}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let i;const o=e.groupNode,a=o.name,h=this.getBindGroupArray(a,s);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let n=null;if("texture"===t||"storageTexture"===t?n=new vI(r.name,r.node,o,e.access?e.access:null):"cubeTexture"===t?n=new TI(r.name,r.node,o,e.access?e.access:null):"texture3D"===t&&(n=new _I(r.name,r.node,o,e.access?e.access:null)),n.store=!0===e.isStorageTextureNode,n.setVisibility(dP[s]),"fragment"===s&&!1===this.isUnfilterable(e.value)&&!1===n.store){const e=new JI(`${r.name}_sampler`,r.node,o);e.setVisibility(dP[s]),h.push(e,n),i=[e,n]}else h.push(n),i=[n]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const r=new("buffer"===t?mI:eP)(e,o);r.setVisibility(dP[s]),h.push(r),i=r}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new yI(a,o),n.setVisibility(dP[s]),e[a]=n,h.push(n)),i=this.getNodeUniform(r,t),n.addUniform(i)}n.uniformGPU=i}return r}getBuiltin(e,t,s,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:s}),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,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n`;return s.result&&(r+=`\treturn ${s.result};\n`),r+="\n}\n",r}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")}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],s=this.directives[e];if(void 0!==s)for(const e of s)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")}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:i,type:r}of s.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,s,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:s,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const n=this.getType(i);t.push(`var<${s}> ${e}: array< ${n}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","id","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 s=this.getAttributesArray();for(let e=0,i=s.length;e`)}const i=this.getBuiltins("output");return i&&t.push("\t"+i),t.join(",\n")}getStructs(e){const t=[],s=this.structs[e];for(let e=0,i=s.length;e output : ${r};\n\n`)}return t.join("\n\n")}getVar(e,t){return`var ${t} : ${this.getType(e)}`}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`\t${this.getVar(e.type,e.name)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];for(let r=0;r";else if(!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array";else if(!0===t.isDepthTexture)i=`texture_depth${n}_2d`;else if(!0===t.isVideoTexture)i="texture_external";else if(!0===t.isData3DTexture)i="texture_3d";else if(!0===r.node.isStorageTextureNode){i=`texture_storage_2d<${nP(t)}, ${this.getStorageAccess(r.node)}>`}else{i=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const e=r.node,t=this.getType(e.bufferType),s=e.bufferCount,n=s>0&&"buffer"===r.type?", "+s:"",a=e.isAtomic?`atomic<${t}>`:`${t}`,h=`\t${r.name} : array< ${a}${n} >\n`,u=e.isStorageBufferNode?`storage, ${this.getStorageAccess(e)}`:"uniform";i.push(this._getWGSLStructBinding("NodeBuffer_"+e.id,h,u,o.binding++,o.group))}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(n[t]||(n[t]={index:o.binding++,id:o.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in n){const t=n[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let o=s.join("\n");return o+=i.join("\n"),o+=r.join("\n"),o}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],n=r[r.length-1],o=n.outputNode,a=void 0!==o&&!0===o.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),h=e.name;if(h&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${h}\n\t`),i+=`${r.code}\n\t`,e===n&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(a)s.returnType=o.nodeType,i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;\n\n",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getType(e){return gP[e]||e}isAvailable(e){let t=pP[e];return void 0===t&&("float32Filterable"===e&&(t=this.renderer.hasFeature("float32-filterable")),pP[e]=t),t}_getWGSLMethod(e){return void 0!==fP[e]&&this._include(e),yP[e]}_include(e){const t=fP[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// 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${xP}\n\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\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){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = id.x + id.y * numWorkgroups.x * u32(${t}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\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,s,i=0,r=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${s}> ${e} : ${n};`}}class vP{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=LA.Depth24PlusStencil8:e.depth&&(t=LA.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}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?fA:e.isLineSegments||e.isMesh&&!0===t.wireframe?yA:e.isLine?xA:e.isMesh?bA:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){return navigator.userAgent.includes("Quest")?LA.BGRA8Unorm:navigator.gpu.getPreferredCanvasFormat()}}const TP=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),_P=new Map([[gn,["float16"]]]),wP=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class SP{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,r=i.get(s);let n=r.buffer;if(void 0===n){const o=i.device;let a=s.array;if(!1===e.normalized&&(a.constructor===Int16Array||a.constructor===Uint16Array)){const e=new Uint32Array(a.length);for(let t=0;t1},layout:u.createPipelineLayout({bindGroupLayouts:d})},A={},N=e.context.depth,C=e.context.stencil;if(!0!==N&&!0!==C||(!0===N&&(A.format=w,A.depthWriteEnabled=i.depthWrite,A.depthCompare=_),!0===C&&(A.stencilFront=f,A.stencilBack={},A.stencilReadMask=i.stencilFuncMask,A.stencilWriteMask=i.stencilWriteMask),M.depthStencil=A),null===t)c.pipeline=u.createRenderPipeline(M);else{const e=new Promise((e=>{u.createRenderPipelineAsync(M).then((t=>{c.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e){const t=this.backend,{utils:s,device:i}=t,r=s.getCurrentDepthStencilFormat(e),n={label:"renderBundleEncoder",colorFormats:[s.getCurrentColorFormat(e)],depthStencilFormat:r,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(n)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),o=[];for(const e of t){const t=s.get(e);o.push(t.layout)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:o})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,o=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,a=null!==e.blendDstAlpha?e.blendDstAlpha:n,h=null!==e.blendEquationAlpha?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(h)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:iN},s={srcFactor:r,dstFactor:n,operation:iN}};if(e.premultipliedAlpha)switch(i){case 1:r(HA,YA,HA,YA);break;case 2:r(HA,HA,HA,HA);break;case 3:r(jA,$A,jA,HA);break;case 4:r(jA,qA,jA,XA)}else switch(i){case 1:r(XA,YA,HA,YA);break;case 2:r(XA,HA,XA,HA);break;case 3:r(jA,$A,jA,HA);break;case 4:r(jA,qA,jA,qA)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case 200:t=jA;break;case 201:t=HA;break;case 202:t=qA;break;case 203:t=$A;break;case R:t=XA;break;case E:t=YA;break;case 208:t=ZA;break;case 209:t=JA;break;case 206:t=KA;break;case 207:t=QA;break;case 210:t=eN;break;case 211:t=tN;break;case 212:t=sN;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=TA;break;case gs:t=CA;break;case 513:t=_A;break;case 515:t=SA;break;case 514:t=wA;break;case 518:t=NA;break;case 516:t=MA;break;case 517:t=AA;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case ts:t=lN;break;case 0:t=cN;break;case 7681:t=dN;break;case 5386:t=pN;break;case 7682:t=mN;break;case 7683:t=gN;break;case 34055:t=fN;break;case 34056:t=yN;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case v:t=iN;break;case 101:t=rN;break;case 102:t=nN;break;case 103:t=oN;break;case 104:t=aN;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?OA:zA),s.side){case c:i.frontFace=IA,i.cullMode=UA;break;case d:i.frontFace=IA,i.cullMode=FA;break;case 2:i.frontFace=IA,i.cullMode=PA;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?uN:hN}_getDepthCompare(e){let t;if(!1===e.depthTest)t=CA;else{const s=e.depthFunc;switch(s){case 0:t=TA;break;case 1:t=CA;break;case 2:t=_A;break;case 3:t=SA;break;case 4:t=wA;break;case 5:t=NA;break;case 6:t=MA;break;case 7:t=AA;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class NP extends BI{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.trackTimestamp=!0===e.trackTimestamp,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new vP(this),this.attributeUtils=new SP(this),this.bindingUtils=new MP(this),this.pipelineUtils=new AP(this),this.textureUtils=new rP(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference},i=await navigator.gpu.requestAdapter(e);if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(ON),n=[];for(const e of r)i.features.has(e)&&n.push(e);const o={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(o)}else s=t.device;const i=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=s,this.context=i;const r=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(ON.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r}),this.updateSize()}get coordinateSystem(){return Os}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 s=e.colorAttachments[0];this.renderer.samples>0?s.view=this.colorBuffer.createView():s.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}_getRenderPassDescriptor(e){const t=e.renderTarget,s=this.get(t);let i=s.descriptors;if(void 0===i||s.width!==t.width||s.height!==t.height||s.activeMipmapLevel!==t.activeMipmapLevel||s.samples!==t.samples){i={},s.descriptors=i;const e=()=>{t.removeEventListener("dispose",e),this.delete(t)};t.addEventListener("dispose",e)}const r=e.getCacheKey();let n=i[r];if(void 0===n){const o=e.textures,a=[];for(let t=0;t0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=s.createQuerySet({type:"occlusion",count:i}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e),this.initTimestampQuery(e,n),n.occlusionQuerySet=r;const o=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),s>0){const i=8*s;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const n=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,n,0,i),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.prepareTimestampBuffer(e,t.encoder),this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eo?(h.x=Math.min(t.dispatchCount,o),h.y=Math.ceil(t.dispatchCount/o)):h.x=t.dispatchCount,r.dispatchWorkgroups(h.x,h.y,h.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.prepareTimestampBuffer(e,t.cmdEncoderGPU),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:s,context:i,pipeline:r}=e,n=e.getBindings(),o=this.get(i),a=this.get(r).pipeline,h=o.currentSets,u=o.currentPass,l=e.getDrawParameters();if(null===l)return;h.pipeline!==a&&(u.setPipeline(a),h.pipeline=a);const c=h.bindingGroups;for(let e=0,t=n.length;e1?0:s;u.drawIndexed(t[s],i,e[s]/n,0,o)}}else if(!0===p){const{vertexCount:i,instanceCount:r,firstVertex:n}=l,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndexedIndirect(e,0)}else u.drawIndexed(i,r,n,0,0);t.update(s,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:n}=l,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndirect(e,0)}else u.draw(i,r,n,0);t.update(s,i,r)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),o=r.getCurrentColorSpace(e.context),a=r.getCurrentColorFormat(e.context),h=r.getCurrentDepthStencilFormat(e.context),u=r.getPrimitiveTopology(s,i);let l=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===o&&t.colorFormat===a&&t.depthStencilFormat===h&&t.primitiveTopology===u&&t.clippingContextCacheKey===e.clippingContext.cacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=n,t.colorSpace=o,t.colorFormat=a,t.depthStencilFormat=h,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContext.cacheKey,l=!0),l}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,r=e.context;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.clippingContext.cacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const s=this.get(e);if(!s.timeStampQuerySet){const e=this.device.createQuerySet({type:"timestamp",count:2}),i={querySet:e,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1};Object.assign(t,{timestampWrites:i}),s.timeStampQuerySet=e}}prepareTimestampBuffer(e,t){if(!this.trackTimestamp)return;const s=this.get(e),i=2*BigInt64Array.BYTES_PER_ELEMENT;void 0===s.currentTimestampQueryBuffers&&(s.currentTimestampQueryBuffers={resolveBuffer:this.device.createBuffer({label:"timestamp resolve buffer",size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),resultBuffer:this.device.createBuffer({label:"timestamp result buffer",size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),isMappingPending:!1});const{resolveBuffer:r,resultBuffer:n,isMappingPending:o}=s.currentTimestampQueryBuffers;!0!==o&&(t.resolveQuerySet(s.timeStampQuerySet,0,2,r,0),t.copyBufferToBuffer(r,0,n,0,i))}async resolveTimestampAsync(e,t="render"){if(!this.trackTimestamp)return;const s=this.get(e);if(void 0===s.currentTimestampQueryBuffers)return;const{resultBuffer:i,isMappingPending:r}=s.currentTimestampQueryBuffers;!0!==r&&(s.currentTimestampQueryBuffers.isMappingPending=!0,i.mapAsync(GPUMapMode.READ).then((()=>{const e=new BigUint64Array(i.getMappedRange()),r=Number(e[1]-e[0])/1e6;this.renderer.info.updateTimestamp(t,r),i.unmap(),s.currentTimestampQueryBuffers.isMappingPending=!1})))}createNodeBuilder(e,t){return new bP(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),i=s.currentPass.finish();this.get(t).bundleGPU=i,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e){this.bindingUtils.createBindings(e)}updateBindings(e){this.bindingUtils.createBindings(e)}updateBinding(e){this.bindingUtils.updateBinding(e)}createIndexAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0){let n=0,o=0,a=0,h=0,u=0,l=0,c=e.image.width,d=e.image.height;null!==s&&(h=s.x,u=s.y,l=s.z||0,c=s.width,d=s.height),null!==i&&(n=i.x,o=i.y,a=i.z||0);const p=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),m=this.get(e).texture,g=this.get(t).texture;p.copyTextureToTexture({texture:m,mipLevel:r,origin:{x:h,y:u,z:l}},{texture:g,mipLevel:r,origin:{x:n,y:o,z:a}},[c,d,1]),this.device.queue.submit([p.finish()])}copyFramebufferToTexture(e,t,s){const i=this.get(t),{encoder:r,descriptor:n}=i;let o=null;o=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const a=this.get(e).texture;if(o.format===a.format){i.currentPass.end(),r.copyTextureToTexture({texture:o,origin:{x:s.x,y:s.y,z:0}},{texture:a},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e);for(let e=0;e(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new YI(e)));super(new t(e),e),this.nodes.library=new RP,this.isWebGPURenderer=!0}}const BP=new pT,IP=new rA(BP);class PP{constructor(e,t=$p(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0,BP.name="PostProcessing"}render(){this.update();const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;e.toneMapping=0,e.outputColorSpace=Jt,IP.render(e),e.toneMapping=t,e.outputColorSpace=s}update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;IP.material.fragmentNode=!0===this.outputColorTransform?Ty(this.outputNode,t,s):this.outputNode.context({toneMapping:t,outputColorSpace:s}),IP.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){this.update();const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;e.toneMapping=0,e.outputColorSpace=Jt,await IP.renderAsync(e),e.toneMapping=t,e.outputColorSpace=s}}function FP(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new Xr),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}function UP(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 OP(e,t,s={}){return(s=FP(e,s)).background=t.background,s.backgroundNode=t.backgroundNode,s.overrideMaterial=t.overrideMaterial,s}var zP=Object.freeze({__proto__:null,resetRendererAndSceneState:function(e,t,s){return s=OP(e,t,s),t.background=null,t.backgroundNode=null,t.overrideMaterial=null,s},resetRendererState:function(e,t){return t=FP(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t},restoreRendererAndSceneState:function(e,t,s){UP(e,s),t.background=s.background,t.backgroundNode=s.backgroundNode,t.overrideMaterial=s.overrideMaterial},restoreRendererState:UP,saveRendererAndSceneState:OP,saveRendererState:FP});class LP extends yi{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=Te,this.minFilter=Te,this.isStorageTexture=!0}}class VP extends an{constructor(e,t,s=Float32Array){!1===ArrayBuffer.isView(e)&&(e=new s(e*t)),super(e,t),this.isStorageBufferAttribute=!0}}class DP extends zo{constructor(e,t,s=Float32Array){!1===ArrayBuffer.isView(e)&&(e=new s(e*t)),super(e,t),this.isStorageInstancedBufferAttribute=!0}}class kP extends VP{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class GP extends el{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,s,i){const r=new il(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,(s=>{try{t(this.parse(JSON.parse(s)))}catch(t){i?i(t):console.error(t),this.manager.itemError(e)}}),s,i)}parseNodes(e){const t={};if(void 0!==e){for(const s of e){const{uuid:e,type:i}=s;t[e]=this.createNodeFromType(i),t[e].uuid=e}const s={nodes:t,textures:this.textures};for(const i of e){i.meta=s;t[i.uuid].deserialize(i),delete i.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const s={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=s,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),Up()):wp(new this.nodes[e])}}class WP extends El{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),s=this.nodes,i=e.inputNodes;for(const e in i){const r=i[e];t[e]=s[r]}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 jP extends Fl{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 s=super.parse(e,t);return this._nodesJSON=null,s}parseNodes(e,t){if(void 0!==e){const s=new GP;return s.setNodes(this.nodes),s.setTextures(t),s.parseNodes(e)}return{}}parseMaterials(e,t){const s={};if(void 0!==e){const i=this.parseNodes(this._nodesJSON,t),r=new WP;r.setTextures(t),r.setNodes(i),r.setNodeMaterials(this.nodeMaterials);for(let t=0,i=e.length;t>8&255]+Ls[e>>16&255]+Ls[e>>24&255]+"-"+Ls[255&t]+Ls[t>>8&255]+"-"+Ls[t>>16&15|64]+Ls[t>>24&255]+"-"+Ls[63&s|128]+Ls[s>>8&255]+"-"+Ls[s>>16&255]+Ls[s>>24&255]+Ls[255&i]+Ls[i>>8&255]+Ls[i>>16&255]+Ls[i>>24&255]).toLowerCase()}function Ws(e,t,s){return Math.max(t,Math.min(s,e))}function js(e,t){return(e%t+t)%t}function Hs(e,t,s){return(1-s)*e+s*t}function qs(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function $s(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Xs={DEG2RAD:Ds,RAD2DEG:ks,generateUUID:Gs,clamp:Ws,euclideanModulo:js,mapLinear:function(e,t,s,i,r){return i+(e-t)*(r-i)/(s-t)},inverseLerp:function(e,t,s){return e!==t?(s-e)/(t-e):0},lerp:Hs,damp:function(e,t,s,i){return Hs(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(js(e,2*t)-t)},smoothstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*(3-2*e)},smootherstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Vs=e);let t=Vs+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*Ds},radToDeg:function(e){return e*ks},isPowerOfTwo:function(e){return 0==(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,s,i,r){const n=Math.cos,o=Math.sin,a=n(s/2),h=o(s/2),u=n((t+i)/2),l=o((t+i)/2),c=n((t-i)/2),d=o((t-i)/2),p=n((i-t)/2),m=o((i-t)/2);switch(r){case"XYX":e.set(a*l,h*c,h*d,a*u);break;case"YZY":e.set(h*d,a*l,h*c,a*u);break;case"ZXZ":e.set(h*c,h*d,a*l,a*u);break;case"XZX":e.set(a*l,h*m,h*p,a*u);break;case"YXY":e.set(h*p,a*l,h*m,a*u);break;case"ZYZ":e.set(h*m,h*p,a*l,a*u);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:$s,denormalize:qs};class Ys{constructor(e=0,t=0){Ys.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Ws(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const s=Math.cos(t),i=Math.sin(t),r=this.x-e.x,n=this.y-e.y;return this.x=r*s-n*i+e.x,this.y=r*i+n*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Zs{constructor(e,t,s,i,r,n,o,a,h){Zs.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,h)}set(e,t,s,i,r,n,o,a,h){const u=this.elements;return u[0]=e,u[1]=i,u[2]=o,u[3]=t,u[4]=r,u[5]=a,u[6]=s,u[7]=n,u[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[3],a=s[6],h=s[1],u=s[4],l=s[7],c=s[2],d=s[5],p=s[8],m=i[0],g=i[3],f=i[6],y=i[1],x=i[4],b=i[7],v=i[2],T=i[5],_=i[8];return r[0]=n*m+o*y+a*v,r[3]=n*g+o*x+a*T,r[6]=n*f+o*b+a*_,r[1]=h*m+u*y+l*v,r[4]=h*g+u*x+l*T,r[7]=h*f+u*b+l*_,r[2]=c*m+d*y+p*v,r[5]=c*g+d*x+p*T,r[8]=c*f+d*b+p*_,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8];return t*n*u-t*o*h-s*r*u+s*o*a+i*r*h-i*n*a}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8],l=u*n-o*h,c=o*a-u*r,d=h*r-n*a,p=t*l+s*c+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=l*m,e[1]=(i*h-u*s)*m,e[2]=(o*s-i*n)*m,e[3]=c*m,e[4]=(u*t-i*a)*m,e[5]=(i*r-o*t)*m,e[6]=d*m,e[7]=(s*a-h*t)*m,e[8]=(n*t-s*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,s,i,r,n,o){const a=Math.cos(r),h=Math.sin(r);return this.set(s*a,s*h,-s*(a*n+h*o)+n+e,-i*h,i*a,-i*(-h*n+a*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Js.makeScale(e,t)),this}rotate(e){return this.premultiply(Js.makeRotation(-e)),this}translate(e,t){return this.premultiply(Js.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<9;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const Js=new Zs;const Ks={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Qs(e,t){return new Ks[e](t)}function ei(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function ti(){const e=ei("canvas");return e.style.display="block",e}const si={};const ii={enabled:!0,workingColorSpace:Jt,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Qt&&(e.r=ri(e.r),e.g=ri(e.g),e.b=ri(e.b)),this.spaces[t].primaries!==this.spaces[s].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Qt&&(e.r=ni(e.r),e.g=ni(e.g),e.b=ni(e.b)),e):e},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===Yt?Kt:this.spaces[e].transfer},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,s){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace}};function ri(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function ni(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}const oi=[.64,.33,.3,.6,.15,.06],ai=[.2126,.7152,.0722],hi=[.3127,.329],ui=(new Zs).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),li=(new Zs).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);let ci;ii.define({[Jt]:{primaries:oi,whitePoint:hi,transfer:Kt,toXYZ:ui,fromXYZ:li,luminanceCoefficients:ai,workingColorSpaceConfig:{unpackColorSpace:Zt},outputColorSpaceConfig:{drawingBufferColorSpace:Zt}},[Zt]:{primaries:oi,whitePoint:hi,transfer:Qt,toXYZ:ui,fromXYZ:li,luminanceCoefficients:ai,outputColorSpaceConfig:{drawingBufferColorSpace:Zt}}});class di{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===ci&&(ci=ei("canvas")),ci.width=e.width,ci.height=e.height;const s=ci.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),t=ci}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=ei("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==ae)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case pe:e.x=e.x-Math.floor(e.x);break;case me:e.x=e.x<0?0:1;break;case ge:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case pe:e.y=e.y-Math.floor(e.y);break;case me:e.y=e.y<0?0:1;break;case ge:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}yi.DEFAULT_IMAGE=null,yi.DEFAULT_MAPPING=ae,yi.DEFAULT_ANISOTROPY=1;class xi{constructor(e=0,t=0,s=0,i=1){xi.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=this.w,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i+n[12]*r,this.y=n[1]*t+n[5]*s+n[9]*i+n[13]*r,this.z=n[2]*t+n[6]*s+n[10]*i+n[14]*r,this.w=n[3]*t+n[7]*s+n[11]*i+n[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,s,i,r;const n=.01,o=.1,a=e.elements,h=a[0],u=a[4],l=a[8],c=a[1],d=a[5],p=a[9],m=a[2],g=a[6],f=a[10];if(Math.abs(u-c)a&&e>y?ey?a=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),n=Math.atan2(r,t*s);e=Math.sin(e*n)/r,o=Math.sin(o*n)/r}const r=o*s;if(a=a*e+c*r,h=h*e+d*r,u=u*e+p*r,l=l*e+m*r,e===1-o){const e=1/Math.sqrt(a*a+h*h+u*u+l*l);a*=e,h*=e,u*=e,l*=e}}e[t]=a,e[t+1]=h,e[t+2]=u,e[t+3]=l}static multiplyQuaternionsFlat(e,t,s,i,r,n){const o=s[i],a=s[i+1],h=s[i+2],u=s[i+3],l=r[n],c=r[n+1],d=r[n+2],p=r[n+3];return e[t]=o*p+u*l+a*d-h*c,e[t+1]=a*p+u*c+h*l-o*d,e[t+2]=h*p+u*d+o*c-a*l,e[t+3]=u*p-o*l-a*c-h*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,r=e._z,n=e._order,o=Math.cos,a=Math.sin,h=o(s/2),u=o(i/2),l=o(r/2),c=a(s/2),d=a(i/2),p=a(r/2);switch(n){case"XYZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"YXZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"ZXY":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"ZYX":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"YZX":this._x=c*u*l+h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l-c*d*p;break;case"XZY":this._x=c*u*l-h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l+c*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],r=t[8],n=t[1],o=t[5],a=t[9],h=t[2],u=t[6],l=t[10],c=s+o+l;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(u-a)*e,this._y=(r-h)*e,this._z=(n-i)*e}else if(s>o&&s>l){const e=2*Math.sqrt(1+s-o-l);this._w=(u-a)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+h)/e}else if(o>l){const e=2*Math.sqrt(1+o-s-l);this._w=(r-h)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(a+u)/e}else{const e=2*Math.sqrt(1+l-s-o);this._w=(n-i)/e,this._x=(r+h)/e,this._y=(a+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return sMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ws(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(0===s)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,i=e._y,r=e._z,n=e._w,o=t._x,a=t._y,h=t._z,u=t._w;return this._x=s*u+n*o+i*h-r*a,this._y=i*u+n*a+r*o-s*h,this._z=r*u+n*h+s*a-i*o,this._w=n*u-s*o-i*a-r*h,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const s=this._x,i=this._y,r=this._z,n=this._w;let o=n*e._w+s*e._x+i*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=n,this._x=s,this._y=i,this._z=r,this;const a=1-o*o;if(a<=Number.EPSILON){const e=1-t;return this._w=e*n+t*this._w,this._x=e*s+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const h=Math.sqrt(a),u=Math.atan2(h,o),l=Math.sin((1-t)*u)/h,c=Math.sin(t*u)/h;return this._w=n*l+this._w*c,this._x=s*l+this._x*c,this._y=i*l+this._y*c,this._z=r*l+this._z*c,this._onChangeCallback(),this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),r=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ai{constructor(e=0,t=0,s=0){Ai.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return void 0===s&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Ci.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ci.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6]*i,this.y=r[1]*t+r[4]*s+r[7]*i,this.z=r[2]*t+r[5]*s+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=e.elements,n=1/(r[3]*t+r[7]*s+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*s+r[8]*i+r[12])*n,this.y=(r[1]*t+r[5]*s+r[9]*i+r[13])*n,this.z=(r[2]*t+r[6]*s+r[10]*i+r[14])*n,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,r=e.x,n=e.y,o=e.z,a=e.w,h=2*(n*i-o*s),u=2*(o*t-r*i),l=2*(r*s-n*t);return this.x=t+a*h+n*l-o*u,this.y=s+a*u+o*h-r*l,this.z=i+a*l+r*u-n*h,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i,this.y=r[1]*t+r[5]*s+r[9]*i,this.z=r[2]*t+r[6]*s+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,r=e.z,n=t.x,o=t.y,a=t.z;return this.x=i*a-r*o,this.y=r*n-s*a,this.z=s*o-i*n,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Ni.copy(this).projectOnVector(e),this.sub(Ni)}reflect(e){return this.sub(Ni.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Ws(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ni=new Ai,Ci=new Mi;class Ri{constructor(e=new Ai(1/0,1/0,1/0),t=new Ai(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Bi),Bi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Vi),Di.subVectors(this.max,Vi),Pi.subVectors(e.a,Vi),Fi.subVectors(e.b,Vi),Ui.subVectors(e.c,Vi),Oi.subVectors(Fi,Pi),zi.subVectors(Ui,Fi),Li.subVectors(Pi,Ui);let t=[0,-Oi.z,Oi.y,0,-zi.z,zi.y,0,-Li.z,Li.y,Oi.z,0,-Oi.x,zi.z,0,-zi.x,Li.z,0,-Li.x,-Oi.y,Oi.x,0,-zi.y,zi.x,0,-Li.y,Li.x,0];return!!Wi(t,Pi,Fi,Ui,Di)&&(t=[1,0,0,0,1,0,0,0,1],!!Wi(t,Pi,Fi,Ui,Di)&&(ki.crossVectors(Oi,zi),t=[ki.x,ki.y,ki.z],Wi(t,Pi,Fi,Ui,Di)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Bi).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Ei[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ei[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ei[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ei[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ei[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ei[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ei[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ei[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ei)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Ei=[new Ai,new Ai,new Ai,new Ai,new Ai,new Ai,new Ai,new Ai],Bi=new Ai,Ii=new Ri,Pi=new Ai,Fi=new Ai,Ui=new Ai,Oi=new Ai,zi=new Ai,Li=new Ai,Vi=new Ai,Di=new Ai,ki=new Ai,Gi=new Ai;function Wi(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){Gi.fromArray(e,n);const o=r.x*Math.abs(Gi.x)+r.y*Math.abs(Gi.y)+r.z*Math.abs(Gi.z),a=t.dot(Gi),h=s.dot(Gi),u=i.dot(Gi);if(Math.max(-Math.max(a,h,u),Math.min(a,h,u))>o)return!1}return!0}const ji=new Ri,Hi=new Ai,qi=new Ai;class $i{constructor(e=new Ai,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const s=this.center;void 0!==t?s.copy(t):ji.setFromPoints(e).getCenter(s);let i=0;for(let t=0,r=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Hi.subVectors(e,this.center);const t=Hi.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Hi,s/e),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(qi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Hi.copy(e.center).add(qi)),this.expandByPoint(Hi.copy(e.center).sub(qi))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Xi=new Ai,Yi=new Ai,Zi=new Ai,Ji=new Ai,Ki=new Ai,Qi=new Ai,er=new Ai;class tr{constructor(e=new Ai,t=new Ai(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Xi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Xi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Xi.copy(this.origin).addScaledVector(this.direction,t),Xi.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){Yi.copy(e).add(t).multiplyScalar(.5),Zi.copy(t).sub(e).normalize(),Ji.copy(this.origin).sub(Yi);const r=.5*e.distanceTo(t),n=-this.direction.dot(Zi),o=Ji.dot(this.direction),a=-Ji.dot(Zi),h=Ji.lengthSq(),u=Math.abs(1-n*n);let l,c,d,p;if(u>0)if(l=n*a-o,c=n*o-a,p=r*u,l>=0)if(c>=-p)if(c<=p){const e=1/u;l*=e,c*=e,d=l*(l+n*c+2*o)+c*(n*l+c+2*a)+h}else c=r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;else c=-r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;else c<=-p?(l=Math.max(0,-(-n*r+o)),c=l>0?-r:Math.min(Math.max(-r,-a),r),d=-l*l+c*(c+2*a)+h):c<=p?(l=0,c=Math.min(Math.max(-r,-a),r),d=c*(c+2*a)+h):(l=Math.max(0,-(n*r+o)),c=l>0?r:Math.min(Math.max(-r,-a),r),d=-l*l+c*(c+2*a)+h);else c=n>0?-r:r,l=Math.max(0,-(n*c+o)),d=-l*l+c*(c+2*a)+h;return s&&s.copy(this.origin).addScaledVector(this.direction,l),i&&i.copy(Yi).addScaledVector(Zi,c),d}intersectSphere(e,t){Xi.subVectors(e.center,this.origin);const s=Xi.dot(this.direction),i=Xi.dot(Xi)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),o=s-n,a=s+n;return a<0?null:o<0?this.at(a,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return null===s?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,r,n,o,a;const h=1/this.direction.x,u=1/this.direction.y,l=1/this.direction.z,c=this.origin;return h>=0?(s=(e.min.x-c.x)*h,i=(e.max.x-c.x)*h):(s=(e.max.x-c.x)*h,i=(e.min.x-c.x)*h),u>=0?(r=(e.min.y-c.y)*u,n=(e.max.y-c.y)*u):(r=(e.max.y-c.y)*u,n=(e.min.y-c.y)*u),s>n||r>i?null:((r>s||isNaN(s))&&(s=r),(n=0?(o=(e.min.z-c.z)*l,a=(e.max.z-c.z)*l):(o=(e.max.z-c.z)*l,a=(e.min.z-c.z)*l),s>a||o>i?null:((o>s||s!=s)&&(s=o),(a=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Xi)}intersectTriangle(e,t,s,i,r){Ki.subVectors(t,e),Qi.subVectors(s,e),er.crossVectors(Ki,Qi);let n,o=this.direction.dot(er);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}Ji.subVectors(this.origin,e);const a=n*this.direction.dot(Qi.crossVectors(Ji,Qi));if(a<0)return null;const h=n*this.direction.dot(Ki.cross(Ji));if(h<0)return null;if(a+h>o)return null;const u=-n*Ji.dot(er);return u<0?null:this.at(u/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class sr{constructor(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g){sr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g)}set(e,t,s,i,r,n,o,a,h,u,l,c,d,p,m,g){const f=this.elements;return f[0]=e,f[4]=t,f[8]=s,f[12]=i,f[1]=r,f[5]=n,f[9]=o,f[13]=a,f[2]=h,f[6]=u,f[10]=l,f[14]=c,f[3]=d,f[7]=p,f[11]=m,f[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new sr).fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,s){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,s=e.elements,i=1/ir.setFromMatrixColumn(e,0).length(),r=1/ir.setFromMatrixColumn(e,1).length(),n=1/ir.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*r,t[5]=s[5]*r,t[6]=s[6]*r,t[7]=0,t[8]=s[8]*n,t[9]=s[9]*n,t[10]=s[10]*n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,r=e.z,n=Math.cos(s),o=Math.sin(s),a=Math.cos(i),h=Math.sin(i),u=Math.cos(r),l=Math.sin(r);if("XYZ"===e.order){const e=n*u,s=n*l,i=o*u,r=o*l;t[0]=a*u,t[4]=-a*l,t[8]=h,t[1]=s+i*h,t[5]=e-r*h,t[9]=-o*a,t[2]=r-e*h,t[6]=i+s*h,t[10]=n*a}else if("YXZ"===e.order){const e=a*u,s=a*l,i=h*u,r=h*l;t[0]=e+r*o,t[4]=i*o-s,t[8]=n*h,t[1]=n*l,t[5]=n*u,t[9]=-o,t[2]=s*o-i,t[6]=r+e*o,t[10]=n*a}else if("ZXY"===e.order){const e=a*u,s=a*l,i=h*u,r=h*l;t[0]=e-r*o,t[4]=-n*l,t[8]=i+s*o,t[1]=s+i*o,t[5]=n*u,t[9]=r-e*o,t[2]=-n*h,t[6]=o,t[10]=n*a}else if("ZYX"===e.order){const e=n*u,s=n*l,i=o*u,r=o*l;t[0]=a*u,t[4]=i*h-s,t[8]=e*h+r,t[1]=a*l,t[5]=r*h+e,t[9]=s*h-i,t[2]=-h,t[6]=o*a,t[10]=n*a}else if("YZX"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*u,t[4]=r-e*l,t[8]=i*l+s,t[1]=l,t[5]=n*u,t[9]=-o*u,t[2]=-h*u,t[6]=s*l+i,t[10]=e-r*l}else if("XZY"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*u,t[4]=-l,t[8]=h*u,t[1]=e*l+r,t[5]=n*u,t[9]=s*l-i,t[2]=i*l-s,t[6]=o*u,t[10]=r*l+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(nr,e,or)}lookAt(e,t,s){const i=this.elements;return ur.subVectors(e,t),0===ur.lengthSq()&&(ur.z=1),ur.normalize(),ar.crossVectors(s,ur),0===ar.lengthSq()&&(1===Math.abs(s.z)?ur.x+=1e-4:ur.z+=1e-4,ur.normalize(),ar.crossVectors(s,ur)),ar.normalize(),hr.crossVectors(ur,ar),i[0]=ar.x,i[4]=hr.x,i[8]=ur.x,i[1]=ar.y,i[5]=hr.y,i[9]=ur.y,i[2]=ar.z,i[6]=hr.z,i[10]=ur.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[4],a=s[8],h=s[12],u=s[1],l=s[5],c=s[9],d=s[13],p=s[2],m=s[6],g=s[10],f=s[14],y=s[3],x=s[7],b=s[11],v=s[15],T=i[0],_=i[4],w=i[8],S=i[12],M=i[1],A=i[5],N=i[9],C=i[13],R=i[2],E=i[6],B=i[10],I=i[14],P=i[3],F=i[7],U=i[11],O=i[15];return r[0]=n*T+o*M+a*R+h*P,r[4]=n*_+o*A+a*E+h*F,r[8]=n*w+o*N+a*B+h*U,r[12]=n*S+o*C+a*I+h*O,r[1]=u*T+l*M+c*R+d*P,r[5]=u*_+l*A+c*E+d*F,r[9]=u*w+l*N+c*B+d*U,r[13]=u*S+l*C+c*I+d*O,r[2]=p*T+m*M+g*R+f*P,r[6]=p*_+m*A+g*E+f*F,r[10]=p*w+m*N+g*B+f*U,r[14]=p*S+m*C+g*I+f*O,r[3]=y*T+x*M+b*R+v*P,r[7]=y*_+x*A+b*E+v*F,r[11]=y*w+x*N+b*B+v*U,r[15]=y*S+x*C+b*I+v*O,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[4],i=e[8],r=e[12],n=e[1],o=e[5],a=e[9],h=e[13],u=e[2],l=e[6],c=e[10],d=e[14];return e[3]*(+r*a*l-i*h*l-r*o*c+s*h*c+i*o*d-s*a*d)+e[7]*(+t*a*d-t*h*c+r*n*c-i*n*d+i*h*u-r*a*u)+e[11]*(+t*h*l-t*o*d-r*n*l+s*n*d+r*o*u-s*h*u)+e[15]*(-i*o*u-t*a*l+t*o*c+i*n*l-s*n*c+s*a*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],u=e[8],l=e[9],c=e[10],d=e[11],p=e[12],m=e[13],g=e[14],f=e[15],y=l*g*h-m*c*h+m*a*d-o*g*d-l*a*f+o*c*f,x=p*c*h-u*g*h-p*a*d+n*g*d+u*a*f-n*c*f,b=u*m*h-p*l*h+p*o*d-n*m*d-u*o*f+n*l*f,v=p*l*a-u*m*a-p*o*c+n*m*c+u*o*g-n*l*g,T=t*y+s*x+i*b+r*v;if(0===T)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const _=1/T;return e[0]=y*_,e[1]=(m*c*r-l*g*r-m*i*d+s*g*d+l*i*f-s*c*f)*_,e[2]=(o*g*r-m*a*r+m*i*h-s*g*h-o*i*f+s*a*f)*_,e[3]=(l*a*r-o*c*r-l*i*h+s*c*h+o*i*d-s*a*d)*_,e[4]=x*_,e[5]=(u*g*r-p*c*r+p*i*d-t*g*d-u*i*f+t*c*f)*_,e[6]=(p*a*r-n*g*r-p*i*h+t*g*h+n*i*f-t*a*f)*_,e[7]=(n*c*r-u*a*r+u*i*h-t*c*h-n*i*d+t*a*d)*_,e[8]=b*_,e[9]=(p*l*r-u*m*r-p*s*d+t*m*d+u*s*f-t*l*f)*_,e[10]=(n*m*r-p*o*r+p*s*h-t*m*h-n*s*f+t*o*f)*_,e[11]=(u*o*r-n*l*r-u*s*h+t*l*h+n*s*d-t*o*d)*_,e[12]=v*_,e[13]=(u*m*i-p*l*i+p*s*c-t*m*c-u*s*g+t*l*g)*_,e[14]=(p*o*i-n*m*i-p*s*a+t*m*a+n*s*g-t*o*g)*_,e[15]=(n*l*i-u*o*i+u*s*a-t*l*a-n*s*c+t*o*c)*_,this}scale(e){const t=this.elements,s=e.x,i=e.y,r=e.z;return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),r=1-s,n=e.x,o=e.y,a=e.z,h=r*n,u=r*o;return this.set(h*n+s,h*o-i*a,h*a+i*o,0,h*o+i*a,u*o+s,u*a-i*n,0,h*a-i*o,u*a+i*n,r*a*a+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,r,n){return this.set(1,s,r,0,e,1,n,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,r=t._x,n=t._y,o=t._z,a=t._w,h=r+r,u=n+n,l=o+o,c=r*h,d=r*u,p=r*l,m=n*u,g=n*l,f=o*l,y=a*h,x=a*u,b=a*l,v=s.x,T=s.y,_=s.z;return i[0]=(1-(m+f))*v,i[1]=(d+b)*v,i[2]=(p-x)*v,i[3]=0,i[4]=(d-b)*T,i[5]=(1-(c+f))*T,i[6]=(g+y)*T,i[7]=0,i[8]=(p+x)*_,i[9]=(g-y)*_,i[10]=(1-(c+m))*_,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;let r=ir.set(i[0],i[1],i[2]).length();const n=ir.set(i[4],i[5],i[6]).length(),o=ir.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],rr.copy(this);const a=1/r,h=1/n,u=1/o;return rr.elements[0]*=a,rr.elements[1]*=a,rr.elements[2]*=a,rr.elements[4]*=h,rr.elements[5]*=h,rr.elements[6]*=h,rr.elements[8]*=u,rr.elements[9]*=u,rr.elements[10]*=u,t.setFromRotationMatrix(rr),s.x=r,s.y=n,s.z=o,this}makePerspective(e,t,s,i,r,n,o=2e3){const a=this.elements,h=2*r/(t-e),u=2*r/(s-i),l=(t+e)/(t-e),c=(s+i)/(s-i);let d,p;if(o===Us)d=-(n+r)/(n-r),p=-2*n*r/(n-r);else{if(o!==Os)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-n/(n-r),p=-n*r/(n-r)}return a[0]=h,a[4]=0,a[8]=l,a[12]=0,a[1]=0,a[5]=u,a[9]=c,a[13]=0,a[2]=0,a[6]=0,a[10]=d,a[14]=p,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(e,t,s,i,r,n,o=2e3){const a=this.elements,h=1/(t-e),u=1/(s-i),l=1/(n-r),c=(t+e)*h,d=(s+i)*u;let p,m;if(o===Us)p=(n+r)*l,m=-2*l;else{if(o!==Os)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);p=r*l,m=-1*l}return a[0]=2*h,a[4]=0,a[8]=0,a[12]=-c,a[1]=0,a[5]=2*u,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=m,a[14]=-p,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<16;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const ir=new Ai,rr=new sr,nr=new Ai(0,0,0),or=new Ai(1,1,1),ar=new Ai,hr=new Ai,ur=new Ai,lr=new sr,cr=new Mi;class dr{constructor(e=0,t=0,s=0,i=dr.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,r=i[0],n=i[4],o=i[8],a=i[1],h=i[5],u=i[9],l=i[2],c=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Ws(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(c,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Ws(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,h)):(this._y=Math.atan2(-l,r),this._z=0);break;case"ZXY":this._x=Math.asin(Ws(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(-l,d),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(a,r));break;case"ZYX":this._y=Math.asin(-Ws(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(a,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(Ws(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,h),this._y=Math.atan2(-l,r)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-Ws(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,h),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-u,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return lr.makeRotationFromQuaternion(e),this.setFromRotationMatrix(lr,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return cr.setFromEuler(this),this.setFromQuaternion(cr,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}dr.DEFAULT_ORDER="XYZ";class pr{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const s=t.shapes;if(Array.isArray(s))for(let t=0,i=s.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(s.geometries=t),i.length>0&&(s.materials=i),r.length>0&&(s.textures=r),o.length>0&&(s.images=o),a.length>0&&(s.shapes=a),h.length>0&&(s.skeletons=h),u.length>0&&(s.animations=u),l.length>0&&(s.nodes=l)}return s.object=i,s;function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,s,i,r){Er.subVectors(i,t),Br.subVectors(s,t),Ir.subVectors(e,t);const n=Er.dot(Er),o=Er.dot(Br),a=Er.dot(Ir),h=Br.dot(Br),u=Br.dot(Ir),l=n*h-o*o;if(0===l)return r.set(0,0,0),null;const c=1/l,d=(h*a-o*u)*c,p=(n*u-o*a)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,Pr)&&(Pr.x>=0&&Pr.y>=0&&Pr.x+Pr.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,Pr)?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(r,Pr.x),a.addScaledVector(n,Pr.y),a.addScaledVector(o,Pr.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return Dr.setScalar(0),kr.setScalar(0),Gr.setScalar(0),Dr.fromBufferAttribute(e,t),kr.fromBufferAttribute(e,s),Gr.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Dr,r.x),n.addScaledVector(kr,r.y),n.addScaledVector(Gr,r.z),n}static isFrontFacing(e,t,s,i){return Er.subVectors(s,t),Br.subVectors(e,t),Er.cross(Br).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Er.subVectors(this.c,this.b),Br.subVectors(this.a,this.b),.5*Er.cross(Br).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Wr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Wr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Wr.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Wr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Wr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,r=this.c;let n,o;Fr.subVectors(i,s),Ur.subVectors(r,s),zr.subVectors(e,s);const a=Fr.dot(zr),h=Ur.dot(zr);if(a<=0&&h<=0)return t.copy(s);Lr.subVectors(e,i);const u=Fr.dot(Lr),l=Ur.dot(Lr);if(u>=0&&l<=u)return t.copy(i);const c=a*l-u*h;if(c<=0&&a>=0&&u<=0)return n=a/(a-u),t.copy(s).addScaledVector(Fr,n);Vr.subVectors(e,r);const d=Fr.dot(Vr),p=Ur.dot(Vr);if(p>=0&&d<=p)return t.copy(r);const m=d*h-a*p;if(m<=0&&h>=0&&p<=0)return o=h/(h-p),t.copy(s).addScaledVector(Ur,o);const g=u*p-d*l;if(g<=0&&l-u>=0&&d-p>=0)return Or.subVectors(r,i),o=(l-u)/(l-u+(d-p)),t.copy(i).addScaledVector(Or,o);const f=1/(g+m+c);return n=m*f,o=c*f,t.copy(s).addScaledVector(Fr,n).addScaledVector(Ur,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const jr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Hr={h:0,s:0,l:0},qr={h:0,s:0,l:0};function $r(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class Xr{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Zt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,ii.toWorkingColorSpace(this,t),this}setRGB(e,t,s,i=ii.workingColorSpace){return this.r=e,this.g=t,this.b=s,ii.toWorkingColorSpace(this,i),this}setHSL(e,t,s,i=ii.workingColorSpace){if(e=js(e,1),t=Ws(t,0,1),s=Ws(s,0,1),0===t)this.r=this.g=this.b=s;else{const i=s<=.5?s*(1+t):s+t-s*t,r=2*s-i;this.r=$r(r,i,e+1/3),this.g=$r(r,i,e),this.b=$r(r,i,e-1/3)}return ii.toWorkingColorSpace(this,i),this}setStyle(e,t=Zt){function s(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],o=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],r=s.length;if(3===r)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Zt){const s=jr[e.toLowerCase()];return void 0!==s?this.setHex(s,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=ri(e.r),this.g=ri(e.g),this.b=ri(e.b),this}copyLinearToSRGB(e){return this.r=ni(e.r),this.g=ni(e.g),this.b=ni(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Zt){return ii.fromWorkingColorSpace(Yr.copy(this),e),65536*Math.round(Ws(255*Yr.r,0,255))+256*Math.round(Ws(255*Yr.g,0,255))+Math.round(Ws(255*Yr.b,0,255))}getHexString(e=Zt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ii.workingColorSpace){ii.fromWorkingColorSpace(Yr.copy(this),t);const s=Yr.r,i=Yr.g,r=Yr.b,n=Math.max(s,i,r),o=Math.min(s,i,r);let a,h;const u=(o+n)/2;if(o===n)a=0,h=0;else{const e=n-o;switch(h=u<=.5?e/(n+o):e/(2-n-o),n){case s:a=(i-r)/e+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const s=e[t];if(void 0===s){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s:console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const s={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),void 0!==this.roughness&&(s.roughness=this.roughness),void 0!==this.metalness&&(s.metalness=this.metalness),void 0!==this.sheen&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(s.shininess=this.shininess),void 0!==this.clearcoat&&(s.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(s.dispersion=this.dispersion),void 0!==this.iridescence&&(s.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(s.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(s.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(s.combine=this.combine)),void 0!==this.envMapRotation&&(s.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(s.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(s.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(s.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(s.size=this.size),null!==this.shadowSide&&(s.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(s.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(s.blending=this.blending),this.side!==c&&(s.side=this.side),!0===this.vertexColors&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),!0===this.transparent&&(s.transparent=!0),this.blendSrc!==R&&(s.blendSrc=this.blendSrc),this.blendDst!==E&&(s.blendDst=this.blendDst),this.blendEquation!==v&&(s.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(s.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(s.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(s.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(s.depthFunc=this.depthFunc),!1===this.depthTest&&(s.depthTest=this.depthTest),!1===this.depthWrite&&(s.depthWrite=this.depthWrite),!1===this.colorWrite&&(s.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==gs&&(s.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(s.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ts&&(s.stencilFail=this.stencilFail),this.stencilZFail!==ts&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==ts&&(s.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(s.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(s.rotation=this.rotation),!0===this.polygonOffset&&(s.polygonOffset=!0),0!==this.polygonOffsetFactor&&(s.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(s.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(s.linewidth=this.linewidth),void 0!==this.dashSize&&(s.dashSize=this.dashSize),void 0!==this.gapSize&&(s.gapSize=this.gapSize),void 0!==this.scale&&(s.scale=this.scale),!0===this.dithering&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),!0===this.alphaHash&&(s.alphaHash=!0),!0===this.alphaToCoverage&&(s.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(s.premultipliedAlpha=!0),!0===this.forceSinglePass&&(s.forceSinglePass=!0),!0===this.wireframe&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(s.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(s.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(s.flatShading=!0),!1===this.visible&&(s.visible=!1),!1===this.toneMapped&&(s.toneMapped=!1),!1===this.fog&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(s.textures=t),r.length>0&&(s.images=r)}return s}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let s=null;if(null!==t){const e=t.length;s=new Array(e);for(let i=0;i!==e;++i)s[i]=t[i].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Kr extends Jr{static get type(){return"MeshBasicMaterial"}constructor(e){super(),this.isMeshBasicMaterial=!0,this.color=new Xr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Qr=en();function en(){const e=new ArrayBuffer(4),t=new Float32Array(e),s=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const n=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,s=0;for(;0==(8388608&t);)t<<=1,s-=8388608;t&=-8388609,s+=947912704,n[e]=t|s}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(a[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:o,offsetTable:a}}function tn(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Ws(e,-65504,65504),Qr.floatView[0]=e;const t=Qr.uint32View[0],s=t>>23&511;return Qr.baseTable[s]+((8388607&t)>>Qr.shiftTable[s])}function sn(e){const t=e>>10;return Qr.uint32View[0]=Qr.mantissaTable[Qr.offsetTable[t]+(1023&e)]+Qr.exponentTable[t],Qr.floatView[0]}const rn={toHalfFloat:tn,fromHalfFloat:sn},nn=new Ai,on=new Ys;class an{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Ss,this.updateRanges=[],this.gpuType=Ie,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,r=this.itemSize;i=0;--t)if(e[t]>=65535)return!0;return!1}(e)?mn:dn)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(void 0!==s){const t=(new Zs).getNormalMatrix(e);s.applyNormalMatrix(t),s.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return xn.makeRotationFromQuaternion(e),this.applyMatrix4(xn),this}rotateX(e){return xn.makeRotationX(e),this.applyMatrix4(xn),this}rotateY(e){return xn.makeRotationY(e),this.applyMatrix4(xn),this}rotateZ(e){return xn.makeRotationZ(e),this.applyMatrix4(xn),this}translate(e,t,s){return xn.makeTranslation(e,t,s),this.applyMatrix4(xn),this}scale(e,t,s){return xn.makeScale(e,t,s),this.applyMatrix4(xn),this}lookAt(e){return bn.lookAt(e),bn.updateMatrix(),this.applyMatrix4(bn.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(vn).negate(),this.translate(vn.x,vn.y,vn.z),this}setFromPoints(e){const t=[];for(let s=0,i=e.length;s0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const s in t)void 0!==t[s]&&(e[s]=t[s]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const t in s){const i=s[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const s=this.morphAttributes[t],n=[];for(let t=0,i=s.length;t0&&(i[t]=n,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(e.data.groups=JSON.parse(JSON.stringify(n)));const o=this.boundingSphere;return null!==o&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const s=e.index;null!==s&&this.setIndex(s.clone(t));const i=e.attributes;for(const e in i){const s=i[e];this.setAttribute(e,s.clone(t))}const r=e.morphAttributes;for(const e in r){const s=[],i=r[e];for(let e=0,r=i.length;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;e(e.far-e.near)**2)return}Mn.copy(r).invert(),An.copy(e.ray).applyMatrix4(Mn),null!==s.boundingBox&&!1===An.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,An)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,o=r.index,a=r.attributes.position,h=r.attributes.uv,u=r.attributes.uv1,l=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==o)if(Array.isArray(n))for(let r=0,a=c.length;rs.far?null:{distance:u,point:Un.clone(),object:e}}(e,t,s,i,Rn,En,Bn,Fn);if(l){const e=new Ai;Wr.getBarycoord(Fn,Rn,En,Bn,e),r&&(l.uv=Wr.getInterpolatedAttribute(r,a,h,u,e,new Ys)),n&&(l.uv1=Wr.getInterpolatedAttribute(n,a,h,u,e,new Ys)),o&&(l.normal=Wr.getInterpolatedAttribute(o,a,h,u,e,new Ai),l.normal.dot(i.direction)>0&&l.normal.multiplyScalar(-1));const t={a:a,b:h,c:u,normal:new Ai,materialIndex:0};Wr.getNormal(Rn,En,Bn,t.normal),l.face=t,l.barycoord=e}return l}class Ln extends Sn{constructor(e=1,t=1,s=1,i=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:r,depthSegments:n};const o=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const a=[],h=[],u=[],l=[];let c=0,d=0;function p(e,t,s,i,r,n,p,m,g,f,y){const x=n/g,b=p/f,v=n/2,T=p/2,_=m/2,w=g+1,S=f+1;let M=0,A=0;const N=new Ai;for(let n=0;n0?1:-1,u.push(N.x,N.y,N.z),l.push(a/g),l.push(1-n/f),M+=1}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const e in this.extensions)!0===this.extensions[e]&&(s[e]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class kn extends Rr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new sr,this.projectionMatrix=new sr,this.projectionMatrixInverse=new sr,this.coordinateSystem=Us}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Gn=new Ai,Wn=new Ys,jn=new Ys;class Hn extends kn{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*ks*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Ds*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*ks*Math.atan(Math.tan(.5*Ds*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,s){Gn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Gn.x,Gn.y).multiplyScalar(-e/Gn.z),Gn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Gn.x,Gn.y).multiplyScalar(-e/Gn.z)}getViewSize(e,t){return this.getViewBounds(e,Wn,jn),t.subVectors(jn,Wn)}setViewOffset(e,t,s,i,r,n){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*Ds*this.fov)/this.zoom,s=2*t,i=this.aspect*s,r=-.5*i;const n=this.view;if(null!==this.view&&this.view.enabled){const e=n.fullWidth,o=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/o,i*=n.width/e,s*=n.height/o}const o=this.filmOffset;0!==o&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-s,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const qn=-90;class $n extends Rr{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Hn(qn,1,e,t);i.layers=this.layers,this.add(i);const r=new Hn(qn,1,e,t);r.layers=this.layers,this.add(r);const n=new Hn(qn,1,e,t);n.layers=this.layers,this.add(n);const o=new Hn(qn,1,e,t);o.layers=this.layers,this.add(o);const a=new Hn(qn,1,e,t);a.layers=this.layers,this.add(a);const h=new Hn(qn,1,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,o,a]=t;for(const e of t)this.remove(e);if(e===Us)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else{if(e!==Os)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,n,o,a,h,u]=this.children,l=e.getRenderTarget(),c=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1,e.setRenderTarget(s,0,i),e.render(t,r),e.setRenderTarget(s,1,i),e.render(t,n),e.setRenderTarget(s,2,i),e.render(t,o),e.setRenderTarget(s,3,i),e.render(t,a),e.setRenderTarget(s,4,i),e.render(t,h),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,u),e.setRenderTarget(l,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Xn extends yi{constructor(e,t,s,i,r,n,o,a,h,u){super(e=void 0!==e?e:[],t=void 0!==t?t:he,s,i,r,n,o,a,h,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Yn extends vi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Xn(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:Te}fromEquirectangularTexture(e,t){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 s={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Ln(5,5,5),r=new Dn({name:"CubemapFromEquirect",uniforms:Vn(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:d,blending:m});r.uniforms.tEquirect.value=t;const n=new On(i,r),o=t.minFilter;t.minFilter===Se&&(t.minFilter=Te);return new $n(1,10,this).update(e,n),t.minFilter=o,n.geometry.dispose(),n.material.dispose(),this}clear(e,t,s,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}class Zn{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new Xr(e),this.density=t}clone(){return new Zn(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Jn{constructor(e,t=1,s=1e3){this.isFog=!0,this.name="",this.color=new Xr(e),this.near=t,this.far=s}clone(){return new Jn(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Kn extends Rr{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new dr,this.environmentIntensity=1,this.environmentRotation=new dr,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Qn{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Ss,this.updateRanges=[],this.version=0,this.uuid=Gs()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,s){e*=this.stride,s*=t.stride;for(let i=0,r=this.stride;ie.far||t.push({distance:a,point:ro.clone(),uv:Wr.getInterpolation(ro,lo,co,po,mo,go,fo,new Ys),face:null,object:this})}copy(e,t){return super.copy(e,t),void 0!==e.center&&this.center.copy(e.center),this.material=e.material,this}}function xo(e,t,s,i,r,n){ao.subVectors(e,s).addScalar(.5).multiply(i),void 0!==r?(ho.x=n*ao.x-r*ao.y,ho.y=r*ao.x+n*ao.y):ho.copy(ao),e.copy(t),e.x+=ho.x,e.y+=ho.y,e.applyMatrix4(uo)}const bo=new Ai,vo=new Ai;class To extends Rr{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let e=0,s=t.length;e0){let s,i;for(s=1,i=t.length;s0){bo.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(bo);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){bo.setFromMatrixPosition(e.matrixWorld),vo.setFromMatrixPosition(this.matrixWorld);const s=bo.distanceTo(vo)/e.zoom;let i,r;for(t[0].object.visible=!0,i=1,r=t.length;i=e))break;t[i-1].object.visible=!1,t[i].object.visible=!0}for(this._currentLevel=i-1;i1?null:t.copy(e.start).addScaledVector(s,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const s=t||Xo.getNormalMatrix(e),i=this.coplanarPoint(qo).applyMatrix4(e),r=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const Zo=new $i,Jo=new Ai;class Ko{constructor(e=new Yo,t=new Yo,s=new Yo,i=new Yo,r=new Yo,n=new Yo){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(s),o[3].copy(i),o[4].copy(r),o[5].copy(n),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=2e3){const s=this.planes,i=e.elements,r=i[0],n=i[1],o=i[2],a=i[3],h=i[4],u=i[5],l=i[6],c=i[7],d=i[8],p=i[9],m=i[10],g=i[11],f=i[12],y=i[13],x=i[14],b=i[15];if(s[0].setComponents(a-r,c-h,g-d,b-f).normalize(),s[1].setComponents(a+r,c+h,g+d,b+f).normalize(),s[2].setComponents(a+n,c+u,g+p,b+y).normalize(),s[3].setComponents(a-n,c-u,g-p,b-y).normalize(),s[4].setComponents(a-o,c-l,g-m,b-x).normalize(),t===Us)s[5].setComponents(a+o,c+l,g+m,b+x).normalize();else{if(t!==Os)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);s[5].setComponents(o,l,m,x).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Zo.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Zo.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Zo)}intersectsSprite(e){return Zo.center.set(0,0,0),Zo.radius=.7071067811865476,Zo.applyMatrix4(e.matrixWorld),this.intersectsSphere(Zo)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(s)0?e.max.x:e.min.x,Jo.y=i.normal.y>0?e.max.y:e.min.y,Jo.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Jo)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function Qo(e,t){return e-t}function ea(e,t){return e.z-t.z}function ta(e,t){return t.z-e.z}class sa{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t,s){const i=this.pool,r=this.list;this.index>=i.length&&i.push({start:-1,count:-1,z:-1,index:-1});const n=i[this.index];r.push(n),this.index++,n.start=e.start,n.count=e.count,n.z=t,n.index=s}reset(){this.list.length=0,this.index=0}}const ia=new sr,ra=new sr,na=new sr,oa=new Xr(1,1,1),aa=new sr,ha=new Ko,ua=new Ri,la=new $i,ca=new Ai,da=new Ai,pa=new Ai,ma=new sa,ga=new On,fa=[];function ya(e,t,s=0){const i=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){const r=e.count;for(let n=0;n65535?new Uint32Array(i):new Uint16Array(i);t.setIndex(new an(e,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(Boolean(e.getIndex())!==Boolean(t.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const s in t.attributes){if(!e.hasAttribute(s))throw new Error(`BatchedMesh: Added geometry missing "${s}". All geometries must have consistent attributes.`);const i=e.getAttribute(s),r=t.getAttribute(s);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ri);const e=this.boundingBox,t=this._drawInfo;e.makeEmpty();for(let s=0,i=t.length;s=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("BatchedMesh: Maximum item count reached.");const t={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(Qo),s=this._availableInstanceIds.shift(),this._drawInfo[s]=t):(s=this._drawInfo.length,this._drawInfo.push(t));const i=this._matricesTexture,r=i.image.data;na.toArray(r,16*s),i.needsUpdate=!0;const n=this._colorsTexture;return n&&(oa.toArray(n.image.data,4*s),n.needsUpdate=!0),s}addGeometry(e,t=-1,s=-1){this._initializeGeometry(e),this._validateGeometry(e);const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let r=null;const n=this._reservedRanges,o=this._drawRanges,a=this._bounds;0!==this._geometryCount&&(r=n[n.length-1]),i.vertexCount=-1===t?e.getAttribute("position").count:t,i.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const h=e.getIndex(),u=null!==h;if(u&&(i.indexCount=-1===s?h.count:s,i.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==i.indexStart&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const l={start:u?i.indexStart:i.vertexStart,count:-1,active:!0},c={boxInitialized:!1,box:new Ri,sphereInitialized:!1,sphere:new $i};let d;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Qo),d=this._availableGeometryIds.shift(),n[d]=i,o[d]=l,a[d]=c):(d=this._geometryCount,this._geometryCount++,n.push(i),o.push(l),a.push(c)),this.setGeometryAt(d,e),d}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const s=this.geometry,i=null!==s.getIndex(),r=s.getIndex(),n=t.getIndex(),o=this._reservedRanges[e];if(i&&n.count>o.indexCount||t.attributes.position.count>o.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const a=o.vertexStart,h=o.vertexCount;for(const e in s.attributes){const i=t.getAttribute(e),r=s.getAttribute(e);ya(i,r,a);const n=i.itemSize;for(let e=i.count,t=h;e=t.length||!1===t[e].active)return this;const s=this._drawInfo;for(let t=0,i=s.length;t=t.length||!1===t[e].active||(t[e].active=!1,this._availableInstanceIds.push(e),this._visibilityChanged=!0),this}optimize(){let e=0,t=0;const s=this._drawRanges,i=this._reservedRanges,r=this.geometry;for(let n=0,o=s.length;n=this._geometryCount)return null;const s=this._bounds[e],i=s.box,r=this.geometry;if(!1===s.boxInitialized){i.makeEmpty();const t=r.index,n=r.attributes.position,o=this._drawRanges[e];for(let e=o.start,s=o.start+o.count;e=this._geometryCount)return null;const s=this._bounds[e],i=s.sphere,r=this.geometry;if(!1===s.sphereInitialized){i.makeEmpty(),this.getBoundingBoxAt(e,ua),ua.getCenter(i.center);const t=r.index,n=r.attributes.position,o=this._drawRanges[e];let a=0;for(let e=o.start,s=o.start+o.count;e=s.length||!1===s[e].active||(t.toArray(r,16*e),i.needsUpdate=!0),this}getMatrixAt(e,t){const s=this._drawInfo,i=this._matricesTexture.image.data;return e>=s.length||!1===s[e].active?null:t.fromArray(i,16*e)}setColorAt(e,t){null===this._colorsTexture&&this._initColorsTexture();const s=this._colorsTexture,i=this._colorsTexture.image.data,r=this._drawInfo;return e>=r.length||!1===r[e].active||(t.toArray(i,4*e),s.needsUpdate=!0),this}getColorAt(e,t){const s=this._colorsTexture.image.data,i=this._drawInfo;return e>=i.length||!1===i[e].active?null:t.fromArray(s,4*e)}setVisibleAt(e,t){const s=this._drawInfo;return e>=s.length||!1===s[e].active||s[e].visible===t||(s[e].visible=t,this._visibilityChanged=!0),this}getVisibleAt(e){const t=this._drawInfo;return!(e>=t.length||!1===t[e].active)&&t[e].visible}setGeometryIdAt(e,t){const s=this._drawInfo;return e>=s.length||!1===s[e].active||t<0||t>=this._geometryCount?null:(s[e].geometryIndex=t,this)}getGeometryIdAt(e){const t=this._drawInfo;return e>=t.length||!1===t[e].active?-1:t[e].geometryIndex}getGeometryRangeAt(e,t={}){if(e<0||e>=this._geometryCount)return null;const s=this._drawRanges[e];return t.start=s.start,t.count=s.count,t}setInstanceCount(e){const t=this._availableInstanceIds,s=this._drawInfo;for(t.sort(Qo);t[t.length-1]===s.length;)s.pop(),t.pop();if(ethis._drawRanges[t].active)),i=Math.max(...s.map((e=>e.vertexStart+e.vertexCount)));if(i>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index){const e=Math.max(...s.map((e=>e.indexStart+e.indexCount)));if(e>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`)}const r=this.geometry;r.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized=!1,this.geometry=new Sn,this._initializeGeometry(r);const n=this.geometry;r.index&&xa(r.index.array,n.index.array);for(const e in r.attributes)xa(r.attributes[e].array,n.attributes[e].array)}raycast(e,t){const s=this._drawInfo,i=this._drawRanges,r=this.matrixWorld,n=this.geometry;ga.material=this.material,ga.geometry.index=n.index,ga.geometry.attributes=n.attributes,null===ga.geometry.boundingBox&&(ga.geometry.boundingBox=new Ri),null===ga.geometry.boundingSphere&&(ga.geometry.boundingSphere=new $i);for(let n=0,o=s.length;n({...e}))),this._reservedRanges=e._reservedRanges.map((e=>({...e}))),this._drawInfo=e._drawInfo.map((e=>({...e}))),this._bounds=e._bounds.map((e=>({boxInitialized:e.boxInitialized,box:e.box.clone(),sphereInitialized:e.sphereInitialized,sphere:e.sphere.clone()}))),this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(e,t,s,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const n=i.getIndex(),o=null===n?1:n.array.BYTES_PER_ELEMENT,a=this._drawInfo,h=this._multiDrawStarts,u=this._multiDrawCounts,l=this._drawRanges,c=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data;c&&(aa.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse).multiply(this.matrixWorld),ha.setFromProjectionMatrix(aa,e.coordinateSystem));let m=0;if(this.sortObjects){ra.copy(this.matrixWorld).invert(),ca.setFromMatrixPosition(s.matrixWorld).applyMatrix4(ra),da.set(0,0,-1).transformDirection(s.matrixWorld).transformDirection(ra);for(let e=0,t=a.length;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;ei)return;Aa.applyMatrix4(e.matrixWorld);const a=t.ray.origin.distanceTo(Aa);return at.far?void 0:{distance:a,point:Na.clone().applyMatrix4(e.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:e}}const Ea=new Ai,Ba=new Ai;class Ia extends Ca{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,s=[];for(let e=0,i=t.count;e0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;er.far)return;n.push({distance:h,distanceToRay:Math.sqrt(a),point:s,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}class ka extends Rr{constructor(){super(),this.isGroup=!0,this.type="Group"}}class Ga extends yi{constructor(e,t,s,i,r,n,o,a,h){super(e,t,s,i,r,n,o,a,h),this.isVideoTexture=!0,this.minFilter=void 0!==n?n:Te,this.magFilter=void 0!==r?r:Te,this.generateMipmaps=!1;const u=this;"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback((function t(){u.needsUpdate=!0,e.requestVideoFrameCallback(t)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;!1==="requestVideoFrameCallback"in e&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class Wa extends yi{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=fe,this.minFilter=fe,this.generateMipmaps=!1,this.needsUpdate=!0}}class ja extends yi{constructor(e,t,s,i,r,n,o,a,h,u,l,c){super(null,n,o,a,h,u,i,r,l,c),this.isCompressedTexture=!0,this.image={width:t,height:s},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class Ha extends ja{constructor(e,t,s,i,r,n){super(e,t,s,r,n),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=me,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class qa extends ja{constructor(e,t,s){super(void 0,e[0].width,e[0].height,t,s,he),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class $a extends yi{constructor(e,t,s,i,r,n,o,a,h){super(e,t,s,i,r,n,o,a,h),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Xa extends yi{constructor(e,t,s,i,r,n,o,a,h,u=1026){if(u!==We&&u!==je)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===s&&u===We&&(s=Be),void 0===s&&u===je&&(s=Oe),super(null,i,r,n,o,a,u,s,h),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==o?o:fe,this.minFilter=void 0!==a?a:fe,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class Ya{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){const s=this.getUtoTmapping(e);return this.getPoint(s,t)}getPoints(e=5){const t=[];for(let s=0;s<=e;s++)t.push(this.getPoint(s/e));return t}getSpacedPoints(e=5){const t=[];for(let s=0;s<=e;s++)t.push(this.getPointAt(s/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let s,i=this.getPoint(0),r=0;t.push(0);for(let n=1;n<=e;n++)s=this.getPoint(n/e),r+=s.distanceTo(i),t.push(r),i=s;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){const s=this.getLengths();let i=0;const r=s.length;let n;n=t||e*s[r-1];let o,a=0,h=r-1;for(;a<=h;)if(i=Math.floor(a+(h-a)/2),o=s[i]-n,o<0)a=i+1;else{if(!(o>0)){h=i;break}h=i-1}if(i=h,s[i]===n)return i/(r-1);const u=s[i];return(i+(n-u)/(s[i+1]-u))/(r-1)}getTangent(e,t){const s=1e-4;let i=e-s,r=e+s;i<0&&(i=0),r>1&&(r=1);const n=this.getPoint(i),o=this.getPoint(r),a=t||(n.isVector2?new Ys:new Ai);return a.copy(o).sub(n).normalize(),a}getTangentAt(e,t){const s=this.getUtoTmapping(e);return this.getTangent(s,t)}computeFrenetFrames(e,t){const s=new Ai,i=[],r=[],n=[],o=new Ai,a=new sr;for(let t=0;t<=e;t++){const s=t/e;i[t]=this.getTangentAt(s,new Ai)}r[0]=new Ai,n[0]=new Ai;let h=Number.MAX_VALUE;const u=Math.abs(i[0].x),l=Math.abs(i[0].y),c=Math.abs(i[0].z);u<=h&&(h=u,s.set(1,0,0)),l<=h&&(h=l,s.set(0,1,0)),c<=h&&s.set(0,0,1),o.crossVectors(i[0],s).normalize(),r[0].crossVectors(i[0],o),n[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),n[t]=n[t-1].clone(),o.crossVectors(i[t-1],i[t]),o.length()>Number.EPSILON){o.normalize();const e=Math.acos(Ws(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(a.makeRotationAxis(o,e))}n[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(Ws(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(o.crossVectors(r[0],r[e]))>0&&(t=-t);for(let s=1;s<=e;s++)r[s].applyMatrix4(a.makeRotationAxis(i[s],t*s)),n[s].crossVectors(i[s],r[s])}return{tangents:i,normals:r,binormals:n}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Za extends Ya{constructor(e=0,t=0,s=1,i=1,r=0,n=2*Math.PI,o=!1,a=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=s,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=n,this.aClockwise=o,this.aRotation=a}getPoint(e,t=new Ys){const s=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const n=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(h)/r)+1)*r:0===u&&h===r-1&&(h=r-2,u=1),this.closed||h>0?o=i[(h-1)%r]:(Qa.subVectors(i[0],i[1]).add(i[0]),o=Qa);const l=i[h%r],c=i[(h+1)%r];if(this.closed||h+2i.length-2?i.length-1:n+1],l=i[n>i.length-3?i.length-1:n+2];return s.set(rh(o,a.x,h.x,u.x,l.x),rh(o,a.y,h.y,u.y,l.y)),s}copy(e){super.copy(e),this.points=[];for(let t=0,s=e.points.length;t=s){const e=i[r]-s,n=this.curves[r],o=n.getLength(),a=0===o?0:1-e/o;return n.getPointAt(a,t)}r++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let s=0,i=this.curves.length;s1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,s=e.curves.length;t0){const e=h.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y)}this.curves.push(h);const u=h.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class yh extends Sn{constructor(e=[new Ys(0,-.5),new Ys(.5,0),new Ys(0,.5)],t=12,s=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:s,phiLength:i},t=Math.floor(t),i=Ws(i,0,2*Math.PI);const r=[],n=[],o=[],a=[],h=[],u=1/t,l=new Ai,c=new Ys,d=new Ai,p=new Ai,m=new Ai;let g=0,f=0;for(let t=0;t<=e.length-1;t++)switch(t){case 0:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,d.x=1*f,d.y=-g,d.z=0*f,m.copy(d),d.normalize(),a.push(d.x,d.y,d.z);break;case e.length-1:a.push(m.x,m.y,m.z);break;default:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,d.x=1*f,d.y=-g,d.z=0*f,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),a.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=t;r++){const d=s+r*u*i,p=Math.sin(d),m=Math.cos(d);for(let s=0;s<=e.length-1;s++){l.x=e[s].x*p,l.y=e[s].y,l.z=e[s].x*m,n.push(l.x,l.y,l.z),c.x=r/t,c.y=s/(e.length-1),o.push(c.x,c.y);const i=a[3*s+0]*p,u=a[3*s+1],d=a[3*s+0]*m;h.push(i,u,d)}}for(let s=0;s0&&(u.push(r,n,a),x+=3),t>0&&(u.push(n,o,a),x+=3)}h.addGroup(f,x,0),f+=x}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new fn(l,3)),this.setAttribute("normal",new fn(c,3)),this.setAttribute("uv",new fn(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vh(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Th extends vh{constructor(e=1,t=1,s=32,i=1,r=!1,n=0,o=2*Math.PI){super(0,e,t,s,i,r,n,o),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:s,heightSegments:i,openEnded:r,thetaStart:n,thetaLength:o}}static fromJSON(e){return new Th(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class _h extends Sn{constructor(e=[],t=[],s=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:s,detail:i};const r=[],n=[];function o(e,t,s,i){const r=i+1,n=[];for(let i=0;i<=r;i++){n[i]=[];const o=e.clone().lerp(s,i/r),a=t.clone().lerp(s,i/r),h=r-i;for(let e=0;e<=h;e++)n[i][e]=0===e&&i===r?o:o.clone().lerp(a,e/h)}for(let e=0;e.9&&o<.1&&(t<.2&&(n[e+0]+=1),s<.2&&(n[e+2]+=1),i<.2&&(n[e+4]+=1))}}()}(),this.setAttribute("position",new fn(r,3)),this.setAttribute("normal",new fn(r.slice(),3)),this.setAttribute("uv",new fn(n,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new _h(e.vertices,e.indices,e.radius,e.details)}}class wh extends _h{constructor(e=1,t=0){const s=(1+Math.sqrt(5))/2,i=1/s;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-s,0,-i,s,0,i,-s,0,i,s,-i,-s,0,-i,s,0,i,-s,0,i,s,0,-s,0,-i,s,0,-i,-s,0,i,s,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new wh(e.radius,e.detail)}}const Sh=new Ai,Mh=new Ai,Ah=new Ai,Nh=new Wr;class Ch extends Sn{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},null!==e){const s=4,i=Math.pow(10,s),r=Math.cos(Ds*t),n=e.getIndex(),o=e.getAttribute("position"),a=n?n.count:o.count,h=[0,0,0],u=["a","b","c"],l=new Array(3),c={},d=[];for(let e=0;e80*s){a=u=e[0],h=l=e[1];for(let t=s;tu&&(u=c),d>l&&(l=d);p=Math.max(u-a,l-h),p=0!==p?32767/p:0}return Ph(n,o,s,a,h,p,0),o};function Bh(e,t,s,i,r){let n,o;if(r===function(e,t,s,i){let r=0;for(let n=t,o=s-i;n0)for(n=t;n=t;n-=i)o=Kh(n,e[n],e[n+1],o);return o&&qh(o,o.next)&&(Qh(o),o=o.next),o}function Ih(e,t){if(!e)return e;t||(t=e);let s,i=e;do{if(s=!1,i.steiner||!qh(i,i.next)&&0!==Hh(i.prev,i,i.next))i=i.next;else{if(Qh(i),i=t=i.prev,i===i.next)break;s=!0}}while(s||i!==t);return t}function Ph(e,t,s,i,r,n,o){if(!e)return;!o&&n&&function(e,t,s,i){let r=e;do{0===r.z&&(r.z=kh(r.x,r.y,t,s,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,s,i,r,n,o,a,h,u=1;do{for(s=e,e=null,n=null,o=0;s;){for(o++,i=s,a=0,t=0;t0||h>0&&i;)0!==a&&(0===h||!i||s.z<=i.z)?(r=s,s=s.nextZ,a--):(r=i,i=i.nextZ,h--),n?n.nextZ=r:e=r,r.prevZ=n,n=r;s=i}n.nextZ=null,u*=2}while(o>1)}(r)}(e,i,r,n);let a,h,u=e;for(;e.prev!==e.next;)if(a=e.prev,h=e.next,n?Uh(e,i,r,n):Fh(e))t.push(a.i/s|0),t.push(e.i/s|0),t.push(h.i/s|0),Qh(e),e=h.next,u=h.next;else if((e=h)===u){o?1===o?Ph(e=Oh(Ih(e),t,s),t,s,i,r,n,2):2===o&&zh(e,t,s,i,r,n):Ph(Ih(e),t,s,i,r,n,1);break}}function Fh(e){const t=e.prev,s=e,i=e.next;if(Hh(t,s,i)>=0)return!1;const r=t.x,n=s.x,o=i.x,a=t.y,h=s.y,u=i.y,l=rn?r>o?r:o:n>o?n:o,p=a>h?a>u?a:u:h>u?h:u;let m=i.next;for(;m!==t;){if(m.x>=l&&m.x<=d&&m.y>=c&&m.y<=p&&Wh(r,a,n,h,o,u,m.x,m.y)&&Hh(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Uh(e,t,s,i){const r=e.prev,n=e,o=e.next;if(Hh(r,n,o)>=0)return!1;const a=r.x,h=n.x,u=o.x,l=r.y,c=n.y,d=o.y,p=ah?a>u?a:u:h>u?h:u,f=l>c?l>d?l:d:c>d?c:d,y=kh(p,m,t,s,i),x=kh(g,f,t,s,i);let b=e.prevZ,v=e.nextZ;for(;b&&b.z>=y&&v&&v.z<=x;){if(b.x>=p&&b.x<=g&&b.y>=m&&b.y<=f&&b!==r&&b!==o&&Wh(a,l,h,c,u,d,b.x,b.y)&&Hh(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==o&&Wh(a,l,h,c,u,d,v.x,v.y)&&Hh(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;b&&b.z>=y;){if(b.x>=p&&b.x<=g&&b.y>=m&&b.y<=f&&b!==r&&b!==o&&Wh(a,l,h,c,u,d,b.x,b.y)&&Hh(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=x;){if(v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==o&&Wh(a,l,h,c,u,d,v.x,v.y)&&Hh(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function Oh(e,t,s){let i=e;do{const r=i.prev,n=i.next.next;!qh(r,n)&&$h(r,i,i.next,n)&&Zh(r,n)&&Zh(n,r)&&(t.push(r.i/s|0),t.push(i.i/s|0),t.push(n.i/s|0),Qh(i),Qh(i.next),i=e=n),i=i.next}while(i!==e);return Ih(i)}function zh(e,t,s,i,r,n){let o=e;do{let e=o.next.next;for(;e!==o.prev;){if(o.i!==e.i&&jh(o,e)){let a=Jh(o,e);return o=Ih(o,o.next),a=Ih(a,a.next),Ph(o,t,s,i,r,n,0),void Ph(a,t,s,i,r,n,0)}e=e.next}o=o.next}while(o!==e)}function Lh(e,t){return e.x-t.x}function Vh(e,t){const s=function(e,t){let s,i=t,r=-1/0;const n=e.x,o=e.y;do{if(o<=i.y&&o>=i.next.y&&i.next.y!==i.y){const e=i.x+(o-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=n&&e>r&&(r=e,s=i.x=i.x&&i.x>=h&&n!==i.x&&Wh(os.x||i.x===s.x&&Dh(s,i)))&&(s=i,c=l)),i=i.next}while(i!==a);return s}(e,t);if(!s)return t;const i=Jh(s,e);return Ih(i,i.next),Ih(s,s.next)}function Dh(e,t){return Hh(e.prev,e,t.prev)<0&&Hh(t.next,e,e.next)<0}function kh(e,t,s,i,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Gh(e){let t=e,s=e;do{(t.x=(e-o)*(n-a)&&(e-o)*(i-a)>=(s-o)*(t-a)&&(s-o)*(n-a)>=(r-o)*(i-a)}function jh(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let s=e;do{if(s.i!==e.i&&s.next.i!==e.i&&s.i!==t.i&&s.next.i!==t.i&&$h(s,s.next,e,t))return!0;s=s.next}while(s!==e);return!1}(e,t)&&(Zh(e,t)&&Zh(t,e)&&function(e,t){let s=e,i=!1;const r=(e.x+t.x)/2,n=(e.y+t.y)/2;do{s.y>n!=s.next.y>n&&s.next.y!==s.y&&r<(s.next.x-s.x)*(n-s.y)/(s.next.y-s.y)+s.x&&(i=!i),s=s.next}while(s!==e);return i}(e,t)&&(Hh(e.prev,e,t.prev)||Hh(e,t.prev,t))||qh(e,t)&&Hh(e.prev,e,e.next)>0&&Hh(t.prev,t,t.next)>0)}function Hh(e,t,s){return(t.y-e.y)*(s.x-t.x)-(t.x-e.x)*(s.y-t.y)}function qh(e,t){return e.x===t.x&&e.y===t.y}function $h(e,t,s,i){const r=Yh(Hh(e,t,s)),n=Yh(Hh(e,t,i)),o=Yh(Hh(s,i,e)),a=Yh(Hh(s,i,t));return r!==n&&o!==a||(!(0!==r||!Xh(e,s,t))||(!(0!==n||!Xh(e,i,t))||(!(0!==o||!Xh(s,e,i))||!(0!==a||!Xh(s,t,i)))))}function Xh(e,t,s){return t.x<=Math.max(e.x,s.x)&&t.x>=Math.min(e.x,s.x)&&t.y<=Math.max(e.y,s.y)&&t.y>=Math.min(e.y,s.y)}function Yh(e){return e>0?1:e<0?-1:0}function Zh(e,t){return Hh(e.prev,e,e.next)<0?Hh(e,t,e.next)>=0&&Hh(e,e.prev,t)>=0:Hh(e,t,e.prev)<0||Hh(e,e.next,t)<0}function Jh(e,t){const s=new eu(e.i,e.x,e.y),i=new eu(t.i,t.x,t.y),r=e.next,n=t.prev;return e.next=t,t.prev=e,s.next=r,r.prev=s,i.next=s,s.prev=i,n.next=i,i.prev=n,i}function Kh(e,t,s,i){const r=new eu(e,t,s);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Qh(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function eu(e,t,s){this.i=e,this.x=t,this.y=s,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class tu{static area(e){const t=e.length;let s=0;for(let i=t-1,r=0;r2&&e[t-1].equals(e[0])&&e.pop()}function iu(e,t){for(let s=0;sNumber.EPSILON){const c=Math.sqrt(l),d=Math.sqrt(h*h+u*u),p=t.x-a/c,m=t.y+o/c,g=((s.x-u/d-p)*u-(s.y+h/d-m)*h)/(o*u-a*h);i=p+o*g-e.x,r=m+a*g-e.y;const f=i*i+r*r;if(f<=2)return new Ys(i,r);n=Math.sqrt(f/2)}else{let e=!1;o>Number.EPSILON?h>Number.EPSILON&&(e=!0):o<-Number.EPSILON?h<-Number.EPSILON&&(e=!0):Math.sign(a)===Math.sign(u)&&(e=!0),e?(i=-a,r=o,n=Math.sqrt(l)):(i=o,r=a,n=Math.sqrt(l/2))}return new Ys(i/n,r/n)}const B=[];for(let e=0,t=A.length,s=t-1,i=e+1;e=0;e--){const t=e/p,s=l*Math.cos(t*Math.PI/2),i=c*Math.sin(t*Math.PI/2)+d;for(let e=0,t=A.length;e=0;){const i=s;let r=s-1;r<0&&(r=e.length-1);for(let e=0,s=a+2*p;e0)&&d.push(t,r,h),(e!==s-1||a0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class wu extends Jr{static get type(){return"MeshPhongMaterial"}constructor(e){super(),this.isMeshPhongMaterial=!0,this.color=new Xr(16777215),this.specular=new Xr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Su extends Jr{static get type(){return"MeshToonMaterial"}constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.color=new Xr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class Mu extends Jr{static get type(){return"MeshNormalMaterial"}constructor(e){super(),this.isMeshNormalMaterial=!0,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Au extends Jr{static get type(){return"MeshLambertMaterial"}constructor(e){super(),this.isMeshLambertMaterial=!0,this.color=new Xr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Nu extends Jr{static get type(){return"MeshDepthMaterial"}constructor(e){super(),this.isMeshDepthMaterial=!0,this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Cu extends Jr{static get type(){return"MeshDistanceMaterial"}constructor(e){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class Ru extends Jr{static get type(){return"MeshMatcapMaterial"}constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.color=new Xr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ys(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Eu extends va{static get type(){return"LineDashedMaterial"}constructor(e){super(),this.isLineDashedMaterial=!0,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function Bu(e,t,s){return!e||!s&&e.constructor===t?e:"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e)}function Iu(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Pu(e){const t=e.length,s=new Array(t);for(let e=0;e!==t;++e)s[e]=e;return s.sort((function(t,s){return e[t]-e[s]})),s}function Fu(e,t,s){const i=e.length,r=new e.constructor(i);for(let n=0,o=0;o!==i;++n){const i=s[n]*t;for(let s=0;s!==t;++s)r[o++]=e[i+s]}return r}function Uu(e,t,s,i){let r=1,n=e[0];for(;void 0!==n&&void 0===n[i];)n=e[r++];if(void 0===n)return;let o=n[i];if(void 0!==o)if(Array.isArray(o))do{o=n[i],void 0!==o&&(t.push(n.time),s.push.apply(s,o)),n=e[r++]}while(void 0!==n);else if(void 0!==o.toArray)do{o=n[i],void 0!==o&&(t.push(n.time),o.toArray(s,s.length)),n=e[r++]}while(void 0!==n);else do{o=n[i],void 0!==o&&(t.push(n.time),s.push(o)),n=e[r++]}while(void 0!==n)}const Ou={convertArray:Bu,isTypedArray:Iu,getKeyframeOrder:Pu,sortedArray:Fu,flattenJSON:Uu,subclip:function(e,t,s,i,r=30){const n=e.clone();n.name=t;const o=[];for(let e=0;e=i)){h.push(t.times[e]);for(let s=0;sn.tracks[e].times[0]&&(a=n.tracks[e].times[0]);for(let e=0;e=i.times[c]){const e=c*h+a,t=e+h-a;d=i.values.slice(e,t)}else{const e=i.createInterpolant(),t=a,s=h-a;e.evaluate(n),d=e.resultBuffer.slice(t,s)}if("quaternion"===r){(new Mi).fromArray(d).normalize().conjugate().toArray(d)}const p=o.times.length;for(let e=0;e=r)break e;{const o=t[1];e=r)break t}n=s,s=0}}for(;s>>1;et;)--n;if(++n,0!==r||n!==i){r>=n&&(n=Math.max(n,1),r=n-1);const e=this.getValueSize();this.times=s.slice(r,n),this.values=this.values.slice(r*e,n*e)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const s=this.times,i=this.values,r=s.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let n=null;for(let t=0;t!==r;t++){const i=s[t];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,t,i),e=!1;break}if(null!==n&&n>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,t,i,n),e=!1;break}n=i}if(void 0!==i&&Iu(i))for(let t=0,s=i.length;t!==s;++t){const s=i[t];if(isNaN(s)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,t,s),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),s=this.getValueSize(),i=this.getInterpolation()===Ft,r=e.length-1;let n=1;for(let o=1;o0){e[n]=e[r];for(let e=r*s,i=n*s,o=0;o!==s;++o)t[i+o]=t[e+o];++n}return n!==e.length?(this.times=e.slice(0,n),this.values=t.slice(0,n*s)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),s=new(0,this.constructor)(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}ku.prototype.TimeBufferType=Float32Array,ku.prototype.ValueBufferType=Float32Array,ku.prototype.DefaultInterpolation=Pt;class Gu extends ku{constructor(e,t,s){super(e,t,s)}}Gu.prototype.ValueTypeName="bool",Gu.prototype.ValueBufferType=Array,Gu.prototype.DefaultInterpolation=It,Gu.prototype.InterpolantFactoryMethodLinear=void 0,Gu.prototype.InterpolantFactoryMethodSmooth=void 0;class Wu extends ku{}Wu.prototype.ValueTypeName="color";class ju extends ku{}ju.prototype.ValueTypeName="number";class Hu extends zu{constructor(e,t,s,i){super(e,t,s,i)}interpolate_(e,t,s,i){const r=this.resultBuffer,n=this.sampleValues,o=this.valueSize,a=(s-t)/(i-t);let h=e*o;for(let e=h+o;h!==e;h+=4)Mi.slerpFlat(r,0,n,h-o,n,h,a);return r}}class qu extends ku{InterpolantFactoryMethodLinear(e){return new Hu(this.times,this.values,this.getValueSize(),e)}}qu.prototype.ValueTypeName="quaternion",qu.prototype.InterpolantFactoryMethodSmooth=void 0;class $u extends ku{constructor(e,t,s){super(e,t,s)}}$u.prototype.ValueTypeName="string",$u.prototype.ValueBufferType=Array,$u.prototype.DefaultInterpolation=It,$u.prototype.InterpolantFactoryMethodLinear=void 0,$u.prototype.InterpolantFactoryMethodSmooth=void 0;class Xu extends ku{}Xu.prototype.ValueTypeName="vector";class Yu{constructor(e="",t=-1,s=[],i=2500){this.name=e,this.tracks=s,this.duration=t,this.blendMode=i,this.uuid=Gs(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],s=e.tracks,i=1/(e.fps||1);for(let e=0,r=s.length;e!==r;++e)t.push(Zu(s[e]).scale(i));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){const t=[],s=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let e=0,i=s.length;e!==i;++e)t.push(ku.toJSON(s[e]));return i}static CreateFromMorphTargetSequence(e,t,s,i){const r=t.length,n=[];for(let e=0;e1){const e=n[1];let t=i[e];t||(i[e]=t=[]),t.push(s)}}const n=[];for(const e in i)n.push(this.CreateFromMorphTargetSequence(e,i[e],t,s));return n}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const s=function(e,t,s,i,r){if(0!==s.length){const n=[],o=[];Uu(s,n,o,i),0!==n.length&&r.push(new e(t,n,o))}},i=[],r=e.name||"default",n=e.fps||30,o=e.blendMode;let a=e.length||-1;const h=e.hierarchy||[];for(let e=0;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==tl[e])return void tl[e].push({onLoad:t,onProgress:s,onError:i});tl[e]=[],tl[e].push({onLoad:t,onProgress:s,onError:i});const n=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),o=this.mimeType,a=this.responseType;fetch(n).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body||void 0===t.body.getReader)return t;const s=tl[e],i=t.body.getReader(),r=t.headers.get("X-File-Size")||t.headers.get("Content-Length"),n=r?parseInt(r):0,o=0!==n;let a=0;const h=new ReadableStream({start(e){!function t(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:o,loaded:a,total:n});for(let e=0,t=s.length;e{e.error(t)}))}()}});return new Response(h)}throw new sl(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)})).then((e=>{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,o)));case"json":return e.json();default:if(void 0===o)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(o),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Ju.add(e,t);const s=tl[e];delete tl[e];for(let e=0,i=s.length;e{const s=tl[e];if(void 0===s)throw this.manager.itemError(e),t;delete tl[e];for(let e=0,i=s.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class rl extends el{constructor(e){super(e)}load(e,t,s,i){const r=this,n=new il(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(e,(function(s){try{t(r.parse(JSON.parse(s)))}catch(t){i?i(t):console.error(t),r.manager.itemError(e)}}),s,i)}parse(e){const t=[];for(let s=0;s0:i.vertexColors=e.vertexColors),void 0!==e.uniforms)for(const t in e.uniforms){const r=e.uniforms[t];switch(i.uniforms[t]={},r.type){case"t":i.uniforms[t].value=s(r.value);break;case"c":i.uniforms[t].value=(new Xr).setHex(r.value);break;case"v2":i.uniforms[t].value=(new Ys).fromArray(r.value);break;case"v3":i.uniforms[t].value=(new Ai).fromArray(r.value);break;case"v4":i.uniforms[t].value=(new xi).fromArray(r.value);break;case"m3":i.uniforms[t].value=(new Zs).fromArray(r.value);break;case"m4":i.uniforms[t].value=(new sr).fromArray(r.value);break;default:i.uniforms[t].value=r.value}}if(void 0!==e.defines&&(i.defines=e.defines),void 0!==e.vertexShader&&(i.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(i.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(i.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)i.extensions[t]=e.extensions[t];if(void 0!==e.lights&&(i.lights=e.lights),void 0!==e.clipping&&(i.clipping=e.clipping),void 0!==e.size&&(i.size=e.size),void 0!==e.sizeAttenuation&&(i.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(i.map=s(e.map)),void 0!==e.matcap&&(i.matcap=s(e.matcap)),void 0!==e.alphaMap&&(i.alphaMap=s(e.alphaMap)),void 0!==e.bumpMap&&(i.bumpMap=s(e.bumpMap)),void 0!==e.bumpScale&&(i.bumpScale=e.bumpScale),void 0!==e.normalMap&&(i.normalMap=s(e.normalMap)),void 0!==e.normalMapType&&(i.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),i.normalScale=(new Ys).fromArray(t)}return void 0!==e.displacementMap&&(i.displacementMap=s(e.displacementMap)),void 0!==e.displacementScale&&(i.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(i.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(i.roughnessMap=s(e.roughnessMap)),void 0!==e.metalnessMap&&(i.metalnessMap=s(e.metalnessMap)),void 0!==e.emissiveMap&&(i.emissiveMap=s(e.emissiveMap)),void 0!==e.emissiveIntensity&&(i.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(i.specularMap=s(e.specularMap)),void 0!==e.specularIntensityMap&&(i.specularIntensityMap=s(e.specularIntensityMap)),void 0!==e.specularColorMap&&(i.specularColorMap=s(e.specularColorMap)),void 0!==e.envMap&&(i.envMap=s(e.envMap)),void 0!==e.envMapRotation&&i.envMapRotation.fromArray(e.envMapRotation),void 0!==e.envMapIntensity&&(i.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(i.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(i.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(i.lightMap=s(e.lightMap)),void 0!==e.lightMapIntensity&&(i.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(i.aoMap=s(e.aoMap)),void 0!==e.aoMapIntensity&&(i.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(i.gradientMap=s(e.gradientMap)),void 0!==e.clearcoatMap&&(i.clearcoatMap=s(e.clearcoatMap)),void 0!==e.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=s(e.clearcoatRoughnessMap)),void 0!==e.clearcoatNormalMap&&(i.clearcoatNormalMap=s(e.clearcoatNormalMap)),void 0!==e.clearcoatNormalScale&&(i.clearcoatNormalScale=(new Ys).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(i.iridescenceMap=s(e.iridescenceMap)),void 0!==e.iridescenceThicknessMap&&(i.iridescenceThicknessMap=s(e.iridescenceThicknessMap)),void 0!==e.transmissionMap&&(i.transmissionMap=s(e.transmissionMap)),void 0!==e.thicknessMap&&(i.thicknessMap=s(e.thicknessMap)),void 0!==e.anisotropyMap&&(i.anisotropyMap=s(e.anisotropyMap)),void 0!==e.sheenColorMap&&(i.sheenColorMap=s(e.sheenColorMap)),void 0!==e.sheenRoughnessMap&&(i.sheenRoughnessMap=s(e.sheenRoughnessMap)),i}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return El.createMaterialFromType(e)}static createMaterialFromType(e){return new{ShadowMaterial:bu,SpriteMaterial:so,RawShaderMaterial:vu,ShaderMaterial:Dn,PointsMaterial:Fa,MeshPhysicalMaterial:_u,MeshStandardMaterial:Tu,MeshPhongMaterial:wu,MeshToonMaterial:Su,MeshNormalMaterial:Mu,MeshLambertMaterial:Au,MeshDepthMaterial:Nu,MeshDistanceMaterial:Cu,MeshBasicMaterial:Kr,MeshMatcapMaterial:Ru,LineDashedMaterial:Eu,LineBasicMaterial:va,Material:Jr}[e]}}class Bl{static decodeText(e){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0,i=e.length;s0){const s=new Ku(t);r=new ol(s),r.setCrossOrigin(this.crossOrigin);for(let t=0,s=e.length;t0){i=new ol(this.manager),i.setCrossOrigin(this.crossOrigin);for(let t=0,i=e.length;t{const t=new Ri;t.min.fromArray(e.boxMin),t.max.fromArray(e.boxMax);const s=new $i;return s.radius=e.sphereRadius,s.center.fromArray(e.sphereCenter),{boxInitialized:e.boxInitialized,box:t,sphereInitialized:e.sphereInitialized,sphere:s}})),n._maxInstanceCount=e.maxInstanceCount,n._maxVertexCount=e.maxVertexCount,n._maxIndexCount=e.maxIndexCount,n._geometryInitialized=e.geometryInitialized,n._geometryCount=e.geometryCount,n._matricesTexture=l(e.matricesTexture.uuid),void 0!==e.colorsTexture&&(n._colorsTexture=l(e.colorsTexture.uuid));break;case"LOD":n=new To;break;case"Line":n=new Ca(h(e.geometry),u(e.material));break;case"LineLoop":n=new Pa(h(e.geometry),u(e.material));break;case"LineSegments":n=new Ia(h(e.geometry),u(e.material));break;case"PointCloud":case"Points":n=new Va(h(e.geometry),u(e.material));break;case"Sprite":n=new yo(u(e.material));break;case"Group":n=new ka;break;case"Bone":n=new Io;break;default:n=new Rr}if(n.uuid=e.uuid,void 0!==e.name&&(n.name=e.name),void 0!==e.matrix?(n.matrix.fromArray(e.matrix),void 0!==e.matrixAutoUpdate&&(n.matrixAutoUpdate=e.matrixAutoUpdate),n.matrixAutoUpdate&&n.matrix.decompose(n.position,n.quaternion,n.scale)):(void 0!==e.position&&n.position.fromArray(e.position),void 0!==e.rotation&&n.rotation.fromArray(e.rotation),void 0!==e.quaternion&&n.quaternion.fromArray(e.quaternion),void 0!==e.scale&&n.scale.fromArray(e.scale)),void 0!==e.up&&n.up.fromArray(e.up),void 0!==e.castShadow&&(n.castShadow=e.castShadow),void 0!==e.receiveShadow&&(n.receiveShadow=e.receiveShadow),e.shadow&&(void 0!==e.shadow.intensity&&(n.shadow.intensity=e.shadow.intensity),void 0!==e.shadow.bias&&(n.shadow.bias=e.shadow.bias),void 0!==e.shadow.normalBias&&(n.shadow.normalBias=e.shadow.normalBias),void 0!==e.shadow.radius&&(n.shadow.radius=e.shadow.radius),void 0!==e.shadow.mapSize&&n.shadow.mapSize.fromArray(e.shadow.mapSize),void 0!==e.shadow.camera&&(n.shadow.camera=this.parseObject(e.shadow.camera))),void 0!==e.visible&&(n.visible=e.visible),void 0!==e.frustumCulled&&(n.frustumCulled=e.frustumCulled),void 0!==e.renderOrder&&(n.renderOrder=e.renderOrder),void 0!==e.userData&&(n.userData=e.userData),void 0!==e.layers&&(n.layers.mask=e.layers),void 0!==e.children){const o=e.children;for(let e=0;e{t&&t(s),r.manager.itemEnd(e)})).catch((e=>{i&&i(e)})):(setTimeout((function(){t&&t(n),r.manager.itemEnd(e)}),0),n);const o={};o.credentials="anonymous"===this.crossOrigin?"same-origin":"include",o.headers=this.requestHeader;const a=fetch(e,o).then((function(e){return e.blob()})).then((function(e){return createImageBitmap(e,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(s){return Ju.add(e,s),t&&t(s),r.manager.itemEnd(e),s})).catch((function(t){i&&i(t),Ju.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)}));Ju.add(e,a),r.manager.itemStart(e)}}let Vl;class Dl{static getContext(){return void 0===Vl&&(Vl=new(window.AudioContext||window.webkitAudioContext)),Vl}static setContext(e){Vl=e}}class kl extends el{constructor(e){super(e)}load(e,t,s,i){const r=this,n=new il(this.manager);function o(t){i?i(t):console.error(t),r.manager.itemError(e)}n.setResponseType("arraybuffer"),n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(e,(function(e){try{const s=e.slice(0);Dl.getContext().decodeAudioData(s,(function(e){t(e)})).catch(o)}catch(e){o(e)}}),s,i)}}const Gl=new sr,Wl=new sr,jl=new sr;class Hl{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Hn,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Hn,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,jl.copy(e.projectionMatrix);const s=t.eyeSep/2,i=s*t.near/t.focus,r=t.near*Math.tan(Ds*t.fov*.5)/t.zoom;let n,o;Wl.elements[12]=-s,Gl.elements[12]=s,n=-r*t.aspect+i,o=r*t.aspect+i,jl.elements[0]=2*t.near/(o-n),jl.elements[8]=(o+n)/(o-n),this.cameraL.projectionMatrix.copy(jl),n=-r*t.aspect-i,o=r*t.aspect-i,jl.elements[0]=2*t.near/(o-n),jl.elements[8]=(o+n)/(o-n),this.cameraR.projectionMatrix.copy(jl)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Wl),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Gl)}}class ql extends Hn{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class $l{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Xl(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=Xl();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Xl(){return performance.now()}const Yl=new Ai,Zl=new Mi,Jl=new Ai,Kl=new Ai;class Ql extends Rr{constructor(){super(),this.type="AudioListener",this.context=Dl.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new $l}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener,s=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Yl,Zl,Jl),Kl.set(0,0,-1).applyQuaternion(Zl),t.positionX){const e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Yl.x,e),t.positionY.linearRampToValueAtTime(Yl.y,e),t.positionZ.linearRampToValueAtTime(Yl.z,e),t.forwardX.linearRampToValueAtTime(Kl.x,e),t.forwardY.linearRampToValueAtTime(Kl.y,e),t.forwardZ.linearRampToValueAtTime(Kl.z,e),t.upX.linearRampToValueAtTime(s.x,e),t.upY.linearRampToValueAtTime(s.y,e),t.upZ.linearRampToValueAtTime(s.z,e)}else t.setPosition(Yl.x,Yl.y,Yl.z),t.setOrientation(Kl.x,Kl.y,Kl.z,s.x,s.y,s.z)}}class ec extends Rr{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(!0===this.isPlaying)return void console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.Audio: this Audio has no playback control.");this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;console.warn("THREE.Audio: this Audio has no playback control.")}stop(e=0){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this;console.warn("THREE.Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(s,i,this._addIndex*t,1,t);for(let e=t,r=t+t;e!==r;++e)if(s[e]!==s[e+t]){o.setValue(s,i);break}}saveOriginalState(){const e=this.binding,t=this.buffer,s=this.valueSize,i=s*this._origIndex;e.getValue(t,i);for(let e=s,r=i;e!==r;++e)t[e]=t[i+e%s];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=3*this.valueSize;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let s=e;s=.5)for(let i=0;i!==r;++i)e[t+i]=e[s+i]}_slerp(e,t,s,i){Mi.slerpFlat(e,t,e,t,e,s,i)}_slerpAdditive(e,t,s,i,r){const n=this._workIndex*r;Mi.multiplyQuaternionsFlat(e,n,e,t,e,s),Mi.slerpFlat(e,t,e,t,e,n,i)}_lerp(e,t,s,i,r){const n=1-i;for(let o=0;o!==r;++o){const r=t+o;e[r]=e[r]*n+e[s+o]*i}}_lerpAdditive(e,t,s,i,r){for(let n=0;n!==r;++n){const r=t+n;e[r]=e[r]+e[s+n]*i}}}const hc="\\[\\]\\.:\\/",uc=new RegExp("["+hc+"]","g"),lc="[^"+hc+"]",cc="[^"+hc.replace("\\.","")+"]",dc=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",lc)+/(WCOD+)?/.source.replace("WCOD",cc)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",lc)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",lc)+"$"),pc=["material","materials","bones","map"];class mc{constructor(e,t,s){this.path=t,this.parsedPath=s||mc.parseTrackName(t),this.node=mc.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,s){return e&&e.isAnimationObjectGroup?new mc.Composite(e,t,s):new mc(e,t,s)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(uc,"")}static parseTrackName(e){const t=dc.exec(e);if(null===t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const s={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=s.nodeName&&s.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const e=s.nodeName.substring(i+1);-1!==pc.indexOf(e)&&(s.nodeName=s.nodeName.substring(0,i),s.objectName=e)}if(null===s.propertyName||0===s.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return s}static findNode(e,t){if(void 0===t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const s=e.skeleton.getBoneByName(t);if(void 0!==s)return s}if(e.children){const s=function(e){for(let i=0;i=r){const n=r++,u=e[n];t[u.uuid]=h,e[h]=u,t[a]=n,e[n]=o;for(let e=0,t=i;e!==t;++e){const t=s[e],i=t[n],r=t[h];t[h]=i,t[n]=r}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,s=this._bindings,i=s.length;let r=this.nCachedObjects_,n=e.length;for(let o=0,a=arguments.length;o!==a;++o){const a=arguments[o].uuid,h=t[a];if(void 0!==h)if(delete t[a],h0&&(t[o.uuid]=h),e[h]=o,e.pop();for(let e=0,t=i;e!==t;++e){const t=s[e];t[h]=t[r],t.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const s=this._bindingsIndicesByPath;let i=s[e];const r=this._bindings;if(void 0!==i)return r[i];const n=this._paths,o=this._parsedPaths,a=this._objects,h=a.length,u=this.nCachedObjects_,l=new Array(h);i=r.length,s[e]=i,n.push(e),o.push(t),r.push(l);for(let s=u,i=a.length;s!==i;++s){const i=a[s];l[s]=new mc(i,e,t)}return l}unsubscribe_(e){const t=this._bindingsIndicesByPath,s=t[e];if(void 0!==s){const i=this._paths,r=this._parsedPaths,n=this._bindings,o=n.length-1,a=n[o];t[e[o]]=s,n[s]=a,n.pop(),r[s]=r[o],r.pop(),i[s]=i[o],i.pop()}}}class fc{constructor(e,t,s=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=s,this.blendMode=i;const r=t.tracks,n=r.length,o=new Array(n),a={endingStart:Ut,endingEnd:Ut};for(let e=0;e!==n;++e){const t=r[e].createInterpolant(null);o[e]=t,t.settings=a}this._interpolantSettings=a,this._interpolants=o,this._propertyBindings=new Array(n),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,s){if(e.fadeOut(t),this.fadeIn(t),s){const s=this._clip.duration,i=e._clip.duration,r=i/s,n=s/i;e.warp(1,r,t),this.warp(n,1,t)}return this}crossFadeTo(e,t,s){return e.crossFadeFrom(this,t,s)}stopFading(){const e=this._weightInterpolant;return null!==e&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,s){const i=this._mixer,r=i.time,n=this.timeScale;let o=this._timeScaleInterpolant;null===o&&(o=i._lendControlInterpolant(),this._timeScaleInterpolant=o);const a=o.parameterPositions,h=o.sampleValues;return a[0]=r,a[1]=r+s,h[0]=e/n,h[1]=t/n,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,s,i){if(!this.enabled)return void this._updateWeight(e);const r=this._startTime;if(null!==r){const i=(e-r)*s;i<0||0===s?t=0:(this._startTime=null,t=s*i)}t*=this._updateTimeScale(e);const n=this._updateTime(t),o=this._updateWeight(e);if(o>0){const e=this._interpolants,t=this._propertyBindings;if(this.blendMode===Vt)for(let s=0,i=e.length;s!==i;++s)e[s].evaluate(n),t[s].accumulateAdditive(o);else for(let s=0,r=e.length;s!==r;++s)e[s].evaluate(n),t[s].accumulate(i,o)}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const s=this._weightInterpolant;if(null!==s){const i=s.evaluate(e)[0];t*=i,e>s.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const s=this._timeScaleInterpolant;if(null!==s){t*=s.evaluate(e)[0],e>s.parameterPositions[1]&&(this.stopWarping(),0===t?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,s=this.loop;let i=this.time+e,r=this._loopCount;const n=2202===s;if(0===e)return-1===r?i:n&&1==(1&r)?t-i:i;if(2200===s){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else{if(!(i<0)){this.time=i;break e}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(-1===r&&(e>=0?(r=0,this._setEndings(!0,0===this.repetitions,n)):this._setEndings(0===this.repetitions,!0,n)),i>=t||i<0){const s=Math.floor(i/t);i-=t*s,r+=Math.abs(s);const o=this.repetitions-r;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(1===o){const t=e<0;this._setEndings(t,!t,n)}else this._setEndings(!1,!1,n);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:s})}}else this.time=i;if(n&&1==(1&r))return t-i}return i}_setEndings(e,t,s){const i=this._interpolantSettings;s?(i.endingStart=Ot,i.endingEnd=Ot):(i.endingStart=e?this.zeroSlopeAtStart?Ot:Ut:zt,i.endingEnd=t?this.zeroSlopeAtEnd?Ot:Ut:zt)}_scheduleFading(e,t,s){const i=this._mixer,r=i.time;let n=this._weightInterpolant;null===n&&(n=i._lendControlInterpolant(),this._weightInterpolant=n);const o=n.parameterPositions,a=n.sampleValues;return o[0]=r,a[0]=t,o[1]=r+e,a[1]=s,this}}const yc=new Float32Array(1);class xc extends zs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const s=e._localRoot||this._root,i=e._clip.tracks,r=i.length,n=e._propertyBindings,o=e._interpolants,a=s.uuid,h=this._bindingsByRootAndName;let u=h[a];void 0===u&&(u={},h[a]=u);for(let e=0;e!==r;++e){const r=i[e],h=r.name;let l=u[h];if(void 0!==l)++l.referenceCount,n[e]=l;else{if(l=n[e],void 0!==l){null===l._cacheIndex&&(++l.referenceCount,this._addInactiveBinding(l,a,h));continue}const i=t&&t._propertyBindings[e].binding.parsedPath;l=new ac(mc.create(s,h,i),r.ValueTypeName,r.getValueSize()),++l.referenceCount,this._addInactiveBinding(l,a,h),n[e]=l}o[e].resultBuffer=l.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,s=e._clip.uuid,i=this._actionsByClip[s];this._bindAction(e,i&&i.knownActions[0]),this._addInactiveAction(e,s,t)}const t=e._propertyBindings;for(let e=0,s=t.length;e!==s;++e){const s=t[e];0==s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,s=t.length;e!==s;++e){const s=t[e];0==--s.useCount&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return null!==t&&t=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,s=this._nActiveActions,i=this.time+=e,r=Math.sign(e),n=this._accuIndex^=1;for(let o=0;o!==s;++o){t[o]._update(i,e,r,n)}const o=this._bindings,a=this._nActiveBindings;for(let e=0;e!==a;++e)o[e].apply(n);return this}setTime(e){this.time=0;for(let e=0;e=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bc).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Pc=new Ai,Fc=new Ai;class Uc{constructor(e=new Ai,t=new Ai){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){Pc.subVectors(e,this.start),Fc.subVectors(this.end,this.start);const s=Fc.dot(Fc);let i=Fc.dot(Pc)/s;return t&&(i=Ws(i,0,1)),i}closestPointToPoint(e,t,s){const i=this.closestPointToPointParameter(e,t);return this.delta(s).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const Oc=new Ai;class zc extends Rr{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const s=new Sn,i=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let e=0,t=1,s=32;e1)for(let s=0;s.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{hd.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(hd,t)}}setLength(e,t=.2*e,s=.2*t){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(s,t,s),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class dd extends Ia{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],s=new Sn;s.setAttribute("position",new fn(t,3)),s.setAttribute("color",new fn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(s,new va({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(e,t,s){const i=new Xr,r=this.geometry.attributes.color.array;return i.set(e),i.toArray(r,0),i.toArray(r,3),i.set(t),i.toArray(r,6),i.toArray(r,9),i.set(s),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class pd{constructor(){this.type="ShapePath",this.color=new Xr,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new fh,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,s,i){return this.currentPath.quadraticCurveTo(e,t,s,i),this}bezierCurveTo(e,t,s,i,r,n){return this.currentPath.bezierCurveTo(e,t,s,i,r,n),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(e,t){const s=t.length;let i=!1;for(let r=s-1,n=0;nNumber.EPSILON){if(h<0&&(s=t[n],a=-a,o=t[r],h=-h),e.yo.y)continue;if(e.y===s.y){if(e.x===s.x)return!0}else{const t=h*(e.x-s.x)-a*(e.y-s.y);if(0===t)return!0;if(t<0)continue;i=!i}}else{if(e.y!==s.y)continue;if(o.x<=e.x&&e.x<=s.x||s.x<=e.x&&e.x<=o.x)return!0}}return i}const s=tu.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,n,o;const a=[];if(1===i.length)return n=i[0],o=new Rh,o.curves=n.curves,a.push(o),a;let h=!s(i[0].getPoints());h=e?!h:h;const u=[],l=[];let c,d,p=[],m=0;l[m]=void 0,p[m]=[];for(let t=0,o=i.length;t1){let e=!1,s=0;for(let e=0,t=l.length;e0&&!1===e&&(p=u)}for(let e=0,t=l.length;e>>16,2246822507),s^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(s^s>>>13,3266489909),4294967296*(2097151&i)+(s>>>0)}const bd=e=>xd(e),vd=e=>xd(e),Td=(...e)=>xd(e);function _d(e,t=!1){const s=[];!0===e.isNode&&(s.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of wd(e))s.push(s,xd(i.slice(0,-4)),r.getCacheKey(t));return xd(s)}function*wd(e,t=!1){for(const s in e){if(!0===s.startsWith("_"))continue;const i=e[s];if(!0===Array.isArray(i))for(let e=0;ee.charCodeAt(0))).buffer}var Cd=Object.freeze({__proto__:null,arrayBufferToBase64:Ad,base64ToArrayBuffer:Nd,getCacheKey:_d,getNodeChildren:wd,getValueFromType:Md,getValueType:Sd,hash:Td,hashArray:vd,hashString:bd});const Rd={VERTEX:"vertex",FRAGMENT:"fragment"},Ed={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Bd={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Id=["fragment","vertex"],Pd=["setup","analyze","generate"],Fd=[...Id,"compute"],Ud=["x","y","z","w"];let Od=0;class zd extends zs{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Ed.NONE,this.updateBeforeType=Ed.NONE,this.updateAfterType=Ed.NONE,this.uuid=Xs.generateUUID(),this.version=0,this._cacheKey=null,this._cacheKeyVersion=0,this.global=!1,this.isNode=!0,Object.defineProperty(this,"id",{value:Od++})}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.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Ed.FRAME)}onRenderUpdate(e){return this.onUpdate(e,Ed.RENDER)}onObjectUpdate(e){return this.onUpdate(e,Ed.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of wd(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=_d(this,e),this._cacheKeyVersion=this.version),this._cacheKey}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)}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}setup(e){const t=e.getNodeProperties(this);let s=0;for(const e of this.getChildren())t["node"+s++]=e;return null}analyze(e){if(1===e.increaseUsage(this)){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){e.stack.nodes.length;t.initialized=!0,t.outputNode=this.setup(e),null!==t.outputNode&&e.stack.nodes.length;for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const s=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i?(i=this.generate(e)||"",r.snippet=i):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),i=e.format(i,s,t)}else i=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),i}getSerializeChildren(){return wd(this)}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:r,childNode:n}of t)void 0!==r?(void 0===s[i]&&(s[i]=Number.isInteger(r)?[]:{}),s[i][r]=n.toJSON(e.meta).uuid):s[i]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const r of e.inputNodes[s])i.push(t[r]);this[s]=i}else if("object"==typeof e.inputNodes[s]){const i={};for(const r in e.inputNodes[s]){const n=e.inputNodes[s][r];i[r]=t[n]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:s,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=n(e.textures),s=n(e.images),i=n(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),i.length>0&&(r.nodes=i)}return r}}class Ld extends zd{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){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}class Vd extends zd{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(i)||(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),r=s.build(e,i);return e.format(r,i,t)}}class Dd extends zd{static get type(){return"TempNode"}constructor(e){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,s,t);if("void"!==s&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,s),n=e.getVarFromNode(this,null,s),o=e.getPropertyName(n);return e.addLineFlowCode(`${o} = ${r}`,this),i.snippet=r,i.propertyName=o,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class kd extends Dd{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,s)=>t+e.getTypeLength(s.getNodeType(e))),0))}generate(e,t){const s=this.getNodeType(e),i=this.nodes,r=e.getComponentType(s),n=[];for(const t of i){let s=t.build(e);const i=e.getComponentType(t.getNodeType(e));i!==r&&(s=e.format(s,i,r)),n.push(s)}const o=`${e.getType(s)}( ${n.join(", ")} )`;return e.format(o,s,t)}}const Gd=Ud.join("");class Wd extends zd{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(Ud.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))}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let r=null;if(i>1){let n=null;this.getVectorLength()>=i&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const o=s.build(e,n);r=this.components.length===i&&this.components===Gd.slice(0,this.components.length)?e.format(o,n,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else r=s.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class jd extends Dd{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,r=this.getNodeType(e),n=e.getTypeFromLength(s.length,i.getNodeType(e)),o=i.build(e,n),a=t.build(e,r),h=e.getTypeLength(r),u=[];for(let e=0;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Kd=e=>Jd(e).split("").sort().join(""),Qd={setup(e,t){const s=t.shift();return e(Sp(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Xd.assign(s,...e),s);if(Yd.has(t)){const i=Yd.get(t);return e.isStackNode?(...e)=>s.add(i(...e)):(...e)=>i(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Yd.has(t.slice(0,t.length-6))){const i=Yd.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>s.assign(e[0],i(...e)):(...e)=>s.assign(i(s,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=Jd(t),wp(new Wd(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Kd(t.slice(3).toLowerCase()),s=>wp(new jd(e,t,s));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Kd(t.slice(4).toLowerCase()),()=>wp(new Hd(wp(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),wp(new Wd(e,t));if(!0===/^\d+$/.test(t))return wp(new Ld(s,new $d(Number(t),"uint")))}return Reflect.get(e,t,s)},set:(e,t,s,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,s,i):(i[t].assign(s),!0)},ep=new WeakMap,tp=new WeakMap,sp=function(e,t=null){for(const s in e)e[s]=wp(e[s],t);return e},ip=function(e,t=null){const s=e.length;for(let i=0;iwp(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...Mp(t))):null!==s?(s=wp(s),(...i)=>r(new e(t,...Mp(i),s))):(...s)=>r(new e(t,...Mp(s)))},np=function(e,...t){return wp(new e(...Mp(t)))};class op extends zd{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}call(e){const{shaderNode:t,inputNodes:s}=this,i=e.getNodeProperties(t);if(i.onceOutput)return i.onceOutput;let r=null;if(t.layout){let i=tp.get(e.constructor);void 0===i&&(i=new WeakMap,tp.set(e.constructor,i));let n=i.get(t);void 0===n&&(n=wp(e.buildFunctionNode(t)),i.set(t,n)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(n),r=wp(n.call(s))}else{const i=t.jsFunc,n=null!==s?i(s,e):i(e);r=wp(n)}return t.once&&(i.onceOutput=r),r}getOutputNode(e){const t=e.getNodeProperties(this);return null===t.outputNode&&(t.outputNode=this.setupOutput(e)),t.outputNode}setup(e){return this.getOutputNode(e)}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){return this.getOutputNode(e).build(e,t)}}class ap extends zd{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 Sp(e),wp(new op(this,e))}setup(){return this.call()}}const hp=[!1,!0],up=[0,1,2,3],lp=[-1,-2],cp=[.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],dp=new Map;for(const e of hp)dp.set(e,new $d(e));const pp=new Map;for(const e of up)pp.set(e,new $d(e,"uint"));const mp=new Map([...pp].map((e=>new $d(e.value,"int"))));for(const e of lp)mp.set(e,new $d(e,"int"));const gp=new Map([...mp].map((e=>new $d(e.value))));for(const e of cp)gp.set(e,new $d(e));for(const e of cp)gp.set(-e,new $d(-e));const fp={bool:dp,uint:pp,ints:mp,float:gp},yp=new Map([...dp,...gp]),xp=(e,t)=>yp.has(e)?yp.get(e):!0===e.isNode?e:new $d(e,t),bp=function(e,t=null){return(...s)=>{if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every((e=>"object"!=typeof e)))&&(s=[Md(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return wp(t.get(s[0]));if(1===s.length){const t=xp(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?wp(t):wp(new Vd(t,e))}const i=s.map((e=>xp(e)));return wp(new kd(i,e))}},vp=e=>"object"==typeof e&&null!==e?e.value:e,Tp=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function _p(e,t){return new Proxy(new ap(e,t),Qd)}const wp=(e,t=null)=>function(e,t=null){const s=Sd(e);if("node"===s){let t=ep.get(e);return void 0===t&&(t=new Proxy(e,Qd),ep.set(e,t),ep.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?wp(xp(e,t)):"shader"===s?Cp(e):e}(e,t),Sp=(e,t=null)=>new sp(e,t),Mp=(e,t=null)=>new ip(e,t),Ap=(...e)=>new rp(...e),Np=(...e)=>new np(...e),Cp=(e,t)=>{const s=new _p(e,t),i=(...e)=>{let t;return Sp(e),t=e[0]&&e[0].isNode?[...e]:e[0],s.call(t)};return i.shaderNode=s,i.setLayout=e=>(s.setLayout(e),i),i.once=()=>(s.once=!0,i),i},Rp=(...e)=>(console.warn("TSL.ShaderNode: tslFn() has been renamed to Fn()."),Cp(...e));Zd("toGlobal",(e=>(e.global=!0,e)));const Ep=e=>{Xd=e},Bp=()=>Xd,Ip=(...e)=>Xd.If(...e);function Pp(e){return Xd&&Xd.add(e),e}Zd("append",Pp);const Fp=new bp("color"),Up=new bp("float",fp.float),Op=new bp("int",fp.ints),zp=new bp("uint",fp.uint),Lp=new bp("bool",fp.bool),Vp=new bp("vec2"),Dp=new bp("ivec2"),kp=new bp("uvec2"),Gp=new bp("bvec2"),Wp=new bp("vec3"),jp=new bp("ivec3"),Hp=new bp("uvec3"),qp=new bp("bvec3"),$p=new bp("vec4"),Xp=new bp("ivec4"),Yp=new bp("uvec4"),Zp=new bp("bvec4"),Jp=new bp("mat2"),Kp=new bp("mat3"),Qp=new bp("mat4"),em=(e="")=>wp(new $d(e,"string")),tm=e=>wp(new $d(e,"ArrayBuffer"));Zd("toColor",Fp),Zd("toFloat",Up),Zd("toInt",Op),Zd("toUint",zp),Zd("toBool",Lp),Zd("toVec2",Vp),Zd("toIVec2",Dp),Zd("toUVec2",kp),Zd("toBVec2",Gp),Zd("toVec3",Wp),Zd("toIVec3",jp),Zd("toUVec3",Hp),Zd("toBVec3",qp),Zd("toVec4",$p),Zd("toIVec4",Xp),Zd("toUVec4",Yp),Zd("toBVec4",Zp),Zd("toMat2",Jp),Zd("toMat3",Kp),Zd("toMat4",Qp);const sm=Ap(Ld),im=(e,t)=>wp(new Vd(wp(e),t)),rm=(e,t)=>wp(new Wd(wp(e),t));Zd("element",sm),Zd("convert",im);class nm extends zd{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.version=0,this.shared=t,this.order=s,this.isUniformGroup=!0}set needsUpdate(e){!0===e&&this.version++}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 om=e=>new nm(e),am=(e,t=0)=>new nm(e,!0,t),hm=am("frame"),um=am("render"),lm=om("object");class cm extends qd{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=lm}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const s=this.getSelf();return e=e.bind(s),super.onUpdate((t=>{const i=e(t,s);void 0!==i&&(this.value=i)}),t)}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const n=r.getInputType(e),o=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.label),a=e.getPropertyName(o);return void 0!==e.context.label&&delete e.context.label,e.format(a,s,t)}}const dm=(e,t)=>{const s=Tp(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return wp(new cm(i,s))};class pm extends zd{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}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 mm=(e,t)=>wp(new pm(e,t)),gm=(e,t)=>wp(new pm(e,t,!0)),fm=Np(pm,"vec4","DiffuseColor"),ym=Np(pm,"vec3","EmissiveColor"),xm=Np(pm,"float","Roughness"),bm=Np(pm,"float","Metalness"),vm=Np(pm,"float","Clearcoat"),Tm=Np(pm,"float","ClearcoatRoughness"),_m=Np(pm,"vec3","Sheen"),wm=Np(pm,"float","SheenRoughness"),Sm=Np(pm,"float","Iridescence"),Mm=Np(pm,"float","IridescenceIOR"),Am=Np(pm,"float","IridescenceThickness"),Nm=Np(pm,"float","AlphaT"),Cm=Np(pm,"float","Anisotropy"),Rm=Np(pm,"vec3","AnisotropyT"),Em=Np(pm,"vec3","AnisotropyB"),Bm=Np(pm,"color","SpecularColor"),Im=Np(pm,"float","SpecularF90"),Pm=Np(pm,"float","Shininess"),Fm=Np(pm,"vec4","Output"),Um=Np(pm,"float","dashSize"),Om=Np(pm,"float","gapSize"),zm=Np(pm,"float","pointWidth"),Lm=Np(pm,"float","IOR"),Vm=Np(pm,"float","Transmission"),Dm=Np(pm,"float","Thickness"),km=Np(pm,"float","AttenuationDistance"),Gm=Np(pm,"color","AttenuationColor"),Wm=Np(pm,"float","Dispersion");class jm extends Dd{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}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 s=e.getTypeLength(t.node.getNodeType(e));return Ud.join("").slice(0,s)!==t.components}return!1}generate(e,t){const{targetNode:s,sourceNode:i}=this,r=this.needsSplitAssign(e),n=s.getNodeType(e),o=s.context({assign:!0}).build(e),a=i.build(e,n),h=i.getNodeType(e),u=e.getDataFromNode(this);let l;if(!0===u.initialized)"void"!==t&&(l=o);else if(r){const i=e.getVarFromNode(this,null,n),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${a}`,this);const h=s.node.context({assign:!0}).build(e);for(let t=0;t{const i=s.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r))for(let e=0;e(t=t.length>1||t[0]&&!0===t[0].isNode?Mp(t):Sp(t[0]),wp(new qm(wp(e),t)));Zd("call",$m);class Xm extends Dd{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new Xm(e,t,s);for(let t=0;t>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"=="===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("<"===s||">"===s||"<="===s||">="===s){const s=t?e.getTypeLength(t):Math.max(e.getTypeLength(n),e.getTypeLength(o));return s>1?`bvec${s}`:"bool"}return"float"===n&&e.isMatrix(o)?o:e.isMatrix(n)&&e.isVector(o)?e.getVectorFromMatrix(n):e.isVector(n)&&e.isMatrix(o)?e.getVectorFromMatrix(o):e.getTypeLength(o)>e.getTypeLength(n)?o:n}generate(e,t){const s=this.op,i=this.aNode,r=this.bNode,n=this.getNodeType(e,t);let o=null,a=null;"void"!==n?(o=i.getNodeType(e),a=void 0!==r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s?e.isVector(o)?a=o:o!==a&&(o=a="float"):">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):e.isMatrix(o)&&e.isVector(a)?a=e.getVectorFromMatrix(o):o=e.isVector(o)&&e.isMatrix(a)?e.getVectorFromMatrix(a):a=n):o=a=n;const h=i.build(e,o),u=void 0!==r?r.build(e,a):null,l=e.getTypeLength(t),c=e.getFunctionOperator(s);return"void"!==t?"<"===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThan",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} < ${u} )`,n,t):"<="===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThanEqual",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} <= ${u} )`,n,t):">"===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThan",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} > ${u} )`,n,t):">="===s&&l>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThanEqual",t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} >= ${u} )`,n,t):"!"===s||"~"===s?e.format(`(${s}${h})`,o,t):c?e.format(`${c}( ${h}, ${u} )`,n,t):e.format(`( ${h} ${s} ${u} )`,n,t):"void"!==o?c?e.format(`${c}( ${h}, ${u} )`,n,t):e.format(`${h} ${s} ${u}`,n,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Ym=Ap(Xm,"+"),Zm=Ap(Xm,"-"),Jm=Ap(Xm,"*"),Km=Ap(Xm,"/"),Qm=Ap(Xm,"%"),eg=Ap(Xm,"=="),tg=Ap(Xm,"!="),sg=Ap(Xm,"<"),ig=Ap(Xm,">"),rg=Ap(Xm,"<="),ng=Ap(Xm,">="),og=Ap(Xm,"&&"),ag=Ap(Xm,"||"),hg=Ap(Xm,"!"),ug=Ap(Xm,"^^"),lg=Ap(Xm,"&"),cg=Ap(Xm,"~"),dg=Ap(Xm,"|"),pg=Ap(Xm,"^"),mg=Ap(Xm,"<<"),gg=Ap(Xm,">>");Zd("add",Ym),Zd("sub",Zm),Zd("mul",Jm),Zd("div",Km),Zd("modInt",Qm),Zd("equal",eg),Zd("notEqual",tg),Zd("lessThan",sg),Zd("greaterThan",ig),Zd("lessThanEqual",rg),Zd("greaterThanEqual",ng),Zd("and",og),Zd("or",ag),Zd("not",hg),Zd("xor",ug),Zd("bitAnd",lg),Zd("bitNot",cg),Zd("bitOr",dg),Zd("bitXor",pg),Zd("shiftLeft",mg),Zd("shiftRight",gg);const fg=(...e)=>(console.warn("TSL.OperatorNode: .remainder() has been renamed to .modInt()."),Qm(...e));Zd("remainder",fg);class yg extends Dd{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=s,this.cNode=i}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>o?t:n>o?s:o>r?i:t}getNodeType(e){const t=this.method;return t===yg.LENGTH||t===yg.DISTANCE||t===yg.DOT?"float":t===yg.CROSS?"vec3":t===yg.ALL?"bool":t===yg.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===yg.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,h=!0===e.renderer.isWebGLRenderer;if(s===yg.TRANSFORM_DIRECTION){let s=n,i=o;e.isMatrix(s.getNodeType(e))?i=$p(Wp(i),0):s=$p(Wp(s),0);const r=Jm(s,i).xyz;return Ug(r).build(e,t)}if(s===yg.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);if(s===yg.ONE_MINUS)return Zm(1,n).build(e,t);if(s===yg.RECIPROCAL)return Km(1,n).build(e,t);if(s===yg.DIFFERENCE)return Wg(Zm(n,o)).build(e,t);{const u=[];return s===yg.CROSS||s===yg.MOD?u.push(n.build(e,i),o.build(e,i)):h&&s===yg.STEP?u.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):h&&(s===yg.MIN||s===yg.MAX)||s===yg.MOD?u.push(n.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):s===yg.REFRACT?u.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===yg.MIX?u.push(n.build(e,r),o.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):(u.push(n.build(e,r)),null!==o&&u.push(o.build(e,r)),null!==a&&u.push(a.build(e,r))),e.format(`${e.getMethod(s,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}yg.ALL="all",yg.ANY="any",yg.EQUALS="equals",yg.RADIANS="radians",yg.DEGREES="degrees",yg.EXP="exp",yg.EXP2="exp2",yg.LOG="log",yg.LOG2="log2",yg.SQRT="sqrt",yg.INVERSE_SQRT="inversesqrt",yg.FLOOR="floor",yg.CEIL="ceil",yg.NORMALIZE="normalize",yg.FRACT="fract",yg.SIN="sin",yg.COS="cos",yg.TAN="tan",yg.ASIN="asin",yg.ACOS="acos",yg.ATAN="atan",yg.ABS="abs",yg.SIGN="sign",yg.LENGTH="length",yg.NEGATE="negate",yg.ONE_MINUS="oneMinus",yg.DFDX="dFdx",yg.DFDY="dFdy",yg.ROUND="round",yg.RECIPROCAL="reciprocal",yg.TRUNC="trunc",yg.FWIDTH="fwidth",yg.BITCAST="bitcast",yg.TRANSPOSE="transpose",yg.ATAN2="atan2",yg.MIN="min",yg.MAX="max",yg.MOD="mod",yg.STEP="step",yg.REFLECT="reflect",yg.DISTANCE="distance",yg.DIFFERENCE="difference",yg.DOT="dot",yg.CROSS="cross",yg.POW="pow",yg.TRANSFORM_DIRECTION="transformDirection",yg.MIX="mix",yg.CLAMP="clamp",yg.REFRACT="refract",yg.SMOOTHSTEP="smoothstep",yg.FACEFORWARD="faceforward";const xg=Up(1e-6),bg=Up(1e6),vg=Up(Math.PI),Tg=Up(2*Math.PI),_g=Ap(yg,yg.ALL),wg=Ap(yg,yg.ANY),Sg=Ap(yg,yg.EQUALS),Mg=Ap(yg,yg.RADIANS),Ag=Ap(yg,yg.DEGREES),Ng=Ap(yg,yg.EXP),Cg=Ap(yg,yg.EXP2),Rg=Ap(yg,yg.LOG),Eg=Ap(yg,yg.LOG2),Bg=Ap(yg,yg.SQRT),Ig=Ap(yg,yg.INVERSE_SQRT),Pg=Ap(yg,yg.FLOOR),Fg=Ap(yg,yg.CEIL),Ug=Ap(yg,yg.NORMALIZE),Og=Ap(yg,yg.FRACT),zg=Ap(yg,yg.SIN),Lg=Ap(yg,yg.COS),Vg=Ap(yg,yg.TAN),Dg=Ap(yg,yg.ASIN),kg=Ap(yg,yg.ACOS),Gg=Ap(yg,yg.ATAN),Wg=Ap(yg,yg.ABS),jg=Ap(yg,yg.SIGN),Hg=Ap(yg,yg.LENGTH),qg=Ap(yg,yg.NEGATE),$g=Ap(yg,yg.ONE_MINUS),Xg=Ap(yg,yg.DFDX),Yg=Ap(yg,yg.DFDY),Zg=Ap(yg,yg.ROUND),Jg=Ap(yg,yg.RECIPROCAL),Kg=Ap(yg,yg.TRUNC),Qg=Ap(yg,yg.FWIDTH),ef=Ap(yg,yg.BITCAST),tf=Ap(yg,yg.TRANSPOSE),sf=Ap(yg,yg.ATAN2),rf=Ap(yg,yg.MIN),nf=Ap(yg,yg.MAX),of=Ap(yg,yg.MOD),af=Ap(yg,yg.STEP),hf=Ap(yg,yg.REFLECT),uf=Ap(yg,yg.DISTANCE),lf=Ap(yg,yg.DIFFERENCE),cf=Ap(yg,yg.DOT),df=Ap(yg,yg.CROSS),pf=Ap(yg,yg.POW),mf=Ap(yg,yg.POW,2),gf=Ap(yg,yg.POW,3),ff=Ap(yg,yg.POW,4),yf=Ap(yg,yg.TRANSFORM_DIRECTION),xf=e=>Jm(jg(e),pf(Wg(e),1/3)),bf=e=>cf(e,e),vf=Ap(yg,yg.MIX),Tf=(e,t=0,s=1)=>wp(new yg(yg.CLAMP,wp(e),wp(t),wp(s))),_f=e=>Tf(e),wf=Ap(yg,yg.REFRACT),Sf=Ap(yg,yg.SMOOTHSTEP),Mf=Ap(yg,yg.FACEFORWARD),Af=Cp((([e])=>{const t=cf(e.xy,Vp(12.9898,78.233)),s=of(t,vg);return Og(zg(s).mul(43758.5453))})),Nf=(e,t,s)=>vf(t,s,e),Cf=(e,t,s)=>Sf(t,s,e);Zd("all",_g),Zd("any",wg),Zd("equals",Sg),Zd("radians",Mg),Zd("degrees",Ag),Zd("exp",Ng),Zd("exp2",Cg),Zd("log",Rg),Zd("log2",Eg),Zd("sqrt",Bg),Zd("inverseSqrt",Ig),Zd("floor",Pg),Zd("ceil",Fg),Zd("normalize",Ug),Zd("fract",Og),Zd("sin",zg),Zd("cos",Lg),Zd("tan",Vg),Zd("asin",Dg),Zd("acos",kg),Zd("atan",Gg),Zd("abs",Wg),Zd("sign",jg),Zd("length",Hg),Zd("lengthSq",bf),Zd("negate",qg),Zd("oneMinus",$g),Zd("dFdx",Xg),Zd("dFdy",Yg),Zd("round",Zg),Zd("reciprocal",Jg),Zd("trunc",Kg),Zd("fwidth",Qg),Zd("atan2",sf),Zd("min",rf),Zd("max",nf),Zd("mod",of),Zd("step",af),Zd("reflect",hf),Zd("distance",uf),Zd("dot",cf),Zd("cross",df),Zd("pow",pf),Zd("pow2",mf),Zd("pow3",gf),Zd("pow4",ff),Zd("transformDirection",yf),Zd("mix",Nf),Zd("clamp",Tf),Zd("refract",wf),Zd("smoothstep",Cf),Zd("faceForward",Mf),Zd("difference",lf),Zd("saturate",_f),Zd("cbrt",xf),Zd("transpose",tf),Zd("rand",Af);class Rf extends zd{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const t=this.ifNode.getNodeType(e);if(null!==this.elseNode){const s=this.elseNode.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(t))return s}return t}setup(e){const t=this.condNode.cache(),s=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=s.context({nodeBlock:s}),n.elseNode=i?i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:n,elseNode:o}=e.getNodeProperties(this),a="void"!==t,h=a?mm(s).build(e):"";i.nodeProperty=h;const u=r.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let l=n.build(e,s);if(l&&(l=a?h+" = "+l+";":"return "+l+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+l+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=o.build(e,s);t&&(t=a?h+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(h,s,t)}}const Ef=Ap(Rf);Zd("select",Ef);const Bf=(...e)=>(console.warn("TSL.ConditionalNode: cond() has been renamed to select()."),Ef(...e));Zd("cond",Bf);class If extends zd{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)}analyze(e){this.node.build(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e);return e.setContext(t),s}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(s),i}}const Pf=Ap(If),Ff=(e,t)=>Pf(e,{label:t});Zd("context",Pf),Zd("label",Ff);class Uf extends zd{static get type(){return"VarNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s}=this,i=e.getVarFromNode(this,s,e.getVectorType(this.getNodeType(e))),r=e.getPropertyName(i),n=t.build(e,i.type);return e.addLineFlowCode(`${r} = ${n}`,this),r}}const Of=Ap(Uf);Zd("toVar",((...e)=>Of(...e).append()));const zf=e=>(console.warn('TSL: "temp" is deprecated. Use ".toVar()" instead.'),Of(e));Zd("temp",zf);class Lf extends zd{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(void 0===s){const i=this.name,r=this.getNodeType(e);t.varying=s=e.getVaryingFromNode(this,i,r),t.node=this.node}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e)}analyze(e){return this.setupVarying(e),this.node.analyze(e)}generate(e){const t=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===t.propertyName){const i=this.getNodeType(e),r=e.getPropertyName(s,Rd.VERTEX);e.flowNodeFromShaderStage(Rd.VERTEX,this.node,i,r),t.propertyName=r}return e.getPropertyName(s)}}const Vf=Ap(Lf);Zd("varying",Vf);const Df="WorkingColorSpace",kf="OutputColorSpace";function Gf(e){let t=null;return e===Jt?t="Linear":e===Zt&&(t="sRGB"),t}function Wf(e,t){return Gf(e)+"To"+Gf(t)}class jf extends Dd{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}getColorSpace(e,t){return t===Df?ii.workingColorSpace:t===kf?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{renderer:t}=e,{colorNode:s}=this,i=this.getColorSpace(e,this.source),r=this.getColorSpace(e,this.target);if(i===r)return s;const n=Wf(i,r);let o=null;const a=t.library.getColorSpaceFunction(n);return null!==a?o=$p(a(s.rgb),s.a):(console.error("ColorSpaceNode: Unsupported Color Space configuration.",n),o=s),o}}const Hf=e=>wp(new jf(wp(e),Df,kf)),qf=e=>wp(new jf(wp(e),kf,Df)),$f=(e,t)=>wp(new jf(wp(e),Df,t)),Xf=(e,t)=>wp(new jf(wp(e),t,Df));Zd("toOutputColorSpace",Hf),Zd("toWorkingColorSpace",qf),Zd("workingToColorSpace",$f),Zd("colorSpaceToWorking",Xf);let Yf=class extends Ld{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),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class Zf extends zd{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=Ed.OBJECT}setGroup(e){return this.group=e,this}element(e){return wp(new Yf(this,wp(e)))}setNodeType(e){const t=dm(null,e).getSelf();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 s=e[t[0]];for(let e=1;ewp(new Jf(e,t,s));class Qf extends Dd{static get type(){return"ToneMappingNode"}constructor(e,t=ty,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}getCacheKey(){return Td(super.getCacheKey(),this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,s=this.toneMapping;if(0===s)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(s);return null!==r?i=$p(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const ey=(e,t,s)=>wp(new Qf(e,wp(t),wp(s))),ty=Kf("toneMappingExposure","float");Zd("toneMapping",((e,t,s)=>ey(t,s,e)));class sy extends qd{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=Ss,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),s=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,n=this.bufferOffset,o=!0===s.isInterleavedBuffer?s:new Qn(s,r),a=new to(o,i,n);o.setUsage(this.usage),this.attribute=a,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=Vf(this).build(e,t)}return r}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 iy=(e,t,s,i)=>wp(new sy(e,t,s,i)),ry=(e,t,s,i)=>iy(e,t,s,i).setUsage(Ms),ny=(e,t,s,i)=>iy(e,t,s,i).setInstanced(!0),oy=(e,t,s,i)=>ry(e,t,s,i).setInstanced(!0);Zd("toAttribute",(e=>iy(e.value)));class ay extends zd{static get type(){return"ComputeNode"}constructor(e,t,s=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=s,this.dispatchCount=0,this.version=1,this.updateBeforeType=Ed.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let s=t[0];for(let e=1;ewp(new ay(wp(e),t,s));Zd("compute",hy);class uy extends zd{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){return this.node.getNodeType(e)}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(s),r}}const ly=(e,...t)=>wp(new uy(wp(e),...t));Zd("cache",ly);class cy extends zd{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 dy=Ap(cy);Zd("bypass",dy);class py extends zd{static get type(){return"RemapNode"}constructor(e,t,s,i=Up(0),r=Up(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:r,doClamp:n}=this;let o=e.sub(t).div(s.sub(t));return!0===n&&(o=o.clamp()),o.mul(r.sub(i)).add(i)}}const my=Ap(py,null,null,{doClamp:!1}),gy=Ap(py);Zd("remap",my),Zd("remapClamp",gy);class fy extends zd{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if("void"!==s)return e.format(`( ${i} )`,s,t);e.addLineFlowCode(i,this)}}const yy=Ap(fy),xy=e=>(e?Ef(e,yy("discard")):yy("discard")).append(),by=()=>yy("return").append();Zd("discard",xy);class vy extends Dd{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutput=!0}setup({context:e}){let t=this.colorNode||e.color;const s=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||Yt;return 0!==s&&(t=t.toneMapping(s)),i!==Yt&&i!==ii.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const Ty=(e,t=null,s=null)=>wp(new vy(wp(e),t,s));function _y(e){console.warn("THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)}Zd("renderOutput",Ty);class wy extends zd{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 s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),n=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(n.name,r,s);return Vf(this).build(e,s)}return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}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 Sy=(e,t)=>wp(new wy(e,t)),My=e=>Sy("uv"+(e>0?e:""),"vec2");class Ay extends zd{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const Ny=Ap(Ay);class Cy extends cm{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Ed.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const Ry=Ap(Cy);class Ey extends cm{static get type(){return"TextureNode"}constructor(e,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=Ed.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===Be?"uvec4":this.value.type===Ee?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return My(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=dm(this.value.matrix)),this._matrixUniform.mul(Wp(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Ed.FRAME:Ed.NONE,this}setupUV(e,t){const s=this.value;return!e.isFlipY()||!0!==s.isRenderTargetTexture&&!0!==s.isFramebufferTexture&&!0!==s.isDepthTexture||(t=this.sampler?t.flipY():t.setY(Op(Ny(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this)),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}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,s,i,r,n,o,a){const h=this.value;let u;return u=i?e.generateTextureLevel(h,t,s,i,n):r?e.generateTextureBias(h,t,s,r,n):a?e.generateTextureGrad(h,t,s,a,n):o?e.generateTextureCompare(h,t,s,o,n):!1===this.sampler?e.generateTextureLoad(h,t,s,n):e.generateTexture(h,t,s,n),u}generate(e,t){const s=e.getNodeProperties(this),i=this.value;if(!i||!0!==i.isTexture)throw new Error("TextureNode: Need a three.js texture.");const r=super.generate(e,"property");if("sampler"===t)return r+"_sampler";if(e.isReference(t))return r;{const n=e.getDataFromNode(this);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:i,biasNode:a,compareNode:h,depthNode:u,gradNode:l}=s,c=this.generateUV(e,t),d=i?i.build(e,"float"):null,p=a?a.build(e,"float"):null,m=u?u.build(e,"int"):null,g=h?h.build(e,"float"):null,f=l?[l[0].build(e,"vec2"),l[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);o=e.getPropertyName(y);const x=this.generateSnippet(e,r,c,d,p,m,g,f);e.addLineFlowCode(`${o} = ${x}`,this),n.snippet=x,n.propertyName=o}let a=o;const h=this.getNodeType(e);return e.needsToWorkingColorSpace(i)&&(a=Xf(yy(a,h),i.colorSpace).setup(e).build(e,h)),e.format(a,h,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){const t=this.clone();return t.uvNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}blur(e){const t=this.clone();return t.biasNode=wp(e).mul(Ry(t)),t.referenceNode=this.getSelf(),wp(t)}level(e){const t=this.clone();return t.levelNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}size(e){return Ny(this,e)}bias(e){const t=this.clone();return t.biasNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}compare(e){const t=this.clone();return t.compareNode=wp(e),t.referenceNode=this.getSelf(),wp(t)}grad(e,t){const s=this.clone();return s.gradNode=[wp(e),wp(t)],s.referenceNode=this.getSelf(),wp(s)}depth(e){const t=this.clone();return t.depthNode=wp(e),t.referenceNode=this.getSelf(),wp(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}}const By=Ap(Ey),Iy=(...e)=>By(...e).setSampler(!1),Py=e=>(!0===e.isNode?e:By(e)).convert("sampler"),Fy=dm("float").label("cameraNear").setGroup(um).onRenderUpdate((({camera:e})=>e.near)),Uy=dm("float").label("cameraFar").setGroup(um).onRenderUpdate((({camera:e})=>e.far)),Oy=dm("mat4").label("cameraProjectionMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.projectionMatrix)),zy=dm("mat4").label("cameraProjectionMatrixInverse").setGroup(um).onRenderUpdate((({camera:e})=>e.projectionMatrixInverse)),Ly=dm("mat4").label("cameraViewMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.matrixWorldInverse)),Vy=dm("mat4").label("cameraWorldMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.matrixWorld)),Dy=dm("mat3").label("cameraNormalMatrix").setGroup(um).onRenderUpdate((({camera:e})=>e.normalMatrix)),ky=dm(new Ai).label("cameraPosition").setGroup(um).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld)));class Gy extends zd{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Ed.OBJECT,this._uniformNode=new cm(null)}getNodeType(){const e=this.scope;return e===Gy.WORLD_MATRIX?"mat4":e===Gy.POSITION||e===Gy.VIEW_POSITION||e===Gy.DIRECTION||e===Gy.SCALE?"vec3":void 0}update(e){const t=this.object3d,s=this._uniformNode,i=this.scope;if(i===Gy.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Gy.POSITION)s.value=s.value||new Ai,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Gy.SCALE)s.value=s.value||new Ai,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Gy.DIRECTION)s.value=s.value||new Ai,t.getWorldDirection(s.value);else if(i===Gy.VIEW_POSITION){const i=e.camera;s.value=s.value||new Ai,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}}generate(e){const t=this.scope;return t===Gy.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t!==Gy.POSITION&&t!==Gy.VIEW_POSITION&&t!==Gy.DIRECTION&&t!==Gy.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Gy.WORLD_MATRIX="worldMatrix",Gy.POSITION="position",Gy.SCALE="scale",Gy.VIEW_POSITION="viewPosition",Gy.DIRECTION="direction";const Wy=Ap(Gy,Gy.DIRECTION),jy=Ap(Gy,Gy.WORLD_MATRIX),Hy=Ap(Gy,Gy.POSITION),qy=Ap(Gy,Gy.SCALE),$y=Ap(Gy,Gy.VIEW_POSITION);class Xy extends Gy{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Yy=Np(Xy,Xy.DIRECTION),Zy=Np(Xy,Xy.WORLD_MATRIX),Jy=Np(Xy,Xy.POSITION),Ky=Np(Xy,Xy.SCALE),Qy=Np(Xy,Xy.VIEW_POSITION),ex=dm(new Zs).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),tx=dm(new sr).onObjectUpdate((({object:e},t)=>t.value.copy(e.matrixWorld).invert())),sx=Ly.mul(Zy).toVar("modelViewMatrix"),ix=Cp((e=>(e.context.isHighPrecisionModelViewMatrix=!0,dm("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highPrecisionModelViewMatrix"),rx=Cp((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return dm("mat3").onObjectUpdate((({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highPrecisionModelNormalMatrix"),nx=Sy("position","vec3"),ox=nx.varying("positionLocal"),ax=nx.varying("positionPrevious"),hx=Zy.mul(ox).xyz.varying("v_positionWorld"),ux=ox.transformDirection(Zy).varying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),lx=sx.mul(ox).xyz.varying("v_positionView"),cx=lx.negate().varying("v_positionViewDirection").normalize().toVar("positionViewDirection");class dx extends zd{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Us&&s.side===d?"false":e.getFrontFacing()}}const px=Np(dx),mx=Up(px).mul(2).sub(1),gx=Sy("normal","vec3"),fx=Cp((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('TSL.NormalNode: Vertex attribute "normal" not found on geometry.'),Wp(0,1,0)):gx),"vec3").once()().toVar("normalLocal"),yx=lx.dFdx().cross(lx.dFdy()).normalize().toVar("normalFlat"),xx=Cp((e=>{let t;return t=!0===e.material.flatShading?yx:Vf(Sx(fx),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),bx=Vf(xx.transformDirection(Ly),"v_normalWorld").normalize().toVar("normalWorld"),vx=Cp((e=>e.context.setupNormal()),"vec3").once()().mul(mx).toVar("transformedNormalView"),Tx=vx.transformDirection(Ly).toVar("transformedNormalWorld"),_x=Cp((e=>e.context.setupClearcoatNormal()),"vec3").once()().mul(mx).toVar("transformedClearcoatNormalView"),wx=Cp((([e,t=Zy])=>{const s=Kp(t),i=e.div(Wp(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz})),Sx=Cp((([e],t)=>{const s=t.renderer.nodes.modelNormalViewMatrix;if(null!==s)return s.transformDirection(e);const i=ex.mul(e);return Ly.transformDirection(i)})),Mx=dm(0).onReference((({material:e})=>e)).onRenderUpdate((({material:e})=>e.refractionRatio)),Ax=cx.negate().reflect(vx),Nx=cx.negate().refract(vx,Mx),Cx=Ax.transformDirection(Ly).toVar("reflectVector"),Rx=Nx.transformDirection(Ly).toVar("reflectVector");class Ex extends Ey{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===he?Cx:e.mapping===ue?Rx:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),Wp(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==Os&&s.isRenderTargetTexture?t:Wp(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const Bx=Ap(Ex);class Ix extends cm{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Px=(e,t,s)=>wp(new Ix(e,t,s));class Fx extends Ld{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType();return e.format(t,"vec4",s)}}class Ux extends Ix{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null,"vec4"),this.array=e,this.elementType=t,this._elementType=null,this._elementLength=0,this.updateType=Ed.RENDER,this.isArrayBufferNode=!0}getElementType(){return this.elementType||this._elementType}getElementLength(){return this._elementLength}update(){const{array:e,value:t}=this,s=this.getElementLength(),i=this.getElementType();if(1===s)for(let s=0;swp(new Ux(e,t)),zx=(e,t)=>(console.warn("TSL.UniformArrayNode: uniforms() has been renamed to uniformArray()."),wp(new Ux(e,t)));class Lx extends Ld{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),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class Vx extends zd{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=Ed.OBJECT}element(e){return wp(new Lx(this,wp(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Px(null,e,this.count):Array.isArray(this.getValueFromReference())?Ox(null,e):"texture"===e?By(null):"cubeTexture"===e?Bx(null):dm(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;ewp(new Vx(e,t,s)),kx=(e,t,s,i)=>wp(new Vx(e,t,i,s));class Gx extends Vx{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Wx=(e,t,s)=>wp(new Gx(e,t,s)),jx=Cp((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Sy("tangent","vec4"))))(),Hx=jx.xyz.toVar("tangentLocal"),qx=sx.mul($p(Hx,0)).xyz.varying("v_tangentView").normalize().toVar("tangentView"),$x=qx.transformDirection(Ly).varying("v_tangentWorld").normalize().toVar("tangentWorld"),Xx=qx.toVar("transformedTangentView"),Yx=Xx.transformDirection(Ly).normalize().toVar("transformedTangentWorld"),Zx=e=>e.mul(jx.w).xyz,Jx=Vf(Zx(gx.cross(jx)),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Kx=Vf(Zx(fx.cross(Hx)),"v_bitangentLocal").normalize().toVar("bitangentLocal"),Qx=Vf(Zx(xx.cross(qx)),"v_bitangentView").normalize().toVar("bitangentView"),eb=Vf(Zx(bx.cross($x)),"v_bitangentWorld").normalize().toVar("bitangentWorld"),tb=Zx(vx.cross(Xx)).normalize().toVar("transformedBitangentView"),sb=tb.transformDirection(Ly).normalize().toVar("transformedBitangentWorld"),ib=Kp(qx,Qx,xx),rb=cx.mul(ib),nb=(e,t)=>e.sub(rb.mul(t)),ob=(()=>{let e=Em.cross(cx);return e=e.cross(Em).normalize(),e=vf(e,vx,Cm.mul(xm.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),ab=Cp((e=>{const{eye_pos:t,surf_norm:s,mapN:i,uv:r}=e,n=t.dFdx(),o=t.dFdy(),a=r.dFdx(),h=r.dFdy(),u=s,l=o.cross(u),c=u.cross(n),d=l.mul(a.x).add(c.mul(h.x)),p=l.mul(a.y).add(c.mul(h.y)),m=d.dot(d).max(p.dot(p)),g=mx.mul(m.inverseSqrt());return Ym(d.mul(i.x,g),p.mul(i.y,g),u.mul(i.z)).normalize()}));class hb extends Dd{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:s}=this;let i=this.node.mul(2).sub(1);null!==s&&(i=Wp(i.xy.mul(s),i.z));let r=null;if(1===t)r=Sx(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?ib.mul(i).normalize():ab({eye_pos:lx,surf_norm:xx,mapN:i,uv:My()})}return r}}const ub=Ap(hb),lb=Cp((({textureNode:e,bumpScale:t})=>{const s=t=>e.cache().context({getUV:e=>t(e.uvNode||My()),forceUVContext:!0}),i=Up(s((e=>e)));return Vp(Up(s((e=>e.add(e.dFdx())))).sub(i),Up(s((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),cb=Cp((e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,o=t.dFdy().normalize().cross(n),a=n.cross(r),h=r.dot(o).mul(mx),u=h.sign().mul(i.x.mul(o).add(i.y.mul(a)));return h.abs().mul(s).sub(u).normalize()}));class db extends Dd{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=lb({textureNode:this.textureNode,bumpScale:e});return cb({surf_pos:lx,surf_norm:xx,dHdxy:t})}}const pb=Ap(db),mb=new Map;class gb extends zd{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=mb.get(e);return void 0===s&&(s=Wx(e,t),mb.set(e,s)),s}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,s=this.scope;let i=null;if(s===gb.COLOR){const e=void 0!==t.color?this.getColor(s):Wp();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===gb.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===gb.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Up(1);else if(s===gb.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularMap?e.mul(this.getTexture(s).a):e}else if(s===gb.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===gb.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===gb.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===gb.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(s)):r}else if(s===gb.NORMAL)t.normalMap?(i=ub(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?pb(this.getTexture("bump").r,this.getFloat("bumpScale")):xx;else if(s===gb.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===gb.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===gb.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?ub(this.getTexture(s),this.getCache(s+"Scale","vec2")):xx;else if(s===gb.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===gb.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(.07,1)}else if(s===gb.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=Jp(Qb.x,Qb.y,Qb.y.negate(),Qb.x).mul(e.rg.mul(2).sub(Vp(1)).normalize().mul(e.b))}else i=Qb;else if(s===gb.IRIDESCENCE_THICKNESS){const e=Dx("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Dx("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===gb.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===gb.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===gb.IOR)i=this.getFloat(s);else if(s===gb.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===gb.AO_MAP)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}gb.ALPHA_TEST="alphaTest",gb.COLOR="color",gb.OPACITY="opacity",gb.SHININESS="shininess",gb.SPECULAR="specular",gb.SPECULAR_STRENGTH="specularStrength",gb.SPECULAR_INTENSITY="specularIntensity",gb.SPECULAR_COLOR="specularColor",gb.REFLECTIVITY="reflectivity",gb.ROUGHNESS="roughness",gb.METALNESS="metalness",gb.NORMAL="normal",gb.CLEARCOAT="clearcoat",gb.CLEARCOAT_ROUGHNESS="clearcoatRoughness",gb.CLEARCOAT_NORMAL="clearcoatNormal",gb.EMISSIVE="emissive",gb.ROTATION="rotation",gb.SHEEN="sheen",gb.SHEEN_ROUGHNESS="sheenRoughness",gb.ANISOTROPY="anisotropy",gb.IRIDESCENCE="iridescence",gb.IRIDESCENCE_IOR="iridescenceIOR",gb.IRIDESCENCE_THICKNESS="iridescenceThickness",gb.IOR="ior",gb.TRANSMISSION="transmission",gb.THICKNESS="thickness",gb.ATTENUATION_DISTANCE="attenuationDistance",gb.ATTENUATION_COLOR="attenuationColor",gb.LINE_SCALE="scale",gb.LINE_DASH_SIZE="dashSize",gb.LINE_GAP_SIZE="gapSize",gb.LINE_WIDTH="linewidth",gb.LINE_DASH_OFFSET="dashOffset",gb.POINT_WIDTH="pointWidth",gb.DISPERSION="dispersion",gb.LIGHT_MAP="light",gb.AO_MAP="ao";const fb=Np(gb,gb.ALPHA_TEST),yb=Np(gb,gb.COLOR),xb=Np(gb,gb.SHININESS),bb=Np(gb,gb.EMISSIVE),vb=Np(gb,gb.OPACITY),Tb=Np(gb,gb.SPECULAR),_b=Np(gb,gb.SPECULAR_INTENSITY),wb=Np(gb,gb.SPECULAR_COLOR),Sb=Np(gb,gb.SPECULAR_STRENGTH),Mb=Np(gb,gb.REFLECTIVITY),Ab=Np(gb,gb.ROUGHNESS),Nb=Np(gb,gb.METALNESS),Cb=Np(gb,gb.NORMAL).context({getUV:null}),Rb=Np(gb,gb.CLEARCOAT),Eb=Np(gb,gb.CLEARCOAT_ROUGHNESS),Bb=Np(gb,gb.CLEARCOAT_NORMAL).context({getUV:null}),Ib=Np(gb,gb.ROTATION),Pb=Np(gb,gb.SHEEN),Fb=Np(gb,gb.SHEEN_ROUGHNESS),Ub=Np(gb,gb.ANISOTROPY),Ob=Np(gb,gb.IRIDESCENCE),zb=Np(gb,gb.IRIDESCENCE_IOR),Lb=Np(gb,gb.IRIDESCENCE_THICKNESS),Vb=Np(gb,gb.TRANSMISSION),Db=Np(gb,gb.THICKNESS),kb=Np(gb,gb.IOR),Gb=Np(gb,gb.ATTENUATION_DISTANCE),Wb=Np(gb,gb.ATTENUATION_COLOR),jb=Np(gb,gb.LINE_SCALE),Hb=Np(gb,gb.LINE_DASH_SIZE),qb=Np(gb,gb.LINE_GAP_SIZE),$b=Np(gb,gb.LINE_WIDTH),Xb=Np(gb,gb.LINE_DASH_OFFSET),Yb=Np(gb,gb.POINT_WIDTH),Zb=Np(gb,gb.DISPERSION),Jb=Np(gb,gb.LIGHT_MAP),Kb=Np(gb,gb.AO_MAP),Qb=dm(new Ys).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))}));class ev extends Dd{static get type(){return"ModelViewProjectionNode"}constructor(e=null){super("vec4"),this.positionNode=e}setup(e){if("fragment"===e.shaderStage)return Vf(e.context.mvp);const t=this.positionNode||ox,s=e.renderer.nodes.modelViewMatrix||sx;return Oy.mul(s).mul(t)}}const tv=Ap(ev);class sv extends zd{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isInstanceIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i,r;if(s===sv.VERTEX)i=e.getVertexIndex();else if(s===sv.INSTANCE)i=e.getInstanceIndex();else if(s===sv.DRAW)i=e.getDrawIndex();else if(s===sv.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===sv.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==sv.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Vf(this).build(e,t)}return r}}sv.VERTEX="vertex",sv.INSTANCE="instance",sv.SUBGROUP="subgroup",sv.INVOCATION_LOCAL="invocationLocal",sv.INVOCATION_SUBGROUP="invocationSubgroup",sv.DRAW="draw";const iv=Np(sv,sv.VERTEX),rv=Np(sv,sv.INSTANCE),nv=Np(sv,sv.SUBGROUP),ov=Np(sv,sv.INVOCATION_SUBGROUP),av=Np(sv,sv.INVOCATION_LOCAL),hv=Np(sv,sv.DRAW);class uv extends zd{static get type(){return"InstanceNode"}constructor(e){super("void"),this.instanceMesh=e,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Ed.FRAME,this.buffer=null,this.bufferColor=null}setup(e){let t=this.instanceMatrixNode,s=this.instanceColorNode;const i=this.instanceMesh;if(null===t){const e=i.instanceMatrix;if(i.count<=1e3)t=Px(e.array,"mat4",Math.max(i.count,1)).element(rv);else{const s=new _c(e.array,16,1);this.buffer=s;const i=e.usage===Ms?oy:ny,r=[i(s,"vec4",16,0),i(s,"vec4",16,4),i(s,"vec4",16,8),i(s,"vec4",16,12)];t=Qp(...r)}this.instanceMatrixNode=t}const r=i.instanceColor;if(r&&null===s){const e=new zo(r.array,3),t=r.usage===Ms?oy:ny;this.bufferColor=e,s=Wp(t(e,"vec3",3,0)),this.instanceColorNode=s}const n=t.mul(ox).xyz;if(ox.assign(n),e.hasGeometryAttribute("normal")){const e=wx(fx,t);fx.assign(e)}null!==this.instanceColorNode&&gm("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMesh.instanceMatrix.usage!==Ms&&null!=this.buffer&&this.instanceMesh.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMesh.instanceMatrix.version),this.instanceMesh.instanceColor&&this.instanceMesh.instanceColor.usage!==Ms&&null!=this.bufferColor&&this.instanceMesh.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceMesh.instanceColor.version)}}const lv=Ap(uv);class cv extends zd{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=rv:this.batchingIdNode=hv);const t=Cp((([e])=>{const t=Ny(Iy(this.batchMesh._indirectTexture),0),s=Op(e).modInt(Op(t)),i=Op(e).div(Op(t));return Iy(this.batchMesh._indirectTexture,Dp(s,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(Op(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=Ny(Iy(i),0),n=Up(s).mul(4).toInt().toVar(),o=n.modInt(r),a=n.div(Op(r)),h=Qp(Iy(i,Dp(o,a)),Iy(i,Dp(o.add(1),a)),Iy(i,Dp(o.add(2),a)),Iy(i,Dp(o.add(3),a))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Cp((([e])=>{const t=Ny(Iy(u),0).x,s=e,i=s.modInt(t),r=s.div(t);return Iy(u,Dp(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);gm("vec3","vBatchColor").assign(t)}const l=Kp(h);ox.assign(h.mul(ox));const c=fx.div(Wp(l[0].dot(l[0]),l[1].dot(l[1]),l[2].dot(l[2]))),d=l.mul(c).xyz;fx.assign(d),e.hasGeometryAttribute("tangent")&&Hx.mulAssign(l)}}const dv=Ap(cv),pv=new WeakMap;class mv extends zd{static get type(){return"SkinningNode"}constructor(e,t=!1){let s,i,r;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=Ed.OBJECT,this.skinIndexNode=Sy("skinIndex","uvec4"),this.skinWeightNode=Sy("skinWeight","vec4"),t?(s=Dx("bindMatrix","mat4"),i=Dx("bindMatrixInverse","mat4"),r=kx("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(s=dm(e.bindMatrix,"mat4"),i=dm(e.bindMatrixInverse,"mat4"),r=Px(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=s,this.bindMatrixInverseNode=i,this.boneMatricesNode=r,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=ox){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),u=e.element(s.w),l=r.mul(t),c=Ym(o.mul(i.x).mul(l),a.mul(i.y).mul(l),h.mul(i.z).mul(l),u.mul(i.w).mul(l));return n.mul(c).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=fx){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),u=e.element(s.w);let l=Ym(i.x.mul(o),i.y.mul(a),i.z.mul(h),i.w.mul(u));return l=n.mul(l).mul(r),l.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=kx("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,ax)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")}setup(e){this.needsPreviousBoneMatrices(e)&&ax.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(ox.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();fx.assign(t),e.hasGeometryAttribute("tangent")&&Hx.assign(t)}}generate(e,t){if("void"!==t)return ox.build(e,t)}update(e){const t=(this.useReference?e.object:this.skinnedMesh).skeleton;pv.get(t)!==e.frameId&&(pv.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const gv=e=>wp(new mv(e)),fv=e=>wp(new mv(e,!0));class yv extends zd{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt()+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;eNumber(n)?">=":"<"));const l={start:r,end:n,condition:h},c=l.start,d=l.end;let p="",m="",g="";u||(u="int"===a||"uint"===a?h.includes("<")?"++":"--":h.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(a,o)+" = "+c,m+=o+" "+h+" "+d,g+=o+" "+u;const f=`for ( ${p}; ${m}; ${g} )`;e.addFlowCode((0===t?"\n":"")+e.tab+f+" {\n\n").addFlowTab()}const r=i.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,s=this.params.length-1;twp(new yv(Mp(e,"int"))).append(),bv=()=>yy("continue").append(),vv=()=>yy("break").append(),Tv=(...e)=>(console.warn("TSL.LoopNode: loop() has been renamed to Loop()."),xv(...e)),_v=new WeakMap,wv=new xi,Sv=Cp((({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=Op(iv).mul(s).add(n),a=o.div(i),h=o.sub(a.mul(i));return Iy(e,Dp(h,a)).depth(r).mul(t)}));class Mv extends zd{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=dm(1),this.updateType=Ed.OBJECT}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,n=void 0!==r?r.length:0,{texture:o,stride:a,size:h}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,n=void 0!==r?r.length:0;let o=_v.get(e);if(void 0===o||o.count!==n){void 0!==o&&o.texture.dispose();const a=e.morphAttributes.position||[],h=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let l=0;!0===t&&(l=1),!0===s&&(l=2),!0===i&&(l=3);let c=e.attributes.position.count*l,d=1;const p=4096;c>p&&(d=Math.ceil(c/p),c=p);const m=new Float32Array(c*d*4*n),g=new Ti(m,c,d,n);g.type=Ie,g.needsUpdate=!0;const f=4*l;for(let x=0;x{const t=Up(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Iy(this.mesh.morphTexture,Dp(Op(e).add(1),Op(rv))).r):t.assign(Dx("morphTargetInfluences","float").element(e).toVar()),!0===s&&ox.addAssign(Sv({bufferMap:o,influence:t,stride:a,width:u,depth:e,offset:Op(0)})),!0===i&&fx.addAssign(Sv({bufferMap:o,influence:t,stride:a,width:u,depth:e,offset:Op(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 Av=Ap(Mv);class Nv extends zd{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}generate(){console.warn("Abstract function.")}}class Cv extends Nv{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Rv extends If{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:Wp().toVar("directDiffuse"),directSpecular:Wp().toVar("directSpecular"),indirectDiffuse:Wp().toVar("indirectDiffuse"),indirectSpecular:Wp().toVar("indirectSpecular")};return{radiance:Wp().toVar("radiance"),irradiance:Wp().toVar("irradiance"),iblIrradiance:Wp().toVar("iblIrradiance"),ambientOcclusion:Up(1).toVar("ambientOcclusion"),reflectedLight:s,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 Ev=Ap(Rv);class Bv extends Nv{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Iv,Pv;class Fv extends zd{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Fv.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Ed.NONE;return this.scope!==Fv.SIZE&&this.scope!==Fv.VIEWPORT||(e=Ed.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Fv.VIEWPORT?null!==t?Pv.copy(t.viewport):(e.getViewport(Pv),Pv.multiplyScalar(e.getPixelRatio())):null!==t?(Iv.width=t.width,Iv.height=t.height):e.getDrawingBufferSize(Iv)}setup(){const e=this.scope;let t=null;return t=e===Fv.SIZE?dm(Iv||(Iv=new Ys)):e===Fv.VIEWPORT?dm(Pv||(Pv=new xi)):Vp(zv.div(Ov)),t}generate(e){if(this.scope===Fv.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Ov).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Fv.COORDINATE="coordinate",Fv.VIEWPORT="viewport",Fv.SIZE="size",Fv.UV="uv";const Uv=Np(Fv,Fv.UV),Ov=Np(Fv,Fv.SIZE),zv=Np(Fv,Fv.COORDINATE),Lv=Np(Fv,Fv.VIEWPORT),Vv=Lv.zw,Dv=zv.sub(Lv.xy),kv=Dv.div(Vv),Gv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.'),Ov)),"vec2").once()(),Wv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.'),Uv)),"vec2").once()(),jv=Cp((()=>(console.warn('TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.'),Uv.flipY())),"vec2").once()(),Hv=new Ys;class qv extends Ey{static get type(){return"ViewportTextureNode"}constructor(e=Uv,t=null,s=null){null===s&&((s=new Wa).minFilter=Se),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Ed.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Hv);const s=this.value;s.image.width===Hv.width&&s.image.height===Hv.height||(s.image.width=Hv.width,s.image.height=Hv.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 $v=Ap(qv),Xv=Ap(qv,null,null,{generateMipmaps:!0});let Yv=null;class Zv extends qv{static get type(){return"ViewportDepthTextureNode"}constructor(e=Uv,t=null){null===Yv&&(Yv=new Xa),super(e,t,Yv)}}const Jv=Ap(Zv);class Kv extends zd{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===Kv.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===Kv.DEPTH_BASE)null!==s&&(i=rT().assign(s));else if(t===Kv.DEPTH)i=e.isPerspectiveCamera?tT(lx.z,Fy,Uy):Qv(lx.z,Fy,Uy);else if(t===Kv.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=sT(s,Fy,Uy);i=Qv(e,Fy,Uy)}else i=s;else i=Qv(lx.z,Fy,Uy);return i}}Kv.DEPTH_BASE="depthBase",Kv.DEPTH="depth",Kv.LINEAR_DEPTH="linearDepth";const Qv=(e,t,s)=>e.add(t).div(t.sub(s)),eT=(e,t,s)=>t.sub(s).mul(e).sub(t),tT=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),sT=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),iT=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Eg(e.div(t).add(1)),r=Eg(s.div(t).add(1));return i.div(r)},rT=Ap(Kv,Kv.DEPTH_BASE),nT=Np(Kv,Kv.DEPTH),oT=Ap(Kv,Kv.LINEAR_DEPTH),aT=oT(Jv());nT.assign=e=>rT(e);class hT extends zd{static get type(){return"ClippingNode"}constructor(e=hT.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{localClipIntersection:s,localClippingCount:i,globalClippingCount:r}=t,n=r+i,o=s?n-i:n;return this.scope===hT.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(t.planes,n,o):this.setupDefault(t.planes,n,o)}setupAlphaToCoverage(e,t,s){return Cp((()=>{const i=Ox(e),r=mm("float","distanceToPlane"),n=mm("float","distanceToGradient"),o=mm("float","clipOpacity");let a;if(o.assign(1),xv(s,(({i:e})=>{a=i.element(e),r.assign(lx.dot(a.xyz).negate().add(a.w)),n.assign(r.fwidth().div(2)),o.mulAssign(Sf(n.negate(),n,r)),o.equal(0).discard()})),s{a=i.element(t),r.assign(lx.dot(a.xyz).negate().add(a.w)),n.assign(r.fwidth().div(2)),e.mulAssign(Sf(n.negate(),n,r).oneMinus())})),o.mulAssign(e.oneMinus())}fm.a.mulAssign(o),fm.a.equal(0).discard()}))()}setupDefault(e,t,s){return Cp((()=>{const i=Ox(e);let r;if(xv(s,(({i:e})=>{r=i.element(e),lx.dot(r.xyz).greaterThan(r.w).discard()})),s{r=i.element(t),e.assign(lx.dot(r.xyz).greaterThan(r.w).and(e))})),e.discard()}}))()}}hT.ALPHA_TO_COVERAGE="alphaToCoverage",hT.DEFAULT="default";class uT extends Jr{static get type(){return"NodeMaterial"}constructor(){super(),this.isNodeMaterial=!0,this.type=this.constructor.type,this.forceSinglePass=!1,this.fog=!0,this.lights=!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.positionNode=null,this.geometryNode=null,this.depthNode=null,this.shadowNode=null,this.shadowPositionNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+_d(this)}build(e){this.setup(e)}setupObserver(e){return new yd(e)}setup(e){let t;e.context.setupNormal=()=>this.setupNormal(e),e.addStack(),e.stack.outputNode=this.vertexNode||this.setupPosition(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const s=this.setupClipping(e);if(!0===this.depthWrite&&this.setupDepth(e),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==s&&e.stack.add(s);const r=$p(i,fm.a).max(0);t=this.setupOutput(e,r),Fm.assign(t),null!==this.outputNode&&(t=this.outputNode);if(null!==e.renderer.getRenderTarget()){const s=e.renderer.getMRT(),i=this.mrtNode;null!==s?(t=s,null!==i&&(t=s.merge(i))):null!==i&&(t=i)}}else{let s=this.fragmentNode;!0!==s.isOutputStructNode&&(s=$p(s)),t=this.setupOutput(e,s)}e.stack.outputNode=t,e.addFlow("fragment",e.removeStack()),e.monitor=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{globalClippingCount:t,localClippingCount:s}=e.clippingContext;let i=null;if(t||s){const t=e.renderer.samples;this.alphaToCoverage&&t>1?i=wp(new hT(hT.ALPHA_TO_COVERAGE)):e.stack.add(wp(new hT))}return i}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=s.isPerspectiveCamera?iT(tv().w,Fy,Uy):Qv(lx.z,Fy,Uy))}null!==i&&nT.assign(i).append()}setupPosition(e){const{object:t}=e,s=t.geometry;if(e.addStack(),(s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Av(t).append(),!0===t.isSkinnedMesh&&fv(t).append(),this.displacementMap){const e=Wx("displacementMap","texture"),t=Wx("displacementScale","float"),s=Wx("displacementBias","float");ox.addAssign(fx.normalize().mul(e.x.mul(t).add(s)))}t.isBatchedMesh&&dv(t).append(),t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&lv(t).append(),null!==this.positionNode&&ox.assign(this.positionNode);const i=tv();return e.context.vertex=e.removeStack(),e.context.mvp=i,i}setupDiffuseColor({object:e,geometry:t}){let s=this.colorNode?$p(this.colorNode):yb;if(!0===this.vertexColors&&t.hasAttribute("color")&&(s=$p(s.xyz.mul(Sy("color","vec3")),s.a)),e.instanceColor){s=gm("vec3","vInstanceColor").mul(s)}if(e.isBatchedMesh&&e._colorsTexture){s=gm("vec3","vBatchColor").mul(s)}fm.assign(s);const i=this.opacityNode?Up(this.opacityNode):vb;if(fm.a.assign(fm.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?Up(this.alphaTestNode):fb;fm.a.lessThanEqual(e).discard()}!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&fm.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Wp(0):fm.rgb}setupNormal(){return this.normalNode?Wp(this.normalNode):Cb}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Wx("envMap","cubeTexture"):Wx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Bv(Jb)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Kb;t.push(new Cv(e))}let r=this.lightsNode||e.lightsNode;return t.length>0&&(r=e.renderer.lighting.createNode([...r.getLights(),...t])),r}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:r}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let o=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e);o=Ev(n,t,s,i)}else null!==s&&(o=Wp(null!==i?vf(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(ym.assign(Wp(r||bb)),o=o.add(ym)),o}setupOutput(e,t){if(!0===this.fog){const s=e.fogNode;s&&(t=$p(s.mix(t.rgb,s.colorNode),t.a))}return t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.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 s=Jr.prototype.toJSON.call(this,e),i=wd(this);s.inputNodes={};for(const{property:t,childNode:r}of i)s.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),n=r(e.nodes);t.length>0&&(s.textures=t),i.length>0&&(s.images=i),n.length>0&&(s.nodes=n)}return s}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.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.shadowNode=e.shadowNode,this.shadowPositionNode=e.shadowPositionNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const lT=new Fa;class cT extends uT{static get type(){return"InstancedPointsNodeMaterial"}constructor(e={}){super(),this.lights=!1,this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.pointWidth=1,this.pointColorNode=null,this.pointWidthNode=null,this.setDefaultValues(lT),this.setValues(e)}setup(e){this.setupShaders(e),super.setup(e)}setupShaders({renderer:e}){const t=this.alphaToCoverage,s=this.useColor;this.vertexNode=Cp((()=>{const e=Sy("instancePosition").xyz,t=$p(sx.mul($p(e,1))),s=Lv.z.div(Lv.w),i=Oy.mul(t),r=nx.xy.toVar();return r.mulAssign(this.pointWidthNode?this.pointWidthNode:Yb),r.assign(r.div(Lv.z)),r.y.assign(r.y.mul(s)),r.assign(r.mul(i.w)),i.addAssign($p(r,0,0)),i}))(),this.fragmentNode=Cp((()=>{const i=Up(1).toVar(),r=bf(My().mul(2).sub(1));if(t&&e.samples>1){const e=Up(r.fwidth()).toVar();i.assign(Sf(e.oneMinus(),e.add(1),r).oneMinus())}else r.greaterThan(1).discard();let n;if(this.pointColorNode)n=this.pointColorNode;else if(s){n=Sy("instanceColor").mul(yb)}else n=yb;return i.mulAssign(vb),$p(n,i)}))()}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.needsUpdate=!0)}}const dT=new va;class pT extends uT{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.lights=!1,this.setDefaultValues(dT),this.setValues(e)}}const mT=new Eu;class gT extends uT{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.lights=!1,this.setDefaultValues(mT),this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode,t=this.dashScaleNode?Up(this.dashScaleNode):jb,s=this.dashSizeNode?Up(this.dashSizeNode):Hb,i=this.dashSizeNode?Up(this.dashGapNode):qb;Um.assign(s),Om.assign(i);const r=Vf(Sy("lineDistance").mul(t));(e?r.add(e):r).mod(Um.add(Om)).greaterThan(Um).discard()}}const fT=new Eu;class yT extends uT{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.lights=!1,this.setDefaultValues(fT),this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.useDash=e.dashed,this.useWorldUnits=!1,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setup(e){this.setupShaders(e),super.setup(e)}setupShaders({renderer:e}){const t=this.alphaToCoverage,s=this.useColor,i=this.dashed,r=this.worldUnits,n=Cp((({start:e,end:t})=>{const s=Oy.element(2).element(2),i=Oy.element(3).element(2).mul(-.5).div(s).sub(e.z).div(t.z.sub(e.z));return $p(vf(e.xyz,t.xyz,i),t.w)})).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=Cp((()=>{const e=Sy("instanceStart"),t=Sy("instanceEnd"),s=$p(sx.mul($p(e,1))).toVar("start"),o=$p(sx.mul($p(t,1))).toVar("end");r&&(gm("vec3","worldStart").assign(s.xyz),gm("vec3","worldEnd").assign(o.xyz));const a=Lv.z.div(Lv.w),h=Oy.element(2).element(3).equal(-1);Ip(h,(()=>{Ip(s.z.lessThan(0).and(o.z.greaterThan(0)),(()=>{o.assign(n({start:s,end:o}))})).ElseIf(o.z.lessThan(0).and(s.z.greaterThanEqual(0)),(()=>{s.assign(n({start:o,end:s}))}))}));const u=Oy.mul(s),l=Oy.mul(o),c=u.xyz.div(u.w),d=l.xyz.div(l.w),p=d.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(a)),p.assign(p.normalize());const m=$p().toVar();if(r){const e=o.xyz.sub(s.xyz).normalize(),t=vf(s.xyz,o.xyz,.5).normalize(),r=e.cross(t).normalize(),n=e.cross(r),a=gm("vec4","worldPos");a.assign(nx.y.lessThan(.5).select(s,o));const h=$b.mul(.5);a.addAssign($p(nx.x.lessThan(0).select(r.mul(h),r.mul(h).negate()),0)),i||(a.addAssign($p(nx.y.lessThan(.5).select(e.mul(h).negate(),e.mul(h)),0)),a.addAssign($p(n.mul(h),0)),Ip(nx.y.greaterThan(1).or(nx.y.lessThan(0)),(()=>{a.subAssign($p(n.mul(2).mul(h),0))}))),m.assign(Oy.mul(a));const u=Wp().toVar();u.assign(nx.y.lessThan(.5).select(c,d)),m.z.assign(u.z.mul(m.w))}else{const e=Vp(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(a)),e.x.assign(e.x.div(a)),e.assign(nx.x.lessThan(0).select(e.negate(),e)),Ip(nx.y.lessThan(0),(()=>{e.assign(e.sub(p))})).ElseIf(nx.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul($b)),e.assign(e.div(Lv.w)),m.assign(nx.y.lessThan(.5).select(u,l)),e.assign(e.mul(m.w)),m.assign(m.add($p(e,0,0)))}return m}))();const o=Cp((({p1:e,p2:t,p3:s,p4:i})=>{const r=e.sub(s),n=i.sub(s),o=t.sub(e),a=r.dot(n),h=n.dot(o),u=r.dot(o),l=n.dot(n),c=o.dot(o).mul(l).sub(h.mul(h)),d=a.mul(h).sub(u.mul(l)).div(c).clamp(),p=a.add(h.mul(d)).div(l).clamp();return Vp(d,p)}));this.fragmentNode=Cp((()=>{const n=My();if(i){const e=this.offsetNode?Up(this.offsetNodeNode):Xb,t=this.dashScaleNode?Up(this.dashScaleNode):jb,s=this.dashSizeNode?Up(this.dashSizeNode):Hb,i=this.dashSizeNode?Up(this.dashGapNode):qb;Um.assign(s),Om.assign(i);const r=Sy("instanceDistanceStart"),o=Sy("instanceDistanceEnd"),a=nx.y.lessThan(.5).select(t.mul(r),jb.mul(o)),h=Vf(a.add(Xb)),u=e?h.add(e):h;n.y.lessThan(-1).or(n.y.greaterThan(1)).discard(),u.mod(Um.add(Om)).greaterThan(Um).discard()}const a=Up(1).toVar("alpha");if(r){const s=gm("vec3","worldStart"),r=gm("vec3","worldEnd"),n=gm("vec4","worldPos").xyz.normalize().mul(1e5),h=r.sub(s),u=o({p1:s,p2:r,p3:Wp(0,0,0),p4:n}),l=s.add(h.mul(u.x)),c=n.mul(u.y),d=l.sub(c).length().div($b);if(!i)if(t&&e.samples>1){const e=d.fwidth();a.assign(Sf(e.negate().add(.5),e.add(.5),d).oneMinus())}else d.greaterThan(.5).discard()}else if(t&&e.samples>1){const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1)),s=e.mul(e).add(t.mul(t)),i=Up(s.fwidth()).toVar("dlen");Ip(n.y.abs().greaterThan(1),(()=>{a.assign(Sf(i.oneMinus(),i.add(1),s).oneMinus())}))}else Ip(n.y.abs().greaterThan(1),(()=>{const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()}));let h;if(this.lineColorNode)h=this.lineColorNode;else if(s){const e=Sy("instanceColorStart"),t=Sy("instanceColorEnd");h=nx.y.lessThan(.5).select(e,t).mul(yb)}else h=yb;return $p(h,a)}))()}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 xT=e=>wp(e).mul(.5).add(.5),bT=e=>wp(e).mul(2).sub(1),vT=new Mu;class TT extends uT{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(vT),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Up(this.opacityNode):vb;fm.assign($p(xT(vx),e))}}class _T extends Dd{static get type(){return"EquirectUVNode"}constructor(e=ux){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan2(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Vp(t,s)}}const wT=Ap(_T);class ST extends Yn{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=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 r=new Ln(5,5,5),n=wT(ux),o=new uT;o.colorNode=By(t,n,0),o.side=d,o.blending=m;const a=new On(r,o),h=new Kn;h.add(a),t.minFilter===Se&&(t.minFilter=Te);const u=new $n(1,10,this),l=e.getMRT();return e.setMRT(null),u.update(e,h),e.setMRT(l),t.minFilter=s,t.currentGenerateMipmaps=i,a.geometry.dispose(),a.material.dispose(),this}}const MT=new WeakMap;class AT extends Dd{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Bx();const t=new Xn;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Ed.RENDER}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:s[i.property];if(e&&e.isTexture){const s=e.mapping;if(s===le||s===ce){if(MT.has(e)){const t=MT.get(e);CT(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new ST(s.height);i.fromEquirectangularTexture(t,e),CT(i.texture,e.mapping),this._cubeTexture=i.texture,MT.set(e,i.texture),e.addEventListener("dispose",NT)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function NT(e){const t=e.target;t.removeEventListener("dispose",NT);const s=MT.get(t);void 0!==s&&(MT.delete(t),s.dispose())}function CT(e,t){t===le?e.mapping=he:t===ce&&(e.mapping=ue)}const RT=Ap(AT);class ET extends Nv{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=RT(this.envNode)}}class BT extends Nv{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Up(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class IT{start(){}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class PT extends IT{constructor(){super()}indirect(e,t,s){const i=e.ambientOcclusion,r=e.reflectedLight,n=s.context.irradianceLightMap;r.indirectDiffuse.assign($p(0)),n?r.indirectDiffuse.addAssign(n):r.indirectDiffuse.addAssign($p(1,1,1,0)),r.indirectDiffuse.mulAssign(i),r.indirectDiffuse.mulAssign(fm.rgb)}finish(e,t,s){const i=s.material,r=e.outgoingLight,n=s.context.environment;if(n)switch(i.combine){case 0:r.rgb.assign(vf(r.rgb,r.rgb.mul(n.rgb),Sb.mul(Mb)));break;case 1:r.rgb.assign(vf(r.rgb,n.rgb,Sb.mul(Mb)));break;case 2:r.rgb.addAssign(n.rgb.mul(Sb.mul(Mb)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",i.combine)}}}const FT=new Kr;class UT extends uT{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(FT),this.setValues(e)}setupNormal(){return xx}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new ET(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new BT(Jb)),t}setupOutgoingLight(){return fm.rgb}setupLightingModel(){return new PT}}const OT=Cp((({f0:e,f90:t,dotVH:s})=>{const i=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(i.oneMinus()).add(t.mul(i))})),zT=Cp((e=>e.diffuseColor.mul(1/Math.PI))),LT=Cp((({dotNH:e})=>Pm.mul(Up(.5)).add(1).mul(Up(1/Math.PI)).mul(e.pow(Pm)))),VT=Cp((({lightDirection:e})=>{const t=e.add(cx).normalize(),s=vx.dot(t).clamp(),i=cx.dot(t).clamp(),r=OT({f0:Bm,f90:1,dotVH:i}),n=Up(.25),o=LT({dotNH:s});return r.mul(n).mul(o)}));class DT extends PT{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=vx.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(zT({diffuseColor:fm.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(VT({lightDirection:e})).mul(Sb))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(zT({diffuseColor:fm}))),s.indirectDiffuse.mulAssign(e)}}const kT=new Au;class GT extends uT{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(kT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new ET(t):null}setupLightingModel(){return new DT(!1)}}const WT=new wu;class jT extends uT{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(WT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new ET(t):null}setupLightingModel(){return new DT}setupVariants(){const e=(this.shininessNode?Up(this.shininessNode):xb).max(1e-4);Pm.assign(e);const t=this.specularNode||Tb;Bm.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const HT=Cp((e=>{if(!1===e.geometry.hasAttribute("normal"))return Up(0);const t=xx.dFdx().abs().max(xx.dFdy().abs());return t.x.max(t.y).max(t.z)})),qT=Cp((e=>{const{roughness:t}=e,s=HT();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i})),$T=Cp((({alpha:e,dotNL:t,dotNV:s})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt()),n=s.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return Km(.5,r.add(n).max(xg))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),XT=Cp((({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const h=a.mul(Wp(e.mul(s),t.mul(i),o).length()),u=o.mul(Wp(e.mul(r),t.mul(n),a).length());return Km(.5,h.add(u)).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"}]}),YT=Cp((({alpha:e,dotNH:t})=>{const s=e.pow2(),i=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(i.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),ZT=Up(1/Math.PI),JT=Cp((({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=Wp(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),h=n.div(a);return ZT.mul(n.mul(h.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"}]}),KT=Cp((e=>{const{lightDirection:t,f0:s,f90:i,roughness:r,f:n,USE_IRIDESCENCE:o,USE_ANISOTROPY:a}=e,h=e.normalView||vx,u=r.pow2(),l=t.add(cx).normalize(),c=h.dot(t).clamp(),d=h.dot(cx).clamp(),p=h.dot(l).clamp(),m=cx.dot(l).clamp();let g,f,y=OT({f0:s,f90:i,dotVH:m});if(vp(o)&&(y=Sm.mix(y,n)),vp(a)){const e=Rm.dot(t),s=Rm.dot(cx),i=Rm.dot(l),r=Em.dot(t),n=Em.dot(cx),o=Em.dot(l);g=XT({alphaT:Nm,alphaB:u,dotTV:s,dotBV:n,dotTL:e,dotBL:r,dotNV:d,dotNL:c}),f=JT({alphaT:Nm,alphaB:u,dotNH:p,dotTH:i,dotBH:o})}else g=$T({alpha:u,dotNL:c,dotNV:d}),f=YT({alpha:u,dotNH:p});return y.mul(g).mul(f)})),QT=Cp((({roughness:e,dotNV:t})=>{const s=$p(-1,-.0275,-.572,.022),i=$p(1,.0425,1.04,-.04),r=e.mul(s).add(i),n=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return Vp(-1.04,1.04).mul(n).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),e_=Cp((e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=QT({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))})),t_=Cp((({f:e,f90:t,dotVH:s})=>{const i=s.oneMinus().saturate(),r=i.mul(i),n=i.mul(r,r).clamp(0,.9999);return e.sub(Wp(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"}]}),s_=Cp((({roughness:e,dotNH:t})=>{const s=e.pow2(),i=Up(1).div(s),r=t.pow2().oneMinus().max(.0078125);return Up(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),i_=Cp((({dotNV:e,dotNL:t})=>Up(1).div(Up(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),r_=Cp((({lightDirection:e})=>{const t=e.add(cx).normalize(),s=vx.dot(e).clamp(),i=vx.dot(cx).clamp(),r=vx.dot(t).clamp(),n=s_({roughness:wm,dotNH:r}),o=i_({dotNV:i,dotNL:s});return _m.mul(n).mul(o)})),n_=Cp((({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=Vp(s,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r})).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),o_=Cp((({f:e})=>{const t=e.length();return nf(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),a_=Cp((({v1:e,v2:t})=>{const s=e.dot(t),i=s.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),n=i.add(4.1616724).mul(i).add(3.417594).toVar(),o=r.div(n),a=s.greaterThan(0).select(o,nf(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return e.cross(t).mul(a)})).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),h_=Cp((({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:o,p3:a})=>{const h=n.sub(r).toVar(),u=a.sub(r).toVar(),l=h.cross(u),c=Wp().toVar();return Ip(l.dot(s.sub(r)).greaterThanEqual(0),(()=>{const h=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(h).negate(),l=i.mul(Kp(h,u,e).transpose()).toVar(),d=l.mul(r.sub(s)).normalize().toVar(),p=l.mul(n.sub(s)).normalize().toVar(),m=l.mul(o.sub(s)).normalize().toVar(),g=l.mul(a.sub(s)).normalize().toVar(),f=Wp(0).toVar();f.addAssign(a_({v1:d,v2:p})),f.addAssign(a_({v1:p,v2:m})),f.addAssign(a_({v1:m,v2:g})),f.addAssign(a_({v1:g,v2:d})),c.assign(Wp(o_({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"}]}),u_=1/6,l_=e=>Jm(u_,Jm(e,Jm(e,e.negate().add(3)).sub(3)).add(1)),c_=e=>Jm(u_,Jm(e,Jm(e,Jm(3,e).sub(6))).add(4)),d_=e=>Jm(u_,Jm(e,Jm(e,Jm(-3,e).add(3)).add(3)).add(1)),p_=e=>Jm(u_,pf(e,3)),m_=e=>l_(e).add(c_(e)),g_=e=>d_(e).add(p_(e)),f_=e=>Ym(-1,c_(e).div(l_(e).add(c_(e)))),y_=e=>Ym(1,p_(e).div(d_(e).add(p_(e)))),x_=(e,t,s)=>{const i=e.uvNode,r=Jm(i,t.zw).add(.5),n=Pg(r),o=Og(r),a=m_(o.x),h=g_(o.x),u=f_(o.x),l=y_(o.x),c=f_(o.y),d=y_(o.y),p=Vp(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),m=Vp(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Vp(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),f=Vp(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),y=m_(o.y).mul(Ym(a.mul(e.uv(p).level(s)),h.mul(e.uv(m).level(s)))),x=g_(o.y).mul(Ym(a.mul(e.uv(g).level(s)),h.mul(e.uv(f).level(s))));return y.add(x)},b_=Cp((([e,t=Up(3)])=>{const s=Vp(e.size(Op(t))),i=Vp(e.size(Op(t.add(1)))),r=Km(1,s),n=Km(1,i),o=x_(e,$p(r,s),Pg(t)),a=x_(e,$p(n,i),Fg(t));return Og(t).mix(o,a)})),v_=Cp((([e,t,s,i,r])=>{const n=Wp(wf(t.negate(),Ug(e),Km(1,i))),o=Wp(Hg(r[0].xyz),Hg(r[1].xyz),Hg(r[2].xyz));return Ug(n).mul(s.mul(o))})).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"}]}),T_=Cp((([e,t])=>e.mul(Tf(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),__=Xv(),w_=Cp((([e,t,s])=>{const i=__.uv(e),r=Eg(Up(Ov.x)).mul(T_(t,s));return b_(i,r)})),S_=Cp((([e,t,s])=>(Ip(s.notEqual(0),(()=>{const i=Rg(t).negate().div(s);return Ng(i.negate().mul(e))})),Wp(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),M_=Cp((([e,t,s,i,r,n,o,a,h,u,l,c,d,p,m])=>{let g,f;if(m){g=$p().toVar(),f=Wp().toVar();const r=l.sub(1).mul(m.mul(.025)),n=Wp(l.sub(r),l,l.add(r));xv({start:0,end:3},(({i:r})=>{const l=n.element(r),m=v_(e,t,c,l,a),y=o.add(m),x=u.mul(h.mul($p(y,1))),b=Vp(x.xy.div(x.w)).toVar();b.addAssign(1),b.divAssign(2),b.assign(Vp(b.x,b.y.oneMinus()));const v=w_(b,s,l);g.element(r).assign(v.element(r)),g.a.addAssign(v.a),f.element(r).assign(i.element(r).mul(S_(Hg(m),d,p).element(r)))})),g.a.divAssign(3)}else{const r=v_(e,t,c,l,a),n=o.add(r),m=u.mul(h.mul($p(n,1))),y=Vp(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Vp(y.x,y.y.oneMinus())),g=w_(y,s,l),f=i.mul(S_(Hg(r),d,p))}const y=f.rgb.mul(g.rgb),x=e.dot(t).clamp(),b=Wp(e_({dotNV:x,specularColor:r,specularF90:n,roughness:s})),v=f.r.add(f.g,f.b).div(3);return $p(b.oneMinus().mul(y),g.a.oneMinus().mul(v).oneMinus())})),A_=Kp(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),N_=(e,t)=>e.sub(t).div(e.add(t)).pow2(),C_=(e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=Wp(54856e-17,44201e-17,52481e-17),r=Wp(1681e3,1795300,2208400),n=Wp(43278e5,93046e5,66121e5),o=Up(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let a=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());a=Wp(a.x.add(o),a.y,a.z).div(1.0685e-7);return A_.mul(a)},R_=Cp((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=vf(e,t,Sf(0,.03,i)),o=e.div(n).pow2().mul(Up(1).sub(s.pow2())),a=Up(1).sub(o).sqrt(),h=N_(n,e),u=OT({f0:h,f90:1,dotVH:s}),l=u.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=Up(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Wp(1).add(t).div(Wp(1).sub(t))})(r.clamp(0,.9999)),m=N_(p,n.toVec3()),g=OT({f0:m,f90:1,dotVH:a}),f=Wp(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(i,a,2),x=Wp(d).add(f),b=u.mul(g).clamp(1e-5,.9999),v=b.sqrt(),T=l.pow2().mul(g).div(Wp(1).sub(b));let _=u.add(T),w=T.sub(l);for(let e=1;e<=2;++e){w=w.mul(v);const t=C_(Up(e).mul(y),Up(e).mul(x)).mul(2);_=_.add(w.mul(t))}return _.max(Wp(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"}]}),E_=Cp((({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.pow2(),n=Ef(s.lessThan(.25),Up(-339.2).mul(r).add(Up(161.4).mul(s)).sub(25.9),Up(-8.48).mul(r).add(Up(14.3).mul(s)).sub(9.95)),o=Ef(s.lessThan(.25),Up(44).mul(r).sub(Up(23.7).mul(s)).add(3.26),Up(1.97).mul(r).sub(Up(3.27).mul(s)).add(.72));return Ef(s.lessThan(.25),0,Up(.1).mul(s).sub(.025)).add(n.mul(i).add(o).exp()).mul(1/Math.PI).saturate()})),B_=Wp(.04),I_=Up(1);class P_ extends IT{constructor(e=!1,t=!1,s=!1,i=!1,r=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=r,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=Wp().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Wp().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Wp().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Wp().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Wp().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=vx.dot(cx).clamp();this.iridescenceFresnel=R_({outsideIOR:Up(1),eta2:Mm,cosTheta1:e,thinFilmThickness:Am,baseF0:Bm}),this.iridescenceF0=t_({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=hx,s=ky.sub(hx).normalize(),i=Tx;e.backdrop=M_(i,s,xm,fm,Bm,Im,t,Zy,Ly,Oy,Lm,Dm,Gm,km,this.dispersion?Wm:null),e.backdropAlpha=Vm,fm.a.mulAssign(vf(1,e.backdrop.a,Vm))}}computeMultiscattering(e,t,s){const i=vx.dot(cx).clamp(),r=QT({roughness:xm,dotNV:i}),n=(this.iridescenceF0?Sm.mix(Bm,this.iridescenceF0):Bm).mul(r.x).add(s.mul(r.y)),o=r.x.add(r.y).oneMinus(),a=Bm.add(Bm.oneMinus().mul(.047619)),h=n.mul(a).div(o.mul(a).oneMinus());e.addAssign(n),t.addAssign(h.mul(o))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=vx.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(r_({lightDirection:e}))),!0===this.clearcoat){const s=_x.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(KT({lightDirection:e,f0:B_,f90:I_,roughness:Tm,normalView:_x})))}s.directDiffuse.addAssign(i.mul(zT({diffuseColor:fm.rgb}))),s.directSpecular.addAssign(i.mul(KT({lightDirection:e,f0:Bm,f90:1,roughness:xm,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:r,ltc_1:n,ltc_2:o}){const a=t.add(s).sub(i),h=t.sub(s).sub(i),u=t.sub(s).add(i),l=t.add(s).add(i),c=vx,d=cx,p=lx.toVar(),m=n_({N:c,V:d,roughness:xm}),g=n.uv(m).toVar(),f=o.uv(m).toVar(),y=Kp(Wp(g.x,0,g.y),Wp(0,1,0),Wp(g.z,0,g.w)).toVar(),x=Bm.mul(f.x).add(Bm.oneMinus().mul(f.y)).toVar();r.directSpecular.addAssign(e.mul(x).mul(h_({N:c,V:d,P:p,mInv:y,p0:a,p1:h,p2:u,p3:l}))),r.directDiffuse.addAssign(e.mul(fm).mul(h_({N:c,V:d,P:p,mInv:Kp(1,0,0,0,1,0,0,0,1),p0:a,p1:h,p2:u,p3:l})))}indirect(e,t,s){this.indirectDiffuse(e,t,s),this.indirectSpecular(e,t,s),this.ambientOcclusion(e,t,s)}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(zT({diffuseColor:fm})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:s}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(_m,E_({normal:vx,viewDir:cx,roughness:wm}))),!0===this.clearcoat){const e=_x.dot(cx).clamp(),t=e_({dotNV:e,specularColor:B_,specularF90:I_,roughness:Tm});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=Wp().toVar("singleScattering"),r=Wp().toVar("multiScattering"),n=t.mul(1/Math.PI);this.computeMultiscattering(i,r,Im);const o=i.add(r),a=fm.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(e.mul(i)),s.indirectSpecular.addAssign(r.mul(n)),s.indirectDiffuse.addAssign(a.mul(n))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const s=vx.dot(cx).clamp().add(e),i=xm.mul(-16).oneMinus().negate().exp2(),r=e.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(r)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=_x.dot(cx).clamp(),s=OT({dotVH:e,f0:B_,f90:I_}),i=t.mul(vm.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(vm));t.assign(i)}if(!0===this.sheen){const e=_m.r.max(_m.g).max(_m.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const F_=Up(1),U_=Up(-2),O_=Up(.8),z_=Up(-1),L_=Up(.4),V_=Up(2),D_=Up(.305),k_=Up(3),G_=Up(.21),W_=Up(4),j_=Up(4),H_=Up(16),q_=Cp((([e])=>{const t=Wp(Wg(e)).toVar(),s=Up(-1).toVar();return Ip(t.x.greaterThan(t.z),(()=>{Ip(t.x.greaterThan(t.y),(()=>{s.assign(Ef(e.x.greaterThan(0),0,3))})).Else((()=>{s.assign(Ef(e.y.greaterThan(0),1,4))}))})).Else((()=>{Ip(t.z.greaterThan(t.y),(()=>{s.assign(Ef(e.z.greaterThan(0),2,5))})).Else((()=>{s.assign(Ef(e.y.greaterThan(0),1,4))}))})),s})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),$_=Cp((([e,t])=>{const s=Vp().toVar();return Ip(t.equal(0),(()=>{s.assign(Vp(e.z,e.y).div(Wg(e.x)))})).ElseIf(t.equal(1),(()=>{s.assign(Vp(e.x.negate(),e.z.negate()).div(Wg(e.y)))})).ElseIf(t.equal(2),(()=>{s.assign(Vp(e.x.negate(),e.y).div(Wg(e.z)))})).ElseIf(t.equal(3),(()=>{s.assign(Vp(e.z.negate(),e.y).div(Wg(e.x)))})).ElseIf(t.equal(4),(()=>{s.assign(Vp(e.x.negate(),e.z).div(Wg(e.y)))})).Else((()=>{s.assign(Vp(e.x,e.y).div(Wg(e.z)))})),Jm(.5,s.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),X_=Cp((([e])=>{const t=Up(0).toVar();return Ip(e.greaterThanEqual(O_),(()=>{t.assign(F_.sub(e).mul(z_.sub(U_)).div(F_.sub(O_)).add(U_))})).ElseIf(e.greaterThanEqual(L_),(()=>{t.assign(O_.sub(e).mul(V_.sub(z_)).div(O_.sub(L_)).add(z_))})).ElseIf(e.greaterThanEqual(D_),(()=>{t.assign(L_.sub(e).mul(k_.sub(V_)).div(L_.sub(D_)).add(V_))})).ElseIf(e.greaterThanEqual(G_),(()=>{t.assign(D_.sub(e).mul(W_.sub(k_)).div(D_.sub(G_)).add(k_))})).Else((()=>{t.assign(Up(-2).mul(Eg(Jm(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Y_=Cp((([e,t])=>{const s=e.toVar();s.assign(Jm(2,s).sub(1));const i=Wp(s,1).toVar();return Ip(t.equal(0),(()=>{i.assign(i.zyx)})).ElseIf(t.equal(1),(()=>{i.assign(i.xzy),i.xz.mulAssign(-1)})).ElseIf(t.equal(2),(()=>{i.x.mulAssign(-1)})).ElseIf(t.equal(3),(()=>{i.assign(i.zyx),i.xz.mulAssign(-1)})).ElseIf(t.equal(4),(()=>{i.assign(i.xzy),i.xy.mulAssign(-1)})).ElseIf(t.equal(5),(()=>{i.z.mulAssign(-1)})),i})).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),Z_=Cp((([e,t,s,i,r,n])=>{const o=Up(s),a=Wp(t),h=Tf(X_(o),U_,n),u=Og(h),l=Pg(h),c=Wp(J_(e,a,l,i,r,n)).toVar();return Ip(u.notEqual(0),(()=>{const t=Wp(J_(e,a,l.add(1),i,r,n)).toVar();c.assign(vf(c,t,u))})),c})),J_=Cp((([e,t,s,i,r,n])=>{const o=Up(s).toVar(),a=Wp(t),h=Up(q_(a)).toVar(),u=Up(nf(j_.sub(o),0)).toVar();o.assign(nf(o,j_));const l=Up(Cg(o)).toVar(),c=Vp($_(a,h).mul(l.sub(2)).add(1)).toVar();return Ip(h.greaterThan(2),(()=>{c.y.addAssign(l),h.subAssign(3)})),c.x.addAssign(h.mul(l)),c.x.addAssign(u.mul(Jm(3,H_))),c.y.addAssign(Jm(4,Cg(n).sub(l))),c.x.mulAssign(i),c.y.mulAssign(r),e.uv(c).grad(Vp(),Vp())})),K_=Cp((({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const h=Lg(i),u=s.mul(h).add(r.cross(s).mul(zg(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return J_(e,u,t,n,o,a)})),Q_=Cp((({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:o,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})=>{const d=Wp(Ef(t,s,df(s,i))).toVar();Ip(_g(d.equals(Wp(0))),(()=>{d.assign(Wp(i.z,0,i.x.negate()))})),d.assign(Ug(d));const p=Wp().toVar();return p.addAssign(r.element(Op(0)).mul(K_({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),xv({start:Op(1),end:e},(({i:e})=>{Ip(e.greaterThanEqual(n),(()=>{vv()}));const t=Up(o.mul(Up(e))).toVar();p.addAssign(r.element(e).mul(K_({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(K_({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})))})),$p(p,1)}));let ew=null;const tw=new WeakMap;function sw(e){let t=tw.get(e);if((void 0!==t?t.pmremVersion:-1)!==e.pmremVersion){const s=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const s=6;for(let i=0;i0}(s))return null;t=ew.fromEquirectangular(e,t)}t.pmremVersion=e.pmremVersion,tw.set(e,t)}return t.texture}class iw extends Dd{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new yi;i.isRenderTargetTexture=!0,this._texture=By(i),this._width=dm(0),this._height=dm(0),this._maxMip=dm(0),this.updateBeforeType=Ed.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,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:s,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(){let e=this._pmrem;const t=e?e.pmremVersion:-1,s=this._value;t!==s.pmremVersion&&(e=!0===s.isPMREMTexture?s:sw(s),null!==e&&(this._pmrem=e,this.updateFromTexture(e)))}setup(e){null===ew&&(ew=e.createPMREMGenerator()),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this));const s=this.value;e.renderer.coordinateSystem===Us&&!0!==s.isPMREMTexture&&!0===s.isRenderTargetTexture&&(t=Wp(t.x.negate(),t.yz));let i=this.levelNode;return null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),Z_(this._texture,t,i,this._width,this._height,this._maxMip)}}const rw=Ap(iw),nw=new WeakMap;class ow extends Nv{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:t[s.property];let i=nw.get(e);void 0===i&&(i=rw(e),nw.set(e,i)),s=i}const i=t.envMap?Dx("envMapIntensity","float",e.material):Dx("environmentIntensity","float",e.scene),r=!0===t.useAnisotropy||t.anisotropy>0?ob:vx,n=s.context(aw(xm,r)).mul(i),o=s.context(hw(Tx)).mul(Math.PI).mul(i),a=ly(n),h=ly(o);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(h);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=s.context(aw(Tm,_x)).mul(i),t=ly(e);u.addAssign(t)}}}const aw=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=cx.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(Ly)),s),getTextureLevel:()=>e}},hw=e=>({getUV:()=>e,getTextureLevel:()=>Up(1)}),uw=new Tu;class lw extends uT{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(uw),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new ow(t):null}setupLightingModel(){return new P_}setupSpecular(){const e=vf(Wp(.04),fm.rgb,bm);Bm.assign(e),Im.assign(1)}setupVariants(){const e=this.metalnessNode?Up(this.metalnessNode):Nb;bm.assign(e);let t=this.roughnessNode?Up(this.roughnessNode):Ab;t=qT({roughness:t}),xm.assign(t),this.setupSpecular(),fm.assign($p(fm.rgb.mul(e.oneMinus()),fm.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const cw=new _u;class dw extends lw{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(cw),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?Up(this.iorNode):kb;Lm.assign(e),Bm.assign(vf(rf(mf(Lm.sub(1).div(Lm.add(1))).mul(wb),Wp(1)).mul(_b),fm.rgb,bm)),Im.assign(vf(_b,1,bm))}setupLightingModel(){return new P_(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Up(this.clearcoatNode):Rb,t=this.clearcoatRoughnessNode?Up(this.clearcoatRoughnessNode):Eb;vm.assign(e),Tm.assign(qT({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Wp(this.sheenNode):Pb,t=this.sheenRoughnessNode?Up(this.sheenRoughnessNode):Fb;_m.assign(e),wm.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Up(this.iridescenceNode):Ob,t=this.iridescenceIORNode?Up(this.iridescenceIORNode):zb,s=this.iridescenceThicknessNode?Up(this.iridescenceThicknessNode):Lb;Sm.assign(e),Mm.assign(t),Am.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?Vp(this.anisotropyNode):Ub).toVar();Cm.assign(e.length()),Ip(Cm.equal(0),(()=>{e.assign(Vp(1,0))})).Else((()=>{e.divAssign(Vp(Cm)),Cm.assign(Cm.saturate())})),Nm.assign(Cm.pow2().mix(xm.pow2(),1)),Rm.assign(ib[0].mul(e.x).add(ib[1].mul(e.y))),Em.assign(ib[1].mul(e.x).sub(ib[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Up(this.transmissionNode):Vb,t=this.thicknessNode?Up(this.thicknessNode):Db,s=this.attenuationDistanceNode?Up(this.attenuationDistanceNode):Gb,i=this.attenuationColorNode?Wp(this.attenuationColorNode):Wb;if(Vm.assign(e),Dm.assign(t),km.assign(s),Gm.assign(i),this.useDispersion){const e=this.dispersionNode?Up(this.dispersionNode):Zb;Wm.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Wp(this.clearcoatNormalNode):Bb}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),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 pw extends P_{constructor(e,t,s,i){super(e,t,s),this.useSSS=i}direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){if(!0===this.useSSS){const i=r.material,{thicknessColorNode:n,thicknessDistortionNode:o,thicknessAmbientNode:a,thicknessAttenuationNode:h,thicknessPowerNode:u,thicknessScaleNode:l}=i,c=e.add(vx.mul(o)).normalize(),d=Up(cx.dot(c.negate()).saturate().pow(u).mul(l)),p=Wp(d.add(a).mul(n));s.directDiffuse.addAssign(p.mul(h.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r)}}class mw extends dw{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=Up(.1),this.thicknessAmbientNode=Up(0),this.thicknessAttenuationNode=Up(.1),this.thicknessPowerNode=Up(2),this.thicknessScaleNode=Up(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new pw(this.useClearcoat,this.useSheen,this.useIridescence,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 gw=Cp((({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=Vp(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=Wx("gradientMap","texture").context({getUV:()=>r});return Wp(e.r)}{const e=r.fwidth().mul(.5);return vf(Wp(.7),Wp(1),Sf(Up(.7).sub(e.x),Up(.7).add(e.x),r.x))}}));class fw extends IT{direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){const n=gw({normal:gx,lightDirection:e,builder:r}).mul(t);s.directDiffuse.addAssign(n.mul(zT({diffuseColor:fm.rgb})))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(zT({diffuseColor:fm}))),s.indirectDiffuse.mulAssign(e)}}const yw=new Su;class xw extends uT{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(yw),this.setValues(e)}setupLightingModel(){return new fw}}class bw extends Dd{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=Wp(cx.z,0,cx.x.negate()).normalize(),t=cx.cross(e);return Vp(e.dot(vx),t.dot(vx)).mul(.495).add(.5)}}const vw=Np(bw),Tw=new Ru;class _w extends uT{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Tw),this.setValues(e)}setupVariants(e){const t=vw;let s;s=e.material.matcap?Wx("matcap","texture").context({getUV:()=>t}):Wp(vf(.2,.8,t.y)),fm.rgb.mulAssign(s.rgb)}}const ww=new Fa;class Sw extends uT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.isPointsNodeMaterial=!0,this.lights=!1,this.transparent=!0,this.sizeNode=null,this.setDefaultValues(ww),this.setValues(e)}copy(e){return this.sizeNode=e.sizeNode,super.copy(e)}}class Mw extends Dd{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:s}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return Jp(e,i,i.negate(),e).mul(s)}{const e=t,i=Qp($p(1,0,0,0),$p(0,Lg(e.x),zg(e.x).negate(),0),$p(0,zg(e.x),Lg(e.x),0),$p(0,0,0,1)),r=Qp($p(Lg(e.y),0,zg(e.y),0),$p(0,1,0,0),$p(zg(e.y).negate(),0,Lg(e.y),0),$p(0,0,0,1)),n=Qp($p(Lg(e.z),zg(e.z).negate(),0,0),$p(zg(e.z),Lg(e.z),0,0),$p(0,0,1,0),$p(0,0,0,1));return i.mul(r).mul(n).mul($p(s,1)).xyz}}}const Aw=Ap(Mw),Nw=new so;class Cw extends uT{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this.lights=!1,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.setDefaultValues(Nw),this.setValues(e)}setupPosition({object:e,camera:t,context:s}){const i=this.sizeAttenuation,{positionNode:r,rotationNode:n,scaleNode:o}=this,a=ox;let h=sx.mul(Wp(r||0)),u=Vp(Zy[0].xyz.length(),Zy[1].xyz.length());if(null!==o&&(u=u.mul(o)),!i)if(t.isPerspectiveCamera)u=u.mul(h.z.negate());else{const e=Up(2).div(Oy.element(1).element(1));u=u.mul(e.mul(2))}let l=a.xy;if(e.center&&!0===e.center.isVector2){const e=((e,t,s)=>wp(new Zf(e,t,s)))("center","vec2");l=l.sub(e.sub(.5))}l=l.mul(u);const c=Up(n||Ib),d=Aw(l,c);h=$p(h.xy.add(d),h.zw);const p=Oy.mul(h);return s.vertex=a,p}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)}}class Rw extends IT{constructor(){super(),this.shadowNode=Up(1).toVar("shadowMask")}direct({shadowMask:e}){this.shadowNode.mulAssign(e)}finish(e){fm.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(fm.rgb)}}const Ew=new bu;class Bw extends uT{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Ew),this.setValues(e)}setupLightingModel(){return new Rw}}const Iw=Cp((({texture:e,uv:t})=>{const s=1e-4,i=Wp().toVar();return Ip(t.x.lessThan(s),(()=>{i.assign(Wp(1,0,0))})).ElseIf(t.y.lessThan(s),(()=>{i.assign(Wp(0,1,0))})).ElseIf(t.z.lessThan(s),(()=>{i.assign(Wp(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(Wp(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(Wp(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(Wp(0,0,-1))})).Else((()=>{const s=.01,r=e.uv(t.add(Wp(-.01,0,0))).r.sub(e.uv(t.add(Wp(s,0,0))).r),n=e.uv(t.add(Wp(0,-.01,0))).r.sub(e.uv(t.add(Wp(0,s,0))).r),o=e.uv(t.add(Wp(0,0,-.01))).r.sub(e.uv(t.add(Wp(0,0,s))).r);i.assign(Wp(r,n,o))})),i.normalize()}));class Pw extends Ey{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Wp(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){return t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return Iw({texture:this,uv:e})}}const Fw=Ap(Pw);class Uw extends uT{static get type(){return"VolumeNodeMaterial"}constructor(e={}){super(),this.lights=!1,this.isVolumeNodeMaterial=!0,this.testNode=null,this.setValues(e)}setup(e){const t=Fw(this.map,null,0),s=Cp((({orig:e,dir:t})=>{const s=Wp(-.5),i=Wp(.5),r=t.reciprocal(),n=s.sub(e).mul(r),o=i.sub(e).mul(r),a=rf(n,o),h=nf(n,o),u=nf(a.x,nf(a.y,a.z)),l=rf(h.x,rf(h.y,h.z));return Vp(u,l)}));this.fragmentNode=Cp((()=>{const e=Vf(Wp(tx.mul($p(ky,1)))),i=Vf(nx.sub(e)).normalize(),r=Vp(s({orig:e,dir:i})).toVar();r.x.greaterThan(r.y).discard(),r.assign(Vp(nf(r.x,0),r.y));const n=Wp(e.add(r.x.mul(i))).toVar(),o=Wp(i.abs().reciprocal()).toVar(),a=Up(rf(o.x,rf(o.y,o.z))).toVar("delta");a.divAssign(Wx("steps","float"));const h=$p(Wx("base","color"),0).toVar();return xv({type:"float",start:r.x,end:r.y,update:"+= delta"},(()=>{const e=mm("float","d").assign(t.uv(n.add(.5)).r);null!==this.testNode?this.testNode({map:t,mapValue:e,probe:n,finalColor:h}).append():(h.a.assign(1),vv()),n.addAssign(i.mul(a))})),h.a.equal(0).discard(),$p(h)}))(),super.setup(e)}}class Ow{constructor(e,t){this.nodes=e,this.info=t,this.animationLoop=null,this.requestId=null,this._init()}_init(){const e=(t,s)=>{this.requestId=self.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,s)};e()}dispose(){self.cancelAnimationFrame(this.requestId),this.requestId=null}setAnimationLoop(e){this.animationLoop=e}}class zw{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let s=0;s{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){const t=this.material;let s=this.clippingContext;Array.isArray(t.clippingPlanes)?(s!==e&&s||(s=new Vw,this.clippingContext=s),s.update(e,t)):this.clippingContext!==e&&(this.clippingContext=e)}get clippingNeedsUpdate(){return this.clippingContext.version!==this.clippingContextVersion&&(this.clippingContextVersion=this.clippingContext.version,!0)}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().monitor)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;s.push(e);const n=e.isInterleavedBufferAttribute?e.data:e;i.add(n)}return this.attributes=s,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:r}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),o=this.getIndex(),a=null!==o,h=s.isInstancedBufferGeometry?s.instanceCount:e.count>1?e.count:1;if(0===h)return null;if(n.instanceCount=h,!0===e.isBatchedMesh)return n;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let l=r.start*u,c=(r.start+r.count)*u;null!==i&&(l=Math.max(l,i.start*u),c=Math.min(c,(i.start+i.count)*u));const d=s.attributes.position;let p=1/0;a?p=o.count:null!=d&&(p=d.count),l=Math.max(l,0),c=Math.min(c,p);const m=c-l;return m<0||m===1/0?null:(n.vertexCount=m,n.firstVertex=l,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t}=this;let s=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let s=Object.getPrototypeOf(e);for(;s;){const e=Object.getOwnPropertyDescriptors(s);for(const s in e)if(void 0!==e[s]){const i=e[s];i&&"function"==typeof i.get&&t.push(s)}s=Object.getPrototypeOf(s)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const i=t[e];let r;if(null!==i){const e=typeof i;"number"===e?r=0!==i?"1":"0":"object"===e?(r="{",i.isTexture&&(r+=i.mapping),r+="}"):r=String(i)}else r=String(i);s+=r+","}return s+=this.clippingContext.cacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.morphTargetInfluences&&(s+=e.morphTargetInfluences.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),bd(s)}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=this._nodes.getCacheKey(this.scene,this.lightsNode);return this.object.receiveShadow&&(e+=1),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const Gw=[];class Ww{constructor(e,t,s,i,r,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=r,this.info=n,this.chainMaps={}}get(e,t,s,i,r,n,o){const a=this.getChainMap(o);Gw[0]=e,Gw[1]=t,Gw[2]=n,Gw[3]=r;let h=a.get(Gw);return void 0===h?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o),a.set(Gw,h)):(h.updateClipping(n.clippingContext),(h.version!==t.version||h.needsUpdate)&&(h.initialCacheKey!==h.getCacheKey()?(h.dispose(),h=this.get(e,t,s,i,r,n,o)):h.version=t.version)),h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new zw)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,h,u){const l=this.getChainMap(u),c=new kw(e,t,s,i,r,n,o,a,h);return c.onDispose=()=>{this.pipelines.delete(c),this.bindings.delete(c),this.nodes.delete(c),l.delete(c.getChainArray())},c}}class jw{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;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 Hw=1,qw=2,$w=3,Xw=4,Yw=16;class Zw extends jw{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return void 0!==t&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===Hw?this.backend.createAttribute(e):t===qw?this.backend.createIndexAttribute(e):t===$w?this.backend.createStorageAttribute(e):t===Xw&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version=0;--t)if(e[t]>=65535)return!0;return!1}(t)?mn:dn)(t,1);return r.version=Jw(e),r}class Qw extends jw{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",s)};t.addEventListener("dispose",s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,$w):this.updateAttribute(e,Hw);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,qw);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,Xw)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=Kw(t),e.set(t,s)):s.version!==Jw(t)&&(this.attributes.delete(s),s=Kw(t),e.set(t,s)),i=s}return i}}class eS{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,previousFrameCalls:0,timestampCalls:0},this.compute={calls:0,frameCalls:0,timestamp:0,previousFrameCalls:0,timestampCalls:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}updateTimestamp(e,t){0===this[e].timestampCalls&&(this[e].timestamp=0),this[e].timestamp+=t,this[e].timestampCalls++,this[e].timestampCalls>=this[e].previousFrameCalls&&(this[e].timestampCalls=0)}reset(){const e=this.render.frameCalls;this.render.previousFrameCalls=e;const t=this.compute.frameCalls;this.compute.previousFrameCalls=t,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 tS{constructor(e){this.cacheKey=e,this.usedTimes=0}}class sS extends tS{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class iS extends tS{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let rS=0;class nS{constructor(e,t,s=null,i=null){this.id=rS++,this.code=e,this.stage=t,this.transforms=s,this.attributes=i,this.usedTimes=0}}class oS extends jw{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:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let o=this.programs.compute.get(n.computeShader);void 0===o&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),o=new nS(n.computeShader,"compute",n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,o),s.createProgram(o));const a=this._getComputeCacheKey(e,o);let h=this.caches.get(a);void 0===h&&(r&&0===r.usedTimes&&this._releasePipeline(r),h=this._getComputePipeline(e,o,a,t)),h.usedTimes++,o.usedTimes++,i.version=e.version,i.pipeline=h}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState();let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new nS(n.vertexShader,"vertex"),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o));let a=this.programs.fragment.get(n.fragmentShader);void 0===a&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),a=new nS(n.fragmentShader,"fragment"),this.programs.fragment.set(n.fragmentShader,a),s.createProgram(a));const h=this._getRenderCacheKey(e,o,a);let u=this.caches.get(h);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,o,a,h,t)):e.pipeline=u,u.usedTimes++,o.usedTimes++,a.usedTimes++,i.pipeline=u}return i.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,s,i){s=s||this._getComputeCacheKey(e,t);let r=this.caches.get(s);return void 0===r&&(r=new iS(s,t),this.caches.set(s,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,s,i,r){i=i||this._getRenderCacheKey(e,t,s);let n=this.caches.get(i);return void 0===n&&(n=new sS(i,t,s),this.caches.set(i,n),e.pipeline=n,this.backend.createRenderPipeline(e,r)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].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 aS extends jw{constructor(e,t,s,i,r,n){super(),this.backend=e,this.textures=s,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t),s.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t),s.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,s=e.isIndirectStorageBufferAttribute?Xw:$w;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!this.nodes.updateGroup(t))continue}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){t.needsBindingsUpdate(this.textures.get(t.texture).generation)&&(i=!0);const e=t.update(),r=t.texture;e&&this.textures.updateTexture(r);const n=s.get(r);if(!0===s.isWebGPUBackend&&void 0===n.texture&&void 0===n.externalTexture&&(console.error("Bindings._update: binding should be available:",t,e,r,t.textureNode.value,i),this.textures.updateTexture(r),i=!0),!0===r.isStorageTexture){const e=this.get(r);!0===t.store?e.needsMipmap=!0:!0===r.generateMipmaps&&this.textures.needsMipmaps(r)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(r),e.needsMipmap=!1)}}}!0===i&&this.backend.updateBindings(e,t)}}function hS(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function uS(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}class lS{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,s),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,i,r,n){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:r,group:n},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=s,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=n),this.renderItemsIndex++,o}push(e,t,s,i,r,n){const o=this.getNextRenderItem(e,t,s,i,r,n);!0===e.occlusionTest&&this.occlusionQueryCount++,(!0===s.transparent||s.transmission>0?this.transparent:this.opaque).push(o)}unshift(e,t,s,i,r,n){const o=this.getNextRenderItem(e,t,s,i,r,n);(!0===s.transparent?this.transparent: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||hS),this.transparent.length>1&&this.transparent.sort(t||uS)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,h=o.height>>t;let u=e.depthTexture||r[t];const l=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===u&&l&&(u=new Xa,u.format=e.stencilBuffer?je:We,u.type=e.stencilBuffer?Oe:Be,u.image.width=a,u.image.height=h,r[t]=u),s.width===o.width&&o.height===s.height||(c=!0,u&&(u.needsUpdate=!0,u.image.width=a,u.image.height=h)),s.width=o.width,s.height=o.height,s.textures=n,s.depthTexture=u||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(c=!0,u&&(u.needsUpdate=!0),s.sampleCount=i);const d={sampleCount:i};for(let e=0;e{e.removeEventListener("dispose",t);for(let e=0;e0){const i=e.image;if(void 0===i)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=i;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(r.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version}if(!0!==s.initialized){s.initialized=!0,s.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}s.version=e.version}getSize(e,t=fS){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),t.width=s.width,t.height=s.height,t.depth=e.isCubeTexture?6:s.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return i=e.isCompressedTexture?e.mipmaps.length:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return!!this.isEnvironmentTexture(e)||(!0===e.isCompressedTexture||e.minFilter!==fe&&e.minFilter!==Te)}isEnvironmentTexture(e){const t=e.mapping;return t===le||t===ce||t===he||t===ue}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class xS extends Xr{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}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 bS extends pm{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}const vS=(e,t)=>wp(new bS(e,t));class TS extends zd{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}add(e){return this.nodes.push(e),this}If(e,t){const s=new _p(t);return this._currentCond=Ef(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new _p(t),i=Ef(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new _p(e),this}build(e,...t){const s=Bp();Ep(this);for(const t of this.nodes)t.build(e,"void");return Ep(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("TSL.StackNode: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("TSL.StackNode: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const _S=Ap(TS);class wS extends zd{static get type(){return"StructTypeNode"}constructor(e){super(),this.types=e,this.isStructTypeNode=!0}getMemberTypes(){return this.types}}class SS extends zd{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}setup(e){super.setup(e);const t=this.members,s=[];for(let i=0;i{const t=e.toUint().mul(747796405).add(2891336453),s=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return s.shiftRight(22).bitXor(s).toFloat().mul(1/2**32)})),ES=(e,t)=>pf(Jm(4,e.mul(Zm(1,e))),t),BS=(e,t)=>e.lessThan(.5)?ES(e.mul(2),t).div(2):Zm(1,ES(Jm(Zm(1,e),2),t).div(2)),IS=(e,t,s)=>pf(Km(pf(e,t),Ym(pf(e,t),pf(Zm(1,e),s))),1/t),PS=(e,t)=>zg(vg.mul(t.mul(e).sub(1))).div(vg.mul(t.mul(e).sub(1))),FS=Cp((([e])=>e.fract().sub(.5).abs())).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),US=Cp((([e])=>Wp(FS(e.z.add(FS(e.y.mul(1)))),FS(e.z.add(FS(e.x.mul(1)))),FS(e.y.add(FS(e.x.mul(1))))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),OS=Cp((([e,t,s])=>{const i=Wp(e).toVar(),r=Up(1.4).toVar(),n=Up(0).toVar(),o=Wp(i).toVar();return xv({start:Up(0),end:Up(3),type:"float",condition:"<="},(()=>{const e=Wp(US(o.mul(2))).toVar();i.addAssign(e.add(s.mul(Up(.1).mul(t)))),o.mulAssign(1.8),r.mulAssign(1.5),i.mulAssign(1.2);const a=Up(FS(i.z.add(FS(i.x.add(FS(i.y)))))).toVar();n.addAssign(a.div(r)),o.addAssign(.14)})),n})).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"p",type:"vec3"},{name:"spd",type:"float"},{name:"time",type:"float"}]});class zS extends zd{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 s=this._candidateFnCall;if(null===s){let i=null,r=-1;for(const s of this.functionNodes){const n=s.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const o=n.inputs;if(t.length===o.length){let n=0;for(let s=0;sr&&(i=s,r=n)}}this._candidateFnCall=s=i(...t)}return s}}const LS=Ap(zS),VS=e=>(...t)=>LS(e,...t),DS=dm(0).setGroup(um).onRenderUpdate((e=>e.time)),kS=dm(0).setGroup(um).onRenderUpdate((e=>e.deltaTime)),GS=dm(0,"uint").setGroup(um).onRenderUpdate((e=>e.frameId)),WS=(e=1)=>(console.warn('TSL: timerLocal() is deprecated. Use "time" instead.'),DS.mul(e)),jS=(e=1)=>(console.warn('TSL: timerGlobal() is deprecated. Use "time" instead.'),DS.mul(e)),HS=(e=1)=>(console.warn('TSL: timerDelta() is deprecated. Use "deltaTime" instead.'),kS.mul(e)),qS=(e=DS)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),$S=(e=DS)=>e.fract().round(),XS=(e=DS)=>e.add(.5).fract().mul(2).sub(1).abs(),YS=(e=DS)=>e.fract(),ZS=Cp((([e,t,s=Vp(.5)])=>Aw(e.sub(s),t).add(s))),JS=Cp((([e,t,s=Vp(.5)])=>{const i=e.sub(s),r=i.dot(i),n=r.mul(r).mul(t);return e.add(i.mul(n))})),KS=Cp((({position:e=null,horizontal:t=!0,vertical:s=!1})=>{let i;null!==e?(i=Zy.toVar(),i[3][0]=e.x,i[3][1]=e.y,i[3][2]=e.z):i=Zy;const r=Ly.mul(i);return vp(t)&&(r[0][0]=Zy[0].length(),r[0][1]=0,r[0][2]=0),vp(s)&&(r[1][0]=0,r[1][1]=Zy[1].length(),r[1][2]=0),r[2][0]=0,r[2][1]=0,r[2][2]=1,Oy.mul(r).mul(ox)})),QS=Cp((([e=null])=>{const t=oT();return oT(Jv(e)).sub(t).lessThan(0).select(Uv,e)}));class eM extends zd{static get type(){return"SpriteSheetUVNode"}constructor(e,t=My(),s=Up(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=s}setup(){const{frameNode:e,uvNode:t,countNode:s}=this,{width:i,height:r}=s,n=e.mod(i.mul(r)).floor(),o=n.mod(i),a=r.sub(n.add(1).div(i).ceil()),h=s.reciprocal(),u=Vp(o,a);return t.add(u).mul(h)}}const tM=Ap(eM);class sM extends zd{static get type(){return"TriplanarTexturesNode"}constructor(e,t=null,s=null,i=Up(1),r=ox,n=fx){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=s,this.scaleNode=i,this.positionNode=r,this.normalNode=n}setup(){const{textureXNode:e,textureYNode:t,textureZNode:s,scaleNode:i,positionNode:r,normalNode:n}=this;let o=n.abs().normalize();o=o.div(o.dot(Wp(1)));const a=r.yz.mul(i),h=r.zx.mul(i),u=r.xy.mul(i),l=e.value,c=null!==t?t.value:l,d=null!==s?s.value:l,p=By(l,a).mul(o.x),m=By(c,h).mul(o.y),g=By(d,u).mul(o.z);return Ym(p,m,g)}}const iM=Ap(sM),rM=(...e)=>iM(...e),nM=new Yo,oM=new Ai,aM=new Ai,hM=new Ai,uM=new sr,lM=new Ai(0,0,-1),cM=new xi,dM=new Ai,pM=new Ai,mM=new xi,gM=new Ys,fM=new bi,yM=Uv.flipX();fM.depthTexture=new Xa(1,1);let xM=!1;class bM extends Ey{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||fM.texture,yM),this._reflectorBaseNode=e.reflector||new vM(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=wp(new bM({defaultTexture:fM.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._reflectorBaseNode=this._reflectorBaseNode,e}}class vM extends zd{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:s=new Rr,resolution:i=1,generateMipmaps:r=!1,bounces:n=!0,depth:o=!1}=t;this.textureNode=e,this.target=s,this.resolution=i,this.generateMipmaps=r,this.bounces=n,this.depth=o,this.updateBeforeType=n?Ed.RENDER:Ed.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new WeakMap}_updateResolution(e,t){const s=this.resolution;t.getDrawingBufferSize(gM),e.setSize(Math.round(gM.width*s),Math.round(gM.height*s))}setup(e){return this._updateResolution(fM,e.renderer),super.setup(e)}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 bi(0,0,{type:Pe}),!0===this.generateMipmaps&&(t.texture.minFilter=1008,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new Xa),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&xM)return;xM=!0;const{scene:t,camera:s,renderer:i,material:r}=e,{target:n}=this,o=this.getVirtualCamera(s),a=this.getRenderTarget(o);if(i.getDrawingBufferSize(gM),this._updateResolution(a,i),aM.setFromMatrixPosition(n.matrixWorld),hM.setFromMatrixPosition(s.matrixWorld),uM.extractRotation(n.matrixWorld),oM.set(0,0,1),oM.applyMatrix4(uM),dM.subVectors(aM,hM),dM.dot(oM)>0)return;dM.reflect(oM).negate(),dM.add(aM),uM.extractRotation(s.matrixWorld),lM.set(0,0,-1),lM.applyMatrix4(uM),lM.add(hM),pM.subVectors(aM,lM),pM.reflect(oM).negate(),pM.add(aM),o.coordinateSystem=s.coordinateSystem,o.position.copy(dM),o.up.set(0,1,0),o.up.applyMatrix4(uM),o.up.reflect(oM),o.lookAt(pM),o.near=s.near,o.far=s.far,o.updateMatrixWorld(),o.projectionMatrix.copy(s.projectionMatrix),nM.setFromNormalAndCoplanarPoint(oM,aM),nM.applyMatrix4(o.matrixWorldInverse),cM.set(nM.normal.x,nM.normal.y,nM.normal.z,nM.constant);const h=o.projectionMatrix;mM.x=(Math.sign(cM.x)+h.elements[8])/h.elements[0],mM.y=(Math.sign(cM.y)+h.elements[9])/h.elements[5],mM.z=-1,mM.w=(1+h.elements[10])/h.elements[14],cM.multiplyScalar(1/cM.dot(mM));h.elements[2]=cM.x,h.elements[6]=cM.y,h.elements[10]=i.coordinateSystem===Os?cM.z-0:cM.z+1-0,h.elements[14]=cM.w,this.textureNode.value=a.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=a.depthTexture),r.visible=!1;const u=i.getRenderTarget(),l=i.getMRT();i.setMRT(null),i.setRenderTarget(a),i.render(t,o),i.setMRT(l),i.setRenderTarget(u),r.visible=!0,xM=!1}}const TM=e=>wp(new bM(e)),_M=new wl(-1,1,1,-1,0,1);class wM extends Sn{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new fn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new fn(t,2))}}const SM=new wM;class MM extends On{constructor(e=null){super(SM,e),this.camera=_M,this.isQuadMesh=!0}renderAsync(e){return e.renderAsync(this,_M)}render(e){e.render(this,_M)}}const AM=new Ys;class NM extends Ey{static get type(){return"RTTNode"}constructor(e,t=null,s=null,i={type:Pe}){const r=new bi(t,s,i);super(r.texture,My()),this.node=e,this.width=t,this.height=s,this.renderTarget=r,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this.updateMap=new WeakMap,this._rttNode=null,this._quadMesh=new MM(new uT),this.updateBeforeType=Ed.RENDER}get autoSize(){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 s=e*this.pixelRatio,i=t*this.pixelRatio;this.renderTarget.setSize(s,i),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.autoSize){this.pixelRatio=e.getPixelRatio();const t=e.getSize(AM);this.setSize(t.width,t.height)}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 Ey(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const CM=(e,...t)=>wp(new NM(wp(e),...t)),RM=(e,...t)=>e.isTextureNode?e:CM(e,...t),EM=Cp((([e,t,s],i)=>{let r;i.renderer.coordinateSystem===Os?(e=Vp(e.x,e.y.oneMinus()).mul(2).sub(1),r=$p(Wp(e,t),1)):r=$p(Wp(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=$p(s.mul(r));return n.xyz.div(n.w)})),BM=Cp((([e,t])=>{const s=t.mul($p(e,1)),i=s.xy.div(s.w).mul(.5).add(.5).toVar();return Vp(i.x,i.y.oneMinus())}));class IM extends wy{static get type(){return"VertexColorNode"}constructor(e=0){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 s;return s=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new xi(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const PM=(...e)=>wp(new IM(...e));class FM extends zd{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const UM=Np(FM);class OM extends zd{static get type(){return"SceneNode"}constructor(e=OM.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let i;return t===OM.BACKGROUND_BLURRINESS?i=Dx("backgroundBlurriness","float",s):t===OM.BACKGROUND_INTENSITY?i=Dx("backgroundIntensity","float",s):console.error("THREE.SceneNode: Unknown scope:",t),i}}OM.BACKGROUND_BLURRINESS="backgroundBlurriness",OM.BACKGROUND_INTENSITY="backgroundIntensity";const zM=Np(OM,OM.BACKGROUND_BLURRINESS),LM=Np(OM,OM.BACKGROUND_INTENSITY);class VM extends Ld{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}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.bufferObject&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let s;const i=e.context.assign;if(s=!1===e.isAvailable("storageBuffer")?!0===this.node.bufferObject&&!0!==i?e.generatePBO(this):this.node.build(e):super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}const DM=Ap(VM),kM="point-list",GM="line-list",WM="line-strip",jM="triangle-list",HM="triangle-strip",qM="never",$M="less",XM="equal",YM="less-equal",ZM="greater",JM="not-equal",KM="greater-equal",QM="always",eA="store",tA="load",sA="clear",iA="ccw",rA="none",nA="front",oA="back",aA="uint16",hA="uint32",uA={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10uFloat:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Stencil8:"stencil8",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},lA="clamp-to-edge",cA="repeat",dA="mirror-repeat",pA="linear",mA="nearest",gA="zero",fA="one",yA="src",xA="one-minus-src",bA="src-alpha",vA="one-minus-src-alpha",TA="dst",_A="one-minus-dst",wA="dst-alpha",SA="one-minus-dst-alpha",MA="src-alpha-saturated",AA="constant",NA="one-minus-constant",CA="add",RA="subtract",EA="reverse-subtract",BA="min",IA="max",PA=0,FA=15,UA="keep",OA="zero",zA="replace",LA="invert",VA="increment-clamp",DA="decrement-clamp",kA="increment-wrap",GA="decrement-wrap",WA="storage",jA="read-only-storage",HA="write-only",qA="read-only",$A="float",XA="unfilterable-float",YA="depth",ZA="sint",JA="uint",KA="2d",QA="3d",eN="2d",tN="2d-array",sN="cube",iN="3d",rN="all",nN="vertex",oN="instance",aN={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class hN extends Ix{static get type(){return"StorageBufferNode"}constructor(e,t,s=0){super(e,t,s),this.isStorageBufferNode=!0,this.access=WA,this.isAtomic=!1,this.bufferObject=!1,this.bufferCount=s,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 DM(this,e)}setBufferObject(e){return this.bufferObject=e,this}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(jA)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=iy(this.value),this._varying=Vf(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}generate(e){if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:s}=this.getAttributeData(),i=s.build(e);return e.registerTransform(i,t),i}}const uN=(e,t,s)=>wp(new hN(e,t,s)),lN=(e,t,s)=>wp(new hN(e,t,s).setBufferObject(!0));class cN extends Ey{static get type(){return"StorageTextureNode"}constructor(e,t,s=null){super(e,t),this.storeNode=s,this.isStorageTextureNode=!0,this.access=HA}getInputType(){return"storageTexture"}setup(e){super.setup(e);e.getNodeProperties(this).storeNode=this.storeNode}setAccess(e){return this.access=e,this}generate(e,t){let s;return s=null!==this.storeNode?this.generateStore(e):super.generate(e,t),s}toReadOnly(){return this.setAccess(qA)}toWriteOnly(){return this.setAccess(HA)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:s,storeNode:i}=t,r=super.generate(e,"property"),n=s.build(e,"uvec2"),o=i.build(e,"vec4"),a=e.generateTextureStore(e,r,n,o);e.addLineFlowCode(a,this)}}const dN=Ap(cN),pN=(e,t,s)=>{const i=dN(e,t,s);return null!==s&&i.append(),i};class mN extends Vx{static get type(){return"UserDataNode"}constructor(e,t,s=null){super(e,t,s),this.userData=s}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const gN=(e,t,s)=>wp(new mN(e,t,s)),fN=new WeakMap;class yN extends Dd{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.updateType=Ed.OBJECT,this.updateAfterType=Ed.OBJECT,this.previousModelWorldMatrix=dm(new sr),this.previousProjectionMatrix=dm(new sr).setGroup(um),this.previousCameraViewMatrix=dm(new sr)}update({frameId:e,camera:t,object:s}){const i=bN(s);this.previousModelWorldMatrix.value.copy(i);const r=xN(t);r.frameId!==e&&(r.frameId=e,void 0===r.previousProjectionMatrix?(r.previousProjectionMatrix=new sr,r.previousCameraViewMatrix=new sr,r.currentProjectionMatrix=new sr,r.currentCameraViewMatrix=new sr,r.previousProjectionMatrix.copy(t.projectionMatrix),r.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(r.previousProjectionMatrix.copy(r.currentProjectionMatrix),r.previousCameraViewMatrix.copy(r.currentCameraViewMatrix)),r.currentProjectionMatrix.copy(t.projectionMatrix),r.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(r.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(r.previousCameraViewMatrix))}updateAfter({object:e}){bN(e).copy(e.matrixWorld)}setup(){const e=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),t=Oy.mul(sx).mul(ox),s=this.previousProjectionMatrix.mul(e).mul(ax),i=t.xy.div(t.w),r=s.xy.div(s.w);return Zm(i,r)}}function xN(e){let t=fN.get(e);return void 0===t&&(t={},fN.set(e,t)),t}function bN(e,t=0){const s=xN(e);let i=s[t];return void 0===i&&(s[t]=i=new sr),i}const vN=Np(yN),TN=Cp((([e,t])=>rf(1,e.oneMinus().div(t)).oneMinus())).setLayout({name:"burnBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),_N=Cp((([e,t])=>rf(e.div(t.oneMinus()),1))).setLayout({name:"dodgeBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),wN=Cp((([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus())).setLayout({name:"screenBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),SN=Cp((([e,t])=>vf(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),af(.5,e)))).setLayout({name:"overlayBlend",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),MN=Cp((([e])=>RN(e.rgb))),AN=Cp((([e,t=Up(1)])=>t.mix(RN(e.rgb),e.rgb))),NN=Cp((([e,t=Up(1)])=>{const s=Ym(e.r,e.g,e.b).div(3),i=e.r.max(e.g.max(e.b)),r=i.sub(s).mul(t).mul(-3);return vf(e.rgb,i,r)})),CN=Cp((([e,t=Up(1)])=>{const s=Wp(.57735,.57735,.57735),i=t.cos();return Wp(e.rgb.mul(i).add(s.cross(e.rgb).mul(t.sin()).add(s.mul(cf(s,e.rgb).mul(i.oneMinus())))))})),RN=(e,t=Wp(ii.getLuminanceCoefficients(new Ai)))=>cf(e,t),EN=(e,t)=>vf(Wp(0),e,RN(e).sub(t).max(0)),BN=Cp((([e,t=Wp(1),s=Wp(0),i=Wp(1),r=Up(1),n=Wp(ii.getLuminanceCoefficients(new Ai,Jt))])=>{const o=e.rgb.dot(Wp(n)),a=nf(e.rgb.mul(t).add(s),0).toVar(),h=a.pow(i).toVar();return Ip(a.r.greaterThan(0),(()=>{a.r.assign(h.r)})),Ip(a.g.greaterThan(0),(()=>{a.g.assign(h.g)})),Ip(a.b.greaterThan(0),(()=>{a.b.assign(h.b)})),a.assign(o.add(a.sub(o).mul(r))),$p(a.rgb,e.a)}));class IN extends Dd{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 PN=Ap(IN);let FN=null;class UN extends qv{static get type(){return"ViewportSharedTextureNode"}constructor(e=Uv,t=null){null===FN&&(FN=new Wa),super(e,t,FN)}updateReference(){return this}}const ON=Ap(UN),zN=new Ys;class LN extends Ey{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class VN extends LN{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class DN extends Dd{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new Xa;r.isRenderTargetTexture=!0,r.name="depth";const n=new bi(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Pe,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this.updateBeforeType=Ed.FRAME,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=dm(0),this._cameraFar=dm(0),this._mrt=null,this.isPassNode=!0}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}isGlobal(){return!0}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.isRenderTargetTexture=!0,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(),t.isRenderTargetTexture=!0,this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(this._textureNodes[e]=t=wp(new VN(this,e)),this._textureNodes[e].updateTexture()),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),this._previousTextureNodes[e]=t=wp(new VN(this,e,!0)),this._previousTextureNodes[e].updateTexture()),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=sT(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=Qv(r,s,i)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,!0===e.backend.isWebGLBackend&&(this.renderTarget.samples=0),this.renderTarget.depthTexture.isMultisampleRenderTargetTexture=this.renderTarget.samples>1,this.scope===DN.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s,camera:i}=this;this._pixelRatio=t.getPixelRatio();const r=t.getSize(zN);this.setSize(r.width,r.height);const n=t.getRenderTarget(),o=t.getMRT();this._cameraNear.value=i.near,this._cameraFar.value=i.far;for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(n),t.setMRT(o)}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}DN.COLOR="color",DN.DEPTH="depth";const kN=(e,t,s)=>wp(new DN(DN.COLOR,e,t,s)),GN=(e,t)=>wp(new LN(e,t)),WN=(e,t)=>wp(new DN(DN.DEPTH,e,t));class jN extends DN{static get type(){return"ToonOutlinePassNode"}constructor(e,t,s,i,r){super(DN.COLOR,e,t),this.colorNode=s,this.thicknessNode=i,this.alphaNode=r,this._materialCache=new WeakMap}updateBefore(e){const{renderer:t}=e,s=t.getRenderObjectFunction();t.setRenderObjectFunction(((e,s,i,r,n,o,a)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const h=this._getOutlineMaterial(n);t.renderObject(e,s,i,r,h,o,a)}t.renderObject(e,s,i,r,n,o,a)})),super.updateBefore(e),t.setRenderObjectFunction(s)}_createMaterial(){const e=new uT;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=d;const t=fx.negate(),s=Oy.mul(sx),i=Up(1),r=s.mul($p(ox,1)),n=s.mul($p(ox.add(t),1)),o=Ug(r.sub(n));return e.vertexNode=r.add(o.mul(this.thicknessNode).mul(r.w).mul(i)),e.colorNode=$p(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 HN=(e,t,s=new Xr(0,0,0),i=.003,r=1)=>wp(new jN(e,t,wp(s),wp(i),wp(r))),qN=Cp((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return vf(t,s,i)})).setLayout({name:"sRGBToLinearSRGB",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),$N=Cp((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return vf(t,s,i)})).setLayout({name:"linearSRGBTosRGB",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),XN=Cp((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),YN=Cp((([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"}]}),ZN=Cp((([e,t])=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(i).pow(2.2)})).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),JN=Cp((([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)})),KN=Cp((([e,t])=>{const s=Kp(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Kp(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=JN(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),QN=Kp(Wp(1.6605,-.1246,-.0182),Wp(-.5876,1.1329,-.1006),Wp(-.0728,-.0083,1.1187)),eC=Kp(Wp(.6274,.0691,.0164),Wp(.3293,.9195,.088),Wp(.0433,.0113,.8956)),tC=Cp((([e])=>{const t=Wp(e).toVar(),s=Wp(t.mul(t)).toVar(),i=Wp(s.mul(s)).toVar();return Up(15.5).mul(i.mul(s)).sub(Jm(40.14,i.mul(t))).add(Jm(31.96,i).sub(Jm(6.868,s.mul(t))).add(Jm(.4298,s).add(Jm(.1191,t).sub(.00232))))})),sC=Cp((([e,t])=>{const s=Wp(e).toVar(),i=Kp(Wp(.856627153315983,.137318972929847,.11189821299995),Wp(.0951212405381588,.761241990602591,.0767994186031903),Wp(.0482516061458583,.101439036467562,.811302368396859)),r=Kp(Wp(1.1271005818144368,-.1413297634984383,-.14132976349843826),Wp(-.11060664309660323,1.157823702216272,-.11060664309660294),Wp(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Up(-12.47393),o=Up(4.026069);return s.mulAssign(t),s.assign(eC.mul(s)),s.assign(i.mul(s)),s.assign(nf(s,1e-10)),s.assign(Eg(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(Tf(s,0,1)),s.assign(tC(s)),s.assign(r.mul(s)),s.assign(pf(nf(Wp(0),s),Wp(2.2))),s.assign(QN.mul(s)),s.assign(Tf(s,0,1)),s})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),iC=Cp((([e,t])=>{const s=Up(.76),i=Up(.15);e=e.mul(t);const r=rf(e.r,rf(e.g,e.b)),n=Ef(r.lessThan(.08),r.sub(Jm(6.25,r.mul(r))),.04);e.subAssign(n);const o=nf(e.r,nf(e.g,e.b));Ip(o.lessThan(s),(()=>e));const a=Zm(1,s),h=Zm(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(h.div(o));const u=Zm(1,Km(1,i.mul(o.sub(h)).add(1)));return vf(e,Wp(h),u)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class rC extends zd{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.code=e,this.language=s,this.includes=t}isGlobal(){return!0}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.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 nC=Ap(rC),oC=(e,t)=>nC(e,t,"js"),aC=(e,t)=>nC(e,t,"wgsl"),hC=(e,t)=>nC(e,t,"glsl");class uC extends rC{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,r=s.type,n=e.getCodeFromNode(this,r);""!==i&&(n.name=i);const o=e.getPropertyName(n),a=this.getNodeFunction(e).getCode(o);return n.code=a+"\n","property"===t?o:e.format(`${o}()`,r,t)}}const lC=(e,t=[],s="")=>{for(let e=0;ei.call(...e);return r.functionNode=i,r},cC=(e,t)=>lC(e,t,"glsl"),dC=(e,t)=>lC(e,t,"wgsl");class pC extends zd{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outpuType=null,this.events=new zs,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:Up()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Ad(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?Nd(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 mC=Ap(pC);class gC extends Map{get(e,t=null,...s){if(this.has(e))return super.get(e);if(null!==t){const i=t(...s);return this.set(e,i),i}}}class fC{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 yC=new gC;class xC extends zd{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new gC,this._output=mC(),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 s=this._outputs;return void 0===s[e]?s[e]=mC(t):s[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const s=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),s[e]=t,s[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),s[e]=t,s[e].events.addEventListener("refresh",this.onRefresh)):void 0===s[e]?(s[e]=mC(t),s[e].events.addEventListener("refresh",this.onRefresh)):s[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 s=this.getObject()[e];if("function"==typeof s)return s(...t)}async callAsync(e,...t){const s=this.getObject()[e];if("function"==typeof s)return"AsyncFunction"===s.constructor.name?await s(...t):s(...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 fC(this),t=yC.get("THREE"),s=yC.get("TSL"),i=this.getMethod(this.codeNode),r=[e,this._local,yC,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,s];this._object=i(...r);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:Up()}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+" };",s="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],s),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=[bd(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const s in this.parameters)t.push(this.parameters[s].getCacheKey(e));return vd(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 bC=Ap(xC);class vC extends zd{static get type(){return"FogNode"}constructor(e,t){super("float"),this.isFogNode=!0,this.colorNode=e,this.factorNode=t}getViewZNode(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||lx.z).negate()}setup(){return this.factorNode}}const TC=Ap(vC);class _C extends vC{static get type(){return"FogRangeNode"}constructor(e,t,s){super(e),this.isFogRangeNode=!0,this.nearNode=t,this.farNode=s}setup(e){const t=this.getViewZNode(e);return Sf(this.nearNode,this.farNode,t)}}const wC=Ap(_C);class SC extends vC{static get type(){return"FogExp2Node"}constructor(e,t){super(e),this.isFogExp2Node=!0,this.densityNode=t}setup(e){const t=this.getViewZNode(e),s=this.densityNode;return s.mul(s,t,t).negate().exp().oneMinus()}}const MC=Ap(SC);let AC=null,NC=null;class CC extends zd{static get type(){return"RangeNode"}constructor(e=Up(),t=Up()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Sd(this.minNode.value)),s=e.getTypeLength(Sd(this.maxNode.value));return t>s?t:s}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let s=null;if(t.count>1){const i=this.minNode.value,r=this.maxNode.value,n=e.getTypeLength(Sd(i)),o=e.getTypeLength(Sd(r));AC=AC||new xi,NC=NC||new xi,AC.setScalar(0),NC.setScalar(0),1===n?AC.setScalar(i):i.isColor?AC.set(i.r,i.g,i.b):AC.set(i.x,i.y,i.z||0,i.w||0),1===o?NC.setScalar(r):r.isColor?NC.set(r.r,r.g,r.b):NC.set(r.x,r.y,r.z||0,r.w||0);const a=4,h=a*t.count,u=new Float32Array(h);for(let e=0;ewp(new EC(e,t)),IC=BC("numWorkgroups","uvec3"),PC=BC("workgroupId","uvec3"),FC=BC("localId","uvec3"),UC=BC("subgroupSize","uint");const OC=Ap(class extends zd{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;!0===s.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}}),zC=()=>OC("workgroup").append(),LC=()=>OC("storage").append(),VC=()=>OC("texture").append();class DC extends Ld{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let s;const i=e.context.assign;if(s=super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}class kC extends zd{constructor(e,t,s=0){super(t),this.bufferType=t,this.bufferCount=s,this.isWorkgroupInfoNode=!0,this.scope=e}label(e){return this.name=e,this}getHash(){return this.uuid}setScope(e){return this.scope=e,this}getInputType(){return`${this.scope}Array`}element(e){return wp(new DC(this,e))}generate(e){return e.getScopedArray(this.name||`${this.scope}Array_${this.id}`,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}const GC=(e,t)=>wp(new kC("Workgroup",e,t));class WC extends Dd{static get type(){return"AtomicFunctionNode"}constructor(e,t,s,i=null){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.storeNode=i}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=this.method,s=this.getNodeType(e),i=this.getInputType(e),r=this.pointerNode,n=this.valueNode,o=[];o.push(`&${r.build(e,i)}`),o.push(n.build(e,i));const a=`${e.getMethod(t,s)}( ${o.join(", ")} )`;if(null!==this.storeNode){const t=this.storeNode.build(e,i);e.addLineFlowCode(`${t} = ${a}`,this)}else e.addLineFlowCode(a,this)}}WC.ATOMIC_LOAD="atomicLoad",WC.ATOMIC_STORE="atomicStore",WC.ATOMIC_ADD="atomicAdd",WC.ATOMIC_SUB="atomicSub",WC.ATOMIC_MAX="atomicMax",WC.ATOMIC_MIN="atomicMin",WC.ATOMIC_AND="atomicAnd",WC.ATOMIC_OR="atomicOr",WC.ATOMIC_XOR="atomicXor";const jC=Ap(WC),HC=(e,t,s,i)=>{const r=jC(e,t,s,i);return r.append(),r},qC=(e,t,s=null)=>HC(WC.ATOMIC_STORE,e,t,s),$C=(e,t,s=null)=>HC(WC.ATOMIC_ADD,e,t,s),XC=(e,t,s=null)=>HC(WC.ATOMIC_SUB,e,t,s),YC=(e,t,s=null)=>HC(WC.ATOMIC_MAX,e,t,s),ZC=(e,t,s=null)=>HC(WC.ATOMIC_MIN,e,t,s),JC=(e,t,s=null)=>HC(WC.ATOMIC_AND,e,t,s),KC=(e,t,s=null)=>HC(WC.ATOMIC_OR,e,t,s),QC=(e,t,s=null)=>HC(WC.ATOMIC_XOR,e,t,s);let eR;function tR(e){eR=eR||new WeakMap;let t=eR.get(e);return void 0===t&&eR.set(e,t={}),t}function sR(e){const t=tR(e);return t.position||(t.position=dm(new Ai).setGroup(um).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld))))}function iR(e){const t=tR(e);return t.targetPosition||(t.targetPosition=dm(new Ai).setGroup(um).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld))))}function rR(e){const t=tR(e);return t.viewPosition||(t.viewPosition=dm(new Ai).setGroup(um).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new Ai,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}const nR=e=>Ly.transformDirection(sR(e).sub(iR(e))),oR=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},aR=new WeakMap;class hR extends zd{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Wp().toVar("totalDiffuse"),this.totalSpecularNode=Wp().toVar("totalSpecular"),this.outgoingLightNode=Wp().toVar("outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getSelf().getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getDataFromNode(this);for(const s of t.nodes)s.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=(e=>e.sort(((e,t)=>e.id-t.id)))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(wp(e));else{let i=null;if(null!==s&&(i=oR(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;aR.has(e)?i=aR.get(e):(i=wp(new s(e)),aR.set(e,i)),t.push(i)}}this._lightNodes=t}setupLights(e,t){for(const s of t)s.build(e)}setup(e){null===this._lightNodes&&this.setupLightsNode(e);const t=e.context,s=t.lightingModel;let i=this.outgoingLightNode;if(s){const{_lightNodes:r,totalDiffuseNode:n,totalSpecularNode:o}=this;t.outgoingLight=i;const a=e.addStack();e.getDataFromNode(this).nodes=a.nodes,s.start(t,a,e),this.setupLights(e,r),s.indirect(t,a,e);const{backdrop:h,backdropAlpha:u}=t,{directDiffuse:l,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=t.reflectedLight;let m=l.add(d);null!==h&&(m=Wp(null!==u?u.mix(m,h):h),t.material.transparent=!0),n.assign(m),o.assign(c.add(p)),i.assign(n.add(o)),s.finish(t,a,e),i=i.bypass(e.removeStack())}return i}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}const uR=(e=[])=>wp(new hR).setLights(e),lR=Cp((({depthTexture:e,shadowCoord:t})=>By(e,t.xy).compare(t.z))),cR=Cp((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>By(e,t).compare(s),r=Dx("mapSize","vec2",s).setGroup(um),n=Dx("radius","float",s).setGroup(um),o=Vp(1).div(r),a=o.x.negate().mul(n),h=o.y.negate().mul(n),u=o.x.mul(n),l=o.y.mul(n),c=a.div(2),d=h.div(2),p=u.div(2),m=l.div(2);return Ym(i(t.xy.add(Vp(a,h)),t.z),i(t.xy.add(Vp(0,h)),t.z),i(t.xy.add(Vp(u,h)),t.z),i(t.xy.add(Vp(c,d)),t.z),i(t.xy.add(Vp(0,d)),t.z),i(t.xy.add(Vp(p,d)),t.z),i(t.xy.add(Vp(a,0)),t.z),i(t.xy.add(Vp(c,0)),t.z),i(t.xy,t.z),i(t.xy.add(Vp(p,0)),t.z),i(t.xy.add(Vp(u,0)),t.z),i(t.xy.add(Vp(c,m)),t.z),i(t.xy.add(Vp(0,m)),t.z),i(t.xy.add(Vp(p,m)),t.z),i(t.xy.add(Vp(a,l)),t.z),i(t.xy.add(Vp(0,l)),t.z),i(t.xy.add(Vp(u,l)),t.z)).mul(1/17)})),dR=Cp((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>By(e,t).compare(s),r=Dx("mapSize","vec2",s).setGroup(um),n=Vp(1).div(r),o=n.x,a=n.y,h=t.xy,u=Og(h.mul(r).add(.5));return h.subAssign(u.mul(n)),Ym(i(h,t.z),i(h.add(Vp(o,0)),t.z),i(h.add(Vp(0,a)),t.z),i(h.add(n),t.z),vf(i(h.add(Vp(o.negate(),0)),t.z),i(h.add(Vp(o.mul(2),0)),t.z),u.x),vf(i(h.add(Vp(o.negate(),a)),t.z),i(h.add(Vp(o.mul(2),a)),t.z),u.x),vf(i(h.add(Vp(0,a.negate())),t.z),i(h.add(Vp(0,a.mul(2))),t.z),u.y),vf(i(h.add(Vp(o,a.negate())),t.z),i(h.add(Vp(o,a.mul(2))),t.z),u.y),vf(vf(i(h.add(Vp(o.negate(),a.negate())),t.z),i(h.add(Vp(o.mul(2),a.negate())),t.z),u.x),vf(i(h.add(Vp(o.negate(),a.mul(2))),t.z),i(h.add(Vp(o.mul(2),a.mul(2))),t.z),u.x),u.y)).mul(1/9)})),pR=Cp((({depthTexture:e,shadowCoord:t})=>{const s=Up(1).toVar(),i=By(e).uv(t.xy).rg,r=af(t.z,i.x);return Ip(r.notEqual(Up(1)),(()=>{const e=t.z.sub(i.x),n=nf(0,i.y.mul(i.y));let o=n.div(n.add(e.mul(e)));o=Tf(Zm(o,.3).div(.95-.3)),s.assign(Tf(nf(r,o)))})),s})),mR=Cp((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Up(0).toVar(),n=Up(0).toVar(),o=e.lessThanEqual(Up(1)).select(Up(0),Up(2).div(e.sub(1))),a=e.lessThanEqual(Up(1)).select(Up(0),Up(-1));xv({start:Op(0),end:Op(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Up(e).mul(o)),u=i.uv(Ym(zv.xy,Vp(0,h).mul(t)).div(s)).x;r.addAssign(u),n.addAssign(u.mul(u))})),r.divAssign(e),n.divAssign(e);const h=Bg(n.sub(r.mul(r)));return Vp(r,h)})),gR=Cp((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Up(0).toVar(),n=Up(0).toVar(),o=e.lessThanEqual(Up(1)).select(Up(0),Up(2).div(e.sub(1))),a=e.lessThanEqual(Up(1)).select(Up(0),Up(-1));xv({start:Op(0),end:Op(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Up(e).mul(o)),u=i.uv(Ym(zv.xy,Vp(h,0).mul(t)).div(s));r.addAssign(u.x),n.addAssign(Ym(u.y.mul(u.y),u.x.mul(u.x)))})),r.divAssign(e),n.divAssign(e);const h=Bg(n.sub(r.mul(r)));return Vp(r,h)})),fR=[lR,cR,dR,pR];let yR=null;const xR=new MM;class bR extends zd{static get type(){return"ShadowNode"}constructor(e,t=null){super(),this.light=e,this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this.updateBeforeType=Ed.RENDER,this._node=null,this.isShadowNode=!0}setupShadow(e){const{object:t,renderer:s}=e;null===yR&&(yR=new uT,yR.fragmentNode=$p(0,0,0,1),yR.isShadowNodeMaterial=!0,yR.name="ShadowMaterial");const i=this.shadow,r=s.shadowMap.type,n=new Xa(i.mapSize.width,i.mapSize.height);n.compareFunction=ys;const o=e.createRenderTarget(i.mapSize.width,i.mapSize.height);if(o.depthTexture=n,i.camera.updateProjectionMatrix(),3===r){n.compareFunction=null,this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$e,type:Pe}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$e,type:Pe});const t=By(n),s=By(this.vsmShadowMapVertical.texture),r=Dx("blurSamples","float",i).setGroup(um),o=Dx("radius","float",i).setGroup(um),a=Dx("mapSize","vec2",i).setGroup(um);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new uT);h.fragmentNode=mR({samples:r,radius:o,size:a,shadowPass:t}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new uT),h.fragmentNode=gR({samples:r,radius:o,size:a,shadowPass:s}).context(e.getSharedContext()),h.name="VSMHorizontal"}const a=Dx("intensity","float",i).setGroup(um),h=Dx("bias","float",i).setGroup(um),u=Dx("normalBias","float",i).setGroup(um),l=t.material.shadowPositionNode||hx;let c,d=dm(i.matrix).setGroup(um).mul(l.add(Tx.mul(u)));if(i.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)d=d.xyz.div(d.w),c=d.z,s.coordinateSystem===Os&&(c=c.mul(2).sub(1));else{const e=d.w;d=d.xy.div(e);const t=dm("float").onRenderUpdate((()=>i.camera.near)),s=dm("float").onRenderUpdate((()=>i.camera.far));c=iT(e,t,s)}d=Wp(d.x,d.y.oneMinus(),c.add(h));const p=d.x.greaterThanEqual(0).and(d.x.lessThanEqual(1)).and(d.y.greaterThanEqual(0)).and(d.y.lessThanEqual(1)).and(d.z.lessThanEqual(1)),m=i.filterNode||fR[s.shadowMap.type]||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const g=By(o.texture,d),f=p.select(m({depthTexture:3===r?this.vsmShadowMapHorizontal.texture:n,shadowCoord:d,shadow:i}),Up(1));return this.shadowMap=o,this.shadow.map=o,vf(1,f.rgb.mix(g,1),a.mul(g.a))}setup(e){if(!1!==e.renderer.shadowMap.enabled)return null!==this._node?this._node:this._node=this.setupShadow(e)}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:o}=e,a=r.shadowMap.type,h=t.depthTexture.version;this._depthVersionCached=h;const u=n.overrideMaterial;n.overrideMaterial=yR,t.setSize(i.mapSize.width,i.mapSize.height),i.updateMatrices(s),i.camera.layers.mask=o.layers.mask;const l=r.getRenderTarget(),c=r.getRenderObjectFunction();r.setRenderObjectFunction(((e,...t)=>{(!0===e.castShadow||e.receiveShadow&&3===a)&&r.renderObject(e,...t)})),r.setRenderTarget(t),r.render(n,i.camera),r.setRenderObjectFunction(c),!0!==s.isPointLight&&3===a&&this.vsmPass(r),r.setRenderTarget(l),n.overrideMaterial=u}vsmPass(e){const{shadow:t}=this;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height),e.setRenderTarget(this.vsmShadowMapVertical),xR.material=this.vsmMaterialVertical,xR.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),xR.material=this.vsmMaterialHorizontal,xR.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),this.updateBeforeType=Ed.NONE}updateBefore(e){const{shadow:t}=this;(t.needsUpdate||t.autoUpdate)&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const vR=(e,t)=>wp(new bR(e,t));class TR extends Nv{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.updateType=Ed.FRAME,this.light=e,this.color=new Xr,this.colorNode=dm(this.color).setGroup(um),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0}getCacheKey(){return Td(super.getCacheKey(),this.light.id,this.light.castShadow?1:0)}getHash(){return this.light.uuid}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const e=vR(this.light);this.shadowNode=e,this.shadowColorNode=s=this.colorNode.mul(e),this.baseColorNode=this.colorNode}this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&this.shadowNode.dispose()}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const _R=Cp((e=>{const{lightDistance:t,cutoffDistance:s,decayExponent:i}=e,r=t.pow(i).max(.01).reciprocal();return s.greaterThan(0).select(r.mul(t.div(s).pow4().oneMinus().clamp().pow2()),r)})),wR=Cp((({color:e,lightViewPosition:t,cutoffDistance:s,decayExponent:i},r)=>{const n=r.context.lightingModel,o=t.sub(lx),a=o.normalize(),h=o.length(),u=_R({lightDistance:h,cutoffDistance:s,decayExponent:i}),l=e.mul(u),c=r.context.reflectedLight;n.direct({lightDirection:a,lightColor:l,reflectedLight:c},r.stack,r)}));class SR extends TR{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=dm(0).setGroup(um),this.decayExponentNode=dm(0).setGroup(um)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setup(){wR({color:this.colorNode,lightViewPosition:rR(this.light),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode}).append()}}const MR=Cp((([e=t()])=>{const t=e.mul(2),s=t.x.floor(),i=t.y.floor();return s.add(i).mod(2).sign()})),AR=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=Lp(e).toVar();return Ef(n,r,i)})).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),NR=Cp((([e,t])=>{const s=Lp(t).toVar(),i=Up(e).toVar();return Ef(s,i.negate(),i)})).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),CR=Cp((([e])=>{const t=Up(e).toVar();return Op(Pg(t))})).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),RR=Cp((([e,t])=>{const s=Up(e).toVar();return t.assign(CR(s)),s.sub(Up(t))})),ER=VS([Cp((([e,t,s,i,r,n])=>{const o=Up(n).toVar(),a=Up(r).toVar(),h=Up(i).toVar(),u=Up(s).toVar(),l=Up(t).toVar(),c=Up(e).toVar(),d=Up(Zm(1,a)).toVar();return Zm(1,o).mul(c.mul(d).add(l.mul(a))).add(o.mul(u.mul(d).add(h.mul(a))))})).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"}]}),Cp((([e,t,s,i,r,n])=>{const o=Up(n).toVar(),a=Up(r).toVar(),h=Wp(i).toVar(),u=Wp(s).toVar(),l=Wp(t).toVar(),c=Wp(e).toVar(),d=Up(Zm(1,a)).toVar();return Zm(1,o).mul(c.mul(d).add(l.mul(a))).add(o.mul(u.mul(d).add(h.mul(a))))})).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"}]})]),BR=VS([Cp((([e,t,s,i,r,n,o,a,h,u,l])=>{const c=Up(l).toVar(),d=Up(u).toVar(),p=Up(h).toVar(),m=Up(a).toVar(),g=Up(o).toVar(),f=Up(n).toVar(),y=Up(r).toVar(),x=Up(i).toVar(),b=Up(s).toVar(),v=Up(t).toVar(),T=Up(e).toVar(),_=Up(Zm(1,p)).toVar(),w=Up(Zm(1,d)).toVar();return Up(Zm(1,c)).toVar().mul(w.mul(T.mul(_).add(v.mul(p))).add(d.mul(b.mul(_).add(x.mul(p))))).add(c.mul(w.mul(y.mul(_).add(f.mul(p))).add(d.mul(g.mul(_).add(m.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"}]}),Cp((([e,t,s,i,r,n,o,a,h,u,l])=>{const c=Up(l).toVar(),d=Up(u).toVar(),p=Up(h).toVar(),m=Wp(a).toVar(),g=Wp(o).toVar(),f=Wp(n).toVar(),y=Wp(r).toVar(),x=Wp(i).toVar(),b=Wp(s).toVar(),v=Wp(t).toVar(),T=Wp(e).toVar(),_=Up(Zm(1,p)).toVar(),w=Up(Zm(1,d)).toVar();return Up(Zm(1,c)).toVar().mul(w.mul(T.mul(_).add(v.mul(p))).add(d.mul(b.mul(_).add(x.mul(p))))).add(c.mul(w.mul(y.mul(_).add(f.mul(p))).add(d.mul(g.mul(_).add(m.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"}]})]),IR=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=zp(e).toVar(),o=zp(n.bitAnd(zp(7))).toVar(),a=Up(AR(o.lessThan(zp(4)),r,i)).toVar(),h=Up(Jm(2,AR(o.lessThan(zp(4)),i,r))).toVar();return NR(a,Lp(o.bitAnd(zp(1)))).add(NR(h,Lp(o.bitAnd(zp(2)))))})).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),PR=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Up(t).toVar(),a=zp(e).toVar(),h=zp(a.bitAnd(zp(15))).toVar(),u=Up(AR(h.lessThan(zp(8)),o,n)).toVar(),l=Up(AR(h.lessThan(zp(4)),n,AR(h.equal(zp(12)).or(h.equal(zp(14))),o,r))).toVar();return NR(u,Lp(h.bitAnd(zp(1)))).add(NR(l,Lp(h.bitAnd(zp(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"}]}),FR=VS([IR,PR]),UR=Cp((([e,t,s])=>{const i=Up(s).toVar(),r=Up(t).toVar(),n=Hp(e).toVar();return Wp(FR(n.x,r,i),FR(n.y,r,i),FR(n.z,r,i))})).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),OR=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Up(t).toVar(),a=Hp(e).toVar();return Wp(FR(a.x,o,n,r),FR(a.y,o,n,r),FR(a.z,o,n,r))})).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"}]}),zR=VS([UR,OR]),LR=Cp((([e])=>{const t=Up(e).toVar();return Jm(.6616,t)})).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),VR=Cp((([e])=>{const t=Up(e).toVar();return Jm(.982,t)})).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),DR=VS([LR,Cp((([e])=>{const t=Wp(e).toVar();return Jm(.6616,t)})).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),kR=VS([VR,Cp((([e])=>{const t=Wp(e).toVar();return Jm(.982,t)})).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),GR=Cp((([e,t])=>{const s=Op(t).toVar(),i=zp(e).toVar();return i.shiftLeft(s).bitOr(i.shiftRight(Op(32).sub(s)))})).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),WR=Cp((([e,t,s])=>{e.subAssign(s),e.bitXorAssign(GR(s,Op(4))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(GR(e,Op(6))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(GR(t,Op(8))),t.addAssign(e),e.subAssign(s),e.bitXorAssign(GR(s,Op(16))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(GR(e,Op(19))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(GR(t,Op(4))),t.addAssign(e)})),jR=Cp((([e,t,s])=>{const i=zp(s).toVar(),r=zp(t).toVar(),n=zp(e).toVar();return i.bitXorAssign(r),i.subAssign(GR(r,Op(14))),n.bitXorAssign(i),n.subAssign(GR(i,Op(11))),r.bitXorAssign(n),r.subAssign(GR(n,Op(25))),i.bitXorAssign(r),i.subAssign(GR(r,Op(16))),n.bitXorAssign(i),n.subAssign(GR(i,Op(4))),r.bitXorAssign(n),r.subAssign(GR(n,Op(14))),i.bitXorAssign(r),i.subAssign(GR(r,Op(24))),i})).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),HR=Cp((([e])=>{const t=zp(e).toVar();return Up(t).div(Up(zp(Op(4294967295))))})).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),qR=Cp((([e])=>{const t=Up(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"}]}),$R=VS([Cp((([e])=>{const t=Op(e).toVar(),s=zp(zp(1)).toVar(),i=zp(zp(Op(3735928559)).add(s.shiftLeft(zp(2))).add(zp(13))).toVar();return jR(i.add(zp(t)),i,i)})).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),Cp((([e,t])=>{const s=Op(t).toVar(),i=Op(e).toVar(),r=zp(zp(2)).toVar(),n=zp().toVar(),o=zp().toVar(),a=zp().toVar();return n.assign(o.assign(a.assign(zp(Op(3735928559)).add(r.shiftLeft(zp(2))).add(zp(13))))),n.addAssign(zp(i)),o.addAssign(zp(s)),jR(n,o,a)})).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Op(t).toVar(),n=Op(e).toVar(),o=zp(zp(3)).toVar(),a=zp().toVar(),h=zp().toVar(),u=zp().toVar();return a.assign(h.assign(u.assign(zp(Op(3735928559)).add(o.shiftLeft(zp(2))).add(zp(13))))),a.addAssign(zp(n)),h.addAssign(zp(r)),u.addAssign(zp(i)),jR(a,h,u)})).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Cp((([e,t,s,i])=>{const r=Op(i).toVar(),n=Op(s).toVar(),o=Op(t).toVar(),a=Op(e).toVar(),h=zp(zp(4)).toVar(),u=zp().toVar(),l=zp().toVar(),c=zp().toVar();return u.assign(l.assign(c.assign(zp(Op(3735928559)).add(h.shiftLeft(zp(2))).add(zp(13))))),u.addAssign(zp(a)),l.addAssign(zp(o)),c.addAssign(zp(n)),WR(u,l,c),u.addAssign(zp(r)),jR(u,l,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"}]}),Cp((([e,t,s,i,r])=>{const n=Op(r).toVar(),o=Op(i).toVar(),a=Op(s).toVar(),h=Op(t).toVar(),u=Op(e).toVar(),l=zp(zp(5)).toVar(),c=zp().toVar(),d=zp().toVar(),p=zp().toVar();return c.assign(d.assign(p.assign(zp(Op(3735928559)).add(l.shiftLeft(zp(2))).add(zp(13))))),c.addAssign(zp(u)),d.addAssign(zp(h)),p.addAssign(zp(a)),WR(c,d,p),c.addAssign(zp(o)),d.addAssign(zp(n)),jR(c,d,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"}]})]),XR=VS([Cp((([e,t])=>{const s=Op(t).toVar(),i=Op(e).toVar(),r=zp($R(i,s)).toVar(),n=Hp().toVar();return n.x.assign(r.bitAnd(Op(255))),n.y.assign(r.shiftRight(Op(8)).bitAnd(Op(255))),n.z.assign(r.shiftRight(Op(16)).bitAnd(Op(255))),n})).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Op(t).toVar(),n=Op(e).toVar(),o=zp($R(n,r,i)).toVar(),a=Hp().toVar();return a.x.assign(o.bitAnd(Op(255))),a.y.assign(o.shiftRight(Op(8)).bitAnd(Op(255))),a.z.assign(o.shiftRight(Op(16)).bitAnd(Op(255))),a})).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),YR=VS([Cp((([e])=>{const t=Vp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Up(RR(t.x,s)).toVar(),n=Up(RR(t.y,i)).toVar(),o=Up(qR(r)).toVar(),a=Up(qR(n)).toVar(),h=Up(ER(FR($R(s,i),r,n),FR($R(s.add(Op(1)),i),r.sub(1),n),FR($R(s,i.add(Op(1))),r,n.sub(1)),FR($R(s.add(Op(1)),i.add(Op(1))),r.sub(1),n.sub(1)),o,a)).toVar();return DR(h)})).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Op().toVar(),n=Up(RR(t.x,s)).toVar(),o=Up(RR(t.y,i)).toVar(),a=Up(RR(t.z,r)).toVar(),h=Up(qR(n)).toVar(),u=Up(qR(o)).toVar(),l=Up(qR(a)).toVar(),c=Up(BR(FR($R(s,i,r),n,o,a),FR($R(s.add(Op(1)),i,r),n.sub(1),o,a),FR($R(s,i.add(Op(1)),r),n,o.sub(1),a),FR($R(s.add(Op(1)),i.add(Op(1)),r),n.sub(1),o.sub(1),a),FR($R(s,i,r.add(Op(1))),n,o,a.sub(1)),FR($R(s.add(Op(1)),i,r.add(Op(1))),n.sub(1),o,a.sub(1)),FR($R(s,i.add(Op(1)),r.add(Op(1))),n,o.sub(1),a.sub(1)),FR($R(s.add(Op(1)),i.add(Op(1)),r.add(Op(1))),n.sub(1),o.sub(1),a.sub(1)),h,u,l)).toVar();return kR(c)})).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),ZR=VS([Cp((([e])=>{const t=Vp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Up(RR(t.x,s)).toVar(),n=Up(RR(t.y,i)).toVar(),o=Up(qR(r)).toVar(),a=Up(qR(n)).toVar(),h=Wp(ER(zR(XR(s,i),r,n),zR(XR(s.add(Op(1)),i),r.sub(1),n),zR(XR(s,i.add(Op(1))),r,n.sub(1)),zR(XR(s.add(Op(1)),i.add(Op(1))),r.sub(1),n.sub(1)),o,a)).toVar();return DR(h)})).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op().toVar(),i=Op().toVar(),r=Op().toVar(),n=Up(RR(t.x,s)).toVar(),o=Up(RR(t.y,i)).toVar(),a=Up(RR(t.z,r)).toVar(),h=Up(qR(n)).toVar(),u=Up(qR(o)).toVar(),l=Up(qR(a)).toVar(),c=Wp(BR(zR(XR(s,i,r),n,o,a),zR(XR(s.add(Op(1)),i,r),n.sub(1),o,a),zR(XR(s,i.add(Op(1)),r),n,o.sub(1),a),zR(XR(s.add(Op(1)),i.add(Op(1)),r),n.sub(1),o.sub(1),a),zR(XR(s,i,r.add(Op(1))),n,o,a.sub(1)),zR(XR(s.add(Op(1)),i,r.add(Op(1))),n.sub(1),o,a.sub(1)),zR(XR(s,i.add(Op(1)),r.add(Op(1))),n,o.sub(1),a.sub(1)),zR(XR(s.add(Op(1)),i.add(Op(1)),r.add(Op(1))),n.sub(1),o.sub(1),a.sub(1)),h,u,l)).toVar();return kR(c)})).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),JR=VS([Cp((([e])=>{const t=Up(e).toVar(),s=Op(CR(t)).toVar();return HR($R(s))})).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),Cp((([e])=>{const t=Vp(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar();return HR($R(s,i))})).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar(),r=Op(CR(t.z)).toVar();return HR($R(s,i,r))})).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),Cp((([e])=>{const t=$p(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar(),r=Op(CR(t.z)).toVar(),n=Op(CR(t.w)).toVar();return HR($R(s,i,r,n))})).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),KR=VS([Cp((([e])=>{const t=Up(e).toVar(),s=Op(CR(t)).toVar();return Wp(HR($R(s,Op(0))),HR($R(s,Op(1))),HR($R(s,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),Cp((([e])=>{const t=Vp(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar();return Wp(HR($R(s,i,Op(0))),HR($R(s,i,Op(1))),HR($R(s,i,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Cp((([e])=>{const t=Wp(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar(),r=Op(CR(t.z)).toVar();return Wp(HR($R(s,i,r,Op(0))),HR($R(s,i,r,Op(1))),HR($R(s,i,r,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Cp((([e])=>{const t=$p(e).toVar(),s=Op(CR(t.x)).toVar(),i=Op(CR(t.y)).toVar(),r=Op(CR(t.z)).toVar(),n=Op(CR(t.w)).toVar();return Wp(HR($R(s,i,r,n,Op(0))),HR($R(s,i,r,n,Op(1))),HR($R(s,i,r,n,Op(2))))})).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),QR=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Up(0).toVar(),u=Up(1).toVar();return xv(o,(()=>{h.addAssign(u.mul(YR(a))),u.mulAssign(r),a.mulAssign(n)})),h})).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"}]}),eE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Wp(0).toVar(),u=Up(1).toVar();return xv(o,(()=>{h.addAssign(u.mul(ZR(a))),u.mulAssign(r),a.mulAssign(n)})),h})).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"}]}),tE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar();return Vp(QR(a,o,n,r),QR(a.add(Wp(Op(19),Op(193),Op(17))),o,n,r))})).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"}]}),sE=Cp((([e,t,s,i])=>{const r=Up(i).toVar(),n=Up(s).toVar(),o=Op(t).toVar(),a=Wp(e).toVar(),h=Wp(eE(a,o,n,r)).toVar(),u=Up(QR(a.add(Wp(Op(19),Op(193),Op(17))),o,n,r)).toVar();return $p(h,u)})).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"}]}),iE=Cp((([e,t,s,i,r,n,o])=>{const a=Op(o).toVar(),h=Up(n).toVar(),u=Op(r).toVar(),l=Op(i).toVar(),c=Op(s).toVar(),d=Op(t).toVar(),p=Vp(e).toVar(),m=Wp(KR(Vp(d.add(l),c.add(u)))).toVar(),g=Vp(m.x,m.y).toVar();g.subAssign(.5),g.mulAssign(h),g.addAssign(.5);const f=Vp(Vp(Up(d),Up(c)).add(g)).toVar(),y=Vp(f.sub(p)).toVar();return Ip(a.equal(Op(2)),(()=>Wg(y.x).add(Wg(y.y)))),Ip(a.equal(Op(3)),(()=>nf(Wg(y.x),Wg(y.y)))),cf(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"}]}),rE=VS([iE,Cp((([e,t,s,i,r,n,o,a,h])=>{const u=Op(h).toVar(),l=Up(a).toVar(),c=Op(o).toVar(),d=Op(n).toVar(),p=Op(r).toVar(),m=Op(i).toVar(),g=Op(s).toVar(),f=Op(t).toVar(),y=Wp(e).toVar(),x=Wp(KR(Wp(f.add(p),g.add(d),m.add(c)))).toVar();x.subAssign(.5),x.mulAssign(l),x.addAssign(.5);const b=Wp(Wp(Up(f),Up(g),Up(m)).add(x)).toVar(),v=Wp(b.sub(y)).toVar();return Ip(u.equal(Op(2)),(()=>Wg(v.x).add(Wg(v.y)).add(Wg(v.z)))),Ip(u.equal(Op(3)),(()=>nf(nf(Wg(v.x),Wg(v.y)),Wg(v.z)))),cf(v,v)})).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"}]})]),nE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(RR(n.x,o),RR(n.y,a)).toVar(),u=Up(1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(rE(h,e,t,o,a,r,i)).toVar();u.assign(rf(u,s))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),oE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(RR(n.x,o),RR(n.y,a)).toVar(),u=Vp(1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(rE(h,e,t,o,a,r,i)).toVar();Ip(s.lessThan(u.x),(()=>{u.y.assign(u.x),u.x.assign(s)})).ElseIf(s.lessThan(u.y),(()=>{u.y.assign(s)}))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),aE=Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Vp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Vp(RR(n.x,o),RR(n.y,a)).toVar(),u=Wp(1e6,1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{const s=Up(rE(h,e,t,o,a,r,i)).toVar();Ip(s.lessThan(u.x),(()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(s)})).ElseIf(s.lessThan(u.y),(()=>{u.z.assign(u.y),u.y.assign(s)})).ElseIf(s.lessThan(u.z),(()=>{u.z.assign(s)}))}))})),Ip(i.equal(Op(0)),(()=>{u.assign(Bg(u))})),u})).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),hE=VS([nE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(RR(n.x,o),RR(n.y,a),RR(n.z,h)).toVar(),l=Up(1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(rE(u,e,t,s,o,a,h,r,i)).toVar();l.assign(rf(l,n))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),uE=VS([oE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(RR(n.x,o),RR(n.y,a),RR(n.z,h)).toVar(),l=Vp(1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(rE(u,e,t,s,o,a,h,r,i)).toVar();Ip(n.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(n)})).ElseIf(n.lessThan(l.y),(()=>{l.y.assign(n)}))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),lE=VS([aE,Cp((([e,t,s])=>{const i=Op(s).toVar(),r=Up(t).toVar(),n=Wp(e).toVar(),o=Op().toVar(),a=Op().toVar(),h=Op().toVar(),u=Wp(RR(n.x,o),RR(n.y,a),RR(n.z,h)).toVar(),l=Wp(1e6,1e6,1e6).toVar();return xv({start:-1,end:Op(1),name:"x",condition:"<="},(({x:e})=>{xv({start:-1,end:Op(1),name:"y",condition:"<="},(({y:t})=>{xv({start:-1,end:Op(1),name:"z",condition:"<="},(({z:s})=>{const n=Up(rE(u,e,t,s,o,a,h,r,i)).toVar();Ip(n.lessThan(l.x),(()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(n)})).ElseIf(n.lessThan(l.y),(()=>{l.z.assign(l.y),l.y.assign(n)})).ElseIf(n.lessThan(l.z),(()=>{l.z.assign(n)}))}))}))})),Ip(i.equal(Op(0)),(()=>{l.assign(Bg(l))})),l})).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),cE=Cp((([e])=>{const t=e.y,s=e.z,i=Wp().toVar();return Ip(t.lessThan(1e-4),(()=>{i.assign(Wp(s,s,s))})).Else((()=>{let r=e.x;r=r.sub(Pg(r)).mul(6).toVar();const n=Op(Kg(r)),o=r.sub(Up(n)),a=s.mul(t.oneMinus()),h=s.mul(t.mul(o).oneMinus()),u=s.mul(t.mul(o.oneMinus()).oneMinus());Ip(n.equal(Op(0)),(()=>{i.assign(Wp(s,u,a))})).ElseIf(n.equal(Op(1)),(()=>{i.assign(Wp(h,s,a))})).ElseIf(n.equal(Op(2)),(()=>{i.assign(Wp(a,s,u))})).ElseIf(n.equal(Op(3)),(()=>{i.assign(Wp(a,h,s))})).ElseIf(n.equal(Op(4)),(()=>{i.assign(Wp(u,a,s))})).Else((()=>{i.assign(Wp(s,a,h))}))})),i})).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),dE=Cp((([e])=>{const t=Wp(e).toVar(),s=Up(t.x).toVar(),i=Up(t.y).toVar(),r=Up(t.z).toVar(),n=Up(rf(s,rf(i,r))).toVar(),o=Up(nf(s,nf(i,r))).toVar(),a=Up(o.sub(n)).toVar(),h=Up().toVar(),u=Up().toVar(),l=Up().toVar();return l.assign(o),Ip(o.greaterThan(0),(()=>{u.assign(a.div(o))})).Else((()=>{u.assign(0)})),Ip(u.lessThanEqual(0),(()=>{h.assign(0)})).Else((()=>{Ip(s.greaterThanEqual(o),(()=>{h.assign(i.sub(r).div(a))})).ElseIf(i.greaterThanEqual(o),(()=>{h.assign(Ym(2,r.sub(s).div(a)))})).Else((()=>{h.assign(Ym(4,s.sub(i).div(a)))})),h.mulAssign(1/6),Ip(h.lessThan(0),(()=>{h.addAssign(1)}))})),Wp(h,u,l)})).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),pE=Cp((([e])=>{const t=Wp(e).toVar(),s=qp(ig(t,Wp(.04045))).toVar(),i=Wp(t.div(12.92)).toVar(),r=Wp(pf(nf(t.add(Wp(.055)),Wp(0)).div(1.055),Wp(2.4))).toVar();return vf(i,r,s)})).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),mE=(e,t)=>{e=Up(e),t=Up(t);const s=Vp(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Sf(e.sub(s),e.add(s),t)},gE=(e,t,s,i)=>vf(e,t,s[i].clamp()),fE=(e,t,s=My())=>gE(e,t,s,"x"),yE=(e,t,s=My())=>gE(e,t,s,"y"),xE=(e,t,s,i,r)=>vf(e,t,mE(s,i[r])),bE=(e,t,s,i=My())=>xE(e,t,s,i,"x"),vE=(e,t,s,i=My())=>xE(e,t,s,i,"y"),TE=(e=1,t=0,s=My())=>s.mul(e).add(t),_E=(e,t=1)=>(e=Up(e)).abs().pow(t).mul(e.sign()),wE=(e,t=1,s=.5)=>Up(e).sub(s).mul(t).add(s),SE=(e=My(),t=1,s=0)=>YR(e.convert("vec2|vec3")).mul(t).add(s),ME=(e=My(),t=1,s=0)=>ZR(e.convert("vec2|vec3")).mul(t).add(s),AE=(e=My(),t=1,s=0)=>{e=e.convert("vec2|vec3");return $p(ZR(e),YR(e.add(Vp(19,73)))).mul(t).add(s)},NE=(e=My(),t=1)=>hE(e.convert("vec2|vec3"),t,Op(1)),CE=(e=My(),t=1)=>uE(e.convert("vec2|vec3"),t,Op(1)),RE=(e=My(),t=1)=>lE(e.convert("vec2|vec3"),t,Op(1)),EE=(e=My())=>JR(e.convert("vec2|vec3")),BE=(e=My(),t=3,s=2,i=.5,r=1)=>QR(e,Op(t),s,i).mul(r),IE=(e=My(),t=3,s=2,i=.5,r=1)=>tE(e,Op(t),s,i).mul(r),PE=(e=My(),t=3,s=2,i=.5,r=1)=>eE(e,Op(t),s,i).mul(r),FE=(e=My(),t=3,s=2,i=.5,r=1)=>sE(e,Op(t),s,i).mul(r),UE=Cp((([e,t])=>{const s=e.x,i=e.y,r=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(i)),n=n.add(t.element(2).mul(1.023328).mul(r)),n=n.add(t.element(3).mul(1.023328).mul(s)),n=n.add(t.element(4).mul(.858086).mul(s).mul(i)),n=n.add(t.element(5).mul(.858086).mul(i).mul(r)),n=n.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(s).mul(r)),n=n.add(t.element(8).mul(.429043).mul(Jm(s,s).sub(Jm(i,i)))),n})),OE=new xS;class zE extends jw{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===r)i._clearColor.getRGB(OE,Jt),OE.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(OE,Jt),OE.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;OE.copy(i._clearColor);let o=s.backgroundMesh;if(void 0===o){const e=Pf($p(n).mul(LM),{getUV:()=>bx,getTextureLevel:()=>zM});let t=tv();t=t.setZ(t.w);const i=new uT;i.name="Background.material",i.side=d,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.lights=!1,i.vertexNode=t,i.colorNode=e,s.backgroundMeshNode=e,s.backgroundMesh=o=new On(new cu(1,32,32),i),o.frustumCulled=!1,o.name="Background.mesh",o.onBeforeRender=function(e,t,s){this.matrixWorld.copyPosition(s.matrixWorld)}}const a=n.getCacheKey();s.backgroundCacheKey!==a&&(s.backgroundMeshNode.node=$p(n).mul(LM),s.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null)}else console.error("THREE.Renderer: Unsupported background configuration.",r);if(!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=OE.r,e.g=OE.g,e.b=OE.b,e.a=OE.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(e.r*=e.a,e.g*=e.a,e.b*=e.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,s.clearColor=!0===i.autoClearColor,s.clearDepth=!0===i.autoClearDepth,s.clearStencil=!0===i.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let LE=0;class VE{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=LE++}}class DE{constructor(e,t,s,i,r,n,o,a,h,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=o,this.updateAfterNodes=a,this.monitor=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new VE(t.name,[],t.index,t);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class kE{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class GE{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf()}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 WE{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class jE extends WE{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class HE{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let qE=0;class $E{constructor(e=null){this.id=qE++,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 XE{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 YE extends XE{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class ZE extends XE{constructor(e,t=new Ys){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class JE extends XE{constructor(e,t=new Ai){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class KE extends XE{constructor(e,t=new xi){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class QE extends XE{constructor(e,t=new Xr){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class eB extends XE{constructor(e,t=new Zs){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class tB extends XE{constructor(e,t=new sr){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class sB extends YE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class iB extends ZE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class rB extends JE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class nB extends KE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class oB extends QE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class aB extends eB{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class hB extends tB{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}const uB=[.125,.215,.35,.446,.526,.582],lB=20,cB=new wl(-1,1,1,-1,0,1),dB=new Hn(90,1),pB=new Xr;let mB=null,gB=0,fB=0;const yB=(1+Math.sqrt(5))/2,xB=1/yB,bB=[new Ai(-yB,xB,0),new Ai(yB,xB,0),new Ai(-xB,0,yB),new Ai(xB,0,yB),new Ai(0,yB,-xB),new Ai(0,yB,xB),new Ai(-1,1,-1),new Ai(1,1,-1),new Ai(-1,1,1),new Ai(1,1,1)],vB=[3,1,5,0,4,2],TB=Y_(My(),Sy("faceIndex")).normalize(),_B=Wp(TB.x,TB.y.negate(),TB.z);class wB{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}fromScene(e,t=0,s=.1,i=100){mB=this._renderer.getRenderTarget(),gB=this._renderer.getActiveCubeFace(),fB=this._renderer.getActiveMipmapLevel(),this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,s,i,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=NB(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=CB(),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())}_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?h=uB[a-e+4-1]:0===a&&(h=0),i.push(h);const u=1/(o-2),l=-u,c=1+u,d=[l,l,c,l,c,c,l,l,c,c,l,c],p=6,m=6,g=3,f=2,y=1,x=new Float32Array(g*m*p),b=new Float32Array(f*m*p),v=new Float32Array(y*m*p);for(let e=0;e2?0:-1,i=[t,s,0,t+2/3,s,0,t+2/3,s+1,0,t,s,0,t+2/3,s+1,0,t,s+1,0],r=vB[e];x.set(i,g*m*r),b.set(d,f*m*r);const n=[r,r,r,r,r,r];v.set(n,y*m*r)}const T=new Sn;T.setAttribute("position",new an(x,g)),T.setAttribute("uv",new an(b,f)),T.setAttribute("faceIndex",new an(v,y)),t.push(T),r.push(new On(T,null)),n>4&&n--}return{lodPlanes:t,sizeLods:s,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,s){const i=Ox(new Array(lB).fill(0)),r=dm(new Ai(0,1,0)),n=dm(0),o=Up(lB),a=dm(0),h=dm(1),u=By(null),l=dm(0),c=Up(1/t),d=Up(1/s),p=Up(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:_B,dTheta:n,samples:h,envMap:u,mipInt:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=AB("blur");return g.uniforms=m,g.fragmentNode=Q_({...m,latitudinal:a.equal(1)}),g}(i,e,t)}return i}async _compileMaterial(e){const t=new On(this._lodPlanes[0],e);await this._renderer.compile(t,cB)}_sceneToCubeUV(e,t,s,i){const r=dB;r.near=t,r.far=s;const n=[-1,1,-1,-1,-1,-1],o=[1,1,1,-1,-1,-1],a=this._renderer,h=a.autoClear;a.getClearColor(pB),a.autoClear=!1;let u=this._backgroundBox;if(null===u){const e=new Kr({name:"PMREM.Background",side:d,depthWrite:!1,depthTest:!1});u=new On(new Ln,e)}let l=!1;const c=e.background;c?c.isColor&&(u.material.color.copy(c),e.background=null,l=!0):(u.material.color.copy(pB),l=!0),a.setRenderTarget(i),a.clear(),l&&a.render(u,r);for(let t=0;t<6;t++){const s=t%3;0===s?(r.up.set(0,n[t],0),r.lookAt(o[t],0,0)):1===s?(r.up.set(0,0,n[t]),r.lookAt(0,o[t],0)):(r.up.set(0,n[t],0),r.lookAt(0,0,o[t]));const h=this._cubeSize;MB(i,s*h,t>2?h:0,h,h),a.render(e,r)}a.autoClear=h,e.background=c}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===he||e.mapping===ue;i?null===this._cubemapMaterial&&(this._cubemapMaterial=NB(e)):null===this._equirectMaterial&&(this._equirectMaterial=CB(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;MB(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,cB)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;tlB&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const g=[];let f=0;for(let e=0;ey-4?i-y+4:0),4*(this._cubeSize-x),3*x,2*x),a.setRenderTarget(t),a.render(u,cB)}}function SB(e,t,s){const i=new bi(e,t,s);return i.texture.mapping=de,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function MB(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function AB(e){const t=new uT;return t.depthTest=!1,t.depthWrite=!1,t.blending=m,t.name=`PMREM_${e}`,t}function NB(e){const t=AB("cubemap");return t.fragmentNode=Bx(e,_B),t}function CB(e){const t=AB("equirect");return t.fragmentNode=By(e,wT(_B),0),t}const RB=new WeakMap,EB=new Map([[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),BB=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),IB=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class PB{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.monitor=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.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=_S(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new $E,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.useComparisonMethod=!1}getBindGroupsCache(){let e=RB.get(this.renderer);return void 0===e&&(e=new zw,RB.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new bi(e,t,s)}createCubeRenderTarget(e,t){return new ST(e,t)}createPMREMGenerator(){return new wB(this.renderer)}includes(e){return this.nodes.includes(e)}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let r,n=!0;for(const e of t)i.push(e),n=n&&!0!==e.groupNode.shared;return n?(r=s.get(i),void 0===r&&(r=new VE(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new VE(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},s=this.bindings;for(const e of Fd)for(const i in s[e]){const r=s[e][i];(t[i]||(t[i]=[])).push(...r)}e=[];for(const s in t){const i=t[s],r=this._getBindGroup(s,i);e.push(r)}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(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${IB(t.r)}, ${IB(t.g)}, ${IB(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>4&&t&&(t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' 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 s=this.attributes;for(const t of s)if(t.name===e)return t;const i=new kE(e,t);return s.push(i),i}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||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Ee)return"int";if(t===Be)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;const s=EB.get(e);return("float"===t?"":t[0])+s}getTypeFromArray(e){return BB.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof gn||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[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(){return this.stack=_S(this.stack),this.stacks.push(Bp()||this.stack),Ep(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Ep(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let i=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getData(e);return void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e);let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new kE("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeFromNode(e,t=this.shaderStage){const s=this.getDataFromNode(e,t);if(void 0===s.structType){const i=this.structs.index++;e.name=`StructType${i}`,this.structs[t].push(e),s.structType=e}return e}getUniformFromNode(e,t,s=this.shaderStage,i=null){const r=this.getDataFromNode(e,s,this.globalCache);let n=r.uniform;if(void 0===n){const o=this.uniforms.index++;n=new GE(i||"nodeUniform"+o,t,e),this.uniforms[s].push(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage){const r=this.getDataFromNode(e,i);let n=r.variable;if(void 0===n){const e=this.vars[i]||(this.vars[i]=[]);null===t&&(t="nodeVar"+e.length),n=new WE(t,s),e.push(n),r.variable=n}return n}getVaryingFromNode(e,t=null,s=e.getNodeType(this)){const i=this.getDataFromNode(e,"any");let r=i.varying;if(void 0===r){const e=this.varyings,n=e.length;null===t&&(t="nodeVarying"+n),r=new jE(t,s),e.push(r),i.varying=r}return r}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;r=new HE("nodeCode"+n,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,n=t;for(;n;){if(!0===i.get(n)){r=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(r)for(const e of s)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),n=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),n.set(s,!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),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}buildFunctionNode(e){const t=new uC,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[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)s[e.name]=new bS(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,r=this.cache,n=this.buildStage,o=this.stack,a={code:""};this.flow=a,this.vars={},this.cache=new $E,this.stack=_S();for(const s of Pd)this.setBuildStage(s),a.result=e.build(this,t);return a.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.cache=r,this.stack=o,this.setBuildStage(n),a}getFunctionOperator(){return null}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const r=this.shaderStage;this.setShaderStage(e);const n=this.flowChildNode(t,s);return null!==i&&(n.code+=`${this.tab+i} = ${n.result};\n`),this.flowCode[e]=this.flowCode[e]+n.code,this.setShaderStage(r),n}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t){return`${this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(void 0!==s)for(const e of s)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}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.")}build(){const{object:e,material:t,renderer:s}=this;if(null!==t){let e=s.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new uT),e.build(this)}else this.addFlow("compute",e);for(const e of Pd){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of Fd){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"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 sB(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new iB(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new rB(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new nB(e);if("color"===t)return new oB(e);if("mat3"===t)return new aB(e);if("mat4"===t)return new hB(e);throw new Error(`Uniform "${t}" not declared.`)}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const i=this.getTypeLength(t),r=this.getTypeLength(s);return 16===i&&9===r?`${this.getType(s)}(${e}[0].xyz, ${e}[1].xyz, ${e}[2].xyz)`:9===i&&4===r?`${this.getType(s)}(${e}[0].xy, ${e}[1].xy)`:i>4||r>4||0===r?e:i===r?`${this.getType(s)}( ${e} )`:i>r?this.format(`${e}.${"xyz".slice(0,r)}`,this.getTypeFromLength(r,this.getComponentType(t)),s):4===r&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${e} - Node System\n`}}class FB{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.startTime=null,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 s=e.get(t);return void 0===s&&(s={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(s,this.renderId)}else t===Ed.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(s,this.renderId)}else t===Ed.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===Ed.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.frameId&&!1!==e.update(this)&&t.set(s,this.frameId)}else if(t===Ed.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.renderId&&!1!==e.update(this)&&t.set(s,this.renderId)}else t===Ed.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 UB{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}UB.isNodeFunctionInput=!0;class OB extends TR{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,s=this.colorNode,i=nR(this.light),r=e.context.reflectedLight;t.direct({lightDirection:i,lightColor:s,reflectedLight:r},e.stack,e)}}const zB=new sr,LB=new sr;let VB=null;class DB extends TR{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=dm(new Ai).setGroup(um),this.halfWidth=dm(new Ai).setGroup(um)}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;LB.identity(),zB.copy(t.matrixWorld),zB.premultiply(s),LB.extractRotation(zB),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(LB),this.halfHeight.value.applyMatrix4(LB)}setup(e){let t,s;super.setup(e),e.isAvailable("float32Filterable")?(t=By(VB.LTC_FLOAT_1),s=By(VB.LTC_FLOAT_2)):(t=By(VB.LTC_HALF_1),s=By(VB.LTC_HALF_2));const{colorNode:i,light:r}=this,n=e.context.lightingModel,o=rR(r),a=e.context.reflectedLight;n.directRectArea({lightColor:i,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,reflectedLight:a,ltc_1:t,ltc_2:s},e.stack,e)}static setLTC(e){VB=e}}class kB extends TR{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=dm(0).setGroup(um),this.penumbraCosNode=dm(0).setGroup(um),this.cutoffDistanceNode=dm(0).setGroup(um),this.decayExponentNode=dm(0).setGroup(um)}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){const{coneCosNode:t,penumbraCosNode:s}=this;return Sf(t,s,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:s,cutoffDistanceNode:i,decayExponentNode:r,light:n}=this,o=rR(n).sub(lx),a=o.normalize(),h=a.dot(nR(n)),u=this.getSpotAttenuation(h),l=o.length(),c=_R({lightDistance:l,cutoffDistance:i,decayExponent:r}),d=s.mul(u).mul(c),p=e.context.reflectedLight;t.direct({lightDirection:a,lightColor:d,reflectedLight:p},e.stack,e)}}class GB extends kB{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e){const t=this.light.iesMap;let s=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);s=By(t,Vp(i,0),0).r}else s=super.getSpotAttenuation(e);return s}}class WB extends TR{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class jB extends TR{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=sR(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=dm(new Xr).setGroup(um)}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:s,lightDirectionNode:i}=this,r=xx.dot(i).mul(.5).add(.5),n=vf(s,t,r);e.context.irradiance.addAssign(n)}}class HB extends TR{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Ai);this.lightProbe=Ox(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=UE(bx,this.lightProbe);e.context.irradiance.addAssign(t)}}class qB{parseFunction(){console.warn("Abstract function.")}}class $B{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}$B.isNodeFunction=!0;const XB=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,YB=/[a-z_0-9]+/gi,ZB="#pragma main";class JB extends $B{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(ZB),s=-1!==t?e.slice(t+12):e,i=s.match(XB);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=YB.exec(r));)n.push(o);const a=[];let h=0;for(;h0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==s||i){let i=null;if(!0===s.isCubeTexture||s.mapping===le||s.mapping===ce||s.mapping===de)if(e.backgroundBlurriness>0||s.mapping===de)i=rw(s,bx);else{let e;e=!0===s.isCubeTexture?Bx(s):By(s),i=RT(e)}else!0===s.isTexture?i=By(s,Uv.flipY()).setUpdateMatrix(!0):!0!==s.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",s);t.backgroundNode=i,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){let e=null;if(s.isFogExp2){const t=Dx("color","color",s).setGroup(um),i=Dx("density","float",s).setGroup(um);e=MC(t,i)}else if(s.isFog){const t=Dx("color","color",s).setGroup(um),i=Dx("near","float",s).setGroup(um),r=Dx("far","float",s).setGroup(um);e=wC(t,i,r)}else console.error("WebGPUNodes: Unsupported fog configuration.",s);t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){let e=null;!0===s.isCubeTexture?e=Bx(s):!0===s.isTexture?e=By(s):console.error("Nodes: Unsupported environment configuration.",s),t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,r=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=i,n.material=r,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}hasOutputChange(e){return QB.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=By(e,Uv).renderOutput(t.toneMapping,t.currentColorSpace);return QB.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new FB,this.nodeBuilderCache=new Map}}class tI{constructor(e,t){this.scene=e,this.camera=t}clone(){return Object.assign(new this.constructor,this)}}class sI{constructor(){this.lists=new zw}get(e,t){const s=this.lists,i=[e,t];let r=s.get(i);return void 0===r&&(r=new tI(e,t),s.set(i,r)),r}dispose(){this.lists=new zw}}class iI{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map,this.colorSpaceNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(null!==s){t=new s;for(const s in e)t[s]=e[s]}return t}addColorSpace(e,t){this.addType(e,t,this.colorSpaceNodes)}getColorSpaceFunction(e){return this.colorSpaceNodes.get(e)||null}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t.type,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t))console.warn(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}}addClass(e,t,s){if(s.has(t))console.warn(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}}const rI=new hR;class nI extends zw{constructor(){super()}createNode(e=[]){return(new hR).setLights(e)}getNode(e,t){if(e.isQuadMesh)return rI;const s=[e,t];let i=this.get(s);return void 0===i&&(i=this.createNode(),this.set(s,i)),i}}const oI=new Kn,aI=new Ys,hI=new xi,uI=new Ko,lI=new sr,cI=new xi;class dI{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:r=!0,stencil:n=!1,antialias:o=!1,samples:a=0,getFallback:h=null}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=a||!0===o?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=Zt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=r,this.stencil=n,this.clippingPlanes=[],this.info=new eS,this.nodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new iI,this.lighting=new nI,this._getFallback=h,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new xi(0,0,this._width,this._height),this._scissor=new xi(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new MM(new uT),this._quad.material.type="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const u=!0===this.alpha?0:1;this._clearColor=new xS(0,0,0,u),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr={enabled:!1},this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,s)=>{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(e,t,this._renderTarget),n=e.overrideMaterial||s.material,o=this._objects.get(s,n,e,t,i.lightsNode,r),{fragmentShader:a,vertexShader:h}=o.getNodeBuilderState();return{fragmentShader:a,vertexShader:h}}}}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 s=this.backend;try{await s.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=s=this._getFallback(e),await s.init(this)}catch(e){return void t(e)}}this._nodes=new eI(this,s),this._animation=new Ow(this._nodes,this.info),this._attributes=new Zw(s),this._background=new zE(this,this._nodes),this._geometries=new Qw(this._attributes,this.info),this._textures=new yS(this,s,this.info),this._pipelines=new oS(s,this._nodes),this._bindings=new aS(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Ww(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new cS(this.lighting),this._bundles=new sI,this._renderContexts=new gS,this._initialized=!0,e()}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,n=this._currentRenderContext,o=this._currentRenderObjectFunction,a=this._compilationPromises,h=!0===e.isScene?e:oI;null===s&&(s=e);const u=this._renderTarget,l=this._renderContexts.get(s,t,u),c=this._activeMipmapLevel,d=[];this._currentRenderContext=l,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),l.depth=this.depth,l.stencil=this.stencil,l.clippingContext||(l.clippingContext=new Vw),l.clippingContext.updateGlobal(this,t),h.onBeforeRender(this,e,t,u);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p),s!==e&&s.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==u){this._textures.updateRenderTarget(u,c);const e=this._textures.get(u);l.textures=e.textures,l.depthTexture=e.depthTexture}else l.textures=null,l.depthTexture=null;this._nodes.updateScene(h),this._background.update(h,p,l);const m=p.opaque,g=p.transparent,f=p.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,h,f),!0===this.transparent&&g.length>0&&this._renderObjects(g,t,h,f),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=o,this._compilationPromises=a,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init();const s=this._renderScene(e,t);await this.backend.resolveTimestampAsync(s,"render")}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,o=this._currentRenderContext,a=this._bundles.get(i,r),h=this.backend.get(a);void 0===h.renderContexts&&(h.renderContexts=new Set);const u=i.version!==h.version,l=!1===h.renderContexts.has(o)||u;if(h.renderContexts.add(o),l){this.backend.beginBundle(o),(void 0===h.renderObjects||u)&&(h.renderObjects=[]),this._currentRenderBundle=a;const e=n.opaque;e.length>0&&this._renderObjects(e,r,t,s),this._currentRenderBundle=null,this.backend.finishBundle(o,a),h.version=i.version}else{const{renderObjects:e}=h;for(let t=0,s=e.length;t>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=b,p.viewport=!1===p.viewportValue.equals(hI),p.scissorValue.copy(f).multiplyScalar(y).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(hI),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new Vw),p.clippingContext.updateGlobal(this,t),h.onBeforeRender(this,e,t,d),lI.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),uI.setFromProjectionMatrix(lI,m);const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,c);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=l,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,this._nodes.updateScene(h),this._background.update(h,v,p),this.backend.beginRender(p);const{bundles:T,lightsNode:_,transparent:w,opaque:S}=v;if(T.length>0&&this._renderBundles(T,h,_),!0===this.opaque&&S.length>0&&this._renderObjects(S,t,h,_),!0===this.transparent&&w.length>0&&this._renderObjects(w,t,h,_),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=o,this._currentRenderObjectFunction=a,null!==i){this.setRenderTarget(u,l,c);const e=this._quad;this._nodes.hasOutputChange(d.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(d.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}return h.onAfterRender(this,e,t,d),p}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,s){this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,s=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(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,s,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,r=0,n=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,i),o.minDepth=r,o.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,s=!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,s);const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i&&(this._textures.updateRenderTarget(i),r=this._textures.get(i)),this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget){const e=this._quad;this._nodes.hasOutputChange(i.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(i.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}}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,s=!0){!1===this._initialized&&await this.init(),this.clear(e,t,s)}clearColorAsync(){return this.clearAsync(!0,!1,!1)}clearDepthAsync(){return this.clearAsync(!1,!0,!1)}clearStencilAsync(){return this.clearAsync(!1,!1,!0)}get currentToneMapping(){return null!==this._renderTarget?0:this.toneMapping}get currentColorSpace(){return null!==this._renderTarget?Jt:this.outputColorSpace}dispose(){this.info.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(),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,r=this._pipelines,n=this._bindings,o=this._nodes,a=Array.isArray(e)?e:[e];if(void 0===a[0]||!0!==a[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const t of a){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),n.delete(t),o.delete(t)};t.addEventListener("dispose",e);const s=t.onInitFunction;null!==s&&s.call(t,{renderer:this})}o.updateForCompute(t),n.updateForCompute(t);const s=n.getForCompute(t),a=r.getForCompute(t,s);i.compute(e,t,s,a)}i.finishCompute(e),t.renderId=s}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e),await this.backend.resolveTimestampAsync(e,"compute")}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(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)}copyFramebufferToTexture(e,t=null){const s=this._currentRenderContext;this._textures.updateTexture(e),t=null===t?cI.set(0,0,e.image.width,e.image.height):t,this.backend.copyFramebufferToTexture(e,s,t)}copyTextureToTexture(e,t,s=null,i=null,r=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r)}readRenderTargetPixelsAsync(e,t,s,i,r,n=0,o=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,o)}_projectObject(e,t,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||uI.intersectsSprite(e)){!0===this.sortObjects&&cI.setFromMatrixPosition(e.matrixWorld).applyMatrix4(lI);const{geometry:t,material:r}=e;r.visible&&i.push(e,t,r,s,cI.z,null)}}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)&&(!e.frustumCulled||uI.intersectsObject(e))){const{geometry:t,material:r}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),cI.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(lI)),Array.isArray(r)){const n=t.groups;for(let o=0,a=n.length;o0?i:"";t=`${e.name} {\n\t${s} ${r.name}[${n}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,n=!0}const o=r.node.precision;if(null!==o&&(t=NI[o]+" "+t),n){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,s.push(t)}let r="";for(const t in i){const s=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Ee){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let s=0;for(const i of e)t+=`layout( location = ${s++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[],s=e.getMemberTypes();for(let e=0;ee*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,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);!1===i.has(e)&&i.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 s=this.extensions[e];if(void 0!==s)for(const{name:e,behavior:i}of s.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}isAvailable(e){let t=CI[e];if(void 0===t){if("float32Filterable"===e){const e=this.renderer.backend.extensions;e.has("OES_texture_float_linear")?(e.get("OES_texture_float_linear"),t=!0):t=!1}CI[e]=t}return t}isFlipY(){return!0}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${i.code}\n\t`,e===r&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${i.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=s}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);let o=n.uniformGPU;if(void 0===o){const i=e.groupNode,a=i.name,h=this.getBindGroupArray(a,s);if("texture"===t)o=new wI(r.name,r.node,i),h.push(o);else if("cubeTexture"===t)o=new SI(r.name,r.node,i),h.push(o);else if("texture3D"===t)o=new MI(r.name,r.node,i),h.push(o);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,r.name=`buffer${e.id}`;const t=new yI(e,i);t.name=e.name,h.push(t),o=t}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new vI(s+"_"+a,i),e[a]=n,h.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let BI=null,II=null,PI=null;class FI{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}async init(e){this.renderer=e}begin(){}finish(){}draw(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}createRenderPipeline(){}createComputePipeline(){}destroyPipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}createDefaultTexture(){}createTexture(){}copyTextureToBuffer(){}createAttribute(){}createIndexAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}resolveTimestampAsync(){}hasFeatureAsync(){}hasFeature(){}getInstanceCount(e){const{object:t,geometry:s}=e;return s.isInstancedBufferGeometry?s.instanceCount:t.count>1?t.count:1}getDrawingBufferSize(){return BI=BI||new Ys,this.renderer.getDrawingBufferSize(BI)}getScissor(){return II=II||new xi,this.renderer.getScissor(II)}setScissorTest(){}getClearColor(){const e=this.renderer;return PI=PI||new xS,e.getClearColor(PI),PI.getRGB(PI,this.renderer.currentColorSpace),PI}getDomElement(){let t=this.domElement;return null===t&&(t=void 0!==this.parameters.canvas?this.parameters.canvas:ti(),"setAttribute"in t&&t.setAttribute("data-engine",`three.js r${e} webgpu`),this.domElement=t),t}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)}}let UI=0;class OI{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 zI{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,a=s.get(o);let h,u=a.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,n),a.bufferGPU=u,a.bufferType=t,a.version=o.version),r instanceof Float32Array)h=i.FLOAT;else if(r instanceof Uint16Array)h=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)h=i.SHORT;else if(r instanceof Uint32Array)h=i.UNSIGNED_INT;else if(r instanceof Int32Array)h=i.INT;else if(r instanceof Int8Array)h=i.BYTE;else if(r instanceof Uint8Array)h=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);h=i.UNSIGNED_BYTE}let l={bufferGPU:u,bufferType:t,type:h,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===Ee,id:UI++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);l=new OI(l,e)}s.set(e,l)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,n=t.get(r),o=n.bufferType,a=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,n.bufferGPU),0===a.length)s.bufferSubData(o,0,i);else{for(let e=0,t=a.length;e1?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE)}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===s||(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t&&(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:s}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const n=e.textures;if(i.length!==n.length||i[0]!==s.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e{!function r(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void i();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(r)}()}))}}let WI,jI,HI,qI=!1;class $I{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===qI&&(this._init(this.gl),qI=!0)}_init(e){WI={[pe]:e.REPEAT,[me]:e.CLAMP_TO_EDGE,[ge]:e.MIRRORED_REPEAT},jI={[fe]:e.NEAREST,[ye]:e.NEAREST_MIPMAP_NEAREST,[be]:e.NEAREST_MIPMAP_LINEAR,[Te]:e.LINEAR,[_e]:e.LINEAR_MIPMAP_NEAREST,[Se]:e.LINEAR_MIPMAP_LINEAR},HI={512:e.NEVER,519:e.ALWAYS,[ys]:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===fe||e===ye||e===be?t.NEAREST:t.LINEAR}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,r=!1){const{gl:n,extensions:o}=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 a=t;return t===n.RED&&(s===n.FLOAT&&(a=n.R32F),s===n.HALF_FLOAT&&(a=n.R16F),s===n.UNSIGNED_BYTE&&(a=n.R8),s===n.UNSIGNED_SHORT&&(a=n.R16),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.R8UI),s===n.UNSIGNED_SHORT&&(a=n.R16UI),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RG&&(s===n.FLOAT&&(a=n.RG32F),s===n.HALF_FLOAT&&(a=n.RG16F),s===n.UNSIGNED_BYTE&&(a=n.RG8),s===n.UNSIGNED_SHORT&&(a=n.RG16),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RG_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RG8UI),s===n.UNSIGNED_SHORT&&(a=n.RG16UI),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RGB&&(s===n.FLOAT&&(a=n.RGB32F),s===n.HALF_FLOAT&&(a=n.RGB16F),s===n.UNSIGNED_BYTE&&(a=n.RGB8),s===n.UNSIGNED_SHORT&&(a=n.RGB16),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I),s===n.UNSIGNED_BYTE&&(a=i===Zt&&!1===r?n.SRGB8:n.RGB8),s===n.UNSIGNED_SHORT_5_6_5&&(a=n.RGB565),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGB4),s===n.UNSIGNED_INT_5_9_9_9_REV&&(a=n.RGB9_E5)),t===n.RGB_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGB8UI),s===n.UNSIGNED_SHORT&&(a=n.RGB16UI),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I)),t===n.RGBA&&(s===n.FLOAT&&(a=n.RGBA32F),s===n.HALF_FLOAT&&(a=n.RGBA16F),s===n.UNSIGNED_BYTE&&(a=n.RGBA8),s===n.UNSIGNED_SHORT&&(a=n.RGBA16),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I),s===n.UNSIGNED_BYTE&&(a=i===Zt&&!1===r?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1)),t===n.RGBA_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGBA8UI),s===n.UNSIGNED_SHORT&&(a=n.RGBA16UI),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_INT&&(a=n.DEPTH24_STENCIL8),s===n.FLOAT&&(a=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(a=n.DEPTH24_STENCIL8),a!==n.R16F&&a!==n.R32F&&a!==n.RG16F&&a!==n.RG32F&&a!==n.RGBA16F&&a!==n.RGBA32F||o.get("EXT_color_buffer_float"),a}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE),s.texParameteri(e,s.TEXTURE_WRAP_S,WI[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,WI[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||s.texParameteri(e,s.TEXTURE_WRAP_R,WI[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,jI[t.magFilter]);const n=void 0!==t.mipmaps&&t.mipmaps.length>0,o=t.minFilter===Te&&n?Se:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,jI[o]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,HI[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===fe)return;if(t.minFilter!==be&&t.minFilter!==Se)return;if(t.type===Ie&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,r=this.getGLTextureType(e);let n=i[r];void 0===n&&(n=t.createTexture(),s.state.bindTexture(r,n),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=n),s.set(e,{textureGPU:n,glTextureType:r,isDefault:!0})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:r,width:n,height:o,depth:a}=t,h=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,h,u,e.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,r,l,n,o,a):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,l,n,o,a):e.isVideoTexture||s.texStorage2D(d,r,l,n,o),i.set(e,{textureGPU:c,glTextureType:d,glFormat:h,glType:u,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:r,glTextureType:n,glFormat:o,glType:a}=i.get(t),{width:h,height:u}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(n,r),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(n,0,0,0,h,u,o,a,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:r}=t,{textureGPU:n,glTextureType:o,glFormat:a,glType:h,glInternalFormat:u}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===n)return;const l=e=>e.isDataTexture?e.image.data:e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLImageElement||e instanceof HTMLCanvasElement?e:e.data;if(this.backend.state.bindTexture(o,n),this.setTextureParameters(o,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t0,c=t.renderTarget?t.renderTarget.height:this.backend.gerDrawingBufferSize().y;if(l){const s=0!==o||0!==a;let l,d;if(!0===e.isDepthTexture?(l=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(l|=i.STENCIL_BUFFER_BIT)):(l=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),s){const e=this.backend.get(t.renderTarget),s=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,s),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=c-a-u;i.blitFramebuffer(o,p,o+h,p+u,o,p,o+h,p+u,l,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,s),r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,p,h,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,n,0),i.blitFramebuffer(0,0,h,u,0,0,h,u,l,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,c-u-a,h,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t){const{gl:s}=this,i=t.renderTarget,{samples:r,depthTexture:n,depthBuffer:o,stencilBuffer:a,width:h,height:u}=i;if(s.bindRenderbuffer(s.RENDERBUFFER,e),o&&!a){let t=s.DEPTH_COMPONENT24;r>0?(n&&n.isDepthTexture&&n.type===s.FLOAT&&(t=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,r,t,h,u)):s.renderbufferStorage(s.RENDERBUFFER,t,h,u),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else o&&a&&(r>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,r,s.DEPTH24_STENCIL8,h,u):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,h,u),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,s,i,r,n){const{backend:o,gl:a}=this,{textureGPU:h,glFormat:u,glType:l}=this.backend.get(e),c=a.createFramebuffer();a.bindFramebuffer(a.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?a.TEXTURE_CUBE_MAP_POSITIVE_X+n:a.TEXTURE_2D;a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,d,h,0);const p=this._getTypedArrayType(l),m=i*r*this._getBytesPerTexel(l,u),g=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.bufferData(a.PIXEL_PACK_BUFFER,m,a.STREAM_READ),a.readPixels(t,s,i,r,u,l,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();const f=new p(m/p.BYTES_PER_ELEMENT);return a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,f),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.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:s}=this;let i=0;return e===s.UNSIGNED_BYTE&&(i=1),e!==s.UNSIGNED_SHORT_4_4_4_4&&e!==s.UNSIGNED_SHORT_5_5_5_1&&e!==s.UNSIGNED_SHORT_5_6_5&&e!==s.UNSIGNED_SHORT&&e!==s.HALF_FLOAT||(i=2),e!==s.UNSIGNED_INT&&e!==s.FLOAT||(i=4),t===s.RGBA?4*i:t===s.RGB?3*i:t===s.ALPHA?i:void 0}}class XI{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 YI{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 s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const ZI={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"};class JI{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:s,mode:i,object:r,type:n,info:o,index:a}=this;0!==a?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),o.update(r,t,i,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:o,object:a,info:h}=this;0!==s&&(0!==o?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),h.update(a,t,r,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:o}=this;if(0===s)return;const a=i.get("WEBGL_multi_draw");if(null===a)for(let i=0;i0)){const e=t.queryQueue.shift();this.initTimestampQuery(e)}}async resolveTimestampAsync(e,t="render"){if(!this.disjoint||!this.trackTimestamp)return;const s=this.get(e);s.gpuQueries||(s.gpuQueries=[]);for(let e=0;e0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext,n=e.occlusionQueryCount;n>0&&(n>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const o=e.textures;if(null!==o)for(let e=0;e0){const r=i.framebuffers[e.getCacheKey()],n=t.COLOR_BUFFER_BIT,o=i.msaaFrameBuffer,a=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,o),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,r);for(let s=0;s{let o=0;for(let t=0;t0&&e.add(i[t]),s[t]=null,r.deleteQuery(n),o++))}o1?m.renderInstances(y,g,f):m.render(y,g),o.bindVertexArray(null)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new EI(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,r="fragment"===s?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(){console.warn("Abstract class.")}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:n}=i,o=s.createProgram(),a=this.get(r).shaderGPU,h=this.get(n).shaderGPU;if(s.attachShader(o,a),s.attachShader(o,h),s.linkProgram(o),this.set(i,{programGPU:o,fragmentShader:a,vertexShader:h}),null!==t&&this.parallel){const r=new Promise((t=>{const r=this.parallel,n=()=>{s.getProgramParameter(o,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(n)};n()}));t.push(r)}else this._completeCompile(e,i)}_handleSource(e,t){const s=e.split("\n"),i=[],r=Math.max(t-6,0),n=Math.min(t+6,s.length);for(let e=r;e":" "} ${r}: ${s[e]}`)}return i.join("\n")}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=e.getShaderInfoLog(t).trim();if(i&&""===r)return"";const n=/ERROR: 0:(\d+)/.exec(r);if(n){const i=parseInt(n[1]);return s.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=i.getProgramInfoLog(e).trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,s,t);else{const n=this._getShaderErrors(i,s,"vertex"),o=this._getShaderErrors(i,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+o)}else""!==r&&console.warn("THREE.WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:o,vertexShader:a}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,o,a),s.useProgram(n);const h=e.getBindings();this._setupBindings(h,n),this.set(t,{programGPU:n})}createComputePipeline(e,t){const{state:s,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:n}=e,o=i.createProgram(),a=this.get(r).shaderGPU,h=this.get(n).shaderGPU,u=n.transforms,l=[],c=[];for(let e=0;eZI[t]===e)),s=this.extensions;for(let e=0;e0){if(void 0===l){const i=[];l=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,l);const r=[],u=e.textures;for(let s=0;s,\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:HM,stripIndexFormat:hA},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:HM,stripIndexFormat:hA},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,o=this.getTransferPipeline(i),a=this.getFlipYPipeline(i),h=this.device.createTexture({size:{width:r,height:n,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),u=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:eN,baseArrayLayer:s}),l=h.createView({baseMipLevel:0,mipLevelCount:1,dimension:eN,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),d=(e,t,s)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:s,loadOp:sA,storeOp:eA,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,r),n.draw(4,1,0,0),n.end()};d(o,u,l),d(a,l,u),this.device.queue.submit([c.finish()]),h.destroy()}generateMipmaps(e,t,s=0){const i=this.get(e);void 0===i.useCount&&(i.useCount=0,i.layers=[]);const r=i.layers[s]||this._mipmapCreateBundles(e,t,s),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,r),this.device.queue.submit([n.finish()]),0!==i.useCount&&(i.layers[s]=r),i.useCount++}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:eN,baseArrayLayer:s});const o=[];for(let a=1;a1&&!e.isMultisampleRenderTargetTexture){const e=Object.assign({},p);e.label=e.label+"-msaa",e.sampleCount=l,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=p}destroyTexture(e){const t=this.backend,s=t.get(e);s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else{const s=e.image.depth||1;for(let e=0;e1;for(let o=0;o]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,lP=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,cP={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_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 dP extends $B{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(uP);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=lP.exec(s));)i.push({name:r[1],type:r[2]});const n=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class pP extends qB{parseFunction(e){return new dP(e)}}const mP=self.GPUShaderStage,gP={vertex:mP?mP.VERTEX:1,fragment:mP?mP.FRAGMENT:2,compute:mP?mP.COMPUTE:4},fP={instance:!0,swizzleAssign:!1,storageBuffer:!0},yP={"^^":"tsl_xor"},xP={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"},bP={tsl_xor:new rC("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new rC("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new rC("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new rC("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new rC("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new rC("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new rC("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new rC("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 rC("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:new rC("\nfn tsl_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 {\n\n\tlet uvScaled = vec2( uv * vec2( dimension ) );\n\n\treturn ( ( uvScaled % dimension ) + dimension ) % dimension;\n\n}\n"),biquadraticTexture:new rC("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, level : i32 ) -> vec4f {\n\n\tlet iRes = vec2i( textureDimensions( map, level ) );\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, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2i( 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")},vP={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"};/Windows/g.test(navigator.userAgent)&&(bP.pow_float=new rC("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),bP.pow_vec2=new rC("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[bP.pow_float]),bP.pow_vec3=new rC("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[bP.pow_float]),bP.pow_vec4=new rC("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[bP.pow_float]),vP.pow_float="tsl_pow_float",vP.pow_vec2="tsl_pow_vec2",vP.pow_vec3="tsl_pow_vec3",vP.pow_vec4="tsl_pow_vec4");let TP="";!0!==/Firefox|Deno/g.test(navigator.userAgent)&&(TP+="diagnostic( off, derivative_uniformity );\n");class _P extends PB{constructor(e,t){super(e,t,new pP),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==Yt}_generateTextureSample(e,t,s,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s):this.generateTextureLod(e,t,s,"0")}_generateVideoSample(e,t,s=this.shaderStage){if("fragment"===s)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${s} shader.`)}_generateTextureSampleLevel(e,t,s,i,r,n=this.shaderStage){return"fragment"===n&&!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,i):this.generateTextureLod(e,t,s,i)}generateFilteredTexture(e,t,s,i="0"){return this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${s}, i32( ${i} ) )`}generateTextureLod(e,t,s,i="0"){this._include("repeatWrapping");return`textureLoad( ${t}, tsl_repeatWrapping( ${s}, ${!0===e.isMultisampleRenderTargetTexture?`textureDimensions( ${t} )`:`textureDimensions( ${t}, 0 )`} ), i32( ${i} ) )`}generateTextureLoad(e,t,s,i,r="0u"){return i?`textureLoad( ${t}, ${s}, ${i}, ${r} )`:`textureLoad( ${t}, ${s}, ${r} )`}generateTextureStore(e,t,s,i){return`textureStore( ${t}, ${s}, ${i} )`}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===Ie||!0===e.isMultisampleRenderTargetTexture}generateTexture(e,t,s,i,r=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,s,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,s,"0",i,r):this._generateTextureSample(e,t,s,i,r),n}generateTextureGrad(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,s,i,r,n=this.shaderStage){let o=null;return o=!0===e.isVideoTexture?this._generateVideoSample(t,s,n):this._generateTextureSampleLevel(e,t,s,i,r,n),o}generateTextureBias(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} 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,s=e.type;return"texture"===s||"cubeTexture"===s||"storageTexture"===s||"texture3D"===s?t:"buffer"===s||"storageBuffer"===s||"indirectStorageBuffer"===s?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=yP[e];return void 0!==t?(this._include(t),t):null}getStorageAccess(e){if(e.isStorageTextureNode)switch(e.access){case qA:return"read";case HA:return"write";default:return"read_write"}else switch(e.access){case WA:return"read_write";case jA:return"read";default:return"write"}}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let i;const o=e.groupNode,a=o.name,h=this.getBindGroupArray(a,s);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let n=null;if("texture"===t||"storageTexture"===t?n=new wI(r.name,r.node,o,e.access?e.access:null):"cubeTexture"===t?n=new SI(r.name,r.node,o,e.access?e.access:null):"texture3D"===t&&(n=new MI(r.name,r.node,o,e.access?e.access:null)),n.store=!0===e.isStorageTextureNode,n.setVisibility(gP[s]),"fragment"===s&&!1===this.isUnfilterable(e.value)&&!1===n.store){const e=new eP(`${r.name}_sampler`,r.node,o);e.setVisibility(gP[s]),h.push(e,n),i=[e,n]}else h.push(n),i=[n]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const r=new("buffer"===t?yI:iP)(e,o);r.setVisibility(gP[s]),h.push(r),i=r}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new vI(a,o),n.setVisibility(gP[s]),e[a]=n,h.push(n)),i=this.getNodeUniform(r,t),n.addUniform(i)}n.uniformGPU=i}return r}getBuiltin(e,t,s,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:s}),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,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n`;return s.result&&(r+=`\treturn ${s.result};\n`),r+="\n}\n",r}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")}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],s=this.directives[e];if(void 0!==s)for(const e of s)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")}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:i,type:r}of s.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,s,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:s,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const n=this.getType(i);t.push(`var<${s}> ${e}: array< ${n}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","id","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 s=this.getAttributesArray();for(let e=0,i=s.length;e`)}const i=this.getBuiltins("output");return i&&t.push("\t"+i),t.join(",\n")}getStructs(e){const t=[],s=this.structs[e];for(let e=0,i=s.length;e output : ${r};\n\n`)}return t.join("\n\n")}getVar(e,t){return`var ${t} : ${this.getType(e)}`}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`\t${this.getVar(e.type,e.name)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];for(let r=0;r";else if(!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array";else if(!0===t.isDepthTexture)i=`texture_depth${n}_2d`;else if(!0===t.isVideoTexture)i="texture_external";else if(!0===t.isData3DTexture)i="texture_3d";else if(!0===r.node.isStorageTextureNode){i=`texture_storage_2d<${hP(t)}, ${this.getStorageAccess(r.node)}>`}else{i=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const e=r.node,t=this.getType(e.bufferType),s=e.bufferCount,n=s>0&&"buffer"===r.type?", "+s:"",a=e.isAtomic?`atomic<${t}>`:`${t}`,h=`\t${r.name} : array< ${a}${n} >\n`,u=e.isStorageBufferNode?`storage, ${this.getStorageAccess(e)}`:"uniform";i.push(this._getWGSLStructBinding("NodeBuffer_"+e.id,h,u,o.binding++,o.group))}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(n[t]||(n[t]={index:o.binding++,id:o.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in n){const t=n[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let o=s.join("\n");return o+=i.join("\n"),o+=r.join("\n"),o}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],n=r[r.length-1],o=n.outputNode,a=void 0!==o&&!0===o.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),h=e.name;if(h&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${h}\n\t`),i+=`${r.code}\n\t`,e===n&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(a)s.returnType=o.nodeType,i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;\n\n",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getType(e){return xP[e]||e}isAvailable(e){let t=fP[e];return void 0===t&&("float32Filterable"===e&&(t=this.renderer.hasFeature("float32-filterable")),fP[e]=t),t}_getWGSLMethod(e){return void 0!==bP[e]&&this._include(e),vP[e]}_include(e){const t=bP[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// 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${TP}\n\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\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){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = id.x + id.y * numWorkgroups.x * u32(${t}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\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,s,i=0,r=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${s}> ${e} : ${n};`}}class wP{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=uA.Depth24PlusStencil8:e.depth&&(t=uA.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}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?kM:e.isLineSegments||e.isMesh&&!0===t.wireframe?GM:e.isLine?WM:e.isMesh?jM:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){return navigator.userAgent.includes("Quest")?uA.BGRA8Unorm:navigator.gpu.getPreferredCanvasFormat()}}const SP=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),MP=new Map([[gn,["float16"]]]),AP=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class NP{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,r=i.get(s);let n=r.buffer;if(void 0===n){const o=i.device;let a=s.array;if(!1===e.normalized&&(a.constructor===Int16Array||a.constructor===Uint16Array)){const e=new Uint32Array(a.length);for(let t=0;t1},layout:u.createPipelineLayout({bindGroupLayouts:d})},A={},N=e.context.depth,C=e.context.stencil;if(!0!==N&&!0!==C||(!0===N&&(A.format=w,A.depthWriteEnabled=i.depthWrite,A.depthCompare=_),!0===C&&(A.stencilFront=f,A.stencilBack={},A.stencilReadMask=i.stencilFuncMask,A.stencilWriteMask=i.stencilWriteMask),M.depthStencil=A),null===t)c.pipeline=u.createRenderPipeline(M);else{const e=new Promise((e=>{u.createRenderPipelineAsync(M).then((t=>{c.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e){const t=this.backend,{utils:s,device:i}=t,r=s.getCurrentDepthStencilFormat(e),n={label:"renderBundleEncoder",colorFormats:[s.getCurrentColorFormat(e)],depthStencilFormat:r,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(n)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),o=[];for(const e of t){const t=s.get(e);o.push(t.layout)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:o})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,o=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,a=null!==e.blendDstAlpha?e.blendDstAlpha:n,h=null!==e.blendEquationAlpha?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(h)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:CA},s={srcFactor:r,dstFactor:n,operation:CA}};if(e.premultipliedAlpha)switch(i){case 1:r(fA,vA,fA,vA);break;case 2:r(fA,fA,fA,fA);break;case 3:r(gA,xA,gA,fA);break;case 4:r(gA,yA,gA,bA)}else switch(i){case 1:r(bA,vA,fA,vA);break;case 2:r(bA,fA,bA,fA);break;case 3:r(gA,xA,gA,fA);break;case 4:r(gA,yA,gA,yA)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case 200:t=gA;break;case 201:t=fA;break;case 202:t=yA;break;case 203:t=xA;break;case R:t=bA;break;case E:t=vA;break;case 208:t=TA;break;case 209:t=_A;break;case 206:t=wA;break;case 207:t=SA;break;case 210:t=MA;break;case 211:t=AA;break;case 212:t=NA;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=qM;break;case gs:t=QM;break;case 513:t=$M;break;case 515:t=YM;break;case 514:t=XM;break;case 518:t=KM;break;case 516:t=ZM;break;case 517:t=JM;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case ts:t=UA;break;case 0:t=OA;break;case 7681:t=zA;break;case 5386:t=LA;break;case 7682:t=VA;break;case 7683:t=DA;break;case 34055:t=kA;break;case 34056:t=GA;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case v:t=CA;break;case 101:t=RA;break;case 102:t=EA;break;case 103:t=BA;break;case 104:t=IA;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?aA:hA),s.side){case c:i.frontFace=iA,i.cullMode=oA;break;case d:i.frontFace=iA,i.cullMode=nA;break;case 2:i.frontFace=iA,i.cullMode=rA;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?FA:PA}_getDepthCompare(e){let t;if(!1===e.depthTest)t=QM;else{const s=e.depthFunc;switch(s){case 0:t=qM;break;case 1:t=QM;break;case 2:t=$M;break;case 3:t=YM;break;case 4:t=XM;break;case 5:t=KM;break;case 6:t=ZM;break;case 7:t=JM;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class EP extends FI{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.trackTimestamp=!0===e.trackTimestamp,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new wP(this),this.attributeUtils=new NP(this),this.bindingUtils=new CP(this),this.pipelineUtils=new RP(this),this.textureUtils=new aP(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference},i=await navigator.gpu.requestAdapter(e);if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(aN),n=[];for(const e of r)i.features.has(e)&&n.push(e);const o={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(o)}else s=t.device;const i=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=s,this.context=i;const r=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(aN.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r}),this.updateSize()}get coordinateSystem(){return Os}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 s=e.colorAttachments[0];this.renderer.samples>0?s.view=this.colorBuffer.createView():s.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}_getRenderPassDescriptor(e){const t=e.renderTarget,s=this.get(t);let i=s.descriptors;if(void 0===i||s.width!==t.width||s.height!==t.height||s.activeMipmapLevel!==t.activeMipmapLevel||s.samples!==t.samples){i={},s.descriptors=i;const e=()=>{t.removeEventListener("dispose",e),this.delete(t)};t.addEventListener("dispose",e)}const r=e.getCacheKey();let n=i[r];if(void 0===n){const o=e.textures,a=[];for(let t=0;t0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=s.createQuerySet({type:"occlusion",count:i}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e),this.initTimestampQuery(e,n),n.occlusionQuerySet=r;const o=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),s>0){const i=8*s;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const n=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,n,0,i),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.prepareTimestampBuffer(e,t.encoder),this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eo?(h.x=Math.min(t.dispatchCount,o),h.y=Math.ceil(t.dispatchCount/o)):h.x=t.dispatchCount,r.dispatchWorkgroups(h.x,h.y,h.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.prepareTimestampBuffer(e,t.cmdEncoderGPU),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:s,context:i,pipeline:r}=e,n=e.getBindings(),o=this.get(i),a=this.get(r).pipeline,h=o.currentSets,u=o.currentPass,l=e.getDrawParameters();if(null===l)return;h.pipeline!==a&&(u.setPipeline(a),h.pipeline=a);const c=h.bindingGroups;for(let e=0,t=n.length;e1?0:s;u.drawIndexed(t[s],i,e[s]/n,0,o)}}else if(!0===p){const{vertexCount:i,instanceCount:r,firstVertex:n}=l,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndexedIndirect(e,0)}else u.drawIndexed(i,r,n,0,0);t.update(s,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:n}=l,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndirect(e,0)}else u.draw(i,r,n,0);t.update(s,i,r)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),o=r.getCurrentColorSpace(e.context),a=r.getCurrentColorFormat(e.context),h=r.getCurrentDepthStencilFormat(e.context),u=r.getPrimitiveTopology(s,i);let l=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===o&&t.colorFormat===a&&t.depthStencilFormat===h&&t.primitiveTopology===u&&t.clippingContextCacheKey===e.clippingContext.cacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=n,t.colorSpace=o,t.colorFormat=a,t.depthStencilFormat=h,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContext.cacheKey,l=!0),l}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,r=e.context;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.clippingContext.cacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const s=this.get(e);if(!s.timeStampQuerySet){const e=this.device.createQuerySet({type:"timestamp",count:2}),i={querySet:e,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1};Object.assign(t,{timestampWrites:i}),s.timeStampQuerySet=e}}prepareTimestampBuffer(e,t){if(!this.trackTimestamp)return;const s=this.get(e),i=2*BigInt64Array.BYTES_PER_ELEMENT;void 0===s.currentTimestampQueryBuffers&&(s.currentTimestampQueryBuffers={resolveBuffer:this.device.createBuffer({label:"timestamp resolve buffer",size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),resultBuffer:this.device.createBuffer({label:"timestamp result buffer",size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),isMappingPending:!1});const{resolveBuffer:r,resultBuffer:n,isMappingPending:o}=s.currentTimestampQueryBuffers;!0!==o&&(t.resolveQuerySet(s.timeStampQuerySet,0,2,r,0),t.copyBufferToBuffer(r,0,n,0,i))}async resolveTimestampAsync(e,t="render"){if(!this.trackTimestamp)return;const s=this.get(e);if(void 0===s.currentTimestampQueryBuffers)return;const{resultBuffer:i,isMappingPending:r}=s.currentTimestampQueryBuffers;!0!==r&&(s.currentTimestampQueryBuffers.isMappingPending=!0,i.mapAsync(GPUMapMode.READ).then((()=>{const e=new BigUint64Array(i.getMappedRange()),r=Number(e[1]-e[0])/1e6;this.renderer.info.updateTimestamp(t,r),i.unmap(),s.currentTimestampQueryBuffers.isMappingPending=!1})))}createNodeBuilder(e,t){return new _P(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),i=s.currentPass.finish();this.get(t).bundleGPU=i,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e){this.bindingUtils.createBindings(e)}updateBindings(e){this.bindingUtils.createBindings(e)}updateBinding(e){this.bindingUtils.updateBinding(e)}createIndexAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0){let n=0,o=0,a=0,h=0,u=0,l=0,c=e.image.width,d=e.image.height;null!==s&&(h=s.x,u=s.y,l=s.z||0,c=s.width,d=s.height),null!==i&&(n=i.x,o=i.y,a=i.z||0);const p=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),m=this.get(e).texture,g=this.get(t).texture;p.copyTextureToTexture({texture:m,mipLevel:r,origin:{x:h,y:u,z:l}},{texture:g,mipLevel:r,origin:{x:n,y:o,z:a}},[c,d,1]),this.device.queue.submit([p.finish()])}copyFramebufferToTexture(e,t,s){const i=this.get(t),{encoder:r,descriptor:n}=i;let o=null;o=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const a=this.get(e).texture;if(o.format===a.format){i.currentPass.end(),r.copyTextureToTexture({texture:o,origin:{x:s.x,y:s.y,z:0}},{texture:a},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e);for(let e=0;e(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new KI(e)));super(new t(e),e),this.library=new IP,this.isWebGPURenderer=!0}}const FP=new uT,UP=new MM(FP);class OP{constructor(e,t=$p(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0,FP.name="PostProcessing"}render(){this.update();const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;e.toneMapping=0,e.outputColorSpace=Jt,UP.render(e),e.toneMapping=t,e.outputColorSpace=s}update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;UP.material.fragmentNode=!0===this.outputColorTransform?Ty(this.outputNode,t,s):this.outputNode.context({toneMapping:t,outputColorSpace:s}),UP.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){this.update();const e=this.renderer,t=e.toneMapping,s=e.outputColorSpace;e.toneMapping=0,e.outputColorSpace=Jt,await UP.renderAsync(e),e.toneMapping=t,e.outputColorSpace=s}}function zP(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new Xr),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}function LP(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 VP(e,t,s={}){return(s=zP(e,s)).background=t.background,s.backgroundNode=t.backgroundNode,s.overrideMaterial=t.overrideMaterial,s}var DP=Object.freeze({__proto__:null,resetRendererAndSceneState:function(e,t,s){return s=VP(e,t,s),t.background=null,t.backgroundNode=null,t.overrideMaterial=null,s},resetRendererState:function(e,t){return t=zP(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t},restoreRendererAndSceneState:function(e,t,s){LP(e,s),t.background=s.background,t.backgroundNode=s.backgroundNode,t.overrideMaterial=s.overrideMaterial},restoreRendererState:LP,saveRendererAndSceneState:VP,saveRendererState:zP});class kP extends yi{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=Te,this.minFilter=Te,this.isStorageTexture=!0}}class GP extends an{constructor(e,t,s=Float32Array){!1===ArrayBuffer.isView(e)&&(e=new s(e*t)),super(e,t),this.isStorageBufferAttribute=!0}}class WP extends zo{constructor(e,t,s=Float32Array){!1===ArrayBuffer.isView(e)&&(e=new s(e*t)),super(e,t),this.isStorageInstancedBufferAttribute=!0}}class jP extends GP{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class HP extends el{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,s,i){const r=new il(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,(s=>{try{t(this.parse(JSON.parse(s)))}catch(t){i?i(t):console.error(t),this.manager.itemError(e)}}),s,i)}parseNodes(e){const t={};if(void 0!==e){for(const s of e){const{uuid:e,type:i}=s;t[e]=this.createNodeFromType(i),t[e].uuid=e}const s={nodes:t,textures:this.textures};for(const i of e){i.meta=s;t[i.uuid].deserialize(i),delete i.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const s={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=s,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),Up()):wp(new this.nodes[e])}}class qP extends El{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),s=this.nodes,i=e.inputNodes;for(const e in i){const r=i[e];t[e]=s[r]}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 $P extends Fl{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 s=super.parse(e,t);return this._nodesJSON=null,s}parseNodes(e,t){if(void 0!==e){const s=new HP;return s.setNodes(this.nodes),s.setTextures(t),s.parseNodes(e)}return{}}parseMaterials(e,t){const s={};if(void 0!==e){const i=this.parseNodes(this._nodesJSON,t),r=new qP;r.setTextures(t),r.setNodes(i),r.setNodeMaterials(this.nodeMaterials);for(let t=0,i=e.length;t