rize_depth(d_lrez)/far,linearize_depth(d_hrez)/far,step(0.5,v_uv.x));gl_FragColor=vec4(vec3(output_d),1.0); #else vec2 filtered_uv=nearest_depth_filter(v_uv);vec4 ao=texture(texture_ao_lrez,filtered_uv);gl_FragColor=vec4(ao.rgb,1.0);gl_FragColor=ao; #endif }`;var Ef=[[.478712,.875764],[-.337956,-.793959],[-.955259,-.028164],[.864527,.325689],[.209342,-.395657],[-.106779,.672585],[.156213,.235113],[-.413644,-.082856],[-.415667,.323909],[.141896,-.93998],[.954932,-.182516],[-.766184,.410799],[-.434912,-.458845],[.415242,-.078724],[.728335,-.491777],[-.058086,-.066401],[.20299,.686837],[-.808362,-.556402],[.507386,-.640839],[-.723494,-.22924],[.48974,.317826],[-.622663,.765301],[-.01064,.929347],[.663146,.647618],[-.096674,-.413835],[.525945,-.321063],[-.122533,.366019],[.195235,-.687983],[-.563203,.098748],[.418563,.561335],[-.378595,.800367],[.826922,.001024],[-.085372,-.766651],[-.92192,.183673],[-.590008,-.721799],[.167751,-.164393],[.032961,-.56253],[.6329,-.107059],[-.46408,.569669],[-.173676,-.958758],[-.242648,-.234303],[-.275362,.157163],[.382295,-.795131],[.562955,.115562],[.190586,.470121],[.770764,-.297576],[.237281,.93105],[-.666642,-.455871],[-.905649,-.298379],[.33952,.157829],[.701438,-.7041],[-.062758,.160346],[-.220674,.957141],[.642692,.432706],[-.77339,-.015272],[-.671467,.24688],[.158051,.062859],[.806009,.527232],[-.05762,-.247071],[.333436,-.51671],[-.550658,-.315773],[-.652078,.589846],[.008818,.530556],[-.210004,.519896]];var GQ=new it({vertexShader:uL,fragmentShader:hL}),Tf=new it({vertexShader:pL,fragmentShader:mL,uniforms:{texture_ao_lrez:new le(null),texture_depth_lrez:new le(null),texture_depth_hrez:new le(null),near:new le(null),far:new le(null)}}),Bx=class extends xi{constructor(e,r){super("AmbientOcclusionPass",void 0,r);this.fogEnabled=!1;this.fogNear=1;this.fogFar=1e3;this.frameIndex=0;this._runHalfRes=!0;this._width=1;this._height=1;let i=1024,s=1024;this.gBuffer=new dt(i,s,{type:xo?Wn:br,depthTexture:new ns(i,s),minFilter:rt,magFilter:rt}),this.depthBufferHighRes=new dt(i,s,{depthTexture:new ns(i,s)}),this.aoBuffer=new dt(i,s,{minFilter:rt,magFilter:rt}),this.splineScene=e,this.splineCamera=r;let o=new Float32Array(Ef.length*2);for(let l=0;l with size float rectangle(vec2 st, vec2 size) { size = vec2(0.5) - size * 0.5; vec2 uv = vec2(step(size.x, st.x), step(size.y, st.y)); uv *= vec2(step(size.x, 1.0 - st.x), step(size.y, 1.0 - st.y)); return uv.x * uv.y; } uniform vec2 uSize; uniform float uScale; uniform float uDPR; uniform float uCurrent; uniform vec3 uSceneColor; void main() { vec2 screenUv = gl_FragCoord.xy / uResolution.xy; screenUv *= 1.0 / uDPR; vec2 center = vec2(0.5, -0.5); vec2 outsideUv = screenUv; outsideUv += center; outsideUv -= uCoords.xy / uResolution.xy; outsideUv = (outsideUv - 0.5) + 0.5; outsideUv -= center; vec2 s = (uSize / uResolution) * uScale; float isOutside = 1.0 - rectangle(outsideUv, s); vec2 mid = vec2(0.5); vec2 insideUv = (screenUv - mid + s * mid) / s; vec4 background = texture2D(tInput, screenUv); vec4 image = texture2D(tMap, insideUv); gl_FragColor = mix(image, background, isOutside); } `,Nx=class extends hn{constructor(){super(new it({vertexShader:jQ,fragmentShader:HQ,uniforms:{tInput:new le(null),tMap:new le(null),uResolution:new le(new k),uSize:new le(new k),uCoords:new le(new k),uScale:new le(1),uSceneColor:new le(new We(16711680)),uDPR:new le(1),uCurrent:new le(0)}}),"tInput"),this.needsSwap=!0}get uniforms(){return this.fullscreenMaterial.uniforms}get texture(){return this.uniforms.tMap.value}set texture(t){this.uniforms.tMap.value=t}};var WQ=` void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,qQ=` uniform sampler2D toScene; uniform sampler2D fromScene; uniform vec2 resolution; uniform vec2 uResolution; uniform float uDPR; uniform float mixRatio; uniform sampler2D tMixTexture; uniform int useTexture; uniform float threshold; void main() { vec2 screenUv = gl_FragCoord.xy / uResolution.xy; screenUv *= 1.0 / uDPR; vec4 texel1 = texture2D( fromScene, screenUv ); vec4 texel2 = texture2D( toScene, screenUv ); if (useTexture==1) { vec4 transitionTexel = texture2D( tMixTexture, screenUv ); float r = mixRatio * (1.0 + threshold * 2.0) - threshold; float mixf=clamp((transitionTexel.r - r)*(1.0/threshold), 0.0, 1.0); gl_FragColor = mix( texel1, texel2, mixf ); } else { gl_FragColor = mix( texel1, texel2, mixRatio ); } } `,YQ=[],Fx=class extends hn{constructor(){super(new it({vertexShader:WQ,fragmentShader:qQ,uniforms:{toScene:new le(null),fromScene:new le(null),uResolution:new le(new k),uDPR:new le(1),mixRatio:new le(0),threshold:new le(.1),useTexture:new le(0),tMixTexture:{value:YQ[0]}}}),"toScene"),this.needsSwap=!0}get uniforms(){return this.fullscreenMaterial.uniforms}get texture(){return this.uniforms.fromScene.value}set texture(t){this.uniforms.fromScene.value=t}};var XQ=` void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,KQ=` uniform sampler2D inputBuffer; uniform sampler2D blurredInputBuffer; uniform sampler2D overlay; uniform float blurIntensity; uniform vec2 uResolution; uniform float uDPR; void main() { vec2 screenUv = gl_FragCoord.xy / uResolution.xy; screenUv *= 1.0 / uDPR; vec4 texel1 = texture2D( overlay, screenUv ); vec4 texel2 = texture2D( inputBuffer, screenUv ); vec4 texel3 = texture2D( blurredInputBuffer, screenUv ); float blurMask2 = max(sign(texel1.a), 0.0) * blurIntensity; gl_FragColor = mix( mix(texel2, texel3, blurMask2), texel1, texel1.a ); } `,Vx=class extends hn{constructor(){super(new it({vertexShader:XQ,fragmentShader:KQ,uniforms:{inputBuffer:new le(null),blurredInputBuffer:new le(null),overlay:new le(null),uResolution:new le(new k),uDPR:new le(1),blurIntensity:new le(0)}}));this._blurEnabled=!1;this.blurTarget=new dt(1,1,{minFilter:rt,magFilter:rt,wrapS:Qt,wrapT:Qt}),this.blurPass=new _x({width:window.innerWidth,height:window.innerHeight,kernelSize:zm.HUGE,resolutionScale:.25}),this.blurPass.renderToScreen=!1,this.uniforms.blurredInputBuffer.value=this.blurTarget.texture}get uniforms(){return this.fullscreenMaterial.uniforms}get texture(){return this.uniforms.overlay.value}set texture(e){this.uniforms.overlay.value=e}setResolution(e,r,i=1){this.uniforms.uResolution.value.set(e,r),this.uniforms.uDPR.value=i,this.blurPass.setSize(e,r),this.blurTarget.setSize(e,r),this.blurPass.setSize(e,r)}get uiCanvas(){return this._uiCanvas}set uiCanvas(e){this._uiCanvas=e,e.texture&&(this.uniforms.overlay.value=e.texture);let i=e.frame;if(i){let s=i.data.backgroundBlur,o=s.radius;this._blurEnabled=s.enabled,this.uniforms.blurIntensity.value=this._blurEnabled?1:0,this.blurPass.scale=o/3}}render(e,r,i,s,o){this._blurEnabled&&(this.blurPass.setDepthTexture(this.getDepthTexture()),this.blurPass.render(e,r,this.blurTarget,s,o)),super.render(e,r,i,s,o)}};var QQ=` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,ZQ=` uniform sampler2D tInput; uniform sampler2D tOverlayImage; varying vec2 vUv; uniform vec2 uResolution; uniform vec2 uRightBottom; uniform vec2 uImageSize; uniform float uScale; uniform float uDPR; vec3 blendNormal(vec3 base, vec3 blend) { return blend; } vec3 blendNormal(vec3 base, vec3 blend, float opacity) { return (blendNormal(base, blend) * opacity + base * (1.0 - opacity)); } vec4 drawFixedSizeImage(sampler2D image, vec2 screenUV, vec2 imageSize, vec2 imageCoords, vec2 screenSize, float dpr) { vec2 uv = (screenUV * screenSize * dpr - imageCoords) / (imageSize * dpr); if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { return vec4(0.0); } return texture2D(image, uv); } void main() { vec2 screenUV = gl_FragCoord.xy / (uResolution.xy * uDPR); vec2 imageCoords = vec2(uResolution.x * uDPR - uImageSize.x * uScale * uDPR - uRightBottom.x * uDPR, uRightBottom.y * uDPR); vec4 background = texture2D(tInput, screenUV); vec4 image = drawFixedSizeImage(tOverlayImage, screenUV, uImageSize * uScale, imageCoords, uResolution, uDPR); gl_FragColor = vec4(blendNormal(background.rgb, image.rgb, image.a), max(background.a, image.a)); } `,kx=class extends hn{constructor(){super(new it({vertexShader:QQ,fragmentShader:ZQ,uniforms:{tInput:new le(null),tOverlayImage:new le(null),uResolution:new le(new k),uImageSize:new le(new k),uRightBottom:new le(new k(20,20)),uScale:new le(.25),uDPR:new le(1)}}),"tInput")}get uniforms(){return this.fullscreenMaterial.uniforms}get texture(){return this.uniforms.tOverlayImage.value}set texture(t){this.uniforms.tOverlayImage.value=t,this.uniforms.uImageSize.value.set(t.image.width,t.image.height)}};function yL(n,t){return t&&t.enabled&&n.push(t.effect),n}var JQ=n=>Object.values(Pt).includes(n)?n:Pt.NORMAL,Gm=class extends pr{constructor(e,r){super();this._needsDOFResize=r;this.postprocessingState=qh.defaultData;this._scene=new ei;this._camera=new wr;this.effects=new Map;this.blueNoiseTexture=new gi;this._renderToScreen=!0;this._isUIOverlayEnabled=!1;this.clock=new Py,this.renderer=e,this.debug=!1,this.effects.set("bloom",new pf),this.effects.set("chromaticAberration",new gf),this.effects.set("vignette",new bf),this.effects.set("noise",new xf),this.effects.set("colorAverage",new yf),this.effects.set("hueSaturation",new vf),this.effects.set("brightnessContrast",new mf),this.effects.set("depthOfField",new Sf),this.effects.set("pixelation",new wf),this.effectComposer=new Rx(this.renderer),this.effectComposer.autoRenderToScreen=!1,this.opaquePass=new ru(!0,this.scene,this.camera),this.opaquePass.clear=!0,this.transmissionPass=new Ox(this.scene,this.camera,this.renderer),this.aoPass=new Bx(this.scene,this.camera),this.taaPass=new Dx,this.taaPass.renderToScreen=!1,this.helperPass=new Lx(this.camera),this.helperPass.renderToScreen=!1,this.stylesOverlayPass=new Nx,this.stylesOverlayPass.enabled=!1,this.uiOverlayPass=new Vx,this.uiOverlayPass.enabled=!1,this.logoOverlayPass=new kx,this.logoOverlayPass.enabled=!1,this.sceneTransitionPass=new Fx,this.sceneTransitionPass.enabled=!1,this._initCopyPass(),this._initPasses()}set overlayTexture(e){e!==void 0?(this.stylesOverlayPass.texture=e,this.stylesOverlayPass.enabled=!0):this.stylesOverlayPass.enabled=!1}get overlayTexture(){return this.stylesOverlayPass.texture}set sceneHelpers(e){this.helperPass.sceneHelpers=e}get sceneHelpers(){return this.helperPass.sceneHelpers}set sceneHelpersOnTop(e){this.helperPass.sceneHelpersOnTop=e}get sceneHelpersOnTop(){return this.helperPass.sceneHelpersOnTop}get scene(){return this._scene}set scene(e){this._scene=e,this.opaquePass.setScene(e),this.transmissionPass.setScene(e),this.aoPass.setScene(e)}get camera(){return this._camera}set camera(e){let r=this._camera!==e;this._camera=e,this.opaquePass.setCamera(e),this.transmissionPass.setCamera(e),r&&this.transmissionPass.updatePasses(this.renderer),this.aoPass.setCamera(e),this.helperPass.setCamera(e),this.effects.get("depthOfField").setCamera(e)}updateRenderToScreen(){let e=!1;for(let r=this.effectComposer.passes.length-1;r>=0;r--){let i=this.effectComposer.passes[r];if(i.enabled===!0&&!e&&this._renderToScreen){i.renderToScreen=!0,e=!0;continue}i.renderToScreen=!1}}get isUIOverlayEnabled(){return this._isUIOverlayEnabled}disableUIOverlay(){this._isUIOverlayEnabled=!1}enableUIOverlay(){this._isUIOverlayEnabled=!0}disableHelpers(){this.helperPass.enabled=!1,this.updateRenderToScreen()}enableHelpers(){this.helperPass.enabled=!0,this.updateRenderToScreen()}updateBlueNoiseTexture(e){this.blueNoiseTexture=new gi(e,128,128),this.blueNoiseTexture.wrapS=Rs,this.blueNoiseTexture.wrapT=Rs,this.blueNoiseTexture.minFilter=Vt,this.blueNoiseTexture.magFilter=Vt,this.blueNoiseTexture.needsUpdate=!0}setAmbientOcclusionParams(e,r,i,s,o,a,l,c){this.aoPass.enabled=e,this.aoPass.radius=r,this.aoPass.bias=i,this.aoPass.aoColor=s,this.aoPass.fogEnabled=o,this.aoPass.fogNear=a,this.aoPass.fogFar=l,this.aoPass.runHalfRes!==!c&&(this.aoPass.runHalfRes=!c)}setTransmissionPassEnabled(e){this.transmissionPass.enabled=e,this.opaquePass.hasTransmissionPass=e}_initPasses(){if(this.uvEffectPass?.dispose(),this.effectPass?.dispose(),this.effectComposer.removeAllPasses(),this.transmissionPass.updatePasses(this.renderer),this.effectComposer.addPass(this.aoPass),this.effectComposer.addPass(this.opaquePass),this.effectComposer.addPass(this.transmissionPass),this.effectComposer.addPass(this.taaPass),this.postprocessingState.enabled){let e=[this.effects.get("pixelation")].reduce(yL,[]);e.length>0&&(this.uvEffectPass=new tu(this.camera,...e),this.uvEffectPass.renderToScreen=!1,this.effectComposer.addPass(this.uvEffectPass));let r=[this.effects.get("chromaticAberration"),this.effects.get("bloom"),this.effects.get("depthOfField"),this.effects.get("colorAverage"),this.effects.get("hueSaturation"),this.effects.get("brightnessContrast"),this.effects.get("vignette"),this.effects.get("noise")].reduce(yL,[]);if(r.length>0&&(this.effectPass=new tu(this.camera,...r),this.effectPass.renderToScreen=!1,this.effectComposer.addPass(this.effectPass),this._needsDOFResize&&this.effects.get("depthOfField")?.enabled&&window!==void 0)){let i=this.renderer.viewportWidth,s=this.renderer.viewportHeight;this.renderer.setSize(i-1,s-1),this.renderer.setSize(i,s)}}this.effectComposer.addPass(this.stylesOverlayPass),this.effectComposer.addPass(this.uiOverlayPass),this.effectComposer.addPass(this.sceneTransitionPass),this.effectComposer.addPass(this.helperPass),this.effectComposer.addPass(this.logoOverlayPass)}_initCopyPass(){if(this._savePass)return;let e=new k;this.renderer.getDrawingBufferSize(e),this._rt=new dt(e.x,e.y,{depthBuffer:!1,stencilBuffer:!1,wrapS:Rs,wrapT:Rs}),this._rt.samples=0,this._savePass=new Um(this._rt,!1),this._savePass.renderToScreen=!1}setCopyPass(e){this._rt=e,this._savePass=new Um(this._rt,!1),this.renderToScreen=!1}get renderToScreen(){return this._renderToScreen}set renderToScreen(e){if(this._renderToScreen===e)return;let r=this.effectComposer;!r||(e===!0?r.removePass(this._savePass):r.addPass(this._savePass),this._renderToScreen=e,this.updateRenderToScreen())}set sceneTransitionFromTexture(e){e!==this.sceneTransitionPass.texture&&(e!==null?this.sceneTransitionPass.enabled=!0:(this.sceneTransitionPass.enabled=!1,this.updateRenderToScreen()),this.sceneTransitionPass.texture=e)}setWatermark(e){this.logoOverlayPass.enabled=e!==null,e&&(this.logoOverlayPass.texture=e)}get texture(){return this._rt&&this._rt.texture}get renderTarget(){return this._rt}updatePostprocessing(e){let{enabled:r,...i}=e,s=!1;r!==this.postprocessingState.enabled&&(s=!0);for(let o of Object.entries(i)){let a=o[1],l=this.effects.get(o[0]);if(l){l.enabled!==a.enabled&&(s=!0),l.enabled=a.enabled;for(let[c,u]of Object.entries(a))c==="blendFunction"?l.blendFunction=JQ(u):l[c]=u}}this.postprocessingState=e,s&&this._initPasses()}render(){this.effectComposer.render(this.clock.getDelta())}setScissor(e,r,i,s){e instanceof Ze?(this.effectComposer.inputBuffer.scissor.set(e.x,e.y,e.z,e.w),this.effectComposer.outputBuffer.scissor.set(e.x,e.y,e.z,e.w)):(this.effectComposer.inputBuffer.scissor.set(e,r,i,s),this.effectComposer.outputBuffer.scissor.set(e,r,i,s));let o=this.renderer.getPixelRatio();this.effectComposer.inputBuffer.scissor.multiplyScalar(o),this.effectComposer.outputBuffer.scissor.multiplyScalar(o),this.renderer.setScissor(e,r,i,s)}setScissorTest(e){this.effectComposer.inputBuffer.scissorTest=e,this.effectComposer.outputBuffer.scissorTest=e,this.renderer.setScissorTest(e)}setViewport(e,r,i,s){e instanceof Ze?(this.effectComposer.inputBuffer.viewport.copy(e),this.effectComposer.outputBuffer.viewport.copy(e)):(this.effectComposer.inputBuffer.viewport.set(e,r,i,s),this.effectComposer.outputBuffer.viewport.set(e,r,i,s))}resize(e,r,i){if(this.effectComposer.setSize(e,r,i),this._rt){let s=this.renderer.getPixelRatio();this._rt.setSize(e*s,r*s)}}dispose(){this.uvEffectPass?.dispose(),this.effectPass?.dispose(),this.effectComposer.dispose()}};var $Q=n=>` // PCSS implementation based on: // https://www.gamedev.net/articles/programming/graphics/contact-hardening-soft-shadows-made-fast-r4906/ // NOTE: This number affects how big the shadow blur can // possibly get. Bigger number == bigger blur, but less precise results const float gPenumbraFilterSize = 80.0; const int gPenumbraSamples = ${n}; const int gShadowSamples = ${n}; const float gShadowSamplesRpc = 1.0f / float(gShadowSamples); #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_SHADOWS ]; struct SpotLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif /* #if NUM_RECT_AREA_LIGHTS > 0 // TODO (abelnation): create uniforms for area light shadows #endif */ float computePenumbra(int index, sampler2D shadowMap, float temporalAngle, float texelSize, vec2 uv, float compare, float texelScalar, float shadowRadius) { float penumbra = 1.0; float blockerDepthAvg = 0.0; float blockerCount = 0.0; #pragma unroll_loop_start for(int i = 0; i < gPenumbraSamples; i ++) { vec2 offset = (vogelDiskSample(i, gShadowSamples, temporalAngle) * texelSize) * texelScalar; float depth = unpackRGBAToDepth( texture2D( shadowMap, uv + offset ) ); if(depth < compare + 0.0001) { blockerDepthAvg += depth; blockerCount++; } } #pragma unroll_loop_end if (blockerCount > 0.0) { blockerDepthAvg /= blockerCount; // Compute penumbra penumbra = (compare - blockerDepthAvg) / (blockerDepthAvg); penumbra *= penumbra; penumbra *= 200.0 * penumbraSize[min(index, ${5} - 1)]; // Magic number that affects how quickly the penumbra grows return clamp(penumbra, 0.00, 1.0); } return 0.0; } float vogelShadow(int index, sampler2D shadowMap, vec2 uv, float texelSize, float compare, float shadowRadius) { float shadow = 0.0f; // NOTE: When using TAA, we should use screen space interleaved gradient noise vec2 halton = haltonSequence[frameIndex]; float temporalOffset = getNoiseInterleavedGradient(gl_FragCoord.xy + halton); float temporalAngle = temporalOffset * PI2; float texelScalar = (gPenumbraFilterSize) / (texelSize * 1024.); float penumbra = computePenumbra(index, shadowMap, temporalAngle, texelSize, uv, compare, texelScalar, shadowRadius); if (penumbra == -1.0) { return 1.0; } #pragma unroll_loop_start for (int i = 0; i < gShadowSamples; i++) { vec2 vogelSample = vogelDiskSample(i, gShadowSamples, temporalAngle) * texelSize; // Overall blurring offset vec2 offset = vogelSample * (shadowRadius * 2.); // Penumbra offset offset += vogelSample * (penumbra * texelScalar); shadow += step( compare, unpackRGBAToDepth( texture2D( shadowMap, uv + offset ) ) ); } #pragma unroll_loop_end return shadow * gShadowSamplesRpc; } float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); } vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { return unpackRGBATo2Half( texture2D( shadow, uv ) ); } float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ float occlusion = 1.0; vec2 distribution = texture2DDistribution( shadow, uv ); float hard_shadow = step( compare , distribution.x ); // Hard Shadow if (hard_shadow != 1.0 ) { float distance = compare - distribution.x ; float variance = max( 0.00000, distribution.y * distribution.y ); float softness_probability = variance / (variance + distance * distance ); // Chebeyshevs inequality softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); // 0.3 reduces light bleed occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); } return occlusion; } float getShadow( int i, sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; // if ( something && something ) breaks ATI OpenGL shader compiler // if ( all( something, something ) ) using this instead bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 ); bool inFrustum = all( inFrustumVec ); bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 ); bool frustumTest = all( frustumTestVec ); if ( frustumTest ) { #if defined( SHADOWMAP_TYPE_PCF ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; return vogelShadow(i, shadowMap, shadowCoord.xy, texelSize.x, shadowCoord.z, shadowRadius ); #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float dx = texelSize.x; float dy = texelSize.y; vec2 uv = shadowCoord.xy; vec2 f = fract( uv * shadowMapSize + 0.5 ); uv -= f * texelSize; shadow = ( texture2DCompare( shadowMap, uv, shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), f.x ), mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), f.x ), f.y ) ) * ( 1.0 / 9.0 ); #elif defined( SHADOWMAP_TYPE_VSM ) shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); #else // no percentage-closer filtering: shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); #endif } return shadow; } // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D // vector suitable for 2D texture mapping. This code uses the following layout for the // 2D texture: // // xzXZ // y Y // // Y - Positive y direction // y - Negative y direction // X - Positive x direction // x - Negative x direction // Z - Positive z direction // z - Negative z direction // // Source and test bed: // https://gist.github.com/tschw/da10c43c467ce8afd0c4 vec2 cubeToUV( vec3 v, float texelSizeY ) { // Number of texels to avoid at the edge of each square vec3 absV = abs( v ); // Intersect unit cube float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); absV *= scaleToCube; // Apply scale to avoid seams // two texels less per square (one texel will do for NEAREST) v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); // Unwrap // space: -1 ... 1 range for each square // // #X## dim := ( 4 , 2 ) // # # center := ( 1 , 1 ) vec2 planar = v.xy; float almostATexel = 1.5 * texelSizeY; float almostOne = 1.0 - almostATexel; if ( absV.z >= almostOne ) { if ( v.z > 0.0 ) planar.x = 4.0 - v.x; } else if ( absV.x >= almostOne ) { float signX = sign( v.x ); planar.x = v.z * signX + 2.0 * signX; } else if ( absV.y >= almostOne ) { float signY = sign( v.y ); planar.x = v.x + 2.0 * signY + 2.0; planar.y = v.z * signY - 2.0; } // Transform to UV space // scale := 0.5 / dim // translate := ( center + 0.5 ) / dim return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); } float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); // for point lights, the uniform @vShadowCoord is re-purposed to hold // the vector from the light to the world-space position of the fragment. vec3 lightToPosition = shadowCoord.xyz; // dp = normalized distance from light to fragment position float compare = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); // need to clamp? compare += shadowBias; // bd3D = base direction 3D vec3 bd3D = normalize( lightToPosition ); vec2 halton = haltonSequence[frameIndex]; float temporalOffset = getNoiseInterleavedGradient(gl_FragCoord.xy + halton); float temporalAngle = temporalOffset * PI2; #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_VSM ) for (int i = 0; i < gShadowSamples; i++) { vec2 vogelSample = vogelDiskSample(i, gShadowSamples, temporalAngle) * texelSize; // Overall blurring offset vec3 offset = vec3(vogelSample.x, vogelSample.y, -vogelSample.x) * (shadowRadius + 5.); // NOTE: Removed for now // Penumbra offset //offset += vec3(vogelSample.x, vogelSample.y, vogelSample.y) * (penumbra * gPenumbraFilterSize); shadow += texture2DCompare( shadowMap, cubeToUV( bd3D + offset, texelSize.y ), compare ); } return shadow * gShadowSamplesRpc; #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) for (int i = 0; i < 16; i++) { vec2 vogelSample = vogelDiskSample(i, gShadowSamples, temporalAngle) * texelSize; // Overall blurring offset vec3 offset = vec3(vogelSample.x, vogelSample.y, -vogelSample.x) * (shadowRadius + 5.); shadow += texture2DCompare( shadowMap, cubeToUV( bd3D + offset, texelSize.y ), compare ); } return shadow * (1.0 / 16.0); #else // no percentage-closer filtering return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), compare ); #endif } #endif `,eZ=xt.lights_fragment_begin,tZ=xt.shadowmask_pars_fragment,vL=null,rZ=n=>{switch(n){case"low":return 8;case"medium":return 16;case"high":return 32;default:return 16}},xL=(n="medium")=>{if(vL===n)return!1;vL=n;let t=rZ(n);xt.shadowmap_pars_fragment=$Q(t);let e=eZ.slice();e=e.replace("getShadow( spotShadowMap[ i ]",`getShadow( UNROLLED_LOOP_INDEX + ${3}, spotShadowMap[ i ]`),e=e.replace("getShadow( directionalShadowMap[ i ]","getShadow( UNROLLED_LOOP_INDEX, directionalShadowMap[ i ]"),xt.lights_fragment_begin=e;let r=tZ.slice();return r=r.replaceAll("getShadow(","getShadow( UNROLLED_LOOP_INDEX, "),xt.shadowmask_pars_fragment=r,!0};var iZ=` attribute vec3 randomColor; varying vec3 vNormal; flat out vec3 vColor; #include #include void main() { #include #include #include #include vec3 transformed = vec3(position); #include #include vNormal = normal; vColor = randomColor; gl_Position = projectionMatrix * (modelViewMatrix * vec4(transformed, 1.0)); } `,nZ=` uniform float depthContrast; varying vec3 vNormal; flat in vec3 vColor; void main() { vec3 normal = (normalize(vNormal)).rgb; float contrastDepth = (gl_FragCoord.z - 0.5) * depthContrast + 0.5; vec3 resultColor = mix(mix(vColor, normal, 0.2), vec3(contrastDepth), 0.4); gl_FragColor = vec4(resultColor, vColor.r); gl_FragColor = vec4(resultColor, vColor.r); } `,Ux=new it({vertexShader:iZ,fragmentShader:nZ,uniforms:{depthContrast:{value:1}}});var bL=new er,SL=new k,zx=class extends Hw{constructor(e){super(e);this._pixelRatio=this.getPixelRatio();this.viewportWidth=1;this.viewportHeight=1;this.resolution=new k;this.dummyCamera=new wr;this.sceneTransitionDuration=0;this.sceneTransitionTimeRemaining=-1;this.isXRCopyPassSet=!1;this.clear=(e=!0,r=!0,i=!0)=>{let s=this.getContext(),o=0;e&&(o|=s.COLOR_BUFFER_BIT),r&&(o|=s.DEPTH_BUFFER_BIT),i&&(o|=s.STENCIL_BUFFER_BIT),s.clear(o),s.clearBufferfv(s.COLOR,1,[0,0,0,1])};this.pipeline=new Gm(this,e?.needsDOFResize??!1),this.autoClear=!1;let r=this.setPixelRatio.bind(this),i=this.setSize.bind(this);this.shadowMap.enabled=!0,this.shadowMap.type=Ly,this.dummyCamera.matrixAutoUpdate=!1,this.domElement.removeAttribute("data-engine");let s=this.getContext();if(s&&"drawingBufferColorSpace"in s)try{s.drawingBufferColorSpace="display-p3"}catch(o){console.warn(o)}this.setPixelRatio=o=>{this._pixelRatio!==o&&(this._pixelRatio=o,r(o))},this.setSize=(o,a,l=!0)=>{(this.viewportWidth!==o||this.viewportHeight!==a)&&(this.viewportWidth=o,this.viewportHeight=a,i(o,a,l),this.normalRenderTarget?.setSize(o*this._pixelRatio,a*this._pixelRatio),this._resizeTransmission(o,a),this.transmissionDepthTarget?.setSize(o*this._pixelRatio/2,a*this._pixelRatio/2),this.pipeline.resize(o,a,l))},this._superDispose=this.dispose,this.dispose=this._currentDispose}createAORenderTarget(){this.aoRenderTarget===void 0&&(this.aoRenderTarget=new dt(this.viewportWidth*this._pixelRatio,this.viewportHeight*this._pixelRatio,{generateMipmaps:!1,minFilter:rt,magFilter:rt,wrapS:Qt,wrapT:Qt,depthBuffer:!1}))}_resizeTransmission(e,r){this.transmissionRenderTarget?.setSize(e*this._pixelRatio/(this.hdTransmission?1:2),r*this._pixelRatio/(this.hdTransmission?1:2)),this.aoRenderTarget?.setSize(e*this._pixelRatio/1,r*this._pixelRatio/1)}get hdTransmission(){return $e.transmissionLod.value===1}set hdTransmission(e){$e.transmissionLod.value=e===!0?1:2,this._resizeTransmission(this.viewportWidth,this.viewportHeight)}createTransmissionRenderTarget(){this.transmissionRenderTarget===void 0&&(this.transmissionRenderTarget=new dt(this.viewportWidth*this._pixelRatio/(this.hdTransmission?1:2),this.viewportHeight*this._pixelRatio/(this.hdTransmission?1:2),{generateMipmaps:!0,minFilter:xc,magFilter:rt,wrapS:Qt,wrapT:Qt,depthBuffer:!1}),this.transmissionDepthTarget=new dt(this.viewportWidth*this._pixelRatio/2,this.viewportHeight*this._pixelRatio/2,{minFilter:Vt,magFilter:Vt,depthBuffer:!1}))}createNormalRenderTarget(){this.normalRenderTarget===void 0&&(this.normalRenderTarget=new dt(this.viewportWidth*this._pixelRatio,this.viewportHeight*this._pixelRatio,{generateMipmaps:!1,minFilter:Vt,magFilter:Vt,type:br,depthTexture:new ns(this.viewportWidth*this._pixelRatio,this.viewportHeight*this._pixelRatio)}))}renderNormal(e,r,i){this.normalRenderTarget&&(this.setClearColor(0),i.layers.enable(8),i.layers.disable(0),i.layers.disable(3),r.traverseEntity(s=>{s.layers.isEnabled(8)&&(s.copyPreviousMatrix=!1)}),this.setRenderTarget(this.normalRenderTarget),this.clear(),i instanceof wr?Ux.uniforms.depthContrast.value=(i.far-i.near)/1e4:Ux.uniforms.depthContrast.value=1,r.overrideMaterial=Ux,this.render(r,i),this.setClearColor(r.bgColor,r.bgColor.a),this.setRenderTarget(null),r.overrideMaterial=e.wireframeState?Gx:null,i.layers.enable(0),i.layers.enable(3),r.traverseEntity(s=>{s.layers.isEnabled(8)&&(s.copyPreviousMatrix=!0)}))}renderSplineSceneWithDummyCamera(e,r,i=1){this.dummyCamera.updateCameraState(r.dataPatched),this.dummyCamera.matrix.copy(r.matrixWorld);let s=r.height,o=r.width,a=this.viewportWidth/this.viewportHeight;o{$e.penumbraSize.value[m]=p}),$e.pixelRatioNode.value=this.getPixelRatio(),this.resolution.x!==0&&this.resolution.y!==0?$e.resolution.value.set(this.resolution.x,this.resolution.y):$e.resolution.value.set(this.viewportWidth*this._pixelRatio,this.viewportHeight*this._pixelRatio),a!==void 0?($e.normalRenderTarget.value=a,$e.normalRenderTargetDepth.value=bL):u.needsNormal()&&(this.createNormalRenderTarget(),$e.normalRenderTarget.value=this.normalRenderTarget.texture,$e.normalRenderTargetDepth.value=this.normalRenderTarget.depthTexture,this.renderNormal(u,l,r));let h=l.data.ao,d=h.occlusion;if(d&&(this.createAORenderTarget(),$e.aoRenderTarget.value=this.aoRenderTarget.texture),$e.aoEnabled.value=d,this.pipeline.setAmbientOcclusionParams(h.occlusion,h.radius,h.bias,l.aoColor,l.fog!==null,l.backupFog.near,l.backupFog.far,h.aoFullRes&&!xo),this.pipeline.aoPass.setBlueNoiseTexture(this.pipeline.blueNoiseTexture),this.pipeline.isUIOverlayEnabled&&l.uiCanvas?.enabled&&l.uiCanvas.texture&&l.uiCanvas.texture.image.width>0){let p=this.getSize(SL),m=this.getPixelRatio();(l.uiCanvas.width!==this.viewportWidth||l.uiCanvas.height!==this.viewportHeight||l.uiCanvas.dpr!==m)&&l.uiCanvas.applySize({width:this.viewportWidth,height:this.viewportHeight},m),l.uiCanvas.render(this),this.pipeline.uiOverlayPass.uiCanvas=l.uiCanvas,this.pipeline.uiOverlayPass.enabled=!0,this.pipeline.uiOverlayPass.setResolution(p.x,p.y,m),this.pipeline.updateRenderToScreen()}else this.pipeline.uiOverlayPass.enabled=!1,this.pipeline.updateRenderToScreen();if(this.pipeline.logoOverlayPass.enabled){let p=this.getSize(SL),m=this.getPixelRatio();this.pipeline.logoOverlayPass.uniforms.uResolution.value.set(p.x,p.y),this.pipeline.logoOverlayPass.uniforms.uDPR.value=m}let f=!1;if(o!==void 0)$e.transmissionRenderTarget.value=o,$e.transmissionRenderTargetDepth.value=bL,this.pipeline.setTransmissionPassEnabled(!1);else{let p=u.needsTransmission();p&&(this.transmissionRenderTarget===void 0&&(f=!0),this.createTransmissionRenderTarget(),$e.transmissionRenderTarget.value=this.transmissionRenderTarget.texture,$e.aspectRatio.value=DR(this.viewportWidth,this.viewportHeight),$e.transmissionRenderTargetDepth.value=this.transmissionDepthTarget.texture),this.pipeline.setTransmissionPassEnabled(p)}r.layers.enable(3),r.layers.enable(8),this.pipeline.sceneHelpers=i,this.pipeline.sceneHelpersOnTop=s,this.pipeline.scene=l,this.pipeline.camera=r,f&&this.pipeline.transmissionPass.updatePasses(this),this.pipeline.postprocessingState!==l.postprocessing&&(this.pipeline.updatePostprocessing(l.postprocessing),!i&&!s&&this.pipeline.disableHelpers()),this.clearAlphaOverride!==void 0&&this.setClearAlpha(this.clearAlphaOverride),l.overrideMaterial=u.wireframeState?Gx:null,this.pipeline.render(),$e.frameIndex.value=($e.frameIndex.value+1)%16,r instanceof wr&&r.copyHistory(),l.visible=c}renderFromSceneForSceneTransitionPass(e,r,i){this.pipeline.renderToScreen=!1,this.pipeline.renderTarget,this.renderSplineScene(e,r),this.pipeline.sceneTransitionFromTexture=this.pipeline.renderTarget.texture,this.sceneTransitionDuration=i,this.sceneTransitionTimeRemaining=i,this.pipeline.renderToScreen=!0;let s=this.pipeline.sceneTransitionPass.uniforms;s.uDPR.value=window.devicePixelRatio,s.uResolution.value.set(this.domElement.width,this.domElement.height).divideScalar(window.devicePixelRatio)}_currentDispose(){this._superDispose(),this.pipeline.dispose(),this.aoRenderTarget?.dispose(),this.transmissionRenderTarget?.dispose(),this.transmissionDepthTarget?.dispose(),this.normalRenderTarget?.dispose(),this.normalRenderTarget?.depthTexture?.dispose()}};var Mf=class extends Uo(Oy){constructor(e,r=15,i=10066329){super(e,r,i);this.object=e;this.added=!1;this.name=`DirectionalLightHelper: ${e.uuid}`}raycast(e,r){zo(this.object,Mf.geometryHelper,e,r)}};var Cf=class extends Uo(Dy){constructor(e,r=15,i=6710886){super(e,r,i);this.object=e;this.name=`PointLightHelper: ${e.uuid}`}raycast(e,r){zo(this.object,Cf.geometryHelper,e,r)}};var jx=class extends Uo(Iy){constructor(e,r=6710886){super(e,r);this.object=e;this.name=`SpotLightHelper: ${e.uuid}`}raycast(e,r){zo(this.object,jx.geometryHelper,e,r)}update(){if(this.object!==void 0){let e=jx._vector,r=this.object.distance?this.object.distance:1e3,i=r*Math.tan(this.object.angle);this.cone.scale.set(i,i,r),e.setFromMatrixPosition(this.object.target.matrixWorld),this.cone.lookAt(e);let s=this.color!==void 0?this.color:this.light.color;if(this.cone.material instanceof Array)for(let o=0,a=this.cone.material.length;o0?Hx(i,e-1):[null,null];(e>0&&i.length?i[a].charAt(l):null)===` `&&(s++,o=0),this.current.start=e,this.current.end=void 0;let[u,h]=rT(this.object,s,o),{AD:d,descender:f}=this.object,p=f+d*.5,{width:m,height:g,depth:y}=this.object.geometry.userData.parameters,v=typeof m=="string"?0:m,x=typeof g=="string"?0:g;this.caretMesh.scale.set(1,this.caretHeight,1),this.caretMesh.position.set(u-v*.5,h+p+x*.5,y),this.hideSelectionMesh(),this.showCaretMesh()}setSelection(e,r){if(this.object===void 0)return;let i=this.object.wrappedText;this.current.start=e,this.current.end=r;let s=[],o=[],a=aZ(i,e,r),{lineHeight:l,AD:c,descender:u}=this.object,h=u+c*.5-l*.5;for(let[v,x,S]of a)if(x!==S){let[w,A]=rT(this.object,v,x),[T,b]=rT(this.object,v,S);A+=h,b+=h,b+=l;let M=s.length/3;s.push(w,A,0),s.push(T,A,0),s.push(T,b,0),s.push(w,b,0),o.push(M+0,M+1,M+2),o.push(M+2,M+3,M+0)}let d=new _e;d.setIndex(o),d.setAttribute("position",new Te(s,3));let{width:f,height:p,depth:m}=this.object.geometry.userData.parameters,g=typeof f=="string"?0:f,y=typeof p=="string"?0:p;this.selectionMesh.geometry.dispose(),this.selectionMesh.geometry=d,this.selectionMesh.position.x=-g*.5,this.selectionMesh.position.y=y*.5,this.selectionMesh.position.z=m,this.showSelectionMesh(),this.hideCaretMesh()}getSelectionFromPosition(e,r,i="previous"){if(this.object===void 0||this.object.font===void 0)return;let s=this.object.wrappedText,o=s.length,a=this.object.lineHeight,l=o*a,{height:c,verticalAlign:u}=this.object.geometry.userData.parameters,h=typeof c=="string"?0:c,d=0;u===3?d=h-l:u===2&&(d=h*.5-l*.5);let f=Math.min(Math.floor(Math.max(Math.min(-r-d,l),0)/a),o-1),p=this.object.charCoords[f],m=this.object.charWidths[f],g=0,y=!1;if(i==="previous"){for(let x=0;x0){g=x,y=!0;break}}else if(i==="closest"){let x=1/0;for(let S=0;S=S&&es+=o.length,0)+i}showSelectionMesh(){this.selectionMesh.material.opacity=this._selectionVisibleAlpha}hideSelectionMesh(){this.selectionMesh.material.opacity=0}showCaretMesh(){this.caretMesh.material.opacity=this._caretVisibleAlpha}hideCaretMesh(){this.caretMesh.material.opacity=0}};function rT(n,t,e){let{charCoords:r,charWidths:i,initialOffsetY:s,lineHeight:o}=n;if(r[t]&&r[t].length===0||r.length===0){let u=0,{horizontalAlign:h}=n.data.geometry,d=n.wrappedText,{width:f}=n.geometry.userData.parameters;return d.length===1&&d[0].length===0&&(h===3?u=f*.5:h===2&&(u=f)),[u,s-o*t]}let a=r[t];if(a===void 0||a.length===0)return[0,0];let[l,c]=a[Math.min(e,a.length-1)];return e>=a.length&&(l+=i[t][e-1]),[l,c]}function Hx(n,t){let e=0;for(let r=0;r=n[r].length&&(r++,i=0);for(let l=r;l<=s;l++){let c=n[l],u=l===r?i:0,h=l===s?o:c.length;a.push([l,u,h])}return a}function wL(n,t){let e=ri.fromHex(3223857),r=.8;for(let i of n.layers){if(i.data.type==="light"||i.data.type==="displace"||i.data.type==="fresnel"||i.data.type==="matcap"||i.data.type==="texture"||i.data.type==="toon"||i.data.type==="outline"||i.data.type==="transmission"||i.data.type==="noise")continue;let s=typeof i.data.alpha=="string"?Number(t.getVariable(i.data.alpha)):i.data.alpha;if(i.data.type==="color"&&s>.3){e=lZ(i.data.color,t),r=s;break}else if((i.data.type==="depth"||i.data.type==="gradient")&&s>.3){let o=cZ(i.data);e={r:o[0],g:o[1],b:o[2]},r=typeof i.data.alpha=="string"?1:i.data.alpha;break}}return{...e,a:r}}function lZ(n,t){return typeof n=="string"?t.data.colors[n]:n}function cZ(n){return n.colors[0]}function uZ(n,t){n.shadow.camera.right=t/2,n.shadow.camera.left=-t/2,n.shadow.camera.top=t/2,n.shadow.camera.bottom=-t/2,n.shadow.needsUpdate=!0}var _f=class extends df(Cy,Mf){constructor(t,e,r){super(),this.super_Entity(t,e),this.castShadow=!0,this.shadow.mapSize.width=2048,this.shadow.mapSize.height=2048,this.shadow.normalBias=1,this.layers.enable(3);let s=this.shadow.camera;s.top=1250,s.bottom=-1250,s.right=1250,s.left=-1250,s.near=-1e4,s.far=2500;let o=new dl(this.shadow.camera);o.visible=!1,this.gizmos.shadowmap=o}update(){this.shadow.camera.updateProjectionMatrix();for(let t in this.gizmos){let e=this.gizmos[t];e instanceof dl&&e.update()}}updateMatrixWorld(t){super.updateMatrixWorld(t),this.objectHelper&&this.objectHelper.update()}updateState(t,e){this.updateState_Light(t,e);let r=t.depth!==void 0&&t.depth!==this.shadow.camera.far||t.size!==void 0&&t.size/2!==this.shadow.camera.right;t.size!==void 0&&uZ(this,t.size),t.shadowRadius!==void 0&&(this.shadow.radius=t.shadowRadius),t.shadowResolution!==void 0&&(this.shadow.mapSize.set(t.shadowResolution,t.shadowResolution),this.shadow.map&&(this.shadow.map.dispose(),this.shadow.map=null)),t.penumbraSize!==void 0&&e.scene.markPenumbraSizeDirty(),r&&this.update()}};var AL=new E,EL=new E,TL=new Ke,If=class extends df(Ty,jm){constructor(t,e,r){super(),this.super_Entity(t,e),this.castShadow=!0,this.shadow.mapSize.width=1024,this.shadow.mapSize.height=1024,this.shadow.normalBias=1,this.layers.enable(3);let s=this.shadow.camera;s.fov=we.RAD2DEG*2*this.angle,s.aspect=1,s.near=100,s.far=2500;let o=new dl(this.shadow.camera);o.visible=!1,this.gizmos.shadowmap=o,this.update()}update(){this.shadow.camera.updateProjectionMatrix();for(let t in this.gizmos){let e=this.gizmos[t];e instanceof dl&&e.update()}}updateMatrixWorld(t){super.updateMatrixWorld(t),EL.setFromMatrixPosition(this.matrixWorld),TL.setFromRotationMatrix(this.matrixWorld),AL.copy(this.up).applyQuaternion(TL).negate().multiplyScalar(this.distance),this.target.position.copy(EL).add(AL),this.target.updateMatrixWorld(),this.objectHelper&&this.objectHelper.update()}updateState(t,e){this.updateState_Light(t,e),t.distance!==void 0&&(this.distance=t.distance),t.decay!==void 0&&(this.decay=t.decay),t.angle!==void 0&&(this.angle=t.angle),t.penumbra!==void 0&&(this.penumbra=t.penumbra),t.shadowRadius!==void 0&&(this.shadow.radius=t.shadowRadius),t.penumbraSize!==void 0&&e.scene.markPenumbraSizeDirty(),t.shadowResolution!==void 0&&(this.shadow.mapSize.set(t.shadowResolution,t.shadowResolution),this.shadow.map&&(this.shadow.map.dispose(),this.shadow.map=null))}};function hZ(n){let t=(n[0][0]+n[1][1])/2,e=(n[0][0]-n[1][1])/2,r=(n[1][0]+n[0][1])/2,i=(n[1][0]-n[0][1])/2,s=Math.sqrt(t*t+i*i),o=Math.sqrt(e*e+r*r),a=s+o,l=s-o,c=Math.atan2(r,e),u=Math.atan2(i,t),h=(u-c)/2,d=(u+c)/2,f=[[Math.cos(d),Math.sin(d)],[-Math.sin(d),Math.cos(d)]],p=[[a,0],[0,l]],m=[[Math.cos(h),Math.sin(h)],[-Math.sin(h),Math.cos(h)]];return f[0][0]*=-1,f[0][1]*=-1,m[0][0]*=-1,m[1][0]*=-1,[f,p,m]}function Wx(n,t){return[[n[0][0]*t[0][0]+n[0][1]*t[1][0],n[0][0]*t[0][1]+n[0][1]*t[1][1]],[n[1][0]*t[0][0]+n[1][1]*t[1][0],n[1][0]*t[0][1]+n[1][1]*t[1][1]]]}function ML(n){return[[n[0][0],n[1][0]],[n[0][1],n[1][1]]]}function CL(n){let[t,e,r]=hZ(n),i=Wx(t,ML(r)),s=Wx(Wx(r,e),ML(r)),o=Math.atan2(i[1][0],i[0][0]),a=[s[0][0],s[1][1]],l=[s[0][1]/s[1][1],s[1][0]/s[0][0]];return{rotation:o,scale:a,shear:l}}function PL({rotation:n,scale:t,shear:e}){let r=Math.cos(n),i=Math.sin(n),s=[[r,-i],[i,r]],o=[[t[0],e[0]*t[1]],[e[1]*t[0],t[1]]],a=Wx(s,o);return[a[0][0],a[1][0],a[0][1],a[1][1]]}var St;(w=>{function n(){return[1,0,0,0,1,0,0,0,1]}w.identity=n;function t(A,T=w.identity()){for(let b=0,M=A.length;b=i[0]&&t<=s[0]&&e>=i[1]&&e<=s[1]}applyTransforms(t){t.setTransform(this.worldMatrix,this.ignoreCameraZoom)}get singleBBox(){return this.singleBBoxNeedsUpdate&&(this.singleBBoxNeedsUpdate=!1,this._singleBBox.setFromObjectSize(this,!1),this._singleBBox.computeVertices(),this._singleBBox.computeEdges()),this._singleBBox}get recursiveBBox(){return this.recursiveBBoxNeedsUpdate&&(this.recursiveBBoxNeedsUpdate=!1,this._recursiveBBox.setFromObjectSize(this,!0),this._recursiveBBox.computeVertices(),this._recursiveBBox.computeEdges()),this._recursiveBBox}updateLocalMatrix(){this.localMatrix=St.compose(this.position,this.scale,IL(this.rotation),Ca.getPivot(this.dataPatched),this.shear)}updateWorldMatrix(t,e,r){let i=this.parent;e&&i!==null&&i!==void 0&&i.updateWorldMatrix(t,!0,!1),t&&this.updateLocalMatrix(),this.parent?this.worldMatrix=St.append(this.parent.worldMatrix,this.localMatrix):this.worldMatrix=St.copy(this.localMatrix),this.singleBBoxNeedsUpdate=!0,this.recursiveBBoxNeedsUpdate=!0}get pivot(){return Ca.getPivot(this.data)}getCenter(){return[0,0]}getHalfSize(){return[0,0]}get id(){return this.uuid}resetBBoxNeedsUpdateSelf(){this.singleBBoxNeedsUpdate=!0,this.recursiveBBoxNeedsUpdate=!0}resetBBoxNeedsUpdate(){this.resetBBoxNeedsUpdateSelf(),this.traverseAncestors(t=>{t.resetBBoxNeedsUpdateSelf()})}updateTransformState(t){let e=!1;t.position!==void 0&&(e=!0,this.position=t.position),t.rotation!==void 0&&(e=!0,this.rotation=t.rotation),t.scale!==void 0&&(e=!0,this.scale=t.scale),t.shear!==void 0&&(e=!0,this.shear=t.shear),e&&(this.updateWorldMatrix(!0,!1,!0),this.resetBBoxNeedsUpdate())}updateByOp(t,e,r){t.type===0&&t.props.visible!==void 0&&(this.visible=t.props.visible),this.data=e,this.data=e;let i=t,s=Lt(t.path,["states","*"]);if(s!==null){if(t.type===0){let[o]=s;if(this?.stateSelection===o){let a={...t.props};if(delete a.name,Object.values(t.props).some(l=>l===void 0)){let l=this.data;if(l!==void 0){let c=Sr.zoom(l,t.path.slice(2));if(c)for(let u in t.props)t.props[u]===void 0&&u in c&&(a[u]=c[u])}}i={...t,props:a,path:t.path.slice(2)}}}}else if(t.type===0){let o=this.stateSelection?this.data.states.data(this.stateSelection):void 0;if(o!==void 0){if(t.props.name!==void 0&&o.name){let{name:l,...c}=o;o=c}let a=Sr.removeOverridden(t.path,t.props,o);i={...t,props:a}}}this.updateByPatchedOpBase(i,Ma.patch(this.data,this.stateSelection?this.data.states.data(this.stateSelection):void 0),r)}changeSelectedState(t,e,r=!1){if(!(this.data.states.length===0&&!r)){for(let i of this.data.states)Ma.toOps(this.data,i.data).forEach(o=>{let a=Vh.replaceProps(o,this.data);this.dataPatched=this.data,this.updateByPatchedOp(a,this.data,e)});if(t!==null){let i=this.data.states.data(t);i&&(this.dataPatched=Ma.patch(this.data,i),Ma.toOps(this.data,i).forEach(o=>{this.updateByPatchedOp(o,this.dataPatched,e)}))}r&&this.updateTransformState(this.dataPatched),this.stateSelection=t}}updateState(t,e){t.name!==void 0&&(this.name=t.name),t.visible!==void 0&&(this.visible=t.visible),this.updateTransformState(t)}updateByPatchedOpBase(t,e,r){this.dataPatched=e,this.updateByPatchedOp(t,e,r)}updateByPatchedOp(t,e,r){t.path.length===0&&t.type===0&&this.updateState(t.props,r),this.requestRender()}traverseFrameAncestors(t){this.traverseAncestors(e=>{e.data.type==="frame2d"&&t(e)})}traverseAncestors(t){let e=this.parent;for(;e;)t(e),e=e.parent}requestRender(){this.traverseFrameAncestors(t=>{t.requestRender()})}clone(t){let e=new rr(this.uuid,this.data,t);return e.parent=void 0,e}addEventListener(t,e){this.emitter.on(t,e)}removeEventListener(t,e){this.emitter.off(t,e)}dispatchEvent(t){this.emitter.emit(t.type,{...t,target:t.target??this})}traverseSortNextHelper(){let t=this.parent;if(t){let e=t.children;if(e){let r=e.indexOf(this)+1;return e[r]?e[r]:t.traverseSortNextHelper()}}}sortNext(){let t=this.children;return t&&t.length>0&&t[0]?t[0]:this.traverseSortNextHelper()}isDescendantOf(t){t instanceof rr&&(t=t.uuid);let e=this;for(;e.parent;){if(e.parent.uuid===t)return!0;e=e.parent}return!1}};var Zi=class extends rr{constructor(e,r,i){super(e,r,i);this.uuid=e;this.data=r;this.context=i;this.children=[]}add(e){e.parent&&e.parent instanceof Zi&&e.parent.remove(e),this.children.push(e),e.parent=this}remove(e){let r=this.children.indexOf(e);r>=0&&(this.children.splice(r,1),e.parent=void 0)}traverse(e){let r=e(this);if(r!==!0)for(let i of this.children)i instanceof Zi?i.traverse(e):r=e(i)}intersectsChildrenHelper(e,r,i,s,o){for(let a of this.children)if(a.intersects(e,r,i,!1)&&(o.push(a),s)||a instanceof Zi&&a.intersectsChildrenHelper(e,r,i,s,o))return!0;return!1}intersectsChildren(e,r,i,s=!1,o=[],a=!1){return this.intersectsChildrenHelper(e,r,i,s,o),o}intersectsChildrenHelperReverse(e,r,i,s,o){for(let a of this.children)if(a instanceof Zi&&a.intersectsChildrenHelperReverse(e,r,i,s,o)||a.intersects(e,r,i,!1)&&(o.push(a),s))return!0;return!1}intersectsChildrenReverse(e,r,i,s=!1,o=[],a=!1){return this.intersectsChildrenHelperReverse(e,r,i,s,o),o}updateWorldMatrix(e,r,i){if(super.updateWorldMatrix(e,r,i),i&&this.children)for(let s of this.children)s.updateWorldMatrix(e,!1,!0)}find(e){let r;return this.traverse(i=>{i.uuid===e&&(r=i)}),r}innerDrawChildren(e){for(let r=this.children.length-1;r>=0;r--)this.children[r].draw(e)}resetBBoxNeedsUpdate(){super.resetBBoxNeedsUpdate(),this.traverse(e=>{e.resetBBoxNeedsUpdateSelf()})}clone(e){let r=new Zi(this.uuid,this.data,e);r.parent=void 0;for(let i of this.children)r.add(i.clone(e));return r}},kn=class extends Zi{constructor(e,r,i){super(e,r,i);this.uuid=e;this.data=r;this.updateState(r,i)}draw(e){!this.visible||(e.save(),this.applyTransforms(e),this.innerDrawChildren(e),e.restore())}clone(e){let r=new kn(this.uuid,this.data,e);r.parent=void 0;for(let i of this.children)r.add(i.clone(e));return r}};function fZ(n,t){let[[e,r],[i,s]]=n,[[o,a],[l,c]]=t,u=(e-i)*(a-c)-(r-s)*(o-l);if(u===0)return!1;let h=((e-o)*(a-c)-(r-a)*(o-l))/u,d=-((e-i)*(r-a)-(r-s)*(e-o))/u;return h>=0&&h<=1&&d>=0&&d<=1}var OL=[[-1,1],[-1,-1],[1,-1],[1,1]],DL=(n,t,e)=>{let r=n.getCenter(),i=n.getHalfSize(),s=St.append(t,n.worldMatrix);i[0]===0&&i[1]===0?e.push(St.apply(r,s)):OL.forEach(o=>{let a=[o[0]*i[0]+r[0],o[1]*i[1]+r[1]];e.push(St.apply(a,s))})},$l=class{constructor(){this.matrix=St.identity();this.min=[1/0,1/0];this.max=[-1/0,-1/0];this.vertices=[];this.edges=[]}setFromObjectSize(t,e=!1){t.updateWorldMatrix(),this.makeEmpty(),St.copy(t.worldMatrix,this.matrix);let r=St.invert(t.worldMatrix);this.expandByObjectSize(t,r,e)}expandByObjectSize(t,e,r=!1){let i=[];r===!0&&t instanceof Zi?t.traverse(s=>{s.visible&&DL(s,e,i)}):DL(t,e,i),this.setFromPoints(i)}setFromSize(t,e,r){this.makeEmpty(),St.copy(r,this.matrix),this.expandBySize(t,e,r)}expandBySize(t,e,r){[St.apply([0,0],r),St.apply([0,e],r),St.apply([t,e],r),St.apply([t,0],r)].forEach(s=>this.expandByPoint(s))}getCenter(){let[t,e]=this.min,[r,i]=this.getHalfSize();return St.apply([t+r,e+i],this.matrix)}getSize(){return[this.max[0]-this.min[0],this.max[1]-this.min[1]]}getHalfSize(){return[(this.max[0]-this.min[0])*.5,(this.max[1]-this.min[1])*.5]}makeEmpty(){this.min=[1/0,1/0],this.max=[-1/0,-1/0]}setFromPoints(t){this.makeEmpty();for(let e of t)this.expandByPoint(e)}expandByPoint(t){this.min=[Math.min(this.min[0],t[0]),Math.min(this.min[1],t[1])],this.max=[Math.max(this.max[0],t[0]),Math.max(this.max[1],t[1])]}computeVertices(){let[t,e]=this.getHalfSize(),r=this.getCenter(),[i,s,o,a]=St.getAbcdef(this.matrix),l=St.create(i,s,o,a,r[0],r[1]);this.vertices=OL.map(([c,u])=>St.apply([c*t,u*e],l))}computeEdges(){this.edges=[];for(let t=0,e=this.vertices.length;t=r[0]&&t<=i[0]&&e>=r[1]&&e<=i[1]}containsPoint(t){let[e,r]=t,[i,s]=this.min,[o,a]=this.max;return e>=i&&e<=o&&r>=s&&r<=a}intersectsBBox2D(t){for(let e=0,r=this.edges.length;e{LL=n}),RL=!1;var qx;function NL(){if(RL)return;if(qx)return qx;async function n(){let e=await import("./ui.js");LL(e.default??e),RL=!0}return qx=n(),qx}function nT(n){let t=!1;return n.scene.objects.traverse((e,r)=>{(r.type==="Mesh"&&r.geometry.type==="UIGeometry"||r.type==="Page"&&r.uiFrame!==void 0)&&(t=!0)}),t}var pt,iT;async function pZ(n){let t=await BL;pt||(iT||(iT=t({locateFile:()=>n})),pt=await iT)}var FL=St.identity(),Hm=class{constructor(t,e=1){this.canvas=t;this._dpr=e;this._width=0;this._height=0;this._strokeMode="inside";this._layerBlur=0;this._backgroundBlur=0;this._dropShadowBlur=0;this._dropShadowOffsetX=0;this._dropShadowOffsetY=0;this._dropShadowColor=bt.transparent;this._innerShadowBlur=0;this._innerShadowOffsetX=0;this._innerShadowOffsetY=0;this._innerShadowSpread=0;this._innerShadowColor=bt.transparent;this._fonts=new Map;this._isSizeDirty=!1;try{let r=t.getBoundingClientRect();t.width=r.width*e,t.height=r.height*e}catch{console.log(t.width,e)}this._currentM3Transform=FL,this._currentTransform=new Float32Array(FL)}get dpr(){return this._dpr}set dpr(t){this._dpr=t,this._isSizeDirty=!0}async init(){if(!this.wasmURL)throw Error("Your must set the wasm binary url with renderer.wasmURL = ... before you can call renderer.init");await pZ(this.wasmURL),this._surface=pt.MakeWebGLCanvasSurface(this.canvas),this.ctx=this._surface?.getCanvas(),this._paint=new pt.Paint,this._paint.setAntiAlias(!0),this._paintFill=this._paint.copy(),this._paintFill.setStyle(pt.PaintStyle.Fill),this._paintStroke=this._paint.copy(),this._paintStroke.setStyle(pt.PaintStyle.Stroke),this.ctx?.scale(this.dpr,this.dpr)}get currentTransform(){return this._currentM3Transform}get currentTransformBuffer(){return this._currentTransform}set currentTransform(t){this._currentM3Transform=t,this._currentTransform.set(t)}async loadFont(t,e){let r=await(await fetch(t)).arrayBuffer();this.registerFont(r,e)}registerFont(t,e){if(this._fonts.has(e))return;let r=pt.FontMgr.FromData(t);if(r)this._fonts.set(e,r);else throw new Error("Invalid font data for "+e)}get width(){return this._width}get height(){return this._height}set strokeColor(t){this._paintStroke&&this._paintStroke.setColor(Yx(t),pt.ColorSpace.DISPLAY_P3)}set fillColor(t){this._paintFill&&this._paintFill.setColor(Yx(t),pt.ColorSpace.DISPLAY_P3)}set lineWidth(t){this._paintStroke&&this._paintStroke.setStrokeWidth(this._strokeMode==="center"?t:t*2)}set strokeMode(t){this._strokeMode=t}set dropShadowBlur(t){this._dropShadowBlur=t}set dropShadowColor(t){this._dropShadowColor=t}set dropShadowOffsetX(t){this._dropShadowOffsetX=t}set dropShadowOffsetY(t){this._dropShadowOffsetY=t}set innerShadowBlur(t){this._innerShadowBlur=t}set innerShadowColor(t){this._innerShadowColor=t}set innerShadowOffsetX(t){this._innerShadowOffsetX=t}set innerShadowOffsetY(t){this._innerShadowOffsetY=t}set innerShadowSpread(t){this._innerShadowSpread=t}set layerBlur(t){this._layerBlur=t}set backgroundBlur(t){this._backgroundBlur=t}clear(){this.ctx?.clear(pt.TRANSPARENT)}save(){this.ctx?.save()}restore(){this.ctx?.restore()}beginPath(){this._currentPath?.delete(),this._currentPath=new pt.Path}closePath(){let t=this._currentPath;if(t){if(t.isEmpty())return;let e=t.getBounds();(e[3]-e[1]||e[2]-e[0])&&t.close()}}fill(){this._paintInner(this._paintFill,!0)}stroke(){this._paintInner(this._paintStroke,!1)}clipRect(t,e,r,i,s=0,o=0,a=0,l=0){let c=pt.XYWHRect(t,e,r,i);if(s===0&&o===0&&l===0&&a===0)this.ctx?.clipRect(c,pt.ClipOp.Intersect,!0);else{let u=pt.RRectXY(c,s,s);u[4]=u[5]=s,u[6]=u[7]=o,u[8]=u[9]=a,u[10]=u[11]=l,this.ctx?.clipRRect(u,pt.ClipOp.Intersect,!0)}}_applyShadowOffsetMatrix(){if(this.ctx){let t=St.invert(this.currentTransform);this.ctx.concat(t);let e=St.translate(St.identity(),this._dropShadowOffsetX,this._dropShadowOffsetY);this.ctx.concat(e),this.ctx.concat(this._currentTransform)}}_applyEffectsToPaint(t,e,r=!0){if(this.ctx&&this._currentPath){let i,s=!1;if(r&&this._hasDropShadow()){let o=t.copy();o.setColor(Yx(this._dropShadowColor));let a;this._dropShadowBlur>0&&(a=pt.MaskFilter.MakeBlur(pt.BlurStyle.Normal,this._dropShadowBlur*this.dpr*(this.camera?.scale??1),!1),o.setMaskFilter(a)),this.ctx.save(),this.ctx.clipPath(this._currentPath,pt.ClipOp.Difference,!0),this._applyShadowOffsetMatrix(),e(o),this.ctx.restore(),o.delete(),a?.delete()}if(this._backgroundBlur>0&&r){this.ctx.save(),this.ctx.clipPath(this._currentPath,pt.ClipOp.Intersect,!0);let o=pt.ImageFilter.MakeBlur(this._backgroundBlur,this._backgroundBlur,pt.TileMode.Clamp,null),a=t.copy();a.setImageFilter(o),a.setAlphaf(1);let l=this._currentPath.computeTightBounds();this.ctx.saveLayer(a,l,null,pt.SaveLayerInitWithPrevious),this.ctx.drawColor(t.getColor()),this.ctx.restore(),this.ctx.restore(),a.delete(),o.delete(),s=!0}if(this._layerBlur>0){let o=t.copy();i=pt.MaskFilter.MakeBlur(pt.BlurStyle.Normal,this._layerBlur*this.dpr*(this.camera?.scale??1),!1),o.setMaskFilter(i),e(o),o.delete(),i.delete(),s=!0}if(s||e(t),r&&this._hasInnerShadow()){let o=new pt.Paint;o.setAntiAlias(!0),o.setStyle(pt.PaintStyle.Fill),o.setColor(Yx(this._innerShadowColor));let a;this._innerShadowBlur>0&&(a=pt.MaskFilter.MakeBlur(pt.BlurStyle.Normal,this._innerShadowBlur*this.dpr*(this.camera?.scale??1),!1),o.setMaskFilter(a));let l=this._currentPath.computeTightBounds(),[c,u,h,d]=l,f=h-c,p=d-u;this.ctx.save(),this.ctx.clipPath(this._currentPath,pt.ClipOp.Intersect,!0),this.ctx.saveLayer(o,l,null,pt.SaveLayerInitWithPrevious),this.ctx?.translate(this._innerShadowOffsetX,this._innerShadowOffsetY),this.ctx.drawRect(pt.XYWHRect(-1e3-this._innerShadowOffsetX,-1e3-this._innerShadowOffsetY,2e3+f+Math.abs(this._innerShadowOffsetX*2),2e3+p+Math.abs(this._innerShadowOffsetY*2)),o),o.setBlendMode(pt.BlendMode.Clear),this.ctx.drawPath(this._currentPath,o),this.ctx.restore(),this.ctx.restore(),o.delete(),a?.delete()}}}_paintInner(t,e=!0){if(this.ctx&&this._currentPath&&t){let r=this.ctx,i=this._currentPath;this._applyEffectsToPaint(t,s=>{let o=!1;!e&&this._strokeMode!=="center"&&(r.save(),r.clipPath(i,this._strokeMode==="outside"?pt.ClipOp.Difference:pt.ClipOp.Intersect,!0),o=!0),r.drawPath(i,s),o&&r.restore()},e)}}_hasDropShadow(){return this._dropShadowColor?.a>0}_hasInnerShadow(){return this._innerShadowColor?.a>0}path(t){this._currentPath?.addPath(pt.Path.MakeFromSVGString(t))}ellipse(t,e,r,i,s,o,a,l){if(!VL([t,e,r,i])||!this._currentPath)return;if(r<0||i<0)throw Error("radii cannot be negative");let c=pt.XYWHRect(t-r,e-i,r*2,i*2);this._currentPath?.addOval(c)}rect(t,e,r,i,s=0,o=0,a=0,l=0){let c=pt.XYWHRect(t,e,r,i);if(!!VL(c))if(s===0&&o===0&&l===0&&a===0)this._currentPath?.addRect(c);else{let u=pt.RRectXY(c,s,s);u[4]=u[5]=s,u[6]=u[7]=o,u[8]=u[9]=a,u[10]=u[11]=l,this._currentPath?.addRRect(u)}}getHorizontalAlign(t){switch(t){case 2:return pt.TextAlign.Right;case 3:return pt.TextAlign.Center;case 4:return pt.TextAlign.Justify;case 1:default:return pt.TextAlign.Left}}drawTextInner(t,e,r,[i,s,o,a],l,c,u=!0){let h=0,{ctx:d}=this;if(!d)return h;let f=c.copy(),p=c.copy();return p.setAlphaf(0),this._applyEffectsToPaint(f,m=>{e.pushPaintStyle(r,m,p),e.addText(t);let g=e.build();g.layout(o);let y=s;l===2?y+=(a-g.getHeight())/2:l===3&&(y+=a-g.getHeight()),d.drawParagraph(g,i,y),h=g.getHeight(),e.reset(),g.delete()},u),f.delete(),p.delete(),h}drawText(t,e){let r=0,i=this._fonts.get(e.font),{ctx:s,_paintFill:o,_paintStroke:a}=this;if(i&&s){let l=new pt.TextStyle({fontFamilies:[e.font],fontSize:e.fontSize,heightMultiplier:e.lineHeight,letterSpacing:e.letterSpacing}),c=new pt.ParagraphStyle({textStyle:l,textAlign:this.getHorizontalAlign(e.horizontalAlign)}),u=pt.XYWHRect(e.x,e.y,e.width,e.height),h=pt.ParagraphBuilder.Make(c,i);o&&(r=this.drawTextInner(t,h,l,u,e.verticalAlign,o,!0)),a&&(r=this.drawTextInner(t,h,l,u,e.verticalAlign,a,!1)),h.delete()}return{height:r}}render(){this._surface?.flush()}moveTo(t,e){this._currentPath?.moveTo(t,e)}lineTo(t,e){this._currentPath?.lineTo(t,e)}bezierCurveTo(t,e,r,i,s,o){this._currentPath?.cubicTo(t,e,r,i,s,o)}quadraticCurveTo(t,e,r,i){this._currentPath?.quadTo(t,e,r,i)}setTransform(t,e=!1){if(!this.ctx)return;let r=this.ctx.getTotalMatrix(),i=St.invert(r);if(i&&this.ctx.concat(i),this.ctx?.scale(this.dpr,this.dpr),this.camera?.enabled&&(this.ctx?.concat(this.camera.worldMatrix),e)){let s=St.getScale(this.camera.worldMatrix);this.ctx?.scale(1/s[0],1/s[1])}this.ctx?.concat(t),this.currentTransform=t}transform(t){this.ctx?.concat(t)}setSize(t,e){!this._isSizeDirty&&t===this._width&&e===this._height||(this._isSizeDirty=!1,this._width=t,this._height=e,this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",this.canvas.width=t*this.dpr,this.canvas.height=e*this.dpr,this._surface&&(this._surface=pt.MakeWebGLCanvasSurface(this.canvas),this.ctx=this._surface?.getCanvas()))}};function VL(n){for(let t=0;t0?this.stroke.color:bt.transparent,e.strokeMode=this.stroke.mode,e.lineWidth=this.stroke.thickness}applyFilters(e){this.layerBlur.enabled?e.layerBlur=this.layerBlur.radius*5:e.layerBlur=0,this.backgroundBlur.enabled?e.backgroundBlur=this.backgroundBlur.radius*5:e.backgroundBlur=0,this.dropShadow.enabled?(e.dropShadowBlur=this.dropShadow.blurRadius*5,e.dropShadowColor=this.dropShadow.color,e.dropShadowOffsetX=this.dropShadow.offset[0],e.dropShadowOffsetY=this.dropShadow.offset[1]):e.dropShadowColor=bt.transparent,this.innerShadow.enabled?(e.innerShadowSpread=this.innerShadow.spread,e.innerShadowBlur=this.innerShadow.blurRadius*5,e.innerShadowColor=this.innerShadow.color,e.innerShadowOffsetX=this.innerShadow.offset[0],e.innerShadowOffsetY=this.innerShadow.offset[1]):e.innerShadowColor=bt.transparent}innerDraw(e){}draw(e){!this.visible||(e.save(),this.applyTransforms(e),this.applyFilters(e),this.applyFillStroke(e),e.beginPath(),this.innerDraw(e),this.autoClose&&e.closePath(),this.fill.enabled&&e.fill(),this.stroke.enabled&&e.stroke(),e.restore())}updateByPatchedOp(e,r,i){super.updateByPatchedOp(e,r,i),e.type===0&&(Lt(e.path,["fill"])?this.fill.update(e.props):Lt(e.path,["stroke"])?this.stroke.update(e.props):Lt(e.path,["dropShadow"])?this.dropShadow.update(e.props):Lt(e.path,["innerShadow"])?this.innerShadow.update(e.props):Lt(e.path,["layerBlur"])?this.layerBlur.update(e.props):Lt(e.path,["backgroundBlur"])?this.backgroundBlur.update(e.props):this.resetBBoxNeedsUpdate())}updateState(e,r){super.updateState(e,r),e.fill!==void 0&&this.fill.update(e.fill),e.stroke!==void 0&&this.stroke.update(e.stroke),e.dropShadow!==void 0&&this.dropShadow.update(e.dropShadow),e.innerShadow!==void 0&&this.innerShadow.update(e.innerShadow),e.layerBlur!==void 0&&this.layerBlur.update(e.layerBlur),e.backgroundBlur!==void 0&&this.backgroundBlur.update(e.backgroundBlur)}clone(e){let r=new Ar(this.uuid,this.data,e);return r.parent=void 0,r}};var ec=class extends Ar{constructor(e,r,i){super(e,r,i);this.uuid=e;this.data=r;this.width=0;this.height=0;this.updateState(r,i)}innerDraw(e){e.ellipse(this.width*.5,this.height*.5,this.width*.5,this.height*.5,0,0,Math.PI*2)}intersectsInLocalSpace(e,r){return _L(e,r,this.width*.5,this.height*.5,this.width*.5,this.height*.5)}getCenter(){return[this.width*.5,this.height*.5]}getHalfSize(){return[this.width*.5,this.height*.5]}updateSizeState(e){let r=!1;e.width!==void 0&&(this.width=typeof e.width=="number"?e.width:this.width,r=!0),e.height!==void 0&&(this.height=typeof e.height=="number"?e.height:this.height,r=!0),r&&this.updateWorldMatrix(!0,!1,!0)}updateState(e,r){super.updateState(e,r),this.updateSizeState(e)}clone(e){let r=new ec(this.uuid,this.data,e);return r.parent=void 0,r}};var Es=class extends Ar{constructor(e,r,i){super(e,r,i);this.uuid=e;this.data=r;this.width=0;this.height=0;this.cornerRadius=[0,0,0,0];this.updateState(r,i)}innerDraw(e){e.rect(0,0,this.width,this.height,...this.cornerRadius)}getCenter(){return[this.width*.5,this.height*.5]}getHalfSize(){return[this.width*.5,this.height*.5]}updateCornerState(e){e.cornerRadius!==void 0&&(this.cornerRadius=e.cornerRadius)}updateSizeState(e){let r=!1;e.width!==void 0&&(this.width=typeof e.width=="number"?e.width:this.width,r=!0),e.height!==void 0&&(this.height=typeof e.height=="number"?e.height:this.height,r=!0),r&&this.updateWorldMatrix(!0,!1,!0)}updateState(e,r){super.updateState(e,r),this.updateSizeState(e),this.updateCornerState(e)}clone(e){let r=new Es(this.uuid,this.data,e);return r.parent=void 0,r}};var tc=class extends Ar{constructor(e,r,i){super(e,r,i);this.uuid=e;this.data=r;this._textHeight=0;this._textHeightDirty=!0;this.width=0;this.height=0;this.updateState(r,i)}get textHeight(){return this._textHeight}applyFillStroke(e){e.fillColor=this.fill.enabled?this.fill.color:bt.transparent,e.strokeColor=this.stroke.enabled&&this.stroke.thickness>0?this.stroke.color:bt.transparent,e.strokeMode="center",e.lineWidth=this.stroke.thickness}innerDraw(e){this._fontHolder?.arrayBuffer&&this._fontHolder.arrayBuffer.byteLength>1&&this.data.font&&e.registerFont(this._fontHolder.arrayBuffer,this.data.font);let r=this.data.textTransform,i=this.data.text.textValue.toString(),s=r===2?i.toUpperCase():r===3?i.toLowerCase():i,{height:o}=e.drawText(s,{x:0,y:0,width:this.width,height:this.height,fontSize:this.data.fontSize,lineHeight:this.data.lineHeight??1,letterSpacing:this.data.letterSpacing??0,horizontalAlign:this.data.horizontalAlign,verticalAlign:this.data.verticalAlign,font:this.data.font});this._textHeight=o}getCenter(){return[this.width*.5,this.height*.5]}getHalfSize(){return[this.width*.5,this.height*.5]}updateSizeState(e){let r=!1;e.width!==void 0&&(this.width=typeof e.width=="number"?e.width:this.width,r=!0),e.height!==void 0&&(this.height=typeof e.height=="number"?e.height:this.height,r=!0),r&&this.updateWorldMatrix(!0,!1,!0)}updateFontState(e,{shared:r}){e.font!==void 0&&(this._fontHolder=r.getFont(e.font),this._fontHolder&&!this._fontHolder.isLoaded&&this._fontHolder.loadingPromise.then(()=>{this.requestRender()}))}updateState(e,r){super.updateState(e,r),this.updateSizeState(e),this.updateFontState(e,r)}clone(e){let r=new tc(this.uuid,this.data,e);return r.parent=void 0,r}};var Df=class extends Ar{constructor(e,r,i){super(e,r,i);this.uuid=e;this.data=r;this.curves=[];this.extremasBBox={min:[0,0],max:[0,0]};this.updateState(r,i)}computeExtremas(){this.curves.length===0&&this.computeCurves();let e=this.curves.map(s=>Qx.extremas(s)),r=[1/0,1/0],i=[-1/0,-1/0];for(let s=0,o=e.length;si[0]&&(i[0]=a[1][0]),a[1][1]>i[1]&&(i[1]=a[1][1])}return this.extremasBBox.min=[r[0],r[1]],this.extremasBBox.max=[i[0],i[1]],this.extremasBBox}computeCurves(){this.curves=[];for(let i=1,s=this.data.points.length;i{function n(o){let a=o.start,l=o.cp1,c=o.cp2,u=o.end,h=[3*(l[0]-a[0]),3*(l[1]-a[1])],d=[3*(c[0]-l[0]),3*(c[1]-l[1])],f=[3*(u[0]-c[0]),3*(u[1]-c[1])],p={start:h,cp:d,end:f};return o.derivative=p,p.derivative=sT.derive(p),p}s.derive=n;function t(o,a,l,c=!1){let u=o-2*a+l;if(u!==0){let h=-Math.sqrt(Math.abs(a*a-o*l)),d=-o+a,f=-(h+d)/u,p=-(-h+d)/u;return[f,p]}else if(a!==l&&u===0)return[(2*a-l)/(2*(a-l))];return[]}function e(o){let a=o.derivative??s.derive(o),l=a.start,c=a.cp,u=a.end;return[t(l[0],c[0],u[0]),t(l[1],c[1],u[1])]}s.droot=e;function r(o){let[a,l]=s.droot(o),c=[o.start[0],o.end[0]],u=[o.start[1],o.end[1]];for(let h of a)c.push(s.compute(o,Math.min(1,Math.max(0,h)))[0]);for(let h of l)u.push(s.compute(o,Math.min(1,Math.max(0,h)))[1]);return c.sort((h,d)=>h-d),u.sort((h,d)=>h-d),[[c[0],u[0]],[c[c.length-1],u[u.length-1]]]}s.extremas=r;function i(o,a){if(a===0)return[...o.start];if(a===1)return[...o.end];let l=1-a,c=l*l,u=a*a,h=c*l,d=c*a*3,f=l*u*3,p=a*u;return[h*o.start[0]+d*o.cp1[0]+f*o.cp2[0]+p*o.end[0],h*o.start[1]+d*o.cp1[1]+f*o.cp2[1]+p*o.end[1]]}s.compute=i})(Qx||(Qx={}));var sT;(r=>{function n(i){let s=i.start,o=i.cp,a=i.end,l=[2*(o[0]-s[0]),2*(o[1]-s[1])],c=[2*(a[0]-o[0]),2*(a[1]-o[1])],u={start:l,end:c};return u.derivative=oT.derive(u),i.derivative=u,u}r.derive=n;function t(i){let s=i.derivative??r.derive(i),o=s.start,a=s.end;return[o[0]!==a[0]?o[0]/(o[0]-a[0]):0,o[1]!==a[1]?o[1]/(o[1]-a[1]):0]}r.droot=t;function e(i,s){if(s===0)return[...i.start];if(s===1)return[...i.end];let o=1-s,a=o*o,l=s*s,c=a,u=o*s*2,h=l;return[c*i.start[0]+u*i.cp[0]+h*i.end[0],c*i.start[1]+u*i.cp[1]+h*i.end[1]]}r.compute=e})(sT||(sT={}));var oT;(e=>{function n(r){let i=r.start,s=r.end,o=[s[0]-i[0],s[1]-i[1]];return r.derivative=o,r.derivative}e.derive=n;function t(r,i){if(i===0)return[...r.start];if(i===1)return[...r.end];let s=r.start,o=r.end;return[s[0]+(o[0]-s[0])*i,s[1]+(o[1]-s[1])*i]}e.compute=t})(oT||(oT={}));var Ji=class extends Zi{constructor(e,r,i){super(e,r,i);this.uuid=e;this.width=0;this.height=0;this.clipped=!0;this.background=new Es(e+"-background",rd.defaultData,i),this.background.parent=this,this.updateState(r,i)}get fill(){return this.background.fill}get stroke(){return this.background.stroke}get backgroundBlur(){return this.background.backgroundBlur}get layerBlur(){return this.background.layerBlur}get dropShadow(){return this.background.dropShadow}get innerShadow(){return this.background.innerShadow}get cornerRadius(){return this.background.cornerRadius}set cornerRadius(e){this.background.cornerRadius=e}updateLocalMatrix(){super.updateLocalMatrix(),this.background?.updateLocalMatrix()}updateWorldMatrix(e,r,i){super.updateWorldMatrix(e,r,i),this.background?.updateWorldMatrix(e,r,i)}draw(e){if(!this.visible)return;e.save();let r=this.width,i=this.height;this.applyTransforms(e),this.background.width=r,this.background.height=i,this.background.draw(e),this.clipped&&e.clipRect(0,0,r,i,...this.cornerRadius),this.innerDrawChildren(e),e.restore()}getCenter(){return[this.width*.5,this.height*.5]}getHalfSize(){return[this.width*.5,this.height*.5]}updateCornerState(e){e.cornerRadius!==void 0&&(this.cornerRadius=e.cornerRadius)}updateSizeState(e){let r=!1;e.width!==void 0&&(this.width=typeof e.width=="number"?e.width:this.width,r=!0),e.height!==void 0&&(this.height=typeof e.height=="number"?e.height:this.height,r=!0),r&&this.updateWorldMatrix(!0,!1,!0)}updateState(e,r){super.updateState(e,r),this.updateSizeState(e),this.updateCornerState(e),e.fill!==void 0&&this.fill.update(e.fill),e.stroke!==void 0&&this.stroke.update(e.stroke),e.dropShadow!==void 0&&this.dropShadow.update(e.dropShadow),e.innerShadow!==void 0&&this.innerShadow.update(e.innerShadow),e.layerBlur!==void 0&&this.layerBlur.update(e.layerBlur),e.backgroundBlur!==void 0&&this.backgroundBlur.update(e.backgroundBlur),e.clipped!==void 0&&(this.clipped=e.clipped)}requestRender(){super.requestRender(),this.dispatchEvent({type:"render"})}dispose(){this.removeEventListener("render")}updateByPatchedOp(e,r,i){super.updateByPatchedOp(e,r,i),e.type===0&&(Lt(e.path,["fill"])?this.fill.update(e.props):Lt(e.path,["stroke"])?this.stroke.update(e.props):Lt(e.path,["dropShadow"])?this.dropShadow.update(e.props):Lt(e.path,["innerShadow"])?this.innerShadow.update(e.props):Lt(e.path,["layerBlur"])?this.layerBlur.update(e.props):Lt(e.path,["backgroundBlur"])?this.backgroundBlur.update(e.props):this.resetBBoxNeedsUpdate())}clone(e){let r=new Ji(this.uuid,this.data,e);r.parent=void 0;for(let i of this.children)r.add(i.clone(e));return r}};var GL=ta(aT(),1),za=class extends Ar{constructor(e,r,i){super(e,r,i);this.uuid=e;this.data=r;this._pathBBox=new DOMRect;this.path="";this.updateState(r,i),this.autoClose=!1,this.computeSVGBBox()}computeSVGBBox(){let e=document.createElementNS("http://www.w3.org/2000/svg","svg"),r=document.createElementNS("http://www.w3.org/2000/svg","path");document.body.appendChild(e),r.setAttribute("d",this.path),e.appendChild(r),this._pathBBox=r.getBBox(),e.remove()}innerDraw(e){e.path(this.path)}intersectsInLocalSpace(e,r){return e>=this._pathBBox.x&&e<=this._pathBBox.x+this._pathBBox.width&&r>=this._pathBBox.y&&r<=this._pathBBox.y+this._pathBBox.height}getCenter(){return[(this._pathBBox.x+this._pathBBox.width)/2,(this._pathBBox.y+this._pathBBox.height)/2]}getHalfSize(){return[(this._pathBBox.x+this._pathBBox.width)/2,(this._pathBBox.y+this._pathBBox.height)/2]}updateState(e,r){super.updateState(e,r),e.path!==void 0&&(this.path=e.path,this.computeSVGBBox())}clone(e){let r=new za(this.uuid,this.data,e);return r.parent=void 0,r}};function jL(n,t=1,e=1){if(t<=0||e<=0)return n;let i=(0,GL.parseSVG)(n).map(s=>{let o={...s};return"x"in o&&(o.x=o.x*t),"y"in o&&(o.y=o.y*e),"x1"in o&&(o.x1=o.x1*t),"x2"in o&&(o.x2=o.x2*t),"y1"in o&&(o.y1=o.y1*e),"y2"in o&&(o.y2=o.y2*e),"rx"in o&&(o.rx=o.rx*t),"ry"in o&&(o.ry=o.ry*e),o});return HL(i)}function HL(n){let t=["rx","ry","xAxisRotation","largeArc","sweep","x1","y1","x2","y2","x","y"],e;return n.map(r=>{let i=[];t.forEach(o=>{if(o in r){let a=r[o]*1;i.length&&a>=0&&i.push(","),i.push(a)}});let s=(e===r.code?i[0]<0?"":",":r.code)+i.join("");return e=r.code,s}).join("")}function WL(n,t,e){switch(t.type){case"ellipse2d":return new ec(n,t,e);case"rectangle2d":return new Es(n,t,e);case"text2d":return new tc(n,t,e);case"vector2d":return new Df(n,t,e);case"path2d":return new za(n,t,e);case"frame2d":return new Ji(n,t,e);case"group2d":default:return new kn(n,t,e)}}var lT=class{constructor(t,e,r){this.uuid=t;this.data=e;this.group=new kn(lT.GROUP_ID,{...Zp.defaultData},r),this.createChildrenObjects(e.objects,this.group,r)}createObject(t,e,r,i,s,o){let a=WL(t,e,o);a&&(i.add(a),i.children.splice(s,0,i.children.pop()),a.updateWorldMatrix(),r.length>0&&(a instanceof kn||a instanceof Ji)&&this.createChildrenObjects(r,a,o))}createChildrenObjects(t,e,r){let i=0;for(let s of t)this.createObject(s.id,s.data,s.children,e,i,r),i+=1}draw(t){this.group.draw(t)}updateEntityByOp(t,e,r,i){let s=this.find(t);if(s)try{s.updateByOp(e,r,{shared:i})}catch(o){console.error(o)}}updateTreeByOp(t,e){if(t.path.length===0&&t.type===7){let r=t.parent===null?this.group:this.find(t.parent);r!==void 0&&r instanceof Zi&&(this.createObject(t.id,t.data,t.children,r,t.localIndex,e),r.requestRender())}else if(t.path.length===0&&t.type===8){let r=this.find(t.id);if(r!==void 0&&r.parent!==void 0&&r.parent instanceof Zi){let i=r.parent;r.resetBBoxNeedsUpdate(),i?.remove(r),i?.requestRender()}}else if(t.path.length===0&&t.type===9){let r=this.find(t.id);if(r!==void 0){let i=r.parent,s=t.parent===null?this:this.find(t.parent);if(s===void 0&&!1&&console.error("unexpected",s,t),s instanceof Zi||s===this){s.add(r);let o=t.localIndex;s.children.splice(o,0,s.children.pop()),r.updateWorldMatrix(!0,!1,!0),i?.requestRender(),r.requestRender()}r.resetBBoxNeedsUpdate()}}}add(t){this.group.add(t)}remove(t){this.group.remove(t)}traverse(t){this.group.traverse(e=>{e!==this.group&&t(e)})}intersectsChildren(t,e,r,i=!1,s=[]){return this.group.intersectsChildren(t,e,r,i,s,!0)}intersectsChildrenReverse(t,e,r,i=!1,s=[]){return this.group.intersectsChildrenReverse(t,e,r,i,s,!0)}find(t){return this.group.find(t)}get children(){return this.group.children}project(t,e){return this.group.project(t,e)}getWithSortKey(t){let e=this.find(t);if(e===void 0)return;let r=[],i=e;for(;i!==this.group;){let s=i;i=i.parent;let o=i.children.indexOf(s);r.splice(0,0,o)}return{entity:e,sortKey:r}}getAllSorted(t){let e=[];for(let r of t){let i=this.getWithSortKey(r.id);i!==void 0&&e.push(i)}return e.sort((r,i)=>fv(r.sortKey,i.sortKey)),e.map(r=>r.entity)}},su=lT;su.GROUP_ID="scene2d";function cT({constraints:n,newParentWidth:t,newParentHeight:e,initialParentWidth:r,initialParentHeight:i,objectInitialWidth:s,objectInitialHeight:o,objectInitialPosition:a}){let{horizontalConstraint:l,verticalConstraint:c}=n,u=t-r,h=e-i,d=s,f=o,p=a[0],m=a[1];if(l!==0){if(l===1)p+=u;else if(l===3)p+=u/2;else if(l===2)d=Math.max(1,d+u);else if(l===4){let g=t/r;d*=g,p*=g}}if(c!==0){if(c===1)m+=h;else if(c===3)m+=h/2;else if(c===2)f=Math.max(1,f+h);else if(c===4){let g=e/i;f*=g,m*=g}}return{width:d,height:f,position:[p,m]}}var vZ=ta(aT(),1);var IVe={mm:{mm:1,cm:.1,in:1/25.4,pt:72/25.4,pc:6/25.4,px:-1},cm:{mm:10,cm:1,in:1/2.54,pt:72/2.54,pc:6/2.54,px:-1},in:{mm:25.4,cm:2.54,in:1,pt:72,pc:6,px:-1},pt:{mm:25.4/72,cm:2.54/72,in:1/72,pt:1,pc:6/72,px:-1},pc:{mm:25.4/6,cm:2.54/6,in:1/6,pt:72/6,pc:1,px:-1},px:{mm:1,px:1,cm:1,in:1,pt:1,pc:1}};var bZ=` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,SZ=` uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = texel; }`,wZ=new nl(-1,1,1,-1,0,1),dT=class extends _e{constructor(){super(),this.setAttribute("position",new Te([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Te([0,2,0,0,2,0],2))}},AZ=new dT,fT=class{constructor(t){this._mesh=new Ut(AZ,t)}dispose(){this._mesh.geometry.dispose()}render(t){t.render(this._mesh,wZ)}get material(){return this._mesh.material}set material(t){this._mesh.material=t}},qL=new it({defines:{},uniforms:{tDiffuse:new le(null)},vertexShader:bZ,fragmentShader:SZ}),EZ=new fT(qL),uT=null,hT=null,TZ=()=>(uT===null&&(uT=document.createElement("canvas")),uT),MZ=n=>(hT===null&&(hT=new Hm(n)),hT),CZ=St.identity(),Of=class{constructor(t,e,r,i){this.uuid=t;this.width=e;this.height=r;this.context=i;this.enabled=!0;this.isScreenSpace=!1;this.dpr=window.devicePixelRatio;this.isFrameDirty=!1;this.onRenderRequestedDownstream=()=>{this.isFrameDirty=!0,this.context.shared.requestRender()};this._innerApplySize=()=>{let t=this.width,e=this.height,r=this.dpr;this.renderer.dpr=this.isScreenSpace?r:Math.floor(2048/Math.max(t,e)),this.renderer.setSize(t,e)};this.onFrameOverrideObjectEvent=t=>{if(t.target?.uuid!==void 0){let e=this.frameRoot?.find(t.target.uuid);e&&e.dispatchEvent({...t,target:e})}};this.scene2d=new su(we.generateUUID(),u0.defaultData,{dpr:window.devicePixelRatio,shared:i.shared}),this.canvas=TZ(),this.renderer=MZ(this.canvas),this.promise=this.init(),this.renderTarget=new dt(1,1,{type:Wn,stencilBuffer:!1,depthBuffer:!1}),i.shared.addUIBuffer(this.uuid,this.renderTarget),this.textureHolder=i.shared.uiBuffer(this.uuid)}get canvasTexture(){return this._canvasTexture||(this._canvasTexture=new xy(this.canvas)),this._canvasTexture}async init(){this.renderer instanceof Hm&&(this.renderer.wasmURL=J0.skiaWasmUrl),await this.renderer.init()}render(t){if(this.isFrameDirty){this.isFrameDirty=!1,this._innerApplySize(),this.renderer.clear(),this.frameOverride?.draw(this.renderer),this.renderer.render(),qL.uniforms.tDiffuse.value=this.canvasTexture,this.canvasTexture.needsUpdate=!0;let e=t.getRenderTarget();t.setRenderTarget(this.renderTarget),t.clear(),EZ.render(t),t.setRenderTarget(e),this.textureHolder?.setNeedsUpdate(!0)}}updateEntity2DByOp(t,e,r,i){this.scene2d.updateEntityByOp(t,e,r,i),this.applySize()}updateTreeByOp(t,e){this.scene2d.updateTreeByOp(t,e),this.applySize()}applyOverrides(t){if(this.frameOverride&&this.frameRoot){this.frameOverride.position=[0,0],this.frameOverride.rotation=0;let e=t?.width??this.width,r=t?.height??this.height;this.frameOverride.width=e,this.frameOverride.height=r,this.frameOverride.localMatrix=CZ,this.isScreenSpace&&(this.frameOverride.fill.color=bt.from0to1([0,0,0,0])),this.frameOverride.data={...this.frameOverride.data,width:e,height:r},YL({objectOverride:this.frameOverride,objectRoot:this.frameRoot,newParentWidth:this.frameOverride.width,newParentHeight:this.frameOverride.height,initialParentWidth:this.frameRoot.width,initialParentHeight:this.frameRoot.height}),this.frameOverride.updateWorldMatrix(!0,!1,!0)}}applySize(t,e=window.devicePixelRatio){let r=Math.max(1,t?.width??this.width),i=Math.max(1,t?.height??this.height);this.dpr=e,this.width=r,this.height=i,this._innerApplySize();let s=1,o=512,a=512;(r*e{r.addEventListener("beginState",this.onFrameOverrideObjectEvent)}),this.frameOverride.traverse(r=>{r.addEventListener("completeState",this.onFrameOverrideObjectEvent)}),this.frame?.requestRender(),e}get frame(){return this.frameOverride}get frameId(){return this.frame?.uuid}find(t){return this.scene2d.find(t)}get texture(){return this.textureHolder?.getTexture(1001)}disposeFrameOverride(){this.frameOverride?.removeEventListener("render",this.onRenderRequestedDownstream),this.frameOverride?.traverse(t=>{t.removeEventListener("beginStateChange",this.onFrameOverrideObjectEvent)}),this.frameOverride?.traverse(t=>{t.removeEventListener("completeState",this.onFrameOverrideObjectEvent)}),this.frameOverride&&this.scene2d.remove(this.frameOverride)}};function YL({objectOverride:n,objectRoot:t,newParentWidth:e,newParentHeight:r,initialParentWidth:i,initialParentHeight:s}){if(n instanceof Ji&&t instanceof Ji||n instanceof kn&&t instanceof kn)for(let o=0,a=n.children.length;o{this.uiCanvas?.applyFrame(e),this.uiCanvas?.applySize()})}updateVisible(){}setBackgroundColor(e){this.bgColor=e,this.fogUseBGColor===!0&&(this.backupFog.color=e)}entityChildrenCount(){return this.uiScene?this.uiScene.children.length:super.entityChildrenCount()}updateAmbientLight(e,r){e.color!==void 0&&(this.ambientLight.color=Qi(e.color,r)),e.intensity!==void 0&&(this.ambientLight.intensity=e.intensity),e.enabled!==void 0&&(e.enabled?this.add(this.ambientLight):this.remove(this.ambientLight))}onDeactive(){this.isActive=!1}onActive(e){this.isActive=!0,e.fog=this.fog,this.traverseEntity(r=>{r instanceof Fn&&r.recomputeBoolean()}),this.updateShadow(this.data.shadow)}forceMaterialsUpdate(){this.traverseEntity(e=>{if(e instanceof vs)if(Array.isArray(e.material))for(let r of e.material)r.needsUpdate=!0;else e.material.needsUpdate=!0,e.material.dispose()})}updateShadow(e){e.softShadowQuality!==void 0&&this.isActive&&xL(e.softShadowQuality)&&this.forceMaterialsUpdate()}updateFog(e,r){if(e.enabled?this.fog=this.backupFog:this.fog=null,this.isActive){let i=this.scene;i.fog=this.fog}this.fogUseBGColor=e.useBackgroundColor,e.useBackgroundColor?this.backupFog.color.set(this.bgColor):this.backupFog.color=Qi(e.color,r),this.backupFog.near=e.near,this.backupFog.far=e.far}updateAo(e,r){e.aoColor!==void 0&&(this.aoColor=Qi(e.aoColor,r))}updateByOp(e,r,i,s){let o=this.data.uiFrame;super.updateByOp(e,r,i,s);let a=r;Lt(e.path,["fog"])?this.updateFog(a.fog,i.shared):Lt(e.path,["ao"])?this.updateAo(a.ao,i.shared):Lt(e.path,["ambient"])?this.updateAmbientLight(a.ambient,i.shared):Lt(e.path,["shadow"])?this.updateShadow(a.shadow):e.type===0&&e.path.length===0&&(e.props.uiFrame!==void 0||o!==a.uiFrame)&&this.updateUIFrame(e.props.uiFrame,i)}updateUIFrame(e,r){e?(this.uiCanvas||this.createUICanvas(e,r),this.uiCanvas.enabled=!0,this.uiCanvas.applyFrame(e)):this.uiCanvas&&(this.uiCanvas.enabled=!1)}updateState(e,r){this.updateState_Entity(e,r),e.backgroundColor!==void 0&&this.setBackgroundColor(Qi(e.backgroundColor,r.shared)),e.fog!==void 0&&this.updateFog(e.fog,r.shared),e.ambient!==void 0&&this.updateAmbientLight(e.ambient,r.shared),e.ao!==void 0&&this.updateAo(e.ao,r.shared),e.shadow!==void 0&&this.updateShadow(e.shadow)}createFrame(e,r){}raycast(e,r){super.raycast(e,r)}switchActiveCamera(e){e&&e.isDescendantOf(this)&&(this.activeCamera!==this.personalCamera&&(this.activeCamera.objectHelper.visible=!0),this.activeCamera=e,e.objectHelper.visible=!1)}get playCamera(){return this.scene?.find(this.data.publish.playCamera)??this.personalCamera}switchToPlayCamera(){this.switchActiveCamera(this.playCamera)}get penumbraSizeArray(){return this.penumbraSizeArrayCache===null&&this.updatePenumbraSizeArray(),this.penumbraSizeArrayCache}updatePenumbraSizeArray(){this.penumbraSizeArrayCache=new Array(5).fill(.5);let e=0,r=0;this.traverseEntity(i=>{if(!i.visible)return!0;i instanceof _f&&i.visible&&e<3&&(this.penumbraSizeArrayCache[e]=i.data.penumbraSize??.5,e+=1),i instanceof If&&i.visible&&e<5-3&&(this.penumbraSizeArrayCache[3+r]=i.data.penumbraSize??.5,r+=1)})}raycastWithClones(e){let r=[],i=s=>{for(let o of s.children){let a=o.cloner;yt.is(o)&&(o.visible||a?.object.data.visible)&&((cn(o)||Vm(o)&&this.scene.enableHelpers&&o.objectHelper.visible)&&(e.intersectObject(o,!1,r),Ym(o,e,r,!0)),i(o))}};return i(this),r}updateEntity2DByOp(e,r,i,s){this.uiCanvas?.updateEntity2DByOp(e,r,i,s)}};var Jx=class extends df(My,Cf){constructor(t,e,r){super(),this.super_Entity(t,e),this.castShadow=!0,this.shadow.mapSize.width=1024,this.shadow.mapSize.height=1024,this.shadow.normalBias=1,this.layers.enable(3);let s=this.shadow.camera;s.fov=90,s.aspect=1,s.near=100,s.far=2500;let o=new E(-s.far+this.position.x,-s.far+this.position.y,-s.far+this.position.z),a=new E(s.far+this.position.x,s.far+this.position.y,s.far+this.position.z),l=new Ht(o,a),c=new fl(l,new We(16755200));c.visible=!1,this.gizmos.shadowmap=c,this.update()}update(){if(this.shadow&&(this.shadow.camera.updateProjectionMatrix(),this.gizmos))for(let t in this.gizmos){let e=this.gizmos[t];if(e instanceof fl){let r=this.shadow.camera,i=new E(-r.far+this.position.x,-r.far+this.position.y,-r.far+this.position.z),s=new E(r.far+this.position.x,r.far+this.position.y,r.far+this.position.z);e.box.set(i,s),e.updateMatrixWorld(!0)}}}updateMatrixWorld(t){super.updateMatrixWorld(t),this.objectHelper&&this.objectHelper.update()}updateState(t,e){this.updateState_Light(t,e),t.distance!==void 0&&(this.distance=t.distance),t.decay!==void 0&&(this.decay=t.decay),t.shadowRadius!==void 0&&(this.shadow.radius=t.shadowRadius),t.shadowResolution!==void 0&&(this.shadow.mapSize.set(t.shadowResolution,t.shadowResolution),this.shadow.map&&(this.shadow.map.dispose(),this.shadow.map=null))}};var $x=class extends cr{get forceComputeSize(){return!0}get shape(){return this.geometry.userData.shape}updateEntityBoxSize(t,e){let r=this.geometry.getAttribute("position");r!==void 0?ym(r,this.geometry.drawRange.start,this.geometry.drawRange.count<1/0?this.geometry.drawRange.count:r.count,t,e):super.updateEntityBoxSize(t,e)}};var rc=class extends cr{constructor(e,r,i){super(e,r,i);this._shapeId=null;this._context=i}updateState(e,r){super.updateState(e,r),this.updateShape()}updateShape(){let e={...this.data.geometry.extrusion.shape};for(let s in e)typeof e[s]=="string"&&(e[s]=this._context.shared.getVariable(e[s],[this.uuid,"geometry","extrusion","shape",s]));let r;if(e.type==="Custom"){let s=e.shapeId;if(s!==this._shapeId&&this.detachShape(),s){this._shapeId=s;let o=this._context.scene.find(s);o?.data&&(o.attachedPaths.add(this),r=o.geometry.userData?.shape),r||this._context.scene.addPendingCommand(()=>this.updateShape())}}else{let s;switch(e.type){case"Rectangle":s=Id;break;case"Ellipse":s=Cd;break;case"Polygon":s=V0;break;case"Star":s=k0;break;default:throw new Error(`Unknown shape type: ${e.type}`)}r=s.create({parameters:e}).userData.shape}let i=this.geometry;r&&i.inputs&&(i.inputs.shapeData=r,i.build(),this.attachedSurfaceCloners.forEach(s=>s.update()))}detachShape(){this._shapeId!==null&&this._context.scene.find(this._shapeId)?.attachedPaths.delete(this)}createGeometryDelayed(e){this.geometryCreateDeleyed=e.shared,this.updateShape(),this.refreshAttachedPaths(e)}updateTransformState(e,r){return super.updateTransformState(e,r)}updateGeometryInteractions(e,r){super.updateGeometryInteractions(e,r),this.updateShape()}updateEntityBoxSize(e,r){let i=this.geometry.getAttribute("position");i!==void 0?ym(i,this.geometry.drawRange.start,this.geometry.drawRange.count<1/0?this.geometry.drawRange.count:i.count,e,r):super.updateEntityBoxSize(e,r)}};var ic=class extends Yl{constructor(e,r,i){super(e,r,i);this.data=r}};var eo=class extends Ss(sn,ws){constructor(e,r,i){super();r.type==="Instance"&&typeof e=="string"&&(r=this.transformAssignData(r,i)),this.super_Entity(e,r),this.objectHelper.update()}get isComponentRoot(){return this.data.type==="Component"&&typeof this.identity=="string"}get isInstanceRoot(){return this.data.type==="Instance"&&typeof this.identity=="string"}transformAssignData(e,r){let i=Qh.getComponentData({scene:r.scene.data,shared:r.shared.data},e.component);if(i){let s,o;for(let a of Po.rootOverrideProps)e[a]===void 0?(s===void 0&&(s={...e}),s[a]=i.data[a]):(o===void 0&&(o={}),o[a]=e[a],s===void 0&&(s={...e}),s[a]=So.apply(i.data[a],e[a]));return this.overrideData=o,s}else return{...vi.defaultData,...e,...Pn(vi.defaultData,Po.rootOverrideProps)}}updateByOp(e,r,i,s){let o;if(this.isInstanceRoot&&!s){if(r=this.transformAssignData(r,i),e.type===0&&e.path.length===0&&this.component)for(let a of Po.rootOverrideProps)a in e.props&&e.props[a]===void 0&&(o===void 0&&(o={...e,props:{...e.props}}),o.props[a]=this.component.data[a]);else if(e.type===0&&e.path.length>0&&Po.rootOverrideProps.includes(e.path[0])){let a=e.path[0];o===void 0&&(o={...e,path:[],props:{[a]:r[a]}})}}super.updateByOp(o??e,r,i,s)}updateState(e,r){this.updateState_Entity(e,r)}expandInstanceChildren(e){let r=this.data;if(this.component===void 0){let i=e.scene.find(r.component)??null,s=!1;if(i!==this.oldComponent){if(this.oldComponent){let o=0;for(let a of this.children)if(yt.is(a))e.scene.disposeAndUnregisterEntityRecursivelyIfNotReregistered(a),eb(a),o+=1;else break;this.children.splice(0,o)}s=!0}if(i){let o={};KL(e,[this.uuid],r.overrides,this,i,i,0,s,o);for(let a of this.children)if(yt.is(a)){let l=a.data;l.type==="Empty"&&l.animations&&a.traverseEntity(c=>{let u=c.dataPatched;if(c instanceof cr&&u.bones&&u.boneInverses){let h=c.dataPatched;if(h.bones&&h.boneInverses){let d=h.bones.map(m=>e.scene.find(o[m])),f=h.boneInverses.map(m=>new ue().fromArray(m)),p=new sl(d,f);c.bind(p,c.bindMatrix)}}else c.matrixAutoUpdate=!0})}}this.oldComponent=this.component}}};function eb(n){if(n.component){let t=n.component.instances.indexOf(n);t>=0&&n.component.instances.splice(t,1);for(let e of n.children)yt.is(e)&&eb(e)}}function XL(n,t,e,r){return n.component===t&&Rc(n.identity,r)?n.overrideData===e?2:1:0}function KL(n,t,e,r,i,s,o,a,l){if(o>50)return!1;if(r.component!==i){if(r.component){let u=r.component.instances.indexOf(r);u>=0&&r.component.instances.splice(u,1)}i.instances.find(u=>u===r)||i.instances.push(r),r.component=i}i instanceof eo&&i.isInstanceRoot&&i.expandInstanceChildren(n);let c=0;for(let u of i.children)if(yt.is(u)){let h=[...t,...typeof u.identity=="string"?[u.identity]:u.identity],d=Xh.resolve(e,h,1);if(d!=null&&!(d instanceof yr)){if(!1)debugger;Object.setPrototypeOf(d,yr.prototype),console.error("wrong prototype")}let f=null,p;if(!a){let m=r.children[c];if(f=yt.is(m)?m:null,f!==null){let g=XL(f,u,d,h);p=g>=1?f.stateSelection:void 0,g!==2&&(f=null)}if(f===null&&(f=n.scene.findInstance(h)??null,f!==null)){let g=XL(f,u,d,h);if(p=g>=1?f.stateSelection:void 0,g!==2)f=null;else{let y=f.parent.children.indexOf(f);f.parent.children.splice(y,1),r.children.splice(c,0,f),f.parent===r?(y<=c&&console.error("not possible"),void 0):(f.parent=r,f.matrixWorldNeedsUpdate=!0,f.resetBBoxNeedsUpdate(),f.updateVisible(),n.pendingDeletes.delete(f),void 0)}}}if(f===null){let m=d?So.apply(u.data,d):u.data;ks.is(m.type)&&(m={...m,type:"Empty"}),f=Hs.createEntity(h,m,n),f.overrideData=d,r.add(f),r.children.splice(r.children.length-1,1),r.children.splice(c,0,f),f.updateState(f.data,n),p&&f.changeSelectedState(p,n),n.scene.registerInstanceAndSetUuid(f)}if(f.isBone){let m=f.identity[f.identity.length-1];l[m]=f.uuid}c+=1,KL(n,t,e,f,u,s,o+1,a,l)}if(!a){let u=c;for(;;){let h=r.children[c];if(yt.is(h))n.pendingDeletes.add(h);else break;c+=1}r.children.splice(u,c-u)}return!0}var tb=class extends Ss(vp,ws){constructor(t,e){super(),this.super_Entity(t,e),this.objectHelper.update(),this.matrixAutoUpdate=!0}updateState(t,e){this.updateState_Entity(t,e)}};var Er=class extends cr{constructor(e,r,i){super(e,r,i);this.onBeforeRender=e=>{this.uiCanvas.render(e)};this.uiCanvas=new Of(e+"-canvas",r.geometry.width,r.geometry.height,i),this.uiCanvas.promise.then(()=>{this.applyFrame(this.dataPatched.geometry.frame,i.shared)})}updateByPatchedOpGeometry(e,r,i){super.updateByPatchedOpGeometry(e,r,i),e.type===0&&(e.props.frame!==void 0&&this.applyFrame(e.props.frame,i.shared),(e.props.width!==void 0||e.props.height!==void 0)&&this.applySize(e.props,i.shared))}applySize(e,r){let i=e?.width??this.dataPatched.geometry.width,s=e?.height??this.dataPatched.geometry.height;this.uiCanvas.applySize({width:i,height:s}),this.applyGeometryParametersFromFrame(r)}applyFrame(e,r){this.uiCanvas.applyFrame(e),this.applyGeometryParametersFromFrame(r),this.applyMaterialParametersFromFrame({shared:r})}applyGeometryParametersFromFrame(e){let r=this.frame;r&&(Object.assign(this.data,{geometry:Object.assign(this.data.geometry,{cornerRadius:r.cornerRadius,cornerType:0})}),Object.assign(this.dataPatched,{geometry:Object.assign(this.dataPatched.geometry,{cornerRadius:r.cornerRadius,cornerType:0})}),this.localGeometry?.dispose(),this.localGeometry=Da(this.dataPatched.geometry,e,this.data.flatShading,this))}applyMaterialParametersFromFrame(e){let r=this.frame;if(r){let i=r.data.backgroundBlur;Object.assign(this.data.material.layers[0].data.texture,{image:this.uiCanvas.uuid}),Object.assign(this.data.material.layers[1].data,{roughness:i.radius,alpha:i.enabled?1:0}),Object.assign(this.dataPatched.material.layers[0].data.texture,{image:this.uiCanvas.uuid}),Object.assign(this.dataPatched.material.layers[1].data,{roughness:i.radius,alpha:i.enabled?1:0}),this.material.reset(this.dataPatched.material,e,!0)}}updateEntity2DByOp(e,r,i,s){this.uiCanvas.updateEntity2DByOp(e,r,i,s),e===this.frameId&&r.type===0&&(r.props.cornerRadius!==void 0?this.applyGeometryParametersFromFrame(s):Lt(r.path,["backgroundBlur"])&&this.applyMaterialParametersFromFrame({shared:s}))}get frame(){return this.uiCanvas.frame}get frameId(){return this.frame?.uuid}removeInteractionGeometry(e){super.removeInteractionGeometry(e),this.applySize({},e)}updateGeometryInteractions(e,r){super.updateGeometryInteractions(e,r),this.applySize({width:e.width,height:e.height},r)}};var rb=class{constructor(t,e,r){this.variables=[],this.currentTextureIndex=0;let i=br,s=new ei,o=new qn;o.position.z=1;let a={passThruTexture:{value:null}},l=h(f(),a),c=new Ut(new Li(2,2),l);s.add(c),this.setDataType=function(p){return i=p,this},this.addVariable=function(p,m,g){let y=this.createShaderMaterial(m),v={name:p,initialValueTexture:g,material:y,dependencies:null,renderTargets:[],wrapS:null,wrapT:null,minFilter:Vt,magFilter:Vt};return this.variables.push(v),v},this.setVariableDependencies=function(p,m){p.dependencies=m},this.init=function(){if(r.capabilities.isWebGL2===!1&&r.extensions.has("OES_texture_float")===!1)return"No OES_texture_float support for float textures.";if(r.capabilities.maxVertexTextures===0)return"No support for vertex shader textures.";for(let p=0;pt){s=o;break}else t1&&(s=1-s,o=1-o),$i.a.fromBufferAttribute(this.positionAttribute,t*3),$i.b.fromBufferAttribute(this.positionAttribute,t*3+1),$i.c.fromBufferAttribute(this.positionAttribute,t*3+2),e.set(0,0,0).addScaledVector($i.a,s).addScaledVector($i.b,o).addScaledVector($i.c,1-(s+o)),r!==void 0&&$i.getNormal(r),i!==void 0&&this.colorAttribute!==void 0&&($i.a.fromBufferAttribute(this.colorAttribute,t*3),$i.b.fromBufferAttribute(this.colorAttribute,t*3+1),$i.c.fromBufferAttribute(this.colorAttribute,t*3+2),ib.set(0,0,0).addScaledVector($i.a,s).addScaledVector($i.b,o).addScaledVector($i.c,1-(s+o)),i.r=ib.x,i.g=ib.y,i.b=ib.z),this}};function QL(n){let t=new Float32Array(n*n*2);for(let e=0;e .5) { float isColliding = step(0.5, collisionFlag); // 1.0 if collisionFlag > 0.5, otherwise 0.0 float bounceOffset = 3.0 * isColliding; // Becomes 3.0 if colliding, 0.0 otherwise vec3 collisionAdjustedVelocity = velocity * (1.0 + bounceOffset); // Update position based on collision or normal movement vec3 fpsVelocity = velocity * min(uFPSRatio, 5.0); position += mix(fpsVelocity, collisionAdjustedVelocity, isColliding); // EMISSION RATE - BIRTH // if (isSpawning == 1.0) { // Better Approach to avoid If statement vec3 newPosition = applyQuaternionToVector(uWorldQuaternion, originalPosition) + uWorldOffset; originalPosition = mix(originalPosition, newPosition, isSpawning); position = mix(position, originalPosition, isSpawning);; timeStart = mix(timeStart, uTime, isSpawning); // Calculate timeLeft for life normalization float timeLeft = max(lifeTime - (uTime - timeStart), 0.0); float life_Normalize = timeLeft / lifeTime; // Use isActive to blend between the calculated color and black vec4 activeColor = vec4(position, life_Normalize); // if (isActive == 1.0) { gl_FragColor = mix(vec4(0.0), activeColor, isActive); } `;var rB=` vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } vec4 permute(vec4 x) { return mod289(((x*34.0)+1.0)*x); } vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; } vec3 fade(vec3 t) { return t*t*t*(t*(t*6.0-15.0)+10.0); } float snoise(vec3 v) { const vec2 C = vec2(1.0/6.0, 1.0/3.0) ; const vec4 D = vec4(0.0, 0.5, 1.0, 2.0); vec3 i = floor(v + dot(v, C.yyy) ); vec3 x0 = v - i + dot(i, C.xxx) ; vec3 g = step(x0.yzx, x0.xyz); vec3 l = 1.0 - g; vec3 i1 = min( g.xyz, l.zxy ); vec3 i2 = max( g.xyz, l.zxy ); vec3 x1 = x0 - i1 + C.xxx; vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y // Permutations i = mod289(i); vec4 p = permute( permute( permute( i.z + vec4(0.0, i1.z, i2.z, 1.0 )) + i.y + vec4(0.0, i1.y, i2.y, 1.0 )) + i.x + vec4(0.0, i1.x, i2.x, 1.0 )); // Gradients: 7x7 points over a square, mapped onto an octahedron. // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) float n_ = 0.142857142857; // 1.0/7.0 vec3 ns = n_ * D.wyz - D.xzx; vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7) vec4 x_ = floor(j * ns.z); vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N) vec4 x = x_ *ns.x + ns.yyyy; vec4 y = y_ *ns.x + ns.yyyy; vec4 h = 1.0 - abs(x) - abs(y); vec4 b0 = vec4( x.xy, y.xy ); vec4 b1 = vec4( x.zw, y.zw ); vec4 s0 = floor(b0)*2.0 + 1.0; vec4 s1 = floor(b1)*2.0 + 1.0; vec4 sh = -step(h, vec4(0.0)); vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ; vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ; vec3 p0 = vec3(a0.xy,h.x); vec3 p1 = vec3(a0.zw,h.y); vec3 p2 = vec3(a1.xy,h.z); vec3 p3 = vec3(a1.zw,h.w); //Normalise gradients vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3))); p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w; // Mix final noise value vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0); m = m * m; return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3) ) ); } vec3 snoiseVec3( vec3 x ){ float s = snoise(vec3( x )); float s1 = snoise(vec3( x.y - 19.1 , x.z + 33.4 , x.x + 47.2 )); float s2 = snoise(vec3( x.z + 74.2 , x.x - 124.5 , x.y + 99.4 )); vec3 c = vec3( s , s1 , s2 ); return c; } vec3 curlNoise( vec3 p, float seed){ p += seed; const float e = .1; vec3 dx = vec3( e , 0.0 , 0.0 ); vec3 dy = vec3( 0.0 , e , 0.0 ); vec3 dz = vec3( 0.0 , 0.0 , e ); vec3 p_x0 = snoiseVec3( p - dx ); vec3 p_x1 = snoiseVec3( p + dx ); vec3 p_y0 = snoiseVec3( p - dy ); vec3 p_y1 = snoiseVec3( p + dy ); vec3 p_z0 = snoiseVec3( p - dz ); vec3 p_z1 = snoiseVec3( p + dz ); float x = p_y1.z - p_y0.z - p_z1.y + p_z0.y; float y = p_z1.x - p_z0.x - p_x1.z + p_x0.z; float z = p_x1.y - p_x0.y - p_y1.x + p_y0.x; const float divisor = 1.0 / ( 2.0 * e ); return normalize( vec3( x , y , z ) * divisor ); } // Classic Perlin noise float cnoise(vec3 P) { vec3 Pi0 = floor(P); // Integer part for indexing vec3 Pi1 = Pi0 + vec3(1.0); // Integer part + 1 Pi0 = mod289(Pi0); Pi1 = mod289(Pi1); vec3 Pf0 = fract(P); // Fractional part for interpolation vec3 Pf1 = Pf0 - vec3(1.0); // Fractional part - 1.0 vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); vec4 iy = vec4(Pi0.yy, Pi1.yy); vec4 iz0 = Pi0.zzzz; vec4 iz1 = Pi1.zzzz; vec4 ixy = permute(permute(ix) + iy); vec4 ixy0 = permute(ixy + iz0); vec4 ixy1 = permute(ixy + iz1); vec4 gx0 = ixy0 * (1.0 / 7.0); vec4 gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5; gx0 = fract(gx0); vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0); vec4 sz0 = step(gz0, vec4(0.0)); gx0 -= sz0 * (step(0.0, gx0) - 0.5); gy0 -= sz0 * (step(0.0, gy0) - 0.5); vec4 gx1 = ixy1 * (1.0 / 7.0); vec4 gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5; gx1 = fract(gx1); vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1); vec4 sz1 = step(gz1, vec4(0.0)); gx1 -= sz1 * (step(0.0, gx1) - 0.5); gy1 -= sz1 * (step(0.0, gy1) - 0.5); vec3 g000 = vec3(gx0.x,gy0.x,gz0.x); vec3 g100 = vec3(gx0.y,gy0.y,gz0.y); vec3 g010 = vec3(gx0.z,gy0.z,gz0.z); vec3 g110 = vec3(gx0.w,gy0.w,gz0.w); vec3 g001 = vec3(gx1.x,gy1.x,gz1.x); vec3 g101 = vec3(gx1.y,gy1.y,gz1.y); vec3 g011 = vec3(gx1.z,gy1.z,gz1.z); vec3 g111 = vec3(gx1.w,gy1.w,gz1.w); vec4 norm0 = taylorInvSqrt(vec4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); g000 *= norm0.x; g010 *= norm0.y; g100 *= norm0.z; g110 *= norm0.w; vec4 norm1 = taylorInvSqrt(vec4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); g001 *= norm1.x; g011 *= norm1.y; g101 *= norm1.z; g111 *= norm1.w; float n000 = dot(g000, Pf0); float n100 = dot(g100, vec3(Pf1.x, Pf0.yz)); float n010 = dot(g010, vec3(Pf0.x, Pf1.y, Pf0.z)); float n110 = dot(g110, vec3(Pf1.xy, Pf0.z)); float n001 = dot(g001, vec3(Pf0.xy, Pf1.z)); float n101 = dot(g101, vec3(Pf1.x, Pf0.y, Pf1.z)); float n011 = dot(g011, vec3(Pf0.x, Pf1.yz)); float n111 = dot(g111, Pf1); vec3 fade_xyz = fade(Pf0); vec4 n_z = mix(vec4(n000, n100, n010, n110), vec4(n001, n101, n011, n111), fade_xyz.z); vec2 n_yz = mix(n_z.xy, n_z.zw, fade_xyz.y); float n_xyz = mix(n_yz.x, n_yz.y, fade_xyz.x); return 2.2 * n_xyz; } vec3 fbm_vec3(vec3 p, float frequency, float offset) { return vec3( cnoise((p+vec3(offset))*frequency), cnoise((p+vec3(offset+20.0))*frequency), cnoise((p+vec3(offset-30.0))*frequency) ); } `;var iB=` #ifdef USE_COLLIDER float restitution = max(uBounce * 2., .01); // Energy Loss // SPHERE COLLIDER // ************************************************************** #ifdef USE_SPHERE_COLLIDER // Convert collider size to radii (assuming uColliderSize is the diameter in each axis) vec3 radii = uColliderSize; // Adjust position relative to collider vec3 relPos = position - uColliderPos; // Apply rotation of the collider to the relative position relPos = applyQuaternionToVector(uColliderQuaternionInvert, relPos); // Scale relative position by radii (for ellipsoid collision detection) vec3 scaledPos = relPos / radii; // Calculate ellipsoidal distance float dist = length(scaledPos); // Distance in terms of ellipsoid // Check for collision if (dist <= 1. + particleSize / length(radii) && collisionFlag == 0.0) { // Compute the normal at the collision point, accounting for particle size vec3 adjustedPos = scaledPos * (1.0 + particleSize / length(radii)); // Compute the normal at the collision point vec3 normal = ellipsoidNormal(adjustedPos, radii); // Rotate the normal back to world space normal = applyQuaternionToVector(uColliderQuaternion, normal); // Reflect the velocity vector off the normal velocity = reflect(velocity, normal) * restitution; collisionFlag = 1.0; } else { collisionFlag = 0.0; } #endif // BOX COLLIDER or PLANE COLLIDER // ************************************************************** #ifdef USE_BOX_COLLIDER // Box dimensions and repulsion variables vec3 boxHalfSize = uColliderSize / 2.0; // Convert world position to box's local space vec3 localPos = applyQuaternionToVector(uColliderQuaternionInvert, position - uColliderPos); // Collision detection vec3 localDistance = abs(localPos) - boxHalfSize; float distToSurface = max(localDistance.x, max(localDistance.y, localDistance.z)); // Collision Detected if (distToSurface <= particleSize * 0.5 && collisionFlag == 0.0) { // Find the nearest face normal for bounce direction vec3 normal; if (localDistance.x > localDistance.y && localDistance.x > localDistance.z) { normal = vec3(sign(localPos.x), 0.0, 0.0); } else if (localDistance.y > localDistance.z) { normal = vec3(0.0, sign(localPos.y), 0.0); } else { normal = vec3(0.0, 0.0, sign(localPos.z)); } // Rotate normal back to world space normal = applyQuaternionToVector(uColliderQuaternion, normal); // Reflect velocity and apply repulsion force velocity = reflect(velocity, normal) * restitution; collisionFlag = 1.0; } else { collisionFlag = 0.0; } #endif #endif // END COLLIDER `;var nB=` #ifdef USE_ATTRACTOR #ifdef USE_SPHERE_COLLIDER // Convert collider size to radii (assuming uColliderSize is the diameter in each axis) vec3 radii = uColliderSize; // Adjust position relative to collider vec3 relPos = position - uColliderPos; // Apply rotation of the collider to the relative position relPos = applyQuaternionToVector(uColliderQuaternionInvert, relPos); // Scale relative position by radii (for ellipsoid collision detection) vec3 scaledPos = relPos / radii; // Calculate ellipsoidal distance float distToSurface = length(scaledPos); // Distance in terms of ellipsoid float insideCheck = 1.0; #endif #ifdef USE_BOX_COLLIDER // Box dimensions vec3 boxHalfSize = uColliderSize / 2.0; // Convert world position to box's local space vec3 localPos = applyQuaternionToVector(uColliderQuaternionInvert, position - uColliderPos); vec3 localDistance = abs(localPos) - boxHalfSize; float distToSurface = max(localDistance.x, max(localDistance.y, localDistance.z)); float insideCheck = particleSize; #endif // Apply vortex force inside the Helper #ifdef USE_FORCE_LOCAL_SPACE if (distToSurface <= insideCheck ) { // Define parameters for the attractor field #ifdef USE_SPHERE_COLLIDER float attractorStrength = (1.0 - distToSurface ) * uForceIntensity; // Adjust as needed #endif #ifdef USE_BOX_COLLIDER float attractorStrength = max((1.0 - insideCheck / distToSurface), 0.) * uForceIntensity; // Adjust as needed #endif float attractorDamping = uForceDamping; // Adjust as needed (higher values will attenuate velocity more) // Use the same radii calculation code as for the collider vec3 attractorRadii = uColliderSize; // Adjust position relative to attractor center vec3 relPos = position - uColliderPos; // Apply rotation of the collider to the relative position relPos = applyQuaternionToVector(uColliderQuaternionInvert, relPos); // Scale relative position by radii (for ellipsoid attraction) vec3 scaledPos = relPos / attractorRadii; // Calculate ellipsoidal distance as attractor radius float attractorRadius = length(scaledPos); // Calculate the distance from the attractor center vec3 relativePosition = position - uColliderPos; // Calculate the force vector towards the attractor center vec3 attractorForce = normalize(relativePosition) * attractorStrength; // Apply the attractor force to the particle velocity -= attractorForce; // Attenuate the particle's velocity velocity *= attractorDamping; } #else // Calculate the distance from the attractor center vec3 relativePosition = position - uColliderPos; // Calculate the force vector towards the attractor center vec3 attractorForce = normalize(relativePosition) * uForceIntensity; // Apply the attractor force to the particle velocity -= attractorForce; // Attenuate the particle's velocity velocity *= uForceDamping; #endif #endif `;var sB=` #ifdef USE_VORTEX // Box dimensions vec3 boxHalfSize = uColliderSize / 2.0; // Convert world position to box's local space vec3 localPos = applyQuaternionToVector(uColliderQuaternionInvert, position - uColliderPos); vec3 localDistance = abs(localPos) - boxHalfSize; float distToSurface = max(localDistance.x, max(localDistance.y, localDistance.z)); // Apply vortex force inside the box if (distToSurface <= particleSize) { float vortexStrength = uForceIntensity; vec3 localTopCenter = vec3(0.0, 0., 0.0); // Transform the local top center to the world space vec3 vortexCenter = uColliderPos + applyQuaternionToVector(uColliderQuaternion, localTopCenter); // Calculate the vector from particle to vortex center vec3 vortexVector = vortexCenter - position; // Calculate the rotation axis from the inverse of the collider's quaternion and the fixed up vector // Note: important to add a tiny z component to the up vector to avoid instability vec3 upVector = vec3(0.0, 1.0, 0.01); vec3 rotationAxis = cross(upVector, applyQuaternionToVector(uColliderQuaternion, vortexVector)); rotationAxis = normalize(rotationAxis); // Add rotational component to velocity float rotationSpeed = length(vortexVector * vortexStrength * 3.0) ; vec3 rotationVelocity = rotationAxis * rotationSpeed; // velocity += rotationVelocity * 0.005 ; velocity = rotationVelocity * 0.005 ; // Calculate vortex force // vec3 vortexForce = normalize(vortexVector) * uSpeed * .1 ; // Apply the vortex force to the particle vec3 originDirection = applyQuaternionToVector(uWorldQuaternion, directions); velocity += applyForce( originDirection * uSpeed * (1. - uForceDamping) , mass * .5); } #endif `;var oB=` // uniform sampler2D uCurrentPosition; // Pass in the variable from GPGPU // uniform sampler2D uCurrentVelocity; // Pass in the variable from GPGPU // uniform sampler2D uCurrentEmissionRate; // Pass in the variable from GPGPU uniform sampler2D uOriginalPosition; uniform sampler2D uDirections; uniform vec3 uDirectionsAxis; uniform vec4 uWorldQuaternion; uniform vec3 uGravity; uniform float uNoiseStrength; // Variation of the noise uniform float uNoiseScale; // Scale of the noise uniform float uNoiseSeed; // Seed of the noise uniform float particleSize; uniform float uSpeed; // update speed of the particles uniform float uRandomMassFactor; // COLLIDER uniform vec3 uColliderPos; // Collider Position uniform vec3 uColliderSize; // Collider Dimension uniform vec4 uColliderQuaternion; // Collider Rotation uniform vec4 uColliderQuaternionInvert; // Collider Rotation uniform float uBounce; // Bounce factor uniform float uForceDamping; uniform float uForceIntensity; `+rB+` float rand(vec2 co){ return fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453); } vec3 applyQuaternionToVector( vec4 q, vec3 v ){ return v + 2.0 * cross( q.xyz, cross( q.xyz, v ) + q.w * v ); } vec3 applyForce(vec3 force, float mass) { vec3 acceleration = force / mass; return acceleration; } vec4 conjugate(vec4 q) { return vec4(q.w, -q.x, -q.y, -q.z); } // Function to compute the normal of the ellipsoid at a given point vec3 ellipsoidNormal(vec3 p, vec3 radii) { return normalize(p / (radii * radii)); } float friction = .3; void main() { vec2 vUv = gl_FragCoord.xy / resolution.xy; vec3 position = texture2D( uCurrentPosition, vUv ).xyz; vec3 originalPosition = texture2D( uOriginalPosition, vUv ).xyz; float timeLeft = texture2D( uCurrentPosition, vUv ).w; vec3 directions = texture2D( uDirections, vUv ).xyz; vec3 velocity = texture2D( uCurrentVelocity, vUv ).xyz; float mass = rand(originalPosition.xy) * 0.5 + 0.5; float isSpawning = texture2D( uCurrentEmissionRate, vUv ).x; // 1. = spawning, 0. = not spawning float isActive = texture2D( uCurrentEmissionRate, vUv ).y; // 1. = active, 0. = not active float collisionFlag =texture2D( uCurrentVelocity, vUv ).w; // Indicate collision // Randomness Mass mass = (1.0 - (uRandomMassFactor * mass)); if (isActive == 1.0) { // ************************************************************** // FORCES NOISES // ************************************************************** #ifdef USE_CURL_NOISE if (uNoiseScale > 0.0 ) { velocity = curlNoise(position * uNoiseScale * .002, uNoiseSeed) * ( uNoiseStrength + 1.0) * .05 * uSpeed; } // Variation of the noise Over Time if (uNoiseStrength > 0.0 && uNoiseScale == 0.0 ) { velocity += curlNoise( position, uNoiseSeed) * uNoiseStrength * 0.05 * uSpeed; } #endif // ************************************************************** #ifdef USE_SIMPLEX_NOISE if (uNoiseScale > 0.0 ) { velocity = vec3(snoise(position * uNoiseScale * .001) * ( uNoiseStrength + 1.0) * .1); velocity *= uSpeed; } // Variation of the noise Over Time if (uNoiseStrength > 0.0 && uNoiseScale == 0.0) { velocity += vec3(snoise(position * uNoiseStrength * .001) * .05 * uSpeed); } #endif // ************************************************************** #ifdef USE_FBM_NOISE if (uNoiseScale > 0.0 ) { velocity = fbm_vec3(position * uNoiseScale * .001, ( uNoiseStrength + 1.0), uNoiseSeed); velocity *= uSpeed; } // Variation of the noise Over Time if (uNoiseStrength > 0.0 && uNoiseScale == 0.0 ) { velocity += fbm_vec3(position * uNoiseStrength * .001, ( uNoiseStrength + 1.0), uNoiseSeed) * .1 * uSpeed; } #endif // COLLIDER ${iB} // ATTRACTION ${nB} // VORTEX ${sB} } // End isActive // SPAWN BIRTH // ************************************************************** // if (isSpawning == 1.) #ifdef USE_NORMALS velocity = mix(velocity, applyQuaternionToVector(uWorldQuaternion, directions) * uSpeed, isSpawning); #else velocity = mix(velocity, applyQuaternionToVector(uWorldQuaternion, uDirectionsAxis) * uSpeed, isSpawning); #endif // if (collisionFlag == 0.0) velocity += applyForce(uGravity, mass * .5) * (1.0 - collisionFlag); gl_FragColor = vec4(velocity, collisionFlag); } `;var gT=` // Linear Fade In float linearFadeIn(float t) { return t; } // linear fade out float linearFadeOut(float t) { return 1.0 - t; } float linearInOut(float t) { return t < 0.5 ? t : (1.0 - t); } // lerp float lerp(float a, float b, float t) { return a + (b - a) * t; } // Ease In Out Quart float exponentialInOut(float t) { return t < 0.4 ? lerp(0.0, 1.0, t / 0.4) : t > 0.6 ? lerp(1.0, 0.0, (t - 0.6) / 0.4) : 1.0; } // constant float constant(float t) { return 1.0; } `;var aB=` float rand(vec3 co){ return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453); } vec3 applyQuaternionToVector( vec4 q, vec3 v ){ return v + 2.0 * cross( q.xyz, cross( q.xyz, v ) + q.w * v ); } vec3 applyForce(vec3 force, float mass) { vec3 acceleration = force / mass; return acceleration; } `;var lB=` vec3 rgb2xyz (in vec3 rgb) { float r = rgb.r; float g = rgb.g; float b = rgb.b; r = r > 0.04045 ? pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); g = g > 0.04045 ? pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); b = b > 0.04045 ? pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); float x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); float y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); float z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); vec3 xyz = vec3( (r * 0.4124) + (g * 0.3576) + (b * 0.1805) * 100.0, (r * 0.2126) + (g * 0.7152) + (b * 0.0722) * 100.0, (r * 0.0193) + (g * 0.1192) + (b * 0.9505) * 100.0 ); return(xyz); } vec3 xyz2lab (in vec3 xyz) { float x = xyz.x / 95.047; float y = xyz.y / 100.0; float z = xyz.z / 108.883; x = x > 0.008856 ? pow(x, 1.0 / 3.0) : (7.787 * x) + (16.0 / 116.0); y = y > 0.008856 ? pow(y, 1.0 / 3.0) : (7.787 * y) + (16.0 / 116.0); z = z > 0.008856 ? pow(z, 1.0 / 3.0) : (7.787 * z) + (16.0 / 116.0); vec3 lab = vec3((116.0 * y) - 16.0, 500.0 * (x - y), 200.0 * (y - z)); return(lab); } vec3 rgb2lab(in vec3 rgb) { vec3 xyz = rgb2xyz(rgb); vec3 lab = xyz2lab(xyz); return(lab); } vec3 xyz2rgb (in vec3 xyz) { float x = xyz.x / 100.0; float y = xyz.y / 100.0; float z = xyz.z / 100.0; float r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); float g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); float b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); r = r > 0.0031308 ? ((1.055 * pow(r, 1.0 / 2.4)) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * pow(g, 1.0 / 2.4)) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * pow(b, 1.0 / 2.4)) - 0.055) : b * 12.92; r = min(max(0.0, r), 1.0); g = min(max(0.0, g), 1.0); b = min(max(0.0, b), 1.0); return(vec3(r, g, b)); } vec3 lab2xyz (in vec3 lab) { float l = lab.x; float a = lab.y; float b = lab.z; float y = (l + 16.0) / 116.0; float x = a / 500.0 + y; float z = y - b / 200.0; float y2 = pow(y, 3.0); float x2 = pow(x, 3.0); float z2 = pow(z, 3.0); y = y2 > 0.008856 ? y2 : (y - 16.0 / 116.0) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16.0 / 116.0) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16.0 / 116.0) / 7.787; x *= 95.047; y *= 100.0; z *= 108.883; return(vec3(x, y, z)); } vec3 lab2rgb (in vec3 lab) { vec3 xyz = lab2xyz(lab); vec3 rgb = xyz2rgb(xyz); return(rgb); } `;var cB=` uniform sampler2D uPosition; uniform float uSize; uniform float uSizeEnd; uniform vec3 uWorldOffset; uniform vec4 uWorldQuaternion; // Billboard Behavior - Currently at Zero, but we can change that uniform float uRotation; uniform float uRotationEnd; uniform vec2 center; // Randomness uniform float uRandScaleFactor; uniform float uRandRotationFactor; attribute vec2 ref; varying float v_LifeLeft; // normalized lifetime 1 to 0 varying vec2 vUv; varying vec2 vRef; ${aB} ${gT} `,uB=({easeSize:n="linearFadeOut"})=>` vUv = uv; vRef = ref; // Normalized LifeTime 1 to 0 float lifeLeft = texture2D(uPosition, ref).w; v_LifeLeft = lifeLeft; // Position From DataTexture Simulation vec3 pos = texture2D(uPosition, ref).rgb - uWorldOffset; // Apply World Quaternion pos = applyQuaternionToVector(uWorldQuaternion, pos); #ifdef USE_SIZE_END // Scaled Over Time float t = 1. - lifeLeft; float currentSize = mix(uSize, uSizeEnd, t); // Linearly interpolate between uSize and uSizeEnd vec3 scaledPosition = position * vec3(currentSize); #else // Change Size Behavior over LifeTime float easeSize = ${n}(1. - lifeLeft); // Scaled Over Time vec3 scaledPosition = position * vec3(uSize * easeSize); #endif // Billboard Behavior vec2 scale; scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) ); scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) ); // Randomness float randRef = rand(ref); scale *= (1.0 - (uRandScaleFactor * randRef)); // Rotation float randRotation = 2.0 * PI * ( uRandRotationFactor * randRef); float originalRotation = (1.0 - uRotation) * 2.0 * PI; float originalRotationEnd = (1.0 - uRotationEnd) * 2.0 * PI; // OverTime float finalRotation = mix(originalRotation + randRotation, originalRotationEnd + randRotation, lifeLeft); vec2 alignedPosition = ( scaledPosition.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( finalRotation ) * alignedPosition.x - sin( finalRotation ) * alignedPosition.y; rotatedPosition.y = sin( finalRotation ) * alignedPosition.x + cos( finalRotation ) * alignedPosition.y; mat4 instanceMatrix = mat4( vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(pos.x, pos.y, pos.z, 1.0) ); mvPosition = modelViewMatrix * instanceMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ); mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; `,hB=` uniform vec4 uColor; // start color uniform vec4 uColor2; // end color uniform sampler2D uTexture; // texture varying float v_LifeLeft; // normalized lifetime 1 to 0 varying vec2 vUv; varying vec2 vRef; float random(vec2 co) { return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453); } `+gT+` ${lB} `,dB=({easeOpacity:n="linearFadeOut"})=>` // if Particle is dead, hide it if (v_LifeLeft <= 0.005 ) { discard; } #ifdef USE_RANDOM_COLORING float randVal = random(vRef); // Generate a random value based on the reference vec4 color = mix(uColor, uColor2, randVal); // Interpolate between the two colors #else vec4 color = mix(uColor, uColor2, 1. - v_LifeLeft); #endif // Opacity over Life Time float finalAlpha = ${n}(1. - v_LifeLeft); vec4 textureColor = texture2D(uTexture, vUv).rgba; finalColor = textureColor.rgb * color.rgb; finalAlpha = color.a * textureColor.a * finalAlpha; gl_FragColor = vec4(finalColor, finalAlpha); `;var sb=class extends it{constructor(e,r){super();this.needsJitter=!0;this.type="ParticleMaterial";this.easeOpacity="linearFadeIn";this.easeSize="linearFadeIn";this.useSizeEnd=!1;this.isColoringRandom=!1;this.init(e,r),this.context=r}reset(){}init(e,r){this.transparent=!0,this.depthTest=!0,this.depthWrite=!1,this.easeOpacity=e.ease,this.easeSize=e.easeSize,this.layers=[],or.startContext(or.globalContext),this.lightLayer=new wn(0,"",{...Gr.defaultData("light","phong"),visible:!1},new Ra,{},r.shared),or.endContext(or.globalContext),this.build()}updateState(e){e.coloring!==void 0&&(this.isColoringRandom=e.coloring==="random"),e.color!==void 0&&(e.color instanceof Array?this.uniforms.uColor.value=e.color:this.uniforms.uColor.value=this.context.shared.color(e.color)),e.color2!==void 0&&(e.color2 instanceof Array?this.uniforms.uColor2.value=e.color2:this.uniforms.uColor2.value=this.context.shared.color(e.color2)),e.size!==void 0&&(this.uniforms.uSize.value=e.size[0],this.uniforms.uSizeEnd.value=e.size[1],e.size[0]!==e.size[1]?this.useSizeEnd=!0:this.useSizeEnd=!1),e.ease!==void 0&&(this.easeOpacity=e.ease,this.build()),e.easeSize!==void 0&&(this.easeSize=e.easeSize,this.build()),this.needsUpdate=!0}onBeforeCompile(e){this.build(),e.defines=this.defines,e.uniforms=this.uniforms,e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader}build(){let e=new Ud;return e.needsJitter=this.needsJitter,e.addFragmentParsCode(MR),e.buildShader("vertex",this.fragment),e.buildShader("fragment",this.fragment),e.addFragmentFinalCode(CR),this.isColoringRandom&&e.define("USE_RANDOM_COLORING"),this.useSizeEnd&&e.define("USE_SIZE_END"),e.addVertexParsCode(cB),e.addFragmentParsCode(hB),e.addVertexFinalCode(uB({easeSize:this.easeSize})),e.addFragmentFinalCode(dB({easeOpacity:this.easeOpacity})),this.vertexShader=e.getCode("vertex"),this.fragmentShader=e.getCode("fragment"),this.defines=e.defines,this.uniforms={...e.uniforms,...this.uniforms},this.extensions=e.extensions,this}get nodeMaterial(){return this}get fragment(){return this.lightLayer.node}getDefines(){return this.defines}nodeMaterialDispose(){this.layers.forEach(e=>e.dispose()),super.dispose()}};var Rf=class{constructor(t,e,r,i){this.type="SphereEmitterShape";this.targetMesh=void 0;this.size=t,this.type=r,this.textureSize=ZL(e);let s=1;this.targetMesh=i?.type==="Mesh"&&i?i:this.getMesh(r,s);let{positions:o,dataTexture:a,dataTextureNormals:l}=this.createPositions(this.textureSize,this.targetMesh??this.getMesh(r,s));this.positionsTexture=a,this.positionsAttribute=o,this.directionsTexture=l}createPositions(t,e){let{positions:r,normals:i}=JL(e,t*t),s=mT(r,t),o=mT(i,t);return{dataTexture:s,positions:r,dataTextureNormals:o}}getMesh(t,e){let r=null;switch(t){case"SphereEmitterShape":{r=new Bs(e*.5,32,32);break}case"TorusEmitterShape":{r=new Wu(e*.5,.3,15,40);break}case"ConeEmitterShape":{r=new al(e,e,15);break}case"BoxEmitterShape":{r=new mi(e,e,e);break}case"PlaneEmitterShape":{r=new Li(e,e),r.rotateX(-Math.PI/2);break}case"MeshEmitterShape":{r=new Bs(e,32,32);break}default:{r=new Bs(e,32,32);break}}return new Ut(r,new on({color:16711680}))}applyToShader(t,e){this.size=new E().fromArray(e.size),t.uEmitterSize.value=this.size}dispose(){this.positionsTexture.dispose(),this.directionsTexture.dispose(),this.positionsAttribute=new Float32Array}};function nc(n){let t={...n},e=Gh.defaultData;t.forceFieldObjectId&&(t.colliderEntityId=t.forceFieldObjectId);let r={...e.shape,...t.shape},i={...e.renderMaterial,...t.renderMaterial};return{...e,...t,shape:r,renderMaterial:i}}var fB=` // uniform sampler2D uCurrentPosition; // Pass in the variable from GPGPU // uniform sampler2D uCurrentVelocity; // Pass in the variable from GPGPU // uniform sampler2D uCurrentEmissionRate; // Pass in the variable from GPGPU uniform sampler2D uIndex; // Texture with corresponding index uniform float uLastIndexEmitted; // Last emitted index uniform float uParticlesToEmit; // Number of particles to emit on that frame uniform float uTime; void main() { vec2 vUv = gl_FragCoord.xy / resolution.xy; float particleIndex = texture(uIndex, vUv).x; float timeLeft = texture2D( uCurrentPosition, vUv ).w; float isActive = texture2D( uCurrentEmissionRate, vUv ).g; // 1. = active, 0. = not active float timeStart = texture2D( uCurrentEmissionRate, vUv ).b; // ********** Detect Colision to Create a flag and use it in position ********** // We are doing this here, so // ********** Emit Particles ********** // X = isSpawning 0.0 or 1.0 // Y = isActive 0.0 or 1.0 // Check if the vertex index is between the first value and the last value // if (particleIndex >= uLastIndexEmitted && particleIndex < uLastIndexEmitted + uParticlesToEmit) { // // Emit a particle by writing 1 to the red channel of the color output // // r: 1. == emit the particle // // g: 1. == particle is now active // timeStart = uTime; // gl_FragColor = vec4(1.0, 1.0, timeStart, 1.0); // } else { // // The Particle is either already emitted or not in the range of the particles to emit // // Do not emit a particle by writing 0 to the red channel of the color output // gl_FragColor = vec4(0.0, isActive, timeStart, 1.0); // } // Determine if the particle is within the emission range float emitLowerBound = step(uLastIndexEmitted, particleIndex); float emitUpperBound = step(particleIndex, uLastIndexEmitted + uParticlesToEmit - 1.0); float emitParticle = emitLowerBound * emitUpperBound; // 1.0 if in range, 0.0 otherwise // Set timeStart and color timeStart = mix(timeStart, uTime, emitParticle); gl_FragColor = vec4(emitParticle, mix(isActive, 1.0, emitParticle), timeStart, 1.0); } `;var yT=10,ob=class extends Tt{constructor(e,r){super();this.type="ParticleEmitter";this.debugMode=!1;this.worldSpace=!0;this.rootObject=null;this.gpuCompute=null;this.positionSimRT=null;this.velocitySimRT=null;this.emissionRateSimRT=null;this.emitterShape=void 0;this.isEmitting=!1;this.hasBeenReset=!1;this.emittedParticlesAmount=0;this.lastEmitTime=0;this.globalTime=0;this.targetFPS=60;this.previousRatio=1;this.lerpFactor=.4;this.particlesAmount=0;this.noiseStrength=0;this.noiseScale=0;this.isBillboardBased=!0;this.simFeaturesDefinition={USE_COLLIDER:!1,USE_ATTRACTOR:!1,USE_VORTEX:!1,USE_SPHERE_COLLIDER:!1,USE_BOX_COLLIDER:!1,USE_FORCE_LOCAL_SPACE:!1,USE_NORMALS:!1,USE_CURL_NOISE:!0,USE_SIMPLEX_NOISE:!1,USE_FBM_NOISE:!1};this.textureLoader=new Ay;this.currentWorldPosition=new E;this.systemQuaternion=new Ke;this.worldGravity=new E(0,0,0);this.directionAxis=new E(0,0,0);this.colliderV3=new E(0,0,0);this.colliderQuaternion=new Ke(0,0,0,1);this.matrixAutoUpdate=!0,this.renderer=e,this.system=r,this.shared=r.context.shared;let i=r.data;this.material=new sb(i.renderMaterial,r.context),this.material.uniforms={uSize:{value:0},uSizeEnd:{value:0},uColor:{value:i.renderMaterial.color},uColor2:{value:i.renderMaterial.color2},uPosition:{value:new E(0,0,0)},uEmissionData:{value:new E(0,0,0)},uTexture:{value:this.defaultTexture},uWorldOffset:{value:new E(0,0,0)},uWorldQuaternion:{value:new Ze(0,0,0,1)},uRandScaleFactor:{value:i.randomScale??0},uRandRotationFactor:{value:i.randomRotation??0},uRotation:{value:i.renderMaterial.spriteRotation[0]??0},uRotationEnd:{value:i.renderMaterial.spriteRotation[1]??0}},this.setTexture(this.material.uniforms,i.renderMaterial.texture),this.init(i)}setTexture(e,r){let i=r.data;if(typeof r=="string"){let s=this.shared.image(r),o=new er(s.img);o.needsUpdate=!0,e.uTexture.value=o;return}if(typeof i!="string"){let s=new Image;s.onload=()=>{let l=new er(s);l.needsUpdate=!0,e.uTexture.value=l};let o=new Blob([i],{type:"image/*"}),a=URL.createObjectURL(o);s.src=a}}updateGeometryAttributes(e,r){let i=QL(r);!this.emitterShape?.positionsAttribute||e.geometry.setAttribute("ref",new mo(i,2))}applyWorldSpace(){if(!this.system.started||!this.worldSpace||!this.positionSimRT||!this.velocitySimRT)return;let e=this.system;e.getWorldQuaternion(this.systemQuaternion),this.systemQuaternion.invert(),e.getWorldPosition(this.currentWorldPosition),this.material.uniforms.uWorldOffset.value=this.currentWorldPosition,this.material.uniforms.uWorldQuaternion.value.copy(this.systemQuaternion.normalize()),this.positionSimRT.material.uniforms.uWorldOffset.value=this.currentWorldPosition,this.systemQuaternion.invert(),this.positionSimRT.material.uniforms.uWorldQuaternion.value.copy(this.systemQuaternion.normalize()),this.velocitySimRT.material.uniforms.uWorldQuaternion.value.copy(this.systemQuaternion.normalize())}update(e,r){if(!this.gpuCompute||!this.positionSimRT||!this.velocitySimRT||!this.emissionRateSimRT||this.hasBeenReset)return;if(this.checkIfAllParticlesAreDead()&&!this.hasBeenReset){this.reset();return}this.applyWorldSpace(),this.globalTime=e,this.positionSimRT.material.uniforms.uTime.value=e,this.emissionRateSimRT.material.uniforms.uTime.value=e;let i=1e3/r,s=this.targetFPS/i,o=this.previousRatio+(s-this.previousRatio)*this.lerpFactor;this.positionSimRT.material.uniforms.uFPSRatio.value=o,this.previousRatio=o;let a=this.isEmitting?this.GoEmitSomeParticles(e,this.system.data.birthRatePerSec):0;this.emissionRateSimRT.material.uniforms.uLastIndexEmitted.value=this.emittedParticlesAmount,this.emissionRateSimRT.material.uniforms.uParticlesToEmit.value=a,this.material.uniforms.uPosition.value=this.gpuCompute.getCurrentRenderTarget(this.positionSimRT)?.texture,this.system.colliderEntities.length>0&&this.renderColliders(),this.gpuCompute.compute()}renderColliders(){if(!this.velocitySimRT)return;let e=this.system.colliderEntities[0],r=this.simFeaturesDefinition.USE_COLLIDER||this.simFeaturesDefinition.USE_ATTRACTOR||this.simFeaturesDefinition.USE_VORTEX;if(e.destroyedInAction&&r&&this.init(nc({...this.system.data,colliderEntityId:null})),!e||e.destroyedInAction)return;e.getWorldPosition(this.colliderV3),this.colliderV3.y===0&&(this.colliderV3.y=1e-4),this.velocitySimRT.material.uniforms.uColliderPos.value.copy(this.colliderV3);let i=e.data.size;this.colliderV3.fromArray(i),this.velocitySimRT.material.uniforms.uColliderSize.value.copy(this.simFeaturesDefinition.USE_SPHERE_COLLIDER?this.colliderV3.multiplyScalar(.5):this.colliderV3),e.getWorldQuaternion(this.colliderQuaternion),this.velocitySimRT.material.uniforms.uColliderQuaternion.value.copy(this.colliderQuaternion.normalize()),this.velocitySimRT.material.uniforms.uColliderQuaternionInvert.value.copy(this.colliderQuaternion.normalize().invert())}updateState(e){!this.velocitySimRT||!this.positionSimRT||(e.renderMaterial&&this.updateMaterialState(e.renderMaterial),this.updateParticleState(e))}updateVariableState(e,r){if(!this.velocitySimRT||!this.positionSimRT)return;r[2]==="size"&&this.material.updateState({size:[e,this.material.uniforms.uSizeEnd.value]}),r[2]==="sizeEnd"&&this.material.updateState({size:[this.material.uniforms.uSize.value,e]});let i=(s,o)=>{let a=[...this.system.data.shape.size];a[s]=o,this.updateParticleState({shape:{...this.system.data.shape,size:a}})};r[2]==="shape_size_0"&&i(0,e),r[2]==="shape_size_1"&&i(1,e),r[2]==="shape_size_2"&&i(2,e),r[2]==="speed"&&(this.velocitySimRT.material.uniforms.uSpeed.value=e/yT),r[2]==="gravity"&&this.worldGravity.set(0,e/100,0),r[2]==="noiseStrength"&&(this.noiseStrength=e,this.velocitySimRT.material.uniforms.uNoiseStrength.value=this.noiseStrength),r[2]==="noiseScale"&&(this.noiseScale=e,this.velocitySimRT.material.uniforms.uNoiseScale.value=this.noiseScale),r[2]==="direction_x"&&(this.directionAxis=this.getDirectionAxis([Number(e),this.system.data.direction[1],this.system.data.direction[2]])),r[2]==="direction_y"&&(this.directionAxis=this.getDirectionAxis([this.system.data.direction[0],Number(e),this.system.data.direction[2]])),r[2]==="direction_z"&&(this.directionAxis=this.getDirectionAxis([this.system.data.direction[0],this.system.data.direction[1],Number(e)]))}updateMaterialState(e){this.material.updateState({...e,size:e.size?[Number(this.shared.getVariable(e.size[0],[this.uuid,"particles","size"])),Number(this.shared.getVariable(e.size[1],[this.uuid,"particles","sizeEnd"]))]:[0,0]}),e.texture&&(this.setTexture(this.material.uniforms,e.texture),this.material.needsUpdate=!0)}updateParticleState(e){if(!(!this.positionSimRT||!this.velocitySimRT)){if(this.shouldReInitGPUCompute(e)&&this.init(nc(this.system.data)),e.life!==void 0&&(this.positionSimRT.material.uniforms.uMaxLifeTime.value=e.life),e.speed!==void 0&&(this.velocitySimRT.material.uniforms.uSpeed.value=Number(this.shared.getVariable(e.speed,[this.uuid,"particles","speed"]))/yT),e.collisionBounce!==void 0&&(this.velocitySimRT.material.uniforms.uBounce.value=e.collisionBounce),e.noiseStrength!==void 0&&(this.noiseStrength=Number(this.shared.getVariable(e.noiseStrength,[this.uuid,"particles","noiseStrength"])),this.velocitySimRT.material.uniforms.uNoiseStrength.value=this.noiseStrength),e.noiseScale!==void 0&&(this.noiseScale=Number(this.shared.getVariable(e.noiseScale,[this.uuid,"particles","noiseScale"])),this.velocitySimRT.material.uniforms.uNoiseScale.value=this.noiseScale),e.noiseSeed!==void 0&&(this.velocitySimRT.material.uniforms.uNoiseSeed.value=e.noiseSeed),e.randomMass!==void 0&&(this.velocitySimRT.material.uniforms.uRandomMassFactor.value=e.randomMass),e.renderMaterial?.size!==void 0){let r=this.shared.getVariable(e.renderMaterial.size[0],[this.uuid,"particles","size"]);this.velocitySimRT.material.uniforms.particleSize.value=Number(r)}if(e.renderMaterial?.spriteRotation!==void 0&&(this.material.uniforms.uRotation.value=e.renderMaterial.spriteRotation[0],this.material.uniforms.uRotationEnd.value=e.renderMaterial.spriteRotation[1]),e.shape!==void 0){let r=e.shape.size??this.system.data.shape.size,i=[Number(this.shared.getVariable(r[0],[this.uuid,"particles","shape_size_0"])),Number(this.shared.getVariable(r[1],[this.uuid,"particles","shape_size_1"])),Number(this.shared.getVariable(r[2],[this.uuid,"particles","shape_size_2"]))],s={...nc(this.system.data).shape,size:i};this.emitterShape?.applyToShader(this.positionSimRT.material.uniforms,s)}if(e.gravity!==void 0&&(this.worldGravity.set(0,Number(this.shared.getVariable(this.system.data.gravity,[this.uuid,"particles","gravity"]))/100,0),this.velocitySimRT.material.uniforms.uGravity={value:this.worldGravity}),e.direction!==void 0){let r=this.getDirectionFromVariable(e.direction);this.directionAxis=this.getDirectionAxis(r),this.velocitySimRT.material.uniforms.uDirectionsAxis.value=this.directionAxis}e.randomRotation!==void 0&&(this.material.uniforms.uRandRotationFactor.value=e.randomRotation),e.randomScale!==void 0&&(this.material.uniforms.uRandScaleFactor.value=e.randomScale)}}updateForceFieldParameters(e){!this.velocitySimRT||(e.forceIntensity!==void 0&&(this.velocitySimRT.material.uniforms.uForceIntensity.value=e.forceIntensity),e.forceDambing!==void 0&&(this.velocitySimRT.material.uniforms.uForceDamping.value=e.forceDambing))}getDirectionAxis(e){let r=[Number(e[0])*we.DEG2RAD,Number(e[1])*we.DEG2RAD,Number(e[2])*we.DEG2RAD],i=new nr(r[0],r[1],r[2],"XYZ");return this.directionAxis.set(0,1,0).applyEuler(i).normalize(),this.velocitySimRT&&(this.velocitySimRT.material.uniforms.uDirectionsAxis.value=this.directionAxis),this.directionAxis}shouldReInitGPUCompute(e){let{birthRatePerSec:r,rootObjectType:i,colliderEntityId:s,shape:o,emitTimeDuration:a,emitTimeCycle:l,life:c,directionMode:u,noiseType:h}=e;return r!==void 0||i!==void 0||(s||s===null)||l!==void 0||o!==void 0||c!==void 0||a!==void 0||u!==void 0||h!==void 0}init(e){this.dispose(),this.particlesAmount=this.getMaxParticlesAmount({birthRatePerSecond:e.birthRatePerSec,particleMaxLifeTime:e.life,loopDuration:e.emitTimeCycle==="infinity"?0:e.emitTimeDuration}),this.particlesAmount>1e5&&(console.warn(`The maximum number of particles is limited to ${1e5}.`),this.particlesAmount=1e5),this.emitterShape=this.createShape(e.shape,this.particlesAmount);let r=setInterval(()=>{if(!!this.emitterShape)if(isNaN(this.emitterShape.positionsTexture.source.data.data[0])){this.init(e);return}else clearInterval(r)},100);if(!this.emitterShape)return;let i=new rb(this.emitterShape.textureSize,this.emitterShape.textureSize,this.renderer),s=this.updateSimulationDefinition(e),o=i.addVariable("uCurrentPosition",s+tB,this.emitterShape.positionsTexture),a=i.addVariable("uCurrentVelocity",s+oB,this.emitterShape.directionsTexture),l=i.addVariable("uCurrentEmissionRate",fB,eB(this.emitterShape.textureSize));i.setVariableDependencies(o,[o,a,l]),i.setVariableDependencies(a,[o,a,l]),i.setVariableDependencies(l,[o,a,l]);let c=$L({size:this.emitterShape.textureSize}),u={uOriginalPosition:{value:this.emitterShape.positionsTexture},uWorldOffset:{value:new E(0,0,0)},uWorldQuaternion:{value:new Ze(0,0,0,1)},uTime:{value:0},uFPSRatio:{value:1},uMaxLifeTime:{value:e.life},uEmitterSize:{value:new E(Number(this.shared.getVariable(e.shape.size[0],[this.uuid,"particles","shape_size_0"])),Number(this.shared.getVariable(e.shape.size[1],[this.uuid,"particles","shape_size_1"])),Number(this.shared.getVariable(e.shape.size[2],[this.uuid,"particles","shape_size_2"])))},particleSize:{value:0}};o.material.uniforms=u;let h=this.getDirectionFromVariable(e.direction);this.directionAxis=this.getDirectionAxis(h),this.worldGravity.set(0,Number(this.shared.getVariable(this.system.data.gravity,[this.uuid,"particles","gravity"]))/100,0),this.noiseStrength=Number(this.shared.getVariable(e.noiseStrength,[this.uuid,"particles","noiseStrength"])),this.noiseScale=Number(this.shared.getVariable(e.noiseScale,[this.uuid,"particles","noiseScale"]));let d=e.colliderEntityId&&this.system.getColliderData(e.colliderEntityId),f={uOriginalPosition:{value:this.emitterShape.positionsTexture},uDirections:{value:this.emitterShape.directionsTexture},uDirectionsAxis:{value:this.directionAxis},uWorldQuaternion:{value:new Ze(0,0,0,1)},uColliderPos:{value:new E(0,0,0)},uColliderSize:{value:new E(0,0,0)},uForceIntensity:{value:d?d.forceIntensity:0},uForceDamping:{value:d?d.forceDambing:0},uColliderQuaternion:{value:new Ze(0,0,0,1)},uColliderQuaternionInvert:{value:new Ze(0,0,0,1)},particleSize:{value:0},uGravity:{value:this.worldGravity},uNoiseStrength:{value:this.noiseStrength},uNoiseScale:{value:this.noiseScale},uNoiseSeed:{value:e.noiseSeed},uRandomMassFactor:{value:e.randomMass},uBounce:{value:e.collisionBounce},uSpeed:{value:Number(this.shared.getVariable(e.speed,[this.uuid,"particles","speed"]))/yT}};a.material.uniforms=f;let p={uIndex:{value:c},uTime:{value:0},uLastIndexEmitted:{value:0},uParticlesToEmit:{value:0}};l.material.uniforms=p;let m=[Number(this.shared.getVariable(e.shape.size[0],[this.uuid,"particles","shape_size_0"])),Number(this.shared.getVariable(e.shape.size[1],[this.uuid,"particles","shape_size_1"])),Number(this.shared.getVariable(e.shape.size[2],[this.uuid,"particles","shape_size_2"]))],g={...nc(this.system.data).shape,size:m};this.emitterShape.applyToShader(o.material.uniforms,g),i.init(),this.gpuCompute=i,this.positionSimRT=o,this.velocitySimRT=a,this.emissionRateSimRT=l,this.rootObject=this.createPrimaryEmitter(this.emitterShape.textureSize),this.add(this.rootObject),this.material.needsUpdate=!0}getDirectionFromVariable(e){let r=Number(this.shared.getVariable(e[0],[this.uuid,"particles","direction_x"])),i=Number(this.shared.getVariable(e[1],[this.uuid,"particles","direction_y"])),s=Number(this.shared.getVariable(e[2],[this.uuid,"particles","direction_z"]));return[r,i,s]}updateSimulationDefinition(e){if(this.simFeaturesDefinition.USE_COLLIDER=!1,this.simFeaturesDefinition.USE_ATTRACTOR=!1,this.simFeaturesDefinition.USE_VORTEX=!1,this.simFeaturesDefinition.USE_SPHERE_COLLIDER=!1,this.simFeaturesDefinition.USE_BOX_COLLIDER=!1,this.simFeaturesDefinition.USE_FORCE_LOCAL_SPACE=!1,this.simFeaturesDefinition.USE_NORMALS=!1,this.simFeaturesDefinition.USE_CURL_NOISE=!1,this.simFeaturesDefinition.USE_SIMPLEX_NOISE=!1,this.simFeaturesDefinition.USE_FBM_NOISE=!1,e.colliderEntityId&&this.system.colliderEntities.length>0){let i=this.system.getColliderData(e.colliderEntityId);switch(i?.forceType){case"attractor":this.simFeaturesDefinition.USE_ATTRACTOR=!0;break;case"collider":this.simFeaturesDefinition.USE_COLLIDER=!0;break;case"vortex":this.simFeaturesDefinition.USE_VORTEX=!0;break}let s=i?.colliderType;s==="sphere"&&(this.simFeaturesDefinition.USE_SPHERE_COLLIDER=!0),s==="box"&&(this.simFeaturesDefinition.USE_BOX_COLLIDER=!0),i?.forceRange==="helper"&&(this.simFeaturesDefinition.USE_FORCE_LOCAL_SPACE=!0)}e.directionMode==="normals"&&(this.simFeaturesDefinition.USE_NORMALS=!0),e.noiseType==="curl"&&(this.simFeaturesDefinition.USE_CURL_NOISE=!0),e.noiseType==="simplex"&&(this.simFeaturesDefinition.USE_SIMPLEX_NOISE=!0),e.noiseType==="fbm"&&(this.simFeaturesDefinition.USE_FBM_NOISE=!0);let r="";for(let[i,s]of Object.entries(this.simFeaturesDefinition))s&&(r+=`#define ${i} `);return r}createShape(e,r){this.emitterShape&&this.emitterShape.dispose();let i=new E(Number(this.shared.getVariable(e.size[0],[this.uuid,"particles","shape_size_0"])),Number(this.shared.getVariable(e.size[1],[this.uuid,"particles","shape_size_1"])),Number(this.shared.getVariable(e.size[2],[this.uuid,"particles","shape_size_2"])));if(e.type==="MeshEmitterShape"){let s=null;return this.system.context.scene.traverseEntity(o=>{o.uuid===e.fromMeshId&&(s=o)}),s?new Rf(i,r,e.type,s):new Rf(i,r,"SphereEmitterShape")}else return new Rf(i,r,e.type)}createPrimaryEmitter(e){let r,i=e*e;return r=new yy(new Li(1,1,1),this.material,i),this.updateGeometryAttributes(r,e),this.material.needsUpdate=!0,r.onBeforeRender=()=>{this.applyWorldSpace()},r}getMaxParticlesAmount({birthRatePerSecond:e,particleMaxLifeTime:r,loopDuration:i=0}){return Math.ceil(e*(r+i))}dispose(){!this.gpuCompute||(this.rootObject?.parent?.remove(this.rootObject),this.gpuCompute.dispose(),this.material.nodeMaterialDispose(),this.emitterShape?.dispose())}GoEmitSomeParticles(e,r){let i=e-this.lastEmitTime,s=1/r;if(i>=s){let o=Math.max(1,Math.floor(i/s));return this.lastEmitTime=e,this.emittedParticlesAmount+o>this.particlesAmount&&(this.emittedParticlesAmount=0),this.emittedParticlesAmount+=o,o}return 0}checkIfAllParticlesAreDead(){return this.lastEmitTime+this.system.data.life+1{this._hasOnAfterRenderBeenCalled||(this._hasOnAfterRenderBeenCalled=!0,this.init(e))};this.context=i,this.data={...r,...nc(r)},this.geometry.setAttribute("position",new Te([],3)),this.material=new on({colorWrite:!1}),this.frustumCulled=!1}init(e){this.renderer=e,this.emitter=new ob(e,this),this.add(this.emitter),this.updateParticleState(this.data)}update(e){if(!this.isReady||!this.started||this.isFrozen||this.isIdle)return;this.actualTime+=e,this.stopped||(this.currentLoopTime+=e);let r=this.data.emitTimeCycle==="one_time";if((this.data.emitTimeCycle==="loop"||r)&&this.currentLoopTime>this.data.emitTimeDuration*1e3&&(this.stopped||(this.stop(),r||this.start(this.data.emitTimeDelay*1e3))),this.emitter&&this.started){let s=this.actualTime/1e3;this.emitter.update(s,e)}this.scale.set(1,1,1),this.updateMatrix()}isReady(){return!!this.emitter}hasCollider(e){return this.colliderEntities.some(r=>r.identity===e)}getColliderData(e){let r=this.colliderEntities.find(i=>i.identity===e);return r?r.data:null}updateByPatchedOp(e,r,i){super.updateByPatchedOp(e,r,i),Lt(e.path,["renderMaterial"])&&this.updateParticleState({renderMaterial:{...this.data.renderMaterial,...Lr.drop(e,1).props}}),Lt(e.path,["shape"])&&this.updateParticleState({shape:{...this.data.shape,...Lr.drop(e,1).props}})}updateState(e,r){super.updateState(e,r),this.updateParticleState(e)}updateParticleState(e){if(!!this.emitter){if(e.colliderEntityId!==void 0&&e.colliderEntityId!==null){let r=this.context.scene.find(e.colliderEntityId);this.colliderEntities=r?[r]:[]}e.colliderEntityId===null&&(this.colliderEntities=[]),this.emitter.updateState(e),e.emitTimeCycle&&this.started&&this.start()}}updateFromColliderEntity(e){!this.emitter||(this.emitter.updateForceFieldParameters(e),this.stop(),this.start())}start(e=0){if(this.currentLoopTime=0,e){this.timeoutId=window.setTimeout(()=>{this.start(0)},e);return}this.started=!0,this.stopped=!1,this.isFrozen=!1,this.emitter?.startEmitting(this.actualTime/1e3)}froze(){this.isFrozen=!0}unFroze(){this.isFrozen=!1}stop(){this.stopped=!0,this.currentLoopTime=0,this.emitter?.stopEmitting(),clearTimeout(this.timeoutId)}reset(){this.started=!1,this.stopped=!1,this.emitter?.reset()}wakeUp(){this.isIdle=!1}sleep(){this.isIdle=!0,this.reset()}};function DZ(){try{let n=window.location.href;if(n.includes("reducesubdiv=")){let t=n.indexOf("reducesubdiv=")+13;return parseInt(n.slice(t,t+1))}}catch{}}var vT=DZ();function OZ(n,t,e){vT!==void 0&&(t?.geometry?.subdivisions??0)>vT&&(console.log("reducing subdivisions",t.name,t.geometry.subdivisions),t.geometry.subdivisions=vT);let r;return t.geometry.type==="TextGeometry"?new Yl(n,t,e):t.geometry.type==="InputGeometry"?new ic(n,t,e):(t.geometry.type==="SubdivGeometry"?r=new Zs(n,t,e):t.geometry.type==="PathGeometry"?r=new rc(n,t,e):t.geometry.type==="VectorGeometry"?r=new $x(n,t,e):t.geometry.type==="BooleanGeometry"?r=new Fn(n,t,e):t.geometry.type==="UIGeometry"?r=new Er(n,t,e):r=new cr(n,t,e),r)}function ab(n,t,e){return console.assert(t.type!==void 0),t.type==="Mesh"?OZ(n,t,e):t.type==="Empty"?new As(n,t):t.type==="Particle"?new sc(n,t,e):t.type==="ParticleCollider"?new Kl(n,t,e):t.type==="Splat"?new As(n,t):t.type==="Bone"?new tb(n,t):t.type==="Page"?new ur(n,t,e):t.type==="PointLight"?new Jx(n,t,e):t.type==="SpotLight"?new If(n,t,e):t.type==="DirectionalLight"?new _f(n,t,e):t.type==="Component"||t.type==="Instance"?new eo(n,t,e):ks.is(t.type)?new wr(n,t):(console.error(t),new As(n,t))}Hs.createEntity=ab;function RZ(n,t,e){let r=ab(n.identity,t,e),i=n.children,s=n.attachedPaths,o=n.parent,a=n.component,l=n.instances,c=n.overrideData,u=n.uuid,h=n.stateSelection;n.dispose();for(let d of Object.keys(n))delete n[d];Object.setPrototypeOf(n,Object.getPrototypeOf(r));for(let d of Object.keys(r))n[d]=r[d];n.children=[...n.children,...i],n.attachedPaths=s,n.parent=o,n.component=a,n.instances=l,n.uuid=u,n.overrideData=c,n.updateState(n.data,e),h&&n.changeSelectedState(h,e),n.resetBBoxNeedsUpdate()}Hs.changeEntityProptotype=RZ;Hs.Cloner=Gi;function mB(n,t,e,r){n.updateByOp(t,e,r,!1)}function gB(n,t){let e=!1,r=t.getLayersOfType("transmission"),i=t.getLayersOfType("outline");return i.length>0&&(n.layers.set(8),r.length>0&&n.layers.enable(3),e=!0,af(n),of(n)),r.length===0&&i.length===0&&n.layers.set(0),n instanceof vs&&n.needsAO&&n.layers.enable(5),e}function yB(n,t){if(!t.layers)return!1;let e=!1,r=t.getLayersOfType("transmission").filter(s=>s.data.visible),i=t.getLayersOfType("outline").filter(s=>s.data.visible);return r.length>0&&(n.layers.set(3),i.length>0&&n.layers.enable(8),e=!0),r.length===0&&i.length===0&&n.layers.set(0),n.needsAO&&n.layers.enable(5),e}function vB(n){let t=!1;return n.traverseEntity(e=>{if(e instanceof vs)if(Array.isArray(e.material))for(let r=0;r{if(e instanceof vs)if(Array.isArray(e.material))for(let r=0;r0&&e.push({...u[0],object:r?s:n})}}var lb=class{constructor(){this._constraints=new Map}setConstraint(t,e){e===null?this._constraints.delete(t):this._constraints.set(t,e)}removeDependencies(t){this._constraints.delete(t)}applyConstraints(t){let e=new Set;this._constraints.forEach((r,i)=>{let s=[i,r],o=r;for(;this._constraints.has(o);){if(o=this._constraints.get(o),s.includes(o)){console.warn(`circular dependency detected: ${s.join(" -> ")}`);break}e.has(o)||s.push(o)}for(let a=s.length-2;a>=0;a--)if(!e.has(s[a])){let l=t.find(s[a]);l?l.applyPathSnapping(t):console.warn(`missing entity ${s[a]}`),e.add(s[a])}})}findDependency(t,e){let r=t;for(;this._constraints.has(r);)if(r=this._constraints.get(r),r===e)return!0;return!1}};var bB="AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAETA2AAAGAIf39/f39/f38AYAABfwISAQNlbnYGbWVtb3J5AgMAgIAEAwQDAAECBzkDEV9fd2FzbV9jYWxsX2N0b3JzAAALc29ydEluZGV4ZXMAARNlbXNjcmlwdGVuX3Rsc19pbml0AAIK3gMDAwABC9IDAwF/BnwBfgJAIAdFDQAgAysDUCEMIAMrAzAhDSADKwMQIQ5BACEDRP///////+9/IQtEAAAAAAAAEAAhCgNAIAIgA0ECdGoCfyAOIAEgA0EMbGoiCCoCALuiIA0gCCoCBLuioCAMIAgqAgi7oqBEAAAAAAAAsECiIgmZRAAAAAAAAOBBYwRAIAmqDAELQYCAgIB4CzYCACAJIAsgCSALYxshCyAJIAogCSAKZBshCiADQQFqIgMgB0cNAAsgB0UNACAGuCAKIAuhoyEJQQAhAwNAAn8gCSACIANBAnRqIgEoAgC3IAuhoiIKmUQAAAAAAADgQWMEQCAKqgwBC0GAgICAeAshCCABIAg2AgAgBCAIQQJ0aiIBIAEoAgBBAWo2AgAgA0EBaiIDIAdHDQALCyAGQQJPBEAgBCgCACEIQQEhAwNAIAQgA0ECdGoiASABKAIAIAhqIgg2AgAgA0EBaiIDIAZHDQALCyAHQQFrIgGtIQ8DQCAEIAIgD6dBAnQiA2ooAgBBAnRqIgcgBygCAEEBayIHNgIAIAUgASAHa0ECdGogACADaigCADYCACAPUCEDIA9CAX0hDyADRQ0ACyAGBEAgBEEAIAZBAnT8CwALCwQAQQAL";var Ho=class{};uo(Ho,"DepthMapRange",1<<16),uo(Ho,"MemoryPageSize",65536),uo(Ho,"BytesPerFloat",4),uo(Ho,"BytesPerInt",4);function FZ(n){let t,e,r,i,s,o,a,l,c,u,h,d,f,p,m,g;function y(P){let I=new Float64Array(u,o,16);for(let D=0;D<16;D++)I[D]=P[D];let _;if(r>1){t.exports.sortIndexes(i,s,c,o,a,l,d.DepthMapRange,r);let D=new Uint32Array(r);_=D.buffer,D.set(new Uint32Array(u,l,r))}else if(r===1){let D=new Uint32Array(r);D[0]=new Uint32Array(u,i,e)[0],_=D.buffer}else _=new ArrayBuffer(0);n.postMessage({sortDone:!0,indexesBuffer:_},[_])}function v(P,I,_){let D=new Float32Array(u,s,e*3);r=0;let L=new Uint32Array(u,i,e);for(let j=0;j<_.length-1;j++){let V=I[j],H=P[j].elements,W=V.filter(Q=>Q.enabled&&Q.mode==="Include").map(Q=>Q.type==="Box"?A(Q):M(Q)),q=V.filter(Q=>Q.enabled&&Q.mode==="Exclude").map(Q=>Q.type==="Box"?A(Q):M(Q));for(let Q=_[j];Q<_[j+1];Q++){let G=f[Q*3],Z=f[Q*3+1],te=f[Q*3+2];if((W.length===0||S(G,Z,te,W))&&(q.length===0||!S(G,Z,te,q))){let $=1/(H[3]*G+H[7]*Z+H[11]*te+H[15]);D[r*3]=(H[0]*G+H[4]*Z+H[8]*te+H[12])*$,D[r*3+1]=(H[1]*G+H[5]*Z+H[9]*te+H[13])*$,D[r*3+2]=(H[2]*G+H[6]*Z+H[10]*te+H[14])*$,L[r]=Q,r++}}}}function x(P,I){let _=[],D=I.filter(V=>V.enabled&&V.mode==="Include").map(V=>V.type==="Box"?A(V):M(V)),L=I.filter(V=>V.enabled&&V.mode==="Exclude").map(V=>V.type==="Box"?A(V):M(V)),j=P.length;for(let V=0;V{let V=w(P,I,_,j.invRotationMatrix,j.cropCenter);return Array.isArray(j)?b(V.x,V.y,V.z,j):C(V.x,V.y,V.z,j)})}function w(P,I,_,D,L){let j=P-L[0],V=I-L[1],H=_-L[2],W=1/(D[3]*j+D[7]*V+D[11]*H+D[15]);return{x:(D[0]*j+D[4]*V+D[8]*H+D[12])*W+L[0],y:(D[1]*j+D[5]*V+D[9]*H+D[13])*W+L[1],z:(D[2]*j+D[6]*V+D[10]*H+D[14])*W+L[2]}}function A(P){let I=P.cropSize[0]/2,_=P.cropSize[1]/2,D=P.cropSize[2]/2,L=[P.cropCenter[0]-I,P.cropCenter[1]-_,P.cropCenter[2]-D,P.cropCenter[0]+I,P.cropCenter[1]+_,P.cropCenter[2]+D],j=T(P.cropRotation);return Object.assign(L,{invRotationMatrix:j,cropCenter:P.cropCenter})}function T(P){let I=[],_=P[0]*Math.PI/180,D=P[1]*Math.PI/180,L=P[2]*Math.PI/180,j=Math.cos(_),V=Math.sin(_),H=Math.cos(D),W=Math.sin(D),q=Math.cos(L),Q=Math.sin(L),G=j*q,Z=j*Q,te=V*q,$=V*Q;return I[0]=H*q,I[1]=-H*Q,I[2]=W,I[4]=Z+te*W,I[5]=G-$*W,I[6]=-V*H,I[8]=$-G*W,I[9]=te+Z*W,I[10]=j*H,I[12]=0,I[13]=0,I[14]=0,I[3]=0,I[7]=0,I[11]=0,I[15]=1,I}function b(P,I,_,D){return P>=D[0]&&P<=D[3]&&I>=D[1]&&I<=D[4]&&_>=D[2]&&_<=D[5]}function M(P){let I=2/P.cropSize[0],_=2/P.cropSize[1],D=2/P.cropSize[2],L=T(P.cropRotation);return{invRadiusX:I,invRadiusY:_,invRadiusZ:D,cropCenter:P.cropCenter,invRotationMatrix:L}}function C(P,I,_,D){let L=(P-D.cropCenter[0])*D.invRadiusX,j=(I-D.cropCenter[1])*D.invRadiusY,V=(_-D.cropCenter[2])*D.invRadiusZ;return L*L+j*j+V*V<=1}n.onmessage=P=>{if(P.data.getCroppedIndexes){let I=new Uint32Array(x(new Float32Array(P.data.positions),P.data.crops)).buffer;n.postMessage({outOfBoundsIndexes:I},[I])}else if(P.data.positions)h=P.data.positions,f=new Float32Array(h),m=P.data.meshMatrixWorlds,g=P.data.cropsArray,p=P.data.meshIndexIntervals,v(m,g,p),n.postMessage({sortSetupComplete:!0});else if(P.data.sort||P.data.newMatrixWorlds||P.data.newCropsArray)(P.data.newMatrixWorlds||P.data.newCropsArray)&&(g=P.data.newCropsArray||g,m=P.data.newMatrixWorlds||m,v(m,g,p)),y(P.data.sort.view,P.data.sort.cameraPosition);else if(P.data.init){d=P.data.init.Constants,e=P.data.init.splatCount;let I=d.BytesPerInt,_=d.BytesPerFloat*3,D=new Uint8Array(P.data.init.sorterWasmBytes),L=I+_,j=e*L,V=e*d.BytesPerInt*2+d.DepthMapRange*d.BytesPerInt*2,H=d.MemoryPageSize*32,W=j+V+H,q=Math.floor(W/d.MemoryPageSize)+1,Q={module:{},env:{memory:new WebAssembly.Memory({initial:q*2,maximum:q*3,shared:!0})}};WebAssembly.compile(D).then(G=>WebAssembly.instantiate(G,Q)).then(G=>{t=G,i=0,s=e*I,o=s+e*_,c=o+16*d.BytesPerFloat*2,a=c+e*d.BytesPerInt,l=a+d.DepthMapRange*d.BytesPerInt,u=Q.env.memory.buffer,n.postMessage({sortSetupPhase1Complete:!0})})}}}function SB(n){let t=new Worker(URL.createObjectURL(new Blob(["(",FZ.toString(),")(self)"],{type:"application/javascript"}))),e=atob(bB),r=new Uint8Array(e.length);for(let i=0;i{if(r.visible===!1)return!0;r.type==="Splat"&&(t=!0)}),t}var oc=class extends Ut{constructor(e,r,i,s,o=!1,a=1,l,c){super(i,s);this.splatCount=r,this.meshIndexIntervals=l,this.meshMatrixWorlds=c,this.splatBuffers=e,this.geometry=i,this.material=s,this.splatDataTextures=null,this.halfPrecisionCovariancesOnGPU=o,this.devicePixelRatio=a,this.resetLocalSplatDataAndTexturesFromSplatBuffer()}static buildMesh(e,r,i=!1,s=1,o,a){let l=oc.buildGeomtery(r),c=oc.buildMaterial(o);return new oc(e,r,l,c,i,s,o,a)}static buildMaterial(e){let r=` precision highp float; #include attribute uint splatIndex; uniform highp sampler2D covariancesTexture; uniform highp usampler2D centersColorsTexture; uniform vec2 focal; uniform vec2 viewport; uniform vec2 basisViewport; uniform vec2 covariancesTextureSize; uniform vec2 centersColorsTextureSize; uniform highp sampler2D meshMatrixWorldsTexture; uniform uint meshIndexIntervals[257]; uniform float orthoZoom; varying vec4 vColor; varying vec2 vUv; varying vec2 vPosition; const vec4 encodeNorm4 = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0); const uvec4 mask4 = uvec4(uint(0x000000FF), uint(0x0000FF00), uint(0x00FF0000), uint(0xFF000000)); const uvec4 shift4 = uvec4(0, 8, 16, 24); vec4 uintToRGBAVec (uint u) { uvec4 urgba = mask4 & u; urgba = urgba >> shift4; vec4 rgba = vec4(urgba) * encodeNorm4; return rgba; } vec2 getDataUV(in int stride, in int offset, in vec2 dimensions) { vec2 samplerUV = vec2(0.0, 0.0); float d = float(splatIndex * uint(stride) + uint(offset)) / dimensions.x; samplerUV.y = float(floor(d)) / dimensions.y; samplerUV.x = fract(d); return samplerUV; } void main () { uvec4 sampledCenterColor = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize)); vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenterColor.gba)); vColor = uintToRGBAVec(sampledCenterColor.r); vPosition = position.xy * 2.0; uint meshIndex; for (int i = 1; i < 257; i++) { if (splatIndex < meshIndexIntervals[i]) { meshIndex = uint(i - 1); break; } } float strideMulmeshIndex = float(4u*meshIndex); float meshMatrixWorldsTextureLength = float(256*4); mat4 modelMat = mat4( texture(meshMatrixWorldsTexture, vec2((strideMulmeshIndex+0.0)/meshMatrixWorldsTextureLength, 0)), texture(meshMatrixWorldsTexture, vec2((strideMulmeshIndex+1.0)/meshMatrixWorldsTextureLength, 0)), texture(meshMatrixWorldsTexture, vec2((strideMulmeshIndex+2.0)/meshMatrixWorldsTextureLength, 0)), texture(meshMatrixWorldsTexture, vec2((strideMulmeshIndex+3.0)/meshMatrixWorldsTextureLength, 0)) ); mat4 modelViewMat = viewMatrix * modelMat; vec4 viewCenter = modelViewMat * vec4(splatCenter, 1.0); vec4 clipCenter = projectionMatrix * viewCenter; vec2 sampledCovarianceA = texture(covariancesTexture, getDataUV(3, 0, covariancesTextureSize)).rg; vec2 sampledCovarianceB = texture(covariancesTexture, getDataUV(3, 1, covariancesTextureSize)).rg; vec2 sampledCovarianceC = texture(covariancesTexture, getDataUV(3, 2, covariancesTextureSize)).rg; vec3 cov3D_M11_M12_M13 = vec3(sampledCovarianceA.rg, sampledCovarianceB.r); vec3 cov3D_M22_M23_M33 = vec3(sampledCovarianceB.g, sampledCovarianceC.rg); // Compute the 2D covariance matrix from the upper-right portion of the 3D covariance matrix mat3 Vrk = mat3( cov3D_M11_M12_M13.x, cov3D_M11_M12_M13.y, cov3D_M11_M12_M13.z, cov3D_M11_M12_M13.y, cov3D_M22_M23_M33.x, cov3D_M22_M23_M33.y, cov3D_M11_M12_M13.z, cov3D_M22_M23_M33.y, cov3D_M22_M23_M33.z ); float s = 1.0 / (viewCenter.z * viewCenter.z); mat3 W = transpose(mat3(modelViewMat)); mat3 T = orthoZoom > 0.0 ? W : W * mat3( focal.x / viewCenter.z, 0., -(focal.x * viewCenter.x) * s, 0., focal.y / viewCenter.z, -(focal.y * viewCenter.y) * s, 0., 0., 0. ); mat3 cov2Dm = transpose(T) * Vrk * T; cov2Dm[0][0] += 0.3; cov2Dm[1][1] += 0.3; // We are interested in the upper-left 2x2 portion of the projected 3D covariance matrix because // we only care about the X and Y values. We want the X-diagonal, cov2Dm[0][0], // the Y-diagonal, cov2Dm[1][1], and the correlation between the two cov2Dm[0][1]. We don't // need cov2Dm[1][0] because it is a symetric matrix. vec3 cov2Dv = vec3(cov2Dm[0][0], cov2Dm[0][1], cov2Dm[1][1]); vec3 ndcCenter = clipCenter.xyz / clipCenter.w; // We now need to solve for the eigen-values and eigen vectors of the 2D covariance matrix // so that we can determine the 2D basis for the splat. This is done using the method described // here: https://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html // // This is a different approach than in the original work at INRIA. In that work they compute the // max extents of the 2D covariance matrix in screen space to form an axis aligned bounding rectangle // which forms the geometry that is actually rasterized. They then use the inverse 2D covariance // matrix (called 'conic') to determine fragment opacity. float a = cov2Dv.x; float d = cov2Dv.z; float b = cov2Dv.y; float D = a * d - b * b; float trace = a + d; float traceOver2 = 0.5 * trace; float term2 = sqrt(trace * trace / 4.0 - D); float eigenValue1 = traceOver2 + term2; float eigenValue2 = max(traceOver2 - term2, 0.00); // prevent negative eigen value const float maxSplatSize = 1024.0; vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a)); // since the eigen vectors are orthogonal, we derive the second one from the first vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x); vec2 basisVector1 = eigenVector1 * min(sqrt(2.0 * eigenValue1), maxSplatSize); vec2 basisVector2 = eigenVector2 * min(sqrt(2.0 * eigenValue2), maxSplatSize); vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) * basisViewport; if (orthoZoom > 0.0) { ndcOffset *= orthoZoom; } gl_Position = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0); }`,i=` precision highp float; #include uniform vec3 debugColor; varying vec4 vColor; varying vec2 vUv; varying vec2 vPosition; layout(location = 1) out vec4 gVelocity; void main () { // compute the negative squared distance from the center of the splat to the // current fragment in the splat's local space. float A = -dot(vPosition, vPosition); if (A < -4.0) discard; vec3 color = vColor.rgb; A = exp(A) * vColor.a; gl_FragColor = vec4(color.rgb, A); gVelocity = vec4(0.0); // so it is ignored by TAA }`,s={covariancesTexture:{type:"t",value:null},centersColorsTexture:{type:"t",value:null},meshIndexIntervals:{value:e},meshMatrixWorldsTexture:{type:"t",value:null},focal:{type:"v2",value:new k},viewport:{type:"v2",value:new k},basisViewport:{type:"v2",value:new k},debugColor:{type:"v3",value:new We},covariancesTextureSize:{type:"v2",value:new k(1024,1024)},centersColorsTextureSize:{type:"v2",value:new k(1024,1024)},orthoZoom:{type:"f",value:-1}};return new it({uniforms:s,vertexShader:r,fragmentShader:i,transparent:!0,alphaTest:1,blending:$a,depthTest:!0,depthWrite:!1,side:fi})}static buildGeomtery(e){let r=new _e;r.setIndex([0,1,2,0,2,3]);let i=new Float32Array(4*3),s=new Xe(i,3);r.setAttribute("position",s),s.setXYZ(0,-1,-1,0),s.setXYZ(1,-1,1,0),s.setXYZ(2,1,1,0),s.setXYZ(3,1,-1,0),s.needsUpdate=!0;let o=new Mp().copy(r),a=new Uint32Array(e),l=new mo(a,1,!1);return l.setUsage(uP),o.setAttribute("splatIndex",l),o.instanceCount=e,o}resetLocalSplatDataAndTexturesFromSplatBuffer(){this.updateLocalSplatDataFromSplatBuffer(),this.allocateAndStoreLocalSplatDataInTextures()}updateLocalSplatDataFromSplatBuffer(){this.splatBuffers.forEach(s=>s.buildPreComputedBuffers()),this.covariances=new Float32Array(this.splatCount*6),this.colors=new Uint8Array(this.splatCount*4),this.centers=new Float32Array(this.splatCount*3);let e=0,r=0,i=0;for(let s of this.splatBuffers){let o=s.nsplats;this.colors.subarray(e,e+o*4).set(s.colorsA),e+=o*4,this.centers.subarray(r,r+o*3).set(s.decoded.xyz.denormDequant().data),r+=o*3,this.covariances.subarray(i,i+o*6).set(new Float32Array(s.precomputedCovarianceBufferData)),i+=o*6}}allocateAndStoreLocalSplatDataInTextures(){let i=this.splatCount,s=new k(4096,1024);for(;s.x*s.y*20&&(ub.set(e.x*this.devicePixelRatio,e.y*this.devicePixelRatio),this.material.uniforms.viewport.value.copy(ub),this.material.uniforms.basisViewport.value.set(2/ub.x,2/ub.y),this.material.uniforms.focal.value.set(r,i),this.material.uniforms.orthoZoom.value=s,this.material.uniformsNeedUpdate=!0)}getSplatDataTextures(){return this.splatDataTextures}getSplatCount(){return this.splatCount}getCenters(){return this.centers}getColors(){return this.colors}getCovariances(){return this.covariances}dispose(){this.geometry.dispose(),this.material.dispose(),this.splatDataTextures&&(this.splatDataTextures.covariances.texture.dispose(),this.splatDataTextures.centerColors.texture.dispose(),this.splatDataTextures.meshMatrixWorlds.texture.dispose()),this.removeFromParent()}};var EB,xT=new Promise(n=>{EB=n}),AB=!1;var db;function bT(){if(AB)return;if(db)return db;async function n(){let e=await import("./gaussian-splat-compression.js");EB(e),AB=!0}return db=n(),db}var TB;xT.then(n=>TB=n);var Xm=class{constructor(t={}){uo(this,"updateView",function(){let t=new ue,e=[],r=new E(0,0,-1),i=new E(0,0,-1),s=new E,o=new E;return function(a=!1,l){let c=this.updateMatrixWorldsInWorkerIfNeeded(),u=this.cropsChanged();if(!a){i.set(0,0,-1).applyQuaternion(l.quaternion);let d=!1,f=!1;if(i.dot(r)<=.95&&(d=!0),o.copy(l.position).sub(s).length()>=1&&(f=!0),!d&&!f&&!c&&!u&&!this.needsInitialRender)return}this.needsInitialRender=!1,s.copy(l.position),r.copy(i),t.copy(l.matrixWorld).invert(),t.premultiply(this.dummyPerspectiveMatrix),e[0]=l.position.x,e[1]=l.position.y,e[2]=l.position.z;let h={sort:{view:t.elements,cameraPosition:e,splatRenderCount:this.splatRenderCount,splatSortCount:this.splatRenderCount},...c?{newMatrixWorlds:this.meshMatrixWorlds}:{},...u?{newCropsArray:this.cropsArray}:{}};this.sortRunning?this.queuedMessage=h:(this.queuedMessage=null,this.sortRunning=!0,this.sortWorker.postMessage(h))}}());this.scene=t.scene,this.currentPage=null,this.devicePixelRatio=window.devicePixelRatio,this.sortWorker=null,this.splatRenderCount=0,this.splatSortCount=0,this.splatMesh=null,this.sortRunning=!1,this.meshMatrixWorlds=null,this.meshMatrixWorldsOld=null,this.cropsArray=null,this.splatEntries=null,this.queuedMessage=null,this.needsInitialRender=!0,this.dummyPerspectiveMatrix=new ue().makePerspective(-1,1,-1,1,.1,1e3)}updateSplatMeshUniforms(t,e){let r=new k;if(this.splatMesh===null)return;this.splatMesh.getSplatCount()>0&&(t.getSize(r),this.cameraFocalLengthX=e.projectionMatrix.elements[0]*this.devicePixelRatio*r.x*.45,this.cameraFocalLengthY=e.projectionMatrix.elements[5]*this.devicePixelRatio*r.y*.45,this.splatMesh.updateUniforms(r,this.cameraFocalLengthX,this.cameraFocalLengthY,e.isPerspectiveCamera?-1:e.zoom*this.devicePixelRatio))}loadSplat(t={}){this.activePage=this.scene.activePage,t.position&&(t.position=new E().fromArray(t.position)),t.orientation&&(t.orientation=new Ke().fromArray(t.orientation)),t.halfPrecisionCovariances=!!t.halfPrecisionCovariances;let e=[];if(this.splatEntries=e,this.activePage.traverseVisibleEntity(o=>{o.data.type==="Splat"&&e.push(o)}),this.splatMesh&&this.splatMesh.dispose(),e.length===0)return this.splatMesh=null,!1;this.meshMatrixWorlds=e.map(o=>o.matrixWorld),this.meshMatrixWorldsOld=e.map(o=>o.matrixWorld.clone()),this.cropsArray=e.map(o=>o.data.crops.map(a=>a.data));let r=e.map(o=>new TB.GSplineBuffer(new Uint8Array(o.data.buffer).buffer)),i=0,s=[0];for(let o of r)i+=o.getSplatCount(),s.push(i);return this.setupSplatMesh(r,i,t.position,t.orientation,t.halfPrecisionCovariances,this.devicePixelRatio,s,this.meshMatrixWorlds),this.setupSortWorker(i),!0}updateMatrixWorldsInWorkerIfNeeded(){let t=this.splatDataTextures.meshMatrixWorlds.data;for(let e=0;ee.equals(this.meshMatrixWorldsOld[r]))?!1:(this.meshMatrixWorldsOld=this.meshMatrixWorlds.map(e=>e.clone()),!0)}cropsChanged(){let t=!1;return this.splatEntries.forEach((e,r)=>{e.data.crops.forEach((i,s)=>{this.cropsArray[r][s]===void 0?(t=!0,this.cropsArray[r][s]=i.data):Object.entries(i.data).forEach(([o,a])=>{Array.isArray(a)&&a.some((l,c)=>l!==this.cropsArray[r][s][o][c])?(t=!0,this.cropsArray[r][s][o]=a):a!==this.cropsArray[r][s]?.[o]&&(t=!0,this.cropsArray[r][s][o]=a)})}),e.data.crops.length!==this.cropsArray[r]?.length&&(this.cropsArray[r].length=e.data.crops.length,t=!0)}),t}setupSplatMesh(t,e,r=new E,i=new Ke,s=!1,o=1,a,l){this.splatMesh=oc.buildMesh(t,e,s,o,a,l),this.splatMesh.position.copy(r),this.splatMesh.quaternion.copy(i),this.splatMesh.frustumCulled=!1,this.splatMesh.renderOrder=99999,this.splatRenderCount=e,this.splatMesh.onBeforeRender=(c,u,h)=>this.update(c,h)}setupSortWorker(t){this.sortWorker=SB(t),this.sortWorker.onmessage=e=>{e.data.sortDone?(this.sortRunning=!1,this.splatMesh?.updateIndexes(new Uint32Array(e.data.indexesBuffer)),this.lastSortTime=e.data.sortTime,this.queuedMessage&&(this.sortWorker.postMessage(this.queuedMessage),this.queuedMessage=null)):e.data.sortCanceled?this.sortRunning=!1:e.data.sortSetupPhase1Complete?this.sortWorker.postMessage({positions:this.splatMesh.getCenters().buffer,meshMatrixWorlds:this.splatMesh.meshMatrixWorlds,meshIndexIntervals:this.splatMesh.meshIndexIntervals,cropsArray:this.cropsArray}):e.data.sortSetupComplete&&(this.splatDataTextures=this.splatMesh.getSplatDataTextures(),this.scene.activePage.add(this.splatMesh),this.needsInitialRender=!0)}}update(t,e){this.splatMesh!==null&&(this.updateSplatMeshUniforms(t,e),this.updateView(!1,e))}getSplatMesh(){return this.splatMesh}};var Gx=new on;Gx.wireframe=!0;var MB=new E,Jl=class extends ei{constructor(e,r){super();this.data=e;this.sharedAssets=r;this.enableHelpers=!1;this.wireframeState=!1;this.needsTransmissionDirty=!0;this.needsNormalDirty=!0;this._needsTransmission=!1;this._needsNormal=!1;this.geometryCacheChanged=!1;this.splatViewer=null;this.entityByUuid={};this.entityIdentityToEntity={};this.toExpandCloner=new Set;this.toUpdateCloner=new Set;this.pendingCommands=[];this.pathConstraints=new lb;this.invisibleObjects=new As("jflkdsafjasdifjaslk",{...t0.defaultData,visible:!1,name:"buildin invisible"});this.needsRecomputeInstances=!1;this.init(e,r),this.matrixAutoUpdate=!1,this.errorPage=new ur("fdasfa",{...ba.defaultData,name:""},{shared:r,scene:this})}markGeometryCacheDirty(){this.geometryCacheChanged=!0}markNeedsUpdateRendererDirty(){this.needsTransmissionDirty=!0,this.needsNormalDirty=!0}needsTransmission(){return this.needsTransmissionDirty&&(this._needsTransmission=xB(this),this.needsTransmissionDirty=!1),this._needsTransmission}needsNormal(){return this.needsNormalDirty&&(this._needsNormal=vB(this),this.needsNormalDirty=!1),this._needsNormal}registerInstanceAndSetUuid(e){let r=e.identity.join("-"),i=this.entityIdentityToEntity[r];i&&(e.uuid=i.uuid),this.entityIdentityToEntity[r]=e,this.entityByUuid[e.uuid]=e}markPenumbraSizeDirty(){for(let e of this.children)e instanceof ur&&(e.penumbraSizeArrayCache=null)}findInstance(e){return this.entityIdentityToEntity[e.join("-")]}get bgColor(){return this.activePage.bgColor}get postprocessing(){return this.activePage.data.postprocessing}getWithSortKey(e){let r=this.find(e);if(r===void 0)return;let i=[],s=r;for(;s!==this;){let o=s;s=s.parent;let a=s.children.indexOf(o);i.splice(0,0,a)}return{entity:r,sortKey:i}}getAllSorted(e){let r=[];for(let i of e){let s=this.getWithSortKey(i.id);s!==void 0&&r.push(s)}return r.sort((i,s)=>fv(i.sortKey,s.sortKey)),r.map(i=>i.entity)}nonExistOrDescendantOf(e,r){let i=this.find(e);if(i===void 0)return!0;for(;i;){if(i.uuid===r)return!0;i=i.parent}return!1}find(e){if(this.activePage&&this.activePage.personalCamera.parent){if(e==="f23858d0-4a3b-4bd8-8173-66ed0af7f6fb-personalCamera")return this.activePage.personalCamera;if(e===hs)return this.activePage.personalCamera}if(e===""||e===void 0)return;let r=this.entityByUuid[e];return r===void 0?this.getObjectByProperty("uuid",e):r}find2D(e){for(let r of this.children)if(r instanceof ur&&r.uiScene){let i=r.uiScene.find(e);if(i)return i}}findScene2DfromObject2D(e){for(let r of this.children)if(r instanceof ur&&r.uiScene&&r.uiScene.find(e))return r.uiScene}find2DInUIObjects(e){let r;return this.traverseEntity(i=>{r===void 0&&i instanceof Er&&(r=i.uiCanvas.find(e))}),r}traverse2D(e){for(let r of this.children)r instanceof ur&&r.uiScene&&r.uiScene.traverse(e)}debugEnsureEntity(e){let r=this.find(e);if(r){if(Array.isArray(r.identity)&&this.findInstance(r.identity)===void 0){console.error("not found instance");debugger}}else{console.error("not found");debugger}}addPendingExpandCloner(e){this.toExpandCloner.add(e)}addPendingUpdateCloner(e){this.toUpdateCloner.add(e)}markToExpandCloner(e){this.toExpandCloner.add(e),e.traverseEntityAncestors(r=>{this.toExpandCloner.add(r)})}doPendingExpandCloner(){this.toExpandCloner.forEach(e=>{e.expandCloner(this)}),this.toExpandCloner.clear()}doPendingUpdateCloner(){this.toUpdateCloner.forEach(e=>{e.cloner?.update()}),this.toUpdateCloner.clear()}doPendingUpdates(){this.doPendingExpandCloner(),this.doPendingUpdateCloner(),this.applyPendingCommands()}addPendingCommand(e){this.pendingCommands.push(e)}applyPendingCommands(){this.pendingCommands.forEach(e=>e()),this.pendingCommands.length=0}updateByLibOp(e,r){e.path.length===1&&e.path[0]==="components"&&e.type===1&&this.createChildrenObjects([{...e.data.asset,id:e.id}],this.invisibleObjects,r)}updateTreeByOp(e,r){if(e.path.length===0&&e.type===7){let i=e.parent===null?this:this.find(e.parent);if(i===void 0)throw new Error("unexpected");let s=this.createObject(e.id,e.data,e.children,i,e.localIndex,r);s.updateVisible(this),s.resetBBoxNeedsUpdate(),cn(s)&&En(s.parent)&&(s.invalidateUpstreamBooleanData(),s.parent.invalidateDownstreamBooleanData().recomputeBoolean()),this.markNeedsRecomputeInstancesForAncessors(i),this.markNeedsRecomputeInstancesForChildren(s),this.markToExpandCloner(s),this.markPenumbraSizeDirty(),s.updatePathSnapping()}else if(e.path.length===0&&e.type===8){let i=this.find(e.id);if(i===void 0)throw new Error("unexpected");this.markToExpandCloner(i),i.resetBBoxNeedsUpdate(),this.unregisterObject(i);let s=i.parent;this.markNeedsRecomputeInstancesForAncessors(s),this.markNeedsRecomputeInstancesForChildren(i),this.markPenumbraSizeDirty(),i.parent.remove(i),En(i.parent)&&(i.parent.invalidateUpstreamBooleanData(),i.parent.invalidateDownstreamBooleanData().recomputeBoolean()),cn(i)&&(i.freeBooleanPointer(),s instanceof Fn&&s.invalidateDownstreamBooleanData().recomputeBoolean()),i instanceof rc&&i.detachShape(),this.disposeAndUnregisterEntityRecursivelyIfNotReregistered(i),this.pathConstraints.removeDependencies(i.uuid),i.updatePathSnapping()}else if(e.path.length===0&&e.type===9){let i=this.find(e.id);if(i===void 0)throw new Error("unexpected");this.markNeedsRecomputeInstancesForChildren(i);let s=i.parent;this.markNeedsRecomputeInstancesForAncessors(s),i.cloner?.resetOnMove(),this.markToExpandCloner(i);let o=e.parent===null?this:this.find(e.parent);if(o===void 0)throw new Error("unexpected");o.add(i),this.markNeedsRecomputeInstancesForAncessors(o),this.markToExpandCloner(i),i.invalidateClonerTransform(i),i.updateVisible(this),i.resetBBoxNeedsUpdate(),this.markPenumbraSizeDirty();let a=e.localIndex;o.children.splice(a,0,o.children.pop()),cn(i)&&(i.invalidateUpstreamBooleanData(),En(i.parent)?i.parent.invalidateDownstreamBooleanData().recomputeBoolean():s instanceof Fn&&s.invalidateDownstreamBooleanData().recomputeBoolean()),i.updatePathSnapping()}this.markNeedsUpdateRendererDirty(),this.markGeometryCacheDirty()}get playPage(){return this.find(this.data.publish.playPage)??this.errorPage}updatePage(e){this.activePage&&this.activePage.onDeactive(),this.activePage=this.errorPage;for(let r of this.children)r instanceof ur&&(r.visible=r.uuid===e,r.visible&&(this.activePage=r,this.activePage.onActive(this)));this.activePage!==this.splatViewer?.activePage&&this.reloadSplats()}updateEntityByOp(e,r,i,s){if(r.type===0){if(("overrides"in r.props||"component"in r.props)&&this.markNeedsRecomputeInstances(),"visible"in r.props&&this.markPenumbraSizeDirty(),r.path.includes("overrides")&&"states"in r.props){let{rest:a}=r.props;r={...r,props:a},this.markNeedsRecomputeInstances()}r.path[0]==="pathSnapping"&&r.props.pathId!==void 0&&this.pathConstraints.setConstraint(e,r.props.pathId)}let o=this.find(e);if(o)try{mB(o,r,i,{scene:this,shared:s}),o instanceof cr&&o.updateGeometryGroupsIfNeeded()}catch(a){console.error(a)}}updateEntity2DByOp(e,r,i,s,o,a=[]){e.updateEntityByOp(r,i,s,o),this.traverseEntity(l=>{(l instanceof Er||l instanceof ur)&&(a.includes(l.frameId??"")||l.frameId===r)&&l.updateEntity2DByOp(r,i,s,o)})}get activeCamera(){return this.activePage.activeCamera}switchActiveCamera(e){this.activePage.switchActiveCamera(e)}isInvisibleObjects(e){return e===this.invisibleObjects||e.hasAnccestor(this.invisibleObjects)}init(e,r){let i=Object.entries(r.data.lib.components).map((s,o)=>({data:s[1].asset.data,children:s[1].asset.children,id:s[0],fi:o}));this.invisibleObjects.updateState(this.invisibleObjects.data,{scene:this,shared:r}),this.add(this.invisibleObjects),this.createChildrenObjects(i,this.invisibleObjects,r),this.createChildrenObjects(e.objects,this,r),this.updatePage(e.publish.playPage),this.activePage.switchToPlayCamera(),this.expandInstances(r,!0),this.traverseEntity(s=>{s instanceof wr&&s.updateUp()}),this.doPendingExpandCloner(),this.applyPendingCommands()}markNeedsRecomputeInstances(){this.needsRecomputeInstances=!0}markNeedsRecomputeInstancesForChildren(e){e.traverseEntity(r=>{(r.data.type==="Component"||r.data.type==="Instance")&&this.markNeedsRecomputeInstances()})}markNeedsRecomputeInstancesForAncessors(e){yt.is(e)&&(e.data.type==="Component"&&this.markNeedsRecomputeInstances(),e.traverseAncestors(r=>{yt.is(r)&&r.data.type==="Component"&&this.markNeedsRecomputeInstances()}))}relativeizeInner(e,r,i,s,o,a,l){if(e){let c=s.find(e);c&&c!==s&&o.forInstancesRec(u=>{u.data=bl(u.data,h=>{let d=h.events.data(l.id),f=u.goUp(a);if(f){let p=[...dv(f.identity),e].join("-"),m=this.entityIdentityToEntity[p];if(m){let g=m.uuid,y=Sr.zoom(d,r);y[i]=g}else{if(!1)debugger;console.warn("cannot find instance")}}}).data})}}rewriteActions(e,r,i,s,o,a){e.forEach(l=>{l.data.type==="Transition"?this.relativeizeInner(l.data.object,[...r,l.id],"object",i,s,o,a):l.data.type==="Animation"?this.relativeizeInner(l.data.object,[...r,l.id],"object",i,s,o,a):l.data.type==="Conditional"&&(this.rewriteActions(l.data.ifActions,[...r,l.id,"ifActions"],i,s,o,a),this.rewriteActions(l.data.elseActions,[...r,l.id,"elseActions"],i,s,o,a))})}rewriteEventsBeforeGoToPlayMode(){this.traverseEntity(e=>{if(e instanceof eo&&typeof e.identity=="string"&&e.data.type==="Component")return e.traverseEntity((r,i)=>{r.data.events.forEach(s=>{if(s.data.type==="GameControl"){let o=!1;if(r.forInstancesRec(a=>{a.data=bl(a.data,l=>{a.isInstanceRoot||(l.events.delete(s.id),o=!0)}).data}),o===!1)for(let a of Jh.list)this.rewriteActions(s.data.gameActions[a],["gameActions",a],e,r,i,s)}else s.data.type==="Conditional"?(s.data.condition.type==="Distance"?(this.relativeizeInner(s.data.condition.fromObject,["condition"],"fromObject",e,r,i,s),this.relativeizeInner(s.data.condition.toObject,["condition"],"toObject",e,r,i,s)):s.data.condition.type==="State"?this.relativeizeInner(s.data.condition.object,["condition"],"object",e,r,i,s):s.data.condition.type==="Comparison"&&(s.data.condition.lOperand.type==="Property"&&this.relativeizeInner(s.data.condition.lOperand.value[0],["condition","lOperand","value"],0,e,r,i,s),s.data.condition.rOperand.type==="Property"&&this.relativeizeInner(s.data.condition.rOperand.value[0],["condition","rOperand","value"],0,e,r,i,s)),this.rewriteActions(s.data.inActions,["inActions"],e,r,i,s),this.rewriteActions(s.data.outActions,["outActions"],e,r,i,s)):"actions"in s.data&&this.rewriteActions(s.data.actions,["actions"],e,r,i,s)})}),!0})}expandInstances(e,r,i){let s=new Set;this.traverseEntity(o=>{if(o instanceof eo&&o.isInstanceRoot)return o.expandInstanceChildren({scene:this,shared:e,pendingDeletes:s}),r||o.resetBBoxNeedsUpdate(),i&&o.traverseEntity(a=>{i.addClip(a)}),!0});for(let o of s)this.disposeAndUnregisterEntityRecursivelyIfNotReregistered(o),eb(o)}recomputeInstances(e,r){this.needsRecomputeInstances&&(this.needsRecomputeInstances=!1,this.traverseEntity(i=>{i instanceof eo&&i.isInstanceRoot&&(i.component=void 0)}),this.expandInstances(e,!1,r))}disposeAndUnregisterEntityRecursivelyIfNotReregistered(e){e.traverseEntity(r=>{let i=typeof r.identity=="string"?r.identity:r.identity.join("-");this.entityIdentityToEntity[i]===r&&(delete this.entityByUuid[r.uuid],delete this.entityIdentityToEntity[i]),r.dispose()})}clearScene(){for(let e of this.children)yt.is(e)&&e.disposeRecursively();this.children.length=0}resetAfterClear(e,r){this.init(e,r)}raycast(e){return this.raycast1(e,!1)}raycast1(e,r){let i=[],s=o=>{for(let a of o.children){let l=a.cloner;if(yt.is(a)&&!a.raycastLock&&(a.visible||l?.object.data.visible))if(r===!0&&a.isInstanceRoot){let c=[];if(e.intersectObject(a,!0,c),c.length){let u=c[0];u.object=a,u.point.applyMatrix4(u.object.matrixWorld);let h=a.matrixWorld.clone().invert();u.point.applyMatrix4(h),i.push(u)}}else(cn(a)||Vm(a)&&this.enableHelpers&&a.objectHelper.visible)&&(e.intersectObject(a,!1,i),Ym(a,e,i)),s(a)}};return s(this.activePage),i}raycastWithClones(e){let r=[],i=s=>{for(let o of s.children){let a=o.cloner;yt.is(o)&&(o.visible||a?.object.data.visible)&&((cn(o)||Vm(o)&&this.enableHelpers&&o.objectHelper.visible)&&(e.intersectObject(o,!1,r),Ym(o,e,r,!0)),i(o))}};return i(this),r}forEachEntity(e){for(let r of this.children)yt.is(r)&&e(r)}traverseConcreteEntity(e){for(let r of this.children)yt.is(r)&&r.isConcreteEntity&&r.traverseEntity(e)}traverseEntity(e){for(let r of this.children)yt.is(r)&&r.traverseEntity(e)}updateFont(e,r){this.traverseEntity(i=>{if(i instanceof cr&&i.data.type==="Mesh"&&(i.data.geometry.type==="TextGeometry"||i.data.geometry.type==="InputGeometry")&&i.data.geometry.font===e){let s=i.geometry,o=i.data.geometry;s.updateFont(e,r).then(()=>{s.update(o);let a=i.invalidateDownstreamBooleanData();En(a)&&a.recomputeBoolean()})}})}traverseObject(e){for(let r of this.children)gd.is(r)&&r.traverseObject(e)}traverseVisibleEntity(e){for(let r of this.children)yt.is(r)&&r.visible&&r.traverseVisibleEntity(e)}dispose(){this.clearScene()}createChildrenObjects(e,r,i){let s=0;for(let o of e)this.createObject(o.id,o.data,o.children,r,s,i),s+=1}registerObjectCreatedInLegacy(e){this.entityByUuid[e.uuid]=e}unregisterObject(e){delete this.entityByUuid[e.uuid];for(let r of e.children)this.unregisterObject(r)}createObject(e,r,i,s,o,a){let l={scene:this,shared:a},c=ab(e,r,l);return c&&(this.entityByUuid[e]=c,s.add(c),s.children.splice(o,0,s.children.pop()),i.length>0&&(c.isInstanceRoot?console.error("instance should not have children!"):this.createChildrenObjects(i,c,a)),c.updateState(r,l),c instanceof cr&&c.updateGeometryGroupsIfNeeded(),c.updateVisible(this),c.cloner&&this.toExpandCloner.add(c),r.pathSnapping?.pathId&&this.pathConstraints.setConstraint(e,r.pathSnapping.pathId)),r.type==="Empty"&&r.animations&&c.traverseEntity(u=>{let h=u.dataPatched;if(u instanceof cr&&h.bones&&h.boneInverses){let d=h.bones.map(m=>this.find(m)),f=h.boneInverses.map(m=>new ue().fromArray(m)),p=new sl(d,f);u.bind(p,u.bindMatrix)}else u.matrixAutoUpdate=!0}),c}getCenter(e){let r=[];for(let s=0,o=e.length;s{if(r instanceof mr)if(Array.isArray(r.material))for(let i=0;i{s instanceof wr&&s.setViewplaneSize(e,r,i)})}initializeSplatViewer(){this.splatViewer=new Xm({scene:this}),this.reloadSplats()}reloadSplats(){this.splatViewer?.loadSplat()}};var Km=(n,t)=>{let e=t.x-n.x,r=t.y-n.y;return Math.sqrt(e*e+r*r)},CB=(n,t)=>{let e=t.x-n.x,r=t.y-n.y;return VZ(Math.atan2(r,e))},PB=(n,t,e)=>{let r={x:0,y:0};return e=fb(e),r.x=n.x-t*Math.cos(e),r.y=n.y-t*Math.sin(e),r},fb=n=>n*(Math.PI/180),VZ=n=>n*(180/Math.PI),_B=n=>isNaN(n.buttons)?n.pressure!==0:n.buttons!==0,ST=new Map,wT=n=>{ST.has(n)&&clearTimeout(ST.get(n)),ST.set(n,setTimeout(n,100))},Lf=(n,t,e)=>{let r=t.split(/[ ,]+/g),i;for(let s=0;s{let r=t.split(/[ ,]+/g),i;for(let s=0;s(n.preventDefault(),n.type.match(/^touch/)?n.changedTouches:n),ET=()=>{if(typeof window>"u")return;let n=window.pageXOffset!==void 0?window.pageXOffset:(document.documentElement||document.body.parentNode||document.body).scrollLeft,t=window.pageYOffset!==void 0?window.pageYOffset:(document.documentElement||document.body.parentNode||document.body).scrollTop;return{x:n,y:t}},mb=(n,t)=>{t.top||t.right||t.bottom||t.left?(n.style.top=t.top,n.style.right=t.right,n.style.bottom=t.bottom,n.style.left=t.left):(n.style.left=t.x+"px",n.style.top=t.y+"px")},gb=(n,t,e)=>{let r=DB(n);for(let i in r)if(r.hasOwnProperty(i))if(typeof t=="string")r[i]=t+" "+e;else{let s="";for(let o=0,a=t.length;o{let e=DB(n);for(let r in e)e.hasOwnProperty(r)&&(e[r]=t);return e},DB=n=>{let t={};return t[n]="",["webkit","Moz","o"].forEach(function(r){t[r+n.charAt(0).toUpperCase()+n.slice(1)]=""}),t},yb=(n,t)=>{for(let e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);return n},OB=(n,t)=>{let e={};for(let r in n)n.hasOwnProperty(r)&&t.hasOwnProperty(r)?e[r]=t[r]:n.hasOwnProperty(r)&&(e[r]=n[r]);return e},Qm=(n,t)=>{if(n.length)for(let e=0,r=n.length;e({x:Math.min(Math.max(n.x,t.x-e),t.x+e),y:Math.min(Math.max(n.y,t.y-e),t.y+e)});typeof window<"u"&&(LB="ontouchstart"in window,BB=!!window.PointerEvent,NB=!!window.MSPointerEvent);var LB,BB,NB,Zm={touch:{start:"touchstart",move:"touchmove",end:"touchend, touchcancel"},mouse:{start:"mousedown",move:"mousemove",end:"mouseup"},pointer:{start:"pointerdown",move:"pointermove",end:"pointerup, pointercancel"},MSPointer:{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}},Bf,Jm={};BB?Bf=Zm.pointer:NB?Bf=Zm.MSPointer:LB?(Bf=Zm.touch,Jm=Zm.mouse):Bf=Zm.mouse;function ou(){}ou.prototype.on=function(n,t){var e=this,r=n.split(/[ ,]+/g),i;e._handlers_=e._handlers_||{};for(var s=0;s=0&&e._handlers_[n].splice(e._handlers_[n].indexOf(t),1),e};ou.prototype.trigger=function(n,t){var e=this,r=n.split(/[ ,]+/g),i;e._handlers_=e._handlers_||{};for(var s=0;se&&t-e&&t<=e&&!n.lockY?i="left":t>-e*3&&t<=-e&&!n.lockX?i="down":n.lockY||(i="right"),n.lockY||(t>-r&&t0?o="up":o="down"),n.force>this.options.threshold){var a={},l;for(l in this.direction)this.direction.hasOwnProperty(l)&&(a[l]=this.direction[l]);var c={};this.direction={x:s,y:o,angle:i},n.direction=this.direction;for(l in a)a[l]===this.direction[l]&&(c[l]=!0);if(c.x&&c.y&&c.angle)return n;(!c.x||!c.y)&&this.trigger("plain",n),c.x||this.trigger("plain:"+s,n),c.y||this.trigger("plain:"+o,n),c.angle||this.trigger("dir dir:"+i,n)}else this.resetDirection();return n};var FB=Ii;function oi(n,t){var e=this;e.nipples=[],e.idles=[],e.actives=[],e.ids=[],e.pressureIntervals={},e.manager=n,e.id=oi.id,oi.id+=1,e.defaults={zone:document.body,multitouch:!1,maxNumberOfNipples:10,mode:"dynamic",position:{top:0,left:0},catchDistance:200,size:100,threshold:.1,color:"white",fadeTime:250,dataOnly:!1,restJoystick:!0,restOpacity:1,lockX:!1,lockY:!1,shape:"circle",dynamicPage:!1,follow:!1},e.config(t),(e.options.mode==="static"||e.options.mode==="semi")&&(e.options.multitouch=!1),e.options.multitouch||(e.options.maxNumberOfNipples=1);let r=getComputedStyle(e.options.zone.parentElement);return r&&r.display==="flex"&&(e.parentIsFlex=!0),e.updateBox(),e.prepareNipples(),e.bindings(),e.begin(),e.nipples}oi.prototype=new Nf;oi.constructor=oi;oi.id=0;oi.prototype.prepareNipples=function(){var n=this,t=n.nipples;t.on=n.on.bind(n),t.off=n.off.bind(n),t.options=n.options,t.destroy=n.destroy.bind(n),t.ids=n.ids,t.id=n.id,t.processOnMove=n.processOnMove.bind(n),t.processOnEnd=n.processOnEnd.bind(n),t.get=function(e){if(e===void 0)return t[0];for(var r=0,i=t.length;r0&&t.pressureFn(n,u,u.identifier),t.processOnMove(n)};if((r=t.idles.indexOf(a))>=0&&t.idles.splice(r,1),t.actives.push(a),t.ids.push(a.identifier),e.mode!=="semi")l(a);else{var c=Km(o,a.position);if(c<=e.catchDistance)l(a);else{a.destroy(),t.processOnStart(n);return}}return a};oi.prototype.getOrCreate=function(n,t){var e=this,r=e.options,i;return/(semi|static)/.test(r.mode)?(i=e.idles[0],i?(e.idles.splice(0,1),i):r.mode==="semi"?e.createNipple(t,n):(console.warn("Coudln't find the needed nipple."),!1)):(i=e.createNipple(t,n),i)};oi.prototype.processOnMove=function(n){var t=this,e=t.options,r=t.manager.getIdentifier(n),i=t.nipples.get(r),s=t.manager.scroll;if(!_B(n)){this.processOnEnd(n);return}if(!i){console.error("Found zombie joystick with ID "+r),t.manager.removeIdentifier(r);return}if(e.dynamicPage){var o=i.el.getBoundingClientRect();i.position={x:s.x+o.left,y:s.y+o.top}}i.identifier=r;var a=i.options.size/2,l={x:n.pageX,y:n.pageY};e.lockX&&(l.y=i.position.y),e.lockY&&(l.x=i.position.x);var c=Km(l,i.position),u=CB(l,i.position),h=fb(u),d=c/a,f={distance:c,position:l},p,m;if(i.options.shape==="circle"?(p=Math.min(c,a),m=PB(i.position,p,u)):(m=RB(l,i.position,a),p=Km(m,i.position)),e.follow){if(c>a){let x=l.x-m.x,S=l.y-m.y;i.position.x+=x,i.position.y+=S,i.el.style.top=i.position.y-(t.box.top+s.y)+"px",i.el.style.left=i.position.x-(t.box.left+s.x)+"px",c=Km(l,i.position)}}else l=m,c=p;var g=l.x-i.position.x,y=l.y-i.position.y;i.frontPosition={x:g,y},e.dataOnly||mb(i.ui.front,i.frontPosition);var v={identifier:i.identifier,position:l,force:d,pressure:n.force||n.pressure||n.webkitForce||0,distance:c,angle:{radian:h,degree:u},vector:{x:g/a,y:-y/a},raw:f,instance:i,lockX:e.lockX,lockY:e.lockY};v=i.computeDirection(v),v.angle={radian:fb(180-u),degree:180-u},i.trigger("move",v),t.trigger("move "+i.id+":move",v)};oi.prototype.processOnEnd=function(n){var t=this,e=t.options,r=t.manager.getIdentifier(n),i=t.nipples.get(r),s=t.manager.removeIdentifier(i.identifier);!i||(e.dataOnly||i.hide(function(){e.mode==="dynamic"&&(i.trigger("removed",i),t.trigger("removed "+i.id+":removed",i),t.manager.trigger("removed "+i.id+":removed",i),i.destroy())}),clearInterval(t.pressureIntervals[i.identifier]),i.resetDirection(),i.trigger("end",i),t.trigger("end "+i.id+":end",i),t.ids.indexOf(i.identifier)>=0&&t.ids.splice(t.ids.indexOf(i.identifier),1),t.actives.indexOf(i)>=0&&t.actives.splice(t.actives.indexOf(i),1),/(semi|static)/.test(e.mode)?t.idles.push(i):t.nipples.indexOf(i)>=0&&t.nipples.splice(t.nipples.indexOf(i),1),t.manager.unbindDocument(),/(semi|static)/.test(e.mode)&&(t.manager.ids[s.id]=s.identifier))};oi.prototype.onDestroyed=function(n,t){var e=this;e.nipples.indexOf(t)>=0&&e.nipples.splice(e.nipples.indexOf(t),1),e.actives.indexOf(t)>=0&&e.actives.splice(e.actives.indexOf(t),1),e.idles.indexOf(t)>=0&&e.idles.splice(e.idles.indexOf(t),1),e.ids.indexOf(t.identifier)>=0&&e.ids.splice(e.ids.indexOf(t.identifier),1),e.manager.removeIdentifier(t.identifier),e.manager.unbindDocument()};oi.prototype.destroy=function(){var n=this;n.unbindEvt(n.options.zone,"start"),n.nipples.forEach(function(e){e.destroy()});for(var t in n.pressureIntervals)n.pressureIntervals.hasOwnProperty(t)&&clearInterval(n.pressureIntervals[t]);n.trigger("destroyed",n.nipples),n.manager.unbindDocument(),n.off()};var VB=oi;function ji(n){var t=this;t.ids={},t.index=0,t.collections=[],t.scroll=ET(),t.config(n),t.prepareCollections();var e=function(){var i;t.collections.forEach(function(s){s.forEach(function(o){i=o.el.getBoundingClientRect(),o.position={x:t.scroll.x+i.left,y:t.scroll.y+i.top}})})};if(typeof window>"u")return t.collections;Lf(window,"resize",function(){wT(e)});var r=function(){t.scroll=ET()};return Lf(window,"scroll",function(){wT(r)}),t.collections}ji.prototype=new Nf;ji.constructor=ji;ji.prototype.prepareCollections=function(){var n=this;n.collections.create=n.create.bind(n),n.collections.on=n.on.bind(n),n.collections.off=n.off.bind(n),n.collections.destroy=n.destroy.bind(n),n.collections.get=function(t){var e;return n.collections.every(function(r){return e=r.get(t),!e}),e}};ji.prototype.create=function(n){return this.createCollection(n)};ji.prototype.createCollection=function(n){var t=this,e=new VB(t,n);return t.bindCollection(e),t.collections.push(e),e};ji.prototype.bindCollection=function(n){var t=this,e,r=function(i,s){e=i.type+" "+s.id+":"+i.type,t.trigger(e,s)};n.on("destroyed",t.onDestroyed.bind(t)),n.on("shown hidden rested dir plain",r),n.on("dir:up dir:right dir:down dir:left",r),n.on("plain:up plain:right plain:down plain:left",r)};ji.prototype.bindDocument=function(){var n=this;n.binded||(n.bindEvt(document,"move").bindEvt(document,"end"),n.binded=!0)};ji.prototype.unbindDocument=function(n){var t=this;(!Object.keys(t.ids).length||n===!0)&&(t.unbindEvt(document,"move").unbindEvt(document,"end"),t.binded=!1)};ji.prototype.getIdentifier=function(n){var t;return n?(t=n.identifier===void 0?n.pointerId:n.identifier,t===void 0&&(t=this.latest||0)):t=this.index,this.ids[t]===void 0&&(this.ids[t]=this.index,this.index+=1),this.latest=t,this.ids[t]};ji.prototype.removeIdentifier=function(n){var t={};for(var e in this.ids)if(this.ids[e]===n){t.id=e,t.identifier=this.ids[e],delete this.ids[e];break}return t};ji.prototype.onmove=function(n){var t=this;return t.onAny("move",n),!1};ji.prototype.onend=function(n){var t=this;return t.onAny("end",n),!1};ji.prototype.oncancel=function(n){var t=this;return t.onAny("end",n),!1};ji.prototype.onAny=function(n,t){var e=this,r,i="processOn"+n.charAt(0).toUpperCase()+n.slice(1);t=pb(t);var s=function(a,l,c){c.ids.indexOf(l)>=0&&(c[i](a),a._found_=!0)},o=function(a){r=e.getIdentifier(a),Qm(e.collections,s.bind(null,a,r)),a._found_||e.removeIdentifier(r)};return Qm(t,o),!1};ji.prototype.destroy=function(){var n=this;n.unbindDocument(!0),n.ids={},n.index=0,n.collections.forEach(function(t){t.destroy()}),n.off()};ji.prototype.onDestroyed=function(n,t){var e=this;if(e.collections.indexOf(t)<0)return!1;e.collections.splice(e.collections.indexOf(t),1)};var kB=ji;var UB=new kB,zB={create:function(n){return UB.create(n)},factory:UB};var GB=new Map,$m=new Map,Wo=class{constructor(t,e,r,i){this.data=e;let{audio:s,volume:o,delay:a,loop:l}=e;if(!s)throw new Error("Missing property");let c=typeof s=="string"?i.getAudio(s).src:s.data;this.audioPlayer=new Na({src:c,volume:o,delay:a,loop:l}),$m.has(r.uuid)?$m.get(r.uuid).push(this):$m.set(r.uuid,[this]),GB.set(t,this)}playByToggle(){this.data.toggle==="stop"?this.audioPlayer.status==="playing"?this.audioPlayer.stop():(this.audioPlayer.stop(),this.audioPlayer.play()):this.data.toggle==="pause"?this.audioPlayer.status==="playing"?this.audioPlayer.pause():this.audioPlayer.play():(this.audioPlayer.stop(),this.audioPlayer.play())}dispose(){this.audioPlayer.stop()}},Ff=class{constructor(t){this.data=t}dispatch(){this.data.playAudio?this.pauseAudio(this.data.playAudio):this.data.object?this.pauseAllAudiosFromObject(this.data.object):this.pauseAllAudios()}pauseAudio(t){let e=GB.get(t);!e||(this.data.delay>0?(this.disposeDelay(),this.timeoutId=window.setTimeout(()=>{e.audioPlayer[this.data.interaction](),this.disposeDelay()},this.data.delay)):e.audioPlayer[this.data.interaction]())}pauseAllAudiosFromObject(t){let e=$m.get(t);!e?.length||(this.data.delay>0?(this.disposeDelay(),this.timeoutId=window.setTimeout(()=>{e.forEach(r=>r.audioPlayer[this.data.interaction]()),this.disposeDelay()},this.data.delay)):e.forEach(r=>r.audioPlayer[this.data.interaction]()))}pauseAllAudios(){let t=[...$m.values()];!t.length||(this.data.delay>0?(this.disposeDelay(),this.timeoutId=window.setTimeout(()=>{t.forEach(e=>{e.forEach(r=>{r.audioPlayer[this.data.interaction]()})}),this.disposeDelay()},this.data.delay)):t.forEach(e=>{e.forEach(r=>{r.audioPlayer[this.data.interaction]()})}))}disposeDelay(){clearTimeout(this.timeoutId),delete this.timeoutId}dispose(){clearTimeout(this.timeoutId),delete this.timeoutId}},eg=class{constructor(t,e,r,i,s){this.data=e;this.shared=i;this.condition=s;if(e.interaction==="play")this.interaction=new Wo(t,e,r,i);else if(e.interaction==="pause"||e.interaction==="stop")this.interaction=new Ff(e);else throw new Error("Missing property")}dispatchBasic(){if(wt(this.shared,this.condition)===!1)return!1;this.interaction instanceof Wo?this.interaction.playByToggle():this.interaction.dispatch()}dispatchConditional(){if(wt(this.shared,this.condition)===!1)return!1;this.interaction instanceof Wo?this.interaction.audioPlayer.play():this.interaction.dispatch()}dispatchGameControl(t){if(wt(this.shared,this.condition)===!1)return!1;this.interaction instanceof Wo&&(t==="start"?this.interaction.audioPlayer.play():this.interaction.audioPlayer.stop())}dispose(){this.interaction.dispose()}};var tg=class{constructor(t,e,r,i){this.data=t;this.page=e;this.shared=r;this.condition=i;this.delay=0;this.emission=t.emission,t.delay!==void 0&&(this.delay=t.delay),this.particleSystem=this.page.scene.find(this.data.emitterObjectId)}toggleEmitting(){this.particleSystem.started&&!this.particleSystem.stopped?this.stop(this.delay):this.start(this.delay)}toggleFroze(){this.particleSystem.started&&!this.particleSystem.isFrozen?this.freeze(this.delay):this.unFreeze(this.delay)}start(t=0){if(t){this.delayTimerId=window.setTimeout(()=>{this.start(0),this.clearDelay()},t);return}this.particleSystem.start()}stop(t=0){if(t){this.delayTimerId=window.setTimeout(()=>{this.stop(0),this.clearDelay()},t);return}this.particleSystem.stop()}freeze(t=0){if(t){this.delayTimerId=window.setTimeout(()=>{this.freeze(0),this.clearDelay()},t);return}this.particleSystem.froze()}unFreeze(t=0){if(t){this.delayTimerId=window.setTimeout(()=>{this.unFreeze(0),this.clearDelay()},t);return}this.particleSystem.unFroze()}reset(t=0){if(t){this.delayTimerId=window.setTimeout(()=>{this.reset(0),this.clearDelay()},t);return}this.particleSystem.reset()}reverseFromCurrent(){switch(this.emission){case"emitToggle":this.toggleEmitting();break;case"pauseToggle":this.toggleFroze();break}}dispatchBasic(){if(wt(this.shared,this.condition)===!1||!this.particleSystem)return!1;switch(this.emission){case"start":this.start(this.delay);break;case"emitToggle":this.toggleEmitting();break;case"pause":this.freeze(this.delay);break;case"pauseToggle":this.toggleFroze();break;case"stop":this.stop(this.delay);break;case"reset":this.reset(this.delay);break;default:break}}dispatchConditional(){if(wt(this.shared,this.condition)===!1||!this.particleSystem)return!1;switch(this.emission){case"start":this.start(this.delay);break;case"stop":this.stop(this.delay);break;case"reset":this.reset(this.delay);break;default:break}}dispatchGameControl(t){if(wt(this.shared,this.condition)===!1||!this.particleSystem)return!1;t==="start"?this.start(this.delay):this.stop(this.delay)}dispose(){!this.particleSystem||(this.particleSystem.reset(),this.clearDelay())}clearDelay(){this.delayTimerId&&(clearTimeout(this.delayTimerId),delete this.delayTimerId)}};var kZ="text/plain",UZ="us-ascii",jB=(n,t)=>t.some(e=>e instanceof RegExp?e.test(n):e===n),zZ=(n,{stripHash:t})=>{let e=/^data:(?[^,]*?),(?[^#]*?)(?:#(?.*))?$/.exec(n);if(!e)throw new Error(`Invalid URL: ${n}`);let{type:r,data:i,hash:s}=e.groups,o=r.split(";");s=t?"":s;let a=!1;o[o.length-1]==="base64"&&(o.pop(),a=!0);let l=(o.shift()||"").toLowerCase(),u=[...o.map(h=>{let[d,f=""]=h.split("=").map(p=>p.trim());return d==="charset"&&(f=f.toLowerCase(),f===UZ)?"":`${d}${f?`=${f}`:""}`}).filter(Boolean)];return a&&u.push("base64"),(u.length>0||l&&l!==kZ)&&u.unshift(l),`data:${u.join(";")},${a?i.trim():i}${s?`#${s}`:""}`};function TT(n,t){if(t={defaultProtocol:"http:",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...t},n=n.trim(),/^data:/i.test(n))return zZ(n,t);if(/^view-source:/i.test(n))throw new Error("`view-source:` is not supported as it is a non-standard protocol");let e=n.startsWith("//");!e&&/^\.*\//.test(n)||(n=n.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,t.defaultProtocol));let i=new URL(n);if(t.forceHttp&&t.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(t.forceHttp&&i.protocol==="https:"&&(i.protocol="http:"),t.forceHttps&&i.protocol==="http:"&&(i.protocol="https:"),t.stripAuthentication&&(i.username="",i.password=""),t.stripHash?i.hash="":t.stripTextFragment&&(i.hash=i.hash.replace(/#?:~:text.*?$/i,"")),i.pathname){let o=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g,a=0,l="";for(;;){let u=o.exec(i.pathname);if(!u)break;let h=u[0],d=u.index,f=i.pathname.slice(a,d);l+=f.replace(/\/{2,}/g,"/"),l+=h,a=d+h.length}let c=i.pathname.slice(a,i.pathname.length);l+=c.replace(/\/{2,}/g,"/"),i.pathname=l}if(i.pathname)try{i.pathname=decodeURI(i.pathname)}catch{}if(t.removeDirectoryIndex===!0&&(t.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(t.removeDirectoryIndex)&&t.removeDirectoryIndex.length>0){let o=i.pathname.split("/"),a=o[o.length-1];jB(a,t.removeDirectoryIndex)&&(o=o.slice(0,-1),i.pathname=o.slice(1).join("/")+"/")}if(i.hostname&&(i.hostname=i.hostname.replace(/\.$/,""),t.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(i.hostname)&&(i.hostname=i.hostname.replace(/^www\./,""))),Array.isArray(t.removeQueryParameters))for(let o of[...i.searchParams.keys()])jB(o,t.removeQueryParameters)&&i.searchParams.delete(o);if(t.removeQueryParameters===!0&&(i.search=""),t.sortQueryParameters){i.searchParams.sort();try{i.search=decodeURIComponent(i.search)}catch{}}t.removeTrailingSlash&&(i.pathname=i.pathname.replace(/\/$/,""));let s=n;return n=i.toString(),!t.removeSingleSlash&&i.pathname==="/"&&!s.endsWith("/")&&i.hash===""&&(n=n.replace(/\/$/,"")),(t.removeTrailingSlash||i.pathname==="/")&&i.hash===""&&t.removeSingleSlash&&(n=n.replace(/\/$/,"")),e&&!t.normalizeProtocol&&(n=n.replace(/^http:\/\//,"//")),t.stripProtocol&&(n=n.replace(/^(?:https?:)?\/\//,"")),n}var xb=class{constructor({url:t,context:e},r,i,s){this.controlsManager=r;this.shared=i;this.condition=s;if(!t)throw new Error("Missing property");this.url=t.startsWith("mailto:")?t:TT(t,{removeTrailingSlash:!1,removeSingleSlash:!1,stripWWW:!1}),this.context=e??"tab"}dispatch(){if(wt(this.shared,this.condition)===!1)return!1;xo?window.location.assign(this.url):(this.context==="tab"||dA&&this.context==="none"?window.open(this.url,"_blank"):this.context==="window"?window.open(this.url,"_blank",`width=${window.innerWidth}, height=${window.innerHeight}`):window.open(this.url,"_parent"),this.controlsManager.orbitControls?.onPointerUp(Je[0]),aI())}};var rg=class{constructor(t,e,r,i,s){this.data=t;this.page=e;this.controlsManager=r;this.shared=i;this.condition=s;this.timeoutIdQueue=[];this.dispatchInner=()=>{this.objects.forEach(this.destroyCallback)};this.destroyCallback=t=>{this.timeoutIdQueue.shift();let e=this.page.scene.find(t);if(e===void 0)return;let r=this.controlsManager.sharedGameControlGlobals.rapierWorld,i=r?e.dataPatched.physics?.fusedBody:!0;if(e.cloner){for(let s of e.cloner.children)i?(s.playModeVisible=!1,s.rigidBody&&e.dataPatched.physics?.rigidBody==="positioned"&&(this.controlsManager.sharedGameControlGlobals.colliderToEntity.delete(s.rigidBody.collider(0).handle),r.removeRigidBody(s.rigidBody),s.rigidBody=void 0),s.bvhGeometry&&(s.bvhGeometry=void 0)):this.clone===void 0||this.clone===s?(s.playModeVisible=!1,s.rigidBody&&(this.controlsManager.sharedGameControlGlobals.colliderToEntity.delete(s.rigidBody.collider(0).handle),r.removeRigidBody(s.rigidBody),s.rigidBody=void 0)):s.playModeVisible===void 0&&(s.playModeVisible=!0);(i||this.clone===void 0||this.clone===!1)&&(e.visible=!1,e.rigidBody&&(this.controlsManager.sharedGameControlGlobals.colliderToEntity.delete(e.rigidBody.collider(0).handle),r.removeRigidBody(e.rigidBody),e.rigidBody=void 0),e.bvhGeometry&&(e.bvhGeometry=void 0))}else e.rigidBody&&(this.controlsManager.sharedGameControlGlobals.colliderToEntity.delete(e.rigidBody.collider(0).handle),r.removeRigidBody(e.rigidBody),e.rigidBody=void 0),e.bvhGeometry&&(e.bvhGeometry=void 0),e.visible=!1;r===void 0?this.controlsManager.sharedGameControlGlobals.entitiesWithTransformAnim=this.controlsManager.sharedGameControlGlobals.entitiesWithTransformAnim.filter(s=>s.bvhGeometry!==void 0):this.controlsManager.sharedGameControlGlobals.entitiesWithTransformAnim=this.controlsManager.sharedGameControlGlobals.entitiesWithTransformAnim.filter(s=>s.rigidBody!==void 0),e.destroyedInAction=!0,this.controlsManager.requestRender()};this.objects=[...t.objects]}dispatch(t){if(wt(this.shared,this.condition)===!1)return!1;this.clone=t,this.data.delay?this.timeoutIdQueue.push(window.setTimeout(this.dispatchInner,this.data.delay*1e3)):this.dispatchInner()}dispatchFromStart(){if(wt(this.shared,this.condition)===!1)return!1;this.timeoutIdQueue.push(window.setTimeout(this.dispatchInner,this.data.delay*1e3))}dispose(){this.timeoutIdQueue.forEach(t=>window.clearTimeout(t))}};var ig=class{constructor(t,e,r,i,s){this.data=t;this.page=e;this.shared=r;this.eventManager=i;this.condition=s;this.shared=r}dispatch(){if(wt(this.shared,this.condition)===!1)return!1;clearTimeout(this.timeoutId),delete this.timeoutId,this.timeoutId=window.setTimeout(()=>{this.shared.reset(this.shared.data,!0),Vf(this.page,this.shared,!0),this.eventManager.reset(),this.eventManager.controlsManager.gameControl?.reset(!0),this.page.switchToPlayCamera(),this.eventManager.controlsManager.requestRender(),delete this.timeoutId},(this.data.delay??0)*1e3)}dispose(){clearTimeout(this.timeoutId),delete this.timeoutId}};var KB={update:null,begin:null,loopBegin:null,changeBegin:null,change:null,changeComplete:null,timelineChangeComplete:null,loopComplete:null,complete:null,loop:1,direction:"normal",autoplay:!0,timelineOffset:0,rewind:!0},_T={duration:1e3,delay:0,endDelay:0,startOnceDelay:0,pingPongDelayCorrection:0,pingPongEndDelayCorrection:0,easing:"easeOutElastic(1, .5)",round:0},GZ=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],Sb={CSS:{},springs:{}};function to(n,t,e){return Math.min(Math.max(n,t),e)}function ng(n,t){return n.indexOf(t)>-1}function MT(n,t){return n.apply(null,t)}var ht={arr:function(n){return Array.isArray(n)},obj:function(n){return ng(Object.prototype.toString.call(n),"Object")},pth:function(n){return ht.obj(n)&&n.hasOwnProperty("totalLength")},svg:function(n){return n instanceof SVGElement},inp:function(n){return n instanceof HTMLInputElement},dom:function(n){return!("isNode"in n)&&(n.nodeType||ht.svg(n))},str:function(n){return typeof n=="string"},fnc:function(n){return typeof n=="function"},und:function(n){return typeof n>"u"},hex:function(n){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(n)},rgb:function(n){return/^rgb/.test(n)},hsl:function(n){return/^hsl/.test(n)},col:function(n){return ht.hex(n)||ht.rgb(n)||ht.hsl(n)},key:function(n){return!KB.hasOwnProperty(n)&&!_T.hasOwnProperty(n)&&n!=="targets"&&n!=="keyframes"}};function QB(n){var t=/\(([^)]+)\)/.exec(n);return t?t[1].split(",").map(function(e){return parseFloat(e)}):[]}function ZB(n,t){var e=QB(n),r=to(ht.und(e[0])?1:e[0],.1,100),i=to(ht.und(e[1])?100:e[1],.1,100),s=to(ht.und(e[2])?10:e[2],.1,100),o=to(ht.und(e[3])?0:e[3],.1,100),a=Math.sqrt(i/r),l=s/(2*Math.sqrt(i*r)),c=l<1?a*Math.sqrt(1-l*l):0,u=1,h=l<1?(l*a+-o)/c:-o+a;function d(p){var m=t?t*p/1e3:p;return l<1?m=Math.exp(-m*l*a)*(u*Math.cos(c*m)+h*Math.sin(c*m)):m=(u+h*m)*Math.exp(-m*a),p===0||p===1?p:1-m}function f(){var p=Sb.springs[n];if(p)return p;for(var m=1/6,g=0,y=0;;)if(g+=m,d(g)===1){if(y++,y>=16)break}else y=0;var v=g*m*1e3;return Sb.springs[n]=v,v}return t?d:f}function jZ(n){return n===void 0&&(n=10),function(t){return Math.ceil(to(t,1e-6,1)*n)*(1/n)}}var HZ=function(){var n=11,t=1/(n-1);function e(u,h){return 1-3*h+3*u}function r(u,h){return 3*h-6*u}function i(u){return 3*u}function s(u,h,d){return((e(h,d)*u+r(h,d))*u+i(h))*u}function o(u,h,d){return 3*e(h,d)*u*u+2*r(h,d)*u+i(h)}function a(u,h,d,f,p){var m,g,y=0;do g=h+(d-h)/2,m=s(g,f,p)-u,m>0?d=g:h=g;while(Math.abs(m)>1e-7&&++y<10);return g}function l(u,h,d,f){for(var p=0;p<4;++p){var m=o(h,d,f);if(m===0)return h;var g=s(h,d,f)-u;h-=g/m}return h}function c(u,h,d,f){if(!(0<=u&&u<=1&&0<=d&&d<=1))return;var p=new Float32Array(n);if(u!==h||d!==f)for(var m=0;m=.001?l(y,A,u,d):T===0?A:a(y,v,v+t,u,d)}return function(y){return u===h&&d===f||y===0||y===1?y:s(g(y),h,f)}}return c}(),JB=function(){var n={linear:function(){return function(r){return r}}},t={Sine:function(){return function(r){return 1-Math.cos(r*Math.PI/2)}},Circ:function(){return function(r){return 1-Math.sqrt(1-r*r)}},Back:function(){return function(r){return r*r*(3*r-2)}},Bounce:function(){return function(r){for(var i,s=4;r<((i=Math.pow(2,--s))-1)/11;);return 1/Math.pow(4,3-s)-7.5625*Math.pow((i*3-2)/22-r,2)}},Elastic:function(r,i){r===void 0&&(r=1),i===void 0&&(i=.5);var s=to(r,1,10),o=to(i,.1,2);return function(a){return a===0||a===1?a:-s*Math.pow(2,10*(a-1))*Math.sin((a-1-o/(Math.PI*2)*Math.asin(1/s))*(Math.PI*2)/o)}}},e=["Quad","Cubic","Quart","Quint","Expo"];return e.forEach(function(r,i){t[r]=function(){return function(s){return Math.pow(s,i+2)}}}),Object.keys(t).forEach(function(r){var i=t[r];n["easeIn"+r]=i,n["easeOut"+r]=function(s,o){return function(a){return 1-i(s,o)(1-a)}},n["easeInOut"+r]=function(s,o){return function(a){return a<.5?i(s,o)(a*2)/2:1-i(s,o)(a*-2+2)/2}}}),n}();function IT(n,t){if(ht.fnc(n))return n;var e=n.split("(")[0],r=JB[e],i=QB(n);switch(e){case"spring":return ZB(n,t);case"cubicBezier":return MT(HZ,i);case"steps":return MT(jZ,i);default:return MT(r,i)}}function $B(n){try{var t=document.querySelectorAll(n);return t}catch{return}}function wb(n,t){for(var e=n.length,r=arguments.length>=2?arguments[1]:void 0,i=[],s=0;s1&&(p-=1),p<1/6?d+(f-d)*6*p:p<1/2?f:p<2/3?d+(f-d)*(2/3-p)*6:d}var a,l,c;if(r==0)a=l=c=i;else{var u=i<.5?i*(1+r):i+r-i*r,h=2*i-u;a=o(h,u,e+1/3),l=o(h,u,e),c=o(h,u,e-1/3)}return"rgba("+a*255+","+l*255+","+c*255+","+s+")"}function XZ(n){if(ht.rgb(n))return WZ(n);if(ht.hex(n))return qZ(n);if(ht.hsl(n))return YZ(n)}function Ga(n){var t=/[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(n);if(t)return t[1]}function KZ(n){if(ng(n,"translate")||n==="perspective")return"px";if(ng(n,"rotate")||ng(n,"skew"))return"deg"}function PT(n,t){return ht.fnc(n)?n(t.target,t.id,t.total):n}function qo(n,t){return n.getAttribute(t)}function RT(n,t,e){var r=Ga(t);if(DT([e,"deg","rad","turn"],r))return t;var i=Sb.CSS[t+e];if(!ht.und(i))return i;var s=100,o=document.createElement(n.tagName),a=n.parentNode&&n.parentNode!==document?n.parentNode:document.body;a.appendChild(o),o.style.position="absolute",o.style.width=s+e;var l=s/o.offsetWidth;a.removeChild(o);var c=l*parseFloat(t);return Sb.CSS[t+e]=c,c}function eN(n,t,e){if(t in n.style){var r=t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),i=n.style[t]||getComputedStyle(n).getPropertyValue(r)||"0";return e?RT(n,i,e):i}}function LT(n,t){if(ht.dom(n)&&!ht.inp(n)&&(qo(n,t)||ht.svg(n)&&n[t]))return"attribute";if(ht.dom(n)&&DT(GZ,t))return"transform";if(ht.dom(n)&&t!=="transform"&&eN(n,t))return"css";if(n[t]!=null)return"object"}function tN(n){if(!!ht.dom(n)){for(var t=n.style.transform||"",e=/(\w+)\(([^)]*)\)/g,r=new Map,i;i=e.exec(t);)r.set(i[1],i[2]);return r}}function QZ(n,t,e,r){var i=ng(t,"scale")?1:0+KZ(t),s=tN(n).get(t)||i;return e&&(e.transforms.list.set(t,s),e.transforms.last=t),r?RT(n,s,r):s}function BT(n,t,e,r){switch(LT(n,t)){case"transform":return QZ(n,t,r,e);case"css":return eN(n,t,e);case"attribute":return qo(n,t);default:return n[t]||0}}function NT(n,t){var e=/^(\*=|\+=|-=)/.exec(n);if(!e)return n;var r=Ga(n)||0,i=parseFloat(t),s=parseFloat(n.replace(e[0],""));switch(e[0][0]){case"+":return i+s+r;case"-":return i-s+r;case"*":return i*s+r}}function rN(n,t){if(ht.col(n))return XZ(n);if(/\s/g.test(n))return n;var e=Ga(n),r=e?n.substr(0,n.length-e.length):n;return t?r+t:r}function FT(n,t){return Math.sqrt(Math.pow(t.x-n.x,2)+Math.pow(t.y-n.y,2))}function ZZ(n){return Math.PI*2*qo(n,"r")}function JZ(n){return qo(n,"width")*2+qo(n,"height")*2}function $Z(n){return FT({x:qo(n,"x1"),y:qo(n,"y1")},{x:qo(n,"x2"),y:qo(n,"y2")})}function iN(n){for(var t=n.points,e=0,r,i=0;i0&&(e+=FT(r,s)),r=s}return e}function eJ(n){var t=n.points;return iN(n)+FT(t.getItem(t.numberOfItems-1),t.getItem(0))}function nN(n){if(n.getTotalLength)return n.getTotalLength();switch(n.tagName.toLowerCase()){case"circle":return ZZ(n);case"rect":return JZ(n);case"line":return $Z(n);case"polyline":return iN(n);case"polygon":return eJ(n)}}function tJ(n){var t=nN(n);return n.setAttribute("stroke-dasharray",t),t}function rJ(n){for(var t=n.parentNode;ht.svg(t)&&ht.svg(t.parentNode);)t=t.parentNode;return t}function sN(n,t){var e=t||{},r=e.el||rJ(n),i=r.getBoundingClientRect(),s=qo(r,"viewBox"),o=i.width,a=i.height,l=e.viewBox||(s?s.split(" "):[0,0,o,a]);return{el:r,viewBox:l,x:l[0]/1,y:l[1]/1,w:o/l[2],h:a/l[3]}}function iJ(n,t){var e=ht.str(n)?$B(n)[0]:n,r=t||100;return function(i){return{property:i,el:e,svg:sN(e),totalLength:nN(e)*(r/100)}}}function nJ(n,t){function e(a){a===void 0&&(a=0);var l=t+a>=1?t+a:0;return n.el.getPointAtLength(l)}var r=sN(n.el,n.svg),i=e(),s=e(-1),o=e(1);switch(n.property){case"x":return(i.x-r.x)*r.w;case"y":return(i.y-r.y)*r.h;case"angle":return Math.atan2(o.y-s.y,o.x-s.x)*180/Math.PI}}function WB(n,t){var e=/[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g,r=rN(ht.pth(n)?n.totalLength:n,t)+"";return{original:r,numbers:r.match(e)?r.match(e).map(Number):[0],strings:ht.str(n)||t?r.split(e):[]}}function oN(n){var t=n?Ab(ht.arr(n)?n.map(HB):HB(n)):[];return wb(t,function(e,r,i){return i.indexOf(e)===r})}function aN(n){var t=oN(n);return t.map(function(e,r){return{target:e,id:r,total:t.length,transforms:{list:tN(e)}}})}function sJ(n,t){var e=OT(t);if(/^spring/.test(e.easing)&&(e.duration=ZB(e.easing)),ht.arr(n)){var r=n.length,i=r===2&&!ht.obj(n[0]);i?n={value:n}:ht.fnc(t.duration)||(e.duration=t.duration/r)}var s=ht.arr(n)?n:[n];return s.map(function(o,a){var l=ht.obj(o)&&!ht.pth(o)?o:{value:o};return ht.und(l.delay)&&(l.delay=a?0:t.delay),ht.und(l.endDelay)&&(l.endDelay=a===s.length-1?t.endDelay:0),l}).map(function(o){return Eb(o,e)})}function oJ(n){for(var t=wb(Ab(n.map(function(s){return Object.keys(s)})),function(s){return ht.key(s)}).reduce(function(s,o){return s.indexOf(o)<0&&s.push(o),s},[]),e={},r=function(s){var o=t[s];e[o]=n.map(function(a){var l={};for(var c in a)ht.key(c)?c==o&&(l.value=a[c]):l[c]=a[c];return l})},i=0;i2||(Z=Math.round(Z*H)/H)),W.push(Z)}var te=V.length;if(!te)Q=W[0];else{Q=V[0];for(var $=0;$=0&&(c.began=!0,v("begin")),!c.loopBegan&&c.currentTime>0&&(c.loopBegan=!0,v("loopBegin")),(c.reversed||I>=0)&&I<=C&&c.currentTime!==0&&(y(0),v("change")),(I>=P&&c.currentTime!==M+c.pingPongDelayCorrection||!M)&&(y(M),v("change")),I>C&&IP&&v("changeComplete"),c.currentTime=to(I,0,M+c.pingPongDelayCorrection),c.began&&v("update"),T>=M)if(x(),!c.remaining)c.paused=!0,c.completed||(c.completed=!0,v("loopComplete"),v("complete"),!c.passThrough&&"Promise"in window&&(a(),u=l(c)));else{o?t+=c.duration/ai.speed:t+=c.duration;for(let _ of s)_.setStartTime(0),_.remaining=_.loop;v("loopComplete"),c.loopBegan=!1,c.direction==="alternate"?h():o&&d()}}return c.reset=function(){var T=c.direction;c.passThrough=!1,c.currentTime=0,c.progress=0,c.paused=!0,c.began=!1,c.loopBegan=!1,c.changeBegan=!1,c.completed=!1,c.changeCompleted=!1,c.reversePlayback=!1,c.reversed=T==="reverse",c.remaining=c.loop,s=c.children,o=s.length;for(var b=o;b--;)c.children[b].reset();y(c.reversed?c.duration:0)},c.setStartTime=function(T){t=T},c.set=function(T,b){return cN(T,b),c},c.tick=function(T){r=T,t||(t=r),A((r+(e-t))*ai.speed)},c.seek=function(T,b=!1){A(T-t,b)},c.pause=function(T){c.paused=!0,o&&(i=T??performance.now())},c.play=function(T){!c.paused||(c.completed&&c.reset(),c.paused=!1,Ts.push(c),o&&i!==void 0&&(t+=(T??performance.now())-i),bb||fJ())},c.reverse=function(){h(),c.completed=!c.reversed,p()},c.restart=function(){c.reset(),c.play()},c.reset(),c.autoplay&&c.play(),c}function XB(n,t){for(var e=t.length;e--;)DT(n,t[e].animatable.target)&&t.splice(e,1)}function mJ(n){for(var t=oN(n),e=Ts.length;e--;){var r=Ts[e],i=r.animations,s=r.children;XB(t,i);for(var o=s.length;o--;){var a=s[o],l=a.animations;XB(t,l),!l.length&&!a.children.length&&s.splice(o,1)}!i.length&&!s.length&&r.pause()}}function gJ(n,t){t===void 0&&(t={});var e=t.direction||"normal",r=t.easing?IT(t.easing):null,i=t.grid,s=t.axis,o=t.from||0,a=o==="first",l=o==="center",c=o==="last",u=ht.arr(n),h=parseFloat(u?n[0]:n),d=u?parseFloat(n[1]):0,f=Ga(u?n[1]:n)||0,p=t.start||0+(u?h:0),m=[],g=0;return function(y,v,x){if(a&&(o=0),l&&(o=(x-1)/2),c&&(o=x-1),!m.length){for(var S=0;S-1&&Ts.splice(i,1);function o(d){d.passThrough=!0}for(var a=0;a=1)return e.copy(n);let s=1-i*i;if(s<=Number.EPSILON){let u=1-r;return e.w=u*n.w+r*t.w,e.x=u*n.x+r*t.x,e.y=u*n.y+r*t.y,e.z=u*n.z+r*t.z,e.normalize(),e}let o=Math.sqrt(s),a=Math.atan2(o,i),l=Math.sin((1-r)*a)/o,c=Math.sin(r*a)/o;return e.w=n.w*l+t.w*c,e.x=n.x*l+t.x*c,e.y=n.y*l+t.y*c,e.z=n.z*l+t.z*c,e}function Zr(n,t,e,r,i,s){let o=e[n]!==void 0?e[n]:void 0,a=r[n];if(a==null)return;let l=o!=null?typeof o=="string"?Number(i.getVariable(o)??0):o:t[n],c=typeof a=="string"?Number(i.getVariable(a)??0):a;if(l!==c)return{update:u=>{let h=we.lerp(l,c,u);s?t[n]=Math.trunc(h):t[n]=h},start:()=>{t[n]=l},end:()=>{t[n]=c}}}function og(n,t,e,r,i,s){let o=e[n]?e[n]:void 0,a=r[n];if(!a)return;let l=t[n],c=[...o??l].map(h=>typeof h=="string"?Number(i.getVariable(h)??0):h),u=[...a].map(h=>typeof h=="string"?Number(i.getVariable(h)??0):h);if(!(c.length!==u.length||Rc(c,u)))return{update:h=>{c.forEach((d,f)=>{let p=we.lerp(d,u[f],h);t[n][f]=s?Math.trunc(p):p})},start:()=>{Object.assign(t[n],c)},end:()=>{Object.assign(t[n],u)}}}function sg(n,t,e){return t.forEach((r,i)=>{n.setComponent(i,typeof r=="string"?Number(e.getVariable(r)??0):r)}),n}function VT(n,t,e,r,i){let s=e[n]?e[n]:void 0,o=r[n];if(!o)return;let a=t[n],l=s?sg(new E,s,i):a.clone(),c=sg(new E,o,i);if(!l.equals(c))return{update:u=>{a.lerpVectors(l,c,u)},start:()=>{a.copy(l)},end:()=>{a.copy(c)}}}function pN(n,t,e){return t.forEach((r,i)=>{n.setComponent(i,typeof r=="string"?Number(e.getVariable(r)??0):r)}),n}function kf(n,t,e,r,i){let s=e[n]?e[n]:void 0,o=r[n];if(!o)return;let a=t[n],l=!(a instanceof k),c=a instanceof k?a:new k().fromArray(a),u=s?pN(new k,s,i):c.clone(),h=pN(new k,o,i);if(!u.equals(h))return{update:d=>{c.lerpVectors(u,h,d),l&&(t[n]=c.toArray())},start:()=>{c.copy(u),l&&(t[n]=c.toArray())},end:()=>{c.copy(h),l&&(t[n]=c.toArray())}}}function gN(n,t,e,r){let i=e[n]?e[n]:void 0,s=r[n];if(!s)return;let o=t[n],a=i?new ue().fromArray(i):o.clone(),l=new E,c=new Ke,u=new E;a.decompose(l,c,u);let h=new ue().fromArray(s),d=new E,f=new Ke,p=new E;if(h.decompose(d,f,p),!a.equals(h))return{update:m=>{fN.slerpQuaternions(c,f,m),hN.lerpVectors(l,d,m),dN.lerpVectors(u,p,m),o.compose(hN,fN,dN)},start:()=>{o.compose(l,c,u)},end:()=>{o.compose(d,f,p)}}}function yN(n,t,e,r,i){let s=e[n]?e[n]:void 0,o=r[n];if(!o)return;let a=t[n],l=s?typeof s=="string"?i.getColor(s).clone():new We().setRGB(s.r,s.g,s.b):a.clone(),c=typeof o=="string"?i.getColor(o).clone():new We().setRGB(o.r,o.g,o.b);if(l.equals(c))return;let u=a.clone();return{update:h=>{u.lerpColors(l,c,h),t[n]?.copy?.(u)},start:()=>{u.copy(l)},end:()=>{u.copy(c)}}}function ag(n,t,e,r,i){let s=e[n]?e[n]:void 0,o=r[n];if(!o)return;let a=t[n],l=new vr(a.r,a.g,a.b,a.a),c=s?typeof s=="string"?i.getColor(s).clone():new vr(s.r,s.g,s.b,s.a):l.clone(),u=typeof o=="string"?i.getColor(o).clone():new vr(o.r,o.g,o.b,o.a);if(!c.equals(u))return{update:h=>{l.lerpColors(c,u,h);let d=we.lerp(c.a,u.a,h);l.a=d,t[n]={r:l.r,g:l.g,b:l.b,a:l.a}},start:()=>{l.copy(c)},end:()=>{l.copy(u)}}}function Yo(n,t,e,r,i){if(typeof t[n]=="number")return Zr(n,t,e??{},r,i);if(Array.isArray(t[n]))return og(n,t,e??{},r,i)}function vN(n,t,e,r){let i=[],s=n.cameraType==="OrthographicCamera"?t.orthographic?.zoom:t.perspective?.zoom,o=n.cameraType==="OrthographicCamera"?e.orthographic?.zoom:e.perspective?.zoom;if(o!==void 0){let a=s??n.zoom,l=o;a!==l&&i.push({update:c=>{n.zoom=we.lerp(a,l,c),n.updateProjectionMatrix()},start:()=>{n.zoom=a,n.updateProjectionMatrix()},end:()=>{n.zoom=l,n.updateProjectionMatrix()}})}if(e.targetOffset!==void 0){let a=Zr("targetOffset",n,t,e,r);a&&i.push(a)}return i}function vJ(n,t,e,r){if(e.scaleBaked===void 0)return;let i=(t.scaleBaked??n.data.geometry.scaleBaked).map(a=>typeof a=="string"?Number(r.getVariable(a)??0):a),s=e.scaleBaked.map(a=>typeof a=="string"?Number(r.getVariable(a)??0):a);if(Mo.isEqual(i,s))return;let o=[];return o.push({update:a=>{n.updateGeometryInteractions({scaleBaked:[we.lerp(i[0],s[0],a),we.lerp(i[1],s[1],a),we.lerp(i[2],s[2],a)]},r),n.invalidateDownstreamBooleanData(),n.refreshAttachedClonersInteractions()},start:()=>{n.updateGeometryInteractions({scaleBaked:i},r),n.invalidateDownstreamBooleanData(),n.refreshAttachedClonersInteractions()},end:()=>{n.updateGeometryInteractions({scaleBaked:s},r),n.invalidateDownstreamBooleanData(),n.refreshAttachedClonersInteractions()}}),o}function xJ(n,t,e,r){if(!e.extrusion)return;let i=n.extrusion,s=t.extrusion??{},o=e.extrusion,a=[];return HA.forEach(l=>{let c=Yo(l,i,s,o,r);c&&a.push(c)}),a}function xN(n,t,e,r){let i=[];if(!("geometry"in e))return i;let s=n.geometry.userData.parameters,o="geometry"in t?t.geometry:{},a=e.geometry;if(n instanceof Zs){let l=vJ(n,o,a,r);l&&i.push(...l)}else{let l={};if(Object.assign(l,Pn(s,Zv),Pn(o,Zv)),Zv.forEach(c=>{let u=Yo(c,l,o,a,r);u&&i.push(u)}),n instanceof rc){Object.assign(l,{extrusion:{...s.extrusion}});let c=xJ(l,o,a,r);c&&i.push(...c)}i.length&&i.push({update:c=>{n.updateGeometryInteractions(l,r),n.updateGeometryGroupsIfNeeded(),n.refreshAttachedClonersInteractions()},start:c=>{n.updateGeometryInteractions(l,r),n.updateGeometryGroupsIfNeeded(),n.refreshAttachedClonersInteractions()},end:c=>{n.updateGeometryInteractions(l,r),n.updateGeometryGroupsIfNeeded(),n.refreshAttachedClonersInteractions()}})}return i}function bN(n,t,e,r){let i=[];if(e.intensity!==void 0){let s=Zr("intensity",n,t,e,r);s&&i.push(s)}if(e.color!==void 0){let s=yN("color",n,t,e,r);s&&i.push(s)}return i}function wN(n,t,e,r){let i=[];if(Array.isArray(n.material)){if(!("materials"in e&&e.materials))return i;let s="materials"in t&&t.materials?t.materials:[],o=e.materials;n.material.forEach((a,l)=>{if(!o[l])return;let c=s[l]??{},u=o[l];typeof c=="string"||typeof u=="string"||i.push(...SN(a,c,u,r))})}else{if(!("material"in e&&e.material))return i;let s="material"in t&&t.material?t.material:{},o=e.material;if(typeof s=="string"||typeof o=="string")return i;i.push(...SN(n.material,s,o,r))}return i}function SN(n,t,e,r){let i=[],s=Zc(e,r)||!!t.layers&&Zc(t,r);i.push(PJ(n,s));for(let o of n.layers){let a=t.layers?.data(o.uuid),l=e.layers.data(o.uuid);if(!l||o.type!=="light"&&(!(o.visible??!0)||!(l.visible??!0)))continue;let c=o.getNames().filter(u=>!Yv.some(h=>u.includes(h)));for(let u of c)try{let h=o.getValue(u),d;if(u==="colors")d=MJ(o,a,l,u);else if(Array.isArray(h))u==="steps"&&(d=TJ(o,a,l,u));else if(typeof h=="number")d=bJ(o,a,l,u,r);else{if(typeof h=="boolean")continue;h instanceof k?d=SJ(o,a,l,u):h instanceof E?d=wJ(o,a,l,u,r):h instanceof vr?d=EJ(o,a,l,u,r):h instanceof We?d=AJ(o,a,l,u,r):"isTexture"in h&&(d=CJ(o,a,l,u))}d&&(Array.isArray(d)?i.push(...d):i.push(d))}catch(h){console.error(`lerpMaterial: unexpected material layer for ${u}`,h)}}return i}function bJ(n,t,e,r,i){if(!n.hasValue(r)||!(r in e))return;let s=t?t[r]:n.getValue(r),o=e[r],a=typeof s=="string"?Number(i.getVariable(s)??0):s,l=typeof o=="string"?Number(i.getVariable(o)??0):o;if(a!==l)return{update:c=>{n.setValue(r,we.lerp(a,l,c))},start:()=>{n.setValue(r,a)},end:()=>{n.setValue(r,l)}}}function SJ(n,t,e,r){if(!n.hasValue(r)||!(r in e))return;let i=n.getValue(r),s=t?new k().fromArray(t[r]):i.clone(),o=new k().fromArray(e[r]);if(!s.equals(o))return{update:a=>{i.lerpVectors(s,o,a)},start:()=>{i.copy(s)},end:()=>{i.copy(o)}}}function wJ(n,t,e,r,i){if(!n.hasValue(r)||!(r in e))return;let s=n.getValue(r),o=t?t[r]:void 0,a=e[r],l=o?sg(new E,o,i):s.clone(),c=sg(new E,a,i);if(!l.equals(c))return{update:u=>{s.lerpVectors(l,c,u)},start:()=>{s.copy(l)},end:()=>{s.copy(c)}}}function AJ(n,t,e,r,i){if(!n.hasValue(r)||!(r in e))return;let s=t?t[r]:void 0,o=e[r],a=n.getValue(r),l=s?typeof s=="string"?i.getColor(s).clone():new We().setRGB(s.r,s.g,s.b):a.clone(),c=typeof o=="string"?i.getColor(o).clone():new We().setRGB(o.r,o.g,o.b);if(l.equals(c))return;let u=a.clone();return{update:h=>{n.getValue(r)!==u&&n.setValue(r,u),u.lerpColors(l,c,h)},start:()=>{u.copy(l)},end:()=>{u.copy(c)}}}function EJ(n,t,e,r,i){if(!n.hasValue(r)||!(r in e))return;let s=t?t[r]:void 0,o=e[r],a=n.getValue(r),l=s?typeof s=="string"?i.getColor(s).clone():new We().setRGB(s.r,s.g,s.b):a.clone(),c=typeof o=="string"?i.getColor(o).clone():new vr(o.r,o.g,o.b,o.a);if(l.equals(c))return;let u=a.clone();return{update:h=>{n.getValue(r)!==u&&n.setValue(r,u),u.lerpColors(l,c,h)},start:()=>{u.copy(l)},end:()=>{u.copy(c)}}}function TJ(n,t,e,r="steps"){if(!n.hasValue(r)||!(r in e))return;let i=[],s=n.getValue(r),o=t?t[r]:s,a=e[r];return Rc(o,a)||i.push({update:l=>{let c=[...s];for(let u=0;u{n.setValue(r,o)},end:()=>{n.setValue(r,a)}}),i.length?i:void 0}function MJ(n,t,e,r="colors"){if(!n.hasValue(r)||!(r in e))return;let i=[],s=n.getValue(r),o=t?t[r]:s.map(l=>l.toArray()),a=e[r];for(let l=0;l{s[l].fromArray(Xp.lerp(c,u,h))},start:()=>{s[l].fromArray(c)},end:()=>{s[l].fromArray(u)}})}return i.length?i:void 0}function CJ(n,t,e,r="texture"){if(!n.hasValue(r)||!(r in e))return;let i=n.getNode("rotation"),s=t?.[r]?.rotation??0,o=e[r]?.rotation??0;if(i&&s!==o)return{update:g=>{i.value=we.lerp(s,o,g)*we.DEG2RAD},start:()=>{i.value=s*we.DEG2RAD},end:()=>{i.value=o*we.DEG2RAD}};let a=n.getNode("mat");if(!a)return;let l=t?t[r]:a,c=e[r],u=[...l.repeat],h=[...l.offset],d=[...c.repeat],f=[...c.offset],p=l.rotation??0,m=c.rotation??0;if(!Vs.isEqual(u,d)||!Vs.isEqual(h,f)||p!==m)return{update:g=>{a.repeat=Vs.lerp(u,d,g),a.offset=Vs.lerp(h,f,g),a.rotation=we.lerp(p,m,g),a.updateMatrix()},start:()=>{a.repeat=[...u],a.offset=[...h],a.rotation=p,a.updateMatrix()},end:()=>{a.repeat=[...d],a.offset=[...f],a.rotation=m,a.updateMatrix()}}}function PJ(n,t){return{update:()=>{n.transparent=t}}}var kT=new E,AN=new nr;function EN(n,t,e,r,i){let s=[],o,a,l,c,u,h,d,f;if(n instanceof rr?(o=kf("position",n,t,e,i),o&&s.push(o),l=Zr("rotation",n,t,e,i),l&&s.push(l),c=kf("shear",n,t,e,i),c&&s.push(c)):(f={slide:t.pathSnapping?.slide??n.updatedPathSnapping?.slide??n.dataPatched.pathSnapping?.slide??0,offset:t.pathSnapping?.offset??n.updatedPathSnapping?.offset??n.dataPatched.pathSnapping?.offset??0},h=Zr("slide",f,t.pathSnapping??n.updatedPathSnapping??n.dataPatched.pathSnapping,e.pathSnapping??n.dataPatched.pathSnapping,i),h&&s.push(h),d=Zr("offset",f,t.pathSnapping??n.updatedPathSnapping??n.dataPatched.pathSnapping,e.pathSnapping??n.dataPatched.pathSnapping,i),d&&s.push(d),!h&&!d&&(o=VT("position",n,t,e,i),o&&s.push(o),a=VT("scale",n,t,e,i),a&&s.push(a),l=_J(n,t,e,r,i),l&&s.push(l),u=gN("hiddenMatrix",n,t,e),u&&s.push(u))),o||a||l||u||h||d){let p=n instanceof rr?()=>{n.updateWorldMatrix(!0)}:()=>{n.updateMatrix(),n.hasNonUniformScale&&(n.updateMatrixWorld(),n.updateMatrixWorldSVD()),n.parent?.matrixWorldFusedFalse&&(n.matrixWorld.multiplyMatrices(n.parent.matrixWorldFusedFalse,n.matrix),n.matrixWorldNeedsUpdate=!1),cn(n)&&En(n.parent)&&n.invalidateDownstreamBooleanData(!0),n.updatePathSnapping(Object.assign({},t.pathSnapping,f))};s.push({update:p,start:p,end:p})}return s}function _J(n,t,e,r,i){let s=t?.rotation?t.rotation.map(u=>(typeof u=="string"?Number(i.getVariable(u)??0):u)*we.DEG2RAD):void 0,o=e.rotation?.map(u=>(typeof u=="string"?Number(i.getVariable(u)??0):u)*we.DEG2RAD);if(!o)return;let a=s?new E().fromArray(s):new E().setFromEuler(n.rotation),l=new E().fromArray(o);if(a.equals(l))return;let c=kT.subVectors(l,a);if(r&&c.toArray().every(u=>Math.abs(u)<2*Math.PI)){let u=new Ke().setFromEuler(AN.setFromVector3(a)),h=new Ke().setFromEuler(AN.setFromVector3(l));return{update:d=>{mN(u,h,n.quaternion,d)},start:()=>{n.rotation.setFromVector3(a)},end:()=>{n.rotation.setFromVector3(l)}}}else return{update:u=>{kT.lerpVectors(a,l,u),n.rotation.setFromVector3(kT)},start:()=>{n.rotation.setFromVector3(a)},end:()=>{n.rotation.setFromVector3(l)}}}function TN(n,t,e,r){let i=[];if(!("cloner"in e)||!n.cloner)return i;let s=n.cloner,o="cloner"in t?t.cloner:{},a=e.cloner;BA.forEach(f=>{let p;f==="count"?p=Zr("count",s.parameters,o,a,r,!0):p=Yo(f,s.parameters,o??{},a,r),p&&i.push(p)});let l=IJ(s,o,a,r);l?.length&&i.push(...l);let c=DJ(s,o,a,r);c?.length&&i.push(...c);let u=OJ(s,o,a,r);u?.length&&i.push(...u);let h=RJ(s,o,a,r);h?.length&&i.push(...h);let d=LJ(s,o,a,r);return d?.length&&i.push(...d),i.length&&i.push({update:()=>{s.update()}}),i}function IJ(n,t,e,r){if(n.parameters.type!=="radial")return;let i=t.radial,s=e.radial;if(!s)return;let o=n.parameters.radial,a=[];return NA.forEach(l=>{let c=Yo(l,o,i??{},s,r);c&&a.push(c)}),a}function DJ(n,t,e,r){if(n.parameters.type!=="linear")return;let i=t.linear,s=e.linear;if(!s)return;let o=[],a=n.parameters.linear;return FA.forEach(l=>{let c=Yo(l,a,i??{},s,r);c&&o.push(c)}),o}function OJ(n,t,e,r){if(n.parameters.type!=="grid")return;let i=t.grid,s=e.grid;if(!s)return;let o=[],a=n.parameters.grid;return VA.forEach(l=>{let c;l==="count"?c=og(l,a,i??{},s,r,!0):c=Yo(l,a,i??{},s,r),c&&o.push(c)}),o}function RJ(n,t,e,r){if(n.parameters.type!=="toObject")return;let i=t.toObject,s=e.toObject;if(!s)return;let o=[],a=n.parameters.toObject;return kA.forEach(l=>{let c;l==="count"?c=Zr(l,a,i??{},s,r,!0):c=Yo(l,a,i??{},s,r),c&&o.push(c)}),o}function LJ(n,t,e,r){if(!n.parameters.randomness)return;let i=t.randomnessObject,s=e.randomnessObject;if(!s)return;let o=[],a=n.parameters.randomnessObject;return UA.forEach(l=>{let c=Yo(l,a,i??{},s,r);c&&o.push(c)}),o}function BJ(n,t){return{update:()=>{n instanceof Ar&&(n.fill.enabled=t)}}}function NJ(n,t){return{update:()=>{n instanceof Ar&&(n.stroke.enabled=t)}}}function FJ(n,t){return{update:()=>{n instanceof Ar&&(n.dropShadow.enabled=t)}}}function VJ(n,t){return{update:()=>{n instanceof Ar&&(n.innerShadow.enabled=t)}}}function kJ(n,t){return{update:()=>{n instanceof Ar&&(n.backgroundBlur.enabled=t)}}}function UJ(n,t){return{update:()=>{n instanceof Ar&&(n.layerBlur.enabled=t)}}}function MN(n,t,e,r,i){let s=[],o,a,l,c,u,h,d,f,p,m,g,y,v,x,S;if("width"in n&&(o=Zr("width",n,t,e,i),o&&s.push(o)),"height"in n&&(a=Zr("height",n,t,e,i),a&&s.push(a)),n instanceof Ar||n instanceof Ji){let w={...t.fill},A={...e.fill};w.enabled!==void 0&&w.enabled!==A.enabled&&(s.push(BJ(n,!0)),w.enabled||Object.assign(w,{enabled:!0,color:{...w.color,a:0}}),A.enabled||Object.assign(A,{enabled:!0,color:{...A.color,a:0}})),l=ag("color",n.fill,w,A,i),l&&s.push(l)}if(n instanceof Ar){let w={...t.stroke},A={...e.stroke};(w.enabled||A.enabled)&&(s.push(NJ(n,!0)),w.enabled||Object.assign(w,{enabled:!0,color:{...w.color,a:0}}),A.enabled||Object.assign(A,{enabled:!0,color:{...A.color,a:0}})),c=ag("color",n.stroke,w,A,i),c&&s.push(c),u=Zr("thickness",n.stroke,w,A,i),u&&s.push(u)}if(n instanceof Ar){let w={...t.dropShadow},A={...e.dropShadow};(w.enabled||A.enabled)&&(s.push(FJ(n,!0)),w.enabled||Object.assign(w,{enabled:!0,color:{...w.color,a:0}}),A.enabled||Object.assign(A,{enabled:!0,color:{...A.color,a:0}})),h=ag("color",n.dropShadow,w,A,i),h&&s.push(h),d=Zr("blurRadius",n.dropShadow,w,A,i),d&&s.push(d),p=Zr("spread",n.dropShadow,w,A,i),p&&s.push(p),f=kf("offset",n.dropShadow,w,A,i),f&&s.push(f)}if(n instanceof Ar){let w={...t.innerShadow},A={...e.innerShadow};(w.enabled||A.enabled)&&(s.push(VJ(n,!0)),w.enabled||Object.assign(w,{enabled:!0,color:{...w.color,a:0}}),A.enabled||Object.assign(A,{enabled:!0,color:{...A.color,a:0}})),m=ag("color",n.innerShadow,w,A,i),m&&s.push(m),g=Zr("blurRadius",n.innerShadow,w,A,i),g&&s.push(g),v=Zr("spread",n.innerShadow,w,A,i),v&&s.push(v),y=kf("offset",n.innerShadow,w,A,i),y&&s.push(y)}if(n instanceof Ar||n instanceof Ji){let w={...t.backgroundBlur},A={...e.backgroundBlur};(w.enabled||A.enabled)&&(s.push(kJ(n,!0)),w.enabled||Object.assign(w,{enabled:!0,radius:0}),A.enabled||Object.assign(A,{enabled:!0,radius:0})),x=Zr("radius",n.backgroundBlur,w,A,i),x&&s.push(x)}if(n instanceof Ar){let w={...t.layerBlur},A={...e.layerBlur};(w.enabled||A.enabled)&&(s.push(UJ(n,!0)),w.enabled||Object.assign(w,{enabled:!0,radius:0}),A.enabled||Object.assign(A,{enabled:!0,radius:0})),S=Zr("radius",n.layerBlur,w,A,i),S&&s.push(S)}if(n instanceof Ji||n instanceof Es){let w=og("cornerRadius",n,t,e,i);w&&s.push(w)}return s}function UT(n,t,e,r,i){let s=[];return n.data.visible&&s.push(...EN(n,t,e,i,r)),n instanceof rr?s.push(...MN(n,t,e,i,r)):(n.data.visible&&s.push(...TN(n,t,e,r)),cn(n)?(n instanceof cr&&n.data.visible&&s.push(...xN(n,t,e,r)),n.data.visible&&s.push(...wN(n,t,e,r))):N3(n)?n.data.visible&&s.push(...bN(n,t,e,r)):B3(n)&&s.push(...vN(n,t,e,r))),s.length?{update:o=>{s.forEach(a=>a.update(o))},start:o=>{s.forEach(a=>a.start?.(o))},end:o=>{s.forEach(a=>a.end?.(o))}}:void 0}var CN=new E;function Vf(n,t,e=!1){let r=[],i=s=>{let o=s.data;delete s.states,s.currentState=null,s.reversibleToState=null,s.currentTransitionEvent=null;for(let a of o.states){let l={...a.data};s.states||(s.states={}),s.states[a.id]=Ma.patch(o,l)}_N(n.scene,s,null,t,o.events.find(a=>a.data.type==="Follow"||a.data.type==="LookAt")!==void 0),PN(n)};n.scene.traverse2D(i),n.traverseChildren(s=>{if(e&&(s.rigidBody?.setTranslation(s.position0,!0),s.rigidBody?.setRotation(s.rotation0,!0),s.rigidBody?.setLinvel(CN,!0),s.rigidBody?.setAngvel(CN,!0)),!yt.is(s))return;let o=s.uuid,a=s.data;if(delete s.states,s.uuid===hs)return;let l=!1;r.some(c=>n.scene.find(o)?.isDescendantOf(c))?l=!0:a.physics?.fusedBody===!0&&a.physics.rigidBody==="dynamic"&&r.push(o),s.data=a,s.currentState=null,s.reversibleToState=null,s.currentTransitionEvent=null;for(let c of a.states){let u={...c.data};n.data.globalPhysics.usePhysics===!0&&a.physics&&(a.physics.rigidBody==="dynamic"||l)&&(c.data.position!==void 0&&delete u.position,c.data.rotation!==void 0&&delete u.rotation,c.data.hiddenMatrix!==void 0&&delete u.hiddenMatrix),s.states||(s.states={}),s.states[c.id]=Sa.patch(a,u)}_N(n.scene,s,null,t,a.events.find(c=>c.data.type==="Follow"||c.data.type==="LookAt")!==void 0),PN(n),s instanceof Er&&s.frame&&(s.frame.traverse(c=>i(c)),s.uiCanvas?.applySize())}),n.frame&&(n.frame.traverse(s=>i(s)),n.uiCanvas?.applySize())}function PN(n){n.traverseEntity(t=>{for(let e of t.data.events){let r=[];switch(e.data.type){case"Follow":case"MouseHover":case"Scroll":case"MouseDown":case"MouseUp":case"MousePress":case"KeyUp":case"KeyDown":case"KeyPress":case"Collision":r.push(...e.data.actions);break;case"GameControl":for(let i of Object.values(e.data.gameActions))r.push(...i);break;case"DragDrop":r.push(...e.data.dragDropActions.drag,...e.data.dragDropActions.drop);break;case"Conditional":r.push(...e.data.inActions,...e.data.outActions);break}for(let i of r)if(i.data.type==="Create"&&i.data.hideBase==="Yes"){let s=n.scene.find(i.data.object);s&&(s.visible=!1)}}})}function _N(n,t,e,r,i=!1){if(t instanceof cr&&t.removeInteractionGeometry(r),t instanceof rr?t.changeSelectedState(e,{shared:r},i):t.changeSelectedState(e,{scene:n,shared:r},i),t instanceof cr&&t.updateGeometryGroupsIfNeeded(),t instanceof wr&&t.updateCameraState(t.dataPatched,{scene:n,shared:r}),!(t instanceof rr)){if(t.cloner)for(let s of t.cloner.children)s.playModeVisible=void 0;t.updateVisible()}}function GT(n){let t;if(n.easing===5){let{control1:e,control2:r}=n;t=`cubicBezier( ${e[0]}, ${e[1]}, ${r[0]}, ${r[1]} )`}else if(n.easing===6){let{mass:e,stiffness:r,damping:i,velocity:s}=n;t=`spring( ${e}, ${r}, ${i}, ${s} )`}else{let e;switch(n.easing){case 0:e=va.linear;break;case 1:e=va.ease;break;case 2:e=va.easeIn;break;case 3:e=va.easeOut;break;case 4:e=va.easeInOut;break;default:e=va.linear}let[r,i,s,o]=e;t=`cubicBezier( ${r}, ${i}, ${s}, ${o} )`}return{duration:Math.max(n.duration,1e-4),easing:t}}function zT(n){let t={delay:0,loop:n.repeat===-1?!0:n.repeat+1};if(n.repeat===0)t.direction="normal",t.rewind=!1;else switch(n.direction){case"pingpong":t.direction="alternate",t.rewind=!1;break;case"pingpong-rewind":t.direction="alternate",t.rewind=!0;break;default:t.direction="normal",t.rewind=!1;break}switch(t.delay=0,t.endDelay=0,t.startOnceDelay=0,t.pingPongDelayCorrection=0,t.pingPongEndDelayCorrection=0,n.delayDirection){case"start-once":t.startOnceDelay=n.delay;break;case"start":t.delay=n.delay;break;case"end":t.endDelay=n.delay;break;case"start-end":case void 0:t.delay=n.delay,t.endDelay=n.delay;break}return t.direction==="alternate"&&(t.delay/=2,t.endDelay/=2,n.delayDirection==="start"?(t.pingPongDelayCorrection=t.delay,typeof t.loop=="number"&&t.loop%2===0&&(t.pingPongEndDelayCorrection=t.delay)):n.delayDirection==="end"?typeof t.loop=="number"&&t.loop%2!==0&&(t.pingPongEndDelayCorrection=t.endDelay):n.delayDirection==="start-end"&&(t.pingPongDelayCorrection=t.delay,t.pingPongEndDelayCorrection=t.endDelay)),t}var zJ={type:"beginState"},GJ={type:"completeState",isfromEntity:!1},Cb=class{constructor(t,e,r,i,s,o){this.object=t;this.data=i;this.sharedAssets=s;this.allowSlerp=o;this.targets={t:0};this.firstLoop=!0;this._changeBegan=!1;this._changeCompleted=!0;this.onChange=()=>{this.callback&&(this.callback.update(this.targets.t),this.object.requestRender()),this.targets.t===0||this.targets.t===1?this._changeCompleted||(this._changeCompleted=!0,this._changeBegan=!1,this.onChangeComplete()):(this._changeCompleted&&(this._changeCompleted=!1),this._changeBegan||(this._changeBegan=!0,this.onChangeBegin()))};this.onChangeBegin=()=>{this.object.reversibleToState=this.to.id;let t=this.targets.t>.5?this.from.id:this.to.id;this.object.prevState!==this.object.currentState&&(this.object.prevState=this.object.currentState),this.object.currentState=t,this.object.dispatchEvent({type:"beginState",state:t}),this.object instanceof rr||this.object.traverseEntity(e=>{e!==this.object&&e instanceof wr&&e.dispatchEvent(zJ)})};this.onChangeComplete=()=>{this.firstLoop&&(this.onFirstLoop(),this.firstLoop=!1),this.object.reversibleToState=this.to.id;let t=this.targets.t<.5?this.from.id:this.to.id;this.object.prevState!==this.object.currentState&&(this.object.prevState=this.object.currentState),this.object.currentState=t,this.object.dispatchEvent({type:"completeState",state:t}),this.object instanceof rr||this.object.traverseEntity(e=>{e!==this.object&&e instanceof wr&&e.dispatchEvent(GJ)})};this.onFirstLoop=()=>{this.useCurrentState&&(this.callback=UT(this.object,this.from.data,this.to.data,this.sharedAssets,this.allowSlerp))};if(e===void 0){let a=Mb(this.object,this.object.currentState===r?this.object.prevState:this.object.currentState);if(!a)throw new Error("Missing property");this.from=a}else{let a=Mb(this.object,e);if(!a)throw new Error("Missing property");this.from=a}if(r===void 0)throw new Error("Missing property");{let a=Mb(this.object,r);if(!a)throw new Error("Missing property");this.to=a}this.useCurrentState=e===void 0||r===void 0,this.params={targets:this.targets,t:1,autoplay:!1,...zT(i),...GT(i),change:this.onChange},this.callback=UT(this.object,e===void 0?{}:this.from.data,r===void 0?{}:this.to.data,this.sharedAssets,this.allowSlerp)}get changeBegan(){return this._changeBegan}get changeCompleted(){return this._changeCompleted}},lg=class extends pr{constructor(e,r,i,s,o){super();this.eventType=e;this.data=r;this.page=i;this.shared=s;this.condition=o;this.toggleIsForward=!1;this.timelineNeedsRebuild=!1;this.hasPlayedOnce=!1;this.onTimelineChangeComplete=()=>{this.data.tweens[0].data.direction!=="normal"&&(this.toggleIsForward=!this.toggleIsForward),this.timelineNeedsRebuild!==!1&&(this.timeline?.pause(),this.buildTimeline({isForward:this.toggleIsForward,needsRebuild:!1,isRebuild:!0}),this.timeline.play())};if(!r.object)throw new Error("Missing property");let a=this.page.scene.find(r.object)??this.page.uiCanvas?.find(r.object)??this.page.scene.find2DInUIObjects(r.object);if(!a)throw new Error("Missing property");if(!a.states)throw new Error("Missing property");if(this.object=a,r.tweens.length<2)throw new Error("Missing property");this.tweens=Array(this.data.tweens.length-1),this.startOnceDelay=r.tweens[0].data.delayDirection==="start-once"?r.tweens[0].data.delay:0,this.init()}get playing(){return this.timeline?.paused===!1}get changeBegan(){return this.tweens.some(e=>e.changeBegan)??!1}init(){this.initialCurrentState=Mb(this.object,this.object.currentState).id,this.toggleIsForward=!1}get currentState(){return this.data.runMode==="Toggle"&&RA(this.eventType)?this.initialCurrentState:this.object.currentState}buildTimeline({isForward:e=!0,needsRebuild:r=!1,isRebuild:i=!1}={}){try{let s=zT(this.data.tweens[0].data);i&&typeof s.loop=="number"&&s.loop--,this.timeline?.pause(),this.timeline=Tb.timeline({autoplay:!1,...s,...s.loop===!0||s.loop>1?{timelineChangeComplete:this.onTimelineChangeComplete}:{}});let o=this.tweens.findIndex(a=>a?.changeBegan);if(r===!0&&(this.timelineNeedsRebuild=!0),e){let a=o===-1?0:o;for(let l=a;l0;l--){let c=this.data.tweens[l],u=this.data.tweens[l-1],h;l===a&&(this.object.wasMovedByUser===!0||this.object.previousAction?.changeBegan===!0)?(h=void 0,this.object instanceof wr&&(this.object.wasMovedByUser=!1)):h=c.data.state===void 0?this.currentState:c.data.state;let d=new Cb(this.object,h,u.data.state===void 0?this.currentState:u.data.state,c.data,this.shared,this.data.allowSlerp??!1);o!==-1&&l===a&&Object.assign(d.params,{startOnceDelay:0}),this.tweens[l-1]=d,this.timeline.add(d.params,this.timeline.duration+(l===a?s.endDelay:0))}this.timeline.duration+=s.delay}}catch(s){s instanceof Error&&console.error(s.message)}this.object.previousAction?.playing===!0&&this.object.previousAction.pause(),this.object.previousAction=this}play(){if(wt(this.shared,this.condition)===!1||RA(this.eventType)&&this.data.runMode==="Once"&&this.hasPlayedOnce||(this.hasPlayedOnce=!0,this.playing))return!1;clearTimeout(this.timeoutId);let e=zT(this.data.tweens[0].data).pingPongDelayCorrection;this.timeoutId=window.setTimeout(()=>{try{this.buildTimeline(),this.timeline.play()}catch(r){r instanceof Error&&console.error(r.message)}},this.startOnceDelay+e)}pause(){this.timeline?.pause(),clearTimeout(this.timeoutId),this.tweens=Array(this.data.tweens.length-1),delete this.timeoutId}stop(){this.pause();let e=this.data.tweens[0].data.state===void 0?this.initialCurrentState:this.data.tweens[0].data.state;this.object instanceof rr?this.object.changeSelectedState(e,{shared:this.shared}):this.object.changeSelectedState(e,{scene:this.page.scene,shared:this.shared}),this.object.currentState=e}seek(e){if(wt(this.shared,this.condition)===!1)return!1;this.timeline===void 0&&this.buildTimeline(),this.timeline?.seek(e*this.timeline.duration,!0)}toggle(e){if(wt(this.shared,this.condition)===!1)return!1;clearTimeout(this.timeoutId),this.toggleIsForward=e??!this.toggleIsForward,this.playing?(this.timeline?.pause(),this.buildTimeline({isForward:this.toggleIsForward,needsRebuild:!0}),this.timeline.play()):this.timeoutId=window.setTimeout(()=>{this.timeline?.pause(),this.buildTimeline({isForward:this.toggleIsForward}),this.timeline.play()},this.startOnceDelay)}playFromCurrent(){this.toggle(!0)}reverseFromCurrent(){this.toggle(!1)}dispose(){this.pause()}};function Mb(n,t){let e,r;if(typeof t=="string"?(e=t,r=n.states?.[e]):t===null&&(e=null,r=n.data),!(e===void 0||r===void 0))return{id:e,data:r}}var jJ={type:"beginState"},IN={type:"completeState",isfromEntity:!1},DN={type:"requestRender"},cg=class extends pr{constructor(e,r,i,s){super();this.data=e;this.page=r;this.shared=i;this.condition=s;this.toggleIsForward=!1;this.posStart=new E;this.posEnd=new E;this.qStart=new Ke;this.qEnd=new Ke;this.zoomStart=1;this.zoomEnd=1}init(){}get playing(){return this.animation&&this.animation.began&&!this.animation.completed}buildAnimation(e=!1){if(!this.data.animate)return;let r=this.page.scene.find(this.data.targetCamera);if(!r||!r.visible)throw new ReferenceError("Target camera not founded or not visible");let i={t:0};this.posStart.copy(this.page.activeCamera.position),this.qStart.copy(this.page.activeCamera.quaternion),this.zoomStart=this.page.activeCamera.zoom,this.animation=Tb({targets:i,t:1,...GT(this.data),update:()=>{i.t===0&&(this.data.runMode==="Toggle"&&!this.toggleIsForward?this.fromCamera&&(this.posEnd.copy(this.fromCamera.position),this.qEnd.copy(this.fromCamera.quaternion),this.zoomEnd=this.fromCamera.zoom,this.switchCamera(this.fromCamera.uuid)):(this.posEnd.copy(r.position),this.qEnd.copy(r.quaternion),this.zoomEnd=r.zoom,this.fromCamera=this.page.activeCamera,this.switchCamera(r.uuid)),this.page.activeCamera.dispatchEvent(jJ));let s=this.page.activeCamera;s.position.lerpVectors(this.posStart,this.posEnd,i.t),s.quaternion.slerpQuaternions(this.qStart,this.qEnd,i.t),s.zoom=this.zoomStart+(this.zoomEnd-this.zoomStart)*i.t,s.wasMovedBySwitchCameraAction=!0,s.updateMatrix(),s.updateMatrixWorld(),s.updateProjectionMatrix(),s.dispatchEvent(DN),i.t===1&&s.dispatchEvent(IN)}})}switchCamera(e){let r=this.page.activeCamera,i=this.page.scene.find(e);if(!i||!i.visible)throw new ReferenceError("Target camera not founded or not visible");this.page.switchActiveCamera(i),r.dispatchEvent({type:"cameraChange",camera:i})}play(){if(wt(this.shared,this.condition)===!1)return!1;if(!this.playing&&this.page.activeCamera.uuid!==this.data.targetCamera)try{clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout(()=>{delete this.timeoutId,this.data.animate?(this.buildAnimation(),this.animation?.play()):this.switchCamera(this.data.targetCamera)},this.data.delay*1e3)}catch{}}pause(){this.animation?.pause(),clearTimeout(this.timeoutId),delete this.timeoutId}toggle(e){if(wt(this.shared,this.condition)===!1)return!1;if(window.clearTimeout(this.timeoutId),delete this.timeoutId,e!==this.toggleIsForward)try{this.playing?(this.animation?.pause(),this.toggleIsForward=e??!this.toggleIsForward,this.buildAnimation(!0),this.animation?.play()):this.timeoutId=window.setTimeout(()=>{this.toggleIsForward=e??!this.toggleIsForward,this.data.animate?(this.animation?.pause(),this.buildAnimation(),this.animation?.play()):(this.toggleIsForward?(this.fromCamera=this.page.activeCamera,this.switchCamera(this.data.targetCamera)):this.fromCamera&&this.switchCamera(this.fromCamera.uuid),this.page.activeCamera.dispatchEvent(IN),this.page.activeCamera.dispatchEvent(DN))},this.data.delay*1e3)}catch{}}playFromCurrent(){this.toggle(!0)}reverseFromCurrent(){this.toggle(!1)}dispose(){this.pause(),this.toggleIsForward=!1}};function jT(n){let t=n?.tracks.filter(e=>e.ValueTypeName==="vector"||e.ValueTypeName==="quaternion").map(e=>e.times.length);if(t?.length){let e=uA(t);return e&&e>2?e:2}return 2}var ug=class extends pr{constructor(e,r,i,s,o){super();this.data=e;this.page=r;this.animationControls=i;this.shared=s;this.condition=o;this.startOnceDelay=0;this.toggleIsForward=!1;let a=e.object,l=r.scene.find(e.object);l&&Array.isArray(l.identity)&&(a=l.identity[0]),this.data={...e,object:a};let c=this.animationControls.clipIdToAction[e.clipId+"/"+a];if(this.duration=c?.getClip()?.duration??1,this.data.crop2){let u=jT(c?.getClip());this.leftFrameTime=this.data.crop2[0]/(u-1)*this.duration,this.rightFrameTime=this.data.crop2[1]/(u-1)*this.duration}else{let u=c?.getClip()?.tracks[0]?.times.length;u&&u>1?(this.leftFrameTime=this.data.crop[0]/u*this.duration,this.rightFrameTime=this.data.crop[1]/u*this.duration):(this.leftFrameTime=0,this.rightFrameTime=this.duration)}this.startOnceDelay=e.delay}get playing(){return this.threeAnimAction?.isRunning()??!1}play(e=!1){if(wt(this.shared,this.condition)===!1)return!1;window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout(()=>{if(this.threeAnimAction=this.animationControls.play(this.data),!this.threeAnimAction)return;this.threeAnimAction.reset(),this.threeAnimAction.time=this.leftFrameTime,this.threeAnimAction._clip.start=this.leftFrameTime,this.threeAnimAction._clip.duration=this.rightFrameTime;let r=this.data.object;Object.entries(this.animationControls.clipIdToAction).forEach(([i,s])=>{let o=i.split("/")[1];this.threeAnimAction!==s&&o===r&&s.isRunning()&&(e?s.fadeOut(.2):s.stop())}),e&&this.threeAnimAction?.fadeIn(.2)},this.startOnceDelay)}pause(){this.threeAnimAction&&(this.threeAnimAction.paused=!0),window.clearTimeout(this.timeoutId),delete this.timeoutId}stop(){this.threeAnimAction?.fadeOut(.2)}seek(e){this.threeAnimAction=this.animationControls.play(this.data),this.threeAnimAction&&(this.threeAnimAction.paused=!0,this.threeAnimAction.time=we.clamp(this.threeAnimAction.time+1/60*e,this.leftFrameTime,this.rightFrameTime-16e-5),this.animationControls.needsUpdate=!0,this.animationControls.requestRender())}toggle(e,r=!1){if(wt(this.shared,this.condition)===!1)return!1;this.toggleIsForward=e??!this.toggleIsForward,this.threeAnimAction&&(this.threeAnimAction._loopCount=0),this.playing?this.threeAnimAction&&(this.threeAnimAction.timeScale=this.toggleIsForward?1:-1,this.toggleIsForward?(this.threeAnimAction._clip.start=this.leftFrameTime,this.threeAnimAction._clip.duration=this.rightFrameTime):(this.threeAnimAction._clip.start=this.rightFrameTime,this.threeAnimAction._clip.duration=this.leftFrameTime)):this.timeoutId=window.setTimeout(()=>{if(this.threeAnimAction=this.animationControls.play(this.data),this.threeAnimAction){this.toggleIsForward?(this.threeAnimAction.time=this.leftFrameTime,this.threeAnimAction._clip.start=this.leftFrameTime,this.threeAnimAction._clip.duration=this.rightFrameTime):(this.threeAnimAction.time=this.rightFrameTime,this.threeAnimAction._clip.start=this.rightFrameTime,this.threeAnimAction._clip.duration=this.leftFrameTime),this.threeAnimAction.paused=!1,this.threeAnimAction.timeScale=this.toggleIsForward?1:-1;let i=this.data.clipId.split("/")[1];Object.entries(this.animationControls.clipIdToAction).forEach(([s,o])=>{let a=s.split("/")[1];this.threeAnimAction!==o&&a===i&&o.isRunning()&&(r?o.fadeOut(.2):o.stop())}),r&&this.threeAnimAction?.fadeIn(.2)}},this.startOnceDelay)}playFromCurrent(){this.toggle(!0)}reverseFromCurrent(){this.toggle(!1)}dispose(){let e=this.animationControls.clipIdToAction[this.data.clipId+"/"+this.data.object]?.getClip();e&&(e.duration=this.duration),this.pause()}};var hg=class{constructor(t,e,r,i,s){this.data=t;this.page=e;this.eventManager=r;this.shared=i;this.condition=s;this.timeOutId=-1;this.scene=e.scene}dispatch(){if(wt(this.shared,this.condition)===!1)return!1;this.data.target!==this.page.uuid&&(window.clearTimeout(this.timeOutId),this.timeOutId=window.setTimeout(()=>{this.play()},this.data.delay*1e3))}dispose(){window.clearTimeout(this.timeOutId)}play(){if(this.scene.children.every(r=>r.uuid!==this.data.target))return;this.data.transition==="fade"&&this.data.duration>0&&this.eventManager.eventContext.renderer.renderFromSceneForSceneTransitionPass(this.scene,this.scene.activeCamera,this.data.duration*1e3),this.eventManager.deactivate(),this.eventManager.controlsManager.deactivate();let t=this.scene.activeCamera;this.scene.updatePage(this.data.target),this.scene.traverseVisibleEntity(r=>{r.type==="ParticleSystem"&&(r.sleep(),r.wakeUp(),r.data.autoPlay?r.start():r.stop())}),this.scene.activePage.switchToPlayCamera(),this.scene.activeCamera.copyViewPlaneSize(t),Vf(this.scene.activePage,this.shared),this.eventManager.activate(),this.eventManager.controlsManager.activate(this.eventManager)}};var dg=class{constructor(t,e,r,i){this.data=t;this.page=e;this.shared=r;this.condition=i;this.evaluatedCondition=!1}checkConditions(){this.evaluatedCondition=wt(this.shared,this.condition)}dispatch(){if(this.evaluatedCondition===!1)return!1;let t=this.shared.getVariable(this.data.variableId),e=z0(this.data.expression,this.shared,Br.typeOfVariable(t));e!==void 0&&this.shared.updateVariable(this.data.variableId,typeof e=="string"?{textValue:e}:e)}dispose(){}};var fg=class{constructor(t,e,r,i){this.data=t;this.page=e;this.shared=r;this.condition=i;this.timeoutId=null}dispatchInner(){if(wt(this.shared,this.condition)===!1)return!1;let t=this.shared.getDynamicVariablePlayState(this.data.variableId);if(this.data.mode==="PlayPause")this.shared.getDynamicVariableToggleIsForward(this.data.variableId)===void 0&&this.shared.setDynamicVariableToggleIsForward(this.data.variableId,!0),this.shared.setDynamicVariablePlayState(this.data.variableId,t==="Playing"?"Paused":"Playing");else if(this.data.mode==="Play"&&t!=="Playing")this.shared.getDynamicVariableToggleIsForward(this.data.variableId)===void 0&&this.shared.setDynamicVariableToggleIsForward(this.data.variableId,!0),this.shared.setDynamicVariablePlayState(this.data.variableId,"Playing");else if(this.data.mode==="Stop"&&t!=="Stopped")this.shared.setDynamicVariablePlayState(this.data.variableId,"Stopped");else if(this.data.mode==="Pause"&&t!=="Paused")this.shared.setDynamicVariablePlayState(this.data.variableId,"Paused");else if(this.data.mode==="Restart")this.shared.setDynamicVariablePlayState(this.data.variableId,"Restarted");else if(this.data.mode==="Toggle"){let e=this.shared.getDynamicVariableToggleIsForward(this.data.variableId);t==="Playing"?this.shared.setDynamicVariableToggleIsForward(this.data.variableId,e===void 0?!1:!e):(this.shared.setDynamicVariableToggleIsForward(this.data.variableId,!e),this.shared.setDynamicVariablePlayState(this.data.variableId,"Playing"))}}dispatch(){let t=this.data.delay,e=this.shared.getDynamicVariablePlayState(this.data.variableId);this.data.mode==="PlayPause"&&e==="Playing"&&(t=this.data.pauseDelay),t!==0?(this.timeoutId&&window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout(()=>{this.timeoutId=null,this.dispatchInner()},t)):this.dispatchInner()}dispose(){this.timeoutId&&window.clearTimeout(this.timeoutId)}};var Pb=class{constructor(t,e,r,i){this.data=t;this.page=e;this.shared=r;this.condition=i}dispatch(){if(wt(this.shared,this.condition)===!1)return!1;(this.data.target==="single"?this.data.variableId?[this.data.variableId]:[]:Object.keys(this.shared.getVariables())).forEach(e=>{this.shared.getVariable(e);let r=this.shared.data.variables.data(e)?.value;r!==void 0&&this.shared.updateVariable(e,r),this.shared.enableLocalStorageForPersistentVariables&&localStorage.removeItem(gx(e))})}dispose(){}};var _b=class{constructor(t,e,r,i){this.data=t;this.page=e;this.shared=r;this.condition=i}dispatch(){if(wt(this.shared,this.condition)===!1)return!1;this.data.userAPIId&&this.shared.getUserAPI(this.data.userAPIId)?.callUserAPI(this.shared)}dispose(){}};function wt(n,t){if(t===void 0)return!0;if(t.expression.length===0)return!1;let e=z0(t.expression,n,"boolean");return t.negate?!e:!!e}function kt(n,t,e,r,i,s){let o={Audio:[],Video:[],Particles:[],Link:[],Destroy:[],Create:[],Reset:[],Transition:[],SwitchCamera:[],Animation:[],SceneTransition:[],SetVariable:[],DynamicVariablePlay:[],ClearLocalStorage:[],UserAPI:[]},a=l=>({id:c,data:u})=>{try{u.type==="Audio"?Yi[n.type].includes("Audio")&&o.Audio.push(new eg(c,u,s,r,l)):u.type==="Video"&&!(s instanceof rr)?Yi[n.type].includes("Video")&&o.Video.push(new pg(c,u,s,r,l)):u.type==="Particles"?Yi[n.type].includes("Particles")&&o.Particles.push(new tg(u,e,r,l)):u.type==="Link"?Yi[n.type].includes("Link")&&o.Link.push(new xb(u,i.controlsManager,r,l)):u.type==="Create"?Yi[n.type].includes("Create")&&o.Create.push(new mg(u,e,i.controlsManager,r,l)):u.type==="Destroy"?Yi[n.type].includes("Destroy")&&o.Destroy.push(new rg(u,e,i.controlsManager,r,l)):u.type==="Reset"?Yi[n.type].includes("Reset")&&o.Reset.push(new ig(u,e,r,i,l)):u.type==="Transition"?Yi[n.type].includes("Transition")&&o.Transition.push(new lg(n.type,u,e,r,l)):u.type==="SwitchCamera"?Yi[n.type].includes("SwitchCamera")&&o.SwitchCamera.push(new cg(u,e,r,l)):u.type==="SceneTransition"?Yi[n.type].includes("SceneTransition")&&o.SceneTransition.push(new hg(u,e,i,r,l)):u.type==="Animation"?Yi[n.type].includes("Animation")&&o.Animation.push(new ug(u,e,i.animationControls,r,l)):u.type==="SetVariable"?Yi[n.type].includes("SetVariable")&&o.SetVariable.push(new dg(u,e,r,l)):u.type==="DynamicVariablePlay"?Yi[n.type].includes("DynamicVariablePlay")&&o.DynamicVariablePlay.push(new fg(u,e,r,l)):u.type==="Conditional"?Yi[n.type].includes("Conditional")&&(u.ifActions.forEach(a({expression:u.condition,negate:!1})),u.elseActions.forEach(a({expression:u.condition,negate:!0}))):u.type==="ClearLocalStorage"?Yi[n.type].includes("ClearLocalStorage")&&o.ClearLocalStorage.push(new Pb(u,e,r,l)):u.type==="UserAPI"&&Yi[n.type].includes("UserAPI")&&o.UserAPI.push(new _b(u,e,r,l))}catch(h){!1&&console.log(h)}};return t.forEach(a()),o}function hr(n){Object.values(n).forEach(t=>{t.forEach(e=>{(e instanceof eg||e instanceof pg||e instanceof tg||e instanceof ug||e instanceof lg||e instanceof mg||e instanceof rg||e instanceof cg||e instanceof hg||e instanceof ig||e instanceof dg||e instanceof fg)&&e.dispose()})})}function ON(n,t){let e;if("material"in n){let r=n.material;Array.isArray(r)?e=n.material[0].layers.find(i=>i.uuid===t):e=n.material.layers.find(i=>i.uuid===t)}if(!!e)return e.color.texture.image.img instanceof HTMLVideoElement?e.color.texture.image.img:void 0}var RN=new Map,gg=new Map,ja=class{constructor(t,e,r){this.data=e;this.delay=0;this.status="stopped";let{layerId:i,loop:s,volume:o,delay:a}=e;if(this.object=r,i===void 0)throw new Error("Missing property");let l=ON(r,i);l&&(this.videoElement=l,this.videoElement.loop=s===1/0,xo&&(this.videoElement.autoplay=!0),o!==void 0&&(this.videoElement.volume=o)),a!==void 0&&(this.delay=a),gg.has(r.uuid)?gg.get(r.uuid).push(this):gg.set(r.uuid,[this]),RN.set(t,this),this.pause()}mute(){!this.videoElement||(this.videoElement.muted=!0)}unMute(){!this.videoElement||(this.videoElement.muted=!1)}play(t){if(!this.videoElement)return;let e=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);t?(this.mute(),this.delay+=150):e?(this.mute(),window.setTimeout(()=>{this.unMute()},100)):this.unMute(),this.delayTimerId=window.setTimeout(()=>{if(!this.videoElement)return;let r=this.videoElement.play();r!==void 0&&r.then(i=>{}).catch(i=>{this.play()}),this.clearDelay()},this.delay),this.status="playing"}clearDelay(){this.delayTimerId&&(clearTimeout(this.delayTimerId),delete this.delayTimerId)}pause(){!this.videoElement||(this.videoElement.pause(),this.status="paused")}stop(){!this.videoElement||(this.videoElement.pause(),this.videoElement.currentTime=0,this.status="stopped",this.clearDelay())}playByToggle(){this.data.toggle==="stop"?this.status==="playing"?this.stop():(this.stop(),this.play()):this.data.toggle==="pause"?this.status==="playing"?this.pause():this.play():(this.stop(),this.play())}dispose(){!this.videoElement||(this.stop(),this.videoElement.muted=!0)}},Uf=class{constructor(t){this.data=t}dispatch(){this.data.playVideo?this.pauseVideo(this.data.playVideo):this.data.object?this.pauseAllVideosFromObject(this.data.object):this.pauseAllVideos()}pauseVideo(t){let e=RN.get(t);!e||(this.data.delay>0?(this.disposeDelay(),this.timeoutId=window.setTimeout(()=>{e[this.data.interaction](),this.disposeDelay()},this.data.delay)):e[this.data.interaction]())}pauseAllVideosFromObject(t){let e=gg.get(t);!e?.length||(this.data.delay>0?(this.disposeDelay(),this.timeoutId=window.setTimeout(()=>{e.forEach(r=>r[this.data.interaction]()),this.disposeDelay()},this.data.delay)):e.forEach(r=>r[this.data.interaction]()))}pauseAllVideos(){let t=[...gg.values()];!t.length||(this.data.delay>0?(this.disposeDelay(),this.timeoutId=window.setTimeout(()=>{t.forEach(e=>{e.forEach(r=>{r[this.data.interaction]()})}),this.disposeDelay()},this.data.delay)):t.forEach(e=>{e.forEach(r=>{r[this.data.interaction]()})}))}disposeDelay(){clearTimeout(this.timeoutId),delete this.timeoutId}dispose(){clearTimeout(this.timeoutId),delete this.timeoutId}},pg=class{constructor(t,e,r,i,s){this.data=e;this.shared=i;this.condition=s;if(e.interaction==="play")this.interaction=new ja(t,e,r);else if(e.interaction==="pause"||e.interaction==="stop")this.interaction=new Uf(e);else throw new Error("Missing property")}dispatchBasic(){if(wt(this.shared,this.condition)===!1)return!1;this.interaction instanceof ja?this.interaction.playByToggle():this.interaction.dispatch()}dispatchConditional(){if(wt(this.shared,this.condition)===!1)return!1;this.interaction instanceof ja?this.interaction.play():this.interaction.dispatch()}dispose(){this.interaction.dispose()}};var LN=(()=>{let n,t,e,r;function i(a){!n&&!BN()&&t?.sharedGameControlGlobals.createdObjects.length>0&&(n=requestAnimationFrame(s)),a&&(t=a,r=a.requestRender)}function s(a){let l=e?a-e:0,c=t.sharedGameControlGlobals.createdObjects,u=t.sharedGameControlGlobals.nCreatedPerAction,h=c.length,d=0;for(;df.userData.quantity&&u[f.userData.actionId]--,c.splice(d,1),f.removeFromParent(),t.sharedGameControlGlobals.rapierWorld&&f.rigidBody?(t.sharedGameControlGlobals.colliderToEntity.delete(f.rigidBody.collider(0).handle),t.sharedGameControlGlobals.rapierWorld.removeRigidBody(f.rigidBody)):(f.bvhGeometry=void 0,t.sharedGameControlGlobals.entitiesWithTransformAnim=t.sharedGameControlGlobals.entitiesWithTransformAnim.filter(p=>p.bvhGeometry!==void 0)),h--,r())}n=d>0?requestAnimationFrame(s):void 0,e=d>0?a:void 0}function o(){BN()?n&&(cancelAnimationFrame(n),n=void 0,e=void 0):i()}return typeof document<"u"&&document.addEventListener("visibilitychange",o),i})();function BN(){return!!document&&document.hidden}var NN=new Ke,HJ=new E,WJ=new E,mg=class{constructor(t,e,r,i,s){this.data=t;this.page=e;this.controlsManager=r;this.shared=i;this.condition=s;this.intervalId=null;this.timeoutIdQueue=[];this.uniqueId=we.generateUUID();this.dispatch=()=>{if(wt(this.shared,this.condition)===!1)return!1;this.data.delay?this.timeoutIdQueue.push(window.setTimeout(this.dispatchInner,this.data.delay*1e3)):this.dispatchInner()};this.dispatchFromStart=()=>{if(wt(this.shared,this.condition)===!1)return!1;this.timeoutIdQueue.push(window.setTimeout(this.dispatchInner,this.data.delay*1e3))};this.dispatchThrottled=hA(this.dispatch,1e3/this.data.creationSpeed);this.dispatchStart=()=>{this.intervalId===null&&(this.intervalId=window.setInterval(this.dispatch,1e3/this.data.creationSpeed))};this.dispatchStop=()=>{this.intervalId!==null&&(window.clearInterval(this.intervalId),this.intervalId=null)};this.dispatchInner=()=>{this.timeoutIdQueue.shift();let t=new Nr(this.object);if(t.playModeVisible=!0,t.expand(),this.data.coordinateSystem!=="world"){let r=this.data.coordinateSystem,i=this.page.scene.find(r);i&&(i.updateMatrixWorldSVD(),t.hiddenMatrix.copy(i.matrixWorldRigid))}t.scale.copy(this.object.scale),t.position.fromArray(this.data.position),t.rotation.fromArray(this.data.rotation),t.updateMatrix(),this.page.add(t);let e=this.controlsManager.sharedGameControlGlobals;e.createdObjects.push(t),e.nCreatedPerAction[this.uniqueId]===void 0?e.nCreatedPerAction[this.uniqueId]=1:e.nCreatedPerAction[this.uniqueId]++,t.updateWorldMatrix(!0,!0),t.traverseObject(this.traverseObjectCB),LN(),this.controlsManager.requestRender()};this.traverseObjectCB=t=>{t.hasNonUniformScale&&t.updateMatrixWorldSVD();let e;if(this.controlsManager.sharedGameControlGlobals.rapierWorld){if(t instanceof Gi)if(t.objectForSample){if(t.objectForSample.dataPatched.physics.fusedBody)return;e=t.object}else return t.object.dataPatched.physics.fusedBody===!0&&t.object.dataPatched.physics.rigidBody==="dynamic"?!0:void 0;else if(t instanceof Nr)e=t.object;else if(e=t,e.dataPatched.cloner?.hideBase)return!0}else{if(t instanceof Gi)return;t instanceof Nr?e=t.object:e=t}this.data.destroy==="Time"?t.userData.lifetime=this.data.lifetime*1e3:this.data.destroy==="Quantity"&&(t.userData.quantity=this.data.destroyAfterQuantity,t.userData.actionId=this.uniqueId);let r=new E().fromArray(this.data.velocity),i=e.dataPatched;if(!(i.physics.enabled==="visibility"?!i.visible:!i.physics.enabled)&&(this.controlsManager.sharedGameControlGlobals.rapierWorld?(this.controlsManager.addRigidBody(t,e,{fromCreate:!0,dynamic:this.data.dynamic}),this.data.destroy==="Collision"&&(t.rigidBody?.collider(0).setActiveEvents(1),t.userData.hasCollisionDestroy=!0),t.matrixWorld.decompose(HJ,NN,WJ),r.applyQuaternion(NN),this.data.velocity.some(s=>s!==0)&&this.data.dynamic&&t.rigidBody?.setLinvel(r.divideScalar(this.controlsManager.pixelsPerMeter),!0)):("geometry"in t.object&&this.controlsManager.addBoundsTree(t),this.data.velocity.some(s=>s!==0)&&this.data.dynamic&&(t.userData.velocity=r)),e.dataPatched.physics?.fusedBody===!0))return!0};let o=this.page.scene.find(this.data.object);if(!o)throw new Error("Missing Property");if(this.object=o,this.data.coordinateSystem!=="world"&&!this.page.scene.find(this.data.coordinateSystem))throw new Error("Missing Property");LN(r)}dispose(){this.intervalId!==null&&(window.clearInterval(this.intervalId),this.intervalId=null),this.timeoutIdQueue.forEach(t=>window.clearTimeout(t)),this.dispatchThrottled.cancel(),this.page.remove(...this.controlsManager.sharedGameControlGlobals.createdObjects),this.controlsManager.sharedGameControlGlobals.createdObjects=[]}};var YT=200,HT=.02,WT=.3,qJ=65,HWe=new E,FN=new E,VN=new E,YJ=new E,Tn=new E,Un=new E,ac=new E,qT=new ue,kN=new ue,XJ=new ue,WWe=new ue,ro=new Ke,Ha=new Ke,Xo=new nr(0,0,0,"YXZ"),KJ=new E(1,0,0),io=new E(0,1,0),QJ=new E(0,0,1),UN=new E(1,1,1),qWe=new Rr,ZJ=1,JJ=.025,$J=16e-6,zN=12,e$=20,Hi=new Ti,Ms=new Ht,t$={type:"requestRender"},r$={type:"updateMatrix"},GN=Math.PI/6,Ib=class extends pr{constructor(e,r,i,s,o,a,l,c,u){super();this.object=e;this.domElement=r;this.data=i;this.gloabalPhysics=s;this.controlsManager=o;this.cameraFollow=a;this.camera=l;this.page=c;this.sharedAssets=u;this.enableDamping=!0;this.hiddenMatrix0=new ue;this.target0=new E;this.zoom0=1;this.rotForce=1;this.moveForce=1;this.pixelsPerMeter=YT;this.euler0=new nr(0,0,0,"YXZ");this.position0Cam=new E;this.quat0Cam=new Ke;this.scale0Cam=new E;this.hiddenMatrix0Cam=new ue;this.threshEndTranslate=.01;this.threshEndRotate=1e-8;this.threshEndRotVel=.005;this.collider={type:"capsule",radius:40,segment:new Ti(new E(0,-40,0),new E(0,40,0)),matrix:new ue,position:new E,rotation:new Ke};this.euler=new nr(0,0,0,"YXZ");this.eulerDelta=new E;this.lastPosition=new E;this.lastCameraQuaternion=new Ke;this.lastCameraPosition=new E;this.PI_2=Math.PI/2;this.prevMouse=new k;this.velocityTarget=new E;this.velocity=new E;this.directionXZ=new E;this.rotVelocityStick=new E;this.rotVelocityTarget=new E;this.rotVelocity=new E;this.rotDirection=new E;this.nonColliderRotOffset=new ue;this.nonColliderPosOffset=new ue;this.firstPointerId=-1;this.rot=new E;this.path=[];this.movementState={moveNegZ:0,movePosZ:0,moveNegX:0,movePosX:0,moveNegY:0,movePosY:0,rotPosX:0,rotNegX:0,rotPosY:0,rotNegY:0,jump:0,run:0};this.vrEulerYOffset=0;this.onObject=!1;this.actionState={};this.keyAssignments=[["moveNegZ","W"],["moveNegX","A"],["movePosZ","S"],["movePosX","D"],["rotPosX","ArrowUp"],["rotPosY","ArrowLeft"],["rotNegX","ArrowDown"],["rotNegY","ArrowRight"],["jump"," "]];this.collisionEnabled=!0;this.offsetMatrix=new ue;this.objectToTarget=new E;this.objectToTarget0=new E;this.objectToCamXZ=new E;this.objectToCamXZ0=new E;this.targetToCamera=new E;this.targetToCamera0=new E;this.cameraPolarAxis0=new E;this.targetPos=new E;this.targetQuat=new Ke;this.lerpFactorPos=new E().setScalar(.3);this.lerpFactorPosStart=.3;this.lerpFactorPosEnd=.3;this.lerpFactorRotStart=.3;this.lerpFactorRotEnd=.3;this.lerpFactorPosCamera=.3;this.lerpFactorRotCamera=.3;this.objXZQuat=new Ke;this.objXZQuatInv=new Ke;this.objXZRotMat=new ue;this.isFirstPerson=!1;this.didHit=!1;this.groundVelocity=new E;this.pushedVelocity=new E;this.groundYRotation=0;this.objectRealQuat=new Ke;this.colliderWorldQuat=new Ke;this.groundNormal=new E;this.groundTilt=new Ke;this.groundTiltInv=new Ke;this.lastHitObj=null;this.isFirstFrame=!0;this.rotationAccumWhenOrientWithCamera=0;this.navMeshPathDest=null;this.position=new E;this.quaternion=new Ke;this.scale=new E;this.initialAction=!0;this.onPointerDown=e=>{!(e.target===this.domElement||e.target instanceof HTMLElement&&e.target.tagName==="SPLINE-VIEWER"&&e.target.shadowRoot?.contains(this.domElement))||this.firstPointerId!==-1||(this.firstPointerId=e.pointerId,this.domElement.ownerDocument.addEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this.onPointerUp),this.rotBy!=="keys"&&!Ci&&!fA&&this.domElement.requestPointerLock(),this.prevMouse.set(e.clientX,e.clientY))};this.onPointerUp=e=>{this.firstPointerId=-1,this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this.onPointerUp),e.pointerType==="mouse"&&this.domElement.ownerDocument.exitPointerLock()};this.onPointerMove=e=>{if(e.pointerId!==this.firstPointerId)return;let r=e.clientX-this.prevMouse.x,i=e.clientY-this.prevMouse.y;this.prevMouse.set(e.clientX,e.clientY),e.pointerType==="mouse"&&this.rotBy!=="keys"&&(fA&&nI<15.5&&!Ci?(this.eulerDelta.y=-r*this.mouseOrbitSensitivity,this.eulerDelta.x=-i*this.mouseOrbitSensitivity):(this.eulerDelta.y=-e.movementX*this.mouseOrbitSensitivity,this.eulerDelta.x=-e.movementY*this.mouseOrbitSensitivity)),e.pointerType!=="mouse"&&this.rotByTouch==="drag"&&(this.eulerDelta.y=-r*this.mouseOrbitSensitivity*5,this.eulerDelta.x=-i*this.mouseOrbitSensitivity*5),this.controlsManager.requestRender()};this.onPointerlockChange=e=>{this.domElement.ownerDocument.pointerLockElement===this.domElement?Ib.isLocked=!0:Ib.isLocked=!1};this.onPointerlockError=()=>{console.error("SPE.GameControls: Unable to use Pointer Lock API")};this.handleVisibilityChange=()=>{if(document?.hidden)for(let e in this.movementState)this.movementState[e]=0};this.onKeyDown=e=>{!(e.target instanceof HTMLInputElement)&&(e.code==="ArrowLeft"||e.code==="ArrowUp"||e.code==="ArrowRight"||e.code==="ArrowDown"||e.code==="Space")&&e.preventDefault();for(let r of this.keyAssignments)if(e.key.toUpperCase()===r[1]||e.key===r[1]){this.movementState[r[0]]=1;break}this.controlsManager.requestRender()};this.onKeyUp=e=>{for(let r of this.keyAssignments)if(e.key.toUpperCase()===r[1]||e.key===r[1]||e.code.slice(3,e.code.length).toUpperCase()===r[1]){this.movementState[r[0]]=0;break}};this.copyVRGamePadValues=(e,r)=>{for(let i=2;i<4;i++){let s=e.axes[i];r===0?i===2?this.movementState.movePosX=s:this.movementState.movePosZ=s:(e.buttons[3].pressed?this.movementState.jump=1:this.movementState.jump=0,i===2?(Math.abs(this.movementState.rotPosY)<.3&&Math.abs(s)>=.3&&(this.vrEulerYOffset+=s<0?1:-1),this.movementState.rotPosY=s):this.moveMode==="fly"&&(this.movementState.moveNegY=s))}};this.sharedGameControlGlobals=o.sharedGameControlGlobals,e===l&&(this.isFirstPerson=!0),this.hiddenMatrix0.copy(this.object.hiddenMatrix),this.object.parent?this.object.hiddenMatrix.copy(this.object.parent.matrixWorld).invert():this.object.hiddenMatrix.identity(),this.object.matrix.copy(this.object.matrixWorld),this.object.matrix.decompose(this.position,this.quaternion,this.scale),this.euler0.setFromQuaternion(this.quaternion,"YXZ");let h=this.euler0.clone(),d=h.y;if(this.objectRealQuat.copy(this.quaternion),h.y=0,this.quaternion.setFromEuler(h),this.objXZQuat.copy(this.quaternion),this.objXZQuatInv.copy(this.objXZQuat).invert(),this.objXZRotMat.makeRotationFromQuaternion(this.quaternion),h.set(0,d,0),this.quaternion.setFromEuler(h),this.rot.setFromEuler(h),this.object.matrixAutoUpdate=!1,(this.isFirstPerson||this.cameraFollow===!0)&&(this.target0.copy(this.camera.getTarget()),this.zoom0=this.camera.zoom),this.cameraFollow===!0){this.position0Cam.copy(this.camera.position),this.quat0Cam.copy(this.camera.quaternion),this.scale0Cam.copy(this.camera.scale),this.hiddenMatrix0Cam.copy(this.camera.hiddenMatrix),this.camera.parent?(this.camera.hiddenMatrix.copy(this.camera?.parent.matrixWorld),this.camera.matrix.copy(this.camera.matrixWorld)):this.camera.hiddenMatrix.identity(),this.camera.matrix.copy(this.camera.matrixWorld),this.camera.matrix.decompose(this.camera.position,this.camera.quaternion,this.camera.scale),this.camera.matrixAutoUpdate=!1,this.offsetMatrix.copy(this.object.matrix).invert().multiply(this.camera.matrix);let g=new E(0,0,-1).applyQuaternion(this.camera.quaternion),y=new E().subVectors(this.position,this.camera.position);this.objectToCamXZ.copy(y),this.objectToCamXZ.y=0,this.objectToCamXZ0.copy(this.objectToCamXZ);let v,x;Math.abs(g.y)<1e-6?(y.y=0,g.y=0,x=y.projectOnVector(g)):y.y/g.y>0?x=g.multiplyScalar(y.y/g.y):x=g.multiplyScalar(y.length()),this.targetToCamera0.copy(x).negate(),v=this.camera.position.clone().add(x),this.objectToTarget0.subVectors(v,this.position);let S=new nr().setFromQuaternion(this.camera.quaternion,"YXZ");this.cameraPolarOffset=-S.x,S.x=0,S.z=0,S.y-=Math.PI/2,this.cameraPolarAxis0.set(0,0,-1).applyEuler(S)}if(this.object instanceof wr&&(this.object.matrixAutoUpdate=!1),this.euler.setFromQuaternion(this.quaternion,"YXZ"),this.rotByTouch=i.rotByTouch??"joystick",this.rotBy=i.rotBy??"keys",this.rotationMode=i.rotationMode??"normal",this.moveMode=i.moveMode??"walk",this.collisionEnabled=i.collisionEnabled,this.speedTranslate=(i.speedTranslate??250)*ZJ,this.speedOrbit=(i.speedRotate??100)*JJ,this.mouseOrbitSensitivity=(i.speedRotate??100)*$J,this.keyAssignments=i.keyAssignments.map(g=>{let y=[g[0],g[1]];return y[1]==="\u25B2"?y[1]="ArrowUp":y[1]==="\u25C0"?y[1]="ArrowLeft":y[1]==="\u25BC"?y[1]="ArrowDown":y[1]==="\u25B6"?y[1]="ArrowRight":y[1]==="\u21E7"?y[1]="Shift":y[1]==="\u21B5"?y[1]="Enter":y[1]==="Space"?y[1]=" ":y[1]==="\u2318"?y[1]="Meta":y[1]==="Ctrl"?y[1]="Control":y[1]==="Esc"&&(y[1]="Escape"),y}),i.rotBy==="mouse"){let g;g=this.keyAssignments.findIndex(y=>y[0]==="rotNegX"),g!==-1&&(this.keyAssignments[g][1]=""),g=this.keyAssignments.findIndex(y=>y[0]==="rotPosX"),g!==-1&&(this.keyAssignments[g][1]=""),g=this.keyAssignments.findIndex(y=>y[0]==="rotPosY"),g!==-1&&(this.keyAssignments[g][1]=""),g=this.keyAssignments.findIndex(y=>y[0]==="rotNegY"),g!==-1&&(this.keyAssignments[g][1]="")}this.lerpFactorPosStart=1-.02**(1/((i.delayPos[0]??.3)*60)),this.lerpFactorPosEnd=1-.02**(1/((i.delayPos[1]??.3)*60)),this.lerpFactorPos.setScalar(this.lerpFactorPosStart),this.lerpFactorRotStart=1-.02**(1/((i.delayRot[0]??.3)*60)),this.lerpFactorRotEnd=1-.02**(1/((i.delayRot[1]??.3)*60)),this.lerpFactorPosCamera=1-.02**(1/((i.delayPosCamera??.3)*60)),this.lerpFactorRotCamera=1-.02**(1/((i.delayRotCamera??.3)*60)),this.gravity=(this.gloabalPhysics.gravity??Pl.defaultData.gravity)*zN,this.usePhysics=this.gloabalPhysics.usePhysics??Pl.defaultData.usePhysics,this.jumpPower=i.jumpPower*e$,this.resetYPosition=this.position.y+Math.abs(i.resetYPosition)*(this.gravity>0?1:-1),this.alignToGround=i.alignToGround??!1,this.orientMode=i.autoOrientMove?i.orientMode:"none",this.orientWith=i.orientWith??$h.defaultDataThirdPerson.orientWith,this.slopeThresh=qJ*Math.PI/180,i.collider.type==="capsule"?(this.collider.radius=i.collider.radius,this.collider.segment.start.y=i.collider.height/2-i.collider.radius,this.collider.segment.end.y=-this.collider.segment.start.y,this.offset=i.collider.height*HT/this.pixelsPerMeter,this.stepThresh=i.collider.height*WT/this.pixelsPerMeter,this.colliderHeight=i.collider.height):i.collider.type==="sphere"?(this.collider.radius=i.collider.radius,this.collider.segment.start.y=0,this.collider.segment.end.y=0,this.offset=2*i.collider.radius*HT/this.pixelsPerMeter,this.stepThresh=2*i.collider.radius*WT/this.pixelsPerMeter,this.colliderHeight=i.collider.radius*2):(this.offset=i.collider.height*HT/this.pixelsPerMeter,this.stepThresh=i.collider.height*WT/this.pixelsPerMeter,this.colliderHeight=i.collider.height),this.collider.type=i.collider.type;let f=new E().fromArray(i.collider.position),p=new Ke().setFromEuler(new nr().fromArray([...i.collider.rotation,"XYZ"]));this.collider.position.copy(f).multiply(this.scale),this.collider.rotation.copy(p),this.collider.matrix.compose(f,p,UN),i.cameraXAxis!==void 0&&(this.cameraXAxis=i.cameraXAxis,this.cameraYAxis=i.cameraYAxis,this.minPolarAngle=i.cameraRotXLimits[0],this.maxPolarAngle=i.cameraRotXLimits[1],this.minAzimuthAngleRel=i.cameraRotYLimits[0],this.maxAzimuthAngleRel=i.cameraRotYLimits[1]),this.forwardDir=i.forwardDirection??"-z",this.isFirstPerson&&(this.forwardDir="-z"),this.runMultiplier=i.runMultiplier??2;let m=i.navmesh.destinationHelperRadius*2;if(m>0){let g=new ke;g.push({fi:0,data:{...Gr.defaultData("light","phong"),alpha:0},id:"layer1"}),g.push({fi:0,data:{...Gr.defaultData("color"),color:i.navmesh.destinationHelperColor,alpha:i.navmesh.destinationHelperColor.a},id:"layer2"});let y=new Ba({layers:g},{scene:this.page.scene,shared:this.sharedAssets});this.navMeshPathDest=new Ut(C0.create({parameters:{width:m,height:m/10,hollow:.7}}),y),this.navMeshPathDest.material.userData.opacity0=i.navmesh.destinationHelperColor.a}this.activate()}reset(e=!1){if(this.object.hiddenMatrix.copy(this.hiddenMatrix0),e){this.object.updateMatrix(),this.object.updateMatrixWorld(),this.object.matrix.copy(this.object.matrixWorld),this.object.matrix.decompose(this.position,this.quaternion,this.scale),this.object.parent?this.object.hiddenMatrix.copy(this.object.parent.matrixWorld).invert():this.object.hiddenMatrix.identity();let r=new nr().setFromQuaternion(this.quaternion,"YXZ"),i=r.y;this.objectRealQuat.copy(this.quaternion),r.y=0,this.quaternion.setFromEuler(r),this.objXZQuat.copy(this.quaternion),this.objXZQuatInv.copy(this.objXZQuat).invert(),this.objXZRotMat.makeRotationFromQuaternion(this.quaternion),r.set(0,i,0),this.quaternion.setFromEuler(r),this.rot.setFromEuler(r),this.euler.setFromQuaternion(this.quaternion,"YXZ"),this.velocityTarget.set(0,0,0),this.velocity.set(0,0,0)}else this.object instanceof wr?this.object.matrixAutoUpdate=!0:this.object.updateMatrix();this.cameraFollow===!0&&(this.camera.quaternion.copy(this.quat0Cam),this.camera.position.copy(this.position0Cam),this.camera.scale.copy(this.scale0Cam),this.camera.hiddenMatrix.copy(this.hiddenMatrix0Cam),this.camera.matrixAutoUpdate=!0),this.controlsManager.requestRender()}activate(){this.instantiateActions(),this.domElement.ownerDocument.addEventListener("pointerdown",this.onPointerDown),this.domElement.ownerDocument.addEventListener("keydown",this.onKeyDown),this.domElement.ownerDocument.addEventListener("keyup",this.onKeyUp),this.domElement.ownerDocument.addEventListener("pointerlockchange",this.onPointerlockChange),this.domElement.ownerDocument.addEventListener("pointerlockerror",this.onPointerlockError),this.domElement.ownerDocument.addEventListener("visibilitychange",this.handleVisibilityChange)}deactivate(){this.disposeActions(),this.domElement.ownerDocument.removeEventListener("pointerdown",this.onPointerDown),this.domElement.ownerDocument.removeEventListener("keydown",this.onKeyDown),this.domElement.ownerDocument.removeEventListener("keyup",this.onKeyUp),this.domElement.ownerDocument.removeEventListener("pointerlockchange",this.onPointerlockChange),this.domElement.ownerDocument.removeEventListener("pointerlockerror",this.onPointerlockError),this.domElement.ownerDocument.removeEventListener("visibilitychange",this.handleVisibilityChange)}dispose(){this.deactivate(),this.navMeshPathDest?.parent&&this.page.remove(this.navMeshPathDest)}instantiateActions(){let e=this.data,r=this.sharedAssets;e.gameActions!==void 0&&(this.actions={},Jh.list.forEach(i=>{this.actions[i]=kt({...e,disabled:!1,type:"GameControl"},e.gameActions[i],this.page,r,this.controlsManager.eventManager,this.object)})),this.dispatchStopEvent("move"),this.dispatchStopEvent("run"),this.dispatchStopEvent("jump"),this.dispatchStartEvent("idle"),this.initialAction&&(this.initialAction=!1)}disposeActions(){this.initialAction=!1,this.dispatchStopEvent("idle"),this.dispatchStopEvent("move"),this.dispatchStopEvent("run"),this.dispatchStopEvent("jump"),hr(this.actions.idle),hr(this.actions.move),hr(this.actions.run),hr(this.actions.jump)}dispatchStartEvent(e){this.actions[e]!==void 0&&(this.actionState[e]||(this.actionState[e]=!0,this.actions[e].Transition.forEach(r=>{r.play()}),this.actions[e].Animation.forEach(r=>{r.play(this.initialAction===!1)}),this.actions[e].Create.forEach(r=>{r.dispatchStart()}),this.actions[e].Audio.forEach(r=>{r.dispatchGameControl("start")}),this.actions[e].Particles.forEach(r=>{r.dispatchGameControl("start")})))}dispatchStopEvent(e){this.actions[e]!==void 0&&(!this.actionState[e]||(this.actionState[e]=!1,this.actions[e].Transition.forEach(r=>{r.stop(),r.object.currentState!==null&&r.object.changeSelectedState(null,{scene:this.page.scene,shared:this.sharedAssets})}),this.actions[e].Create.forEach(r=>{r.dispatchStop()}),this.actions[e].Audio.forEach(r=>{r.dispatchGameControl("stop")}),this.actions[e].Particles.forEach(r=>{r.dispatchGameControl("stop")})))}get colliderWorldPosition(){return Tn.copy(this.collider.position).applyQuaternion(this.objectRealQuat).add(this.position)}update(e,r,i){if(this.gravity<0?this.position.ythis.resetYPosition)return this.reset(!0),!0;this.sharedGameControlGlobals.gamePads.forEach(this.copyVRGamePadValues);let s=(this.isFirstFrame?16.6:e)/1e3;this.isFirstFrame&&(this.isFirstFrame=!1);let o=s*60,a=!1;if(this.usePhysics&&this.collisionEnabled){let c=Un.set(0,(this.velocity.y===0?this.pixelsPerMeter*Math.max(Math.abs(this.gravity)/(10*zN),1)*(this.gravity>0?1:-1):this.velocity.y)*s,0).divideScalar(this.pixelsPerMeter),u=this.sharedGameControlGlobals.rapierWorld.castShape(this.colliderWorldPosition.divideScalar(this.pixelsPerMeter),this.colliderWorldQuat,c,this.object.rigidBody?.collider(0).shape,1,!1,16,void 0,void 0,this.object.rigidBody);if(u){this.onObject=!0,this.groundNormal.set(u.normal2.x,u.normal2.y,u.normal2.z).applyQuaternion(this.colliderWorldQuat).negate(),this.alignToGround&&this.groundTiltAdjustment(this.groundNormal),Math.acos(this.groundNormal.y)45&&(this.onObject=!1);let h=u.collider.parent();this.groundYRotation=0,this.groundVelocity.set(0,0,0);for(let d of this.sharedGameControlGlobals.entitiesWithTransformAnim)if(d.rigidBody===h&&d.userData.isFollowingObj!==this.object.uuid){(d.hasNonUniformScale?d.matrixWorldRigid:d.matrixWorld).decompose(Tn,Ha,Un),this.groundVelocity.subVectors(Tn,d.prevT),this.object.getWorldPosition(Un).add(this.collider.position).sub(Tn),this.groundYRotation=Xo.setFromQuaternion(Ha).y-d.prevR.y,ac.copy(Un).applyAxisAngle(io,this.groundYRotation),this.groundVelocity.add(ac.sub(Un)).divideScalar(s);break}}else this.onObject=!1}if(this.moveMode==="walk"&&this.collisionEnabled&&(this.movementState.jump===1&&this.onObject&&(this.velocityTarget.y=this.jumpPower,this.movementState.jump=0,this.dispatchStopEvent("idle"),this.dispatchStopEvent("move"),this.dispatchStopEvent("run"),this.dispatchStopEvent("jump"),this.dispatchStartEvent("jump"),this.onObject=!1),this.onObject?this.velocityTarget.y/=2:this.velocityTarget.y+=this.gravity*o),this.moveMode==="fly"&&(this.velocityTarget.y=(this.movementState.movePosY-this.movementState.moveNegY)*this.speedTranslate),this.directionXZ.z=this.movementState.movePosZ-this.movementState.moveNegZ,this.directionXZ.x=this.movementState.movePosX-this.movementState.moveNegX,this.forwardDir==="+z"&&this.directionXZ.multiplyScalar(-1),this.directionXZ.manhattanLength()>0&&(this.path=[]),this.navMeshPathDest){let c=this.navMeshPathDest.material;if(this.moveMode==="walk"&&this.path.length>1){this.navMeshPathDest.position.copy(this.path[this.path.length-1]),this.navMeshPathDest.parent||this.page.add(this.navMeshPathDest);let u=Tn.subVectors(this.path[1],this.position),h=Un.subVectors(this.path[1],this.path[0]);u.dot(h)<0?this.path.shift():(this.directionXZ.x=h.x,this.directionXZ.z=h.z),c.opacity=c.userData.opacity0}else c.opacity-=.05*c.userData.opacity0,this.navMeshPathDest.material.opacity<=0&&this.navMeshPathDest.parent&&this.page.remove(this.navMeshPathDest)}this.directionXZ.normalize(),this.movementState.run?this.moveForce=this.runMultiplier:this.moveForce=1,this.velocityTarget.z=this.directionXZ.z*this.speedTranslate*this.moveForce,this.velocityTarget.x=this.directionXZ.x*this.speedTranslate*this.moveForce,(this.moveMode==="walk"?this.velocityTarget.x+this.velocityTarget.z===0:this.velocityTarget.manhattanLength()===0)?this.lerpFactorPos.setScalar(this.lerpFactorPosEnd):this.lerpFactorPos.setScalar(this.lerpFactorPosStart),this.moveMode==="walk"&&(this.lerpFactorPos.y=1),this.didHit===!1&&this.pushedVelocity.manhattanLength()===0||this.usePhysics===!1?(this.velocity.x+=(this.velocityTarget.x-this.velocity.x)*(1-(1-this.lerpFactorPos.x)**o),this.velocity.y+=(this.velocityTarget.y-this.velocity.y)*(1-(1-this.lerpFactorPos.y)**o),this.velocity.z+=(this.velocityTarget.z-this.velocity.z)*(1-(1-this.lerpFactorPos.z)**o)):this.velocity.copy(this.velocityTarget),(this.moveMode==="walk"?this.velocity.x**2+this.velocity.z**20&&this.orientMode!=="none"&&this.isFirstPerson===!1)if(this.orientWith==="camera"&&this.path.length<=1){let c=Tn;this.camera.getWorldDirection(c);let u=ac.copy(io).multiplyScalar(c.dot(io));c.sub(u);let h=Un.copy(this.directionXZ);h.x*=-1,this.rot.y=c.angleTo(h)*(c.cross(h).y>0?-1:1)+this.rotationAccumWhenOrientWithCamera}else this.rot.y=(this.path.length>1?0:this.euler.y)+Math.atan2(-this.directionXZ.z,this.directionXZ.x)+Math.PI/2*(this.forwardDir==="+z"?1:-1);if(Xo.setFromVector3(this.rot),this.moveMode==="walk"&&(Xo.x=0),l.applyEuler(Xo),a&&(Ha.setFromUnitVectors(io,this.groundNormal),l.applyQuaternion(Ha)),i){let c=Xo.set(0,this.vrEulerYOffset*GN,0);i.applyEuler(c),l.x+=i.x,l.z+=i.z,this.nonColliderPosOffset.elements[13]+=i.y*s}if(this.usePhysics===!0){let c=Un;this.pushedVelocity.set(0,0,0);for(let u of this.sharedGameControlGlobals.entitiesWithTransformAnim){let h=ac.setFromMatrixPosition(u.matrixWorld).sub(u.prevT).divideScalar(s).divideScalar(this.pixelsPerMeter),d=u.rigidBody.collider(0).castCollider(h,this.object.rigidBody.collider(0),Tn.copy(l).divideScalar(this.pixelsPerMeter),s,!1);h.multiplyScalar(this.pixelsPerMeter);let f=yt.is(u)?u:u.object;if(d!==null&&this.lastHitObj!==f){let p;u instanceof Nr&&(p=u);let m=this.sharedGameControlGlobals.entityToCollisionEvents[f.uuid];if(m)for(let g of m)g.data.target==="character"&&(g.dispatch(p),f.dispatchEvent(Db));this.lastHitObj=f}if(d!==null){this.pushedVelocity.copy(h),c.copy(d.normal1).applyQuaternion(u.quaternion);break}}if(this.pushedVelocity.manhattanLength()!==0){let u=c.dot(l);u<0&&l.addScaledVector(c,-u),l.add(this.pushedVelocity)}else l.add(this.groundVelocity)}if(this.rotDirection.y=Number(this.movementState.rotPosY)-Number(this.movementState.rotNegY),this.rotDirection.x=Number(this.movementState.rotPosX)-Number(this.movementState.rotNegX),this.rotDirection.normalize(),this.rotationMode==="normal"&&(this.movementState.rotPosX||this.movementState.rotNegX)||this.rotationMode==="steer"&&(this.movementState.rotPosX||this.movementState.rotNegX)&&(this.movementState.movePosZ||this.movementState.moveNegZ||this.moveMode==="walk")?this.rotVelocityStick.x=-this.rotDirection.x*this.speedOrbit*this.rotForce:this.rotVelocityStick.x=0,this.rotationMode==="normal"&&(this.movementState.rotPosY||this.movementState.rotNegY)||this.rotationMode==="steer"&&(this.movementState.rotPosY||this.movementState.rotNegY)&&(this.movementState.movePosZ||this.movementState.moveNegZ)?this.rotVelocityStick.y=-this.rotDirection.y*this.speedOrbit*this.rotForce:this.rotVelocityStick.y=0,this.rotVelocityTarget.subVectors(this.eulerDelta.divideScalar(s),this.rotVelocityStick),this.rotVelocityTarget.manhattanLength()===0?this.rotVelocity.lerp(this.rotVelocityTarget,1-(1-this.lerpFactorRotEnd)**o):this.rotVelocity.lerp(this.rotVelocityTarget,1-(1-this.lerpFactorRotStart)**o),this.euler.x+=this.rotVelocity.x*s,this.euler.y+=this.rotVelocity.y*s+this.groundYRotation,this.rotVelocityTarget.y===0&&this.directionXZ.manhattanLength()===0?this.rotationAccumWhenOrientWithCamera=0:(this.cameraFollow===!1||this.cameraYAxis==="Locked")&&(this.rotationAccumWhenOrientWithCamera+=this.rotVelocity.y*s),this.isFirstPerson===!1&&this.orientMode!=="none"&&this.directionXZ.manhattanLength()>0){if(this.orientMode==="radial"){this.objectToCamXZ.copy(this.objectToCamXZ0).applyAxisAngle(io,this.euler.y-this.euler0.y);let c=Un.copy(this.objectToCamXZ).normalize(),u=ac.copy(l).multiplyScalar(s);u.y=0;let h=u.sub(Tn.copy(c).multiplyScalar(u.dot(c))).cross(c).y;this.euler.y-=Math.atan2(h,this.objectToCamXZ.length())}}else this.rot.y+=this.rotVelocity.y*s+this.groundYRotation,this.rotVelocityTarget.y!==0&&(this.cameraFollow===!1||this.cameraYAxis==="Locked")&&(this.euler.y=this.rot.y);if(this.cameraFollow===!0&&(this.moveMode==="walk"?this.cameraXAxis==="Limit"?this.euler.x=we.clamp(this.euler.x,-this.maxPolarAngle+this.cameraPolarOffset+1e-6,-this.minPolarAngle+this.cameraPolarOffset-1e-6):this.euler.x=we.clamp(this.euler.x,-this.PI_2+this.cameraPolarOffset,this.PI_2+this.cameraPolarOffset):this.cameraXAxis==="Limit"&&(this.euler.x=we.clamp(this.euler.x,-this.PI_2,this.PI_2))),this.moveMode==="fly"?this.rot.x=this.euler.x:this.isFirstPerson&&(r?(Xo.copy(r),Xo.y=0):(Xo.copy(this.euler),Xo.y=0),this.nonColliderRotOffset.makeRotationFromEuler(Xo)),r&&(this.moveMode==="walk"?(this.rot.y=r.y,this.rot.x=0,this.rot.z=0):this.rot.setFromEuler(r),this.rot.y+=this.vrEulerYOffset*GN),ro.setFromAxisAngle(KJ,this.rot.x),Ha.setFromAxisAngle(io,this.rot.y),Ha.multiply(ro),ro.setFromAxisAngle(QJ,this.rot.z),Ha.multiply(ro),this.quaternion.copy(Ha),this.objectRealQuat.multiplyQuaternions(this.quaternion,this.objXZQuat),this.colliderWorldQuat.copy(this.objectRealQuat).multiply(this.collider.rotation),this.collisionEnabled)if(this.usePhysics){let c=Un.copy(l).multiplyScalar(s/this.pixelsPerMeter),u=null;this.didHit=!1;let h=new E;for(let d=0;d<5;d++){let f=c.length(),p=ac.copy(c).normalize();if(u=this.sharedGameControlGlobals.rapierWorld.castShape(this.colliderWorldPosition.divideScalar(this.pixelsPerMeter).add(h),this.colliderWorldQuat,p,this.object.rigidBody?.collider(0).shape,f,!1,24,void 0,void 0,this.object.rigidBody),u!==null){this.didHit=!0;let m=this.sharedGameControlGlobals.colliderToEntity.get(u.collider.handle);if(m!==this.lastHitObj&&d===0){this.lastHitObj=m;let x=this.sharedGameControlGlobals.entityToCollisionEvents[m?.uuid];if(x){for(let S of x)if(S.data.target==="character"){let w=(this.sharedGameControlGlobals.rapierWorld?.getCollider(u.collider.handle))._parent,A;if(m.cloner){for(let T of m.cloner.children)if(T.rigidBody===w){A=T;break}}S.dispatch(A),m.dispatchEvent(Db)}}}let g=FN.set(u.normal2.x,u.normal2.y,u.normal2.z).applyQuaternion(this.colliderWorldQuat),y=VN.copy(p).multiplyScalar(u.toi).dot(g),v=u.toi;if(v===0&&(this.position.y+=this.offset*this.pixelsPerMeter),y>this.offset&&(v=u.toi*(y-this.offset)/y,h.addScaledVector(p,v)),c.copy(p).multiplyScalar(f-v),Math.acos(-g.y)>this.slopeThresh){let x=this.colliderWorldPosition.divideScalar(this.pixelsPerMeter).add(h),S=ac.copy(u.witness2).applyQuaternion(this.colliderWorldQuat);S.y=0;let w=x.add(S);w.y+=this.stepThresh;let A=this.sharedGameControlGlobals.rapierWorld.castShape(w,this.colliderWorldQuat,c,this.object.rigidBody?.collider(0).shape,1,!1,24,void 0,void 0,this.object.rigidBody);A!==null&&A.toi===0&&(g.y=0,g.normalize())}c.addScaledVector(g,-c.dot(g))}else{d===0&&this.directionXZ.manhattanLength()!==0&&(this.lastHitObj=null),h.add(c);break}}this.position.addScaledVector(h,this.pixelsPerMeter),this.object.rigidBody?.setTranslation(Tn.copy(this.position).divideScalar(this.pixelsPerMeter),!0),this.object.rigidBody?.setRotation(ro.copy(this.quaternion).premultiply(this.groundTilt).multiply(this.objXZQuat),!0)}else{let c=this.onObject?1:5,u=l.multiplyScalar(s/c);for(let h=0;h0?this.cameraPolarOffset:0))}return this.eulerDelta.set(0,0,0),this.object.dispatchEvent(r$),this.path.length<2&&this.lastPosition.distanceToSquared(this.position)85?ro.identity():ro.setFromUnitVectors(io,e),this.groundTilt.slerp(ro,.06),this.groundTiltInv.copy(this.groundTilt).invert()}collisionAdjustment(e){let r=VN.set(0,0,0);this.object.matrix.compose(this.position,this.quaternion,this.scale);let i=qT.multiplyMatrices(this.object.matrix,this.objXZRotMat).multiply(this.collider.matrix).decompose(Tn,ro,Un).compose(Tn,ro,UN);this.sharedGameControlGlobals.entitiesWithTransformAnim.forEach(o=>{if(o===this.object||o.isDescendantOf(this.object))return;Ms.makeEmpty(),o.updateMatrixWorldSVD();let a=o.matrixWorldRigid,l=kN.copy(a).invert(),c=XJ.copy(kN).multiply(i);Hi.copy(this.collider.segment),Hi.start.applyMatrix4(c),Hi.end.applyMatrix4(c);let u=FN.copy(this.position).applyMatrix4(l);Ms.expandByPoint(Hi.start),Ms.expandByPoint(Hi.end),Ms.min.addScalar(-this.collider.radius),Ms.max.addScalar(this.collider.radius),o.bvhGeometry.boundsTree.shapecast({traverseBoundsOrder(h){return h.distanceToPoint(Hi.end)},intersectsBounds:h=>h.intersectsBox(Ms),intersectsTriangle:h=>{let d=Tn,f=Un,p=h.closestPointToSegment(Hi,d,f);if(po.intersectsBox(Ms),intersectsTriangle:o=>{let a=Tn,l=Un,c=o.closestPointToSegment(Hi,a,l);if(cMath.abs(e*this.velocity.y*.25),this.onObject&&this.dispatchStopEvent("jump");let s=Math.max(0,r.length()-1e-5);r.normalize().multiplyScalar(s),this.position.add(r)}},yg=Ib;yg.isLocked=!1;var jN=ta(v1());function no(n,t){let e=new _e;if(t){let s=t.elements,o=s[0]**2+s[1]**2+s[2]**2,a=s[4]**2+s[5]**2+s[6]**2,l=s[8]**2+s[9]**2+s[10]**2,c=s[0]**2+s[4]**2+s[8]**2,u=s[1]**2+s[5]**2+s[9]**2,h=s[2]**2+s[6]**2+s[10]**2,d=1e-8;if(o{i.visible&&this.intersectObject(i,e,r)}),r}createRaycastLineHelper(){let t=new ss({color:65280,linewidth:10}),e=new E(this.ray.origin.x,this.ray.origin.y,this.ray.origin.z),r=new E(this.ray.direction.x,this.ray.direction.y,this.ray.direction.z),i=this.camera.far-this.camera.near,s=new E().addVectors(e,r.multiplyScalar(i)),o=new _e;return o.setFromPoints([e,s]),new wc(o,t)}};var HN=n=>n instanceof As||n instanceof eo;function s$(n,t){return n.distance-t.distance}function WN(n,t,e){if(!(!Ro(t)||!t.visible)){cn(t)&&t.raycast(n,e);for(let r of t.children)WN(n,r,e)}}function zf(n,t,e,r=!1){if(!r&&!e.some(s=>Gf(n,s)!==void 0))return[];let i=[];return t.children.forEach(s=>WN(n,s,i)),i.sort(s$),i}function vg(n){let t=[];if(n.length){let e=n[0].object;Ro(e)&&t.push(e);let r=e.parent;for(;r;)HN(r)&&t.push(r),r=r.parent}return t}function so(n,t,e,r){let i=n.frame;if(i){let s=t[0]*i.width,o=(1-t[1])*i.height;for(let a of e){let l=a===i.uuid?i:i.find(a);if(l?.intersects(s,o))return r(l),!0}}return!1}function Gf(n,t){if(cn(t)){if(t.visible){let e=[];return t.raycast(n,e),e.length?e[0]:void 0}}else if(HN(t))return qN(n,t)}function qN(n,t){if(!(!Ro(t)||!t.visible)){if(cn(t)){let e=[];if(t.raycast(n,e),e.length)return e[0]}for(let e of t.children){let r=qN(n,e);if(r)return r}}}function o$(n,t,e){return{x:(n-(e.left+window.scrollX))/e.width*2-1,y:-((t-(e.top+window.scrollY))/e.height)*2+1}}function a$(n,t,e){return{x:(n-(e.left+window.scrollX))/e.width,y:1-(t-(e.top+window.scrollY))/e.height}}var Rb=class{constructor(t,e,r,i,s,o,a,l){this.renderer=t;this.publish=e;this.scene=r;this.getCamera=i;this.sharedAssets=s;this.requestRender=o;this.isExport=a;this.frame=l;this.raycaster=new Ob;this._useWindowEvents=!1;this.pointerWorld={x:0,y:0};this.pointerScreen={x:0,y:0};this._useWindowEvents=e.mouseEventTarget==="window",this.domElement=t.domElement,this.eventElement=this._useWindowEvents?window:t.domElement,this._domRect=this.domElement.getBoundingClientRect()}get stopRaycast(){return this.publish.stopRaycast}get page(){return this.scene.activePage}set useWindowEvents(t){this._useWindowEvents=t,this.eventElement=t?window:this.renderer.domElement}get useWindowEvents(){return this._useWindowEvents}set domRect(t){this._domRect=t}get domRect(){return this._domRect}updateRaycaster(t){let{pageX:e,pageY:r}=t.touches?.length>0?t.touches[0]:t;this.pointerWorld=o$(e,r,this._domRect),this.pointerScreen=a$(e,r,this._domRect),this.raycaster.setFromCamera(this.pointerWorld,this.getCamera())}};var Yt=class{constructor(t){this.eventContext=t;this.domEventsNeeded=new Set;this.hasVideoAction=!1}connect(){}disconnect(){}};var KT=[["start","Start"],["keyDown","KeyDown"],["keyUp","KeyUp"],["mouseDown","MouseDown"],["mouseUp","MouseUp"],["mouseHover","MouseHover"],["collision","Collision"],["lookAt","LookAt"],["follow","Follow"],["scroll","Scroll"]],YN=n=>KT.find(([t,e])=>e===n)?.[0],Qo=n=>KT.find(([t])=>t===n)?.[1],l$=(n,t)=>{let e=YN(n);if(e){let r=new CustomEvent(e,{bubbles:!0});return Object.defineProperty(r,"target",{writable:!1,value:t}),r}},Lb=class extends Yt{constructor(){super(...arguments);this.objectsPerEvents=new Map;this.splineEvents={};this.onBeginEvent=e=>{if(!e.eventName||!e.target||e.eventName==="Scroll")return;let r=this.splineEvents[YN(e.eventName)]?.[e.target.uuid];if(!r)return;e.eventName==="Scroll"&&e.deltaY!==void 0&&Object.assign(r,{deltaY:e.deltaY});let{domElement:i}=this.eventContext;i.dispatchEvent(r)}}connect(){let{page:e}=this.eventContext;e.traverseEntity(r=>{if(!!r.data?.events.length){for(let[i,s]of KT)if(r.data.events.some(o=>o.data.type===s&&!o.data.disabled)){this.objectsPerEvents.has(i)?this.objectsPerEvents.get(i)?.push(r):this.objectsPerEvents.set(i,[r]);let o={id:r.uuid,name:r.name},a=l$(s,o),l=this.splineEvents[i];l?l[r.uuid]=a:this.splineEvents[i]={[r.uuid]:a}}}}),this.objectsPerEvents.forEach(r=>{r.forEach(i=>{i.addEventListener("beginEvent",this.onBeginEvent)})})}disconnect(){this.objectsPerEvents.forEach(e=>{e.forEach(r=>{r.removeEventListener("beginEvent",this.onBeginEvent)})})}};var QT=class{constructor(t,e,r,i,s,o){this.id=t;this.data=e;this.object=r;this.entered=!1;if((e.type==="KeyDown"||e.type==="KeyUp"||e.type==="KeyPress")&&!e.key)throw new Error("Missing property");this.actions=kt(e,e.actions,i,s,o,r)}disconnect(){hr(this.actions)}dispatchHeld(t){this.actions.Create.forEach(e=>{t&&e.dispatchThrottled.cancel(),e.dispatchThrottled()})}dispatch(t=!1){this.actions.Transition.forEach(e=>{e.object.currentTransitionEvent!==this&&(e.object.currentTransitionEvent=this,e.init())}),this.data.type==="MousePress"||this.data.type==="KeyPress"?this.entered||(this.entered=!0,this.actions.Transition.forEach(e=>e.playFromCurrent()),this.actions.Animation.forEach(e=>e.playFromCurrent()),this.actions.SwitchCamera.forEach(e=>e.playFromCurrent()),this.actions.Create.forEach(e=>e.dispatchStart())):(this.actions.Transition.some(i=>i.playing&&i.data.runMode!=="Toggle")||this.actions.Transition.forEach(i=>{i.data.runMode==="Toggle"?i.toggle():i.play()}),this.actions.SwitchCamera.some(i=>i.playing&&i.data.runMode!=="Toggle")||this.actions.SwitchCamera.forEach(i=>{i.data.runMode==="Toggle"?i.toggle():i.play()}),this.actions.Animation.forEach(i=>{i.data.runMode==="Toggle"?i.toggle():i.play()})),this.actions.Link.forEach(e=>{e.dispatch()}),this.actions.SceneTransition.forEach(e=>{e.dispatch()}),t===!1&&this.actions.Create.forEach(e=>{e.dispatch()}),this.actions.Destroy.forEach(e=>{e.dispatch()}),this.actions.Reset.forEach(e=>{e.dispatch()}),this.actions.Audio.forEach(e=>{e.dispatchBasic()}),this.actions.Video.forEach(e=>{e.dispatchBasic()}),this.actions.Particles.forEach(e=>{e.dispatchBasic()}),this.actions.SetVariable.forEach(e=>e.checkConditions()),this.actions.SetVariable.forEach(e=>e.dispatch()),this.actions.DynamicVariablePlay.forEach(e=>e.dispatch()),this.actions.ClearLocalStorage.forEach(e=>e.dispatch()),this.actions.UserAPI.forEach(e=>e.dispatch())}dispatchRelease(){this.entered&&(this.entered=!1,this.actions.Transition.forEach(t=>t.reverseFromCurrent()),this.actions.Particles.forEach(t=>t.reverseFromCurrent()),this.actions.Animation.forEach(t=>t.reverseFromCurrent()),this.actions.SwitchCamera.forEach(t=>t.reverseFromCurrent()),this.actions.Create.forEach(t=>t.dispatchStop()))}dispatchUserEvent(t){this.actions.Transition.forEach(e=>{e.object.currentTransitionEvent!==this&&(e.object.currentTransitionEvent=this,e.init())}),t?(this.actions.Transition.forEach(e=>e.reverseFromCurrent()),this.actions.Animation.forEach(e=>e.reverseFromCurrent()),this.actions.SwitchCamera.forEach(e=>e.reverseFromCurrent())):(this.actions.Transition.forEach(e=>e.playFromCurrent()),this.actions.Animation.forEach(e=>e.playFromCurrent()),this.actions.SwitchCamera.forEach(e=>e.playFromCurrent())),this.actions.Link.forEach(e=>{e.dispatch()}),this.actions.SceneTransition.forEach(e=>{e.dispatch()}),this.actions.Create.forEach(e=>{e.dispatch()}),this.actions.Destroy.forEach(e=>{e.dispatch()}),this.actions.Reset.forEach(e=>{e.dispatch()}),this.actions.Audio.forEach(e=>{e.dispatchBasic()}),this.actions.Video.forEach(e=>{e.dispatchBasic()}),this.actions.Particles.forEach(e=>{e.dispatchBasic()}),this.actions.SetVariable.forEach(e=>e.checkConditions()),this.actions.SetVariable.forEach(e=>e.dispatch()),this.actions.DynamicVariablePlay.forEach(e=>e.dispatch()),this.actions.ClearLocalStorage.forEach(e=>e.dispatch()),this.actions.UserAPI.forEach(e=>e.dispatch())}},Bb=class extends Yt{constructor(e,r,i){super(e);this.eventManager=r;this.useForRaycastProperty=i;this.objectsPerTypes={MouseDown:[],MouseUp:[],MousePress:[],KeyDown:[],KeyUp:[],KeyPress:[]};this.canvasMouseEvents=[];this.eventsPerObjects={MouseDown:{},MouseUp:{},MousePress:{},KeyDown:{},KeyUp:{},KeyPress:{}};this.heldKeys={};this.heldKeysPress={};this._prevObjects=[];this.sceneInterects=null;this.onCanvasRaycast=e=>{if(this.useForRaycastProperty===!0&&this.sceneInterects===null){this.eventContext.updateRaycaster(e);let{raycaster:r,page:i}=this.eventContext,s=zf(r,i,[],!0);this.sceneInterects=s,s.length&&(this.eventContext.sharedAssets.raycastProperty={x:s[0].point.x,y:s[0].point.y,z:s[0].point.z,objX:s[0].object.matrixWorld.elements[12],objY:s[0].object.matrixWorld.elements[13],objZ:s[0].object.matrixWorld.elements[14]})}};this.onCanvasMouseDown=e=>{(e.target===this.eventContext.domElement||e.target.tagName==="SPLINE-VIEWER")&&this.canvasMouseEvents.forEach(r=>{(r.data.type==="MouseDown"||r.data.type==="MousePress")&&(this.onCanvasRaycast(e),r.dispatch())})};this.onCanvasMouseUp=e=>{(e.target===this.eventContext.domElement||e.target.tagName==="SPLINE-VIEWER")&&this.canvasMouseEvents.forEach(r=>{r.data.type==="MouseUp"?(this.onCanvasRaycast(e),r.dispatch()):r.data.type==="MousePress"&&r.dispatchRelease()})};this.onMouseDown=e=>{Je.length>1||(this.eventContext.updateRaycaster(e),this.handleMouseEvent("MouseDown"))};this.onMouseUp=e=>{Je.length>1||(this.eventContext.updateRaycaster(e),this.handleMouseEvent("MouseUp"))};this.onMousePressDown=e=>{Je.length>1||(this.eventContext.updateRaycaster(e),this.handleMousePressEvent())};this.onMousePressRelease=e=>{Je.length>1||(this.eventContext.updateRaycaster(e),this.handleMousePressEvent(!0))};this.onKeyDown=e=>{this.heldKeys[e.key]||(this.handleKeyEvent(e,"KeyDown"),this.handleKeyEventHeld(e,"KeyDown",!0)),this.heldKeys[e.key]=!0};this.onKeyUp=e=>{this.handleKeyEvent(e,"KeyUp"),this.handleKeyEventHeld(e,"KeyUp",!0)};this.onKeyPressDown=e=>{this.heldKeysPress[e.key]?this.handleKeyEventHeld(e,"KeyPress"):(this.handleKeyEvent(e,"KeyPress"),this.handleKeyEventHeld(e,"KeyPress",!0)),this.heldKeysPress[e.key]=!0};this.onKeyPressUp=e=>{this.handleKeyEvent(e,"KeyPress",!0)};this.releaseHeldKey=e=>{delete this.heldKeys[e.key]};this.releaseHeldKeyPress=e=>{delete this.heldKeysPress[e.key]};this._onUserEvent=({eventName:e,target:r,reverse:i})=>{if(!e||!r)return;let s=Qo(e);s&&(s==="MouseDown"||s==="MouseUp"||s==="MousePress"?(r.dispatchEvent({type:"beginEvent",eventName:s}),this.eventsPerObjects[s]?.[r.uuid]?.forEach(o=>{o.dispatchUserEvent(i)})):(s==="KeyDown"||s==="KeyUp"||s==="KeyPress")&&(r.dispatchEvent({type:"beginEvent",eventName:s}),this.eventsPerObjects[s]?.[r.uuid]?.forEach(o=>{o.dispatchUserEvent()})))}}connect(){let{page:e,sharedAssets:r,domElement:i}=this.eventContext,s=(o,a)=>{if(!o.data?.events.length)return;let l=["MouseDown","MouseUp","MousePress","KeyDown","KeyUp","KeyPress"];for(let c of l){let u=this.eventsPerObjects[c];o.data.events.filter(({data:h})=>h.type===c&&h.disabled!==!0).forEach(({id:h,data:d})=>{try{let f=new QT(h,d,o,e,r,this.eventManager);f.actions.Video.length&&(this.hasVideoAction=!0),(d.type==="MouseDown"||d.type==="MouseUp"||d.type==="MousePress")&&(d.mode==="Canvas"||d.mode==="Window")?this.canvasMouseEvents.push(f):u[o.uuid]?u[o.uuid].some(p=>p.id===f.id)||u[o.uuid].push(f):u[o.uuid]=[f]}catch(f){!1&&console.log(f)}}),u[o.uuid]?.length&&this.objectsPerTypes[c].push(o instanceof rr&&(c==="MouseDown"||c==="MouseUp"||c==="MousePress")?a:o)}};e.traverseEntity(o=>{(o instanceof Er||o instanceof ur)&&o.frame?.traverse(a=>{s(a,o)}),s(o)}),this.heldKeys={},this.heldKeysPress={},this.domEventsNeeded.clear(),i.addEventListener("pointerdown",this.onCanvasMouseDown),i.addEventListener("pointerup",this.onCanvasMouseUp),(this.objectsPerTypes.MouseDown?.length||this.useForRaycastProperty)&&(this.domEventsNeeded.add("pointerdown"),i.addEventListener("pointerdown",this.onMouseDown)),this.objectsPerTypes.MouseUp?.length&&(this.domEventsNeeded.add("pointerup"),i.addEventListener("pointerup",this.onMouseUp)),this.objectsPerTypes.MousePress?.length&&(this.domEventsNeeded.add("pointerdown"),i.addEventListener("pointerdown",this.onMousePressDown),this.domEventsNeeded.add("pointerup"),i.addEventListener("pointerup",this.onMousePressRelease)),this.objectsPerTypes.KeyDown?.length&&(this.domEventsNeeded.add("keydown"),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.releaseHeldKey)),this.objectsPerTypes.KeyUp?.length&&(this.domEventsNeeded.add("keyup"),document.addEventListener("keyup",this.onKeyUp)),this.objectsPerTypes.KeyPress?.length&&(this.domEventsNeeded.add("keydown"),document.addEventListener("keydown",this.onKeyPressDown),document.addEventListener("keyup",this.releaseHeldKeyPress),this.domEventsNeeded.add("keyup"),document.addEventListener("keyup",this.onKeyPressUp)),Object.entries(this.objectsPerTypes).forEach(([o,a])=>{a.forEach(l=>{l.addEventListener("userEvent",this._onUserEvent)})})}disconnect(){let{domElement:e}=this.eventContext;this.domEventsNeeded.clear(),this.heldKeys={},this.heldKeysPress={},e.removeEventListener("pointerdown",this.onCanvasMouseDown),e.removeEventListener("pointerup",this.onCanvasMouseUp),e.removeEventListener("pointerdown",this.onMouseDown),e.removeEventListener("pointerdown",this.onMousePressDown),e.removeEventListener("pointerup",this.onMouseUp),e.removeEventListener("pointerup",this.onMousePressRelease),document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("keyup",this.onKeyUp),document.removeEventListener("keydown",this.onKeyPressDown),document.removeEventListener("keyup",this.onKeyPressUp),document.removeEventListener("keyup",this.releaseHeldKey),Object.values(this.eventsPerObjects).forEach(r=>{Object.values(r).forEach(i=>{i.forEach(s=>{s.disconnect()})})}),this.canvasMouseEvents.forEach(r=>{r.disconnect()}),Object.entries(this.objectsPerTypes).forEach(([r,i])=>{i.forEach(s=>{s.removeEventListener("userEvent",this._onUserEvent)})})}handleMouseEvent(e){let{stopRaycast:r,raycaster:i,page:s,pointerScreen:o}=this.eventContext,a=this.objectsPerTypes[e],l=a.filter(c=>!(c instanceof rr));if(!(!a.length&&!this.useForRaycastProperty)&&!(s.uiCanvas&&so(s,[o.x,o.y],Object.keys(this.eventsPerObjects[e]),u=>{this.handleObjectMouseEventDispatch(u,e)}))){if(r||this.useForRaycastProperty){let c;if(this.sceneInterects===null?c=zf(i,s,l,this.useForRaycastProperty):(c=this.sceneInterects,this.sceneInterects=null),this.useForRaycastProperty&&c.length&&(this.eventContext.sharedAssets.raycastProperty={x:c[0].point.x,y:c[0].point.y,z:c[0].point.z,objX:c[0].object.matrixWorld.elements[12],objY:c[0].object.matrixWorld.elements[13],objZ:c[0].object.matrixWorld.elements[14]}),r){let u=[c[0]?.uv?.x??0,c[0]?.uv?.y??0];vg(c).forEach(h=>{h instanceof Er&&so(h,u,Object.keys(this.eventsPerObjects[e]),d=>{this.handleObjectMouseEventDispatch(d,e)}),this.eventsPerObjects[e][h.uuid]&&this.handleObjectMouseEventDispatch(h,e)})}}r||l.forEach(c=>{let u=Gf(i,c);u&&(this.handleObjectMouseEventDispatch(c,e),c instanceof Er&&so(c,[u?.uv?.x??0,u?.uv?.y??0],Object.keys(this.eventsPerObjects[e]),h=>{this.handleObjectMouseEventDispatch(h,e)}))})}}handleMousePressEvent(e=!1){let r="MousePress",i=this.objectsPerTypes[r],s=i.filter(a=>!(a instanceof rr)),o=[];if(!!i.length){if(!e){let{stopRaycast:a,raycaster:l,page:c,pointerScreen:u}=this.eventContext,h=!1;if(c.uiCanvas&&(h=so(c,[u.x,u.y],Object.keys(this.eventsPerObjects[r]),d=>{o.push(d)})),a&&!h){let d=zf(l,c,s);o=vg(d),d.forEach(f=>{f.object instanceof Er&&so(f.object,[f?.uv?.x??0,f?.uv?.y??0],Object.keys(this.eventsPerObjects[r]),p=>{o.push(p)})})}else s.forEach(d=>{let f=Gf(l,d);f&&(o.push(d),d instanceof Er&&so(d,[f?.uv?.x??0,f?.uv?.y??0],Object.keys(this.eventsPerObjects[r]),p=>{o.push(p)}))})}this._prevObjects.length&&this._prevObjects.forEach(a=>{o.includes(a)||this.handleObjectMouseEventDispatchRelease(a,r)}),o.length&&o.forEach(a=>{this.handleObjectMouseEventDispatch(a,r)}),this._prevObjects=o}}handleObjectMouseEventDispatch(e,r){e.dispatchEvent({type:"beginEvent",eventName:r}),this.eventsPerObjects[r]?.[e.uuid]?.forEach(i=>{i.dispatch()})}handleObjectMouseEventDispatchRelease(e,r){e.dispatchEvent({type:"beginEvent",eventName:r}),this.eventsPerObjects[r]?.[e.uuid]?.forEach(i=>{i.dispatchRelease()})}handleKeyEvent(e,r,i=!1){this.objectsPerTypes[r].forEach(s=>{let o=this.eventsPerObjects[r][s.uuid];o.some(({data:a})=>"key"in a&&a.key===e.key)&&s.dispatchEvent({type:"beginEvent",eventName:r}),o.forEach(a=>{"key"in a.data&&a.data.key===e.key&&(i?a.dispatchRelease():a.dispatch(!0))})})}handleKeyEventHeld(e,r,i=!1){this.objectsPerTypes[r].forEach(s=>{this.eventsPerObjects[r][s.uuid].forEach(a=>{"key"in a.data&&a.data.key===e.key&&a.dispatchHeld(i)})})}};var c$=new E,u$=new E;var Nb=class{constructor(t,e,r,i,s){this.actionsIn=kt(t,t.inActions,r,i,s,e),this.actionsOut=kt(t,t.outActions,r,i,s,e)}disconnect(){hr(this.actionsIn),hr(this.actionsOut)}};var ZT=class extends Nb{constructor(e,r,i,s,o,a){super(r,i,s,o,a);this.id=e;this.data=r;this.object=i;this.stage="out";this.objects=[];this.onUpdateMatrixWorld=()=>{for(let s of this.objects)if(!s.visible)return;let e=c$.setFromMatrixPosition(this.objects[0].matrixWorld),r=u$.setFromMatrixPosition(this.objects[1].matrixWorld),i=e.distanceTo(r)<=this.distance?"in":"out";if(this.stage!==i){this.stage=i;let s=i==="in"?this.actionsIn:this.actionsOut;s.Audio.forEach(o=>o.dispatchConditional()),s.Particles.forEach(o=>o.dispatchConditional()),s.Video.forEach(o=>o.dispatchConditional()),s.Link.forEach(o=>o.dispatch()),s.Create.forEach(o=>o.dispatch()),s.Destroy.forEach(o=>o.dispatch()),s.Reset.forEach(o=>o.dispatch()),s.Transition.forEach(o=>{o.object.currentTransitionEvent!==this&&(o.object.currentTransitionEvent=this),o.init()}),s.Transition.forEach(o=>o.play()),s.Animation.forEach(o=>o.play()),s.SwitchCamera.forEach(o=>o.play()),s.SceneTransition.forEach(o=>o.dispatch()),s.SetVariable.forEach(o=>o.checkConditions()),s.SetVariable.forEach(o=>o.dispatch()),s.DynamicVariablePlay.forEach(o=>o.dispatch()),s.ClearLocalStorage.forEach(o=>o.dispatch()),s.UserAPI.forEach(o=>o.dispatch())}};let{distance:l,fromObject:c,toObject:u}=r.condition;this.distance=l;for(let h of[c,u]){if(!h)throw new Error("Missing property");let d=s.find(h);if(!d)throw new Error("Missing property");this.objects.push(d)}}connect(){window.setTimeout(()=>{this.objects.forEach(e=>{e.addEventListener("updateMatrixWorld",this.onUpdateMatrixWorld)}),this.onUpdateMatrixWorld()},0)}disconnect(){super.disconnect(),this.stage="out",this.objects.forEach(e=>{e.removeEventListener("updateMatrixWorld",this.onUpdateMatrixWorld)})}},JT=class extends Nb{constructor(e,r,i,s,o,a){super(r,i,s,o,a);this.id=e;this.data=r;this.object=i;this.onBegin=({target:e,state:r})=>{this.toState!==r&&(this.actionsOut.Audio.forEach(i=>i.dispatchConditional()),this.actionsOut.Particles.forEach(i=>i.dispatchConditional()),this.actionsOut.Video.forEach(i=>i.dispatchConditional()),this.actionsOut.Link.forEach(i=>i.dispatch()),this.actionsOut.Create.forEach(i=>i.dispatch()),this.actionsOut.Destroy.forEach(i=>i.dispatch()),this.actionsOut.Reset.forEach(i=>i.dispatch()),this.actionsIn.Transition.forEach(i=>i.pause()),this.object.currentTransitionEvent=this,this.actionsOut.Transition.forEach(i=>i.play()),this.actionsOut.Animation.forEach(i=>i.play()),this.actionsIn.SwitchCamera.forEach(i=>i.pause()),this.actionsOut.SwitchCamera.forEach(i=>i.play()),this.actionsOut.SceneTransition.forEach(i=>i.dispatch()),this.actionsOut.SetVariable.forEach(i=>i.checkConditions()),this.actionsOut.SetVariable.forEach(i=>i.dispatch()),this.actionsOut.DynamicVariablePlay.forEach(i=>i.dispatch()),this.actionsOut.ClearLocalStorage.forEach(i=>i.dispatch()),this.actionsOut.UserAPI.forEach(i=>i.dispatch()))};this.onComplete=({target:e,state:r})=>{this.toState===r&&(this.actionsIn.Audio.forEach(i=>i.dispatchConditional()),this.actionsIn.Particles.forEach(i=>i.dispatchConditional()),this.actionsIn.Video.forEach(i=>i.dispatchConditional()),this.actionsIn.Link.forEach(i=>i.dispatch()),this.actionsIn.Create.forEach(i=>i.dispatch()),this.actionsIn.Destroy.forEach(i=>i.dispatch()),this.actionsIn.Reset.forEach(i=>i.dispatch()),this.actionsOut.Transition.forEach(i=>i.pause()),this.actionsOut.Transition.forEach(i=>i.pause()),this.object.currentTransitionEvent=this,this.actionsIn.Transition.forEach(i=>i.play()),this.actionsIn.Animation.forEach(i=>i.play()),this.actionsOut.SwitchCamera.forEach(i=>i.pause()),this.actionsIn.SwitchCamera.forEach(i=>i.play()),this.actionsIn.SceneTransition.forEach(i=>i.dispatch()),this.actionsIn.SetVariable.forEach(i=>i.checkConditions()),this.actionsIn.SetVariable.forEach(i=>i.dispatch()),this.actionsIn.DynamicVariablePlay.forEach(i=>i.dispatch()),this.actionsOut.ClearLocalStorage.forEach(i=>i.dispatch()),this.actionsOut.UserAPI.forEach(i=>i.dispatch()))};let{condition:l}=r;if(!l.object)throw new Error("Missing property");let c=s.find(l.object)??s.scene.find2D(l.object);if(!c)throw new Error("Missing property");if(this.toObject=c,l.state&&!this.toObject.states?.[l.state])throw new Error("Missing property");this.toState=l.state}connect(){ls(this.actionsOut).forEach(e=>{this.actionsOut[e]?.length&&this.toObject.addEventListener("beginState",this.onBegin)}),ls(this.actionsIn).forEach(e=>{this.actionsIn[e]?.length&&this.toObject.addEventListener("completeState",this.onComplete)})}disconnect(){super.disconnect(),ls(this.actionsOut).forEach(e=>{this.actionsIn[e]?.length&&this.toObject.removeEventListener("beginState",this.onBegin)}),ls(this.actionsIn).forEach(e=>{this.actionsIn[e]?.length&&this.toObject.removeEventListener("completeState",this.onComplete)})}},Fb=class extends Yt{constructor(e,r){super(e);this.eventManager=r;this.eventsPerConditions={Comparison:[],Distance:[],State:[]};this.hasVideoAction=!1}connect(){super.connect();let{page:e,sharedAssets:r}=this.eventContext;e.traverseEntity(i=>{if(!!i.data?.events.length){for(let{id:s,data:o}of i.data.events)if(!o.disabled&&o.type==="Conditional")try{let a;o.condition.type==="Comparison"||(o.condition.type==="Distance"?a=new ZT(s,o,i,e,r,this.eventManager):o.condition.type==="State"&&(a=new JT(s,o,i,e,r,this.eventManager))),a&&(this.eventsPerConditions[o.condition.type].push(a),(a.actionsIn.Video.length||a.actionsOut.Video.length)&&(this.hasVideoAction=!0))}catch(a){!1&&console.log(a)}}}),Object.values(this.eventsPerConditions).forEach(i=>i.forEach(s=>s.connect()))}disconnect(){super.disconnect(),Object.values(this.eventsPerConditions).forEach(e=>e.forEach(r=>r.disconnect()))}};var xg=new E,lc=new E,au=new E,XN=new kr,h$=.01,ir=new E,Di=new E,KN=new E,lu=new Ke,$T=new nr,d$=new ue,eM=new fr,jf=new E,Zo=new E,Hf=.2;function tM(n,t){!t||(t[0]{let i=t.obj;n.copy(i.hiddenMatrix),i.parent!==null&&n.premultiply(i.parent.matrixWorld),n.invert(),i.position.copy(e),t.reference==="global"&&tM(i.position,t.limits),i.position.applyMatrix4(n),t.reference==="parent"?tM(i.position,t.limits):t.reference==="local"&&(lu.copy(t.quat0).invert(),i.position.sub(t.position0),i.position.applyQuaternion(lu),tM(i.position,t.limits),lu.invert(),i.position.applyQuaternion(lu),i.position.add(t.position0)),n.multiply(r??i.matrixWorld).decompose(ir,i.quaternion,Di),i.updateMatrix(),i.hasNonUniformScale&&(i.updateMatrixWorld(),i.updateMatrixWorldSVD()),i instanceof mr&&En(i.parent)&&i.invalidateDownstreamBooleanData(!0)}}(),rM=class{constructor(t,e,r,i,s,o,a){this.object=t;this.id=e;this.data=r;this.dropDestIds=[];this.activeIdx=null;this.wasDragEventTriggered=!1;this.resetDampingFactor=this.data.resetSpeed===0?1:8/this.data.resetSpeed+1,this.snapDampingFactor=this.data.snapSpeed===0?1:8/this.data.snapSpeed+1,this.actionsDrag=kt(r,r.dragDropActions.drag,i,s,o,this.object),this.actionsDrop=kt(r,r.dragDropActions.drop,i,s,o,this.object);let l=[];this.data.objects.forEach(c=>{let u=i.find(c);!u||u.data.visible!==!1&&(l.push(u),a[u.uuid]&&a[u.uuid].forEach(h=>{let d=i.find(h);!d||d.data.visible!==!1&&l.push(d)}))}),this.data.dropDestinations.forEach(c=>{let u=i.find(c);!u||u.data.visible!==!1&&(this.dropDestIds.push(u.uuid),a[u.uuid]&&a[u.uuid].forEach(h=>{let d=i.find(h);!d||d.data.visible!==!1&&this.dropDestIds.push(d.uuid)}))}),this.dragItems=l.map(c=>(this.data.planeMode==="locked"&&(c.userData.lockedPlane=!0),c.userData.worldPosition0=new E().setFromMatrixPosition(c.matrixWorld),{obj:c,fromPosition:new E().setFromMatrixPosition(c.matrixWorld),pointStart:new E,pointEnd:new E,paused:!0,currentDampingFactor:this.data.dampingFactor,reset:!1,position0:new E().copy(c.position),quat0:new Ke().copy(c.quaternion),snapped:!1,orientationMatrix:new ue,limits:this.data.limits,reference:this.data.referenceFrame}))}get activeDragItem(){return this.activeIdx!==null?this.dragItems[this.activeIdx]:null}dispose(){hr(this.actionsDrag),hr(this.actionsDrop),this.dragItems.forEach(t=>{t.fromPosition.copy(t.obj.userData.worldPosition0),t.pointStart.copy(t.fromPosition),t.pointEnd.copy(t.pointStart),t.obj.recursiveBBoxNeedsUpdate=!0,t.obj.userData.lockedPlane=void 0,t.obj.position.copy(t.position0),t.obj.quaternion.copy(t.quat0),t.obj.updateMatrix()})}},Vb=class extends Yt{constructor(e,r){super(e);this.eventManager=r;this.events=[];this.lastDropDestination=null;this.dragTimeout=null;this.onPointerDown=e=>{if(Je.length>1)return;this.eventContext.updateRaycaster(e);let{raycaster:r,page:i}=this.eventContext,s=i.raycastWithClones(r);if(this.lastDropDestination=null,s.length===0){this.activeEvent=null;return}for(let o of this.events){let a=0;for(let{obj:l,pointEnd:c,pointStart:u}of o.dragItems){if(l===s[0].object||l===s[0].object.object||yt.is(l)&&l.isAncestorOf(s[0].object.uuid)){if(o.activeIdx=a,o.activeDragItem.reset=!1,o.activeDragItem.currentDampingFactor=o.data.dampingFactor,o.activeDragItem.snapped=!1,o.data.cursor==="hand"&&this.setCursor("grabbing"),this.eventManager.controlsManager.usePhysics){o.activeDragItem.obj.rigidBody&&o.activeDragItem.obj.rigidBody.setBodyType(2,!0);let h=o.activeDragItem.obj;l.hasNonUniformScale&&l.updateMatrixWorldSVD(),(h.hasNonUniformScale?h.matrixWorldRigid:h.matrixWorld).decompose(ir,lu,Di),$T.setFromQuaternion(lu),h.prevR===void 0?(h.prevR=$T.clone(),h.prevT=ir.clone()):(h.prevR.copy($T),h.prevT.copy(ir)),this.eventManager.controlsManager.sharedGameControlGlobals.entitiesWithTransformAnim.push(o.activeDragItem.obj)}this.calcPlaneIntersectPos(l,u,o.data.plane,o.data.referenceFrame),c.copy(u),(this.eventManager.controlsManager.usePhysics&&l.data.physics?.rigidBody==="dynamic"||o.data.drop===!1||o.data.resetOnSnapFail===!1)&&o.activeDragItem.fromPosition.setFromMatrixPosition(o.activeDragItem.obj.matrixWorld),this.activeEvent=o,this.eventManager.controlsManager.orbitControls&&(this.eventManager.controlsManager.orbitControls.enabled=!1);return}a++}}this.activeEvent=null};this.onPointerMove=e=>{if(Je.length>1)return;this.eventContext.updateRaycaster(e);let{raycaster:r,page:i}=this.eventContext,s=i.raycastWithClones(r);if(Je.length===0){let o=!1;for(let a of this.events){for(let{obj:l}of a.dragItems)if(l===s[0]?.object||l===s[0]?.object?.object||yt.is(l)&&l.isAncestorOf(s[0]?.object.uuid)){switch(o=!0,a.data.cursor){case"hand":this.setCursor("grab");break;case"move":this.setCursor("move");break;default:break}break}if(o)break}o||this.setCursor("default");return}if(this.activeEvent&&this.activeEvent.activeDragItem){let o=this.activeEvent.activeDragItem;o.snapped=!1;let a;if(this.activeEvent.data.drop&&(a=s.filter(l=>o.obj!==l.object&&!o.obj.isAncestorOf(l.object.uuid)&&!(l.object instanceof As)&&(this.activeEvent.data.dropOn==="all"||this.activeEvent.dropDestIds.some(c=>c===l.object.uuid||i.scene.find(c).isAncestorOf(l.object.uuid))))[0]),a){let l=KN.copy(a.face.normal).applyMatrix3(eM.getNormalMatrix(a.object.matrixWorld));if(this.activeEvent.data.snapTo==="center")o.fromPosition.setFromMatrixPosition(a.object.matrixWorld);else if(this.activeEvent.data.snapTo==="surface"){if(o.fromPosition.copy(a.point),this.activeEvent.data.snapSurfaceMode==="bbox"){ir.copy(l).applyMatrix3(eM.setFromMatrix4(o.obj.matrixWorld).transpose());let c=o.obj;ir.x>Hf?Di.x=-c.recursiveBBox.min.x:ir.x<-Hf&&(Di.x=-c.recursiveBBox.max.x),ir.y>Hf?Di.y=-c.recursiveBBox.min.y:ir.y<-Hf&&(Di.y=-c.recursiveBBox.max.y),ir.z>Hf?Di.z=-c.recursiveBBox.min.z:ir.z<-Hf&&(Di.z=-c.recursiveBBox.max.z),Di.applyMatrix3(eM.invert())}else Di.copy(l).multiplyScalar(this.activeEvent.data.snapSurfaceOffset);o.fromPosition.add(Di)}this.activeEvent.data.autoOrient&&(ir.set(0,1,0).cross(l),ir.length()<1e-4&&ir.set(-1,0,0).cross(l),Di.crossVectors(KN,ir),o.orientationMatrix.makeBasis(ir,Di,l)),o.pointStart.copy(o.fromPosition),o.pointEnd.copy(o.pointStart),o.currentDampingFactor=this.activeEvent.snapDampingFactor,o.snapped=!0,this.lastDropDestination!==a.object&&(this.lastDropDestination=a.object,this.activeEvent.actionsDrop.Transition.forEach(c=>{c.play()}),this.activeEvent.actionsDrop.Animation.forEach(c=>{c.play()}),this.activeEvent.actionsDrop.Audio.forEach(c=>{c.dispatchGameControl("start")}),this.activeEvent.actionsDrop.Particles.forEach(c=>{c.dispatchGameControl("start")}),this.activeEvent.actionsDrop.Create.forEach(c=>{c.dispatchThrottled()}))}else o.orientationMatrix.makeRotationFromQuaternion(o.quat0),this.lastDropDestination=null,o.currentDampingFactor=this.activeEvent.data.dampingFactor,this.calcPlaneIntersectPos(o.obj,o.pointEnd,this.activeEvent.data.plane,this.activeEvent.data.referenceFrame),this.activeEvent.actionsDrop.Transition.forEach(l=>{l.stop(),l.object.currentState!==null&&l.object.changeSelectedState(null,{scene:this.eventContext.page.scene,shared:this.eventContext.sharedAssets})}),this.activeEvent.actionsDrop.Animation.forEach(l=>{l.stop()}),this.activeEvent.actionsDrop.Audio.forEach(l=>{l.dispatchGameControl("stop")}),this.activeEvent.actionsDrop.Particles.forEach(l=>{l.dispatchGameControl("stop")});this.activeEvent.actionsDrag.Create.forEach(l=>{l.dispatchThrottled()}),this.activeEvent.actionsDrag.SetVariable.forEach(l=>l.checkConditions()),this.activeEvent.actionsDrag.SetVariable.forEach(l=>l.dispatch()),this.activeEvent.actionsDrag.DynamicVariablePlay.forEach(l=>l.dispatch()),this.activeEvent.actionsDrag.ClearLocalStorage.forEach(l=>l.dispatch()),this.activeEvent.actionsDrag.UserAPI.forEach(l=>l.dispatch()),this.activeEvent.wasDragEventTriggered===!1&&(this.activeEvent.wasDragEventTriggered=!0,this.activeEvent.actionsDrag.Transition.forEach(l=>{l.play()}),this.activeEvent.actionsDrag.Animation.forEach(l=>{l.play()}),this.activeEvent.actionsDrag.Audio.forEach(l=>{l.dispatchGameControl("start")}),this.activeEvent.actionsDrag.Particles.forEach(l=>{l.dispatchGameControl("start")})),this.dragTimeout&&window.clearTimeout(this.dragTimeout),this.dragTimeout=window.setTimeout(()=>{!this.activeEvent||(this.activeEvent.wasDragEventTriggered=!1,this.activeEvent.actionsDrag.Audio.forEach(l=>{l.dispatchGameControl("stop")}),this.activeEvent.actionsDrag.Particles.forEach(l=>{l.dispatchGameControl("stop")}),this.activeEvent.actionsDrag.Transition.forEach(l=>{l.stop(),l.object.currentState!==null&&l.object.changeSelectedState(null,{scene:this.eventContext.page.scene,shared:this.eventContext.sharedAssets})}),this.activeEvent.actionsDrag.Animation.forEach(l=>{l.stop()}))},500),this.updateDragItem(o),o.obj.dispatchEvent({type:"requestRender"})}};this.onPointerUp=e=>{if(this.activeEvent&&this.activeEvent.activeDragItem){this.activeEvent.data.cursor==="hand"&&this.setCursor("grab");let r=this.activeEvent.activeDragItem.obj.data.physics?.rigidBody==="dynamic";this.activeEvent.activeDragItem.snapped===!1&&this.activeEvent.data.drop&&this.activeEvent.data.resetOnSnapFail&&(this.eventManager.controlsManager.usePhysics===!1||!r)&&(this.activeEvent.activeDragItem.reset=this.activeEvent.data.resetOnSnapFail,this.activeEvent.activeDragItem.paused=!1,this.activeEvent.activeDragItem.currentDampingFactor=this.activeEvent.resetDampingFactor),this.eventManager.controlsManager.usePhysics&&r&&(this.eventManager.controlsManager.sharedGameControlGlobals.entitiesWithTransformAnim.pop(),this.activeEvent.activeDragItem.obj.rigidBody.setBodyType(0,!0),this.activeEvent.activeDragItem.paused=!0),this.activeEvent.wasDragEventTriggered===!0&&(this.activeEvent.wasDragEventTriggered=!1,this.activeEvent.actionsDrag.Transition.forEach(i=>{i.stop(),i.object.currentState!==null&&i.object.changeSelectedState(null,{scene:this.eventContext.page.scene,shared:this.eventContext.sharedAssets})}),this.activeEvent.actionsDrag.Animation.forEach(i=>{i.stop()}),this.activeEvent.actionsDrag.Audio.forEach(i=>{i.dispatchGameControl("stop")}),this.activeEvent.actionsDrag.Particles.forEach(i=>{i.dispatchGameControl("stop")}),this.activeEvent.actionsDrop.SetVariable.forEach(i=>i.checkConditions()),this.activeEvent.actionsDrop.SetVariable.forEach(i=>i.dispatch()),this.activeEvent.actionsDrop.DynamicVariablePlay.forEach(i=>i.dispatch()),this.activeEvent.actionsDrop.ClearLocalStorage.forEach(i=>i.dispatch()),this.activeEvent.actionsDrop.UserAPI.forEach(i=>i.dispatch())),this.eventManager.controlsManager.orbitControls&&(this.eventManager.controlsManager.orbitControls.enabled=!0)}}}connect(){let e={};if(this.eventContext.page.traverseEntity(i=>{i.component&&(e[i.component.uuid]?e[i.component.uuid].push(i.uuid):e[i.component.uuid]=[i.uuid])}),this.eventContext.page.traverseEntity(i=>{i.data?.events.filter(s=>s.data.type==="DragDrop"&&!s.data.disabled).forEach(s=>{this.events.push(new rM(i,s.id,s.data,this.eventContext.page,this.eventContext.sharedAssets,this.eventManager,e))})}),!this.events.length)return;this.domEventsNeeded.clear(),this.domEventsNeeded.add("pointerdown");let r=this.eventContext.domElement;r.addEventListener("pointerdown",this.onPointerDown),r.addEventListener("pointermove",this.onPointerMove),r.addEventListener("pointerup",this.onPointerUp),this.domEventsNeeded.add("pointermove")}disconnect(){if(!this.events.length)return;this.domEventsNeeded.clear();let e=this.eventContext.domElement;e.removeEventListener("pointerdown",this.onPointerDown),e.removeEventListener("pointermove",this.onPointerMove),e.removeEventListener("pointerup",this.onPointerUp),this.events.forEach(r=>r.dispose())}setCursor(e){this.eventContext.domElement.style.cursor=e}onAnimationFrameDamping(){for(let e of this.events)for(let r of e.dragItems)r.paused||this.updateDragItem(r,!0)}calcPlaneIntersectPos(e,r,i,s){let{getCamera:o,raycaster:a}=this.eventContext;o().getWorldDirection(lc),lc.negate();let l=lu.identity();switch(s==="parent"?d$.multiplyMatrices(e.parent.matrixWorld,e.hiddenMatrix).decompose(ir,l,Di):s==="local"&&e.matrixWorld.decompose(ir,l,Di),i){case"x":ir.set(1,0,0).applyQuaternion(l),jf.copy(lc).cross(ir),Zo.copy(ir).cross(jf);break;case"y":ir.set(0,1,0).applyQuaternion(l),jf.copy(lc).cross(ir),Zo.copy(ir).cross(jf);break;case"z":ir.set(0,0,1).applyQuaternion(l),jf.copy(lc).cross(ir),Zo.copy(ir).cross(jf);break;case"xy":Zo.set(0,0,1).applyQuaternion(l);break;case"yz":Zo.set(1,0,0).applyQuaternion(l);break;case"xz":Zo.set(0,1,0).applyQuaternion(l);break;case"adaptive":lc.angleTo(Di.set(0,1,0))>Math.PI/6?(ir.crossVectors(Di.set(0,1,0),lc),Zo.crossVectors(ir,Di)):Zo.set(0,1,0);break;default:Zo.copy(lc);break}au.setFromMatrixPosition(e.matrixWorld);let c=e.userData.lockedPlane?e.userData.worldPosition0:au;if(XN.setFromNormalAndCoplanarPoint(Zo,c),!!a.ray.intersectPlane(XN,r)&&(i==="x"||i==="y"||i==="z")){let u=Di.subVectors(r,c).dot(ir);r.copy(c).addScaledVector(ir,u)}}updateDragItem(e,r=!1){au.setFromMatrixPosition(e.obj.matrixWorld),e.reset==="current"?xg.subVectors(e.fromPosition,au).divideScalar(e.currentDampingFactor):e.reset==="original"?(xg.subVectors(e.obj.userData.worldPosition0,au).divideScalar(e.currentDampingFactor),e.fromPosition.copy(e.obj.userData.worldPosition0),e.pointStart.copy(e.fromPosition),e.pointEnd.copy(e.pointStart)):xg.subVectors(e.pointEnd,e.pointStart).add(e.fromPosition).sub(au).divideScalar(e.currentDampingFactor),e.paused=e.currentDampingFactor>1?xg.length()i>0?(n.subVectors(e,r),n.length()<=i?e:t.copy(r).add(n.normalize().multiplyScalar(i))):r}(),ZN=function(){let n=new ue;return(t,e)=>{t.position.copy(e),t.parent!==null&&(n.copy(t.parent.matrixWorld).invert(),t.position.applyMatrix4(n)),n.copy(t.hiddenMatrix).invert(),t.position.applyMatrix4(n),t.updateMatrix(),t.hasNonUniformScale&&(t.updateMatrixWorld(),t.updateMatrixWorldSVD()),t instanceof mr&&En(t.parent)&&t.invalidateDownstreamBooleanData(!0)}}(),nM=class{constructor(t,e,r,i,s,o){this.data=t;this.id=e;this.object=r;this.paused=!1;this.currentDampingFactor=1;this.snapComplete=!1;this.isReset=!1;this.worldPosition0=new E;this.timeoutId=null;this.delayFinished=!0;this.wasOutside=!1;this.data={...Vv.defaultData,...t,...t.resetOnPointerLeave===void 0&&{resetOnPointerLeave:!1}},t.target===void 0||t.target==="cursor"||(this.target=i.find(t.target)),this.data.dampingFactor&&(this.currentDampingFactor=this.data.dampingFactor),this.resetDampingFactor=80/this.data.resetSpeed+1,this.object.getWorldPosition(this.worldPosition0),this.actions=kt(t,t.actions,i,s,o,r)}},kb=class extends Yt{constructor(e,r){super(e);this.eventManager=r;this.events=[];this.pairOfEventListeners=[];this.onMouseMove=e=>{if(!(Je.length>1)){this.eventContext.updateRaycaster(e);for(let r of this.events)r.target===void 0&&this.updateSingleEvent(r)}};this.onMouseEnter=e=>{for(let r of this.events)r.target===void 0&&(r.isReset=!1,r.currentDampingFactor=r.data.dampingFactor)};this.onMouseLeave=e=>{for(let r of this.events)r.target===void 0&&(r.data.resetOnPointerLeave&&(r.isReset=!0,r.currentDampingFactor=r.resetDampingFactor),this.updateSingleEvent(r))};this.onTargetChange=e=>()=>{this.updateSingleEvent(e)}}connect(){let{page:e}=this.eventContext;if(e.traverseEntity(s=>{let o=s.data?.events.find(a=>a.data.type==="Follow"&&!a.data.disabled);o&&(!e.data.globalPhysics.usePhysics||s.dataPatched.physics?.rigidBody!=="dynamic")&&this.events.push(new nM(o.data,o.id,s,e,this.eventContext.sharedAssets,this.eventManager))}),!this.events.length)return;let{domElement:r,eventElement:i}=this.eventContext;this.domEventsNeeded.clear(),Ci&&(this.domEventsNeeded.add("pointerdown"),r.addEventListener("pointerdown",this.onMouseMove)),this.domEventsNeeded.add("pointermove"),i.addEventListener("pointermove",this.onMouseMove),this.eventContext.useWindowEvents||(r.addEventListener("pointerenter",this.onMouseEnter),r.addEventListener("pointerleave",this.onMouseLeave));for(let s of this.events)if(s.target!==void 0){let o=s.target,a=this.onTargetChange(s);this.pairOfEventListeners.push([o,a]),o.addEventListener("requestRender",a)}}disconnect(){if(!this.events.length)return;let{domElement:e,eventElement:r}=this.eventContext;this.domEventsNeeded.clear(),Ci&&e.removeEventListener("pointerdown",this.onMouseMove),r.removeEventListener("pointermove",this.onMouseMove),e.removeEventListener("pointerenter",this.onMouseEnter),e.removeEventListener("pointerleave",this.onMouseLeave);for(let[i,s]of this.pairOfEventListeners)i.removeEventListener("requestRender",s);for(let i of this.events)i.paused=!0,i.isReset=!1,hr(i.actions)}onAnimationFrameDamping(){for(let e of this.events)e.paused||this.updateSingleEvent(e,!0)}updateSingleEvent(e,r=!1){this.events.forEach(l=>{l.actions.Create.forEach(c=>{c.dispatchThrottled()})});let{plane:i,limitDistance:s,limitDistanceEnabled:o}=e.data;if(e.object.getWorldPosition(Wa),e.isReset)qa.copy(e.worldPosition0);else if(e.target)e.target.getWorldPosition(qa);else{let{getCamera:l,raycaster:c}=this.eventContext;if(i==="custom"?(l().getWorldDirection(iM),iM.negate(),Wf.copy(iM)):i==="xy"?Wf.set(0,0,1):i==="xz"?Wf.set(0,1,0):i==="yz"&&Wf.set(1,0,0),QN.setFromNormalAndCoplanarPoint(Wf,Wa),!c.ray.intersectPlane(QN,qa))return}if(!e.isReset){if(qa.distanceTo(e.worldPosition0)>s&&o&&e.target)if(e.snapComplete=!1,e.data.snapDelay&&(e.delayFinished=!1,typeof window<"u"&&e.timeoutId!==null&&(window.clearTimeout(e.timeoutId),e.timeoutId=null)),e.wasOutside=!0,e.data.resetAfterDistanceLimit)qa.copy(e.worldPosition0),e.currentDampingFactor=e.resetDampingFactor;else return;else if(e.wasOutside&&(e.data.snapDelay&&typeof window<"u"&&(e.timeoutId=window.setTimeout(()=>{e.delayFinished=!0,e.paused=!1,this.updateSingleEvent(e)},e.data.snapDelay*1e3)),e.currentDampingFactor=e.data.dampingFactor,e.wasOutside=!1),e.delayFinished===!1)return}e.data.enabledTranslation[0]===!1&&(qa.x=Wa.x),e.data.enabledTranslation[1]===!1&&(qa.y=Wa.y),e.data.enabledTranslation[2]===!1&&(qa.z=Wa.z);let a=g$(Wa,qa,e.wasOutside?0:e.data.maxDelta);if(e.currentDampingFactor>1){let l=Wf.subVectors(a,Wa).divideScalar(e.currentDampingFactor);Wa.add(l),r&&ZN(e.object,Wa),e.paused=l.length(){if(!(Je.length>1)){this._lastMouseEvent=e,this.eventContext.updateRaycaster(e);for(let r of this.events)r.target===void 0&&this.updateSingleEvent(r)}};this.onMouseEnter=e=>{for(let r of this.events)r.target===void 0&&(r.isReset=!1,r.currentDampingFactor=r.data.dampingFactor)};this.onMouseLeave=e=>{for(let r of this.events)r.target===void 0&&(r.data.resetOnPointerLeave&&(r.isReset=!0,r.currentDampingFactor=r.resetDampingFactor),this.updateSingleEvent(r))};this.onScroll=e=>{if(this._lastMouseEvent){let r=new PointerEvent("pointermove",{clientX:this._lastMouseEvent.clientX,clientY:this._lastMouseEvent.clientY,bubbles:!0,cancelable:!0,view:window});this.eventContext.eventElement.dispatchEvent(r)}};this.onTargetChange=e=>()=>{this.updateSingleEvent(e)};this.createUserEventListener=e=>({eventName:r,target:i})=>{if(!r||!i)return;let s=Qo(r);s&&s==="LookAt"&&this.updateSingleEvent(e)}}connect(){let{page:e}=this.eventContext;if(e.traverseEntity(s=>{let o=s.data?.events.find(a=>a.data.type==="LookAt"&&!a.data.disabled);o&&(!e.data.globalPhysics.usePhysics||s.dataPatched.physics?.rigidBody!=="dynamic")&&this.events.push(new oM(o.data,o.id,s,e))}),!this.events.length)return;let{domElement:r,eventElement:i}=this.eventContext;this.domEventsNeeded.clear(),Ci&&(this.domEventsNeeded.add("pointerdown"),r.addEventListener("pointerdown",this.onMouseMove)),this.domEventsNeeded.add("pointermove"),i.addEventListener("pointermove",this.onMouseMove),this.eventContext.useWindowEvents?i.addEventListener("scroll",this.onScroll):(r.addEventListener("pointerenter",this.onMouseEnter),r.addEventListener("pointerleave",this.onMouseLeave));for(let s of this.events){if(s.target!==void 0){let l=this.onTargetChange(s),c=s.target;this.pairOfEventListeners.push([c,l]),c.addEventListener("requestRender",l)}let o=this.createUserEventListener(s),a=s.object;this.pairOfUserEventListeners.push([a,o]),a.addEventListener("userEvent",o)}}disconnect(){if(!this.events.length)return;let{domElement:e,eventElement:r}=this.eventContext;this.domEventsNeeded.clear(),Ci&&e.removeEventListener("pointerdown",this.onMouseMove),r.removeEventListener("pointermove",this.onMouseMove),e.removeEventListener("pointerenter",this.onMouseEnter),e.removeEventListener("pointerleave",this.onMouseLeave),r.removeEventListener("scroll",this.onScroll);for(let[i,s]of this.pairOfEventListeners)i.removeEventListener("requestRender",s);for(let[i,s]of this.pairOfUserEventListeners)i.removeEventListener("userEvent",s);for(let i of this.events)i.paused=!0,i.isReset=!1}onAnimationFrameDamping(){for(let e of this.events)e.paused||this.updateSingleEvent(e)}updateSingleEvent(e){let{tilt:r,axis:i,distance:s,plane:o,limitDistance:a,enabledRotation:l,limitDistanceEnabled:c}=e.data,{getCamera:u,raycaster:h}=this.eventContext,{object:d,target:f}=e;if(d.getWorldPosition(wg),!e.isReset)if(e.target)e.target.getWorldPosition(Ag);else{if(o==="custom"?(u().getWorldDirection(Ub),Ub.negate(),sM.setFromNormalAndCoplanarPoint(Ub,wg)):(o==="xy"?bg.set(0,0,1):o==="xz"?bg.set(0,1,0):o==="yz"&&bg.set(1,0,0),sM.setFromNormalAndCoplanarPoint(bg,wg)),!h.ray.intersectPlane(sM,Ag))return;s>0&&(o==="custom"||o===void 0)&&Ag.addScaledVector(Ub,s)}if(e.isReset||(f?r==="target"?cu.copy(f.up).applyMatrix4(Sg.extractRotation(f.matrixWorld)).normalize():l.some(p=>p===!1)?(i==="x"?(Ya.set(0,0,1),l[2]===!1&&Ya.set(0,1,0)):i==="y"?(Ya.set(1,0,0),l[0]===!1&&Ya.set(0,0,1)):(Ya.set(0,1,0),l[1]===!1&&Ya.set(1,0,0)),cu.copy(Ya).applyQuaternion(e.worldQuaternion0).normalize()):cu.set(0,1,0):o==="custom"?cu.set(0,1,0):cu.copy(bg)),e.isReset)cc.copy(e.worldQuaternion0);else if(wg.distanceTo(Ag)>a&&c&&f)if(e.data.snapDelay&&(e.delayFinished=!1,typeof window<"u"&&e.timeoutId!==null&&(window.clearTimeout(e.timeoutId),e.timeoutId=null)),e.wasOutside=!0,e.data.resetAfterDistanceLimit)cc.copy(e.worldQuaternion0),e.currentDampingFactor=e.resetDampingFactor;else return;else{if(e.wasOutside&&(e.data.snapDelay&&typeof window<"u"&&(e.timeoutId=window.setTimeout(()=>{e.delayFinished=!0,e.paused=!1,this.updateSingleEvent(e)},e.data.snapDelay*1e3)),e.currentDampingFactor=e.data.dampingFactor,e.wasOutside=!1),e.delayFinished===!1)return;b$(Sg,Ag,wg,cu,i,Ya),cc.setFromRotationMatrix(Sg),qf.setFromUnitVectors(Ya.applyQuaternion(cc),cu),l.some(p=>p===!1)&&r!=="target"&&cc.premultiply(qf).normalize()}e.currentDampingFactor>1?(d.updateWorldMatrix(!0,!1),qf.setFromRotationMatrix(XT(d.matrixWorld)),qf.slerp(cc,1/e.currentDampingFactor),JN(d,Sg.makeRotationFromQuaternion(qf)),e.paused=8*(1-qf.dot(cc)){t.object.currentTransitionEvent!==this&&(t.object.currentTransitionEvent=this,t.init())}),this.entered||(this.entered=!0,this.actions.Transition.forEach(t=>t.playFromCurrent()),this.actions.Animation.forEach(t=>t.play()),this.actions.Create.forEach(t=>t.dispatchStart()),this.actions.Particles.forEach(t=>t.dispatchBasic()),this.actions.Destroy.forEach(t=>t.dispatch()),this.actions.SwitchCamera.forEach(t=>t.playFromCurrent()),this.actions.SceneTransition.forEach(t=>t.dispatch()),this.actions.SetVariable.forEach(t=>t.checkConditions()),this.actions.SetVariable.forEach(t=>t.dispatch()),this.actions.DynamicVariablePlay.forEach(t=>t.dispatch()),this.actions.ClearLocalStorage.forEach(t=>t.dispatch()),this.actions.UserAPI.forEach(t=>t.dispatch()))}dispatchLeave(){this.actions.Transition.forEach(t=>{t.object.currentTransitionEvent!==this&&(t.object.currentTransitionEvent=this,t.init())}),this.entered&&(this.entered=!1,this.actions.Create.forEach(t=>t.dispatchStop()),this.actions.Transition.forEach(t=>t.reverseFromCurrent()),this.actions.Particles.forEach(t=>t.reverseFromCurrent()),this.actions.SwitchCamera.forEach(t=>t.reverseFromCurrent()))}dispatchUserEvent(t){this.actions.Transition.forEach(e=>{e.object.currentTransitionEvent!==this&&(e.object.currentTransitionEvent=this,e.init())}),t?(this.actions.Transition.forEach(e=>e.reverseFromCurrent()),this.actions.Particles.forEach(e=>e.reverseFromCurrent()),this.actions.Animation.forEach(e=>e.reverseFromCurrent()),this.actions.SwitchCamera.forEach(e=>e.reverseFromCurrent())):(this.actions.Transition.forEach(e=>e.playFromCurrent()),this.actions.Animation.forEach(e=>e.playFromCurrent()),this.actions.Create.forEach(e=>e.dispatch()),this.actions.Particles.forEach(e=>e.dispatchBasic()),this.actions.Destroy.forEach(e=>e.dispatch()),this.actions.SwitchCamera.forEach(e=>e.playFromCurrent())),this.actions.SceneTransition.forEach(e=>e.dispatch()),this.actions.SetVariable.forEach(e=>e.checkConditions()),this.actions.SetVariable.forEach(e=>e.dispatch()),this.actions.DynamicVariablePlay.forEach(e=>e.dispatch()),this.actions.ClearLocalStorage.forEach(e=>e.dispatch()),this.actions.UserAPI.forEach(e=>e.dispatch())}},Gb=class extends Yt{constructor(e,r){super(e);this.eventManager=r;this.eventsPerObjects={};this.objects=[];this.objects2D=[];this._prevObjects=[];this.onMouseDown=e=>{Je.length>1||(this.eventContext.updateRaycaster(e),this.handleMouseHoverEvent())};this.onMouseUp=e=>{Je.length>1||this.handleMouseHoverEvent(!0)};this.onMouseMove=e=>{Je.length>1||(this.eventContext.updateRaycaster(e),this.handleMouseHoverEvent())};this.onUserEvent=({eventName:e,target:r,reverse:i})=>{if(!e||!r)return;let s=Qo(e);s&&s==="MouseHover"&&(r.dispatchEvent({type:"beginEvent",eventName:"MouseHover"}),this.eventsPerObjects[r.uuid]?.forEach(o=>o.dispatchUserEvent(i)))}}connect(){let{page:e,sharedAssets:r}=this.eventContext,i=(o,a)=>{if(!(!o.visible||!o.data?.events.length)){for(let{id:l,data:c}of o.data.events)if(!c.disabled&&c.type==="MouseHover")try{let u=new aM(l,c,o,e,r,this.eventManager);this.eventsPerObjects[o.uuid]?this.eventsPerObjects[o.uuid].push(u):this.eventsPerObjects[o.uuid]=[u]}catch(u){!1&&console.log(u)}this.eventsPerObjects[o.uuid]?.length&&this.objects.push(o instanceof rr?a:o)}};if(e.traverseEntity(o=>{(o instanceof Er||o instanceof ur)&&o.frame?.traverse(a=>{i(a,o)}),i(o)}),!this.objects.length)return;let{domElement:s}=this.eventContext;this.domEventsNeeded.clear(),Ci&&(this.domEventsNeeded.add("pointerdown"),s.addEventListener("pointerdown",this.onMouseDown),this.domEventsNeeded.add("pointerup"),s.addEventListener("pointerup",this.onMouseUp)),this.domEventsNeeded.add("pointermove"),s.addEventListener("pointermove",this.onMouseMove),this.objects.forEach(o=>{o.addEventListener("userEvent",this.onUserEvent)})}disconnect(){if(!this.objects.length)return;let{domElement:e}=this.eventContext;this.domEventsNeeded.clear(),Ci&&(e.removeEventListener("pointerdown",this.onMouseDown),e.removeEventListener("pointerup",this.onMouseUp)),e.removeEventListener("pointermove",this.onMouseMove),Object.values(this.eventsPerObjects).forEach(r=>{r.forEach(i=>{i.disconnect()})}),this.objects.forEach(r=>{r.removeEventListener("userEvent",this.onUserEvent)})}handleMouseHoverEvent(e=!1){let r=[];if(!e){let{stopRaycast:i,raycaster:s,page:o,pointerScreen:a}=this.eventContext,l=!1;if(o.uiCanvas&&(l=so(o,[a.x,a.y],Object.keys(this.eventsPerObjects),c=>{r.push(c)})),i&&!l){let c=zf(s,o,this.objects);r=vg(c),c.forEach(u=>{u.object instanceof Er&&so(u.object,[u?.uv?.x??0,u?.uv?.y??0],Object.keys(this.eventsPerObjects),h=>{r.push(h)})})}else this.objects.forEach(c=>{let u=Gf(s,c);u&&(r.push(c),c instanceof Er&&so(c,[u?.uv?.x??0,u?.uv?.y??0],Object.keys(this.eventsPerObjects),h=>{r.push(h)}))})}this._prevObjects.length&&this._prevObjects.forEach(i=>{r.includes(i)||(i.dispatchEvent({type:"beginEvent",eventName:"MouseHover"}),this.eventsPerObjects[i.uuid]?.forEach(s=>s.dispatchLeave()))}),r.length&&r.forEach(i=>{i.dispatchEvent({type:"beginEvent",eventName:"MouseHover"}),this.eventsPerObjects[i.uuid]?.forEach(s=>s.dispatchEnter())}),this._prevObjects=r}};var lM=class{constructor(t,e,r,i,s,o){this.id=t;this.data=e;this.object=r;this.scrollCounter=0;this.actions=kt(e,e.actions,i,s,o,r)}connect(){this.scrollCounter=0}disconnect(){hr(this.actions)}dispatch(t){this.actions.Transition.forEach(i=>{i.object.currentTransitionEvent!==this&&(i.object.currentTransitionEvent=this,i.init())});let e=t>0?1:-1;this.scrollCounter+=e,this.scrollCounter=Math.min(Math.max(this.scrollCounter,0),this.data.steps);let r=this.scrollCounter/this.data.steps;this.actions.Transition.forEach(i=>i.seek(r)),this.actions.Animation.forEach(i=>i.seek(e)),this.actions.Create.forEach(i=>i.dispatchThrottled()),this.actions.SetVariable.forEach(i=>i.checkConditions()),this.actions.SetVariable.forEach(i=>i.dispatch()),this.actions.DynamicVariablePlay.forEach(i=>i.dispatch()),this.actions.ClearLocalStorage.forEach(i=>i.dispatch()),this.actions.UserAPI.forEach(i=>i.dispatch())}dispatchUserEvent(t){this.actions.Transition.forEach(e=>{e.object.currentTransitionEvent!==this&&(e.object.currentTransitionEvent=this,e.init())}),t?(this.actions.Transition.forEach(e=>e.reverseFromCurrent()),this.actions.Animation.forEach(e=>e.reverseFromCurrent())):(this.actions.Transition.forEach(e=>{e.playFromCurrent()}),this.actions.Animation.forEach(e=>{e.playFromCurrent()})),this.actions.Create.forEach(e=>e.dispatchThrottled()),this.actions.SetVariable.forEach(e=>e.checkConditions()),this.actions.SetVariable.forEach(e=>e.dispatch()),this.actions.DynamicVariablePlay.forEach(e=>e.dispatch()),this.actions.ClearLocalStorage.forEach(e=>e.dispatch()),this.actions.UserAPI.forEach(e=>e.dispatch())}},cM=class{constructor(t,e,r,i,s,o,a){this.id=t;this.data=e;this.object=r;this.domElement=o;this.eventManager=a;this.scrollStart=0;this.scrollEnd=0;this.actions=kt(e,e.actions,i,s,a,r)}getStickyParentElement(){let t=this.domElement;for(;t;){if(window.getComputedStyle(t).position==="sticky")return t;t=t.parentElement}return null}computeScrollBounds(){let t=this.getStickyParentElement(),e=t?.parentElement,r=this.domElement.getBoundingClientRect(),i={top:r.top,bottom:r.bottom,left:r.left,right:r.right,width:r.width,height:r.height};if(e){let u=e.getBoundingClientRect(),h=window.getComputedStyle(t),d=parseFloat(h.marginTop)+parseFloat(h.marginBottom),f=parseFloat(h.top),p=parseFloat(h.bottom),m=u.height-d;if(!isNaN(f))r.top===f?(i.top+=u.top-f,i.bottom+=u.top-f):r.top<0&&(i.top-=m-r.height,i.bottom-=m-r.height);else if(!isNaN(p)){let g=document.body.clientHeight??window.innerHeight,y=window.innerWidth-(document.documentElement.clientWidth??window.innerWidth);r.bottom===g-p?(i.top+=u.top-r.height+p+y,i.bottom+=u.top-r.height+p+y):r.bottom{s.object.currentTransitionEvent!==this&&(s.object.currentTransitionEvent=this,s.init())});let r=this.scrollEnd-this.scrollStart,i=Math.min(1,Math.max(0,(e-this.scrollStart)/r));this.actions.Transition.forEach(s=>s.seek(i)),this.actions.Animation.forEach(s=>s.seek(i)),this.actions.Create.forEach(s=>s.dispatchThrottled()),this.actions.SetVariable.forEach(s=>s.checkConditions()),this.actions.SetVariable.forEach(s=>s.dispatch()),this.actions.DynamicVariablePlay.forEach(s=>s.dispatch()),this.actions.ClearLocalStorage.forEach(s=>s.dispatch()),this.actions.UserAPI.forEach(s=>s.dispatch())}dispatch(t){this.isInvalidBox&&this.computeScrollBounds(),this.computeScroll(t)}dispatchUserEvent(t){this.actions.Transition.forEach(e=>{e.object.currentTransitionEvent!==this&&(e.object.currentTransitionEvent=this,e.init())}),t?(this.actions.Transition.forEach(e=>e.reverseFromCurrent()),this.actions.Animation.forEach(e=>e.reverseFromCurrent())):(this.actions.Transition.forEach(e=>{e.playFromCurrent()}),this.actions.Animation.forEach(e=>{e.playFromCurrent()})),this.actions.Create.forEach(e=>e.dispatchThrottled()),this.actions.SetVariable.forEach(e=>e.checkConditions()),this.actions.SetVariable.forEach(e=>e.dispatch()),this.actions.DynamicVariablePlay.forEach(e=>e.dispatch(