diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index db5e517..0d08989 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -19,6 +19,11 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + # match-screenshots-to-commits.mjs reads `git log --all`; the default + # shallow checkout gives it one commit, so every history card would + # render "No nearby commit found". + fetch-depth: 0 - uses: actions/setup-node@v4 with: node-version: 20 diff --git a/.gitignore b/.gitignore index 5ab8efd..2425c8c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,16 @@ node_modules/ .env.local .env.DS_Store +# Build output — CI (pages.yml) builds fresh; never commit dist +dist/ + +# Generated by scripts/match-screenshots-to-commits.mjs and build-history-page.mjs on every build +scripts/screenshot-commit-mapping.json +scripts/screenshot-commit-mapping.md +public/history.html + # Claude Code session-local artifacts +.playwright-mcp/ .claude/settings.local.json .claude/pre-session-backup.patch .claude/scheduled_tasks.lock diff --git a/README.md b/README.md index 7e7bf36..59519d7 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,10 @@ SkyBloom is a cozy browser flying game and a small benchmark for human-vs-agent racing. Fly a magic carpet through an infinite procedural world, press **R** to start a seeded 12-gate time trial, save local replays, race your best ghost, or let the bundled SimpleBot fly through the same public Agent API a researcher would use. +You can also just talk to it. A co-pilot listens, answers out loud, flies you to landmarks and +reshapes the world on request — against a local model server, your own API key, or fully +on-device. It runs in the page; there is no server of ours in the loop. + ![SkyBloom screenshot](https://github.com/dusterbloom/skybloom/blob/main/screenshots/image.png) @@ -18,10 +22,9 @@ The research loop is visible in-game through the Race Panel: - **Start Race** creates a seeded 12-gate course. - **Load Ghost** loads the best local replay for that seed. -- **Run SimpleBot** starts the reference agent through `window.agentAPI`. - **Export JSON** downloads an honest benchmark result with `courseSeed`, `worldSeed`, `finalTimeMs`, `splits`, `pilot`, fairness config, replay samples, optional action log, build version, and `verificationStatus`. -Quick SimpleBot run from DevTools: +The bundled SimpleBot reference agent flies through the same public `window.agentAPI` a researcher would use — no panel button, drive it from DevTools: ```js const { SimpleBot } = await import('/src/agents/SimpleBot.js'); @@ -31,10 +34,41 @@ bot.start(); More detail: [docs/BENCHMARK.md](docs/BENCHMARK.md), [docs/AGENT_QUICKSTART.md](docs/AGENT_QUICKSTART.md), and [docs/AGENT_API.md](docs/AGENT_API.md). +## Talk to the Carpet + +Open the menu and press **Talk**. A chat panel appears — type at it or speak to it, both go to +the same conversation. It answers out loud and acts: *take me to the crystal formation*, +*raise a mountain ahead*, *make it sunset*, *let me fly the fox*, *make the music epic*. + +Pick a brain in the Agent tab: + +| Brain | Cost | Notes | +|---|---|---| +| Groq | Free tier | Needs a Groq API key (the panel links to where you get one). Model list is fetched live from Groq once the key is entered. | +| OpenRouter | Free tier | Needs an OpenRouter API key (the panel links to where you get one). The model dropdown is filtered to the `:free` models only — the ones that actually cost nothing. | +| Local server | Free, no key | Any OpenAI-compatible endpoint. LM Studio, Jan, Ollama, llama.cpp and vLLM are detected on their default ports and offered before you are asked for anything. | +| Apple FM | Free, no key | macOS 26+ with `fm serve` running (`localhost:1976`) — auto-detected like the other local servers, no key, no model to download. Two models: `pcc` is the default here — fast and consistently accurate — but it is a call to Apple's Private Cloud Compute, not your Mac; `system` runs fully on-device but measured noticeably less reliable and about 2x slower. | +| On-device | Free, no key | WebLLM on WebGPU. Offline once the weights are cached. | + +Every key is scoped to the brain it was issued for — a key saved for Groq is never sent to +OpenRouter, or vice versa. A meter in the panel counts calls, tokens and cost, so the model +routing is checkable rather than claimed. + +Speech uses the browser's own engines, so nothing downloads by default and the reply starts +immediately — on macOS that is the same speech stack Siri uses. Kokoro and Supertonic-3 are +opt-in neural voices that fetch weights on first use. + +Set **Listen** to hands-free and the mic stays open across turns, ending each one when you +sound finished rather than on a fixed timer, so it stops cutting you off mid-sentence. Press +**V** to talk, or to interrupt the co-pilot while it is speaking. + +Typing works in every browser. Speech needs the Web Speech API — Chrome or Safari; Firefox has +no speech recognition, and there the chat panel is the whole feature. + ## Play 1. Open the deployed site or run locally. -2. Press **Play** for free flight, **Race 12 gates** to start a race after loading, or **Run SimpleBot** to watch the reference agent. +2. Press **Play** for free flight, or **R** once flying to start a seeded 12-gate race. 3. Fly through the lit ring to start the race clock. 4. Follow the next-gate beacon until all 12 gates are passed. 5. Finish to save a local replay, then load the ghost and race it. @@ -52,6 +86,7 @@ Controls: | **1-4 / E** | Select / cast spell | | **M** | Toggle map | | **R** | Start a race when not already racing | +| **V** | Talk to the co-pilot, or interrupt it mid-sentence | Tip: diving trades altitude for speed. The first race is meant to be readable: follow the gold gate and beacon, use the Race Panel for status, and load a ghost after a clean finish. @@ -61,6 +96,10 @@ Tip: diving trades altitude for speed. The first race is meant to be readable: f - Seeded 12-gate time trials with local splits, best times, replay storage, and ghost playback. - Agent API with information/action/tempo fairness constraints: `observe()`, `act()`, `startRace()`, replay/ghost helpers, config, WebSocket transport, and result export. - Reference SimpleBot that uses only `window.agentAPI`. +- Voice co-pilot: speech or typing into one conversation, a spoken reply, and an intent it acts + on. Runs entirely in the page against Groq, OpenRouter, a local server, or an on-device model, + with per-task model routing and a token/cost meter. +- **Creative "genie" API** (`window.worldAPI`) — a separate, non-fairness godmode surface: conjure shapes and animated rigs, import real models from curated repos (flapping birds, propeller planes), fly any of them or **roam as an animal on the ground**, persist everything in a catalogue, and reshape terrain/sky. Speakable by voice or a small LLM. See [docs/AGENT_API.md](docs/AGENT_API.md#creative-mode-the-genie-windowworldapi). - Optional socket.io multiplayer co-presence for casual local experimentation. - GitHub Pages workflow, CI build check, local smoke script, and one-command local launcher. @@ -73,6 +112,14 @@ Tip: diving trades altitude for speed. The first race is meant to be readable: f - GitHub Pages is static hosting. It runs the game, races, ghosts, SimpleBot, and browser Agent API, but it does not host the socket.io multiplayer server. - External local agents from a Pages tab may need `wss://`; for `ws://localhost` research, use a local dev/preview page. - Mobile should load and fly, but the research panel is intentionally compact rather than a full mobile leaderboard UI. +- Speech recognition is the browser's, not ours. Chrome sends microphone audio to Google's + servers, Safari on macOS uses on-device dictation, and Firefox has none. Only the on-device + brain paired with the OS voice keeps a whole turn local. +- A Groq or OpenRouter key typed into the settings lives in this browser's localStorage and goes + straight from the page to that provider — each key is scoped to the brain it was saved for, so + a Groq key is never sent to OpenRouter or back. Fine for your own key; never use a shared one. +- The co-pilot's world edits go through `window.worldAPI`, which is deliberately outside the + fairness constraints. Reshaping terrain mid-race does not produce a comparable benchmark run. ## Run Locally diff --git a/dist/assets/MaterialSystemIntegration-CnfDoB_F.js b/dist/assets/MaterialSystemIntegration-CnfDoB_F.js deleted file mode 100644 index 3d02b2d..0000000 --- a/dist/assets/MaterialSystemIntegration-CnfDoB_F.js +++ /dev/null @@ -1,76 +0,0 @@ -import{C as v,aA as w,x as b,s as x,ax as S,ay as T,aU as P,o as z,ai as E,am as D}from"./three-CH6znIGP.js";class f{constructor(e){this.engine=e,this.deviceTier=this.detectDeviceTier(),this.proceduralMaterials=new Map,this.qualitySettings=this.initializeQualitySettings(),this.materialCache=new Map,this.carpetMaterialParams={baseColor:new v(8930559),patternScale:this.deviceTier==="low"?2:4,detailLevel:this.qualitySettings.proceduralDetail,glowIntensity:this.deviceTier==="low"?.3:.5},this.trailMaterialParams={baseOpacity:this.deviceTier==="low"?.4:.7,glowIntensity:this.deviceTier==="low"?.3:.5,particleSize:this.deviceTier==="low"?.07:.1},this.stats={proceduralTexturesGenerated:0,cacheHits:0,cacheMisses:0,peakMemoryUsage:0},this.initializeMaterials()}detectDeviceTier(){const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return"low";const i=t.getParameter(t.MAX_TEXTURE_SIZE)>=8192&&t.getParameter(t.MAX_RENDERBUFFER_SIZE)>=8192&&navigator.hardwareConcurrency>=4,o=t.getParameter(t.MAX_TEXTURE_SIZE)<=2048||t.getParameter(t.MAX_RENDERBUFFER_SIZE)<=2048||navigator.deviceMemory<=2||/Mobile|Android|iPhone/i.test(navigator.userAgent);return i?"high":o?"low":"medium"}initializeQualitySettings(){return{high:{textureSize:2048,proceduralDetail:1,mipLevels:8,anisotropy:16,shaderComplexity:"high"},medium:{textureSize:1024,proceduralDetail:.7,mipLevels:6,anisotropy:8,shaderComplexity:"medium"},low:{textureSize:512,proceduralDetail:.4,mipLevels:4,anisotropy:4,shaderComplexity:"low"}}[this.deviceTier]}initializeMaterials(){this.createCarpetMaterial(),this.createTrailMaterials()}createCarpetMaterial(){const e=this.generateProceduralTexture("carpet",{size:this.qualitySettings.textureSize,detail:this.carpetMaterialParams.patternScale,color:this.carpetMaterialParams.baseColor}),t=new w({uniforms:{baseTexture:{value:e},glowIntensity:{value:this.carpetMaterialParams.glowIntensity},time:{value:0}},vertexShader:this.getCarpetVertexShader(),fragmentShader:this.getCarpetFragmentShader()});this.materialCache.set("carpet",t)}createTrailMaterials(){const e=new b({color:8978431,transparent:!0,opacity:this.trailMaterialParams.baseOpacity,depthWrite:!1}),t=new x({color:16777215,size:this.trailMaterialParams.particleSize,transparent:!0,opacity:this.trailMaterialParams.baseOpacity,depthWrite:!1,blending:S});this.materialCache.set("trail",e),this.materialCache.set("particle",t)}generateProceduralTexture(e,t){const i=`${e}-${JSON.stringify(t)}`;if(this.proceduralMaterials.has(i))return this.stats.cacheHits++,this.proceduralMaterials.get(i);const o=Math.min(t.size||512,this.qualitySettings.textureSize),n=document.createElement("canvas");n.width=n.height=o;const r=n.getContext("2d");switch(e){case"carpet":this.generateCarpetPattern(r,t);break;case"noise":this.generateNoiseTexture(r,t);break}const a=new T(n);return a.generateMipmaps=!0,a.minFilter=P,a.magFilter=z,a.anisotropy=this.qualitySettings.anisotropy,this.proceduralMaterials.set(i,a),this.stats.proceduralTexturesGenerated++,a}generateCarpetPattern(e,t){const{size:i=512,detail:o=1,color:n=new v(8930559)}=t;e.fillStyle=n.getStyle(),e.fillRect(0,0,i,i);const r=Math.max(2,Math.floor(8*o*this.qualitySettings.proceduralDetail)),a=i/r;for(let l=0;ls*s*s*(s*(s*6-15)+10),r=(s,u,p)=>u+s*(p-u),a=(s,u,p)=>{const d=s&15,y=1+(d&7),C=d&8?-1:1;return y*u+C*p},l=new Array(512);for(let s=0;s<256;s++)l[s]=l[s+256]=s*16807%256;const c=n(e),m=n(t),g=l[i]+o,h=l[i+1]+o;return r(m,r(c,a(l[g],e,t),a(l[h],e-1,t)),r(c,a(l[g+1],e,t-1),a(l[h+1],e-1,t-1)))}getCarpetVertexShader(){return` - varying vec2 vUv; - varying vec3 vNormal; - varying vec3 vViewPosition; - - void main() { - vUv = uv; - vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); - gl_Position = projectionMatrix * mvPosition; - - vNormal = normalize(normalMatrix * normal); - vViewPosition = -mvPosition.xyz; - } - `}getCarpetFragmentShader(){switch(this.qualitySettings.shaderComplexity){case"low":return this.getLowQualityCarpetShader();case"medium":return this.getMediumQualityCarpetShader();case"high":return this.getHighQualityCarpetShader();default:return this.getMediumQualityCarpetShader()}}getLowQualityCarpetShader(){return` - uniform sampler2D baseTexture; - uniform float glowIntensity; - varying vec2 vUv; - - void main() { - vec4 texColor = texture2D(baseTexture, vUv); - gl_FragColor = texColor; - } - `}getMediumQualityCarpetShader(){return` - uniform sampler2D baseTexture; - uniform float glowIntensity; - uniform float time; - - varying vec2 vUv; - varying vec3 vNormal; - - void main() { - vec4 texColor = texture2D(baseTexture, vUv); - - // Add simple lighting - float lightIntensity = max(dot(vNormal, vec3(0.0, 1.0, 0.0)), 0.3); - - // Add subtle glow - float glow = sin(time) * 0.5 + 0.5; - vec3 finalColor = texColor.rgb * lightIntensity + (texColor.rgb * glow * glowIntensity); - - gl_FragColor = vec4(finalColor, texColor.a); - } - `}getHighQualityCarpetShader(){return` - uniform sampler2D baseTexture; - uniform float glowIntensity; - uniform float time; - - varying vec2 vUv; - varying vec3 vNormal; - varying vec3 vViewPosition; - - void main() { - vec4 texColor = texture2D(baseTexture, vUv); - - // Enhanced lighting with fresnel effect - vec3 viewDir = normalize(vViewPosition); - float fresnel = pow(1.0 - max(dot(vNormal, viewDir), 0.0), 3.0); - - // Multi-layered lighting - float directLight = max(dot(vNormal, vec3(0.0, 1.0, 0.0)), 0.3); - float rimLight = pow(1.0 - max(dot(vNormal, viewDir), 0.0), 2.0) * 0.5; - float lightIntensity = directLight + rimLight; - - // Complex glow effect - float timeScale = time * 0.5; - float glow = sin(timeScale) * 0.3 + cos(timeScale * 0.7) * 0.2 + 0.5; - float patternGlow = sin(vUv.x * 20.0 + time) * sin(vUv.y * 20.0 + time) * 0.1; - - // Combine effects - vec3 finalColor = texColor.rgb * lightIntensity; - finalColor += texColor.rgb * (glow + patternGlow) * glowIntensity; - finalColor += fresnel * texColor.rgb * 0.3; - - gl_FragColor = vec4(finalColor, texColor.a); - } - `}getMaterial(e){return this.materialCache.get(e)}updateMaterials(e){const t=this.materialCache.get("carpet");t&&t.uniforms&&(t.uniforms.time.value=e)}disposeTexture(e,t){const i=`${e}-${JSON.stringify(t)}`;this.proceduralMaterials.has(i)&&(this.proceduralMaterials.get(i).dispose(),this.proceduralMaterials.delete(i))}resetMaterials(){console.log("Resetting materials due to visibility change"),this.proceduralMaterials.forEach((e,t)=>{e&&e.needsUpdate!==void 0&&(e.needsUpdate=!0)}),this.materialCache.forEach(e=>{e.uniforms&&(e.uniforms.time&&(e.uniforms.time.value=0),Object.values(e.uniforms).forEach(t=>{t.value&&t.value.isTexture&&(t.value.needsUpdate=!0)}))})}dispose(){this.materialCache.forEach(e=>{e.uniforms&&Object.values(e.uniforms).forEach(t=>{t.value&&t.value.isTexture&&t.value.dispose()}),e.dispose()}),this.proceduralMaterials.forEach(e=>{e.dispose()}),this.materialCache.clear(),this.proceduralMaterials.clear()}}class I{constructor(e){this.engine=e,this.materialManager=new f(e)}async initialize(){this.integrateWithCarpetTrail(),this.integrateWithCarpetController()}integrateWithCarpetTrail(){const e=this.engine.systems.carpetTrail;if(!e||["initialize","createParticle","createSteamParticle","updateRibbonTrail","initializePools"].some(r=>typeof e[r]!="function"))return;e.initialize.bind(e),e.initialize=()=>{console.log("Using optimized materials for carpet trail"),e.particleGeometry=new E(.1,e.isMobile?3:4,e.isMobile?3:4),e.steamGeometry=new D(.5,.5),e.particleMaterial=this.materialManager.getMaterial("particle").clone(),e.ribbonMaterial=this.materialManager.getMaterial("trail").clone(),e.motionLineMaterial=this.materialManager.getMaterial("trail").clone(),e.steamMaterial=this.materialManager.getMaterial("particle").clone(),e.initializePools()};const i=e.createParticle.bind(e);e.createParticle=r=>{const a=i(r);return a&&(a.material=this.materialManager.getMaterial("particle").clone()),a};const o=e.createSteamParticle.bind(e);e.createSteamParticle=r=>{const a=o(r);return a&&(a.material=this.materialManager.getMaterial("particle").clone(),a.material.opacity=.4),a};const n=e.updateRibbonTrail.bind(e);e.updateRibbonTrail=r=>{const a=n(r);return e.ribbonMesh&&(e.ribbonMesh.material=this.materialManager.getMaterial("trail").clone()),a}}integrateWithCarpetController(){const e=this.engine.systems.player?.localPlayer;if(!e)return;const t=e.getObjectByName("carpet");t&&(t.material=this.materialManager.getMaterial("carpet"))}update(e){this.materialManager.updateMaterials(this.engine.elapsed)}reoptimizeMaterials(){console.log("Reoptimizing materials for new device capabilities");const e=new Map(this.materialManager.materialCache);this.materialManager=new f(this.engine),this.integrateWithCarpetTrail(),this.integrateWithCarpetController(),setTimeout(()=>{e.forEach(t=>{t.uniforms&&Object.values(t.uniforms).forEach(i=>{i.value&&i.value.isTexture&&i.value.dispose()}),t.dispose()})},1e3)}dispose(){this.materialManager.dispose()}}export{I as MaterialSystemIntegration}; diff --git a/dist/assets/MobileUI-4RxndL5M.js b/dist/assets/MobileUI-4RxndL5M.js deleted file mode 100644 index b0f381f..0000000 --- a/dist/assets/MobileUI-4RxndL5M.js +++ /dev/null @@ -1,110 +0,0 @@ -class c{constructor(e){this.engine=e||{qualityManager:{uiAnimationLevel:"low"}},this.uiElements=new Map,this.visibleElements=new Set,this.touchElements=new Map,this.elementPool=new Map,this.batterySaving=!1,this.screenWidth=window.innerWidth,this.screenHeight=window.innerHeight,this.orientationLayout=this.screenWidth>this.screenHeight?"landscape":"portrait",this.devicePixelRatio=window.devicePixelRatio||1,this.hasHapticFeedback="vibrate"in navigator,this.isDeviceSmall=Math.min(this.screenWidth,this.screenHeight)<600,this.frameCounter=0,this.batteryUpdateFrequency=1,this.sizes={buttonSize:this.isDeviceSmall?70:80,joystickSize:this.isDeviceSmall?130:150,healthBarWidth:Math.min(320,this.screenWidth*.6),spacing:this.isDeviceSmall?10:15},this.memoryUsage={elementsCreated:0,activeElements:0,poolSize:0},this.visible=!0,window.addEventListener("resize",this.onResize.bind(this))}initialize(){this.createUIContainer(),this.createSimpleControls(),this.createBatterySavingToggle(),this.ensureMobileMinimapVisibility(),console.log("Mobile UI initialized with simplified user controls")}createUIContainer(){const e=document.createElement("div");e.id="mobile-ui-container",e.style.cssText=` - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; - pointer-events: none; - z-index: 1000; - touch-action: none; - `,document.body.appendChild(e),this.uiElements.set("container",e),this.uiContainer=e;const t=()=>{document.documentElement.style.setProperty("--vh",`${window.innerHeight*.01}px`),e.style.height="calc(var(--vh, 1vh) * 100)"};window.addEventListener("resize",t),t()}touchOnUIElement(e){const t=e.changedTouches[0],i=t.clientX,n=t.clientY;for(const[s,a]of this.touchElements.entries())if(a.type==="button"||a.type==="toggle"){const o=a.element;if(!o)continue;const r=o.getBoundingClientRect();if(i>=r.left&&i<=r.right&&n>=r.top&&n<=r.bottom)return!0}return!1}setupCameraControls(){const e=this.getElementFromPool("div")||document.createElement("div");e.id="camera-controls",e.style.cssText=` - position: fixed; - top: 0; - left: 0; - width: 100%; /* Full screen */ - height: 100%; - z-index: 500; /* Below other UI controls */ - pointer-events: auto; - touch-action: none; - user-select: none; - `,this.cameraState={active:!1,lastX:0,lastY:0,deltaX:0,deltaY:0,touchId:null,startX:0,startY:0},e.addEventListener("touchstart",i=>{if(this.touchOnUIElement(i)||(i.preventDefault(),this.cameraState.active))return;const n=i.changedTouches[0];this.cameraState.touchId=n.identifier,this.cameraState.active=!0,this.cameraState.lastX=n.clientX,this.cameraState.lastY=n.clientY,this.cameraState.startX=n.clientX,this.cameraState.startY=n.clientY,this.cameraState.deltaX=0,this.cameraState.deltaY=0}),e.addEventListener("touchmove",i=>{if(this.cameraState.active){i.preventDefault();for(let n=0;n{if(!this.cameraState.active)return;i.preventDefault();let n=!1;for(let s=0;s{s.preventDefault(),t.style.background="rgba(30, 144, 255, 0.7)",this.engine&&this.engine.input&&this.engine.input.keys&&(this.engine.input.keys.KeyW=!0,this.engine.input.keys.KeyS=!1),this.engine&&this.engine.systems&&this.engine.systems.player&&this.engine.systems.player.input&&(this.engine.systems.player.input.currentThrottle=1),this.triggerHapticFeedback("button")}),t.addEventListener("touchend",s=>{s.preventDefault(),t.style.background="rgba(30, 144, 255, 0.3)",this.engine&&this.engine.input&&this.engine.input.keys&&(this.engine.input.keys.KeyW=!1),this.engine&&this.engine.systems&&this.engine.systems.player&&this.engine.systems.player.input&&(this.engine.systems.player.input.currentThrottle=0)}),i.addEventListener("touchstart",s=>{s.preventDefault(),i.style.background="rgba(160, 160, 160, 0.7)",this.engine&&this.engine.input&&this.engine.input.keys&&(this.engine.input.keys.KeyS=!0,this.engine.input.keys.KeyW=!1),this.triggerHapticFeedback("button")}),i.addEventListener("touchend",s=>{s.preventDefault(),i.style.background="rgba(160, 160, 160, 0.3)",this.engine&&this.engine.input&&this.engine.input.keys&&(this.engine.input.keys.KeyS=!1)});const n=this.getElementFromPool("div")||document.createElement("div");n.style.cssText=` - display: flex; - flex-direction: column; - gap: 10px; - pointer-events: none; - `,n.appendChild(t),n.appendChild(i),e.appendChild(n),this.uiContainer.appendChild(e),this.uiElements.set("controlsContainer",e),this.uiElements.set("forwardButton",t),this.uiElements.set("backwardButton",i),this.visibleElements.add("controlsContainer"),this.touchElements.set("forward-button",{element:t,type:"button",action:"forward"}),this.touchElements.set("backward-button",{element:i,type:"button",action:"backward"}),this.memoryUsage.activeElements+=3}createBatterySavingToggle(){const e=this.getElementFromPool("div")||document.createElement("div");e.id="battery-toggle",e.style.cssText=` - position: fixed; - top: ${this.sizes.spacing}px; - right: ${this.sizes.spacing}px; - display: flex; - align-items: center; - background: rgba(0, 0, 0, 0.3); - border-radius: 20px; - padding: 4px 8px; - z-index: 1000; - pointer-events: auto; - `;const t=this.getElementFromPool("div")||document.createElement("div");t.textContent="Power Save",t.style.cssText=` - color: white; - font-size: 12px; - margin-right: 5px; - `;const i=this.getElementFromPool("div")||document.createElement("div");i.style.cssText=` - width: 30px; - height: 16px; - background: #555; - border-radius: 8px; - position: relative; - transition: background 0.3s; - `;const n=this.getElementFromPool("div")||document.createElement("div");n.style.cssText=` - position: absolute; - width: 12px; - height: 12px; - border-radius: 50%; - background: white; - top: 2px; - left: 2px; - transition: transform 0.3s; - `,i.appendChild(n),e.appendChild(t),e.appendChild(i),this.uiContainer.appendChild(e),this.uiElements.set("batterySaver",e),this.uiElements.set("batterySaverToggle",i),this.uiElements.set("batterySaverHandle",n),this.visibleElements.add("batterySaver"),this.memoryUsage.activeElements+=3,i.addEventListener("touchend",s=>{s.preventDefault(),this.toggleBatterySavingMode(),this.triggerHapticFeedback("toggle")}),this.touchElements.set("battery-toggle",{element:i,type:"toggle",action:"battery"})}ensureMobileMinimapVisibility(){setTimeout(()=>{const e=document.getElementById("minimap-container");if(e)e.style.position="absolute",e.style.top="var(--vc-left-stack-top)",e.style.left="var(--vc-safe-x)",e.style.width="var(--vc-minimap-size)",e.style.height="var(--vc-minimap-size)",e.style.zIndex="1500",e.style.display="block",e.style.opacity="1",e.style.visibility="visible",console.log("Mobile minimap visibility enforced");else{console.warn("Minimap container not found, creating it manually");const t=document.createElement("div");t.id="minimap-container",t.style.cssText=` - position: absolute; - top: var(--vc-left-stack-top); - left: var(--vc-safe-x); - width: var(--vc-minimap-size); - height: var(--vc-minimap-size); - border-radius: 50%; - overflow: hidden; - background-color: rgba(0, 0, 20, 0.5); - border: 2px solid rgba(255, 255, 255, 0.5); - box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); - z-index: 1500; - display: block; - opacity: 1; - visibility: visible; - `,this.uiContainer.appendChild(t)}},1e3)}toggleBatterySavingMode(){this.batterySaving=!this.batterySaving;const e=this.uiElements.get("batterySaverToggle"),t=this.uiElements.get("batterySaverHandle");this.batterySaving?(e.style.background="#4CAF50",t.style.transform="translateX(16px)",this.applyBatterySavingMode(!0)):(e.style.background="#555",t.style.transform="translateX(0)",this.applyBatterySavingMode(!1))}applyBatterySavingMode(e){e?(document.documentElement.style.setProperty("--ui-animation-speed","0.5"),this.uiElements.forEach(t=>{t.style&&t.style.backdropFilter&&(t.style.backdropFilter="none"),t.style&&t.style.boxShadow&&(t.style.boxShadow="none")}),this.batteryUpdateFrequency=3):(document.documentElement.style.setProperty("--ui-animation-speed","1"),this.batteryUpdateFrequency=1),this.engine&&(typeof this.engine.setBatterySavingMode=="function"?this.engine.setBatterySavingMode(e):this.engine.qualityManager&&(this.engine.qualityManager.targetFPS=e?30:60))}triggerHapticFeedback(e){if(!(!this.hasHapticFeedback||this.batterySaving))switch(e){case"button":navigator.vibrate(20);break;case"toggle":navigator.vibrate(15);break;case"boost":navigator.vibrate([20,30,40]);break;default:navigator.vibrate(25)}}onResize(){this.screenWidth=window.innerWidth,this.screenHeight=window.innerHeight}getElementFromPool(e){this.elementPool.has(e)||this.elementPool.set(e,[]);const t=this.elementPool.get(e);if(t.length>0){const i=t.pop();return this.memoryUsage.poolSize--,i}return this.memoryUsage.elementsCreated++,null}returnElementToPool(e){if(!e)return;e.parentNode&&e.parentNode.removeChild(e),e.className="",e.id="",e.textContent="",e.innerHTML="",e.removeAttribute("style"),e.replaceWith(e.cloneNode(!1));const t=e.tagName.toLowerCase();this.elementPool.has(t)||this.elementPool.set(t,[]),this.elementPool.get(t).push(e),this.memoryUsage.poolSize++,this.memoryUsage.activeElements--}update(e,t){try{if(this.frameCounter===void 0&&(this.frameCounter=0),this.batterySaving&&this.frameCounter++%(this.batteryUpdateFrequency||1)!==0)return;if(this.frameCounter%60===0){const i=document.getElementById("minimap-container");i&&(i.style.display==="none"||!i.isConnected)&&this.ensureMobileMinimapVisibility()}}catch(i){console.warn("Error updating mobile UI:",i)}}dispose(){this.uiElements.forEach(e=>{e&&e.parentNode&&this.returnElementToPool(e)}),this.uiElements.clear(),this.visibleElements.clear(),this.touchElements.clear(),window.removeEventListener("resize",this.onResize),console.log("Mobile UI disposed with memory stats:",this.memoryUsage)}}export{c as MobileUI}; diff --git a/dist/assets/PhysicsSystem-DKc5nAHw.js b/dist/assets/PhysicsSystem-DKc5nAHw.js deleted file mode 100644 index c7e4b4f..0000000 --- a/dist/assets/PhysicsSystem-DKc5nAHw.js +++ /dev/null @@ -1 +0,0 @@ -import{g as c,Q as g,az as y}from"./three-CH6znIGP.js";class d{constructor(t=1){this.mass=t,this.position=new c,this.velocity=new c,this.acceleration=new c,this.rotation=new y,this.angularVelocity=new c,this.quaternion=new g,this.forces=new c,this.torques=new c,this.surfaceArea=10,this.dragCoefficient=.1,this.liftCoefficient=.3}integrate(t){this.position.addScaledVector(this.velocity,t),this.velocity.addScaledVector(this.acceleration,t),this.quaternion.setFromEuler(this.rotation);const i=new g;i.setFromAxisAngle(this.angularVelocity.normalize(),this.angularVelocity.length()*t),this.quaternion.premultiply(i),this.rotation.setFromQuaternion(this.quaternion),this.forces.set(0,0,0),this.torques.set(0,0,0)}}class S{constructor(t){this.engine=t,this.gravity=-9.81,this.airDensity=1.225,this.timeStep=1/60,this.maxSubSteps=3,this._tempVec3=new c,this._tempVec3_2=new c,this._tempVec3_3=new c,this._tempQuat=new g,this.bodies=new Map,this.heightCache=new C,this.normalCache=new Map,this.maxNormalCacheSize=500,this.lastPerformanceLog=0,this.performanceLogInterval=5e3,t&&t.isMobile!==void 0&&this.heightCache.adaptToDeviceCapabilities(t.isMobile)}async initialize(){return console.log("Initializing PhysicsSystem..."),this.heightCache.clear(),this.engine&&this.engine.isMobile!==void 0&&this.heightCache.adaptToDeviceCapabilities(this.engine.isMobile),console.log("PhysicsSystem initialized"),Promise.resolve()}createRigidBody(t,i=1){const s=new d(i);return this.bodies.set(t,s),s}removeRigidBody(t){this.bodies.delete(t)}update(t,i,s){const e=Math.min(Math.ceil(t/this.timeStep),this.maxSubSteps),o=t/e;for(let h=0;hthis.performanceLogInterval&&(this.logPerformanceMetrics(),this.lastPerformanceLog=s)}logPerformanceMetrics(){if(!this.engine||!this.engine.debug)return;const t=this.heightCache.getStats();console.log("Terrain Height Cache Stats:",t),console.log("Normal Cache Size:",this.normalCache.size)}updatePhysics(t,i){for(const[s,e]of this.bodies)this.applyGravity(e),this.applyAerodynamics(e),e.acceleration.copy(e.forces).divideScalar(e.mass),e.integrate(t),i&&this.handleTerrainCollision(e,i)}applyGravity(t){t.forces.y+=t.mass*this.gravity}applyAerodynamics(t){const i=this._tempVec3.set(0,0,1).applyQuaternion(t.quaternion),s=this._tempVec3_2.copy(t.velocity),e=s.length();if(e>1e-4){const o=Math.acos(i.dot(s.normalize())),h=t.liftCoefficient*Math.sin(2*o),n=t.dragCoefficient+t.liftCoefficient*Math.pow(Math.sin(o),2),a=.5*this.airDensity*e*e,r=this._tempVec3.set(0,1,0).applyQuaternion(t.quaternion).multiplyScalar(h*a*t.surfaceArea),l=this._tempVec3_2.copy(s).normalize().multiplyScalar(-n*a*t.surfaceArea);t.forces.add(r),t.forces.add(l)}}handleTerrainCollision(t,i){const e=this.getTerrainHeight(t.position.x,t.position.z,i)+2;if(t.position.y1e-4){const a=n.normalize().multiplyScalar(-.3*Math.abs(h)*t.mass);t.forces.add(a)}}}getTerrainHeight(t,i,s){const e=this.heightCache.get(t,i);if(e!==void 0)return e;const o=s.getTerrainHeight(t,i);return this.heightCache.set(t,i,o),o}calculateTerrainNormal(t,i,s){const e=this.heightCache.resolution*2,o=Math.floor(t/e)*e,h=Math.floor(i/e)*e,n=`${o},${h}`;if(this.normalCache.has(n))return this._tempVec3.copy(this.normalCache.get(n));const a=1,r=this.getTerrainHeight(t,i,s),l=this.getTerrainHeight(t+a,i,s),u=this.getTerrainHeight(t,i+a,s),m=new c(-(l-r)/a,1,-(u-r)/a).normalize();if(this.normalCache.size>=this.maxNormalCacheSize){const p=this.normalCache.keys().next().value;this.normalCache.delete(p)}return this.normalCache.set(n,m.clone()),this._tempVec3.copy(m)}}class C{constructor(t=32){this.resolution=t,this.cache=new Map,this.maxEntries=5e3,this.hits=0,this.misses=0,this.accessCount=0,this.accessOrder=[],this.adaptiveResolution=!0,this.highActivityRegions=new Map,this.regionAccessThreshold=10,this.regionSize=512}key(t,i){let s=this.resolution;if(this.adaptiveResolution){const h=Math.floor(t/this.regionSize)*this.regionSize,n=Math.floor(i/this.regionSize)*this.regionSize,a=`${h},${n}`;this.highActivityRegions.has(a)&&(s=this.resolution/2)}const e=Math.floor(t/s)*s,o=Math.floor(i/s)*s;return`${e},${o}`}get(t,i){if(this.accessCount++,this.adaptiveResolution&&this.accessCount%10===0){const o=Math.floor(t/this.regionSize)*this.regionSize,h=Math.floor(i/this.regionSize)*this.regionSize,n=`${o},${h}`,a=this.highActivityRegions.get(n)||0;this.highActivityRegions.set(n,a+1),this.highActivityRegions.size>20&&this.cleanupActivityRegions()}const s=this.key(t,i),e=this.cache.get(s);if(e!==void 0){const o=this.accessOrder.indexOf(s);return o!==-1&&this.accessOrder.splice(o,1),this.accessOrder.push(s),this.hits++,e}this.misses++}set(t,i,s){const e=this.key(t,i);for(;this.cache.size>=this.maxEntries&&this.accessOrder.length>0;){const o=this.accessOrder.shift();this.cache.delete(o)}this.cache.set(e,s),this.accessOrder.push(e)}cleanupActivityRegions(){const t=Array.from(this.highActivityRegions.entries()).sort((i,s)=>s[1]-i[1]);this.highActivityRegions=new Map(t.slice(0,10).filter(i=>i[1]>=this.regionAccessThreshold))}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.accessCount=0}getStats(){const t=this.accessCount>0?this.hits/this.accessCount*100:0;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:t.toFixed(2)+"%",highActivityRegions:this.highActivityRegions.size}}adaptToDeviceCapabilities(t){t?(this.maxEntries=2e3,this.resolution=48,this.regionSize=256):(this.maxEntries=5e3,this.resolution=32,this.regionSize=512)}}export{S as PhysicsSystem}; diff --git a/dist/assets/audio/background.mp3 b/dist/assets/audio/background.mp3 deleted file mode 100644 index 566a4c3..0000000 --- a/dist/assets/audio/background.mp3 +++ /dev/null @@ -1,5 +0,0 @@ -<<<<<<< HEAD - -======= - ->>>>>>> 3ba54ef83a25f19ba1b39a083bea4b653822e498 diff --git a/dist/assets/audio/collect.mp3 b/dist/assets/audio/collect.mp3 deleted file mode 100644 index d61d8d8..0000000 Binary files a/dist/assets/audio/collect.mp3 and /dev/null differ diff --git a/dist/assets/audio/spell.mp3 b/dist/assets/audio/spell.mp3 deleted file mode 100644 index 566a4c3..0000000 --- a/dist/assets/audio/spell.mp3 +++ /dev/null @@ -1,5 +0,0 @@ -<<<<<<< HEAD - -======= - ->>>>>>> 3ba54ef83a25f19ba1b39a083bea4b653822e498 diff --git a/dist/assets/bg.png b/dist/assets/bg.png deleted file mode 100644 index 31cd9a2..0000000 Binary files a/dist/assets/bg.png and /dev/null differ diff --git a/dist/assets/crescent.png b/dist/assets/crescent.png deleted file mode 100644 index b253254..0000000 Binary files a/dist/assets/crescent.png and /dev/null differ diff --git a/dist/assets/game-BePiI9nb.js b/dist/assets/game-BePiI9nb.js deleted file mode 100644 index ebd7a52..0000000 --- a/dist/assets/game-BePiI9nb.js +++ /dev/null @@ -1,696 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MaterialSystemIntegration-CnfDoB_F.js","assets/three-CH6znIGP.js","assets/PhysicsSystem-DKc5nAHw.js"])))=>i.map(i=>d[i]); -import{T as mi,a as Dt,b as Hs,L as Vs,c as Ke,F as rt,M as ve,V as Fe,C,d as be,S as we,e as pi,P as fi,D as Xt,f as ye,g as A,I as Us,Q as Yt,h as yi,O as Qt,i as Be,j as gi,B as ce,k as bi,l as qs,N as wi,m as xi,n as Si,o as Ws,p as vi,R as me,q as Mi,r as Lt,s as lt,t as xt,u as _i,v as R,w as pe,x as V,y as Ti,z as ze,A as ki,E as k,G as Ai,H as Ci,J as Ei,K as ct,U as ee,W as Zt,X as K,Y as Pi,Z as Ri,_ as Di,$ as Li,a0 as Ii,a1 as $s,a2 as Ni,a3 as as,a4 as rs,a5 as ls,a6 as cs,a7 as It,a8 as pt,a9 as Oi,aa as Fi,ab as js,ac as zi,ad as Bi,ae as Ve,af as Ue,ag as Q,ah as Z,ai as $,aj as fe,ak as Ks,al as Gi,am as Ne,an as Pe,ao as ht,ap as dt,aq as tt,ar as Jt,as as st,at as Hi,au as Vi,av as Ui,aw as Nt,ax as De,ay as Le,az as ut,aA as Xe,aB as Ot,aC as Xs,aD as qi,aE as mt,aF as hs,aG as Ft,aH as Wi,aI as ds,aJ as $i,aK as us,aL as ji,aM as ms,aN as Ki,aO as ps,aP as Xi,aQ as Yi,aR as Qi,aS as Zi,aT as Ji}from"./three-CH6znIGP.js";const en="modulepreload",tn=function(h){return"/skybloom/"+h},fs={},St=function(e,t,s){let i=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");i=Promise.allSettled(t.map(r=>{if(r=tn(r),r in fs)return;fs[r]=!0;const l=r.endsWith(".css"),c=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${r}"]${c}`))return;const d=document.createElement("link");if(d.rel=l?"stylesheet":en,l||(d.as="script"),d.crossOrigin="",d.href=r,a&&d.setAttribute("nonce",a),document.head.appendChild(d),l)return new Promise((u,m)=>{d.addEventListener("load",u),d.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${r}`)))})}))}function n(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&n(a.reason);return e().catch(n)})};class sn{constructor(){this.isMobile=!1,this.pixelRatio=Math.min(window.devicePixelRatio||1,2),this.gpuTier="unknown",this.memoryLimited=!1,this.supportsFloatTextures=!0,this.supportsDepthTexture=!0,this.supportsShadowMapType=!0,this.maxTextureSize=4096,this.detect()}detect(){return this.isMobile=this._detectMobile(),this._detectWebGLCapabilities(),this._classifyGPUTier(),this._logDetectionResults(),this.isMobile}_detectMobile(){const e=navigator.userAgent.toLowerCase();return!!(/(android|iphone|ipad|ipod|blackberry|windows phone)/g.test(e)||window.innerWidth<768)}_detectWebGLCapabilities(){try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(t){this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE);const s=t.getExtension("OES_texture_float");this.supportsFloatTextures=!!s;const i=t.getExtension("WEBGL_depth_texture");if(this.supportsDepthTexture=!!i,t.getExtension("WEBGL_debug_renderer_info")){const n=t.getParameter(t.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL),o=t.getParameter(t.getExtension("WEBGL_debug_renderer_info").UNMASKED_VENDOR_WEBGL);this.gpuInfo={renderer:n,vendor:o},this.rawRendererInfo=n.toLowerCase()}}else console.warn("WebGL not supported - using fallback values"),this.memoryLimited=!0,this.maxTextureSize=1024,this.supportsFloatTextures=!1,this.supportsDepthTexture=!1}catch(e){console.warn("Failed to detect WebGL capabilities:",e),this.memoryLimited=!0,this.maxTextureSize=1024,this.supportsFloatTextures=!1,this.supportsDepthTexture=!1}}_classifyGPUTier(){if(this.isMobile){this.gpuTier="medium";const e=navigator.userAgent.toLowerCase();e.includes("iphone 13")||e.includes("iphone 14")||e.includes("iphone 15")||e.includes("ipad pro")||e.includes("sm-s")||e.includes("sm-n")||e.includes("pixel 6")||e.includes("pixel 7")||e.includes("pixel 8")?this.gpuTier="high":(e.includes("sm-j")||e.includes("sm-a")||e.includes("redmi")||e.includes("mediatek")||e.includes("wiko")||e.includes("nokia"))&&(this.gpuTier="low",this.memoryLimited=!0),this.maxTextureSize=this.gpuTier==="high"?4096:this.gpuTier==="medium"?2048:1024}else this.gpuTier="high",this.rawRendererInfo&&this.rawRendererInfo.includes("intel")&&!this.rawRendererInfo.includes("iris")&&!this.rawRendererInfo.includes("uhd")&&(this.gpuTier="low",this.memoryLimited=!0)}_logDetectionResults(){console.log("Device Capabilities Detection Results:"),console.log(`- Platform: ${this.isMobile?"Mobile":"Desktop"}`),console.log(`- GPU Tier: ${this.gpuTier}`),console.log(`- Memory Limited: ${this.memoryLimited}`),console.log(`- Max Texture Size: ${this.maxTextureSize}`),console.log(`- Float Textures: ${this.supportsFloatTextures?"Supported":"Not Supported"}`),console.log(`- Depth Textures: ${this.supportsDepthTexture?"Supported":"Not Supported"}`),this.gpuInfo&&console.log(`- GPU Info: ${this.gpuInfo.vendor} ${this.gpuInfo.renderer}`),console.log("Additional Information:"),console.log(`- Device Pixel Ratio: ${window.devicePixelRatio}`),console.log(`- Memory: ${navigator.deviceMemory?navigator.deviceMemory+"GB":"Unknown"}`),console.log(`- Cores: ${navigator.hardwareConcurrency||"Unknown"}`)}getRecommendedTextureSize(e){if(!this.isMobile)return e;switch(this.gpuTier){case"low":return Math.min(e,256);case"medium":return Math.min(e,512);case"high":return Math.min(e,1024);default:return Math.min(e,512)}}supportsFeature(e){switch(e.toLowerCase()){case"shadows":return!this.isMobile||this.gpuTier!=="low";case"reflections":return!this.isMobile||this.gpuTier!=="low";case"postprocessing":return!this.isMobile||this.gpuTier==="high";default:return!0}}}const Se=new sn;class nn{constructor(){this.keys={},this.touches={},this.mouse={x:0,y:0,dx:0,dy:0,buttons:0},this.isTouchDevice="ontouchstart"in window||navigator.maxTouchPoints>0,this.listeners={},this.pointerLocked=!1,this.deviceOrientation={alpha:0,beta:0,gamma:0},this.deviceMotionEnabled=!1,this.deviceMotionAvailable=typeof DeviceOrientationEvent<"u",this.initialOrientation=null,this.deviceMotion={acceleration:{x:0,y:0,z:0},accelerationIncludingGravity:{x:0,y:0,z:0},rotationRate:{alpha:0,beta:0,gamma:0},interval:0},this.fusedOrientation={alpha:0,beta:0,gamma:0},this.lastUpdateTime=0,this.filterCoefficient=.98,this.touchScale=1,this.lastTapTime=0,this.doubleTapThreshold=300,this.boundOnDeviceOrientation=this.onDeviceOrientation.bind(this),this.boundOnDeviceMotion=this.onDeviceMotion.bind(this),this.prevRotationRate={alpha:0,beta:0,gamma:0},this.pointerLocked=!1,this.pointerLockRequested=!1,this.isAndroid=/android/i.test(navigator.userAgent),this.isIOS=/iPad|iPhone|iPod/.test(navigator.userAgent)}initialize(){window.addEventListener("keydown",this.onKeyDown.bind(this)),window.addEventListener("keyup",this.onKeyUp.bind(this)),window.addEventListener("mousedown",this.onMouseDown.bind(this)),window.addEventListener("mouseup",this.onMouseUp.bind(this)),window.addEventListener("mousemove",this.onMouseMove.bind(this)),this.isTouchDevice||(document.addEventListener("click",e=>{e.target.tagName==="BUTTON"||e.target.closest("#intro-screen")||e.target.closest("#ui-container")||this.requestPointerLock()}),document.addEventListener("pointerlockchange",this.onPointerLockChange.bind(this)),document.addEventListener("pointerlockerror",this.onPointerLockError.bind(this))),this.updateInterval=setInterval(()=>{this.updateFusedOrientation()},16),this.isTouchDevice&&(console.log("Touch device detected, setting up touch event handlers"),window.addEventListener("touchstart",this.onTouchStart.bind(this),{passive:!1}),window.addEventListener("touchend",this.onTouchEnd.bind(this),{passive:!1}),window.addEventListener("touchmove",this.onTouchMove.bind(this),{passive:!1}),window.addEventListener("touchcancel",this.onTouchCancel.bind(this),{passive:!1}),this.deviceMotionAvailable&&(console.log("Device orientation available, setting up orientation event handler"),window.addEventListener("deviceorientation",this.onDeviceOrientation.bind(this)),typeof DeviceMotionEvent<"u"&&(console.log("Device motion available, setting up motion event handler"),window.addEventListener("devicemotion",this.onDeviceMotion.bind(this))))),window.addEventListener("contextmenu",e=>e.preventDefault())}onKeyDown(e){this.keys[e.code]=!0,this.emit("keydown",e)}onKeyUp(e){this.keys[e.code]=!1,this.emit("keyup",e)}onMouseDown(e){this.mouse.buttons=e.buttons,this.emit("mousedown",e)}onMouseUp(e){this.mouse.buttons=e.buttons,this.emit("mouseup",e)}onMouseMove(e){if(this.pointerLocked)this.mouse.dx=e.movementX||e.mozMovementX||e.webkitMovementX||0,this.mouse.dy=e.movementY||e.mozMovementY||e.webkitMovementY||0;else{const s=this.mouse.x,i=this.mouse.y;this.mouse.x=e.clientX,this.mouse.y=e.clientY,typeof s=="number"&&typeof i=="number"?(this.mouse.dx=this.mouse.x-s,this.mouse.dy=this.mouse.y-i):(this.mouse.dx=0,this.mouse.dy=0)}const t=this.pointerLocked?1:.5;this.mouse.dx*=t,this.mouse.dy*=t,this.emit("mousemove",{originalEvent:e,dx:this.mouse.dx,dy:this.mouse.dy,x:this.mouse.x,y:this.mouse.y})}isPointerLockAvailable(){return!this.isTouchDevice&&"pointerLockElement"in document&&"requestPointerLock"in document.body}releasePointerLock(){this.pointerLocked&&document.exitPointerLock&&document.exitPointerLock()}onTouchStart(e){const t=e.target;if(t&&t.closest&&t.closest("button, a, input, textarea, select, #settings-menu-panel"))return;e.preventDefault(),console.log("Touch start detected",e.touches.length,"touches");const s={originalEvent:e,touches:[]};for(let i=0;ithis.off(e,t)}off(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(s=>s!==t))}emit(e,t){if(this.listeners[e])for(const s of this.listeners[e])s(t)}isKeyDown(e){return!!this.keys[e]}getTouchCount(){return Object.keys(this.touches).length}requestPointerLock(e=!1){if(!this.isTouchDevice&&!(this.pointerLocked||this.pointerLockRequested))try{document.body.requestPointerLock&&(console.log("Requesting pointer lock for gameplay"),this.pointerLockRequested=!0,document.body.requestPointerLock())}catch(t){console.warn("Pointer lock request failed:",t),this.pointerLockRequested=!1}}onPointerLockChange(){this.pointerLocked=document.pointerLockElement===document.body,this.pointerLockRequested=!1,this.pointerLocked?console.log("Pointer lock acquired"):console.log("Pointer lock released"),this.emit("pointerlock",this.pointerLocked)}onPointerLockError(e){console.warn("Pointer lock error:",e),this.pointerLocked=!1,this.pointerLockRequested=!1,this.emit("pointerlockerror",e)}onDeviceOrientation(e){this.deviceOrientation.alpha=e.alpha||0,this.deviceOrientation.beta=e.beta||0,this.deviceOrientation.gamma=e.gamma||0,this._orientationLogged||(console.log("Device orientation event:",{alpha:e.alpha,beta:e.beta,gamma:e.gamma}),this._orientationLogged=!0,this.isTouchDevice&&!this.deviceMotionEnabled&&(console.log("Auto-enabling device motion for mobile"),this.setDeviceMotionEnabled(!0))),!this.initialOrientation&&this.deviceMotionEnabled&&(this.initialOrientation={alpha:e.alpha||0,beta:e.beta||0,gamma:e.gamma||0},console.log("Device orientation calibrated:",this.initialOrientation)),this.emit("deviceorientation",e)}calibrateDeviceOrientation(){console.log("Calibrating device orientation"),this.initialOrientation={alpha:this.fusedOrientation.alpha,beta:this.fusedOrientation.beta,gamma:this.fusedOrientation.gamma},console.log("Initial orientation set:",this.initialOrientation)}normalizeAngle(e){return(e%360+360)%360}clampAngle(e,t,s){return Math.max(t,Math.min(s,e))}onDeviceMotion(e){e.accelerationIncludingGravity&&(this.deviceMotion.accelerationIncludingGravity.x=e.accelerationIncludingGravity.x||0,this.deviceMotion.accelerationIncludingGravity.y=e.accelerationIncludingGravity.y||0,this.deviceMotion.accelerationIncludingGravity.z=e.accelerationIncludingGravity.z||0),e.rotationRate&&(this.deviceMotion.rotationRate.alpha=e.rotationRate.alpha||0,this.deviceMotion.rotationRate.beta=e.rotationRate.beta||0,this.deviceMotion.rotationRate.gamma=e.rotationRate.gamma||0),this.deviceMotion.interval=e.interval||16,this._motionLogged||(console.log("Device motion event:",{acceleration:e.acceleration,accelerationIncludingGravity:e.accelerationIncludingGravity,rotationRate:e.rotationRate,interval:e.interval}),this._motionLogged=!0),this.emit("devicemotion",e)}updateFusedOrientation(e){if(!this.deviceMotionEnabled||!this.deviceMotion.rotationRate)return;const s=this.lerp(this.prevRotationRate.alpha,this.deviceMotion.rotationRate.alpha*(Math.PI/180),.2),i=performance.now();if(this.lastUpdateTime===0){this.lastUpdateTime=i;return}const n=e||(i-this.lastUpdateTime)/1e3;this.lastUpdateTime=i;const o=this.deviceMotion.rotationRate.beta*(Math.PI/180),a=this.deviceMotion.rotationRate.gamma*(Math.PI/180);this.fusedOrientation.alpha+=s*n,this.fusedOrientation.beta+=o*n,this.fusedOrientation.gamma+=a*n;const r=this.deviceMotion.accelerationIncludingGravity,l=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);if(Math.abs(l-9.8)<1){const c=Math.atan2(-r.x,Math.sqrt(r.y*r.y+r.z*r.z)),d=Math.atan2(r.y,r.z);this.fusedOrientation.beta=this.filterCoefficient*this.fusedOrientation.beta+(1-this.filterCoefficient)*c*(180/Math.PI),this.fusedOrientation.gamma=this.filterCoefficient*this.fusedOrientation.gamma+(1-this.filterCoefficient)*d*(180/Math.PI)}this.fusedOrientation.alpha=this.normalizeAngle(this.fusedOrientation.alpha),this.fusedOrientation.beta=this.clampAngle(this.fusedOrientation.beta,-90,90),this.fusedOrientation.gamma=this.clampAngle(this.fusedOrientation.gamma,-90,90),this.initialOrientation&&(this.fusedOrientation.beta-=this.initialOrientation.beta,this.fusedOrientation.gamma-=this.initialOrientation.gamma),this.emit("fusedorientation",this.fusedOrientation)}lerp(e,t,s){return e*(1-s)+t*s}async setDeviceMotionEnabled(e){if(e&&typeof DeviceOrientationEvent.requestPermission=="function")try{if(await DeviceOrientationEvent.requestPermission()!=="granted")return console.warn("Device orientation permission denied"),!1}catch(t){return console.error("Error requesting permissions:",t),!1}return e?(window.addEventListener("deviceorientation",this.boundOnDeviceOrientation),window.addEventListener("devicemotion",this.boundOnDeviceMotion),this.calibrateDeviceOrientation()):(window.removeEventListener("deviceorientation",this.boundOnDeviceOrientation),window.removeEventListener("devicemotion",this.boundOnDeviceMotion)),this.deviceMotionEnabled=e,e}}function ys(h,e){if(e===mi)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),h;if(e===Dt||e===Hs){let t=h.getIndex();if(t===null){const o=[],a=h.getAttribute("position");if(a!==void 0){for(let r=0;r=2.0 are supported."));return}const l=new Fn(n,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let c=0;c=0&&a[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}l.setExtensions(o),l.setPlugins(a),l.parse(s,i)}parseAsync(e,t){const s=this;return new Promise(function(i,n){s.parse(e,t,i,n)})}}function an(){let h={};return{get:function(e){return h[e]},add:function(e,t){h[e]=t},remove:function(e){delete h[e]},removeAll:function(){h={}}}}const L={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class rn{constructor(e){this.parser=e,this.name=L.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let s=0,i=t.length;s=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,n.source,o)}}class xn{constructor(e){this.parser=e,this.name=L.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,s=this.parser,i=s.json,n=i.textures[e];if(!n.extensions||!n.extensions[t])return null;const o=n.extensions[t],a=i.images[o.source];let r=s.textureLoader;if(a.uri){const l=s.options.manager.getHandler(a.uri);l!==null&&(r=l)}return this.detectSupport().then(function(l){if(l)return s.loadTextureImage(e,o.source,r);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return s.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class Sn{constructor(e){this.parser=e,this.name=L.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,s=this.parser,i=s.json,n=i.textures[e];if(!n.extensions||!n.extensions[t])return null;const o=n.extensions[t],a=i.images[o.source];let r=s.textureLoader;if(a.uri){const l=s.options.manager.getHandler(a.uri);l!==null&&(r=l)}return this.detectSupport().then(function(l){if(l)return s.loadTextureImage(e,o.source,r);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return s.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class vn{constructor(e){this.name=L.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,s=t.bufferViews[e];if(s.extensions&&s.extensions[this.name]){const i=s.extensions[this.name],n=this.parser.getDependency("buffer",i.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return n.then(function(a){const r=i.byteOffset||0,l=i.byteLength||0,c=i.count,d=i.byteStride,u=new Uint8Array(a,r,l);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(c,d,u,i.mode,i.filter).then(function(m){return m.buffer}):o.ready.then(function(){const m=new ArrayBuffer(c*d);return o.decodeGltfBuffer(new Uint8Array(m),c,d,u,i.mode,i.filter),m})})}else return null}}class Mn{constructor(e){this.name=L.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,s=t.nodes[e];if(!s.extensions||!s.extensions[this.name]||s.mesh===void 0)return null;const i=t.meshes[s.mesh];for(const l of i.primitives)if(l.mode!==ie.TRIANGLES&&l.mode!==ie.TRIANGLE_STRIP&&l.mode!==ie.TRIANGLE_FAN&&l.mode!==void 0)return null;const o=s.extensions[this.name].attributes,a=[],r={};for(const l in o)a.push(this.parser.getDependency("accessor",o[l]).then(c=>(r[l]=c,r[l])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(l=>{const c=l.pop(),d=c.isGroup?c.children:[c],u=l[0].count,m=[];for(const f of d){const g=new ye,p=new A,b=new Yt,S=new A(1,1,1),x=new Us(f.geometry,f.material,u);for(let w=0;w0||h.search(/^data\:image\/jpeg/)===0?"image/jpeg":h.search(/\.webp($|\?)/i)>0||h.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}const On=new ye;class Fn{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new an,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let s=!1,i=!1,n=-1;typeof navigator<"u"&&(s=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)===!0,i=navigator.userAgent.indexOf("Firefox")>-1,n=i?navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]:-1),typeof createImageBitmap>"u"||s||i&&n<98?this.textureLoader=new Be(this.options.manager):this.textureLoader=new gi(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new rt(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const s=this,i=this.json,n=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([s.getDependencies("scene"),s.getDependencies("animation"),s.getDependencies("camera")])}).then(function(o){const a={scene:o[0][i.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:i.asset,parser:s,userData:{}};return Ee(n,a,i),Te(a,i),Promise.all(s._invokeAll(function(r){return r.afterRoot&&r.afterRoot(a)})).then(function(){e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],s=this.json.meshes||[];for(let i=0,n=t.length;i{const r=this.associations.get(o);r!=null&&this.associations.set(a,r);for(const[l,c]of o.children.entries())n(c,a.children[l])};return n(s,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let s=0;s=2&&p.setY(P,M[_*r+1]),r>=3&&p.setZ(P,M[_*r+2]),r>=4&&p.setW(P,M[_*r+3]),r>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return p})}loadTexture(e){const t=this.json,s=this.options,n=t.textures[e].source,o=t.images[n];let a=this.textureLoader;if(o.uri){const r=s.manager.getHandler(o.uri);r!==null&&(a=r)}return this.loadTextureImage(e,n,a)}loadTextureImage(e,t,s){const i=this,n=this.json,o=n.textures[e],a=n.images[t],r=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[r])return this.textureCache[r];const l=this.loadImageSource(t,s).then(function(c){c.flipY=!1,c.name=o.name||a.name||"",c.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(c.name=a.uri);const u=(n.samplers||{})[o.sampler]||{};return c.magFilter=bs[u.magFilter]||Ws,c.minFilter=bs[u.minFilter]||qs,c.wrapS=ws[u.wrapS]||me,c.wrapT=ws[u.wrapT]||me,i.associations.set(c,{textures:e}),c}).catch(function(){return null});return this.textureCache[r]=l,l}loadImageSource(e,t){const s=this,i=this.json,n=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const o=i.images[e],a=self.URL||self.webkitURL;let r=o.uri||"",l=!1;if(o.bufferView!==void 0)r=s.getDependency("bufferView",o.bufferView).then(function(d){l=!0;const u=new Blob([d],{type:o.mimeType});return r=a.createObjectURL(u),r});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const c=Promise.resolve(r).then(function(d){return new Promise(function(u,m){let f=u;t.isImageBitmapLoader===!0&&(f=function(g){const p=new as(g);p.needsUpdate=!0,u(p)}),t.load(Ke.resolveURL(d,n.path),f,void 0,m)})}).then(function(d){return l===!0&&a.revokeObjectURL(r),d.userData.mimeType=o.mimeType||Nn(o.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",r),d});return this.sourceCache[e]=c,c}assignTexture(e,t,s,i){const n=this;return this.getDependency("texture",s.index).then(function(o){if(!o)return null;if(s.texCoord!==void 0&&s.texCoord>0&&(o=o.clone(),o.channel=s.texCoord),n.extensions[L.KHR_TEXTURE_TRANSFORM]){const a=s.extensions!==void 0?s.extensions[L.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const r=n.associations.get(o);o=n.extensions[L.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),n.associations.set(o,r)}}return i!==void 0&&(o.colorSpace=i),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let s=e.material;const i=t.attributes.tangent===void 0,n=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+s.uuid;let r=this.cache.get(a);r||(r=new lt,xt.prototype.copy.call(r,s),r.color.copy(s.color),r.map=s.map,r.sizeAttenuation=!1,this.cache.add(a,r)),s=r}else if(e.isLine){const a="LineBasicMaterial:"+s.uuid;let r=this.cache.get(a);r||(r=new _i,xt.prototype.copy.call(r,s),r.color.copy(s.color),r.map=s.map,this.cache.add(a,r)),s=r}if(i||n||o){let a="ClonedMaterial:"+s.uuid+":";i&&(a+="derivative-tangents:"),n&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let r=this.cache.get(a);r||(r=s.clone(),n&&(r.vertexColors=!0),o&&(r.flatShading=!0),i&&(r.normalScale&&(r.normalScale.y*=-1),r.clearcoatNormalScale&&(r.clearcoatNormalScale.y*=-1)),this.cache.add(a,r),this.associations.set(r,this.associations.get(s))),s=r}e.material=s}getMaterialType(){return R}loadMaterial(e){const t=this,s=this.json,i=this.extensions,n=s.materials[e];let o;const a={},r=n.extensions||{},l=[];if(r[L.KHR_MATERIALS_UNLIT]){const d=i[L.KHR_MATERIALS_UNLIT];o=d.getMaterialType(),l.push(d.extendParams(a,n,t))}else{const d=n.pbrMetallicRoughness||{};if(a.color=new C(1,1,1),a.opacity=1,Array.isArray(d.baseColorFactor)){const u=d.baseColorFactor;a.color.setRGB(u[0],u[1],u[2],be),a.opacity=u[3]}d.baseColorTexture!==void 0&&l.push(t.assignTexture(a,"map",d.baseColorTexture,we)),a.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,a.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(a,"metalnessMap",d.metallicRoughnessTexture)),l.push(t.assignTexture(a,"roughnessMap",d.metallicRoughnessTexture))),o=this._invokeOne(function(u){return u.getMaterialType&&u.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(u){return u.extendMaterialParams&&u.extendMaterialParams(e,a)})))}n.doubleSided===!0&&(a.side=pe);const c=n.alphaMode||Mt.OPAQUE;if(c===Mt.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,c===Mt.MASK&&(a.alphaTest=n.alphaCutoff!==void 0?n.alphaCutoff:.5)),n.normalTexture!==void 0&&o!==V&&(l.push(t.assignTexture(a,"normalMap",n.normalTexture)),a.normalScale=new Fe(1,1),n.normalTexture.scale!==void 0)){const d=n.normalTexture.scale;a.normalScale.set(d,d)}if(n.occlusionTexture!==void 0&&o!==V&&(l.push(t.assignTexture(a,"aoMap",n.occlusionTexture)),n.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=n.occlusionTexture.strength)),n.emissiveFactor!==void 0&&o!==V){const d=n.emissiveFactor;a.emissive=new C().setRGB(d[0],d[1],d[2],be)}return n.emissiveTexture!==void 0&&o!==V&&l.push(t.assignTexture(a,"emissiveMap",n.emissiveTexture,we)),Promise.all(l).then(function(){const d=new o(a);return n.name&&(d.name=n.name),Te(d,n),t.associations.set(d,{materials:e}),n.extensions&&Ee(i,d,n),d})}createUniqueName(e){const t=Ti.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,s=this.extensions,i=this.primitiveCache;function n(a){return s[L.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(r){return xs(r,a,t)})}const o=[];for(let a=0,r=e.length;a0&&Ln(b,n),b.name=t.createUniqueName(n.name||"mesh_"+e),Te(b,n),p.extensions&&Ee(i,b,p),t.assignFinalMaterial(b),d.push(b)}for(let m=0,f=d.length;m1?c=new ee:l.length===1?c=l[0]:c=new Qt,c!==l[0])for(let d=0,u=l.length;d{const d=new Map;for(const[u,m]of i.associations)(u instanceof xt||u instanceof as)&&d.set(u,m);return c.traverse(u=>{const m=i.associations.get(u);m!=null&&d.set(u,m)}),d};return i.associations=l(n),n})}_createAnimationTracks(e,t,s,i,n){const o=[],a=e.name?e.name:e.uuid,r=[];Me[n.path]===Me.weights?e.traverse(function(u){u.morphTargetInfluences&&r.push(u.name?u.name:u.uuid)}):r.push(a);let l;switch(Me[n.path]){case Me.weights:l=ls;break;case Me.rotation:l=cs;break;case Me.position:case Me.scale:l=rs;break;default:switch(s.itemSize){case 1:l=ls;break;case 2:case 3:default:l=rs;break}break}const c=i.interpolation!==void 0?Pn[i.interpolation]:$s,d=this._getArrayFromAccessor(s);for(let u=0,m=r.length;u{this.parse(o,t,i)},s,i)}parse(e,t,s=()=>{}){this.decodeDracoFile(e,t,null,null,we).catch(s)}decodeDracoFile(e,t,s,i,n=be,o=()=>{}){const a={attributeIDs:s||this.defaultAttributeIDs,attributeTypes:i||this.defaultAttributeTypes,useUniqueIDs:!!s,vertexColorSpace:n};return this.decodeGeometry(e,a).then(t).catch(o)}decodeGeometry(e,t){const s=JSON.stringify(t);if(Tt.has(e)){const r=Tt.get(e);if(r.key===s)return r.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let i;const n=this.workerNextTaskID++,o=e.byteLength,a=this._getWorker(n,o).then(r=>(i=r,new Promise((l,c)=>{i._callbacks[n]={resolve:l,reject:c},i.postMessage({type:"decode",id:n,taskConfig:t,buffer:e},[e])}))).then(r=>this._createGeometry(r.geometry));return a.catch(()=>!0).then(()=>{i&&n&&this._releaseTask(i,n)}),Tt.set(e,{key:s,promise:a}),a}_createGeometry(e){const t=new ze;e.index&&t.setIndex(new ce(e.index.array,1));for(let s=0;s{s.load(e,i,void 0,n)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(s=>{const i=s[0];e||(this.decoderConfig.wasmBinary=s[1]);const n=Gn.toString(),o=["/* draco decoder */",i,"","/* worker */",n.substring(n.indexOf("{")+1,n.lastIndexOf("}"))].join(` -`);this.workerSourceURL=URL.createObjectURL(new Blob([o]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengthn._taskLoad?-1:1});const s=this.workerPool[this.workerPool.length-1];return s._taskCosts[e]=t,s._taskLoad+=t,s})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{const d=c.draco,u=new d.Decoder;try{const m=t(d,u,new Int8Array(r),l),f=m.attributes.map(g=>g.array.buffer);m.index&&f.push(m.index.array.buffer),self.postMessage({type:"decode",id:a.id,geometry:m},f)}catch(m){console.error(m),self.postMessage({type:"error",id:a.id,error:m.message})}finally{d.destroy(u)}});break}};function t(o,a,r,l){const c=l.attributeIDs,d=l.attributeTypes;let u,m;const f=a.GetEncodedGeometryType(r);if(f===o.TRIANGULAR_MESH)u=new o.Mesh,m=a.DecodeArrayToMesh(r,r.byteLength,u);else if(f===o.POINT_CLOUD)u=new o.PointCloud,m=a.DecodeArrayToPointCloud(r,r.byteLength,u);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!m.ok()||u.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+m.error_msg());const g={index:null,attributes:[]};for(const p in c){const b=self[d[p]];let S,x;if(l.useUniqueIDs)x=c[p],S=a.GetAttributeByUniqueId(u,x);else{if(x=a.GetAttributeId(u,o[c[p]]),x===-1)continue;S=a.GetAttribute(u,x)}const w=i(o,a,u,p,b,S);p==="color"&&(w.vertexColorSpace=l.vertexColorSpace),g.attributes.push(w)}return f===o.TRIANGULAR_MESH&&(g.index=s(o,a,u)),o.destroy(u),g}function s(o,a,r){const c=r.num_faces()*3,d=c*4,u=o._malloc(d);a.GetTrianglesUInt32Array(r,d,u);const m=new Uint32Array(o.HEAPF32.buffer,u,c).slice();return o._free(u),{array:m,itemSize:1}}function i(o,a,r,l,c,d){const u=d.num_components(),f=r.num_points()*u,g=f*c.BYTES_PER_ELEMENT,p=n(o,c),b=o._malloc(g);a.GetAttributeDataArrayForAllPoints(r,d,p,g,b);const S=new c(o.HEAPF32.buffer,b,f).slice();return o._free(b),{name:l,array:S,itemSize:u}}function n(o,a){switch(a){case Float32Array:return o.DT_FLOAT32;case Int8Array:return o.DT_INT8;case Int16Array:return o.DT_INT16;case Int32Array:return o.DT_INT32;case Uint8Array:return o.DT_UINT8;case Uint16Array:return o.DT_UINT16;case Uint32Array:return o.DT_UINT32}}}const Hn={BASE_URL:"/skybloom/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_AUTO_IP:"true",VITE_SERVER_URL:"http://192.168.1.22:4000"};function W(h){if(typeof h!="string"||h.length===0)return h;const e=Hn&&"/skybloom/"||"/",t=e.endsWith("/")?e:`${e}/`,s=h.startsWith("/")?h.slice(1):h;return`${t}${s}`}class Vn{constructor(){this.textures={},this.models={},this.materials={},this.audio={},this.shaders={},this.loadingPromises=new Map,this.retryAttempts=new Map,this.maxRetries=2,this.createFallbackAssets(),this.loadingManager=new zi(()=>{console.log("All assets loaded")},(e,t,s)=>{const i=t/s*100,n=document.getElementById("progress"),o=document.getElementById("loading-text");n&&(n.style.width=`${i}%`),o&&(o.textContent=`Loading assets (${t}/${s})`)},e=>{console.warn(`Asset not found: ${e} - using fallback`)}),this.textureLoader=new Be(this.loadingManager),this.dracoLoader=new Bn,this.dracoLoader.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.3/"),this.gltfLoader=new on(this.loadingManager),this.gltfLoader.setDRACOLoader(this.dracoLoader),this.audioLoader=new Bi(this.loadingManager)}createFallbackAssets(){const e=new Ve(new Uint8Array([255,255,255,255,200,200,200,255,200,200,200,255,255,255,255,255]),2,2,Ue);e.needsUpdate=!0,this.textures.fallback=e;const t=new Uint8Array([180,120,60,255,200,140,80,255,200,140,80,255,180,120,60,255]),s=new Ve(t,2,2,Ue);s.wrapS=me,s.wrapT=me,s.repeat.set(4,4),s.needsUpdate=!0,this.textures.carpet=s;const i=new Uint8Array([100,150,50,255,120,160,60,255,80,140,40,255,110,170,55,255]),n=new Ve(i,2,2,Ue);n.wrapS=me,n.wrapT=me,n.repeat.set(100,100),n.needsUpdate=!0,this.textures.terrain=n;const o=new Uint8Array([100,150,255,255,120,170,255,255,120,170,255,255,100,150,255,255]),a=new Ve(o,2,2,Ue);a.needsUpdate=!0,this.textures.sky=a;const r=new Uint8Array([255,255,255,0,255,255,255,128,255,255,255,128,255,255,255,0]),l=new Ve(r,2,2,Ue);l.needsUpdate=!0,this.textures.particles=l;const c=new Q(2,.1,3),d=new R({map:s,roughness:.7,metalness:.2}),u=new k(c,d),m=new Q(2.2,.05,3.2),f=new R({color:9127187}),g=new k(m,f);g.position.y=-.05,u.add(g);const p=new ee,b=new Z(.03,.01,.2,4),S=new R({color:14540202});for(let N=0;N<10;N++){const D=new k(b,S);D.position.set(-1+N*.2,-.1,1.5),p.add(D);const O=new k(b,S);O.position.set(-1+N*.2,-.1,-1.5),p.add(O)}u.add(p);const x={scene:{children:[u]},animations:[]};this.models.carpet=x;const w=new $(1,16,16),v=new R({color:65535,emissive:43775,emissiveIntensity:.5,transparent:!0,opacity:.8}),M=new k(w,v),_=new $(1.2,16,16),E=new V({color:65535,transparent:!0,opacity:.3,side:fe}),P=new k(_,E);M.add(P);const T={scene:{children:[M]},animations:[]};this.models.mana=T,this.audio.fallback=null}async initialize(){return new Promise(e=>{this.loadTextures(),this.loadModels(),this.loadAudio(),this.loadShaders(),this.loadingManager.itemsTotal===0?e():this.loadingManager.onLoad=e})}loadTextures(){[{name:"carpet",path:W("/assets/textures/carpet.jpg")},{name:"terrain",path:W("/assets/textures/terrain.jpg")},{name:"sky",path:W("/assets/textures/sky.jpg")},{name:"particles",path:W("/assets/textures/particles.png")}].forEach(async({name:t,path:s})=>{try{const n=(await fetch(s)).headers.get("content-length")||0;if(console.log(`Asset check for ${s}: size ${n} bytes`),parseInt(n)<100){console.warn(`Empty asset detected for ${s}, using fallback`);return}this.textureLoader.load(s,o=>{o.colorSpace=we,this.textures[t]=o})}catch(i){console.error(`Failed to check asset ${s}:`,i)}})}loadModels(){[{name:"carpet",path:W("/assets/models/carpet.glb")},{name:"mana",path:W("/assets/models/mana.glb")}].forEach(async({name:t,path:s})=>{try{const n=(await fetch(s)).headers.get("content-length")||0;if(console.log(`Asset check for ${s}: size ${n} bytes`),parseInt(n)<100){console.warn(`Empty asset detected for ${s}, using fallback`);return}this.gltfLoader.load(s,o=>{this.models[t]=o})}catch(i){console.error(`Failed to check asset ${s}:`,i)}})}loadAudio(){[{name:"background",path:W("/assets/audio/background.mp3")},{name:"spell",path:W("/assets/audio/spell.mp3")},{name:"collect",path:W("/assets/audio/collect.mp3")}].forEach(async({name:t,path:s})=>{try{const n=(await fetch(s)).headers.get("content-length")||0;if(console.log(`Asset check for ${s}: size ${n} bytes`),parseInt(n)<100){console.warn(`Empty asset detected for ${s}, using fallback`);return}this.audioLoader.load(s,o=>{this.audio[t]=o})}catch(i){console.error(`Failed to check asset ${s}:`,i)}})}loadShaders(){}getTexture(e){return this.textures[e]||this.textures.fallback}getModel(e){return this.models[e]}getAudio(e){return this.audio[e]||this.audio.fallback}createMaterials(){this.materials.carpet=new R({map:this.getTexture("carpet"),roughness:.7,metalness:.2}),this.materials.terrain=new R({map:this.getTexture("terrain"),roughness:.9,metalness:.1})}}class y{static get level(){return"error"}static shouldLog(e){const t={error:0,warn:1,info:2,debug:3};return t[e]>=t[y.level]}static levels={ERROR:0,WARN:1,INFO:2,DEBUG:3};static currentLevel=this.levels.WARN;static error(e,...t){console.error(`[ERROR] ${e}`,...t)}static warn(e,...t){console.warn(`[WARN] ${e}`,...t)}static info(e,...t){y.currentLevel>=y.levels.INFO&&console.info(`[INFO] ${e}`,...t)}static debug(e,...t){y.currentLevel>=y.levels.DEBUG&&console.debug(`[DEBUG] ${e}`,...t)}}class Un{constructor(){this.metrics={fps:[],drawCalls:[],triangles:[],points:[],lines:[],geometries:[],textures:[],systemTimes:{network:[],world:[],water:[],vegetation:[],atmosphere:[],player:[],carpetTrail:[],landmarks:[],ui:[],minimap:[],render:[]},memoryUsage:[],lastUpdate:Date.now()},this.sampleSize=100,this.sampleInterval=1e3}update(e,t,s){const i=Date.now();if(i-this.metrics.lastUpdate0)o=1/s;else if(t&&t.delta>0)o=1/t.delta;else{const a=i-this.metrics.lastUpdate;a>0&&(o=1e3/a)}o=Math.min(Math.max(o,1),120),this.addMetric("fps",o),this.addMetric("drawCalls",n.render.calls),this.addMetric("triangles",n.render.triangles),this.addMetric("points",n.render.points),this.addMetric("lines",n.render.lines),this.addMetric("geometries",n.memory.geometries),this.addMetric("textures",n.memory.textures),window.performance&&window.performance.memory&&this.addMetric("memoryUsage",window.performance.memory.usedJSHeapSize),this.metrics.lastUpdate=i}addMetric(e,t){this.metrics[e].push(t),this.metrics[e].length>this.sampleSize&&this.metrics[e].shift()}addSystemTime(e,t){this.metrics.systemTimes[e]&&(this.metrics.systemTimes[e].push(t),this.metrics.systemTimes[e].length>this.sampleSize&&this.metrics.systemTimes[e].shift())}getAverages(){const e={};for(const[t,s]of Object.entries(this.metrics))if(t!=="systemTimes"&&t!=="lastUpdate")if(t==="fps"&&s.length>0){const i=[...s].sort((r,l)=>r-l),n=Math.floor(i.length*.1),o=Math.ceil(i.length*.9),a=i.slice(n,o);e[t]=a.length>0?a.reduce((r,l)=>r+l,0)/a.length:s.length>0?s[s.length-1]:0}else e[t]=s.length>0?s.reduce((i,n)=>i+n,0)/s.length:0;e.systemTimes={};for(const[t,s]of Object.entries(this.metrics.systemTimes))e.systemTimes[t]=s.length>0?s.reduce((i,n)=>i+n,0)/s.length:0;return e}generateReport(){const t={averages:this.getAverages(),current:{fps:this.metrics.fps.length>0?this.metrics.fps[this.metrics.fps.length-1]:0,drawCalls:this.metrics.drawCalls.length>0?this.metrics.drawCalls[this.metrics.drawCalls.length-1]:0,triangles:this.metrics.triangles.length>0?this.metrics.triangles[this.metrics.triangles.length-1]:0,systemTimes:{}},peaks:{maxDrawCalls:this.metrics.drawCalls.length>0?Math.max(...this.metrics.drawCalls):0,minFps:this.metrics.fps.length>0?Math.min(...this.metrics.fps):0}};for(const s in this.metrics.systemTimes){const i=this.metrics.systemTimes[s];i.length>0&&(t.current.systemTimes[s]=i[i.length-1],t.peaks[`max${s.charAt(0).toUpperCase()+s.slice(1)}Time`]=Math.max(...i))}return t}reset(){for(const e in this.metrics)if(e==="systemTimes")for(const t in this.metrics.systemTimes)this.metrics.systemTimes[t]=[];else e!=="lastUpdate"&&(this.metrics[e]=[]);this.metrics.lastUpdate=Date.now()}}class qn{constructor(){this.quality={water:"high",vegetation:"high",shadows:"high",effects:"high"},this.performance={autoAdjust:!0,targetFPS:30,lowFPSThreshold:20},this.isMobile=Se.isMobile,this._applyInitialSettings()}_detectMobile(){return Se.isMobile}_applyInitialSettings(){this.isMobile&&(console.log("Mobile device detected, applying optimized settings"),this.quality.water="low",this.quality.vegetation="medium",this.quality.shadows="low",this.quality.effects="medium")}updateFromPerformance(e){return!this.performance.autoAdjust||!this.isMobile?!1:e.current.fpsthis.adjustmentInterval&&(this.dynamicallyAdjustLOD(),this.lastAdjustmentTime=t)}finalizeInitialBenchmark(){if(this.benchmarkFpsSamples.length===0){console.log("Benchmark completed but no samples collected. Using default settings."),this.initialBenchmarkComplete=!0;return}const e=this.benchmarkFpsSamples.reduce((t,s)=>t+s,0)/this.benchmarkFpsSamples.length;console.log(`Initial benchmark results: Average FPS = ${e.toFixed(1)}`),ethis.targetFPS*1.5?(this.distanceScalingFactor=Math.min(.8,this.distanceScalingFactor*1.2),this.qualityLevel=2,console.log(`Benchmark indicates higher-end device. Increasing scaling to ${this.distanceScalingFactor.toFixed(2)} and starting at high quality.`)):(this.qualityLevel=1,console.log(`Benchmark indicates mid-range device. Maintaining scaling at ${this.distanceScalingFactor.toFixed(2)} and starting at medium quality.`)),this.updateQualityBasedOnLevel(),this.updateLODSettings(),this.initialBenchmarkComplete=!0,this.lastQualityChangeTime=Date.now()}detectDeviceCapabilities(){if(!this.isMobile)return;console.log("Using centralized device capabilities data");const e=Se.gpuTier,t=Se.memoryLimited;Se.pixelRatio,e==="high"?this.distanceScalingFactor=Math.min(.8,this.distanceScalingFactor*1.2):e==="low"&&(this.distanceScalingFactor=Math.max(.3,this.distanceScalingFactor*.8)),console.log(`Using device capabilities: GPU Tier: ${e}, Memory Limited: ${t}`),console.log(`Adjusted distance scaling factor: ${this.distanceScalingFactor.toFixed(2)}`)}updateFrameTiming(e){this.frameTimings[this.frameIndex]=e*1e3,this.frameIndex=(this.frameIndex+1)%this.frameTimings.length}getAverageFrameTime(){return this.frameTimings.reduce((e,t)=>e+t)/this.frameTimings.length}applyInitialOptimizations(){if(this.isMobile){if(this.engine.renderer){const e=Math.min(window.devicePixelRatio,2);this.engine.renderer.setPixelRatio(e*.8),this.engine.renderer.shadowMap&&(this.engine.renderer.shadowMap.type=Ks)}if(this.engine.camera&&(this.engine.camera.fov=Math.min(75,this.engine.camera.fov+5),this.engine.camera.far=25e3,this.engine.camera.near=1,this.engine.camera.updateProjectionMatrix()),this.engine.systems.world&&(this.engine.systems.world.viewDistance=6),this.engine.systems.vegetation){const e=this.engine.systems.vegetation;e.densityScale=this.currentVegetationDensity,e.lodDistances=this.getLODDistances().vegetation}}}getHorizonLODDistance(){return this.baseLODDistances.terrain.low*1.8}getLODDistances(){if(this.cachedLODDistances)return this.cachedLODDistances;const e={terrain:{high:this.baseLODDistances.terrain.high*this.distanceScalingFactor,medium:this.baseLODDistances.terrain.medium*this.distanceScalingFactor,low:this.baseLODDistances.terrain.low*this.distanceScalingFactor,horizon:this.getHorizonLODDistance()},vegetation:{high:this.baseLODDistances.vegetation.high*this.distanceScalingFactor,medium:this.baseLODDistances.vegetation.medium*this.distanceScalingFactor,low:this.baseLODDistances.vegetation.low*this.distanceScalingFactor},water:{reflection:this.baseLODDistances.water.reflection*this.distanceScalingFactor,highDetail:this.baseLODDistances.water.highDetail*this.distanceScalingFactor,mediumDetail:this.baseLODDistances.water.mediumDetail*this.distanceScalingFactor}};return this.cachedLODDistances=e,e}getTerrainResolutionMultiplier(){switch(this.qualityLevel){case 0:return .33;case 1:return .67;case 2:default:return 1}}getTerrainResolution(e){if(!this.isMobile)return this.engine.systems.world.terrainResolution;if(this.currentTerrainLOD==="low")return 16;if(this.currentTerrainLOD==="medium")return 32;if(this.currentTerrainLOD==="high")return 48;const t=this.getLODDistances().terrain;return ethis.triangleThresholds.critical?(o=!0,r.push(nthis.triangleThresholds.high&&n<1.1?(o=!0,r.push(nthis.fpsThresholds.good&&sthis.fpsThresholds.excellent&&s0?(this.qualityLevel--,console.log(`⬇️ Decreasing quality to ${this.qualityLevel}/2. Reason: ${r.join(", ")}`),l=!0):a&&this.qualityLevel<2&&(this.qualityLevel++,console.log(`⬆️ Increasing quality to ${this.qualityLevel}/2. Reason: ${r.join(", ")}`),l=!0),l&&(this.updateQualityBasedOnLevel(),this.timeAtCurrentQuality=0,this.lastQualityChangeTime=Date.now(),this.updateLODSettings(),this.qualityLevel===0&&n<.6&&this.engine.renderer)){const c=this.engine.renderer.getPixelRatio();if(c>.6){const d=Math.max(.6,c*.9);this.engine.renderer.setPixelRatio(d),console.log(`🚨 Emergency pixel ratio reduction to ${d.toFixed(2)}`)}}}dynamicallyAdjustLOD(){if(!this.isMobile)return;const e=this.engine.performanceMonitor.generateReport();e.current.fps;const t=e.averages.fps,s=e.averages.triangles||0,i=Date.now()-this.lastQualityChangeTime,n=t/this.targetFPS;console.log(`LOD Assessment: Avg FPS: ${t.toFixed(1)}/${this.targetFPS} (${(n*100).toFixed(0)}%), Triangles: ${s.toFixed(0)}, Quality: ${this.qualityLevel}/2, Time at quality: ${(this.timeAtCurrentQuality/1e3).toFixed(1)}s`);let o=!1,a=!1;const r=[];if(nthis.fpsThresholds.good&&sthis.triangleThresholds.critical?(o=!0,r.push(`Triangle count critically high (${s.toFixed(0)})`)):s>this.triangleThresholds.high&&n<1.1?(o=!0,r.push(`High triangle count (${s.toFixed(0)}) with borderline FPS`)):s1.3&&(a=!0,r.push(`Low triangle count (${s.toFixed(0)}) with excellent FPS`)),o&&i0){if(this.qualityLevel--,console.log(`⬇️ Decreasing quality to ${this.qualityLevel}/2 because: ${r.join(", ")}`),this.updateQualityBasedOnLevel(),this.timeAtCurrentQuality=0,this.lastQualityChangeTime=Date.now(),n<.6&&this.engine.renderer){const l=this.engine.renderer.getPixelRatio();if(l>.6){const c=Math.max(.6,l*.9);this.engine.renderer.setPixelRatio(c),console.log(`🚨 Emergency pixel ratio reduction to ${c.toFixed(2)}`)}}}else a&&this.qualityLevel<2?(this.qualityLevel++,console.log(`⬆️ Increasing quality to ${this.qualityLevel}/2 because: ${r.join(", ")}`),this.updateQualityBasedOnLevel(),this.timeAtCurrentQuality=0,this.lastQualityChangeTime=Date.now()):console.log(`✓ Maintaining quality level ${this.qualityLevel}/2`);(o||a)&&this.updateLODSettings()}updateLODSettings(){if(this.isMobile){if(this.cachedLODDistances=null,this.engine.systems.vegetation){const e=this.engine.systems.vegetation,t=this.currentVegetationDensity,s=this.getLODDistances().vegetation;let i=!1;Math.abs(e.densityScale-t)>.01&&(console.log(`Updating vegetation density to ${t.toFixed(2)}`),e.densityScale=t,i=!0),JSON.stringify(e.lodDistances)!==JSON.stringify(s)&&(e.lodDistances=s),i&&e.regenerateVegetation()}this.engine.systems.world,this.engine.renderer&&this.engine.renderer.shadowMap&&(this.engine.renderer.shadowMap.enabled=!this.optimizations.simplifiedShadows)}}shouldCull(e,t,s=8e3){if(!this.isMobile)return e.distanceTo(t)>s;const i=e.distanceTo(t),n=Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.z-t.z,2)),o=Math.atan2(e.y-t.y,n);if(Math.abs(o)<.15)return i>s*1.5;if(i<2e3)return!1;const l=this.optimizations.aggressiveDistanceCulling?s*.9:s;return i>l}getTextureSize(e){return this.isMobile?this.optimizations.reduced3DTextures?Math.min(e,256):Math.min(e,512):e}}const xe=Object.create(null);xe.open="0";xe.close="1";xe.ping="2";xe.pong="3";xe.message="4";xe.upgrade="5";xe.noop="6";const it=Object.create(null);Object.keys(xe).forEach(h=>{it[xe[h]]=h});const Gt={type:"error",data:"parser error"},Zs=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Js=typeof ArrayBuffer=="function",ei=h=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(h):h&&h.buffer instanceof ArrayBuffer,es=({type:h,data:e},t,s)=>Zs&&e instanceof Blob?t?s(e):Ss(e,s):Js&&(e instanceof ArrayBuffer||ei(e))?t?s(e):Ss(new Blob([e]),s):s(xe[h]+(e||"")),Ss=(h,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(h)};function vs(h){return h instanceof Uint8Array?h:h instanceof ArrayBuffer?new Uint8Array(h):new Uint8Array(h.buffer,h.byteOffset,h.byteLength)}let kt;function $n(h,e){if(Zs&&h.data instanceof Blob)return h.data.arrayBuffer().then(vs).then(e);if(Js&&(h.data instanceof ArrayBuffer||ei(h.data)))return e(vs(h.data));es(h,!1,t=>{kt||(kt=new TextEncoder),e(kt.encode(t))})}const Ms="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",je=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let h=0;h{let e=h.length*.75,t=h.length,s,i=0,n,o,a,r;h[h.length-1]==="="&&(e--,h[h.length-2]==="="&&e--);const l=new ArrayBuffer(e),c=new Uint8Array(l);for(s=0;s>4,c[i++]=(o&15)<<4|a>>2,c[i++]=(a&3)<<6|r&63;return l},Kn=typeof ArrayBuffer=="function",ts=(h,e)=>{if(typeof h!="string")return{type:"message",data:ti(h,e)};const t=h.charAt(0);return t==="b"?{type:"message",data:Xn(h.substring(1),e)}:it[t]?h.length>1?{type:it[t],data:h.substring(1)}:{type:it[t]}:Gt},Xn=(h,e)=>{if(Kn){const t=jn(h);return ti(t,e)}else return{base64:!0,data:h}},ti=(h,e)=>{switch(e){case"blob":return h instanceof Blob?h:new Blob([h]);case"arraybuffer":default:return h instanceof ArrayBuffer?h:h.buffer}},si="",Yn=(h,e)=>{const t=h.length,s=new Array(t);let i=0;h.forEach((n,o)=>{es(n,!1,a=>{s[o]=a,++i===t&&e(s.join(si))})})},Qn=(h,e)=>{const t=h.split(si),s=[];for(let i=0;i{const s=t.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const n=new DataView(i.buffer);n.setUint8(0,126),n.setUint16(1,s)}else{i=new Uint8Array(9);const n=new DataView(i.buffer);n.setUint8(0,127),n.setBigUint64(1,BigInt(s))}h.data&&typeof h.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let At;function Ze(h){return h.reduce((e,t)=>e+t.length,0)}function Je(h,e){if(h[0].length===e)return h.shift();const t=new Uint8Array(e);let s=0;for(let i=0;iMath.pow(2,21)-1){a.enqueue(Gt);break}i=c*Math.pow(2,32)+l.getUint32(4),s=3}else{if(Ze(t)h){a.enqueue(Gt);break}}}})}const ii=4;function X(h){if(h)return eo(h)}function eo(h){for(var e in X.prototype)h[e]=X.prototype[e];return h}X.prototype.on=X.prototype.addEventListener=function(h,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+h]=this._callbacks["$"+h]||[]).push(e),this};X.prototype.once=function(h,e){function t(){this.off(h,t),e.apply(this,arguments)}return t.fn=e,this.on(h,t),this};X.prototype.off=X.prototype.removeListener=X.prototype.removeAllListeners=X.prototype.removeEventListener=function(h,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+h];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+h],this;for(var s,i=0;iPromise.resolve().then(e):(e,t)=>t(e,0),ne=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),to="arraybuffer";function ni(h,...e){return e.reduce((t,s)=>(h.hasOwnProperty(s)&&(t[s]=h[s]),t),{})}const so=ne.setTimeout,io=ne.clearTimeout;function yt(h,e){e.useNativeTimers?(h.setTimeoutFn=so.bind(ne),h.clearTimeoutFn=io.bind(ne)):(h.setTimeoutFn=ne.setTimeout.bind(ne),h.clearTimeoutFn=ne.clearTimeout.bind(ne))}const no=1.33;function oo(h){return typeof h=="string"?ao(h):Math.ceil((h.byteLength||h.size)*no)}function ao(h){let e=0,t=0;for(let s=0,i=h.length;s=57344?t+=3:(s++,t+=4);return t}function oi(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function ro(h){let e="";for(let t in h)h.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(h[t]));return e}function lo(h){let e={},t=h.split("&");for(let s=0,i=t.length;s{this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||t()})),this.writable||(s++,this.once("drain",function(){--s||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};Qn(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Yn(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=oi()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let ai=!1;try{ai=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const uo=ai;function mo(){}class po extends ho{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(i,n)=>{this.onError("xhr post error",i,n)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class ge extends X{constructor(e,t,s){super(),this.createRequest=e,yt(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const t=ni(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=ge.requestsCount++,ge.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=mo,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ge.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}ge.requestsCount=0;ge.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",_s);else if(typeof addEventListener=="function"){const h="onpagehide"in ne?"pagehide":"unload";addEventListener(h,_s,!1)}}function _s(){for(let h in ge.requests)ge.requests.hasOwnProperty(h)&&ge.requests[h].abort()}const fo=function(){const h=ri({xdomain:!1});return h&&h.responseType!==null}();class yo extends po{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=fo&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new ge(ri,this.uri(),e)}}function ri(h){const e=h.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||uo))return new XMLHttpRequest}catch{}if(!e)try{return new ne[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const li=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class go extends ss{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=li?{}:ni(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t{try{this.doWrite(s,n)}catch{}i&&ft(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=oi()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Ct=ne.WebSocket||ne.MozWebSocket;class bo extends go{createSocket(e,t,s){return li?new Ct(e,t,s):t?new Ct(e,t):new Ct(e)}doWrite(e,t){this.ws.send(t)}}class wo extends ss{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=Jn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=Zn();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const n=()=>{s.read().then(({done:a,value:r})=>{a||(this.onPacket(r),n())}).catch(a=>{})};n();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t{i&&ft(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const xo={websocket:bo,webtransport:wo,polling:yo},So=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,vo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ht(h){if(h.length>8e3)throw"URI too long";const e=h,t=h.indexOf("["),s=h.indexOf("]");t!=-1&&s!=-1&&(h=h.substring(0,t)+h.substring(t,s).replace(/:/g,";")+h.substring(s,h.length));let i=So.exec(h||""),n={},o=14;for(;o--;)n[vo[o]]=i[o]||"";return t!=-1&&s!=-1&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=Mo(n,n.path),n.queryKey=_o(n,n.query),n}function Mo(h,e){const t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function _o(h,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,n){i&&(t[i]=n)}),t}const Vt=typeof addEventListener=="function"&&typeof removeEventListener=="function",nt=[];Vt&&addEventListener("offline",()=>{nt.forEach(h=>h())},!1);class ke extends X{constructor(e,t){if(super(),this.binaryType=to,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const s=Ht(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=Ht(t.host).host);yt(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=lo(this.opts.query)),Vt&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},nt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ii,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&ke.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",ke.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,ft(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const n={type:e,data:t,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(ke.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Vt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=nt.indexOf(this._offlineEventListener);s!==-1&&nt.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}ke.protocol=ii;class To extends ke{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",d=>{if(!s)if(d.type==="pong"&&d.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ke.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const u=new Error("probe error");u.transport=t.name,this.emitReserved("upgradeError",u)}}))};function n(){s||(s=!0,c(),t.close(),t=null)}const o=d=>{const u=new Error("probe error: "+d);u.transport=t.name,n(),this.emitReserved("upgradeError",u)};function a(){o("transport closed")}function r(){o("socket closed")}function l(d){t&&d.name!==t.name&&n()}const c=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",a),this.off("close",r),this.off("upgrading",l)};t.once("open",i),t.once("error",o),t.once("close",a),this.once("close",r),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;sxo[i]).filter(i=>!!i)),super(e,s)}};function Ao(h,e="",t){let s=h;t=t||typeof location<"u"&&location,h==null&&(h=t.protocol+"//"+t.host),typeof h=="string"&&(h.charAt(0)==="/"&&(h.charAt(1)==="/"?h=t.protocol+h:h=t.host+h),/^(https?|wss?):\/\//.test(h)||(typeof t<"u"?h=t.protocol+"//"+h:h="https://"+h),s=Ht(h)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const n=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+n+":"+s.port+e,s.href=s.protocol+"://"+n+(t&&t.port===s.port?"":":"+s.port),s}const Co=typeof ArrayBuffer=="function",Eo=h=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(h):h.buffer instanceof ArrayBuffer,ci=Object.prototype.toString,Po=typeof Blob=="function"||typeof Blob<"u"&&ci.call(Blob)==="[object BlobConstructor]",Ro=typeof File=="function"||typeof File<"u"&&ci.call(File)==="[object FileConstructor]";function is(h){return Co&&(h instanceof ArrayBuffer||Eo(h))||Po&&h instanceof Blob||Ro&&h instanceof File}function ot(h,e){if(!h||typeof h!="object")return!1;if(Array.isArray(h)){for(let t=0,s=h.length;t=0&&h.numthis.opts.maxAttachments)throw new Error("too many attachments");s.attachments=a}if(e.charAt(t+1)==="/"){const n=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(n,t)}else s.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const n=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}s.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(ns.isPayloadValid(s.type,n))s.data=n;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case I.CONNECT:return Ts(t);case I.DISCONNECT:return t===void 0;case I.CONNECT_ERROR:return typeof t=="string"||Ts(t);case I.EVENT:case I.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Io.indexOf(t[0])===-1);case I.ACK:case I.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Oo{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=Lo(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Fo=Number.isInteger||function(h){return typeof h=="number"&&isFinite(h)&&Math.floor(h)===h};function Ts(h){return Object.prototype.toString.call(h)==="[object Object]"}const zo=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ns,Encoder:No,get PacketType(){return I}},Symbol.toStringTag,{value:"Module"}));function re(h,e,t){return h.on(e,t),function(){h.off(e,t)}}const Bo=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class hi extends X{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[re(e,"open",this.onopen.bind(this)),re(e,"packet",this.onpacket.bind(this)),re(e,"error",this.onerror.bind(this)),re(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var s,i,n;if(Bo.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:I.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const c=this.ids++,d=t.pop();this._registerAckCallback(c,d),o.id=c}const a=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,r=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!a||(r?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a{this.io.clearTimeoutFn(n),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,i)=>{const n=(o,a)=>o?i(o):s(a);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...n)=>(this._queue[0],i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...n)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:I.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case I.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case I.EVENT:case I.BINARY_EVENT:this.onevent(e);break;case I.ACK:case I.BINARY_ACK:this.onack(e);break;case I.DISCONNECT:this.ondisconnect();break;case I.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...i){s||(s=!0,t.packet({type:I.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:I.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s0&&h.jitter<=1?h.jitter:0,this.attempts=0}Ge.prototype.duration=function(){var h=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*h);h=Math.floor(e*10)&1?h+t:h-t}return Math.min(h,this.max)|0};Ge.prototype.reset=function(){this.attempts=0};Ge.prototype.setMin=function(h){this.ms=h};Ge.prototype.setMax=function(h){this.max=h};Ge.prototype.setJitter=function(h){this.jitter=h};class Wt extends X{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,yt(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new Ge({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||zo;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ko(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=re(t,"open",function(){s.onopen(),e&&e()}),n=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=re(t,"error",n);if(this._timeout!==!1){const a=this._timeout,r=this.setTimeoutFn(()=>{i(),n(new Error("timeout")),t.close()},a);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(re(e,"ping",this.onping.bind(this)),re(e,"data",this.ondata.bind(this)),re(e,"error",this.onerror.bind(this)),re(e,"close",this.onclose.bind(this)),re(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){ft(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new hi(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t)if(this.nsps[s].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;se()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const We={};function at(h,e){typeof h=="object"&&(e=h,h=void 0),e=e||{};const t=Ao(h,e.path||"/socket.io"),s=t.source,i=t.id,n=t.path,o=We[i]&&n in We[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let r;return a?r=new Wt(s,e):(We[i]||(We[i]=new Wt(s,e)),r=We[i]),t.query&&!e.query&&(e.query=t.queryKey),r.socket(t.path,e)}Object.assign(at,{Manager:Wt,Socket:hi,io:at,connect:at});class Go{constructor(){this.listeners={}}on(e,t){return this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t),()=>this.off(e,t)}off(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(s=>s!==t))}emit(e,t){if(this.listeners[e])for(const s of this.listeners[e])s(t)}once(e,t){const s=i=>{this.off(e,s),t(i)};this.on(e,s)}}class Ho{constructor(e){this.engine=e,this.container=document.createElement("div"),this.visible=!1,this.initialized=!1,this.playerElements=new Map}initialize(){this.container.id="player-list",this.container.style.position="absolute",this.container.style.top="120px",this.container.style.right="20px",this.container.style.backgroundColor="rgba(0, 0, 30, 0.7)",this.container.style.borderRadius="10px",this.container.style.padding="10px",this.container.style.boxShadow="0 0 10px rgba(0, 0, 0, 0.3)",this.container.style.color="white",this.container.style.fontFamily="Arial, sans-serif",this.container.style.zIndex="100",this.container.style.maxHeight="300px",this.container.style.overflowY="auto",this.container.style.minWidth="200px",this.container.style.display="none";const e=document.createElement("div");e.id="player-list-toggle-button",e.style.position="absolute",e.style.top="70px",e.style.right="80px",e.style.width="40px",e.style.height="40px",e.style.backgroundColor="rgba(45, 48, 52, 0.9)",e.style.borderRadius="50%",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center",e.style.cursor="pointer",e.style.zIndex="1001",e.style.boxShadow="0 2px 4px rgba(0, 0, 0, 0.3)",e.style.pointerEvents="auto",e.innerHTML="👥",e.style.fontSize="20px",e.title="Players",e.addEventListener("click",()=>{this.toggle(),e.style.backgroundColor=this.visible?"rgba(65, 68, 72, 0.9)":"rgba(45, 48, 52, 0.9)"});const t=document.createElement("div");t.style.display="flex",t.style.justifyContent="space-between",t.style.alignItems="center",t.style.marginBottom="10px",t.style.borderBottom="1px solid rgba(255, 255, 255, 0.2)",t.style.paddingBottom="5px";const s=document.createElement("div");s.textContent="Players",s.style.fontWeight="bold";const i=document.createElement("div");i.textContent="Ping: --",i.style.fontSize="12px",i.style.opacity="0.7",this.pingIndicator=i,t.appendChild(s),t.appendChild(i);const n=document.createElement("div");n.style.display="flex",n.style.flexDirection="column",n.style.gap="5px",this.listContainer=n,this.container.appendChild(t),this.container.appendChild(n),document.getElementById("ui-container").appendChild(e),document.getElementById("ui-container").appendChild(this.container),this.initialized=!0}show(){this.initialized||this.initialize(),this.container.style.display="block",this.visible=!1}hide(){this.initialized&&(this.container.style.display="none",this.visible=!1)}toggle(){this.visible?this.hide():this.show()}updatePlayerList(e,t){this.initialized||this.initialize();const s=new Set;e.forEach(i=>{s.add(i.id),this.playerElements.has(i.id)?this.updatePlayer(i,i.id===t):this.addPlayer(i,i.id===t)}),this.playerElements.forEach((i,n)=>{s.has(n)||this.removePlayer(n)})}addPlayer(e,t){const s=document.createElement("div");s.style.display="flex",s.style.alignItems="center",s.style.padding="5px",s.style.borderRadius="5px",s.style.backgroundColor=t?"rgba(224, 170, 255, 0.2)":"transparent";const i=document.createElement("div");i.style.width="24px",i.style.height="24px",i.style.borderRadius="50%",i.style.backgroundColor=this.getPlayerColor(e.id),i.style.marginRight="10px",i.style.display="flex",i.style.justifyContent="center",i.style.alignItems="center",i.style.color="white",i.style.fontSize="12px",i.style.fontWeight="bold",i.textContent=e.name?e.name.charAt(0).toUpperCase():"?";const n=document.createElement("div");n.textContent=e.name||"Unknown Player",t&&(n.textContent+=" (You)",n.style.fontWeight="bold"),s.appendChild(i),s.appendChild(n),this.playerElements.set(e.id,{element:s,avatar:i}),this.listContainer.appendChild(s)}updatePlayer(e,t){this.playerElements.get(e.id)}removePlayer(e){const t=this.playerElements.get(e);t&&(this.listContainer.removeChild(t.element),this.playerElements.delete(e))}updatePing(e){this.initialized&&(this.pingIndicator.textContent=`Ping: ${e}ms`,e<100?this.pingIndicator.style.color="#72e176":e<200?this.pingIndicator.style.color="#e0aaff":this.pingIndicator.style.color="#ff6b6b")}getPlayerColor(e){let t=0;for(let i=0;i{this.simulateConnection()},500)),y.info("Network manager initialized")}setupEventListeners(){this.socket.on("connect",()=>{y.info("Connected to server"),this.isConnected=!0,this.eventEmitter.emit("connected"),this.socket.emit("request_id")}),this.socket.on("disconnect",()=>{y.warn("Disconnected from server"),this.isConnected=!1,this.eventEmitter.emit("disconnected")}),this.socket.on("connect_error",e=>{y.debug("Connection attempt failed:",e.message)}),this.socket.io.on("reconnect_failed",()=>{this.handleConnectionFailure()}),this.socket.on("player_id",e=>{this.localPlayerId=e.id,y.debug("Received player ID:",this.localPlayerId),this.eventEmitter.emit("connected",{id:this.localPlayerId}),this.playerList.show()}),this.socket.on("player_join",e=>{this.handlePlayerJoin(e)}),this.socket.on("player_leave",e=>{this.handlePlayerLeave(e)}),this.socket.on("player_update",e=>{this.handlePlayerUpdate(e)}),this.socket.on("game_state",e=>{this.handleGameState(e)}),this.socket.on("pong",e=>{this.ping=e,this.playerList.updatePing(e)}),setInterval(()=>{if(this.isConnected){const e=Date.now();this.socket.emit("ping",()=>{const t=Date.now()-e;this.ping=t,this.playerList.updatePing(t)})}},5e3)}connect(){if(this.useSimulation){this.simulateConnection();return}this.socket.connect()}handleConnectionFailure(){if(this.connectionFailureNotified)return;this.connectionFailureNotified=!0,y.warn("Multiplayer server unreachable, giving up after maximum reconnection attempts. Continuing in single-player mode.");const e=this.engine.systems&&this.engine.systems.ui;e&&typeof e.showMessage=="function"&&e.showMessage("Multiplayer unavailable — flying solo")}simulateConnection(){y.info("Simulating network connection"),setTimeout(()=>{this.localPlayerId="player_"+Math.floor(Math.random()*1e4),y.debug("Simulated player ID:",this.localPlayerId),this.isConnected=!0,this.eventEmitter.emit("connected",{id:this.localPlayerId}),this.playerList.show();const e={id:this.localPlayerId,name:"Player",x:0,y:0,z:0};this.handlePlayerJoin(e),this.handlePlayerJoin({id:"player_ai_1",name:"Magic Bot 1",x:10,y:5,z:20}),this.handlePlayerJoin({id:"player_ai_2",name:"Magic Bot 2",x:-15,y:7,z:-5}),y.info("Network simulation initialized")},500)}disconnect(){this.socket&&this.socket.disconnect()}handlePlayerJoin(e){this.players.set(e.id,e),this.playerList.updatePlayerList(Array.from(this.players.values()),this.localPlayerId),this.eventEmitter.emit("player_join",e)}handlePlayerLeave(e){this.players.delete(e.id),this.playerList.updatePlayerList(Array.from(this.players.values()),this.localPlayerId),this.eventEmitter.emit("player_leave",e)}handlePlayerUpdate(e){if(this.players.has(e.id)){const t=this.players.get(e.id);Object.assign(t,e),this.eventEmitter.emit("player_update",t)}}handleGameState(e){this.eventEmitter.emit("game_state",e)}sendPlayerUpdate(e){if(this.useSimulation){this.localPlayerId&&(e.id=this.localPlayerId,this.handlePlayerUpdate(e));return}this.isConnected&&this.socket.emit("player_update",e)}sendPlayerAction(e,t){if(this.useSimulation){this.eventEmitter.emit("player_action",{playerId:this.localPlayerId,action:e,...t});return}this.isConnected&&this.socket.emit("player_action",{action:e,...t})}_update(e){this.useSimulation&&Math.random()<.05&&this.players.forEach((t,s)=>{if(s!==this.localPlayerId){const i={id:s,x:t.x+(Math.random()-.5)*.5,y:t.y+(Math.random()-.5)*.1,z:t.z+(Math.random()-.5)*.5};this.handlePlayerUpdate(i)}})}getPlayers(){return Array.from(this.players.values())}getLocalPlayerId(){return this.localPlayerId}}class Uo extends U{constructor(e){super(e,"questManager"),this.requireDependencies(["player"]),this.eventBus=e.eventBus,this.quests=[],this.activeQuests=[],this.totalDistance=0,this.lastPosition=null}async _initialize(){await this.loadQuests(),this.initializeEventListeners()}async loadQuests(){try{const e=await fetch(W("/assets/quests.json"));if(!e.ok)throw new Error(`HTTP error! status: ${e.status}`);this.quests=await e.json(),y.info("Quests loaded:",this.quests)}catch(e){y.error("Failed to load quests:",e),this.quests=[]}}initializeEventListeners(){this.quests.length>0&&(this.activeQuests=this.quests.map(e=>({...e,status:"active",objectives:e.objectives.map(t=>({...t,current:0}))}))),this.eventBus.on("manaCollected",e=>this.handleManaCollected(e)),this.eventBus.on("spellCast",e=>this.handleSpellCast(e)),this.eventBus.on("landmarkVisited",e=>this.handleLandmarkVisited(e))}_update(e,t){const s=this.engine.systems.get("playerState")?.localPlayer;if(!(!s||!s.position)){if(this.lastPosition){const i=Math.min(s.position.distanceTo(this.lastPosition),200);this.totalDistance+=i,this.checkExploreObjectives(this.totalDistance)}this.lastPosition=s.position.clone()}}handleManaCollected(e){!e||typeof e.amount!="number"||this.activeQuests.forEach(t=>{if(t.status!=="active")return;const s=t.objectives.find(i=>i.type==="collectMana");s&&(s.current+=e.amount,console.log(`Quest progress: ${t.name} - Mana: ${s.current}/${s.target}`),this.checkObjectiveCompletion(t,s))})}handleSpellCast(e){!e||!e.spellId||this.activeQuests.forEach(t=>{if(t.status!=="active")return;const s=t.objectives.find(i=>i.type==="castSpell"&&i.spellId===e.spellId);s&&(s.current+=1,console.log(`Quest progress: ${t.name} - Casts: ${s.current}/${s.target}`),this.checkObjectiveCompletion(t,s))})}handleLandmarkVisited(e){!e||!e.landmarkId||this.activeQuests.forEach(t=>{if(t.status!=="active")return;const s=t.objectives.find(i=>i.type==="visitLandmarks");s&&(s.current+=1,console.log(`Quest progress: ${t.name} - Landmarks: ${s.current}/${s.target}`),this.checkObjectiveCompletion(t,s))})}checkExploreObjectives(e){this.activeQuests.forEach(t=>{if(t.status!=="active")return;const s=t.objectives.find(i=>i.type==="exploreDistance");s&&(s.current=Math.min(e,s.target),e>=s.target&&(console.log(`Quest progress: ${t.name} - Distance: ${s.current}/${s.target}`),this.checkObjectiveCompletion(t,s)))})}checkObjectiveCompletion(e,t){if(e.objectives.every(i=>i.current>=i.target)){e.status="completed",this.applyRewards(e);const i=this.engine.systems.get("ui");if(i&&typeof i.showMessage=="function"){const n=e.rewards&&e.rewards.mana?` — +${e.rewards.mana} mana`:"";i.showMessage(`✦ Quest complete: ${e.name}${n}`,4500,"#ffcc66")}console.log(`Quest completed: ${e.name}`)}}applyRewards(e){const t=this.engine.systems.get("playerState")?.localPlayer;if(t){if(e.rewards.mana){t.mana+=e.rewards.mana;const s=this.engine.systems.get("ui");s&&s.updateManaDisplay(t.mana)}if(e.rewards.unlockSpell){const s=this.engine.systems.get("player");s&&s.spells&&s.spells.unlockNextSpell()}}}getActiveQuests(){return this.activeQuests.filter(e=>e.status==="active"||e.status==="completed")}}const di=Math.sqrt(3),qo=.5*(di-1),$e=(3-di)/6,ks=h=>Math.floor(h)|0,As=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function Wo(h=Math.random){const e=$o(h),t=new Float64Array(e).map(i=>As[i%12*2]),s=new Float64Array(e).map(i=>As[i%12*2+1]);return function(n,o){let a=0,r=0,l=0;const c=(n+o)*qo,d=ks(n+c),u=ks(o+c),m=(d+u)*$e,f=d-m,g=u-m,p=n-f,b=o-g;let S,x;p>b?(S=1,x=0):(S=0,x=1);const w=p-S+$e,v=b-x+$e,M=p-1+2*$e,_=b-1+2*$e,E=d&255,P=u&255;let T=.5-p*p-b*b;if(T>=0){const O=E+e[P],j=t[O],F=s[O];T*=T,a=T*T*(j*p+F*b)}let N=.5-w*w-v*v;if(N>=0){const O=E+S+e[P+x],j=t[O],F=s[O];N*=N,r=N*N*(j*w+F*v)}let D=.5-M*M-_*_;if(D>=0){const O=E+1+e[P+1],j=t[O],F=s[O];D*=D,l=D*D*(j*M+F*_)}return 70*(a+r+l)}}function $o(h){const t=new Uint8Array(512);for(let s=0;s<512/2;s++)t[s]=s;for(let s=0;s<512/2-1;s++){const i=s+~~(h()*(256-s)),n=t[s];t[s]=t[i],t[i]=n}for(let s=256;s<512;s++)t[s]=t[s-256];return t}class jo extends U{constructor(e){super(e,"world"),this.requireDependencies([]),this.scene=e.scene,this.currentChunks=new Map,this.manaNodes=[],this.heightCache=new Map,this.cacheResolution=8,this.maxCacheSize=15e3,this.cacheHits=0,this.cacheMisses=0,this.chunkSize=1024,this.terrainResolution=64,this.maxHeight=400,this.minHeight=-50,this.viewDistance=8,this.waterLevel=0,this.maxManaNodes=30,this._frustum=new Gi,this._frustumMatrix=new ye,this._cameraViewProjectionMatrix=new ye,this.terrainParams={baseScale:.0012,detailScale:.008,mountainScale:.0015,baseHeight:60,mountainHeight:140,detailHeight:10},this.seed=Math.random()*1e3,this.noise=Wo(),this.biomes={ocean:{threshold:.02,color:new C(26282)},beach:{threshold:.02,color:new C(14540151)},plains:{threshold:.03,color:new C(4500036)},forest:{threshold:.04,color:new C(2258722)},mountains:{threshold:.02,color:new C(8947848)},snow:{threshold:.008,color:new C(16777215)}},this.materials={},this.landmarks=new Map,this.landmarkTypes=[{name:"ancient_ruins",minHeight:10,maxHeight:60,minDistance:1e3,maxSlope:.2,frequency:1e-5,size:{min:20,max:40},requiresWater:!1},{name:"magical_circle",minHeight:5,maxHeight:80,minDistance:800,maxSlope:.3,frequency:2e-5,size:{min:10,max:25},requiresWater:!1},{name:"crystal_formation",minHeight:40,maxHeight:120,minDistance:1200,maxSlope:.6,frequency:15e-6,size:{min:15,max:35},requiresWater:!1},{name:"stone_arch",minHeight:20,maxHeight:90,minDistance:1500,maxSlope:.4,frequency:8e-6,size:{min:25,max:50},requiresWater:!1},{name:"ancient_temple",minHeight:30,maxHeight:70,minDistance:2e3,maxSlope:.1,frequency:5e-6,size:{min:40,max:80},requiresWater:!1},{name:"oasis",minHeight:5,maxHeight:30,minDistance:1e3,maxSlope:.15,frequency:1e-5,size:{min:15,max:35},requiresWater:!1}]}fractalNoise(e,t,s,i,n,o){const a=Math.floor(e/this.chunkSize),r=Math.floor(t/this.chunkSize),l=e-a*this.chunkSize,c=t-r*this.chunkSize;Math.min(l,this.chunkSize-l,c,this.chunkSize-c)/10;let u=s,m=2,f=0,g=0;for(let p=0;p.1&&a<.48){const p=(a-.1)/.38,b=1/(1+Math.exp(-(p*8-4))),S=1/(1+Math.exp(-((p-.5)*6))),x=b*(1-p*.4)+S*(p*.4),w=x*(1.15-.3*x),v=this.minHeight+w*65,M=.004,_=.02,E=.09,P=.3,T=Math.pow(1-Math.min(1,p/.2),2),N=Math.pow(Math.max(0,Math.min(1,(p-.8)/.2)),2),D=4*Math.pow(p*(1-p),1.5),O=.015,j=this.fractalNoise(e*O+this.seed*53,t*O+this.seed*59,4,.6,2)*12*(T*.8+N*.8),F=this.fractalNoise(e,t,M,4,.5,2)*(4+T*3.5+N*3),Y=this.fractalNoise(e,t,_,3,.5,2)*(2.5+D*2.8),Ae=this.fractalNoise(e,t,E,2,.5,2)*(1.2+T*1+D*1.5),oe=this.fractalNoise(e,t,P,2,.5,2)*(.8+T*1.2+N*1.2),J=Math.sin(e*.001+t*.002+this.seed*.3)*.5+.5,Ce=Math.pow(J,1.5)*3*Math.max(T,N),q=F*(1+Ce*.3),z=Y*(1+Ce*.2),B=q*(.4+.6*w)+z*(.3+.7*D)+Ae*(.2+.8*Math.min(T,D,N))+oe*(.1+.9*Math.max(T,N))+j,H=v+B;return this._addToHeightCache(n,H),H}let l=(this.fractalNoise(e,t,this.terrainParams.baseScale,8,.5,2)+1)*.5*this.terrainParams.baseHeight;if(a>.15&&a<.2){const p=(a-.25)/.25,S=this.fractalNoise(e,t,.02,2,.5,2);if(S>.3){const x=Math.pow((S-.3)/.7,2)*p;l+=40*x}}if(a>.6){const p=Math.min(1,Math.max(0,(a-.6)/.2)),b=p*p*(3-2*p),S=this.ridgedNoise(e,t,this.terrainParams.mountainScale*1.1,3),x=this.ridgedNoise(e,t,this.terrainParams.mountainScale*.7,5),w=this.ridgedNoise(e+128.37,t-94.21,this.terrainParams.mountainScale*1.4,4),v=this.ridgedNoise(e-57.44,t+63.18,this.terrainParams.mountainScale*2.1,3),M=1+.4*this.fractalNoise(e*4e-4,t*4e-4,3,.5,2),_=(1-b)*.8,E=.6+b*.2,P=.25+b*.1,T=.15-b*.05,N=(S*_+x*E+w*P+v*T)/(_+E+P+T),D=b*M,O=1+.7*this.fractalNoise(e*8e-4,t*8e-4,3,.5,2);l+=N*this.terrainParams.mountainHeight*D*O}const c=this.fractalNoise(e,t,5e-4,2,.5,2),d=this.fractalNoise(e,t,4e-4,2,.5,2),u=(c+1)*.5,m=(d+1)*.5;if(u>.7&&m<.3){const p=this.fractalNoise(e,t,.02,2,.5,2);l+=p*5}const f=this.fractalNoise(e,t,4e-4,2,.5,2);if(f>.5&&l>20&&l<100){let p;l<40?p=30+f*10:l<70?p=60+f*15:p=80+f*20;const b=(f-.5)*(1/.5),S=this.noise(e*.002+this.seed*19,t*.002+this.seed*21),x=b*(.7+.5*S);l=l*(1-x)+p*x}const g=this.fractalNoise(e,t,this.terrainParams.detailScale,2,.5,2);return l+=g*this.terrainParams.detailHeight*.5,this._addToHeightCache(n,l),l}catch{return this._addToHeightCache(n,0),0}}calculateSlope(e,t){this.getTerrainHeight(e,t);const i=this.getTerrainHeight(e,t-2),n=this.getTerrainHeight(e,t+2),o=this.getTerrainHeight(e+2,t),a=this.getTerrainHeight(e-2,t),r=(o-a)/(2*2),l=(n-i)/(2*2);return Math.sqrt(r*r+l*l)}getBiomeColor(e,t,s){return e=this.minHeight+35?new C(14540151):new C(26282):e<120?new C(4500036):e<200?new C(2258722):e<300?new C(6710886):new C(16777215)}createChunkGeometry(e,t){const s=new Ne(this.chunkSize,this.chunkSize,this.terrainResolution,this.terrainResolution);s.rotateX(-Math.PI/2);const i=s.attributes.position.array,n=[];for(let o=0;ou.some(g=>{const p=g.position.x-m,b=g.position.z-f;return p*p+b*b<80*80});for(let u=0;u{t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}createManaNodes(){this.manaNodes.forEach(t=>this.removeManaNode(t)),this.manaNodes=[];const e=this.engine.systems.get("playerState")?.localPlayer;!e||!e.position||this.generateManaNodePositions(e,this.maxManaNodes).forEach(t=>this.spawnManaNode(t))}topUpManaNodes(){const e=this.engine.systems.get("playerState")?.localPlayer;if(!e||!e.position)return;this.manaNodes=this.manaNodes.filter(s=>s.userData&&!s.userData.collected?!0:(this.removeManaNode(s),!1));const t=this.maxManaNodes-this.manaNodes.length;t<=0||this.generateManaNodePositions(e,t,this.manaNodes).forEach(s=>this.spawnManaNode(s))}isPositionSuitableForLandmark(e,t,s){const i=this.getTerrainHeight(e,t);if(is.maxHeight||this.calculateSlope(e,t)>s.maxSlope)return!1;for(const[o,a]of this.landmarks.entries())if(a.type===s.name){const r=a.position.x-e,l=a.position.z-t;if(Math.sqrt(r*r+l*l)=this.maxCacheSize){const s=Math.floor(this.maxCacheSize*.1),i=[...this.heightCache.keys()];for(let n=0;nnew A),a=e.index?e.index.array:null,r=a?a.length/3:n/3,l=new A,c=new A,d=new A,u=new A,m=new A,f=new A;for(let w=0;w1e-4?o[w].normalize():o[w]&&o[w].set(0,1,0)}const p=new Set;for(let w=0;w300&&M<.3&&p.add(w)}const b=new A,S=new A(0,1,0);for(const w of p){const v=new Set;for(let _=0;_0&&b.lengthSq()>1e-4){b.normalize();const _=g.get(w).y;let E=.1;_>300&&(E+=Math.min(.4,(_-300)/150*.4)),E=Math.min(E,.5),o[w].copy(b).lerp(S,E).normalize(),_>340&&o[w].y<.05&&(o[w].y=.05,o[w].normalize())}}const x=new Float32Array(n*3);for(let w=0;w1e-4?o[w].normalize():o[w]?o[w].set(0,1,0):o[w]=new A(0,1,0),x[w*3]=o[w].x,x[w*3+1]=o[w].y,x[w*3+2]=o[w].z;e.setAttribute("normal",new ce(x,3))}createLandmark(e,t,s){const n=this.getTerrainHeight(e,t),o=new ee;o.position.set(e,n,t);const a=s.size.max-s.size.min,r=s.size.min+Math.random()*a;switch(s.name){case"ancient_ruins":this.createAncientRuins(o,r);break;case"magical_circle":this.createMagicalCircle(o,r);break;case"crystal_formation":this.createCrystalFormation(o,r);break;case"stone_arch":this.createStoneArch(o,r);break;case"ancient_temple":this.createAncientTemple(o,r);break;case"oasis":this.createOasis(o,r);break}const l=`${s.name}_${this.landmarks.size}`;return this.landmarks.set(l,{id:l,type:s.name,position:new A(e,n,t),size:r,mesh:o}),this.scene.add(o),o}createAncientRuins(e,t){const s=new R({color:10066329,roughness:.8,metalness:.1}),i=new R({color:7829367,roughness:.9,metalness:.05}),n=Math.floor(5+t/8),o=t*.5;for(let u=0;u.6,S=new Z(t*.05,t*.06,p,8),x=new k(S,b?s:i);if(x.position.set(f,p*.5,g),x.castShadow=!0,x.receiveShadow=!0,x.rotation.y=Math.random()*.2,!b){const w=Math.random()*.3,v=Math.random()*Math.PI*2;x.rotation.x=Math.cos(v)*w,x.rotation.z=Math.sin(v)*w}if(e.add(x),Math.random()>.5){const w=Math.floor(Math.random()*3)+1;for(let v=0;v0){const b=p/o*c;u.setX(g,u.getX(g)+Math.cos(d)*b*o),u.setZ(g,u.getZ(g)+Math.sin(d)*b*o)}}r.computeVertexNormals();const m=new k(r,l);m.position.y=o*.5,m.castShadow=!0,n.add(m);const f=6+Math.floor(Math.random()*3);for(let g=0;g.5){const g=Math.floor(Math.random()*3)+1;for(let p=0;p.01)return;const t=Math.floor(e.position.x/this.chunkSize),s=Math.floor(e.position.z/this.chunkSize),i=this.viewDistance+2,n=5;for(let o=0;o.2)){for(const m of this.landmarkTypes)if(!(Math.random()>m.frequency*1e3)&&this.isPositionSuitableForLandmark(d,u,m)){this.createLandmark(d,u,m);return}}}}updateLandmarks(e,t){this.checkForLandmarkLocations();for(const[s,i]of this.landmarks.entries()){const n=i.mesh;n.parent&&n.traverse(o=>{if(o.userData.isGlowing){const a=o.userData.pulseRate||1,l=(o.userData.originalIntensity||.5)*(.7+Math.sin(t*a)*.3);o.material&&o.material.emissiveIntensity!==void 0&&(o.material.emissiveIntensity=l)}if(o.userData.isFloating){const a=o.userData.floatHeight||1,r=o.userData.floatSpeed||1,l=o.userData.originalY||o.position.y;o.position.y=l+Math.sin(t*r)*a}})}}updateChunks(){const e=this.engine.systemManager.get("playerState")?.localPlayer;if(!e)return;const t=this.engine.camera;if(!t)return;let s=this.viewDistance;if(this.engine.systemManager.get("mobileLOD")&&this.engine.settings&&this.engine.settings.isMobile){const a=Math.ceil(this.engine.systemManager.get("mobileLOD").getHorizonLODDistance()/this.chunkSize);s=Math.max(s,a/this.chunkSize)}const i=Math.floor(e.position.x/this.chunkSize),n=Math.floor(e.position.z/this.chunkSize),o=new Set;this._cameraViewProjectionMatrix.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(this._cameraViewProjectionMatrix);for(let a=-s;a<=s;a++)for(let r=-s;r<=s;r++)if(a*a+r*r<=s*s){const c=i+a,d=n+r,u=c*this.chunkSize,m=d*this.chunkSize,f=`${u},${m}`;if(o.add(f),!this.currentChunks.has(f)){const g=new A(u+this.chunkSize/2,0,m+this.chunkSize/2);g.y=this.getTerrainHeight(g.x,g.z);const p=new js(g,this.chunkSize*.75),S=g.distanceTo(t.position)>this.chunkSize*s*1.5,x=Math.atan2(g.y-t.position.y,Math.sqrt(Math.pow(g.x-t.position.x,2)+Math.pow(g.z-t.position.z,2))),w=Math.abs(x)<.15;if(S&&!w&&!this._frustum.intersectsSphere(p))continue;try{const v=this.createChunkGeometry(u,m),M=this.materials.terrain,_=new k(v,M);_.position.set(u,0,m),_.castShadow=!0,_.receiveShadow=!0,_.renderOrder=0,this.scene.add(_),this.currentChunks.set(f,_)}catch{}}}for(const[a,r]of this.currentChunks.entries())o.has(a)||(this.scene.remove(r),r.geometry.dispose(),this.currentChunks.delete(a))}updateVisibility(e){}_update(e,t){let s=this.engine.systems.player?.localPlayer;if(s||(s=this.engine.systemManager.get("playerState")?.localPlayer),!s)return;this.manaNodes.filter(o=>o.userData&&!o.userData.collected).length<10&&this.topUpManaNodes(),this.manaNodes.length===0&&s&&s.position&&this.createManaNodes(),this.updateChunks(),this.updateLandmarks(e,t),this.manaNodes.forEach((o,a)=>{o.userData&&!o.userData.collected&&(o.position.y+=Math.sin(t*2+a*.5)*.03,o.rotation.y+=e*.5)});const n=50;this.manaNodes.forEach(o=>{if(o.userData&&!o.userData.collected){const a=s.position.distanceTo(o.position),r=Math.max(0,1-a/n),l=o.children.filter(m=>m.material&&m.material.opacity!==void 0);l.forEach(m=>{m.material.opacity=.3+r*.7,m.material.emissiveIntensity!==void 0&&(m.material.emissiveIntensity=r),m.scale.setScalar(1+r*.5)});const c=s.mana||0,u=Math.max(0,1-c/100);l.forEach(m=>{m.material.emissiveIntensity!==void 0&&(m.material.emissiveIntensity+=u*.5)})}})}checkManaCollection(e,t,s){typeof t=="number"&&(s=t,t=e);const i=[],n=new A().subVectors(t,e),o=n.lengthSq(),a=new A,r=new A;if(this.manaNodes.forEach(l=>{if(l.userData&&!l.userData.collected){let c=0;o>0&&(a.subVectors(l.position,e),c=K.clamp(a.dot(n)/o,0,1)),r.copy(e).addScaledVector(n,c),r.distanceTo(l.position)0){const l=i.reduce((c,d)=>c+d.value,0);this.engine.eventBus.emit("manaCollected",{amount:l})}return i}getManaNodesInRadius(e,t){return this.manaNodes.filter(s=>s.userData&&!s.userData.collected&&s.position.distanceTo(e)<=t)}}class Ko extends U{constructor(e){super(e,"playerPhysics"),this.gravity=5.8,this.minAltitude=5,this.maxAltitude=2200,this.dragCoefficient=.4,this.altitudeDamping=.95,this.bankingSensitivity=.08,this.turnDamping=.97,this.velocityAlignRate=2.5,this.maxAltitudeVelocity=90,this.divePower=150,this.diveCapStretch=.4,this.absoluteMaxSpeed=420,this.climbDragCoefficient=.5,this._tempVec1=new A,this._tempVec2=new A,this._tempVec3=new A,this._skipThreshold=5e-4,this._lastSignificantUpdate=0,this._forceUpdateInterval=.1}async _initialize(){if(this.playerSystem=this.engine.systems.get("playerState"),!this.playerSystem)throw new Error("PlayerPhysics requires playerState system");this.treeSystem=null,this.landmarkSystem=null,this.playerRadius=3,this.collisionPushback=.8}_update(e,t){this.updatePhysics(e)}updatePhysics(e){const t=this.playerSystem.localPlayer;if(!t||(this._lastSignificantUpdate+=e,e1&&(this._tempVec2.copy(this._tempVec1).multiplyScalar(i),t.velocity.lerp(this._tempVec2,1-Math.exp(-this.velocityAlignRate*e))),s<0&&t.velocity.addScaledVector(this._tempVec1,-s*this.divePower*e),this._tempVec1.copy(t.acceleration).multiplyScalar(e),t.velocity.add(this._tempVec1),i=t.velocity.length(),i>.001){let a=1-this.dragCoefficient*(i/t.maxSpeed)*e;s>0&&(a-=s*this.climbDragCoefficient*e),t.velocity.multiplyScalar(Math.max(0,a))}let n=t.maxSpeed*(t.speedMultiplier||1);s<0&&(n*=1+this.diveCapStretch*Math.min(1,-s*2)),n=Math.min(n,this.absoluteMaxSpeed);const o=Math.sqrt(t.velocity.x*t.velocity.x+t.velocity.z*t.velocity.z);if(o>n){const a=n/o;t.velocity.x*=a,t.velocity.z*=a}this._tempVec1.copy(t.velocity).multiplyScalar(e),t.position.add(this._tempVec1),this.checkObjectCollisions(t,this._tempVec3),this.updateAltitude(t,e),t.acceleration.set(0,0,0)}updateAltitude(e,t){e.altitudeVelocity=K.clamp(e.altitudeVelocity,-this.maxAltitudeVelocity,this.maxAltitudeVelocity),Math.abs(e.altitudeVelocity)>.001&&(e.position.y+=e.altitudeVelocity*t,e.altitudeVelocity*=Math.pow(this.altitudeDamping,t*60),Math.abs(e.altitudeVelocity)<.001&&(e.altitudeVelocity=0));const s=this.engine.systemManager.get("world");if(!s){y.warn("PlayerPhysics: world system not available");return}const i=s.getTerrainHeight(e.position.x,e.position.z),n=Math.max(this.minAltitude,i+5);e.position.ythis.maxAltitude&&(e.position.y=this.maxAltitude,e.velocity.y>0&&(e.velocity.y=0),e.altitudeVelocity>0&&(e.altitudeVelocity=0))}applyForwardForce(e,t){this._tempVec1.set(0,0,1).applyEuler(e.rotation),e.acceleration.addScaledVector(this._tempVec1,t)}applySideForce(e,t){this._tempVec1.set(1,0,0).applyEuler(e.rotation),e.acceleration.addScaledVector(this._tempVec1,t);const s=Math.PI/6;e.bankAngle=K.clamp(e.bankAngle+t*.01,-s,s)}applyAltitudeChange(e,t){e.altitudeVelocity+=t,e.altitudeVelocity=K.clamp(e.altitudeVelocity,-this.maxAltitudeVelocity,this.maxAltitudeVelocity)}checkObjectCollisions(e,t){this.treeSystem||(this.treeSystem=this.engine.systems.get("simpleTrees")),this.landmarkSystem||(this.landmarkSystem=this.engine.systems.get("landmarks"));let s=null,i=1/0;if(this.treeSystem&&this.treeSystem.spawnedTrees)for(const n of this.treeSystem.spawnedTrees){const o=e.position.x-n.position.x,a=e.position.z-n.position.z,r=Math.sqrt(o*o+a*a),l=n.scale.x*.5,c=this.playerRadius+l;r{this.cooldowns[i.name]=0})}catch(s){y.error("Failed to load spells:",s)}}checkUnlock(e,t){const s=e.unlockCondition;if(!s)return!0;switch(s.type){case"mana":return t.totalMana>=s.value;case"landmarks":return(t.landmarksVisited||0)>=s.value;default:return!1}}selectSpell(e){const t=this.playerSystem.localPlayer;if(t&&e>=0&&e=this.spells.length)return;const s=this.spells[t],i=this.cooldowns[s.name];if(i>0){this.engine.systems.ui&&this.engine.systems.ui.showMessage(`Spell on cooldown: ${Math.ceil(i)}s`);return}if(e.mana{t.speedMultiplier=t.speedMultiplier/s.value||1};break;case"invulnerability":t.invulnerable=!0,i.reset=()=>{t.invulnerable=!1};break;case"scan":if(this.engine.systems.world){const n=this.engine.systems.world.getManaNodesInRadius(t.position,s.value.radius);this.engine.systems.ui&&this.engine.systems.ui.highlightNodes(n),this.engine.systems.minimap&&this.engine.systems.minimap.markNodes(n)}return;case"mana_multiplier":t.manaMultiplier=(t.manaMultiplier||1)*s.value,i.reset=()=>{t.manaMultiplier=t.manaMultiplier/s.value||1};break;default:y.warn("Unknown effect type:",s.type);return}this.activeEffects.push(i)}createVFX(e,t){const s=e.vfx,i=new C(s.color);let n;if(s.type==="aura"||s.type==="shield"){const l=this.playerSystem.localPlayer;n=this.createParticleEmitter(i,!0),l.model.add(n)}else s.type==="scan"&&(n=this.createParticleEmitter(i,!1),n.position.copy(t),this.scene.add(n));const o=e.effect.duration||5,a=this.engine.elapsed,r=()=>{const l=this.engine.elapsed-a;if(l>o){n.parent===player.model?player.model.remove(n):this.scene.remove(n);return}n.material.opacity=1-l/o,requestAnimationFrame(r)};r()}createParticleEmitter(e,t=!1){const s=new lt({map:this.particlesTexture,color:e,transparent:!0,opacity:1,size:.5,blending:De}),i=new ct(this.particlesGeometry,s);return t&&i.position.set(0,0,0),i}updateSpells(e){const t=this.engine.elapsed;Object.keys(this.cooldowns).forEach(s=>{this.cooldowns[s]>0&&(this.cooldowns[s]-=e)});for(let s=this.activeEffects.length-1;s>=0;s--){const i=this.activeEffects[s];t-i.startTime>=i.duration&&(i.reset&&i.reset(),this.activeEffects.splice(s,1))}Math.random()<.01&&this.unlockNextSpell()}unlockNextSpell(){const t=this.playerSystem.engine.systemManager.get("playerState")?.localPlayer;if(!t){y.warn("PlayerSpells.unlockNextSpell: No localPlayer available");return}for(let s=0;s{for(let g=0;g{for(let g=0;g`rgb(${Math.floor(v.r*255)},${Math.floor(v.g*255)},${Math.floor(v.b*255)})`;o.fillStyle=c(a),o.fillRect(0,0,e,e);const d=e*.08;o.strokeStyle=c(l),o.lineWidth=d,o.strokeRect(d/2,d/2,e-d,e-d),o.strokeStyle=c(r),o.lineWidth=d*.3,o.strokeRect(d*1.2,d*1.2,e-d*2.4,e-d*2.4),o.globalAlpha=.15;for(let v=0;v{o.beginPath(),o.arc(v,M,p,0,Math.PI*2),o.fillStyle=c(r),o.globalAlpha=.3,o.fill(),o.globalAlpha=1,o.beginPath(),o.moveTo(v,M-p*.5),o.lineTo(v+p*.5,M),o.lineTo(v,M+p*.5),o.lineTo(v-p*.5,M),o.closePath(),o.fillStyle=c(l),o.fill()});const S=o.getImageData(0,0,e,e),x=S.data;for(let v=0;v{const s=Ie.colorSchemes[t];return Ie.createCarpet({width:5,length:8,primaryColor:s.primary,secondaryColor:s.secondary,borderColor:s.border,includeFringe:!0,segments:16})}),this.carpetMaterials=e.map(t=>({color:Ie.colorSchemes[t].secondary})),y.info(`Created ${this.carpetModels.length} beautiful carpet models`)}createCarpetModel(e){if(this.carpetModels.length===0){y.warn("PlayerModels.createCarpetModel: No carpet models available, creating default");const r=Ie.createCarpet({width:5,length:8,primaryColor:new C(16737792),secondaryColor:new C(16755200),borderColor:new C(4860442),includeFringe:!0}),l=new $(.6,12,12),c=new V({color:16755200,transparent:!0,opacity:.7}),d=new k(l,c);return d.position.y=2.5,r.add(d),r}let t=0;if(e){let r=0;for(let l=0;l{r.isMesh&&r.name==="carpetBody"&&r.material&&(r.material=r.material.clone())});const i=new $(.6,12,12),n=this.carpetMaterials[t]?.color||16777215,o=new V({color:n,transparent:!0,opacity:.7}),a=new k(i,o);return a.position.y=2.5,a.name="playerMarker",s.add(a),s}createCrosshair(){const e=document.createElement("div");e.style.position="absolute",e.style.top="50%",e.style.left="50%",e.style.transform="translate(-50%, -50%)",e.style.width="20px",e.style.height="20px",e.style.borderRadius="50%",e.style.border="2px solid rgba(255, 255, 255, 0.8)",e.style.pointerEvents="none";const t=document.createElement("div");t.style.position="absolute",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.width="4px",t.style.height="4px",t.style.borderRadius="50%",t.style.backgroundColor="rgba(255, 255, 255, 0.8)",e.appendChild(t),document.body.appendChild(e),this.crosshair=e}createManaCollectionEffect(e){const s=new ee;for(let o=0;o<15;o++){const a=new k(new $(.2,8,8),new V({color:65535,transparent:!0,opacity:.8}));a.position.copy(e);const r=o/15*Math.PI*2,l=2,c=5+Math.random()*3;a.userData={velocity:new A(Math.cos(r)*l,c,Math.sin(r)*l),life:1,angle:r},s.add(a)}this.scene.add(s);const i=o=>{let a=!0;for(let r=0;r0&&(a=!1)}if(a){this.scene.remove(s);return}requestAnimationFrame(()=>i(.016))};i(.016);const n=this.playerSystem.localPlayer;n&&n.position.distanceTo(e)<10&&this.createManaFlowEffect(e,n.position.clone())}createManaFlowEffect(e,t){const i=new ee;for(let o=0;o<10;o++){const a=new k(new $(.15,8,8),new V({color:65535,transparent:!0,opacity:.8})),r=Math.random()*.3;a.position.lerpVectors(e,t,r),a.position.x+=(Math.random()-.5)*2,a.position.y+=(Math.random()-.5)*2,a.position.z+=(Math.random()-.5)*2;const l=t.clone().sub(a.position).normalize();a.userData={velocity:l.multiplyScalar(15+Math.random()*5),life:.5+Math.random()*.5},i.add(a)}this.scene.add(i);const n=o=>{let a=!0;for(let r=0;r0&&(a=!1)}if(a){this.scene.remove(i);return}requestAnimationFrame(()=>n(.016))};n(.016)}updateModels(){const e=this.playerSystem.engine.systemManager.get("playerState");if(!e||!e.players){y.warn("PlayerModels.updateModels: playerState or players is undefined");return}e.players.forEach(t=>{t.model||(t.model=this.createCarpetModel(t.id),this.scene.add(t.model)),t.model.position.copy(t.position),t.model.rotation.set(t.rotation.x,t.rotation.y,t.bankAngle||0)})}createTrailEffect(e){const t=this.engine.qualityManager?.batterySavingMode||!1;if(t&&Math.random()<.5)return;const s=new k(new $(.2,8,8),new V({color:8956671,transparent:!0,opacity:.5})),i=new A(0,0,-4).applyEuler(e.rotation);s.position.copy(e.position).add(i),s.position.x+=(Math.random()-.5)*2,s.position.y+=(Math.random()-.5)*.5,s.position.z+=(Math.random()-.5)*2,s.userData={life:t?.6:1,fadeRate:.8+Math.random()*.4},this.scene.add(s);const n=o=>{s.userData.life-=o*s.userData.fadeRate;const a=s.userData.life;if(s.scale.set(a*2,a*2,a*2),s.material.opacity=a*.5,a<=0){this.scene.remove(s);return}requestAnimationFrame(()=>n(.016))};n(.016)}createBoostEffect(e,t){const s=this.engine.qualityManager?.batterySavingMode?15:30,i=new ee,n=new A(0,1,0),o=new A().crossVectors(t,n).normalize(),a=new A().crossVectors(o,t).normalize();for(let c=0;c{let d=!0;r.scale.multiplyScalar(.9),r.material.opacity*=.85,r.material.opacity>.01?d=!1:this.scene.remove(r);for(let u=0;u0&&(d=!1)}if(d){this.scene.remove(i);return}requestAnimationFrame(()=>l(.016))};l(.016),this.engine.systems.audio&&this.engine.systems.audio.playSound("boost",e)}addCameraShake(e=.5,t=.3){if(!this.engine.camera)return;const s=this.engine.camera.position.clone();let i=0;const n=()=>{if(i+=.016,i{if(this.engine.systems.get("playerState")?.localPlayer)switch(t.code){case"Digit1":this.spells.selectSpell(0);break;case"Digit2":this.spells.selectSpell(1);break;case"Digit3":this.spells.selectSpell(2);break;case"Digit4":this.spells.selectSpell(3);break;case"KeyE":this.spells.castSpell();break}}),y.info("Player system initialized")}enable(){y.info("Player system enabled")}updateTransition(e){if(this.transitionAlpha+=e*.5,this.transitionAlpha>=2){this.isTransitioning=!1,this.transitionAlpha=0,this.worldTransitionComplete&&(this.worldTransitionComplete(),this.worldTransitionComplete=null);const t=document.getElementById("transition-overlay");t&&document.body.removeChild(t)}else{const t=document.getElementById("transition-overlay");if(t){const s=this.transitionAlpha<=1?this.transitionAlpha:2-this.transitionAlpha;t.style.opacity=s.toString()}}}checkWorldBoundaries(){}startWorldTransition(){if(this.isTransitioning)return;const e=document.createElement("div");e.id="transition-overlay",e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e.style.backgroundColor="black",e.style.opacity="0",e.style.transition="opacity 0.5s",e.style.zIndex="1000",e.style.pointerEvents="none",document.body.appendChild(e),this.isTransitioning=!0,this.transitionAlpha=0,this.worldTransitionComplete=()=>{this.engine.systems.world.seed=Math.random()*1e3,this.localPlayer.position.set(0,150,0),this.localPlayer.velocity.set(0,0,0),this.lastCollectionPosition=null,this.engine.systems.world.createTerrain(),this.engine.systems.world.createTerrainCollision(),this.engine.systems.world.createManaNodes()}}_update(e,t){if(this.isTransitioning){this.updateTransition(e);return}if(this.models)try{this.models.updateModels()}catch{}this.spells&&this.spells.updateSpells(e),this.checkManaCollection(),this.checkLandmarkVisits(),this.checkWorldBoundaries(),this.broadcastNetworkState(e)}broadcastNetworkState(e){if(this._networkBroadcastAccum+=e,this._networkBroadcastAccum<.1)return;this._networkBroadcastAccum=0;const t=this.engine.systems.get("network"),s=this.localPlayer||this.engine.systems.get("playerState")?.localPlayer;!t||!t.isConnected||!s||t.sendPlayerUpdate({x:s.position.x,y:s.position.y,z:s.position.z,rotationX:s.rotation.x,rotationY:s.rotation.y,rotationZ:s.rotation.z,bankAngle:s.bankAngle||0,mana:s.mana||0,health:s.health||100,speed:s.velocity?s.velocity.length():0})}checkManaCollection(){const e=this.engine.systems.get("playerState");if(!e||!e.localPlayer)return;const t=e.localPlayer;if(!t)return;const s=15,i=this.engine.systems.get("world");if(!i){y.warn("PlayerSystem: World system not available for mana collection");return}const n=this.lastCollectionPosition||t.position,o=i.checkManaCollection(n,t.position,s);this.lastCollectionPosition=(this.lastCollectionPosition||new A).copy(t.position),o.forEach(a=>{const r=a.value*(t.manaMultiplier||1);t.mana+=r,t.totalMana+=r;const l=this.engine.systems.get("ui");l&&l.updateManaDisplay(t.mana),this.models.createManaCollectionEffect(a.position)})}checkLandmarkVisits(){const e=this.engine.systems.get("playerState");if(!e||!e.localPlayer)return;const t=e.localPlayer,s=this.engine.systems.get("landmarks");if(!s||!s.landmarks)return;const i=s.landmarks;if(!i)return;const n=50;for(const[o,a]of i)a.position&&a.position.distanceTo(t.position){s&&s.id&&(y.info("PlayerStateManager: Network connected, updating local player ID"),this.updatePlayer(this.localPlayer.id,{id:s.id}),this.localPlayer.id=s.id)}),t.on("player_join",s=>{this.createNetworkPlayer(s)}),t.on("player_leave",s=>{this.removePlayer(s.id)}),t.on("player_update",s=>{this.updateNetworkPlayer(s)})}else y.warn("PlayerStateManager: No network system available, running in offline mode");y.info("PlayerStateManager initialized with local player:",!!this.localPlayer)}createLocalPlayer(e){const t={id:e,isLocal:!0,position:new A(0,150,0),rotation:new ut(0,0,0,"YXZ"),velocity:new A(0,0,0),acceleration:new A(0,0,0),bankAngle:0,throttle:0,mana:0,totalMana:0,landmarksVisited:0,health:100,maxHealth:100,maxSpeed:210,accelerationValue:400,speedMultiplier:1,rotationSpeed:3,spells:[],altitude:350,altitudeVelocity:0,currentSpell:0,visitedLandmarks:new Set};this.players.set(e,t),this.localPlayer=t,y.info(`Local player created with ID: ${e}`)}createNetworkPlayer(e){if(this.players.has(e.id))return;const t={id:e.id,isLocal:!1,position:new A(e.x||0,e.y||150,e.z||0),rotation:new ut(e.rotationX||0,e.rotationY||0,e.rotationZ||0,"YXZ"),velocity:new A(0,0,0),bankAngle:e.bankAngle||0,mana:0,totalMana:0,landmarksVisited:0,health:100,maxHealth:100,visitedLandmarks:new Set};this.players.set(e.id,t),y.info(`Network player created with ID: ${e.id}`)}removePlayer(e){const t=this.players.get(e);t&&(t.model&&t.model.parent&&t.model.parent.remove(t.model),this.players.delete(e),this.localPlayer&&this.localPlayer.id===e&&(this.localPlayer=null),y.info(`Player removed with ID: ${e}`))}updateNetworkPlayer(e){let t=this.players.get(e.id);if(t||(this.createNetworkPlayer(e),t=this.players.get(e.id)),!(!t||t.isLocal)){if(e.x!==void 0&&e.y!==void 0&&e.z!==void 0){const s=new A(e.x,e.y,e.z);t.velocity.copy(s).sub(t.position),t.position.lerp(s,.35)}e.rotationX!==void 0&&(t.rotation.x=K.lerp(t.rotation.x,e.rotationX,.35)),e.rotationY!==void 0&&(t.rotation.y=K.lerp(t.rotation.y,e.rotationY,.35)),e.rotationZ!==void 0&&(t.rotation.z=K.lerp(t.rotation.z,e.rotationZ,.35)),e.bankAngle!==void 0&&(t.bankAngle=K.lerp(t.bankAngle||0,e.bankAngle,.35)),e.mana!==void 0&&(t.mana=e.mana),e.health!==void 0&&(t.health=e.health),e.speed!==void 0&&(t.speed=e.speed)}}getPlayer(e){return this.players.get(e)}updatePlayer(e,t){const s=this.players.get(e);s&&Object.assign(s,t)}}const Cs=h=>{let e;const t=new Set,s=(l,c)=>{const d=typeof l=="function"?l(e):l;if(!Object.is(d,e)){const u=e;e=c??(typeof d!="object"||d===null)?d:Object.assign({},e,d),t.forEach(m=>m(e,u))}},i=()=>e,a={setState:s,getState:i,getInitialState:()=>r,subscribe:l=>(t.add(l),()=>t.delete(l))},r=e=h(s,i,a);return a},Jo=h=>h?Cs(h):Cs,G={LOADING:"LOADING",INTRO:"INTRO",PLAYING:"PLAYING",PAUSED:"PAUSED"},ea={[G.LOADING]:[G.INTRO],[G.INTRO]:[G.PLAYING],[G.PLAYING]:[G.PAUSED],[G.PAUSED]:[G.PLAYING]},et=Jo((h,e)=>({currentState:G.LOADING,previousState:null,stateEnteredAt:Date.now(),stateMetadata:{},setGameState:(t,s={})=>{const i=e().currentState;return ea[i]?.includes(t)?(console.log(`Game State changing from ${i} to: ${t}`),h({currentState:t,previousState:i,stateEnteredAt:Date.now(),stateMetadata:s}),!0):(console.warn(`Invalid transition from ${i} to ${t}`),!1)},pauseGame:(t="user_paused")=>{e().currentState===G.PLAYING&&e().setGameState(G.PAUSED,{reason:t})},resumeGame:()=>{e().currentState===G.PAUSED&&e().setGameState(G.PLAYING)},forceGameState:(t,s={})=>{const i=e().currentState;return console.log(`Forcing game state from ${i} to: ${t}`),h({currentState:t,previousState:i,stateEnteredAt:Date.now(),stateMetadata:{...s,forced:!0}}),!0}})),le={getState:()=>et.getState(),setState:et.setState,subscribe:et.subscribe,destroy:et.destroy};class ta extends U{constructor(e){super(e,"playerInput"),this.requireDependencies(["playerState"]),this.playerState=e.systems.get("playerState"),this.input=e.input,this.mouseSensitivity=.0015,this.throttleSpeed=1,this.bankingSensitivity=.3,this.rotationDamping=.92,this.turnRate=1.6,this.maxBankAngle=Math.PI/6,this.bankEaseRate=8,this.currentThrottle=0,this.unsubscribeState=null,this.motionControlsEnabled=!1,this.motionSensitivity={pitch:.04,yaw:.06},this.motionResponseCurve={deadzone:2,maxResponse:15},this.isMobile=this.input.isTouchDevice,this.mobileAutoForward=!0,this.touchAltitude={up:!1,down:!1},this.mobileControlElements=[],this.joystick=null,this.virtualPad={enabled:!1,throttle:0,brake:0,turn:0,climb:0},this.inputSourcesThisFrame={keyboard:!1,virtual:!1}}async _initialize(){this.setupInput(),this.isMobile&&this.setupTouchControls(),y.info("PlayerInputSystem initialized")}setupInput(){this.unsubscribeState=le.subscribe(e=>{const t=e.currentState===G.PLAYING;this.setControlsActive(t)}),this.input.on("mousemove",e=>{if(this.input.pointerLocked){const t=this.playerState.localPlayer;if(!t)return;const s=this.input.mouse.dx*this.mouseSensitivity,i=this.input.mouse.dy*this.mouseSensitivity;t.rotation.y-=s;const n=t.rotation.x-i;t.rotation.x=K.clamp(n,-Math.PI/4,Math.PI/4);const o=-s*5;t.bankAngle=K.lerp(t.bankAngle||0,o,.1)}}),this.input.on("keydown",e=>{["Space","KeyW","KeyS","KeyA","KeyD"].includes(e.code)&&e.preventDefault()})}_update(e){this.inputSourcesThisFrame.keyboard=this.input.isKeyDown("KeyW")||this.input.isKeyDown("KeyS")||this.input.isKeyDown("ShiftLeft")||this.input.isKeyDown("ShiftRight")||this.input.isKeyDown("KeyA")||this.input.isKeyDown("KeyD")||this.input.isKeyDown("Space")||this.input.isKeyDown("ControlLeft")||this.input.isKeyDown("ControlRight"),this.inputSourcesThisFrame.virtual=this.virtualPad.enabled&&(this.virtualPad.throttle>.05||this.virtualPad.brake>.05||Math.abs(this.virtualPad.turn)>.05||Math.abs(this.virtualPad.climb)>.05);const t=this.playerState.localPlayer;if(!t)return;let s=0;if(this.input.isKeyDown("KeyA")&&(s-=1),this.input.isKeyDown("KeyD")&&(s+=1),this.joystick&&this.joystick.active&&Math.abs(this.joystick.position.x)>.1&&(s=K.clamp(s+this.joystick.position.x,-1,1)),this.virtualPad.enabled&&this.virtualPad.turn!==0&&(s=K.clamp(s+this.virtualPad.turn,-1,1)),s!==0){t.rotation.y-=s*this.turnRate*e;const f=1-Math.exp(-this.bankEaseRate*e);t.bankAngle=K.lerp(t.bankAngle||0,s*this.maxBankAngle,f)}else t.bankAngle=(t.bankAngle||0)*Math.pow(this.rotationDamping,e*60);if(this.joystick&&this.joystick.active&&Math.abs(this.joystick.position.y)>.1){t.altitudeVelocity+=-this.joystick.position.y*90*e;const f=this.joystick.position.y*.5;t.rotation.x=K.lerp(t.rotation.x,f,1-Math.exp(-6*e)),this.engine.systems.carpetTrail&&this.joystick.position.y<-.3?this.engine.systems.carpetTrail.setSpaceBarState(!0):this.engine.systems.carpetTrail&&this.engine.systems.carpetTrail.setSpaceBarState(!1)}const i=this.input.isKeyDown("KeyW"),n=this.input.isKeyDown("ShiftLeft")||this.input.isKeyDown("ShiftRight"),o=this.virtualPad.enabled&&this.virtualPad.throttle>.05,a=this.virtualPad.enabled&&this.virtualPad.brake>.6,r=i||o,l=this.input.isKeyDown("KeyS")||n||this.virtualPad.enabled&&this.virtualPad.brake>.05;if(r&&!l){const f=i?1:this.virtualPad.throttle;this.currentThrottle<=f?this.currentThrottle=Math.min(f,this.currentThrottle+this.throttleSpeed*e):this.currentThrottle=Math.max(f,this.currentThrottle-this.throttleSpeed*.3*e)}else if(l){const f=n||a?3:1.5;this.currentThrottle=Math.max(0,this.currentThrottle-this.throttleSpeed*f*e)}else this.currentThrottle=Math.max(0,this.currentThrottle-this.throttleSpeed*.3*e);this.isMobile&&this.mobileAutoForward&&!l&&this.currentThrottle<.5&&(this.currentThrottle=.5),t.acceleration=t.acceleration||new A(0,0,0);const c=this.currentThrottle*t.accelerationValue*(t.speedMultiplier||1),d=new A(0,0,1).applyEuler(t.rotation).multiplyScalar(c);t.acceleration.add(d);let u=0,m=this.input.isKeyDown("Space");if(m&&(u+=1),(this.input.isKeyDown("ControlLeft")||this.input.isKeyDown("ControlRight"))&&(u-=1),this.touchAltitude.up&&(u+=1),this.touchAltitude.down&&(u-=1),this.virtualPad.enabled&&this.virtualPad.climb!==0&&(u=K.clamp(u+this.virtualPad.climb,-1,1)),this.engine.systems.carpetTrail){const f=this.virtualPad.enabled&&this.virtualPad.climb>.3;this.engine.systems.carpetTrail.setSpaceBarState(m||this.touchAltitude.up||f)}if(u!==0&&(t.altitudeVelocity+=90*u*e),u===0&&(!this.joystick||!this.joystick.active||Math.abs(this.joystick.position.y)<=.1)&&(t.altitudeVelocity-=5*e),this.motionControlsEnabled&&this.input.deviceMotionEnabled&&this.input.initialOrientation){const f=this.input.fusedOrientation;let g=0;if(Math.abs(f.beta)>this.motionResponseCurve.deadzone){const x=Math.sign(f.beta)*(Math.abs(f.beta)-this.motionResponseCurve.deadzone);g=Math.sign(x)*Math.min(1,Math.pow(Math.abs(x)/this.motionResponseCurve.maxResponse,2)),t.altitudeVelocity+=g*40*e}let p=0;if(Math.abs(f.gamma)>this.motionResponseCurve.deadzone){const x=Math.sign(f.gamma)*(Math.abs(f.gamma)-this.motionResponseCurve.deadzone);p=Math.sign(x)*Math.min(1,Math.pow(Math.abs(x)/this.motionResponseCurve.maxResponse,2)),t.rotation.y-=p*this.motionSensitivity.yaw*120*e;const w=-p*.5;t.bankAngle=K.lerp(t.bankAngle||0,w,1-Math.exp(-10*e))}const b=t.accelerationValue*.5*(t.speedMultiplier||1),S=new A(0,0,1).applyEuler(t.rotation).multiplyScalar(b);t.acceleration.add(S)}}setVirtualPad(e){const t={throttle:[0,1],brake:[0,1],turn:[-1,1],climb:[-1,1]};for(const s in t)if(e&&Object.prototype.hasOwnProperty.call(e,s)){const i=Number(e[s]);this.virtualPad[s]=Number.isFinite(i)?K.clamp(i,t[s][0],t[s][1]):0}return this.virtualPad.enabled=!0,this.virtualPad}clearVirtualPad(){return this.virtualPad.enabled=!1,this.virtualPad.throttle=0,this.virtualPad.brake=0,this.virtualPad.turn=0,this.virtualPad.climb=0,this.virtualPad}setControlsActive(e){e?this.isMobile&&this.showMobileControls():this.isMobile&&this.mobileControlElements&&this.hideMobileControls()}setupTouchControls(){y.debug("Setting up touch controls UI elements");const e=document.createElement("div");e.style.position="fixed",e.style.bottom="calc(var(--vc-safe-bottom, 20px) + 12px)",e.style.right="max(5%, var(--vc-safe-right, 14px))",e.style.width="20vmin",e.style.height="20vmin",e.style.borderRadius="50%",e.style.background="rgba(255, 255, 255, 0.2)",e.style.border="2px solid rgba(255, 255, 255, 0.4)",e.style.zIndex="1000",e.style.display="none",document.body.appendChild(e),this.mobileControlElements.push(e);const t=document.createElement("div");t.style.position="absolute",t.style.top="33%",t.style.left="33%",t.style.width="33%",t.style.height="33%",t.style.borderRadius="50%",t.style.background="rgba(255, 255, 255, 0.8)",t.style.boxShadow="0 0 10px rgba(0, 0, 0, 0.5)",e.appendChild(t),this.joystick={active:!1,position:{x:0,y:0},startPosition:{x:0,y:0},container:{rect:e.getBoundingClientRect(),radius:75}},this.setupJoystickEvents(e,t),window.addEventListener("resize",()=>{this.joystick.container.rect=e.getBoundingClientRect()})}setupJoystickEvents(e,t){let s=null;const i=l=>{if(s!==null)return;const c=e.getBoundingClientRect();for(let d=0;d=c.left&&u.clientX<=c.right&&u.clientY>=c.top&&u.clientY<=c.bottom){l.preventDefault(),s=u.identifier,this.joystick.active=!0,a(u,t);break}}},n=l=>{if(this.joystick.active){for(let c=0;c{for(let c=0;c{const d=e.getBoundingClientRect(),u=d.width/2||1,m=d.left+d.width/2,f=d.top+d.height/2;let g=l.clientX-m,p=l.clientY-f;const b=Math.sqrt(g*g+p*p);b>u&&(g*=u/b,p*=u/b),c.style.left=`calc(33% + ${g}px)`,c.style.top=`calc(33% + ${p}px)`,this.joystick.position.x=g/u,this.joystick.position.y=p/u},r=l=>{s=null,this.joystick.active=!1,this.joystick.position.x=0,this.joystick.position.y=0,l.style.left="33%",l.style.top="33%"};document.body.addEventListener("touchstart",i,{passive:!1}),document.body.addEventListener("touchmove",n,{passive:!1}),document.body.addEventListener("touchend",o,{passive:!1}),document.body.addEventListener("touchcancel",o,{passive:!1})}showMobileControls(){y.info("Showing mobile controls"),this.mobileControlElements.forEach(e=>{e.style.display="block"}),this.updateJoystickContainerRect()}hideMobileControls(){y.info("Hiding mobile controls"),this.mobileControlElements.forEach(e=>{e.style.display="none"})}updateJoystickContainerRect(){this.joystick&&(this.joystick.container.rect=this.mobileControlElements[0].getBoundingClientRect())}toggleMotionControls(e){return this.motionControlsEnabled=e,this.input.setDeviceMotionEnabled(e),e&&this.joystick&&(this.joystick.active=!1,this.joystick.position.x=0,this.joystick.position.y=0),this.motionControlsEnabled}destroy(){this.unsubscribeState&&this.unsubscribeState(),this.mobileControlElements.forEach(e=>{document.body.removeChild(e)})}}class sa extends U{constructor(e){super(e,"playerCamera"),this.requireDependencies(["playerState"])}_initialize(){y.info("PlayerCameraSystem initialized")}_update(e){const t=this.engine.systemManager.get("playerState");if(!t)return;const s=t.localPlayer;if(!s)return;const i=this.engine.input.isTouchDevice;let n,o;i?(n=new A(0,12,-20),o=new A(0,3,30)):(n=new A(0,10,-25),o=new A(0,5,25));const a=new Yt;a.setFromEuler(new ut(s.rotation.x,s.rotation.y,0,"YXZ"));const r=n.clone().applyQuaternion(a),l=o.clone().applyQuaternion(a),c=s.position.clone().add(r),d=this.engine.systemManager.get("world").getTerrainHeight(c.x,c.z),u=2;c.y.01&&(m.fov=g,m.updateProjectionMatrix());const p=(s.bankAngle||0)*.3;m.up.set(-Math.sin(p),Math.cos(p),0).applyQuaternion(a);const b=s.position.clone().add(l);m.lookAt(b)}}let Et=!1;const de={font:"'Sora', 'Outfit', 'Segoe UI', system-ui, sans-serif",panel:"rgba(13, 18, 38, 0.55)",panelSolid:"rgba(13, 18, 38, 0.92)",border:"rgba(255, 255, 255, 0.10)",ink:"#f2f5ff",inkDim:"rgba(242, 245, 255, 0.62)",gold:"#ffcc66",cyan:"#66ffee",magenta:"#ff66cc",radius:"12px"};function Qe(){if(Et||document.getElementById("vc-theme")){Et=!0;return}Et=!0;const h=document.createElement("link");h.rel="stylesheet",h.href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600;800&display=swap",document.head.appendChild(h);const e=document.createElement("style");e.id="vc-theme",e.textContent=` - :root { - --vc-font: ${de.font}; - --vc-panel: ${de.panel}; - --vc-panel-solid: ${de.panelSolid}; - --vc-border: ${de.border}; - --vc-ink: ${de.ink}; - --vc-ink-dim: ${de.inkDim}; - --vc-gold: ${de.gold}; - --vc-cyan: ${de.cyan}; - --vc-magenta: ${de.magenta}; - --vc-radius: ${de.radius}; - --vc-safe-x: max(14px, env(safe-area-inset-left)); - --vc-safe-y: max(14px, env(safe-area-inset-top)); - --vc-safe-right: max(14px, env(safe-area-inset-right)); - --vc-safe-bottom: max(20px, env(safe-area-inset-bottom)); - --vc-dev-hud-offset: 0px; - --vc-minimap-size: 150px; - --vc-left-stack-top: calc(var(--vc-safe-y) + var(--vc-dev-hud-offset)); - --vc-left-stack-after-minimap: calc(var(--vc-left-stack-top) + var(--vc-minimap-size) + 16px); - } - .vc-panel { - background: var(--vc-panel); - border: 1px solid var(--vc-border); - border-radius: var(--vc-radius); - color: var(--vc-ink); - font-family: var(--vc-font); - } - @supports (backdrop-filter: blur(10px)) { - .vc-panel { backdrop-filter: blur(10px); } - } - .vc-chip { - display: inline-flex; align-items: center; gap: 6px; - padding: 6px 12px; border-radius: 999px; - background: var(--vc-panel); border: 1px solid var(--vc-border); - color: var(--vc-ink); font-family: var(--vc-font); font-size: 13px; - } - .vc-label { - font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; - color: var(--vc-ink-dim); font-family: var(--vc-font); - } - .vc-num { font-variant-numeric: tabular-nums; } - .vc-btn-primary { - font-family: var(--vc-font); font-weight: 600; color: #1a1303; - background: linear-gradient(180deg, #ffd98a, var(--vc-gold)); - border: none; border-radius: 999px; cursor: pointer; - padding: 16px 44px; font-size: 19px; letter-spacing: 0.04em; - box-shadow: 0 0 24px rgba(255, 204, 102, 0.35); - transition: transform .2s ease, box-shadow .2s ease; - } - .vc-btn-primary:hover { transform: scale(1.04); box-shadow: 0 0 36px rgba(255, 204, 102, 0.55); } - .vc-btn-ghost { - font-family: var(--vc-font); color: var(--vc-ink); - background: transparent; border: 1px solid var(--vc-border); - border-radius: 999px; cursor: pointer; padding: 9px 18px; font-size: 14px; - transition: border-color .2s ease, background .2s ease; - } - .vc-btn-ghost:hover { border-color: var(--vc-gold); background: rgba(255, 204, 102, 0.08); } - .vc-tabbar { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 4px; - padding: 4px; - margin-bottom: 12px; - border: 1px solid var(--vc-border); - border-radius: 999px; - background: rgba(255, 255, 255, 0.05); - } - .vc-tab { - min-width: 0; - min-height: 30px; - border: 1px solid transparent; - border-radius: 999px; - background: transparent; - color: var(--vc-ink-dim); - font-family: var(--vc-font); - font-size: 11px; - font-weight: 600; - letter-spacing: 0.06em; - text-transform: uppercase; - cursor: pointer; - } - .vc-tab[aria-selected="true"] { - border-color: rgba(255, 204, 102, 0.35); - background: rgba(255, 204, 102, 0.16); - color: var(--vc-ink); - } - .vc-toast-stack { - position: fixed; - top: calc(var(--vc-safe-y) + 10px); - left: 50%; - transform: translateX(-50%); - width: min(420px, calc(100vw - 32px)); - display: flex; - flex-direction: column; - align-items: stretch; - gap: 8px; - pointer-events: none; - z-index: 1100; - } - .vc-toast { - box-sizing: border-box; - width: 100%; - background: rgba(20, 30, 60, 0.82); - color: #fff; - padding: 8px 14px; - border-radius: 10px; - border-left: 3px solid var(--vc-cyan); - font-family: var(--vc-font); - font-size: 14px; - line-height: 1.35; - box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2); - } - /* Gameplay HUD is revealed only once the player presses Play. body.vc-playing - is toggled from the game state in Engine.js, so the title screen stays clean - (this matters most on phones, where the minimap + controls otherwise cover - the menu). !important overrides the inline display set by the HUD systems. */ - body:not(.vc-playing) #minimap-container, - body:not(.vc-playing) #mobile-ui-container, - body:not(.vc-playing) #settings-menu-toggle { display: none !important; } - @media (max-width: 640px) { - :root { - --vc-minimap-size: 108px; - } - /* The minimap reads as clutter and is hard to use on a phone — hide it. */ - #minimap-container { display: none !important; } - /* Make the in-game settings menu readable + thumb-friendly on a phone: a - centred, wide, large-type modal with chunky sliders and 44px tap targets. - !important overrides the panel's inline sizing/positioning. */ - #settings-menu-panel { - top: 50% !important; - bottom: auto !important; - left: 50% !important; - right: auto !important; - transform: translate(-50%, -50%) !important; - width: min(440px, calc(100vw - 20px)) !important; - max-height: 82vh !important; - padding: 18px 20px !important; - border-radius: 16px !important; - font-size: 16px !important; - } - #settings-menu-panel .vc-label { font-size: 14px !important; } - #settings-menu-panel .vc-num { font-size: 17px !important; } - #settings-menu-panel .vc-tabbar { gap: 6px !important; margin-bottom: 16px !important; } - #settings-menu-panel .vc-tab { font-size: 14px !important; min-height: 46px !important; } - #settings-menu-panel .vc-btn-ghost { - font-size: 14px !important; - padding: 12px 16px !important; - min-height: 44px !important; - } - #settings-menu-panel input[type="range"] { - -webkit-appearance: none; - appearance: none; - width: 100%; - background: transparent; - margin: 18px 0 !important; - } - #settings-menu-panel input[type="range"]::-webkit-slider-runnable-track { - height: 10px; - border-radius: 5px; - background: rgba(255, 255, 255, 0.2); - } - #settings-menu-panel input[type="range"]::-webkit-slider-thumb { - -webkit-appearance: none; - appearance: none; - margin-top: -9px; - width: 28px; - height: 28px; - border-radius: 50%; - background: var(--vc-gold); - border: 2px solid #1a1303; - box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4); - } - .vc-toast-stack { - top: auto; - bottom: max(92px, calc(env(safe-area-inset-bottom) + 18px)); - width: min(340px, calc(100vw - 28px)); - } - } - `,document.head.appendChild(e)}const Es=()=>{try{return localStorage.getItem("vc.debug")==="1"}catch{return!1}};class Ye extends U{constructor(e){super(e,"ui"),this.container=document.getElementById("ui-container"),this.elements={},this.unsubscribeState=null,this.canvas=null,this.context=null,this.size=150,this.baseRange=1e4,this.range=1e4,this.zoomLevel=1,this.minZoom=.25,this.maxZoom=2.5,this.minimapContainer=null,this.lastUpdate=0,this.updateInterval=1/60,this.highlightedNodes=new Set,this.highlightEndTime=0,this.terrainColorCache=new Map,this.cacheMaxSize=1e3,this.colors={ocean:"#1e3a8a",beach:"#f4a460",plains:"#90ee90",forest:"#228b22",hills:"#8b4513",mountains:"#696969",snow:"#ffffff",player:"#ffffff",otherPlayer:"#ff0000",landmark:"#ffff00",mana:"#00ff00",compassN:"#ffffff",compassE:"#ffffff",compassS:"#ffffff",compassW:"#ffffff",background:"rgba(0, 0, 0, 0.8)",border:"#ffffff"},this.fogStatusElement=null,this._questKeyHandler=t=>{t.code==="KeyQ"&&!t.repeat&&this.engine.gameStarted&&this.showQuestLog()},window.addEventListener("keydown",this._questKeyHandler)}async _initialize(){Qe(),this.createBaseUI(),this.createManaDisplay(),this.createMinimapContainer(),this.createSettingsMenu(),this.createFlightSettings(),this.createTimeControls(),this.unsubscribeState=le.subscribe(this.handleStateChange.bind(this)),this.startFogStatusUpdates(),y.info("UI system initialized"),this.minimapInitialized=!0}createFogStatus(){Es()&&(this.fogStatusElement=document.createElement("div"),this.fogStatusElement.style.position="absolute",this.fogStatusElement.style.top="10px",this.fogStatusElement.style.right="10px",this.fogStatusElement.style.backgroundColor="rgba(0, 0, 0, 0.7)",this.fogStatusElement.style.color="white",this.fogStatusElement.style.padding="5px 10px",this.fogStatusElement.style.borderRadius="5px",this.fogStatusElement.style.fontSize="12px",this.fogStatusElement.style.fontFamily="monospace",this.fogStatusElement.style.zIndex="1000",this.fogStatusElement.textContent="Fog: Initializing...",this.container.appendChild(this.fogStatusElement))}startFogStatusUpdates(){Es()&&(this.fogStatusInterval=setInterval(()=>{this.updateFogStatus()},2e3))}updateFogStatus(){if(!this.fogStatusElement)return;const e=this.engine.systems.skybox;if(e&&this.engine.scene&&this.engine.scene.fog){const t=this.engine.scene.fog.color.getHexString(),s=this.engine.scene.fog.density.toFixed(6),i=e.timeOfDay.toFixed(2);this.fogStatusElement.textContent=`Fog: #${t} | ${s} | T:${i}`,this.fogStatusElement.style.display="block"}else this.fogStatusElement.textContent="Fog: Not available"}handleStateChange(e){switch(e.currentState){case G.LOADING:this.minimapContainer&&(this.minimapContainer.style.display="none"),this.setSettingsVisible(!1);break;case G.INTRO:this.minimapContainer&&(this.minimapContainer.style.display="none"),this.setSettingsVisible(!1);break;case G.PLAYING:this.showGameUI(),this.minimapContainer&&(this.minimapContainer.style.display="block");break;case G.PAUSED:this.showPauseMenu(),this.minimapContainer&&(this.minimapContainer.style.display="none"),this.setSettingsVisible(!1);break}}createBaseUI(){this.container.style.position="absolute",this.container.style.top="0",this.container.style.left="0",this.createFogStatus(),this.container.style.width="100%",this.container.style.height="100%",this.container.style.pointerEvents="none",this.container.style.display="flex",this.container.style.flexDirection="column",this.container.style.fontFamily="var(--vc-font)",this.container.style.color="white"}createManaDisplay(){const e=document.createElement("div");e.className="vc-chip",e.style.position="absolute",e.style.top="var(--vc-safe-y)",e.style.right="var(--vc-safe-right)",e.style.zIndex="1001";const t=document.createElement("div");t.style.width="8px",t.style.height="8px",t.style.borderRadius="50%",t.style.background="var(--vc-cyan)",t.style.boxShadow="0 0 6px var(--vc-cyan)";const s=document.createElement("div");s.className="vc-num",s.textContent="0",s.style.fontSize="15px",s.style.fontWeight="600",s.style.transition="transform 0.2s ease",e.appendChild(t),e.appendChild(s),this.container.appendChild(e),this.elements.manaText=s}createSettingsMenu(){const e=document.createElement("button");e.id="settings-menu-toggle",e.className="vc-chip",e.type="button",e.textContent="Menu",e.title="Race, speed, and time controls",e.style.position="absolute",e.style.top="calc(var(--vc-safe-y) + 38px)",e.style.right="var(--vc-safe-right)",e.style.display="none",e.style.pointerEvents="auto",e.style.cursor="pointer",e.style.fontSize="13px",e.style.padding="10px 18px",e.style.minHeight="40px",e.style.letterSpacing="0.08em",e.style.textTransform="uppercase",e.style.color="var(--vc-ink-dim)",e.style.zIndex="1001";const t=document.createElement("div");t.id="settings-menu-panel",t.className="vc-panel",t.style.position="absolute",t.style.top="calc(var(--vc-safe-y) + 76px)",t.style.right="var(--vc-safe-right)",t.style.width="min(320px, calc(100vw - 28px))",t.style.maxHeight="calc(100vh - var(--vc-safe-y) - 96px)",t.style.overflowY="auto",t.style.padding="12px 14px",t.style.display="none",t.style.pointerEvents="auto",t.style.zIndex="1001";const s=document.createElement("div");s.style.display="flex",s.style.justifyContent="space-between",s.style.alignItems="center",s.style.gap="10px",s.style.marginBottom="10px";const i=document.createElement("div");i.className="vc-label",i.textContent="Settings";const n=document.createElement("button");n.type="button",n.className="vc-btn-ghost",n.textContent="Close",n.style.padding="5px 10px",n.style.fontSize="11px",n.addEventListener("click",()=>this.closeSettingsMenu()),s.appendChild(i),s.appendChild(n),t.appendChild(s);const o=document.createElement("div");o.className="vc-tabbar";const a={},r={},l=[["race","Race"],["speed","Speed"],["time","Time"]];l.forEach(([c,d])=>{const u=document.createElement("button");u.type="button",u.className="vc-tab",u.textContent=d,u.setAttribute("aria-selected",c==="race"?"true":"false"),u.addEventListener("click",()=>this.showSettingsPane(c)),r[c]=u,o.appendChild(u);const m=document.createElement("div");m.dataset.settingsPane=c,m.style.display=c==="race"?"block":"none",a[c]=m}),t.appendChild(o),l.forEach(([c])=>t.appendChild(a[c])),e.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),t.style.display==="none"?this.openSettingsMenu():this.closeSettingsMenu()}),this.container.appendChild(e),this.container.appendChild(t),this.elements.settingsToggle=e,this.elements.settingsPanel=t,this.elements.settingsTabs=r,this.elements.settingsPanes=a}setSettingsVisible(e){this.elements.settingsToggle&&(this.elements.settingsToggle.style.display=e?"inline-flex":"none"),e||this.closeSettingsMenu()}openSettingsMenu(e=null){e&&this.showSettingsPane(e),this.elements.settingsPanel&&(this.elements.settingsPanel.style.display="block")}closeSettingsMenu(){this.elements.settingsPanel&&(this.elements.settingsPanel.style.display="none")}showSettingsPane(e){const t=this.elements.settingsPanes||{},s=this.elements.settingsTabs||{};Object.keys(t).forEach(i=>{t[i].style.display=i===e?"block":"none",s[i]&&s[i].setAttribute("aria-selected",i===e?"true":"false")})}registerSettingsPane(e,t){const s=this.elements.settingsPanes&&this.elements.settingsPanes[e];return!s||!t?!1:(s.replaceChildren(t),!0)}static FLIGHT_DEFAULTS={cruise:210,rush:420,punch:400};loadFlightSettings(){try{const e=localStorage.getItem("vc.flight");if(e)return{...Ye.FLIGHT_DEFAULTS,...JSON.parse(e)}}catch{}return{...Ye.FLIGHT_DEFAULTS}}applyFlightSettings(e){const t=this.engine.systems.get("playerState")?.localPlayer,s=this.engine.systems.get("playerPhysics");t&&(t.maxSpeed=e.cruise,t.accelerationValue=e.punch),s&&(s.absoluteMaxSpeed=e.rush);try{localStorage.setItem("vc.flight",JSON.stringify(e))}catch{}}createFlightSettings(){const e=this.loadFlightSettings();this.applyFlightSettings(e);const t=document.createElement("div");t.style.display="block";const s=document.createElement("div");s.className="vc-label",s.textContent="Flight feel",s.style.marginBottom="10px",t.appendChild(s);const i=[{key:"cruise",label:"Cruise speed",min:100,max:250,hint:"top speed in level flight"},{key:"rush",label:"Rush ceiling",min:240,max:520,hint:"dive/boost hard limit"},{key:"punch",label:"Throttle punch",min:150,max:500,hint:"how hard W accelerates"}],n={};i.forEach(a=>{const r=document.createElement("div");r.style.marginBottom="10px";const l=document.createElement("div");l.style.display="flex",l.style.justifyContent="space-between",l.style.marginBottom="3px";const c=document.createElement("span");c.className="vc-label",c.textContent=a.label,c.title=a.hint;const d=document.createElement("span");d.className="vc-num",d.style.fontSize="12px",d.style.color="var(--vc-gold)",d.textContent=e[a.key],n[a.key]=d,l.appendChild(c),l.appendChild(d),r.appendChild(l);const u=document.createElement("input");u.type="range",u.min=a.min,u.max=a.max,u.step=5,u.value=e[a.key],u.style.width="100%",u.style.accentColor="var(--vc-gold)",u.style.cursor="pointer",u.addEventListener("input",()=>{if(e[a.key]=Number(u.value),a.key==="cruise"&&e.rush{Object.assign(e,Ye.FLIGHT_DEFAULTS),i.forEach(a=>{n[a.key].textContent=e[a.key];const r=t.querySelector(`input[data-key="${a.key}"]`);r&&(r.value=e[a.key])}),this.applyFlightSettings(e)}),t.appendChild(o),this.registerSettingsPane("speed",t),this.elements.flightPanel=t}createHealthDisplay(){const e=document.createElement("div");e.style.position="absolute",e.style.bottom="20px",e.style.left="50%",e.style.transform="translateX(-50%)",e.style.width="200px",e.style.padding="5px",e.style.background="rgba(0, 0, 30, 0.7)",e.style.borderRadius="5px",e.style.boxShadow="0 0 10px rgba(255, 0, 100, 0.5)";const t=document.createElement("div");t.style.height="10px",t.style.width="100%",t.style.background="linear-gradient(90deg, #ff0066, #ff6699)",t.style.borderRadius="3px",t.style.boxShadow="inset 0 0 5px rgba(0, 0, 0, 0.5)",e.appendChild(t),this.container.appendChild(e),this.elements.healthBar=t}createSpellsUI(){const e=document.createElement("div");e.style.position="absolute",e.style.bottom="20px",e.style.right="20px",e.style.display="flex",e.style.gap="10px",e.style.pointerEvents="auto";const t=[{name:"Fireball",color:"#ff3300",key:"1"},{name:"Lightning",color:"#33ccff",key:"2"},{name:"Shield",color:"#ffcc00",key:"3"}];this.elements.spellSlots=[],t.forEach((s,i)=>{const n=document.createElement("div");n.style.width="50px",n.style.height="50px",n.style.borderRadius="5px",n.style.background="rgba(0, 0, 30, 0.7)",n.style.display="flex",n.style.flexDirection="column",n.style.justifyContent="center",n.style.alignItems="center",n.style.cursor="pointer",n.style.transition="all 0.2s",n.style.boxShadow=`0 0 10px ${s.color}80`;const o=document.createElement("div");o.style.width="30px",o.style.height="30px",o.style.borderRadius="50%",o.style.background=s.color,o.style.boxShadow=`0 0 5px ${s.color}`;const a=document.createElement("div");a.textContent=s.key,a.style.fontSize="12px",a.style.marginTop="5px",n.appendChild(o),n.appendChild(a),e.appendChild(n),n.addEventListener("mouseover",()=>{n.style.transform="scale(1.1)"}),n.addEventListener("mouseout",()=>{n.style.transform="scale(1)"}),n.addEventListener("click",()=>{this.selectSpell(i)}),this.elements.spellSlots.push({element:n,indicator:o,data:s})}),this.container.appendChild(e),window.addEventListener("keydown",s=>{if(s.key>="1"&&s.key<="3"){const i=parseInt(s.key)-1;this.selectSpell(i)}})}createMinimapContainer(){const e=document.getElementById("minimap-container");e&&e.remove(),this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.canvas.width=this.size,this.canvas.height=this.size,this.canvas.style.borderRadius="50%",this.canvas.style.display="block",this.canvas.style.width="100%",this.canvas.style.height="100%",this.minimapContainer=document.createElement("div"),this.minimapContainer.id="minimap-container",this.minimapContainer.style.position="absolute",this.minimapContainer.style.top="var(--vc-left-stack-top)",this.minimapContainer.style.left="var(--vc-safe-x)",this.minimapContainer.style.width="var(--vc-minimap-size)",this.minimapContainer.style.height="var(--vc-minimap-size)",this.minimapContainer.style.border="2px solid "+this.colors.border,this.minimapContainer.style.backgroundColor=this.colors.background,this.minimapContainer.style.borderRadius="50%",this.minimapContainer.style.boxShadow="0 0 20px rgba(255, 255, 255, 0.3)",this.minimapContainer.style.pointerEvents="none",this.minimapContainer.style.zIndex="1000",this.minimapContainer.appendChild(this.canvas);const t=document.createElement("div");t.style.position="absolute",t.style.top="5px",t.style.right="5px",t.style.display="flex",t.style.flexDirection="column",t.style.gap="2px",t.style.pointerEvents="auto";const s=document.createElement("button");s.textContent="+",s.style.width="20px",s.style.height="20px",s.style.backgroundColor="rgba(0, 0, 0, 0.7)",s.style.color="#ffffff",s.style.border="1px solid #ffffff",s.style.borderRadius="3px",s.style.cursor="pointer",s.style.fontSize="12px",s.style.fontWeight="bold",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.title="Zoom In",s.addEventListener("click",()=>this.zoomIn());const i=document.createElement("button");i.textContent="−",i.style.width="20px",i.style.height="20px",i.style.backgroundColor="rgba(0, 0, 0, 0.7)",i.style.color="#ffffff",i.style.border="1px solid #ffffff",i.style.borderRadius="3px",i.style.cursor="pointer",i.style.fontSize="12px",i.style.fontWeight="bold",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.title="Zoom Out",i.addEventListener("click",()=>this.zoomOut());const n=document.createElement("button");n.textContent="⌖",n.style.width="20px",n.style.height="20px",n.style.backgroundColor="rgba(0, 0, 0, 0.7)",n.style.color="#ffffff",n.style.border="1px solid #ffffff",n.style.borderRadius="3px",n.style.cursor="pointer",n.style.fontSize="12px",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.title="Reset Zoom",n.addEventListener("click",()=>this.resetZoom());const o=document.createElement("div");o.style.width="20px",o.style.height="16px",o.style.backgroundColor="rgba(0, 0, 0, 0.7)",o.style.color="#ffffff",o.style.border="1px solid #ffffff",o.style.borderRadius="3px",o.style.fontSize="8px",o.style.fontWeight="bold",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.marginTop="2px",o.textContent="1.0x",this.zoomIndicator=o,t.appendChild(s),t.appendChild(i),t.appendChild(n),t.appendChild(o),this.minimapContainer.appendChild(t),this.minimapContainer.addEventListener("wheel",l=>{l.preventDefault(),l.deltaY<0?this.zoomIn():this.zoomOut()});const a=document.createElement("button");a.textContent="?",a.style.position="absolute",a.style.bottom="5px",a.style.right="5px",a.style.width="20px",a.style.height="20px",a.style.backgroundColor="rgba(0, 0, 0, 0.7)",a.style.color="#ffffff",a.style.border="1px solid #ffffff",a.style.borderRadius="3px",a.style.cursor="pointer",a.style.fontSize="12px",a.style.fontWeight="bold",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="center",a.style.pointerEvents="auto",a.title="Minimap Legend",a.style.zIndex="10";const r=document.createElement("div");r.style.position="absolute",r.style.bottom="30px",r.style.right="5px",r.style.backgroundColor="rgba(0, 0, 0, 0.9)",r.style.border="1px solid #ffffff",r.style.borderRadius="5px",r.style.padding="8px",r.style.color="#ffffff",r.style.fontSize="11px",r.style.fontFamily="Arial, sans-serif",r.style.display="none",r.style.pointerEvents="auto",r.style.zIndex="11",r.style.maxWidth="150px",r.innerHTML=` -
Legend
-
-
- You -
-
-
- Mana -
-
-
- Landmark -
-
-
- Other Player -
-
- N/S/E/W: Cardinal directions -
- `,a.addEventListener("click",()=>{r.style.display=r.style.display==="none"?"block":"none"}),document.addEventListener("click",l=>{!a.contains(l.target)&&!r.contains(l.target)&&(r.style.display="none")}),this.minimapContainer.appendChild(a),this.minimapContainer.appendChild(r),this.container.appendChild(this.minimapContainer),y.info("Minimap container with zoom controls created in UISystem")}setTimeSpeed(e){y.debug(`setTimeSpeed called with speed=${e}`);const t=this.engine.systemManager.get("atmosphere");if(t){const s=t.timeScale;t.timeScale=e,y.info(`Time speed changed from ${s}x to ${e}x`),this.elements.speedButtons?(this.elements.speedButtons.forEach(i=>{const n=parseFloat(i.dataset.speed);i.style.backgroundColor=n===e?"rgba(255, 255, 0, 0.9)":"rgba(0, 0, 0, 0.8)"}),y.debug(`Updated ${this.elements.speedButtons.length} speed button styles`)):y.warn("speedButtons not found in elements")}else y.error("AtmosphereSystem not found when setting time speed"),y.debug("Available systems:",Array.from(this.engine.systemManager.systems.keys()))}setTimeOfDay(e){const t=this.engine.systemManager.get("atmosphere");t&&(t.timeOfDay=e,y.info(`Time of day set to ${e}`))}updateTimeDisplay(){const e=this.engine.systemManager.get("atmosphere");if(e&&this.elements.timeDisplay){const t=e.getTimeOfDay(),s=Math.floor(t*24),i=Math.floor(t*24*60%60),n=s>=12?"PM":"AM",o=s===0?12:s>12?s-12:s;this.elements.timeDisplay.textContent=`${o}:${i.toString().padStart(2,"0")} ${n}`}}_worldToMap(e,t){const i=this.engine.systemManager.get("playerState")?.localPlayer;if(!i)return{mapX:this.size/2,mapY:this.size/2};const n=i.position.x,o=i.position.z,a=this.size/2+(e-n)/this.range*this.size,r=this.size/2-(t-o)/this.range*this.size,l=Math.max(0,Math.min(this.size,a)),c=Math.max(0,Math.min(this.size,r));return{mapX:l,mapY:c}}_clear(){this.context.fillStyle=this.colors.background,this.context.fillRect(0,0,this.size,this.size),this.context.beginPath(),this.context.arc(this.size/2,this.size/2,this.size/2-1,0,2*Math.PI),this.context.strokeStyle=this.colors.border,this.context.lineWidth=2,this.context.stroke(),this.context.beginPath(),this.context.arc(this.size/2,this.size/2,this.size/2-2,0,2*Math.PI),this.context.clip()}_getTerrainColor(e,t){return t==="ocean"?this.colors.ocean:t==="beach"?this.colors.beach:t==="plains"?this.colors.plains:t==="forest"?this.colors.forest:t==="hills"?this.colors.hills:t==="mountains"?this.colors.mountains:t==="snow"?this.colors.snow:e<0?this.colors.ocean:e<10?this.colors.beach:e<50?this.colors.plains:e<100?this.colors.forest:e<200?this.colors.hills:e<300?this.colors.mountains:this.colors.snow}_drawTerrain(){const e=this.engine.systemManager.get("world");if(!e)return;const s=this.engine.systemManager.get("playerState")?.localPlayer;if(!s)return;const i=s.position.x,n=s.position.z,a=this.engine?.isMobile||!1?20:30,r=Math.max(.5,this.zoomLevel),l=Math.floor(a*r),c=this.size/l,d=this.context.createImageData(this.size,this.size),u=d.data;for(let m=0;mthis.cacheMaxSize){const T=this.terrainColorCache.keys().next().value;this.terrainColorCache.delete(T)}}const[v,M,_]=this.parseColorString(w),E=Math.ceil(c);for(let P=0;P{const{mapX:o,mapY:a}=this._worldToMap(n.position.x,n.position.z),r=Math.sqrt((o-t)**2+(a-s)**2),c=Math.max(3,5-r*.05);let d=this.colors.landmark;n.type==="ancient_ruins"?d="#DAA520":n.type==="magical_circle"?d="#9932CC":n.type==="crystal_formation"&&(d="#00CED1"),this.context.shadowColor=d,this.context.shadowBlur=8,this.context.beginPath(),this.context.arc(o,a,c+2,0,2*Math.PI),this.context.fillStyle=d+"40",this.context.fill(),this.context.shadowBlur=4,this.context.beginPath(),this.context.arc(o,a,c,0,2*Math.PI),this.context.fillStyle=d,this.context.fill();const u=.3+.2*Math.sin(i*2+r*.1);this.context.shadowBlur=2,this.context.beginPath(),this.context.arc(o,a,c*.6,0,2*Math.PI),this.context.fillStyle=d+Math.floor(u*255).toString(16).padStart(2,"0"),this.context.fill(),r<40&&(this.context.shadowBlur=0,this.context.fillStyle="#FFFFFF",this.context.font="bold 10px Arial",this.context.textAlign="center",this.context.fillText(n.type.replace("_"," "),o,a-c-8)),this.context.shadowBlur=0})}_drawMana(){const e=this.engine.systemManager.get("world");if(!e||!e.manaNodes)return;const t=this.size/2,s=this.size/2,i=Date.now()*.001;e.manaNodes.forEach(n=>{if(n.collected)return;const{mapX:o,mapY:a}=this._worldToMap(n.position.x,n.position.z),r=Math.sqrt((o-t)**2+(a-s)**2),l=`${n.position.x.toFixed(1)}_${n.position.z.toFixed(1)}`,c=this.highlightedNodes.has(l)&&Date.now(){if(n.id===s?.id)return;const{mapX:o,mapY:a}=this._worldToMap(n.position.x,n.position.z);this.context.beginPath(),this.context.arc(o,a,2,0,2*Math.PI),this.context.fillStyle=this.colors.otherPlayer,this.context.fill(),o>10&&o10&&a{const r=e+Math.cos(a.angle)*a.distance,l=t+Math.sin(a.angle)*a.distance;this.context.fillStyle=a.color,this.context.fillText(a.text,r,l)}),this.context.restore(),this.context.beginPath(),this.context.arc(e,t,2,0,2*Math.PI),this.context.fillStyle=this.colors.player,this.context.fill()}selectSpell(e){(this.elements.spellSlots||[]).forEach((s,i)=>{i===e?(s.element.style.transform="scale(1.1)",s.indicator.style.boxShadow=`0 0 10px ${s.data.color}`):(s.element.style.transform="scale(1)",s.indicator.style.boxShadow=`0 0 5px ${s.data.color}`)});const t=this.engine.systemManager.get("playerState");t&&t.localPlayer&&(t.localPlayer.currentSpell=e)}updateManaDisplay(e){this.elements.manaText&&(this.elements.manaText.textContent=e.toString(),this.elements.manaText.style.transform="scale(1.2)",setTimeout(()=>{this.elements.manaText.style.transform="scale(1)"},200))}showMessage(e,t=3500,s="#66ffee"){if(!this.elements.toastStack){const o=document.createElement("div");o.className="vc-toast-stack",document.body.appendChild(o),this.elements.toastStack=o}const i=this.elements.toastStack;for(;i.children.length>=4;)i.removeChild(i.firstChild);const n=document.createElement("div");n.className="vc-toast",n.style.borderLeftColor=s,n.style.opacity="0",n.style.transform="translateY(-8px)",n.style.transition="opacity 0.25s ease, transform 0.25s ease",n.textContent=e,i.appendChild(n),requestAnimationFrame(()=>{n.style.opacity="1",n.style.transform="translateY(0)"}),setTimeout(()=>{n.style.opacity="0",n.style.transform="translateY(-8px)",setTimeout(()=>n.remove(),300)},t)}updateHealthDisplay(e,t){if(this.elements.healthBar){const s=e/t*100;this.elements.healthBar.style.width=`${s}%`,s>60?this.elements.healthBar.style.background="linear-gradient(90deg, #ff0066, #ff6699)":s>30?this.elements.healthBar.style.background="linear-gradient(90deg, #ffcc00, #ff9900)":this.elements.healthBar.style.background="linear-gradient(90deg, #ff3300, #ff6600)"}}setZoomLevel(e){this.zoomLevel=Math.max(this.minZoom,Math.min(this.maxZoom,e)),this.range=this.baseRange/this.zoomLevel,this.zoomIndicator&&(this.zoomIndicator.textContent=`${this.zoomLevel.toFixed(1)}x`),y.info(`Minimap zoom level set to ${this.zoomLevel.toFixed(2)}x, range: ${this.range.toFixed(0)} units`)}zoomIn(){this.setZoomLevel(this.zoomLevel*1.2)}zoomOut(){this.setZoomLevel(this.zoomLevel/1.2)}resetZoom(){this.setZoomLevel(1)}highlightNodes(e,t=10){!e||!Array.isArray(e)||(this.highlightedNodes.clear(),e.forEach(s=>{if(s&&s.position){const i=`${s.position.x.toFixed(1)}_${s.position.z.toFixed(1)}`;this.highlightedNodes.add(i)}}),this.highlightEndTime=Date.now()+t*1e3,y.info(`Highlighting ${this.highlightedNodes.size} mana nodes for ${t} seconds`),setTimeout(()=>{this.highlightedNodes.clear(),this.highlightEndTime=0},t*1e3))}clearHighlights(){this.highlightedNodes.clear(),this.highlightEndTime=0,y.debug("Cleared all minimap highlights")}update(e,t){const s=this.engine.systemManager.get("player");if(s&&s.localPlayer){const n=s.localPlayer;this.updateHealthDisplay(n.health,n.maxHealth)}this.updateTimeDisplay();const i=le.getState().currentState;this.minimapInitialized&&i===G.PLAYING&&(this.lastUpdate+=e,this.lastUpdate>=this.updateInterval&&(this.lastUpdate=0,this._clear(),this._drawTerrain(),this._drawLandmarks(),this._drawMana(),this._drawPlayers(),this._drawCompassRose()))}updateTimeDisplay(){const e=this.engine.systemManager.get("atmosphere");if(!e){y.warn("AtmosphereSystem not found for time display update"),y.debug("Available systems:",Array.from(this.engine.systemManager.systems.keys()));return}if(this.elements.timeDisplay){const t=e.getTimeOfDay(),s=Math.floor(t*24),i=Math.floor(t*24*60%60);this.elements.timeDisplay.textContent=`${s.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`}else y.warn("timeDisplay element not found")}createTimeControls(){const e=document.createElement("div");e.style.color="var(--vc-ink)",e.style.fontFamily="var(--vc-font)",e.style.display="block";const t=document.createElement("div");t.style.fontSize="22px",t.style.textAlign="center",t.style.marginBottom="15px",t.textContent="00:00",e.appendChild(t),this.elements.timeDisplay=t;const s=document.createElement("div");s.textContent="Presets",s.className="vc-label",s.style.textAlign="left",s.style.marginBottom="10px",e.appendChild(s);const i=[{label:"Night",hour:0,minute:0},{label:"Dawn",hour:6,minute:0},{label:"Noon",hour:12,minute:0},{label:"Dusk",hour:18,minute:0}],n=document.createElement("div");n.style.display="grid",n.style.gridTemplateColumns="repeat(4, 1fr)",n.style.gap="8px",n.style.marginBottom="15px",i.forEach(g=>{const p=document.createElement("button");p.className="vc-btn-ghost",p.textContent=g.label,p.style.padding="7px 6px",p.style.fontSize="12px",p.addEventListener("click",()=>{const b=this.engine.systemManager.get("atmosphere");b&&b.setTime(g.hour,g.minute)}),n.appendChild(p)}),e.appendChild(n);const o=document.createElement("div");o.textContent="Time Scale",o.className="vc-label",o.style.textAlign="left",o.style.marginBottom="10px",e.appendChild(o);const a=document.createElement("div");a.style.display="grid",a.style.gridTemplateColumns="repeat(4, 1fr)",a.style.gap="8px",a.style.marginBottom="15px";const r=[{label:"Real",value:1},{label:"2x",value:2},{label:"60x",value:60},{label:"120x",value:120}],l=[];r.forEach(g=>{const p=document.createElement("button");p.type="button",p.className="vc-btn-ghost",p.textContent=g.label,p.dataset.speed=g.value,p.style.padding="7px 6px",p.style.fontSize="12px",p.addEventListener("click",()=>{this.setTimeSpeed(g.value)}),l.push(p),a.appendChild(p)}),this.elements.speedButtons=l,e.appendChild(a);const c=document.createElement("div");c.textContent="Custom Time",c.className="vc-label",c.style.textAlign="left",c.style.marginBottom="10px",e.appendChild(c);const d=document.createElement("div");d.style.position="relative",d.style.width="100%",d.style.height="30px",d.style.backgroundColor="#1c1e21",d.style.borderRadius="15px",d.style.marginBottom="15px";const u=document.createElement("div");u.style.position="absolute",u.style.top="50%",u.style.left="10px",u.style.right="10px",u.style.height="4px",u.style.transform="translateY(-50%)",u.style.backgroundColor="#3c3e41",u.style.borderRadius="2px",d.appendChild(u);const m=document.createElement("div");m.style.position="absolute",m.style.top="50%",m.style.left="10px",m.style.width="20px",m.style.height="20px",m.style.transform="translate(0, -50%)",m.style.backgroundColor="white",m.style.borderRadius="50%",m.style.cursor="pointer",m.style.boxShadow="0 2px 4px rgba(0, 0, 0, 0.3)",d.appendChild(m);let f=!1;if(u.clientWidth,m.addEventListener("mousedown",g=>{f=!0,g.preventDefault()}),document.addEventListener("mouseup",()=>{f=!1}),document.addEventListener("mousemove",g=>{if(!f)return;const p=u.getBoundingClientRect(),b=p.left+10,x=p.right-10-b;let w=g.clientX-b;w=Math.max(0,Math.min(w,x));const v=w/x;m.style.left=`${v*100}%`;const M=Math.floor(v*24),_=Math.floor(v*24*60%60),E=this.engine.systemManager.get("atmosphere");E&&E.setTime(M,_)}),e.appendChild(d),this.engine.input.isTouchDevice){const g=document.createElement("div");g.textContent="Motion Controls",g.style.fontSize="18px",g.style.textAlign="center",g.style.marginBottom="10px",g.style.marginTop="15px",g.style.fontWeight="bold",e.appendChild(g);const p=document.createElement("div");p.style.display="flex",p.style.justifyContent="center",p.style.alignItems="center",p.style.marginBottom="15px";const b=document.createElement("div");b.textContent="Use device tilt for controls",b.style.marginRight="10px",p.appendChild(b);const S=document.createElement("div");S.style.width="44px",S.style.height="24px",S.style.backgroundColor="#1c1e21",S.style.borderRadius="12px",S.style.position="relative",S.style.cursor="pointer";const x=document.createElement("div");x.style.width="18px",x.style.height="18px",x.style.backgroundColor="white",x.style.borderRadius="50%",x.style.position="absolute",x.style.top="3px",x.style.left="3px",x.style.transition="all 0.2s",S.appendChild(x);let w=!1;const v=M=>{M?(x.style.left="23px",S.style.backgroundColor="#4285f4"):(x.style.left="3px",S.style.backgroundColor="#1c1e21")};S.addEventListener("click",()=>{w=!w,v(w);const M=this.engine.systemManager.get("playerInput");M&&typeof M.toggleMotionControls=="function"&&M.toggleMotionControls(w)}),p.appendChild(S),e.appendChild(p)}this.registerSettingsPane("time",e),this.elements.timePanel=e}showGameUI(){this.setSettingsVisible(!0)}showPauseMenu(){y.debug("Pause menu would show here")}showQuestLog(){const e=this.engine.systemManager.get("questManager");if(!e){y.warn("No quest manager found");return}if(this.elements.questPanel&&this.elements.questPanel.style.display!=="none"){this.elements.questPanel.style.display="none",clearInterval(this._questPanelTimer);return}if(!this.elements.questPanel){const i=document.createElement("div");i.style.position="fixed",i.style.top="170px",i.style.left="12px",i.style.minWidth="210px",i.style.maxWidth="260px",i.style.background="rgba(15, 22, 40, 0.72)",i.style.borderRadius="10px",i.style.padding="10px 12px",i.style.color="#fff",i.style.fontFamily="var(--app-font, sans-serif)",i.style.fontSize="13px",i.style.pointerEvents="none",i.style.zIndex="1000",document.body.appendChild(i),this.elements.questPanel=i}const t=this.elements.questPanel,s=()=>{const i=e.getActiveQuests();t.innerHTML="";const n=document.createElement("div");n.textContent="Quests — Q to close",n.style.opacity="0.65",n.style.marginBottom="6px",n.style.fontSize="11px",n.style.letterSpacing="0.08em",n.style.textTransform="uppercase",t.appendChild(n),i.forEach(o=>{const a=o.status==="completed",r=o.objectives&&o.objectives[0],l=document.createElement("div");l.style.marginBottom="7px";const c=document.createElement("div");if(c.textContent=(a?"✓ ":"")+o.name,c.style.opacity=a?"0.55":"1",l.appendChild(c),!a&&r&&r.target>1){const d=document.createElement("div");d.style.height="4px",d.style.borderRadius="2px",d.style.background="rgba(255,255,255,0.15)",d.style.marginTop="3px";const u=document.createElement("div");u.style.height="100%",u.style.borderRadius="2px",u.style.width=Math.min(100,r.current/r.target*100)+"%",u.style.background="#66ffee",d.appendChild(u),l.appendChild(d)}t.appendChild(l)})};s(),t.style.display="block",clearInterval(this._questPanelTimer),this._questPanelTimer=setInterval(s,1e3)}destroy(){window.removeEventListener("keydown",this._questKeyHandler),clearInterval(this._questPanelTimer),this.elements.toastStack&&this.elements.toastStack.remove(),this.elements.questPanel&&this.elements.questPanel.remove(),this.unsubscribeState&&(this.unsubscribeState(),this.unsubscribeState=null),this.minimapContainer&&(this.minimapContainer.remove(),this.minimapContainer=null),this.canvas=null,this.context=null}showTimeControls(){this.setSettingsVisible(!0),this.openSettingsMenu("time")}}class ia extends U{constructor(e){super(e,"simpleTrees"),this.requireDependencies(["world"]),this.scene=e.scene,this.worldSystem=null,this.assetManager=e.assets,this.treeModels=[],this.spawnedTrees=[],this.chunksWithTrees=new Map,this.clustersPerChunk=3,this.treesPerCluster=15,this.clusterRadius=40,this.minTreeDistance=4,this.scatteredTreeDensity=.15,this.scatteredTreeAttempts=30,this.maxTreesPerChunk=80,this.viewDistance=3,this.keepDistance=this.viewDistance+1,this.maxTotalTrees=1200,this.treeFadeDistance=1800,this._lastPlayerChunkX=null,this._lastPlayerChunkZ=null,this.modelPaths=[W("/assets/models/pine_tree.glb"),W("/assets/models/oak_tree.glb"),W("/assets/models/default_tree.glb"),W("/assets/models/palm_tree.glb"),W("/assets/models/detailed_tree.glb"),W("/assets/models/fat_tree.glb")],this.useProcedural=!1,this._loggedFirstUpdate=!1}async _initialize(){if(y.info("🌲 Initializing Simple Tree System..."),this.worldSystem=this.engine.systems.get("world"),!this.worldSystem){y.error("SimpleTreeSystem: World system not found!");return}this.modelPaths.length>0&&await this.loadTreeModels(),this.treeModels.length===0&&(y.warn("No tree models found, using procedural fallback"),this.useProcedural=!0,this.createProceduralTreeModels()),y.info(`Simple Tree System initialized with ${this.treeModels.length} tree types`)}async loadTreeModels(){y.info(`Attempting to load ${this.modelPaths.length} tree models...`);const e=this.modelPaths.map(async s=>{try{return new Promise((i,n)=>{this.assetManager.gltfLoader.load(s,o=>{y.info(`✅ Successfully loaded tree model: ${s}`),o.scene.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0,a.material&&(a.material.needsUpdate=!0))}),i(o.scene)},o=>{},o=>{y.error(`❌ Failed to load tree model ${s}:`,o),i(null)})})}catch(i){return y.error(`❌ Error loading tree model ${s}:`,i),null}}),t=await Promise.all(e);this.treeModels=t.filter(s=>s!==null),y.info(`Loaded ${this.treeModels.length} out of ${this.modelPaths.length} tree models`)}createProceduralTreeModels(){const e=new ee,t=new k(new Z(.3,.5,4,6),new R({color:4861722}));t.position.y=2,t.castShadow=!0;const s=new k(new Jt(2,6,6),new R({color:2969622}));s.position.y=5,s.castShadow=!0,e.add(t),e.add(s),this.treeModels.push(e);const i=new ee,n=new k(new Z(.3,.4,3,6),new R({color:4861722}));n.position.y=1.5,n.castShadow=!0;const o=new k(new $(2,8,6),new R({color:3832346}));o.position.y=4,o.castShadow=!0,i.add(n),i.add(o),this.treeModels.push(i),y.info("Created 2 procedural tree models")}_update(e){const t=this.engine.systems.get("player");if(!t||!t.localPlayer)return;const s=t.localPlayer;this._loggedFirstUpdate||(y.info(`🌲 Tree system starting - Player at (${s.position.x.toFixed(0)}, ${s.position.z.toFixed(0)})`),this._loggedFirstUpdate=!0);const i=this.worldSystem.chunkSize,n=Math.floor(s.position.x/i),o=Math.floor(s.position.z/i),a=this.viewDistance;for(let r=-a;r<=a;r++)for(let l=-a;l<=a;l++){const c=n+r,d=o+l,u=`${c},${d}`;if(!this.chunksWithTrees.has(u)){const m=this.spawnTreesForChunk(c,d);this.chunksWithTrees.set(u,{x:c,z:d,trees:m})}}(n!==this._lastPlayerChunkX||o!==this._lastPlayerChunkZ)&&(this._lastPlayerChunkX=n,this._lastPlayerChunkZ=o,this.despawnDistantChunks(n,o,s)),this.updateTreeVisibility(s)}despawnDistantChunks(e,t,s){let i=this.spawnedTrees.length,n=!1;for(const[o,a]of this.chunksWithTrees)(Math.abs(a.x-e)>this.keepDistance||Math.abs(a.z-t)>this.keepDistance)&&(i-=a.trees.length,this.removeChunkTrees(o,a),n=!0);if(i>this.maxTotalTrees){const o=this.worldSystem.chunkSize,a=s.position.x,r=s.position.z,l=[];for(const[c,d]of this.chunksWithTrees)if(Math.abs(d.x-e)>this.viewDistance||Math.abs(d.z-t)>this.viewDistance){const u=(d.x+.5)*o-a,m=(d.z+.5)*o-r;l.push({chunkKey:c,entry:d,distSq:u*u+m*m})}l.sort((c,d)=>d.distSq-c.distSq);for(let c=0;cthis.maxTotalTrees;c++)i-=l[c].entry.trees.length,this.removeChunkTrees(l[c].chunkKey,l[c].entry),n=!0}n&&this.rebuildSpawnedTrees()}removeChunkTrees(e,t){const s=t.trees;for(let i=0;i300||this.worldSystem.calculateSlope(l,c)>.6)continue;const m=Math.floor(this.treesPerCluster*(.7+Math.random()*.6));for(let f=0;f300||this.worldSystem.calculateSlope(b,S)>.6||this.isValidTreePosition(b,S)&&(s.push(this.spawnTree(b,x,S)),a++)}}for(let r=0;r300||this.worldSystem.calculateSlope(l,c)>.6||this.isValidTreePosition(l,c)&&(Math.random()>this.scatteredTreeDensity||(s.push(this.spawnTree(l,d,c)),a++))}return a>0&&this.chunksWithTrees.size<=3&&y.info(`🌲 Spawned ${a} trees in chunk ${e},${t} (cluster-based)`),s}isValidTreePosition(e,t){const s=Math.max(0,this.spawnedTrees.length-50);for(let i=s;i{r.isMesh&&(r.castShadow=!0,r.receiveShadow=!0,r.visible=!0)}),this.scene.add(o),this.spawnedTrees.push(o),this.spawnedTrees.length===1&&y.info(`🌲 First tree spawned at (${e.toFixed(0)}, ${t.toFixed(0)}, ${s.toFixed(0)}) with scale ${a.toFixed(1)}`),o}_destroy(){for(const e of this.spawnedTrees)this.scene.remove(e);this.spawnedTrees=[],this.chunksWithTrees.clear(),this._lastPlayerChunkX=null,this._lastPlayerChunkZ=null,y.info("Simple Tree System destroyed")}}class gt extends k{constructor(){const e=gt.SkyShader,t=new Xe({name:e.name,uniforms:Ot.clone(e.uniforms),vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,side:fe,depthWrite:!1});super(new Q(1,1,1),t),this.isSky=!0}}gt.SkyShader={name:"SkyShader",uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new A},up:{value:new A(0,1,0)}},vertexShader:` - uniform vec3 sunPosition; - uniform float rayleigh; - uniform float turbidity; - uniform float mieCoefficient; - uniform vec3 up; - - varying vec3 vWorldPosition; - varying vec3 vSunDirection; - varying float vSunfade; - varying vec3 vBetaR; - varying vec3 vBetaM; - varying float vSunE; - - // constants for atmospheric scattering - const float e = 2.71828182845904523536028747135266249775724709369995957; - const float pi = 3.141592653589793238462643383279502884197169; - - // wavelength of used primaries, according to preetham - const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 ); - // this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function: - // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) - const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 ); - - // mie stuff - // K coefficient for the primaries - const float v = 4.0; - const vec3 K = vec3( 0.686, 0.678, 0.666 ); - // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K - const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 ); - - // earth shadow hack - // cutoffAngle = pi / 1.95; - const float cutoffAngle = 1.6110731556870734; - const float steepness = 1.5; - const float EE = 1000.0; - - float sunIntensity( float zenithAngleCos ) { - zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 ); - return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) ); - } - - vec3 totalMie( float T ) { - float c = ( 0.2 * T ) * 10E-18; - return 0.434 * c * MieConst; - } - - void main() { - - vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); - vWorldPosition = worldPosition.xyz; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - gl_Position.z = gl_Position.w; // set z to camera.far - - vSunDirection = normalize( sunPosition ); - - vSunE = sunIntensity( dot( vSunDirection, up ) ); - - vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 ); - - float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) ); - - // extinction (absorbtion + out scattering) - // rayleigh coefficients - vBetaR = totalRayleigh * rayleighCoefficient; - - // mie coefficients - vBetaM = totalMie( turbidity ) * mieCoefficient; - - }`,fragmentShader:` - varying vec3 vWorldPosition; - varying vec3 vSunDirection; - varying float vSunfade; - varying vec3 vBetaR; - varying vec3 vBetaM; - varying float vSunE; - - uniform float mieDirectionalG; - uniform vec3 up; - - // constants for atmospheric scattering - const float pi = 3.141592653589793238462643383279502884197169; - - const float n = 1.0003; // refractive index of air - const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius) - - // optical length at zenith for molecules - const float rayleighZenithLength = 8.4E3; - const float mieZenithLength = 1.25E3; - // 66 arc seconds -> degrees, and the cosine of that - const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324; - - // 3.0 / ( 16.0 * pi ) - const float THREE_OVER_SIXTEENPI = 0.05968310365946075; - // 1.0 / ( 4.0 * pi ) - const float ONE_OVER_FOURPI = 0.07957747154594767; - - float rayleighPhase( float cosTheta ) { - return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) ); - } - - float hgPhase( float cosTheta, float g ) { - float g2 = pow( g, 2.0 ); - float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 ); - return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse ); - } - - void main() { - - vec3 direction = normalize( vWorldPosition - cameraPosition ); - - // optical length - // cutoff angle at 90 to avoid singularity in next formula. - float zenithAngle = acos( max( 0.0, dot( up, direction ) ) ); - float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) ); - float sR = rayleighZenithLength * inverse; - float sM = mieZenithLength * inverse; - - // combined extinction factor - vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) ); - - // in scattering - float cosTheta = dot( direction, vSunDirection ); - - float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 ); - vec3 betaRTheta = vBetaR * rPhase; - - float mPhase = hgPhase( cosTheta, mieDirectionalG ); - vec3 betaMTheta = vBetaM * mPhase; - - vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) ); - Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) ); - - // nightsky - float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2] - float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2] - vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 ); - vec3 L0 = vec3( 0.1 ) * Fex; - - // composition + solar disc - float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta ); - L0 += ( vSunE * 19000.0 * Fex ) * sundisk; - - vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 ); - - vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) ); - - gl_FragColor = vec4( retColor, 1.0 ); - - #include - #include - - }`};const na={SUN_RADIUS:120,SUN_SEGMENTS:32,RENDER_ORDER:99,RENDER_LAYER:10,DEFAULT_COLOR:16766336,DEFAULT_INTENSITY:1.4,AMBIENT_INTENSITY:1,AMBIENT_MIN_INTENSITY:.25,SUN_DISTANCE:15e3,MAX_HEIGHT:3e3,HORIZON_LEVEL:0,SEASONAL_VARIATION:.15,CYCLE_SPEED:.001,SUNRISE_TIME:.25,SUNSET_TIME:.75,GLOW_OPACITY:.2,BELOW_HORIZON_FACTOR:300,SHADOW_MAP_SIZE:2048,SHADOW_BIAS:-5e-4,SHADOW_NEAR:100,SHADOW_FAR:5e3,SHADOW_CAMERA_SIZE:100},oa=[{t:0,color:2241365,value:.12},{t:.2,color:2241365,value:.12},{t:.23,color:4478327,value:.3},{t:.28,color:16755285,value:.9},{t:.35,color:16771264,value:1.25},{t:.5,color:16775136,value:1.4},{t:.65,color:16771264,value:1.3},{t:.7,color:16764023,value:1.15},{t:.78,color:16742195,value:.85},{t:.85,color:5583718,value:.3},{t:.9,color:2241365,value:.12},{t:1,color:2241365,value:.12}],aa=[{t:0,color:3359846,value:.28},{t:.2,color:3359846,value:.28},{t:.23,color:4478327,value:.34},{t:.28,color:16767408,value:.55},{t:.35,color:15262938,value:.85},{t:.5,color:15920610,value:1},{t:.65,color:15722200,value:.9},{t:.7,color:16769720,value:.8},{t:.78,color:16758152,value:.6},{t:.85,color:6179456,value:.36},{t:.9,color:3359846,value:.28},{t:1,color:3359846,value:.28}],ra=[{t:0,color:16737826},{t:.22,color:16742195},{t:.27,color:16750916},{t:.33,color:16764006},{t:.45,color:16772693},{t:.55,color:16772693},{t:.65,color:16768341},{t:.7,color:16759620},{t:.75,color:16750899},{t:.8,color:16737826},{t:1,color:16737826}],la=[{t:0,color:725030},{t:.2,color:725030},{t:.23,color:1712962},{t:.28,color:4478095},{t:.35,color:7317736},{t:.5,color:7846911},{t:.65,color:6989552},{t:.7,color:6983632},{t:.78,color:4608399},{t:.85,color:2235460},{t:.9,color:725030},{t:1,color:725030}],ca=[{t:0,color:1251891},{t:.2,color:1251891},{t:.23,color:3816030},{t:.28,color:16750950},{t:.36,color:16112056},{t:.5,color:12378111},{t:.64,color:13228524},{t:.7,color:16764040},{t:.78,color:16742212},{t:.85,color:5453148},{t:.9,color:1581117},{t:1,color:1251891}],ha=[{t:0,value:26e-5},{t:.2,value:26e-5},{t:.28,value:24e-5},{t:.5,value:2e-4},{t:.7,value:22e-5},{t:.78,value:24e-5},{t:.85,value:26e-5},{t:1,value:26e-5}],da=[{t:0,color:3820138,value:.16},{t:.2,color:3820138,value:.16},{t:.24,color:5595274,value:.2},{t:.29,color:16763296,value:.28},{t:.4,color:16777215,value:.3},{t:.6,color:16777215,value:.3},{t:.68,color:16773336,value:.3},{t:.74,color:16764830,value:.3},{t:.8,color:16751216,value:.26},{t:.86,color:5917304,value:.2},{t:.92,color:3820138,value:.16},{t:1,color:3820138,value:.16}],Ps=new C,Rs=new C;function Re(h,e,t=null){let s=e-Math.floor(e);Number.isFinite(s)||(s=0);let i=h[0],n=h[h.length-1];for(let c=0;c1e-6?(s-i.t)/o:0;a=Math.max(0,Math.min(1,a)),a=a*a*(3-2*a),t&&i.color!==void 0&&n.color!==void 0&&(Ps.setHex(i.color),Rs.setHex(n.color),t.copy(Ps).lerp(Rs,a));const r=i.value!==void 0?i.value:0,l=n.value!==void 0?n.value:0;return r+(l-r)*a}class ua{constructor(e){this.atmosphereSystem=e,this.scene=e.scene,this.engine=e.engine,this.sky=null,this.isFallbackSky=!1,this.fallbackSkyMaterial=null,this._zenithColor=new C(7846911),this._horizonColor=new C(12378111),this._skyGradientFactors=null}async initialize(){y.info("Initializing SkySystem..."),y.info("Using Fallback Sky"),this.isFallbackSky=!0,this.createFallbackSky(),this.getRenderer()||y.debug("SkySystem: renderer not ready at init; per-frame updates will pick it up lazily"),this.scene.fog=new Xs(12378111,22e-5),y.info("SkySystem initialization complete")}getRenderer(){return this.engine.rendererManager&&this.engine.rendererManager.renderer?this.engine.rendererManager.renderer:this.engine.renderer||null}createStandardSky(){this.sky=new gt;const t=this.engine.camera.far*.8;this.sky.scale.setScalar(t);const s=window.innerWidth/window.innerHeight,i=this.sky.geometry;i.parameters.widthSegments=Math.max(32,Math.floor(32*s)),i.parameters.heightSegments=Math.max(32,Math.floor(32*s)),this.scene.add(this.sky);const n=this.sky.material.uniforms;n.turbidity.value=8,n.rayleigh.value=1,n.mieCoefficient.value=.025,n.mieDirectionalG.value=.999,this.sky.material.side=fe,this.sky.material.depthWrite=!1}createFallbackSky(){const t=this.engine.camera.far*.8,s=Se.gpuTier==="low"?24:32,i=Se.gpuTier==="low"?12:16,n=new $(t,s,i),o=n.getAttribute("position"),a=o.count;this._skyGradientFactors=new Float32Array(a);for(let r=0;r0?1:Math.max(0,1+s/this.config.BELOW_HORIZON_FACTOR);if(this.sunMesh.material.opacity=.9*n,this.sunGlow){const a=1+i*1.5;this.sunGlow.material.opacity=this.config.GLOW_OPACITY*a*n}const o=1+i*.2;this.sunMesh.scale.set(o,o,1),this.updateSunColors()}updateSunColors(){this.sunMesh&&(Re(ra,this.timeOfDay,this.sunMesh.material.color),this.sunGlow&&this.sunGlow.material.color.copy(this.sunMesh.material.color).lerp(ma,.35))}updateLighting(e,t){if(!this.sunLight||!this.ambientLight)return;this.sunLight.intensity=Re(oa,this.timeOfDay,this.sunLight.color);const s=Re(aa,this.timeOfDay,this.ambientLight.color);this.ambientLight.intensity=Math.max(this.config.AMBIENT_MIN_INTENSITY,s)}updateVisibility(){const e=this.timeOfDay>.18&&this.timeOfDay<.82;this.sunMesh&&(this.sunMesh.visible=e&&this.isVisible),this.sunLight&&(this.sunLight.visible=!0)}setupDayNightCycle(){const e=new Date,t=86400,s=e.getHours()*3600+e.getMinutes()*60+e.getSeconds();this.timeOfDay=s/t,y.info(`SunSystem: Initialized time of day to ${this.timeOfDay.toFixed(4)} (${(this.timeOfDay*24).toFixed(1)} hours)`)}getSunPosition(){return this.sunPosition.clone()}getSunLight(){return this.sunLight}getSunDirection(){return this.sunPosition.clone().normalize()}getSunIntensity(){return this.sunLight?this.sunLight.intensity:0}getTimeOfDay(){return this.timeOfDay}setTimeOfDay(e){this.timeOfDay=Math.max(0,Math.min(1,e))}setSunVisibility(e){this.isVisible=e,this.sunMesh&&(this.sunMesh.visible=e)}enableReflections(e){this.sunMesh&&(e?this.sunMesh.layers.enable(this.config.RENDER_LAYER):this.sunMesh.layers.disable(this.config.RENDER_LAYER))}destroy(){this.sunMesh&&this.scene.remove(this.sunMesh),this.sunLight&&this.scene.remove(this.sunLight),this.ambientLight&&this.scene.remove(this.ambientLight),y.info("SunSystem: Cleaned up sun system")}}class fa{constructor(e){this.atmosphereSystem=e,this.scene=e.scene,this.engine=e.engine,this.moonMesh=null,this.moonLight=null,this.moonPosition=new A}async initialize(){const e=new Be,t=await new Promise(n=>{e.load(W("/assets/textures/moon.jpg"),o=>n(o),void 0,()=>{y.warn("Failed to load moon texture, using fallback");const o=document.createElement("canvas");o.width=256,o.height=256;const a=o.getContext("2d");a.fillStyle="#eeeeee",a.fillRect(0,0,256,256);for(let l=0;l<15;l++)a.fillStyle=`rgba(100, 100, 120, ${Math.random()*.5})`,a.beginPath(),a.arc(Math.random()*256,Math.random()*256,Math.random()*30+5,0,Math.PI*2),a.fill();const r=new Le(o);n(r)})}),s=new $(150,32,32),i=new V({map:t,fog:!1,side:pt,transparent:!0,opacity:1,depthTest:!1});this.moonMesh=new k(s,i),this.moonMesh.renderOrder=100,this.moonMesh.layers.set(10),this.scene.add(this.moonMesh),this.moonLight=new Xt(14606079,.2),this.moonLight.position.set(0,1,0),this.moonMesh.add(this.moonLight)}update(e,t){const s=this.atmosphereSystem.getTimeOfDay(),i=this.atmosphereSystem.getNightFactor(),n=this.atmosphereSystem.getMoonPhase(),o=this.atmosphereSystem.getMoonIllumination(),r=s*Math.PI*2-Math.PI/2+Math.PI,l=8e3,c=Math.cos(r)*l,d=Math.max(0,Math.sin(r)*l);this.moonPosition.set(c,d,0);const m=d>300;if(this.moonMesh.visible=m&&i>.1,this.moonMesh.visible&&(this.moonMesh.position.copy(this.moonPosition),this.engine.camera&&this.moonMesh.lookAt(this.engine.camera.position),this.moonMesh.material)){const f=(.7+o*.3)*i;this.moonMesh.material.opacity=f}this.moonLight&&(this.moonLight.intensity=m?.35*i*(.3+.7*o):0),this.moonMesh.rotation.y=n*Math.PI*2%(Math.PI*2)}getMoonPosition(){return this.moonPosition.clone()}}class ya{constructor(e){this.atmosphereSystem=e,this.scene=e.scene,this.engine=e.engine,this.starField=null,this.horizonStarField=null,this.regularStarCount=4500,this.horizonStarCount=2e3}async initialize(){this.createRegularStars(),this.createHorizonStars()}createRegularStars(){const e=new ze,t=[],s=[],i=[];this.generateStarAttributes(t,s,i,this.regularStarCount,!0,15e3),e.setAttribute("position",new Pe(t,3)),e.setAttribute("size",new Pe(s,1)),e.setAttribute("color",new Pe(i,3));const o=new lt({size:5,vertexColors:!0,transparent:!0,opacity:1,blending:De,depthWrite:!1,depthTest:!1,sizeAttenuation:!1});this.starField=new ct(e,o),this.starField.renderOrder=-10,this.scene.add(this.starField)}createHorizonStars(){const e=new ze,t=[],s=[],i=[];this.generateStarAttributes(t,s,i,this.horizonStarCount,!1,15e3),e.setAttribute("position",new Pe(t,3)),e.setAttribute("size",new Pe(s,1)),e.setAttribute("color",new Pe(i,3));const o=new lt({size:4,vertexColors:!0,transparent:!0,opacity:.9,blending:De,depthWrite:!1,depthTest:!1,sizeAttenuation:!1});this.horizonStarField=new ct(e,o),this.horizonStarField.renderOrder=-10,this.scene.add(this.horizonStarField)}generateStarAttributes(e,t,s,i,n){this.starFadeThresholds=this.starFadeThresholds||{},this.starFadeThresholds[n?"regular":"horizon"]=new Float32Array(i);for(let o=0;o.92)s.push(.8+Math.random()*.2,.85+Math.random()*.15,1);else if(f>.85)s.push(1,.7+Math.random()*.3,.4+Math.random()*.3);else if(f>.78)s.push(1,.5+Math.random()*.3,.5+Math.random()*.3);else if(f>.7)s.push(.9+Math.random()*.1,.9+Math.random()*.1,1);else{const g=.9+Math.random()*.1;s.push(g,g,g)}else if(f>.8)s.push(.7+Math.random()*.3,.8+Math.random()*.2,1);else if(f>.6)s.push(1,.9+Math.random()*.1,.8+Math.random()*.2);else{const g=.9+Math.random()*.1;s.push(g,g,g)}}}update(e,t){const s=this.atmosphereSystem.getNightFactor();this.updateStarsVisibility(s),this.engine.camera&&(this.starField&&this.starField.position.copy(this.engine.camera.position),this.horizonStarField&&this.horizonStarField.position.copy(this.engine.camera.position)),this.updateStarTwinkle(e)}updateStarTwinkle(e){if(!this.starField||!this.horizonStarField)return;const t=this.atmosphereSystem.elapsed;if(Math.random()>.99){const s=this.starField.geometry.getAttribute("size"),i=this.horizonStarField.geometry.getAttribute("size");for(let n=0;n<20;n++){const o=Math.floor(Math.random()*this.regularStarCount),a=Math.floor(Math.random()*this.horizonStarCount),r=.1*Math.sin(t*3+o),l=.1*Math.sin(t*2.7+a),c=s.getX(o);s.setX(o,c+r);const d=i.getX(a);i.setX(a,d+l)}s.needsUpdate=!0,i.needsUpdate=!0}}updateStarsVisibility(e){const t=this.atmosphereSystem.elapsed,s=.05*Math.sin(t*10),i=.05*Math.sin(t*10+Math.PI/2);if(this.starField&&(this.starField.visible=e>.03,this.starField.material)){const o=this.smoothstep(.05,.3,e)*.8;this.starField.material.opacity=o+s}if(this.horizonStarField&&(this.horizonStarField.visible=e>.02,this.horizonStarField.material)){const o=this.smoothstep(.03,.25,e)*.7;this.horizonStarField.material.opacity=o+i}}smoothstep(e,t,s){const i=Math.max(0,Math.min(1,(s-e)/(t-e)));return i*i*(3-2*i)}}class ga{constructor(e){this.atmosphereSystem=e,this.scene=e.scene,this.engine=e.engine,this.clouds=[],this.cloudCount=100,this.cloudSpread=3e3,this.cloudHeight=600,this._cloudTint=new C(16777215)}async initialize(){this.createVolumetricClouds()}createCloudSpriteMaterial(){const e=new Be;return new Promise(t=>{e.load(W("/assets/textures/particles.png"),s=>{const i=new mt({map:s,transparent:!0,opacity:.3,blending:hs,depthWrite:!1,depthTest:!0});t(i)},void 0,()=>{y.warn("Error loading cloud texture, using fallback");const s=document.createElement("canvas");s.width=128,s.height=128;const i=s.getContext("2d"),n=i.createRadialGradient(64,64,0,64,64,64);n.addColorStop(0,"rgba(240, 245, 255, 0.8)"),n.addColorStop(.4,"rgba(230, 240, 255, 0.4)"),n.addColorStop(.7,"rgba(220, 235, 255, 0.2)"),n.addColorStop(1,"rgba(220, 235, 255, 0)"),i.fillStyle=n,i.fillRect(0,0,128,128);const o=new Le(s),a=new mt({map:o,transparent:!0,opacity:.3,blending:hs,depthWrite:!1,depthTest:!0});t(a)})})}async createVolumetricClouds(){y.info("Creating volumetric clouds..."),this.clouds=[];const e=await this.createCloudSpriteMaterial(),t=this.engine.systems.player?.localPlayer,s=t?t.position:new A(0,0,0);for(let i=0;i{a.material.rotation+=a.userData.rotationSpeed*e,a.position.x+=a.userData.horizontalSpeed*e,a.position.z+=a.userData.horizontalSpeed*.5*e,a.position.y+=Math.sin(o*.001+a.userData.timeOffset)*a.userData.verticalFactor*e});return}const n=this.atmosphereSystem.elapsed;this.clouds.forEach(o=>{o.material.rotation+=o.userData.rotationSpeed*e,o.position.x+=o.userData.horizontalSpeed*e,o.position.z+=o.userData.horizontalSpeed*.5*e,o.position.y+=Math.sin(n*.001+o.userData.timeOffset)*o.userData.verticalFactor*e;const a=o.position.x-i.position.x,r=o.position.z-i.position.z;if(a*a+r*r>9e6){const c=Math.random()*Math.PI*2,d=2e3+Math.random()*500;o.position.x=i.position.x+d*Math.cos(c),o.position.z=i.position.z+d*Math.sin(c)}})}}class ba extends U{constructor(e){super(e,"atmosphere"),this.engine=e,this.scene=e.scene,this.elapsed=0,this.dayDuration=86400,this.timeScale=1,this.currentDay=0,this.daysPerMonth=30,this.currentMonth=0,this.monthsPerYear=12,this.yearProgress=0,this.moonPhase=1;const t=new Date;t.getHours()*3600+t.getMinutes()*60+t.getSeconds(),this.timeOfDay=.5,y.info("Synced Time of Day:",this.timeOfDay),this.skySystem=null,this.sunSystem=null,this.moonSystem=null,this.starSystem=null,this.cloudSystem=null}async _initialize(){y.info("Initializing AtmosphereSystem...");try{y.debug("Creating SkySystem..."),this.skySystem=new ua(this),y.debug("Creating SunSystem..."),this.sunSystem=new pa(this),y.debug("Creating MoonSystem..."),this.moonSystem=new fa(this),y.debug("Creating StarSystem..."),this.starSystem=new ya(this),this.cloudSystem=new ga(this),y.debug("Initializing subsystems..."),await Promise.all([this.skySystem.initialize(),this.sunSystem.initialize(),this.moonSystem.initialize(),this.starSystem.initialize(),this.cloudSystem.initialize()]),y.info("AtmosphereSystem initialized successfully"),y.debug(`Subsystems created: sun=${!!this.sunSystem}, sky=${!!this.skySystem}, moon=${!!this.moonSystem}, star=${!!this.starSystem}`)}catch(e){throw y.error("AtmosphereSystem initialization failed:",e),e}}updateCalendar(e){this.currentDay;const t=e/this.dayDuration;this.currentDay+=t,this.currentDay>=this.daysPerMonth&&(this.currentDay-=this.daysPerMonth,this.currentMonth++,this.currentMonth>=this.monthsPerYear&&(this.currentMonth=0)),this.yearProgress=(this.currentMonth+this.currentDay/this.daysPerMonth)/this.monthsPerYear,this.moonPhase=this.currentDay/this.daysPerMonth}setTime(e,t){this.timeOfDay=(e+t/60)/24,y.info(`Time set to ${e}:${t.toString().padStart(2,"0")} (${this.timeOfDay.toFixed(4)})`)}update(e,t){try{if(e===0)return;this.elapsed=t;const s=e*this.timeScale,i=this.timeOfDay;this.timeOfDay+=s/this.dayDuration,this.timeOfDay>=1&&(this.timeOfDay-=1,this.updateCalendar(e)),this.sunSystem&&typeof this.sunSystem.update=="function"?this.sunSystem.update(e,t):this.sunSystem?y.error("SunSystem exists but has no update method!"):y.error("SunSystem is null!"),this.skySystem&&typeof this.skySystem.update=="function"?this.skySystem.update(e,t):this.skySystem?y.error("SkySystem exists but has no update method!"):y.error("SkySystem is null!"),this.moonSystem&&typeof this.moonSystem.update=="function"?this.moonSystem.update(e,t):this.moonSystem?y.error("MoonSystem exists but has no update method!"):y.error("MoonSystem is null!"),this.starSystem&&typeof this.starSystem.update=="function"?this.starSystem.update(e,t):this.starSystem?y.error("StarSystem exists but has no update method!"):y.error("StarSystem is null!"),this.cloudSystem&&typeof this.cloudSystem.update=="function"&&this.cloudSystem.update(e,t)}catch(s){throw y.error("AtmosphereSystem._update failed:",s),s}}getTimeOfDay(){return this.timeOfDay}getNightFactor(){return this.timeOfDay>.75||this.timeOfDay<.25?this.timeOfDay>.75?(this.timeOfDay-.75)/.25:1-this.timeOfDay/.25:0}getSunPosition(){return this.sunSystem?this.sunSystem.getSunPosition():new A}getMoonPosition(){return this.moonSystem?this.moonSystem.getMoonPosition():new A}getMoonPhase(){return this.moonPhase}getMoonIllumination(){return Math.sin(this.moonPhase*Math.PI)}}class wa extends k{constructor(e,t={}){super(e),this.isWater=!0;const s=this,i=t.textureWidth!==void 0?t.textureWidth:512,n=t.textureHeight!==void 0?t.textureHeight:512,o=t.clipBias!==void 0?t.clipBias:0,a=t.alpha!==void 0?t.alpha:1,r=t.time!==void 0?t.time:0,l=t.waterNormals!==void 0?t.waterNormals:null,c=t.sunDirection!==void 0?t.sunDirection:new A(.70707,.70707,0),d=new C(t.sunColor!==void 0?t.sunColor:16777215),u=new C(t.waterColor!==void 0?t.waterColor:8355711),m=t.eye!==void 0?t.eye:new A(0,0,0),f=t.distortionScale!==void 0?t.distortionScale:20,g=t.side!==void 0?t.side:pt,p=t.fog!==void 0?t.fog:!1,b=new Wi,S=new A,x=new A,w=new A,v=new ye,M=new A(0,0,-1),_=new ds,E=new A,P=new A,T=new ds,N=new ye,D=new Zt,O=new $i(i,n),j={name:"MirrorShader",uniforms:Ot.merge([us.fog,us.lights,{normalSampler:{value:null},mirrorSampler:{value:null},alpha:{value:1},time:{value:0},size:{value:1},distortionScale:{value:20},textureMatrix:{value:new ye},sunColor:{value:new C(8355711)},sunDirection:{value:new A(.70707,.70707,0)},eye:{value:new A},waterColor:{value:new C(5592405)}}]),vertexShader:` - uniform mat4 textureMatrix; - uniform float time; - - varying vec4 mirrorCoord; - varying vec4 worldPosition; - - #include - #include - #include - #include - - void main() { - mirrorCoord = modelMatrix * vec4( position, 1.0 ); - worldPosition = mirrorCoord.xyzw; - mirrorCoord = textureMatrix * mirrorCoord; - vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); - gl_Position = projectionMatrix * mvPosition; - - #include - #include - #include - #include - #include - }`,fragmentShader:` - uniform sampler2D mirrorSampler; - uniform float alpha; - uniform float time; - uniform float size; - uniform float distortionScale; - uniform sampler2D normalSampler; - uniform vec3 sunColor; - uniform vec3 sunDirection; - uniform vec3 eye; - uniform vec3 waterColor; - - varying vec4 mirrorCoord; - varying vec4 worldPosition; - - vec4 getNoise( vec2 uv ) { - vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0); - vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 ); - vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 ); - vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 ); - vec4 noise = texture2D( normalSampler, uv0 ) + - texture2D( normalSampler, uv1 ) + - texture2D( normalSampler, uv2 ) + - texture2D( normalSampler, uv3 ); - return noise * 0.5 - 1.0; - } - - void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) { - vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) ); - float direction = max( 0.0, dot( eyeDirection, reflection ) ); - specularColor += pow( direction, shiny ) * sunColor * spec; - diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse; - } - - #include - #include - #include - #include - #include - #include - #include - #include - - void main() { - - #include - vec4 noise = getNoise( worldPosition.xz * size ); - vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) ); - - vec3 diffuseLight = vec3(0.0); - vec3 specularLight = vec3(0.0); - - vec3 worldToEye = eye-worldPosition.xyz; - vec3 eyeDirection = normalize( worldToEye ); - sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight ); - - float distance = length(worldToEye); - - vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale; - vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) ); - - float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 ); - float rf0 = 0.3; - float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 ); - vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor; - vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance); - vec3 outgoingLight = albedo; - gl_FragColor = vec4( outgoingLight, alpha ); - - #include - #include - #include - }`},F=new Xe({name:j.name,uniforms:Ot.clone(j.uniforms),vertexShader:j.vertexShader,fragmentShader:j.fragmentShader,lights:!0,side:g,fog:p});F.uniforms.mirrorSampler.value=O.texture,F.uniforms.textureMatrix.value=N,F.uniforms.alpha.value=a,F.uniforms.time.value=r,F.uniforms.normalSampler.value=l,F.uniforms.sunColor.value=d,F.uniforms.waterColor.value=u,F.uniforms.sunDirection.value=c,F.uniforms.distortionScale.value=f,F.uniforms.eye.value=m,s.material=F,s.onBeforeRender=function(Y,Ae,oe){if(x.setFromMatrixPosition(s.matrixWorld),w.setFromMatrixPosition(oe.matrixWorld),v.extractRotation(s.matrixWorld),S.set(0,0,1),S.applyMatrix4(v),E.subVectors(x,w),E.dot(S)>0)return;E.reflect(S).negate(),E.add(x),v.extractRotation(oe.matrixWorld),M.set(0,0,-1),M.applyMatrix4(v),M.add(w),P.subVectors(x,M),P.reflect(S).negate(),P.add(x),D.position.copy(E),D.up.set(0,1,0),D.up.applyMatrix4(v),D.up.reflect(S),D.lookAt(P),D.far=oe.far,D.updateMatrixWorld(),D.projectionMatrix.copy(oe.projectionMatrix),N.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),N.multiply(D.projectionMatrix),N.multiply(D.matrixWorldInverse),b.setFromNormalAndCoplanarPoint(S,x),b.applyMatrix4(D.matrixWorldInverse),_.set(b.normal.x,b.normal.y,b.normal.z,b.constant);const J=D.projectionMatrix;T.x=(Math.sign(_.x)+J.elements[8])/J.elements[0],T.y=(Math.sign(_.y)+J.elements[9])/J.elements[5],T.z=-1,T.w=(1+J.elements[10])/J.elements[14],_.multiplyScalar(2/_.dot(T)),J.elements[2]=_.x,J.elements[6]=_.y,J.elements[10]=_.z+1-o,J.elements[14]=_.w,m.setFromMatrixPosition(oe.matrixWorld);const Ce=Y.getRenderTarget(),q=Y.xr.enabled,z=Y.shadowMap.autoUpdate;s.visible=!1,Y.xr.enabled=!1,Y.shadowMap.autoUpdate=!1,Y.setRenderTarget(O),Y.state.buffers.depth.setMask(!0),Y.autoClear===!1&&Y.clear(),Y.render(Ae,D),s.visible=!0,Y.xr.enabled=q,Y.shadowMap.autoUpdate=z,Y.setRenderTarget(Ce);const B=oe.viewport;B!==void 0&&Y.state.viewport(B)}}}class xa extends U{constructor(e){super(e,"water"),this.scene=e.scene,this.camera=e.camera,this.waterLevel=0,this.water=null,this.sun=null}async _initialize(){y.info("🌊 Initializing Water System..."),this.engine.systems.world?(this.waterLevel=this.engine.systems.world.waterLevel||0,y.info(`Water level: ${this.waterLevel}`)):this.waterLevel=0,this.createOcean(),y.info("🌊 Water System initialized ✅")}createOcean(){const t=new Ne(1e4,1e4,64,64),i=new Be().load(W("/textures/2waternormals.jpg"),a=>{a.wrapS=a.wrapT=me}),n=this.engine.systems.get("sun");let o=new A(.707,.707,0);n&&n.getSunDirection&&(o=n.getSunDirection()),this.water=new wa(t,{textureWidth:512,textureHeight:512,waterNormals:i,sunDirection:o,sunColor:16777215,waterColor:7695,distortionScale:3.7,fog:this.scene.fog!==void 0,alpha:.8}),this.water.rotation.x=-Math.PI/2,this.water.position.y=this.waterLevel+1,this.water.renderOrder=1,this.water.material&&(this.water.material.polygonOffset=!0,this.water.material.polygonOffsetFactor=1,this.water.material.polygonOffsetUnits=1),this.scene.add(this.water),y.info("🌊 Ocean created with realistic reflections")}_update(e){if(!this.water)return;this.camera&&(this.water.position.x=this.camera.position.x,this.water.position.z=this.camera.position.z),this.water.material.uniforms.time.value+=e*.5;const t=this.engine.systems.get("sun");if(t&&t.getSunDirection){const s=t.getSunDirection();this.water.material.uniforms.sunDirection.value.copy(s).normalize()}}destroy(){this.water&&(this.scene.remove(this.water),this.water.geometry&&this.water.geometry.dispose(),this.water.material&&this.water.material.dispose(),this.water=null)}getWaterLevel(){return this.waterLevel}}class Sa extends U{constructor(e){super(e,"skybox"),this.scene=e.scene,this.camera=e.camera,this.skybox=new k,this.skyboxMaterial=null,this.baseSkyboxSize=5e3,this.skyboxSize=this.baseSkyboxSize,this.timeOfDay=.5,this.sunDirection=new A(0,1,0),this.moonDirection=new A(0,-1,0),this.horizonOffset=0,this.seasonalTilt=0,this.dayLength=24,this.daySkyColor=new C(.25,.4,.6),this.dayHorizonColor=new C(.75,.9,1),this.nightSkyColor=new C(.06,.1,.15),this.nightHorizonColor=new C(.07,.13,.18),this.earlyTwilightColor=new C(1,.83,.5),this.lateTwilightColor=new C(1,.333,.167),this.sunVisibility=1,this.moonVisibility=0,this.twilightVisibility=0,this.twilightTime=0,this.starsTexture=null,this.ditherTexture=null,this.skyRotationMatrix=new ji}async _initialize(){y.info("🎨 Initializing Simple Skybox System...");try{this.createSimpleSkybox(),y.info("🎨 Simple Skybox System initialized successfully ✅")}catch(e){y.error("Failed to initialize Skybox System:",e),this.createBasicFallback()}}async generateTextures(){y.debug("Generating procedural skybox textures..."),this.starsTexture=this.generateStarsTexture(),this.ditherTexture=this.generateDitherTexture(),y.debug("Procedural textures generated successfully")}generateStarsTexture(){const t=document.createElement("canvas");t.width=t.height=512;const s=t.getContext("2d");s.fillStyle="black",s.fillRect(0,0,512,512);const i=200;for(let o=0;o 0.0 ? true : false; - bool yPositive = dir.y > 0.0 ? true : false; - bool zPositive = dir.z > 0.0 ? true : false; - float maxAxis = 1.0; - float u = 0.0; - float v = 0.0; - float i = 0.0; - - if (xPositive && absDir.x >= absDir.y && absDir.x >= absDir.z) { - maxAxis = absDir.x; - u = -dir.z; - v = dir.y; - i = 0.0; - } - if (!xPositive && absDir.x >= absDir.y && absDir.x >= absDir.z) { - maxAxis = absDir.x; - u = dir.z; - v = dir.y; - i = 1.0; - } - if (yPositive && absDir.y >= absDir.x && absDir.y >= absDir.z) { - maxAxis = absDir.y; - u = dir.x; - v = -dir.z; - i = 2.0; - } - if (!yPositive && absDir.y >= absDir.x && absDir.y >= absDir.z) { - maxAxis = absDir.y; - u = dir.x; - v = dir.z; - i = 3.0; - } - if (zPositive && absDir.z >= absDir.x && absDir.z >= absDir.y) { - maxAxis = absDir.z; - u = dir.x; - v = dir.y; - i = 4.0; - } - if (!zPositive && absDir.z >= absDir.x && absDir.z >= absDir.y) { - maxAxis = absDir.z; - u = -dir.x; - v = dir.y; - i = 5.0; - } - - u = i * WIDTH_SCALE + (u / maxAxis + 1.0) * WIDTH_SCALE_HALF; - v = (v / maxAxis + 1.0) * 0.5; - return vec2(u, v); - } - - void sampleDither(vec2 fragCoord) { - dither = (texture2D(_DitherTexture, (fragCoord - vec2(0.5)) / _DitherTextureSize).x - 0.5) * DITHER_STRENGTH; - } - - vec3 sampleSkybox(vec3 dir) { - vec3 viewDir = _SkyRotationMatrix * dir; - - float density = clamp(pow(1.0 - max(0.0, dot(dir, UP)) + dither, 2.0), 0.0, 1.0); - - float sunLight = dot(viewDir, UP); - float sun = min(pow(max(0.0, sunLight), SUN_SHARPNESS) * SUN_SIZE, 1.0); - - float moonLight = -sunLight; - float moon = min(pow(max(0.0, moonLight), MOON_SHARPNESS) * MOON_SIZE, 1.0); - - vec3 day = mix(DAY_SKY_COLOR, DAY_HORIZON_COLOR, density); - vec3 twilight = mix(LATE_TWILIGHT_COLOR, EARLY_TWILIGHT_COLOR, _TwilightTime); - vec3 night = mix(NIGHT_SKY_COLOR, NIGHT_HORIZON_COLOR, density); - - vec3 sky = mix(night, day, _SunVisibility); - sky = mix(sky, twilight, density * clamp(sunLight * 0.5 + 0.5 + dither, 0.0, 1.0) * _TwilightVisibility); - - vec2 cubeCoords = sampleCubeCoords(viewDir); - vec4 gridValue = texture2D(_Stars, cubeCoords); - - vec2 gridCoords = vec2(cubeCoords.x * _GridSizeScaled, cubeCoords.y * _GridSize); - vec2 gridCenterCoords = floor(gridCoords) + gridValue.xy; - float stars = max(min(pow(1.0 - min(distance(gridCoords, gridCenterCoords), 1.0), STARS_SHARPNESS) * gridValue.z * STARS_SIZE, 1.0), moon); - stars *= min(exp(-dot(sky, vec3(1.0)) * STARS_FALLOFF) * STARS_VISIBILITY, 1.0); - - sky = mix(sky, max(STARS_COLORS[int(gridValue.w * 6.0)], vec3(moon)), stars); - sky = mix(sky, vec3(1.0), sun); - - return sky; - } - - void main() { - sampleDither(gl_FragCoord.xy); - vec3 skyColor = sampleSkybox(normalize(vWorldDirection)); - gl_FragColor = vec4(skyColor, 1.0); - } - `}_update(e){this._initialized&&(this.timeOfDay+=e*2e-4,this.timeOfDay>1&&(this.timeOfDay=0),this.updateSkyboxPosition(),this.updateHorizonOffset(),this.calculateSunPosition(),this.updateVisibility(),this.updateShaderUniforms())}updateSkyboxPosition(){if(!this.skybox||!this.camera)return;this.skybox.position.copy(this.camera.position);const e=Math.max(this.baseSkyboxSize,this.camera.far*.8);Math.abs(this.skyboxSize-e)>1&&(this.skyboxSize=e,this.skybox.geometry&&(this.skybox.geometry.dispose(),this.skybox.geometry=new $(this.skyboxSize,32,32),this.skybox.geometry.scale(1,1,-1)))}updateHorizonOffset(){if(this.engine.systems.world&&this.camera)try{const e=this.engine.systems.world.getTerrainHeight(this.camera.position.x,this.camera.position.z);this.horizonOffset=e||0}catch(e){this.horizonOffset=0,y.warn("Could not get terrain height for horizon calculation:",e.message)}else this.horizonOffset=0}calculateSunPosition(){const e=this.timeOfDay*Math.PI*2,t=Math.sin(e-Math.PI),s=Math.PI/2.5,i=t*s,n=e-Math.PI,o=this.camera?Math.max(0,this.camera.position.y-this.horizonOffset):0,a=Math.min(o*.001,Math.PI/6),r=i-a,l=Math.cos(r);this.sunDirection.set(Math.sin(n)*l,Math.sin(r),Math.cos(n)*l);const c=-r,d=n+Math.PI,u=Math.cos(c);this.moonDirection.set(Math.sin(d)*u,Math.sin(c),Math.cos(d)*u)}updateVisibility(){const t=Math.asin(Math.max(-1,Math.min(1,this.sunDirection.y)))*180/Math.PI,s=-6;this.sunVisibility=Math.max(0,Math.min(1,(t-s)/10));const n=Math.asin(Math.max(-1,Math.min(1,this.moonDirection.y)))*180/Math.PI;this.moonVisibility=Math.max(0,Math.min(1,(n-s)/10)),this.twilightVisibility=0,t>-6&&t<6&&(this.twilightVisibility=1-Math.abs(t)/6)}updateSceneFog(){}updateShaderUniforms(){!this.skyboxMaterial||!this.skyboxMaterial.uniforms||this.skyboxMaterial.uniforms._TimeOfDay&&(this.skyboxMaterial.uniforms._TimeOfDay.value=this.timeOfDay)}setSkyboxUniforms(e){!e||!e.uniforms||(e.uniforms._SkyRotationMatrix={value:this.skyRotationMatrix},e.uniforms._SunVisibility={value:this.sunVisibility},e.uniforms._MoonVisibility={value:this.moonVisibility},e.uniforms._DirToLight={value:this.sunDirection},y.debug("Set skybox uniforms for material"))}createSimpleSkybox(){y.info("Creating dynamic skybox with horizon-based sun positioning...");try{const e=new $(this.skyboxSize,32,32);e.scale(1,1,-1),this.camera&&this.skybox.position.copy(this.camera.position),this.skyboxMaterial=new Xe({vertexShader:` - varying vec3 vWorldDirection; - void main() { - vec4 worldPosition = modelMatrix * vec4(position, 1.0); - - // Calculate direction from camera to vertex - vWorldDirection = normalize(position.xyz); - - gl_Position = projectionMatrix * viewMatrix * worldPosition; - } - `,fragmentShader:` - uniform float _TimeOfDay; - varying vec3 vWorldDirection; - - void main() { - // Calculate horizon factor (0 = horizon, 1 = zenith/nadir) - float horizonFactor = abs(vWorldDirection.y); - - // Sky colors for different times of day - vec3 skyColor; - vec3 horizonColor; - - if (_TimeOfDay < 0.25) { - // Night to dawn (0.0 - 0.25) - float t = _TimeOfDay / 0.25; - vec3 nightSky = vec3(0.02, 0.05, 0.15); - vec3 nightHorizon = vec3(0.05, 0.08, 0.2); - vec3 dawnSky = vec3(0.3, 0.4, 0.6); - vec3 dawnHorizon = vec3(0.8, 0.5, 0.3); - - skyColor = mix(nightSky, dawnSky, t); - horizonColor = mix(nightHorizon, dawnHorizon, t); - - } else if (_TimeOfDay < 0.75) { - // Day (0.25 - 0.75) - float t = (_TimeOfDay - 0.25) / 0.5; - vec3 dawnSky = vec3(0.3, 0.4, 0.6); - vec3 dawnHorizon = vec3(0.8, 0.5, 0.3); - vec3 daySky = vec3(0.4, 0.6, 0.9); - vec3 dayHorizon = vec3(0.7, 0.8, 0.95); - vec3 duskSky = vec3(0.3, 0.4, 0.6); - vec3 duskHorizon = vec3(0.9, 0.4, 0.2); - - if (t < 0.5) { - // Dawn to midday - float tt = t * 2.0; - skyColor = mix(dawnSky, daySky, tt); - horizonColor = mix(dawnHorizon, dayHorizon, tt); - } else { - // Midday to dusk - float tt = (t - 0.5) * 2.0; - skyColor = mix(daySky, duskSky, tt); - horizonColor = mix(dayHorizon, duskHorizon, tt); - } - - } else { - // Dusk to night (0.75 - 1.0) - float t = (_TimeOfDay - 0.75) / 0.25; - vec3 duskSky = vec3(0.3, 0.4, 0.6); - vec3 duskHorizon = vec3(0.9, 0.4, 0.2); - vec3 nightSky = vec3(0.02, 0.05, 0.15); - vec3 nightHorizon = vec3(0.05, 0.08, 0.2); - - skyColor = mix(duskSky, nightSky, t); - horizonColor = mix(duskHorizon, nightHorizon, t); - } - - // Blend between horizon and sky based on view angle - float blendFactor = pow(horizonFactor, 0.6); - vec3 finalColor = mix(horizonColor, skyColor, blendFactor); - - gl_FragColor = vec4(finalColor, 1.0); - } - `,side:fe,depthWrite:!1,depthTest:!0,fog:!1,uniforms:{_TimeOfDay:{value:.5}}}),this.skybox=new k(e,this.skyboxMaterial),this.skybox.renderOrder=-1,this.scene.add(this.skybox),y.info("Simple skybox created successfully")}catch(e){y.error("Failed to create simple skybox:",e),this.createBasicFallback()}}createBasicFallback(){y.warn("Creating ultra-basic fallback skybox...");const e=new $(this.skyboxSize,8,8);e.scale(1,1,-1);const t=new V({color:8900331,side:fe});this.skybox=new k(e,t),this.scene.add(this.skybox),y.info("Basic fallback skybox created")}createFallbackSkybox(){y.warn("Creating fallback skybox...");const e=new $(this.skyboxSize,16,16);e.scale(1,1,-1);const t=new Xe({vertexShader:` - varying vec3 vWorldDirection; - void main() { - vec4 worldPosition = modelMatrix * vec4(position, 1.0); - vWorldDirection = normalize(worldPosition.xyz - cameraPosition); - gl_Position = projectionMatrix * viewMatrix * worldPosition; - } - `,fragmentShader:` - varying vec3 vWorldDirection; - void main() { - float height = vWorldDirection.y * 0.5 + 0.5; - vec3 skyColor = mix(vec3(0.1, 0.3, 0.6), vec3(0.5, 0.7, 1.0), height); - gl_FragColor = vec4(skyColor, 1.0); - } - `,side:fe});this.skybox.geometry=e,this.skybox.material=t,this.scene.add(this.skybox),y.info("Fallback skybox created")}updateSkyRotation(){const e=this.timeOfDay*Math.PI*2,t=new ye().makeRotationZ(e);this.skyRotationMatrix.setFromMatrix4(t),this.skyboxMaterial&&this.skyboxMaterial.uniforms._SkyRotationMatrix&&(this.skyboxMaterial.uniforms._SkyRotationMatrix.value=this.skyRotationMatrix)}updateLighting(){const e=(this.timeOfDay-.5)*Math.PI;this.sunDirection.set(Math.sin(e),Math.cos(e),0),this.moonDirection.copy(this.sunDirection).multiplyScalar(-1),this.sunVisibility=Math.max(0,Math.cos(e)),this.moonVisibility=Math.max(0,-Math.cos(e));const t=.1,s=.4,i=.6;this.timeOfDay1&&(this.timeOfDay=0),this.updateSkyRotation(),this.updateLighting()}setTimeOfDay(e){this.timeOfDay=Math.max(0,Math.min(1,e)),this.updateSkyRotation(),this.updateLighting()}getSunDirection(){return this.sunDirection.clone()}getMoonDirection(){return this.moonDirection.clone()}dispose(){y.info("Disposing Skybox System..."),this.skybox&&(this.scene.remove(this.skybox),this.skybox.geometry&&this.skybox.geometry.dispose(),this.skybox.material&&this.skybox.material.dispose()),this.starsTexture&&this.starsTexture.dispose(),this.ditherTexture&&this.ditherTexture.dispose(),y.info("Skybox System disposed")}}class va extends U{constructor(e){super(e,"performanceBenchmark"),this.scene=e.scene,this.camera=e.camera,this.benchmarks={cssWater:{fps:[],memory:[],frameTime:[]},threeDWater:{fps:[],memory:[],frameTime:[]}},this.isBenchmarking=!1,this.currentMode="threeDWater",this.benchmarkDuration=1e4,this.benchmarkStartTime=0,this.frameCount=0,this.lastTime=0,this.fps=0,this.frameTime=0,this.memoryUsage=0,this.results=null}async _initialize(){y.info("📊 Initializing Performance Benchmark System..."),this.setupBenchmarkControls(),y.info("📊 Performance Benchmark System initialized ✅")}setupBenchmarkControls(){window.startBenchmark=()=>this.startBenchmark(),window.stopBenchmark=()=>this.stopBenchmark(),window.getBenchmarkResults=()=>this.getBenchmarkResults(),window.switchWaterMode=e=>this.switchWaterMode(e),y.debug("Benchmark controls added to window:"),y.debug("- startBenchmark(): Start performance benchmark"),y.debug("- stopBenchmark(): Stop current benchmark"),y.debug("- getBenchmarkResults(): Get benchmark results"),y.debug("- switchWaterMode('cssWater'|'threeDWater'): Switch water rendering mode")}startBenchmark(){if(this.isBenchmarking){y.warn("Benchmark already running");return}y.info("Starting performance benchmark..."),this.isBenchmarking=!0,this.benchmarkStartTime=performance.now(),this.frameCount=0,this.lastTime=this.benchmarkStartTime,this.resetBenchmarkData(),this.startPerformanceMonitoring()}stopBenchmark(){if(!this.isBenchmarking){y.warn("No benchmark running");return}y.info("Stopping performance benchmark..."),this.isBenchmarking=!1,this.calculateResults(),this.logResults()}resetBenchmarkData(){this.benchmarks.cssWater={fps:[],memory:[],frameTime:[]},this.benchmarks.threeDWater={fps:[],memory:[],frameTime:[]}}startPerformanceMonitoring(){this.monitorPerformance()}monitorPerformance(){if(!this.isBenchmarking)return;const e=performance.now(),t=e-this.lastTime;if(t>=1e3){this.fps=Math.round(this.frameCount*1e3/t),this.frameTime=t/this.frameCount,performance.memory&&(this.memoryUsage=performance.memory.usedJSHeapSize/1024/1024);const s=this.benchmarks[this.currentMode];s.fps.push(this.fps),s.frameTime.push(this.frameTime),this.memoryUsage>0&&s.memory.push(this.memoryUsage),this.frameCount=0,this.lastTime=e,y.debug(`Benchmark [${this.currentMode}]: FPS=${this.fps}, FrameTime=${this.frameTime.toFixed(2)}ms, Memory=${this.memoryUsage.toFixed(1)}MB`)}if(this.frameCount++,e-this.benchmarkStartTime>=this.benchmarkDuration){this.stopBenchmark();return}requestAnimationFrame(()=>this.monitorPerformance())}switchWaterMode(e){if(e!=="cssWater"&&e!=="threeDWater"){y.error("Invalid water mode. Use 'cssWater' or 'threeDWater'");return}y.info(`Switching to ${e} water rendering...`),this.currentMode=e,this.engine.systemManager.get("water")&&y.info(`Water system mode switched to: ${e}`)}calculateResults(){this.results={};for(const[e,t]of Object.entries(this.benchmarks))t.fps.length!==0&&(this.results[e]={averageFps:this.average(t.fps),minFps:Math.min(...t.fps),maxFps:Math.max(...t.fps),averageFrameTime:this.average(t.frameTime),averageMemory:t.memory.length>0?this.average(t.memory):0,sampleCount:t.fps.length})}average(e){return e.reduce((t,s)=>t+s,0)/e.length}logResults(){if(!this.results){y.warn("No benchmark results available");return}y.info("=== PERFORMANCE BENCHMARK RESULTS ===");for(const[e,t]of Object.entries(this.results))y.info(`${e.toUpperCase()} WATER:`),y.info(` Average FPS: ${t.averageFps.toFixed(1)}`),y.info(` FPS Range: ${t.minFps} - ${t.maxFps}`),y.info(` Average Frame Time: ${t.averageFrameTime.toFixed(2)}ms`),y.info(` Average Memory: ${t.averageMemory.toFixed(1)}MB`),y.info(` Samples: ${t.sampleCount}`),y.info("");if(this.results.cssWater&&this.results.threeDWater){const e=this.results.cssWater.averageFps,s=this.results.threeDWater.averageFps-e,i=s/e*100;y.info("COMPARISON:"),y.info(` FPS Difference: ${s>0?"+":""}${s.toFixed(1)} (${i>0?"+":""}${i.toFixed(1)}%)`),y.info(` Winner: ${s>0?"3D Water":s<0?"CSS Water":"Tie"}`)}y.info("===================================")}getBenchmarkResults(){return{isRunning:this.isBenchmarking,currentMode:this.currentMode,results:this.results,currentMetrics:{fps:this.fps,frameTime:this.frameTime,memoryUsage:this.memoryUsage}}}_update(e){}dispose(){y.info("Disposing Performance Benchmark System..."),this.stopBenchmark(),y.info("Performance Benchmark System disposed")}}class Ma extends U{constructor(e){super(e,"carpetTrail"),this.scene=e.scene,this.maxPoints=60,this.contrailLifespan=3,this.minSpeedForEmission=8,this.emissionInterval=.05,this.timeSinceLastEmission=0,this.minStyleSpeed=8,this.maxStyleSpeed=250,this.minHalfWidth=.45,this.maxHalfWidth=1.5,this.minBrightness=.3,this.headColor=new C(1,.8,.3),this.tailColor=new C(.8,.18,.85),this.boostColor=new C(1,.97,.9),this.points=new Array(this.maxPoints);for(let t=0;tthis.minSpeedForEmission;a&&this.timeSinceLastEmission>=this.emissionInterval&&(this.addPoint(i,n),this.timeSinceLastEmission=0),this.cleanupOldPoints(),this._liveActive=a&&this.count>0,this._liveActive&&this.computePoint(this._livePoint,i,n),this.updateTrailGeometry()}computePoint(e,t,s){const i=t.bankAngle||0;this._emitEuler.set(t.rotation.x,t.rotation.y,(t.rotation.z||0)+i,"YXZ"),this._center.set(0,-.2,-this.carpetLength/2),this._center.applyEuler(this._emitEuler),this._center.add(t.position),this._right.set(1,0,0),this._right.applyEuler(this._emitEuler);let n=(s-this.minStyleSpeed)/(this.maxStyleSpeed-this.minStyleSpeed);n<0?n=0:n>1&&(n=1);const o=this._boostGlow;e.x=this._center.x,e.y=this._center.y,e.z=this._center.z,e.rx=this._right.x,e.ry=this._right.y,e.rz=this._right.z,e.halfWidth=(this.minHalfWidth+(this.maxHalfWidth-this.minHalfWidth)*n)*(1+.25*o),e.brightness=(this.minBrightness+(1-this.minBrightness)*n)*(1+.5*o),e.boost=o,e.timestamp=performance.now()/1e3}addPoint(e,t){let s;this.count0&&e-this.points[this.head].timestamp>this.contrailLifespan;)this.head=(this.head+1)%this.maxPoints,this.count--}updateTrailGeometry(){const e=this.count+(this._liveActive?1:0);if(e<2){this.geometry.setDrawRange(0,0);return}const t=performance.now()/1e3;for(let s=0;s1&&(n=1);const o=t.halfWidth*(.3+.7*n),a=this.positions,r=this.colors,l=e*6;a[l]=t.x-t.rx*o,a[l+1]=t.y-t.ry*o,a[l+2]=t.z-t.rz*o,a[l+3]=t.x+t.rx*o,a[l+4]=t.y+t.ry*o,a[l+5]=t.z+t.rz*o;const c=1-n;let d=this.headColor.r+(this.tailColor.r-this.headColor.r)*c,u=this.headColor.g+(this.tailColor.g-this.headColor.g)*c,m=this.headColor.b+(this.tailColor.b-this.headColor.b)*c;if(t.boost>0){const g=.6*t.boost;d+=(this.boostColor.r-d)*g,u+=(this.boostColor.g-u)*g,m+=(this.boostColor.b-m)*g}const f=n*n*t.brightness*(1+.35*this._boostGlow);d*=f,u*=f,m*=f,r[l]=d,r[l+1]=u,r[l+2]=m,r[l+3]=d,r[l+4]=u,r[l+5]=m}setSpaceBarState(e){this.spaceBarPressed=e}resetTrail(){this.head=0,this.count=0,this._liveActive=!1,this.timeSinceLastEmission=0,this.geometry&&this.geometry.setDrawRange(0,0)}handleVisibilityChange(e){e&&this.resetTrail()}destroy(){this.resetTrail(),this.trailMesh&&(this.scene.remove(this.trailMesh),this.trailMesh=null),this.geometry&&(this.geometry.dispose(),this.geometry=null),this.trailMaterial&&(this.trailMaterial.dispose(),this.trailMaterial=null)}}class _a extends U{constructor(e){super(e,"landmarks"),this.scene=e.scene,this.worldSystem=null,this.landmarks=new Map,this.landmarkTypes=[{name:"ancient_ruins",minHeight:5,maxHeight:100,minDistance:800,maxSlope:.3,frequency:2e-5,size:{min:200,max:400},requiresWater:!1},{name:"magical_circle",minHeight:0,maxHeight:120,minDistance:600,maxSlope:.4,frequency:4e-4,size:{min:60,max:120},requiresWater:!1},{name:"crystal_formation",minHeight:20,maxHeight:150,minDistance:900,maxSlope:.8,frequency:3e-4,size:{min:80,max:160},requiresWater:!1}],this.materials={stone:new R({color:10066329,roughness:.8,metalness:.1}),ruinedStone:new R({color:7829367,roughness:.9,metalness:.05}),crystal:new R({color:8939263,emissive:6702250,emissiveIntensity:.5,transparent:!0,opacity:.9,roughness:.2,metalness:.8}),magicCircle:new R({color:13395711,emissive:13395711,emissiveIntensity:.8,transparent:!0,opacity:.7})},this.beaconColors={ancient_ruins:16764006,magical_circle:13395711,crystal_formation:6750190},this.beaconGeometry=new Z(2.5,4,300,8,1,!0),this.beaconMaterials={};for(const[t,s]of Object.entries(this.beaconColors))this.beaconMaterials[t]=new V({color:s,transparent:!0,opacity:.22,depthWrite:!1,blending:De,side:pe,fog:!1})}async _initialize(){y.info("LandmarkSystem._initialize: Initializing landmark materials and configuration"),y.info("LandmarkSystem: Landmark types configured:",this.landmarkTypes.map(e=>e.name))}_update(e,t){this.checkForLandmarkLocations(),this.animateLandmarks(t);const s=this.engine.systems.player?.localPlayer;if(s&&s.position&&this.worldSystem){if(isNaN(s.position.x)||isNaN(s.position.z))return;const i=this.worldSystem.chunkSize*(this.worldSystem.viewDistance+4);for(const[n,o]of this.landmarks.entries()){if(!o.position||isNaN(o.position.x)||isNaN(o.position.z)){o.mesh&&this.scene.remove(o.mesh),this.landmarks.delete(n);continue}const a=o.position.x-s.position.x,r=o.position.z-s.position.z;a*a+r*r>i*i&&(this.scene.remove(o.mesh),this.landmarks.delete(n))}}}isPositionSuitableForLandmark(e,t,s){if(!this.worldSystem&&(this.worldSystem=this.engine.systems.world||this.engine.systemManager.get("world"),!this.worldSystem))return!1;const i=this.worldSystem.getTerrainHeight(e,t);if(is.maxHeight||this.worldSystem.calculateSlope(e,t)>s.maxSlope)return!1;for(const[o,a]of this.landmarks.entries())if(a.type===s.name){const r=a.position.x-e,l=a.position.z-t;if(Math.sqrt(r*r+l*l).6,p=new Z(t*.05,t*.06,f,8),b=new k(p,g?this.materials.stone:this.materials.ruinedStone);if(b.position.set(u,f*.5,m),b.castShadow=!0,b.receiveShadow=!0,b.rotation.y=Math.random()*.2,!g){const S=Math.random()*.3,x=Math.random()*Math.PI*2;b.rotation.x=Math.cos(x)*S,b.rotation.z=Math.sin(x)*S}if(e.add(b),Math.random()>.5){const S=Math.floor(Math.random()*3)+1;for(let x=0;x.05)return;const t=Math.floor(e.position.x/this.worldSystem.chunkSize),s=Math.floor(e.position.z/this.worldSystem.chunkSize),i=this.worldSystem.viewDistance+2,n=5;for(let o=0;o.4)){for(const m of this.landmarkTypes)if(!(Math.random()>m.frequency*1e3)&&this.isPositionSuitableForLandmark(d,u,m)){y.info(`[LandmarkSystem] Creating ${m.name} landmark at ${d.toFixed(2)}, ${u.toFixed(2)}`),this.createLandmark(d,u,m)?y.info(`[LandmarkSystem] Successfully created landmark, total count: ${this.landmarks.size}`):y.warn("[LandmarkSystem] Failed to create landmark");return}}}}catch(e){y.error("Error checking for landmark locations:",e)}}animateLandmarks(e){for(const[t,s]of this.landmarks.entries()){const i=s.mesh;if(!(!i||!i.parent)){if(s.beacon){const n=.85+.15*Math.sin(e*.8+s.beaconPhase);s.beacon.scale.set(n,1,n)}i.traverse(n=>{if(n.userData&&n.userData.isGlowing){const o=n.userData.pulseRate||1,r=(n.userData.originalIntensity||.5)*(.7+Math.sin(e*o)*.3);n.material&&n.material.emissiveIntensity!==void 0&&(n.material.emissiveIntensity=r)}})}}}handleVisibilityChange(e){e&&this.cleanupInvalidLandmarks()}cleanupInvalidLandmarks(){for(const[e,t]of this.landmarks.entries()){const s=t.position;(!s||isNaN(s.x)||isNaN(s.y)||isNaN(s.z))&&(y.debug(`Removing invalid landmark: ${e}`),t.mesh&&this.scene.remove(t.mesh),this.landmarks.delete(e))}}}class Ta extends U{constructor(e){super(e,"minimap"),this.canvas=null,this.context=null,this.size=150,this.range=2e4,this.minimapContainer=null,this.lastUpdate=0,this.updateInterval=1/60,this.enabled=!0,this.colors={water:"rgba(0, 100, 200, 0.8)",mountain:"rgba(100, 100, 100, 0.8)",forest:"rgba(0, 100, 0, 0.8)",desert:"rgba(200, 180, 120, 0.8)",plains:"rgba(0, 170, 0, 0.8)",snow:"rgba(240, 240, 250, 0.8)",landmark:{ancient_ruins:"rgba(200, 180, 100, 0.9)",magical_circle:"rgba(180, 50, 180, 0.9)",crystal_formation:"rgba(100, 220, 220, 0.9)",default:"rgba(255, 255, 255, 0.8)"},mana:"rgba(50, 150, 255, 0.8)",player:"rgba(255, 255, 255, 1)",otherPlayer:"rgba(255, 100, 100, 1)",background:"rgba(0, 0, 20, 0.5)",border:"rgba(255, 255, 255, 0.5)",direction:"white",playerNames:!0}}async initialize(){y.info("MinimapSystem disabled - using UISystem for minimap rendering"),this.enabled=!1,this.initialized=!0}createContainer(){}worldToMap(e,t){return{x:0,z:0}}clear(){}drawTerrain(){}drawLandmarks(){}drawMana(){}drawPlayers(){}drawPlayerOffMap(e,t){}drawCompassRose(){}enable(){}disable(){}update(e,t){}}class ka extends U{constructor(e){super(e,"ambientLife"),this.scene=e.scene,this.camera=e.camera,this.birds=[],this.birdCount=30,this.birdSpread=1500,this.birdHeight=150,this.butterflies=[],this.butterflyCount=20,this.butterflySpread=500}async _initialize(){y.info("🐦 Initializing Ambient Life System..."),this.createBirds(),this.createButterflies(),y.info("🐦 Ambient Life System initialized ✅")}createBirds(){const e=document.createElement("canvas");e.width=64,e.height=64;const t=e.getContext("2d");t.fillStyle="rgba(50, 50, 50, 1.0)",t.beginPath(),t.moveTo(32,28),t.lineTo(8,36),t.lineTo(32,32),t.lineTo(56,36),t.lineTo(32,28),t.closePath(),t.fill();const s=new Le(e),i=new mt({map:s,transparent:!0,opacity:1,depthTest:!0,depthWrite:!1}),n=this.camera.position;for(let o=0;o2500){const l=Math.random()*Math.PI*2,c=800+Math.random()*500;i.position.set(s.x+c*Math.cos(l),n.heightPreference,s.z+c*Math.sin(l))}}for(const i of this.butterflies){const n=i.userData;n.flutterPhase+=t*n.flutterSpeed,Math.sin(n.flutterPhase*15),n.velocity.x+=Math.sin(n.flutterPhase)*.5,n.velocity.z+=Math.cos(n.flutterPhase*1.3)*.5;const o=n.heightPreference-i.position.y;if(n.velocity.y=o*.05,n.velocity.multiplyScalar(.95),i.position.add(n.velocity.clone().multiplyScalar(t)),i.position.distanceTo(s)>1e3){const r=Math.random()*Math.PI*2,l=200+Math.random()*300;i.position.set(s.x+l*Math.cos(r),n.heightPreference,s.z+l*Math.sin(r))}}}_destroy(){for(const e of this.birds)this.scene.remove(e),e.material.dispose();this.birds=[];for(const e of this.butterflies)this.scene.remove(e),e.material.dispose();this.butterflies=[],y.info("Ambient Life System destroyed")}}class Aa extends U{constructor(e){super(e,"proceduralAudio"),this.context=null,this.masterGain=null,this.noiseBuffer=null,this.windSource=null,this.windFilter=null,this.windGain=null,this.windFilter2=null,this.windGain2=null,this.masterVolume=.5,this.muted=!1,this.WIND_MIN_SPEED=20,this.WIND_MAX_SPEED=250,this.WIND_MAX_GAIN=.12,this.WIND_FREQ_MIN=300,this.WIND_FREQ_MAX=1100,this.WIND_SMOOTHING=.15,this.supported=typeof window<"u"&&!!(window.AudioContext||window.webkitAudioContext),this._gestureHandler=null,this._onManaCollected=null,this._onSpellCast=null,this._suspendedByVisibility=!1}async _initialize(){if(!this.supported){y.warn("ProceduralAudioSystem: WebAudio not supported - audio disabled");return}this._gestureHandler=this._onFirstGesture.bind(this),window.addEventListener("pointerdown",this._gestureHandler,{passive:!0}),window.addEventListener("keydown",this._gestureHandler,{passive:!0});const e=this.engine?this.engine.eventBus:null;e&&typeof e.on=="function"?(this._onManaCollected=()=>this._playChime(),this._onSpellCast=()=>this._playWhoosh(),e.on("manaCollected",this._onManaCollected),e.on("spellCast",this._onSpellCast)):y.warn("ProceduralAudioSystem: engine.eventBus unavailable - event sounds disabled")}_onFirstGesture(){if(this._removeGestureListeners(),!(!this.supported||this.context))try{const e=window.AudioContext||window.webkitAudioContext;this.context=new e,this._buildGraph(),this.context.state==="suspended"&&this.context.resume().catch(()=>{})}catch(e){y.warn("ProceduralAudioSystem: failed to create AudioContext - audio disabled",e),this.context=null}}_removeGestureListeners(){this._gestureHandler&&(window.removeEventListener("pointerdown",this._gestureHandler),window.removeEventListener("keydown",this._gestureHandler),this._gestureHandler=null)}handleVisibilityChange(e){const t=this.context;t&&(e?this._suspendedByVisibility&&t.state==="suspended"&&(this._suspendedByVisibility=!1,t.resume().catch(()=>{})):t.state==="running"&&(this._suspendedByVisibility=!0,t.suspend().catch(()=>{})))}_buildGraph(){const e=this.context;e&&(this.masterGain=e.createGain(),this.masterGain.gain.value=this.muted?0:this.masterVolume,this.masterGain.connect(e.destination),this.noiseBuffer=this._createNoiseBuffer(2),this.windSource=e.createBufferSource(),this.windSource.buffer=this.noiseBuffer,this.windSource.loop=!0,this.windFilter=e.createBiquadFilter(),this.windFilter.type="bandpass",this.windFilter.frequency.value=this.WIND_FREQ_MIN,this.windFilter.Q.value=.9,this.windGain=e.createGain(),this.windGain.gain.value=0,this.windFilter2=e.createBiquadFilter(),this.windFilter2.type="bandpass",this.windFilter2.frequency.value=this.WIND_FREQ_MIN*.55,this.windFilter2.Q.value=1.4,this.windGain2=e.createGain(),this.windGain2.gain.value=0,this.windSource.connect(this.windFilter),this.windFilter.connect(this.windGain),this.windGain.connect(this.masterGain),this.windSource.connect(this.windFilter2),this.windFilter2.connect(this.windGain2),this.windGain2.connect(this.masterGain),this.windSource.start())}_createNoiseBuffer(e){const t=this.context,s=Math.max(1,Math.floor(t.sampleRate*e)),i=t.createBuffer(1,s,t.sampleRate),n=i.getChannelData(0);for(let o=0;o{try{o.disconnect(),a.disconnect()}catch{}}}_playWhoosh(){const e=this.context;if(!e||e.state!=="running"||!this.masterGain||!this.noiseBuffer)return;const t=e.currentTime,s=.6,i=e.createBufferSource();i.buffer=this.noiseBuffer;const n=e.createBiquadFilter();n.type="bandpass",n.Q.value=1.2,n.frequency.setValueAtTime(400,t),n.frequency.exponentialRampToValueAtTime(2e3,t+s*.75);const o=e.createGain();o.gain.setValueAtTime(1e-4,t),o.gain.exponentialRampToValueAtTime(.3,t+s*.35),o.gain.exponentialRampToValueAtTime(1e-4,t+s),i.connect(n),n.connect(o),o.connect(this.masterGain),i.start(t),i.stop(t+s+.05),i.onended=()=>{try{i.disconnect(),n.disconnect(),o.disconnect()}catch{}}}setMuted(e){this.muted=!!e,this._applyMasterVolume()}setVolume(e){this.masterVolume=Math.min(Math.max(Number(e)||0,0),1),this._applyMasterVolume()}_applyMasterVolume(){if(!this.context||!this.masterGain)return;const e=this.muted?0:this.masterVolume;this.masterGain.gain.setTargetAtTime(e,this.context.currentTime,.05)}destroy(){this._removeGestureListeners();const e=this.engine?this.engine.eventBus:null;if(e&&typeof e.off=="function"&&(this._onManaCollected&&e.off("manaCollected",this._onManaCollected),this._onSpellCast&&e.off("spellCast",this._onSpellCast)),this._onManaCollected=null,this._onSpellCast=null,this.windSource){try{this.windSource.stop()}catch{}this.windSource=null}if(this.context){try{this.context.close().catch(()=>{})}catch{}this.context=null}this.masterGain=null,this.noiseBuffer=null,this.windFilter=null,this.windGain=null,this.windFilter2=null,this.windGain2=null,super.destroy()}}class Ca extends U{constructor(e){super(e,"proceduralMusic"),this.supported=typeof window<"u"&&!!(window.AudioContext||window.webkitAudioContext),this.context=null,this.masterGain=null,this.reverbGain=null,this.reverb=null,this.muted=!1,this.masterVolume=.35,this.reverbSend=.45,this.intensityOverride=null,this.baseTempo=75,this.maxTempo=112,this.currentTempo=this.baseTempo,this.targetTempo=this.baseTempo,this.tempoSmoothing=.08,this.isPlaying=!1,this.nextPhraseTime=0,this.phraseCount=0,this.beatDuration=60/this.baseTempo,this.phraseBeats=16,this.lookahead=.5,this.scheduleAheadTime=.15,this.scale=[0,2,3,5,7,8,11],this.rootNote=40,this.whistleMotifs=[{degrees:[0,2,4,2,0],rhythm:[1,1,2,1,1]},{degrees:[4,3,2,0],rhythm:[1.5,.5,1,1]},{degrees:[0,0,4,2,3,2],rhythm:[.5,.5,1,.5,1,.5]},{degrees:[6,4,2,0],rhythm:[2,1,1,2]}],this.guitarMotifs=[{degrees:[0,4],rhythm:[2,2]},{degrees:[0,3,4],rhythm:[1,1,2]},{degrees:[4,2,0],rhythm:[1,1,2]},{degrees:[0],rhythm:[4]}],this.brassMotifs=[{degrees:[0,4],rhythm:[2,2]},{degrees:[4,0],rhythm:[1,3]},{degrees:[0],rhythm:[4]}],this._gestureHandler=null,this._onGameStarted=null,this._suspendedByVisibility=!1,this._gameStarted=!1}async _initialize(){if(!this.supported){y.warn("ProceduralMusicSystem: WebAudio not supported - music disabled");return}this._gestureHandler=this._onFirstGesture.bind(this),window.addEventListener("pointerdown",this._gestureHandler,{passive:!0}),window.addEventListener("keydown",this._gestureHandler,{passive:!0});const e=this.engine?this.engine.eventBus:null;e&&typeof e.on=="function"?(this._onGameStarted=()=>{this._gameStarted=!0,this._startMusic()},e.on("gameStarted",this._onGameStarted)):y.warn("ProceduralMusicSystem: engine.eventBus unavailable - music will not auto-start")}_onFirstGesture(){if(this._removeGestureListeners(),!(!this.supported||this.context))try{const e=window.AudioContext||window.webkitAudioContext;this.context=new e,this._buildGraph(),this.context.state==="suspended"&&this.context.resume().catch(()=>{}),this._gameStarted&&this._startMusic()}catch(e){y.warn("ProceduralMusicSystem: failed to create AudioContext - music disabled",e),this.context=null}}_removeGestureListeners(){this._gestureHandler&&(window.removeEventListener("pointerdown",this._gestureHandler),window.removeEventListener("keydown",this._gestureHandler),this._gestureHandler=null)}handleVisibilityChange(e){const t=this.context;t&&(e?this._suspendedByVisibility&&t.state==="suspended"&&(this._suspendedByVisibility=!1,t.resume().catch(()=>{})):t.state==="running"&&(this._suspendedByVisibility=!0,t.suspend().catch(()=>{})))}_buildGraph(){const e=this.context;e&&(this.masterGain=e.createGain(),this.masterGain.gain.value=this.muted?0:this.masterVolume,this.masterGain.connect(e.destination),this.reverb=this._buildReverb(),this.reverbGain=e.createGain(),this.reverbGain.gain.value=this.reverbSend,this.reverb.output.connect(this.reverbGain),this.reverbGain.connect(this.masterGain))}_buildReverb(){const e=this.context,t=e.createGain(),s=e.createGain(),i=[.037,.051,.073,.097,.121],n=[];i.forEach(a=>{const r=e.createDelay(.5);r.delayTime.value=a;const l=e.createGain();l.gain.value=.35,t.connect(r),r.connect(l),l.connect(s),n.push({delay:r,gain:l})});const o=e.createGain();return o.gain.value=.25,s.connect(o),n.forEach(a=>{o.connect(a.delay)}),{input:t,output:s}}_reverbInput(){const t=this.context.createGain();return t.gain.value=1,t.connect(this.reverb.input),t}_startMusic(){!this.context||this.isPlaying||(this.context.state==="suspended"&&this.context.resume().catch(()=>{}),this.isPlaying=!0,this.nextPhraseTime=this.context.currentTime+.5,this.phraseCount=0,y.info("ProceduralMusicSystem: music started"))}_stopMusic(){this.isPlaying=!1}_update(e,t){const s=this.context;if(!s||s.state!=="running"||!this.isPlaying)return;const i=this._getIntensity();for(this.targetTempo=this.baseTempo+i*(this.maxTempo-this.baseTempo),this.currentTempo+=(this.targetTempo-this.currentTempo)*(1-Math.exp(-e/this.tempoSmoothing)),this.beatDuration=60/this.currentTempo;this.nextPhraseTime.75)&&(i*=.7),i}_schedulePhrase(e,t){const s=this.beatDuration;e+this.phraseBeats*s,this._playDrone(e,this.phraseBeats*s);const i=Math.random()<.85,n=t>.35&&Math.random()<.55,o=t>.5&&Math.random()<.6;{const a=this._pick(this.whistleMotifs),r=Math.random()<.5?0:8;this._scheduleMotif(a,e+r*s,s,"whistle")}if(i){const a=this._pick(this.guitarMotifs);if(this._scheduleMotif(a,e,s,"guitar"),Math.random()<.4){const r=this._pick(this.guitarMotifs);this._scheduleMotif(r,e+8*s,s,"guitar")}}if(n){const a=this._pick(this.brassMotifs),r=Math.floor(Math.random()*8)*s;if(this._scheduleMotif(a,e+r,s,"brass"),t>.7&&Math.random()<.5){const l=this._pick(this.brassMotifs);this._scheduleMotif(l,e+(r+8*s)%(this.phraseBeats*s),s,"brass")}}o&&(this._playPercussion("timpani",e),this._playPercussion("timpani",e+8*s),t>.75&&(this._playPercussion("rimshot",e+2*s),this._playPercussion("rimshot",e+10*s))),this.phraseCount%4===3&&this._playPadSwell(e+12*s,4*s)}_scheduleMotif(e,t,s,i){let n=0;for(let o=0;o{const o=this._degreeToFreq(n,1),a=s.createOscillator();a.type="triangle",a.frequency.value=o;const r=s.createGain();r.gain.setValueAtTime(1e-4,e),r.gain.linearRampToValueAtTime(.06,e+t*.5),r.gain.linearRampToValueAtTime(1e-4,e+t);const l=this._reverbInput();a.connect(r),r.connect(this.masterGain),r.connect(l),a.start(e),a.stop(e+t+.2),this._autoDisconnect(a,[r,l])})}_degreeToFreq(e,t=0){const s=this.scale[(e%this.scale.length+this.scale.length)%this.scale.length],i=Math.floor(e/this.scale.length),n=this.rootNote+(i+t)*12+s;return 440*Math.pow(2,(n-69)/12)}_pick(e){return e[Math.floor(Math.random()*e.length)]}_autoDisconnect(e,t){e.onended=()=>{try{t.forEach(s=>s.disconnect())}catch{}}}setMuted(e){this.muted=!!e,this._applyMasterVolume()}setVolume(e){this.masterVolume=Math.min(Math.max(Number(e)||0,0),1),this._applyMasterVolume()}setIntensity(e){this.intensityOverride=e===null?null:Math.min(Math.max(Number(e),0),1)}_applyMasterVolume(){if(!this.context||!this.masterGain)return;const e=this.muted?0:this.masterVolume;this.masterGain.gain.setTargetAtTime(e,this.context.currentTime,.05)}destroy(){this._removeGestureListeners();const e=this.engine?this.engine.eventBus:null;if(e&&typeof e.off=="function"&&this._onGameStarted&&e.off("gameStarted",this._onGameStarted),this._onGameStarted=null,this._stopMusic(),this.context){try{this.context.close().catch(()=>{})}catch{}this.context=null}this.masterGain=null,this.reverbGain=null,this.reverb=null,super.destroy()}}const Ds=[100,300,500,700,900],_e=64,ue={actionHz:[1,20],observationHz:[1,20],observationLatencyMs:[0,1e3],manaRadius:[0,800],landmarkRadius:[0,2e3]};class Ea extends U{constructor(e){super(e,"agentAPI"),this.config={actionHz:10,observationHz:20,observationLatencyMs:0,perceptionRadius:{mana:800,landmarks:2e3}},this._gameTime=0,this._tick=0,this._obsAccumulator=0,this._actAccumulator=0,this._pendingAction=null,this._ring=new Array(_e);for(let t=0;t<_e;t++)this._ring[t]={t:0,snap:null};this._ringHead=0,this._ringCount=0,this._api=null,this._onMessage=null,this._ws=null,this._wsUrl=null,this._wsRetries=0,this._wsStatus="disconnected"}async _initialize(){const e={observe:this.observe.bind(this),act:this.act.bind(this),release:this.release.bind(this),startRace:this.startRace.bind(this),abortRace:this.abortRace.bind(this),listReplays:this.listReplays.bind(this),getLatestReplay:this.getLatestReplay.bind(this),getBestReplay:this.getBestReplay.bind(this),loadGhost:this.loadGhost.bind(this),clearGhost:this.clearGhost.bind(this),exportResult:this.exportResult.bind(this),setConfig:this.setConfig.bind(this),getConfig:this.getConfig.bind(this),connectAgent:this.connectAgent.bind(this),disconnectAgent:this.disconnectAgent.bind(this),transportStatus:()=>this._wsStatus,meta:{version:1,fairness:"information/action/tempo parity; act 10Hz hold-last; observe 20Hz + latency"}};if(Object.freeze(e.meta),Object.freeze(e),this._api=e,typeof window<"u"){window.agentAPI=e,this._onMessage=t=>{try{const s=t&&t.data;if(!s||typeof s!="object"||typeof s.type!="string")return;if(s.type==="agentapi:observe"){const n={type:"agentapi:observation",payload:this.observe()},o=t.source;if(o&&typeof o.postMessage=="function")try{o.postMessage(n,"*")}catch{try{window.postMessage(n,"*")}catch{}}else try{window.postMessage(n,"*")}catch{}}else s.type==="agentapi:act"?this.act(s.payload):s.type==="agentapi:start-race"&&this.startRace(s.seed)}catch{}},window.addEventListener("message",this._onMessage);try{const t=new URLSearchParams(window.location.search).get("agent");t&&this.connectAgent(t)}catch{}}y.info("AgentAPISystem initialized — window.agentAPI is live")}_update(e,t){if(!(!Number.isFinite(e)||e<=0)){this._gameTime+=e;try{const s=1/this.config.actionHz;this._actAccumulator+=e,this._actAccumulator>=s&&(this._actAccumulator%=s,this._applyPendingAction())}catch{}try{const s=1/this.config.observationHz;this._obsAccumulator+=e,this._obsAccumulator>=s&&(this._obsAccumulator%=s,this._captureSnapshot(),this._streamObservation())}catch{}}}connectAgent(e){return typeof e!="string"||!/^wss?:\/\//.test(e)?!1:(this.disconnectAgent(),this._wsUrl=e,this._wsRetries=0,this._openTransport(),!0)}disconnectAgent(){if(this._wsUrl=null,this._ws){try{this._ws.close()}catch{}this._ws=null}this._wsStatus="disconnected",this.release()}_openTransport(){try{this._wsStatus="connecting";const e=new WebSocket(this._wsUrl);this._ws=e,e.onopen=()=>{this._wsStatus="connected",this._wsRetries=0;try{e.send(JSON.stringify({type:"hello",payload:{game:"vibe-carpet",config:this.getConfig()}}))}catch{}},e.onmessage=t=>this._handleTransportMessage(t),e.onclose=()=>this._onTransportClosed(e),e.onerror=()=>{}}catch{this._wsStatus="error"}}_onTransportClosed(e){this._ws===e&&(this._ws=null,this.release(),this._wsUrl&&this._wsRetries<3?(this._wsRetries++,this._wsStatus="reconnecting",setTimeout(()=>{this._wsUrl&&!this._ws&&this._openTransport()},2e3)):this._wsStatus="disconnected")}_streamObservation(){const e=this._ws;if(!(!e||e.readyState!==1))try{const t=this.observe();t&&e.send(JSON.stringify({type:"observation",payload:t}))}catch{}}_handleTransportMessage(e){try{const t=JSON.parse(e.data);if(!t||typeof t.type!="string")return;t.type==="act"?this.act(t.payload):t.type==="release"?this.release():t.type==="start-race"?this.startRace(t.seed):t.type==="config"&&this.setConfig(t.payload||{})}catch{}}observe(){try{const e=this.config.observationLatencyMs/1e3;let t=null,s=null;for(let n=0;n=e)){t=a;break}}const i=t||s;return i?JSON.parse(JSON.stringify(i.snap)):null}catch{return null}}_captureSnapshot(){const e=this._getSystem("playerState"),t=e?e.localPlayer:null;if(!t||!t.position||!t.velocity||!t.rotation)return;const s=this.config,i=this._getSystem("world"),n=!!(i&&typeof i.getTerrainHeight=="function"),o=this._num(t.position.x),a=this._num(t.position.y),r=this._num(t.position.z),l=this._num(t.velocity.x),c=this._num(t.velocity.y),d=this._num(t.velocity.z),u=Math.sqrt(l*l+c*c+d*d),m=this._num(t.rotation.y),f=this._num(t.rotation.x),g=Math.sin(m),p=Math.cos(m),b=this._getSystem("playerInput"),S=b?this._num(b.currentThrottle):0,x=this._getSystem("playerPhysics"),w=x?this._num(x.maxAltitude,null):null,v=n?this._num(i.getTerrainHeight(o,r),null):null,M=[];for(let q=0;qB.distSq-H.distSq);const z=Math.min(10,q.length);for(let B=0;B{if(!z||!z.position)return;const B=this._num(z.position.x),H=this._num(z.position.y),se=this._num(z.position.z),te=B-o,ae=H-a,he=se-r,He=te*te+ae*ae+he*he;He>q||F.push({type:typeof z.type=="string"?z.type:"unknown",pos:[B,H,se],dist:Math.sqrt(He),bearing:this._bearing(te,he,g,p)})}),F.sort((z,B)=>z.dist-B.dist)}const oe=this._num(t.maxSpeed),J={version:1,t:this._gameTime,tick:this._tick++,self:{pos:[o,a,r],vel:[l,c,d],speed:u,heading:m,pitch:f,bank:this._num(t.bankAngle),throttle:S,altitude:a,altitudeAboveTerrain:v===null?null:a-v,mana:this._num(t.mana),totalMana:this._num(t.totalMana),currentSpell:this._num(t.currentSpell,0),effects:P},limits:{maxSpeed:oe,boostedMaxSpeed:oe*1.5,ceiling:w,turnRate:b?this._num(b.turnRate,1.6):1.6,actionHz:s.actionHz,observationHz:s.observationHz},terrain:{below:v,ahead:M},race:N,nearby:{manaNodes:D,landmarks:F}},Ce=this._ring[this._ringHead];Ce.t=this._gameTime,Ce.snap=J,this._ringHead=(this._ringHead+1)%_e,this._ringCount<_e&&this._ringCount++}act(e){try{if(!e||typeof e!="object")return!1;const t={};let s=!1;const i=this._sanitizeAxis(e.throttle,0,1);i!==null&&(t.throttle=i,s=!0);const n=this._sanitizeAxis(e.brake,0,1);n!==null&&(t.brake=n,s=!0);const o=this._sanitizeAxis(e.turn,-1,1);o!==null&&(t.turn=o,s=!0);const a=this._sanitizeAxis(e.climb,-1,1);a!==null&&(t.climb=a,s=!0);let r=null;if(e.selectSpell!==void 0){const l=this._sanitizeAxis(e.selectSpell,0,3);l!==null&&(r=Math.round(l))}return this._pendingAction={pad:s?t:null,selectSpell:r,cast:!!e.cast},this._emitActionQueued(this._pendingAction),!0}catch{return!1}}release(){try{this._pendingAction=null;const e=this._getSystem("playerInput");e&&typeof e.clearVirtualPad=="function"&&e.clearVirtualPad()}catch{}}_applyPendingAction(){const e=this._pendingAction;if(e){if(this._pendingAction=null,e.pad){const t=this._getSystem("playerInput");t&&typeof t.setVirtualPad=="function"&&t.setVirtualPad(e.pad)}if(e.selectSpell!==null||e.cast){const t=this._getSystem("player"),s=t?t.spells:null;s&&(e.selectSpell!==null&&typeof s.selectSpell=="function"&&s.selectSpell(e.selectSpell),e.cast&&typeof s.castSpell=="function"&&s.castSpell())}}}startRace(e){return this._raceCall("start",[e],null)}abortRace(){return this._raceCall("abort",[],null)}listReplays(){return this._raceCall("listReplays",[],[])}getLatestReplay(){return this._raceCall("getLatestReplay",[],null)}getBestReplay(e){return this._raceCall("getBestReplay",[e],null)}loadGhost(e){return this._raceCall("loadGhost",[e],null)}clearGhost(){return this._raceCall("clearGhost",[],null)}exportResult(e=null){return this._raceCall("exportResult",[e],null)}_raceCall(e,t,s){try{const i=this._getSystem("race");if(!i||typeof i[e]!="function")return s;const n=i[e](...t);return n===void 0?s:n}catch{return s}}_emitActionQueued(e){try{const t={},s=e.pad||{};s.throttle!==void 0&&(t.throttle=s.throttle),s.brake!==void 0&&(t.brake=s.brake),s.turn!==void 0&&(t.turn=s.turn),s.climb!==void 0&&(t.climb=s.climb),e.selectSpell!==null&&(t.selectSpell=e.selectSpell),e.cast&&(t.cast=!0);const i=this.engine&&this.engine.eventBus;i&&typeof i.emit=="function"&&i.emit("agentActionQueued",{source:"agentAPI",action:t,config:this.getConfig(),gameTime:this._gameTime})}catch{}}setConfig(e){try{if(e&&typeof e=="object"){if(e.actionHz!==void 0){const t=Number(e.actionHz);Number.isFinite(t)&&(this.config.actionHz=this._clamp(t,ue.actionHz[0],ue.actionHz[1]))}if(e.observationHz!==void 0){const t=Number(e.observationHz);Number.isFinite(t)&&(this.config.observationHz=this._clamp(t,ue.observationHz[0],ue.observationHz[1]))}if(e.observationLatencyMs!==void 0){const t=Number(e.observationLatencyMs);Number.isFinite(t)&&(this.config.observationLatencyMs=this._clamp(t,ue.observationLatencyMs[0],ue.observationLatencyMs[1]))}if(e.perceptionRadius&&typeof e.perceptionRadius=="object"){const t=Number(e.perceptionRadius.mana);Number.isFinite(t)&&(this.config.perceptionRadius.mana=this._clamp(t,ue.manaRadius[0],ue.manaRadius[1]));const s=Number(e.perceptionRadius.landmarks);Number.isFinite(s)&&(this.config.perceptionRadius.landmarks=this._clamp(s,ue.landmarkRadius[0],ue.landmarkRadius[1]))}}}catch{}return this.getConfig()}getConfig(){const e=this.config;return{actionHz:e.actionHz,observationHz:e.observationHz,observationLatencyMs:e.observationLatencyMs,perceptionRadius:{mana:e.perceptionRadius.mana,landmarks:e.perceptionRadius.landmarks}}}_bearing(e,t,s,i){const n=e*s+t*i,o=t*s-e*i;return Math.atan2(o,n)}_sanitizeAxis(e,t,s){if(e==null)return null;const i=Number(e);return Number.isNaN(i)?null:this._clamp(i,t,s)}_clamp(e,t,s){return Math.min(s,Math.max(t,e))}_num(e,t=0){return Number.isFinite(e)?e:t}_getSystem(e){const t=this.engine;if(!t)return null;const s=t.systems;if(s&&typeof s.get=="function"){const n=s.get(e);if(n)return n}const i=t.systemManager;if(i&&typeof i.get=="function"){const n=i.get(e);if(n)return n}return null}destroy(){try{if(this.disconnectAgent(),typeof window<"u"&&(this._onMessage&&window.removeEventListener("message",this._onMessage),window.agentAPI===this._api))try{delete window.agentAPI}catch{window.agentAPI=void 0}this.release()}catch{}this._onMessage=null,this._api=null,this._pendingAction=null;for(let e=0;e<_e;e++)this._ring[e].snap=null,this._ring[e].t=0;this._ringHead=0,this._ringCount=0,super.destroy()}}const Pa=3,Ra=40,Da=.45,La=1,Ia=1.55,Na=360,Oa=300,Fa=12,za=50,Ls=(h,e,t)=>Math.min(t,Math.max(e,h));class ui{constructor(e=window.agentAPI,t={}){this.api=e,this.opts={autoStart:!0,courseSeed:void 0,once:!1,intervalMs:100,...t},this._timer=null,this._raceRequested=!1,this._released=!1}start(){if(this._timer!==null)return this;if(!this.api||typeof this.api.observe!="function")throw new Error("SimpleBot: agentAPI not found. Is the game running with the Agent API loaded?");return this._timer=setInterval(()=>this._tick(),this.opts.intervalMs),this}stop(){return this._timer!==null&&(clearInterval(this._timer),this._timer=null),this.api&&typeof this.api.release=="function"&&this.api.release(),this}_tick(){const e=this.api.observe();if(!e||!e.self)return;const t=e.race;if(!t||t.state==="idle"){this.opts.autoStart&&!this._raceRequested&&(this._raceRequested=!0,this.api.startRace(this.opts.courseSeed));return}if(t.state==="finished"){this._released||(this._released=!0,this.api.release(),this.opts.once?this.stop():this._raceRequested=!1);return}this._released=!1,this._raceRequested=!0;const s=this.steer(e);s&&this.api.act(s)}steer(e){const t=e.race&&e.race.nextGates&&e.race.nextGates[0];if(!t)return null;const s=Ls(t.bearing*Pa,-1,1);let i=Ls(t.elevation/Ra,-1,1);const n=Math.abs(t.bearing),o=e.self&&Number.isFinite(e.self.speed)?e.self.speed:0,a=e.limits&&Number.isFinite(e.limits.maxSpeed)?e.limits.maxSpeed:210,r=n>Da,l=n>La&&t.distIa,d=t.dist<220&&o>a*.55;let u=1;c?u=.1:l?u=.25:r?u=.55:d&&(u=.65);let m=0;c?m=.9:l?m=.7:r&&t.dist<300?m=.35:d&&n>.25&&(m=.25);const f=e.terrain&&e.terrain.ahead||[],g=e.self.altitude;for(const b of f)if(b.dist<=Oa&&b.height>g-Fa){i=1;break}const p=e.limits&&e.limits.ceiling;return typeof p=="number"&&g>p-za&&(i=Math.min(i,0)),{throttle:u,brake:m,turn:s,climb:i}}}typeof window<"u"&&(window.SimpleBot=ui);const Is=12,Pt=18,Ba=2,Ga=330,Ha=450,Va=200,Ua=.55,qa=30,Wa=80,$a=800,ja=250,Ns=2,Os=.1,Ka=.1,Fs="vibecarpet.replays.v1",Xa=20,Rt=2,Ya=6750190,Qa=3364181,zs=16764006,Za=6750190,Bs="local";function Ja(h){let e=h>>>0;return function(){e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}class er extends U{constructor(e){super(e,"race"),this.state="idle",this.courseSeed=0,this.elapsedMs=0,this.currentGateIndex=0,this.splits=[],this.gates=[],this._gatePool=[],this._clockRunning=!1,this._finalTimeMs=0,this._sawKeyboard=!1,this._sawVirtual=!1,this._samples=[],this._actionLog=[],this._sampleAccum=0,this.replays=[],this._latestReplay=null,this._storageWarned=!1,this.ghostReplay=null,this.ghostMesh=null,this._ghostActive=!1,this._ghostCursor=0,this.courseGroup=null,this._gateMeshes=[],this._beaconMesh=null,this._nextGateMesh=null,this._torusGeometry=null,this._beaconGeometry=null,this._ghostGeometry=null,this._materials=null,this._hudRoot=null,this._raceChip=null,this._ghostChip=null,this._panelRoot=null,this._panelToggle=null,this._panelFields={},this._panelButtons={},this._panelOpen=!1,this._hudAccum=0,this._hudDirty=!1,this._panelDirty=!1,this._lastRaceText=null,this._lastGhostText=null,this._lastPanelText={},this._simpleBot=null,this._simpleBotRunning=!1,this._prevPlayerPos=new A,this._tmpA=new A,this._tmpB=new A,this._onKeyDown=null,this._onAgentActionQueued=null,this._hintTimer=null}get gateCount(){return this.gates.length}async _initialize(){this._createSharedResources(),this._createHud(),this._removePanelNodes(),this.replays=this._loadReplayStore(),this._latestReplay=this.replays.length?this.replays[this.replays.length-1]:null,this._onKeyDown=e=>{if(e.code!=="KeyR"||e.repeat)return;const t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)||this._isGamePlaying()&&this.state!=="running"&&this.start()},window.addEventListener("keydown",this._onKeyDown),this._onAgentActionQueued=e=>this.recordAgentAction(e),this.engine.eventBus.on("agentActionQueued",this._onAgentActionQueued),this._hintTimer=setTimeout(()=>{try{this.engine.systems.get("ui")?.showMessage?.("Press R to race")}catch{}},3e3),y.info(`RaceSystem initialized (${this.replays.length} stored replays)`)}_update(e,t){if(this._nextGateMesh&&this._animateNextGate(t),this.state==="running"){const s=this._getLocalPlayer();if(s){if(this._clockRunning){for(this.elapsedMs+=e*1e3,this._trackPilot(),this._sampleAccum+=e;this._sampleAccum>=Os;)this._sampleAccum-=Os,this._pushSample(s);this._updateGhost()}this._checkGatePass(s),this._prevPlayerPos.copy(s.position)}}this._hudAccum+=e,(this._hudAccum>=Ka||this._hudDirty)&&(this._hudAccum=0,this._hudDirty=!1,this._updateHud(),this._updatePanel())}destroy(){if(this._onKeyDown&&(window.removeEventListener("keydown",this._onKeyDown),this._onKeyDown=null),this._hintTimer&&(clearTimeout(this._hintTimer),this._hintTimer=null),this._hudRoot&&this._hudRoot.parentNode&&this._hudRoot.parentNode.removeChild(this._hudRoot),this._panelRoot&&this._panelRoot.parentNode&&this._panelRoot.parentNode.removeChild(this._panelRoot),this._panelToggle&&this._panelToggle.parentNode&&this._panelToggle.parentNode.removeChild(this._panelToggle),this._hudRoot=null,this._raceChip=null,this._ghostChip=null,this._panelRoot=null,this._panelToggle=null,this._panelFields={},this._panelButtons={},this._onAgentActionQueued&&(this.engine.eventBus.off("agentActionQueued",this._onAgentActionQueued),this._onAgentActionQueued=null),this.stopSimpleBot(),this.courseGroup&&(this.engine.scene.remove(this.courseGroup),this.courseGroup=null),this.ghostMesh&&(this.engine.scene.remove(this.ghostMesh),this.ghostMesh=null),this._torusGeometry&&this._torusGeometry.dispose(),this._beaconGeometry&&this._beaconGeometry.dispose(),this._ghostGeometry&&this._ghostGeometry.dispose(),this._torusGeometry=null,this._beaconGeometry=null,this._ghostGeometry=null,this._materials){for(const e of Object.keys(this._materials))this._materials[e].dispose();this._materials=null}this._gateMeshes.length=0,this._beaconMesh=null,this._nextGateMesh=null,this.gates.length=0,this.ghostReplay=null,this._ghostActive=!1,this.state="idle",super.destroy()}start(e){const t=this._getLocalPlayer();if(!t)return y.warn("RaceSystem.start: no local player yet, cannot place a course"),null;const s=Number.isFinite(e)?e>>>0:Math.random()*4294967296>>>0;return this.courseSeed=s,this._buildCourse(s,t),this.state="running",this.elapsedMs=0,this._finalTimeMs=0,this.currentGateIndex=0,this.splits.length=0,this._clockRunning=!1,this._sawKeyboard=!1,this._sawVirtual=!1,this._samples=[],this._actionLog=[],this._sampleAccum=0,this._prevPlayerPos.copy(t.position),this._ghostActive=!1,this._ghostCursor=0,this.ghostMesh&&(this.ghostMesh.visible=!1),this._refreshGateVisuals(),this._hudDirty=!0,this._panelDirty=!0,this._toast(`Race seed ${s} ready — fly through the lit ring`,"#ffcc66"),this.engine.eventBus.emit("raceStarted",{courseSeed:s}),y.info(`RaceSystem: race started, courseSeed=${s}`),s}abort(){this.state="idle",this._clockRunning=!1,this.elapsedMs=0,this.currentGateIndex=0,this.splits.length=0,this._samples=[],this._actionLog=[];for(let t=0;t({id:t,version:e.version,pilot:e.pilot,worldSeed:e.worldSeed,courseSeed:e.courseSeed,date:e.date,finalTimeMs:e.finalTimeMs,splits:Array.isArray(e.splits)?e.splits.slice():[],sampleCount:Array.isArray(e.samples)?e.samples.length:0,actionLogCount:Array.isArray(e.actionLog)?e.actionLog.length:0,verificationStatus:e.verificationStatus||(Array.isArray(e.actionLog)&&e.actionLog.length>0?"action-log-present":"ghost-only")}))}getBestReplay(e){let t=null;for(let s=0;snew V(Object.assign({color:t,blending:De,transparent:!0,opacity:s,depthWrite:!1},i));this._materials={upcoming:e(Ya,.6),passed:e(Qa,.6),next:e(zs,.6),beacon:e(zs,.18,{side:pe}),ghost:e(Za,.35)},this.courseGroup=new ee,this.courseGroup.name="race-course",this.courseGroup.visible=!1;for(let t=0;t1e-10&&(n=this._tmpB.subVectors(t.position,this._prevPlayerPos).dot(s)/i,n<0?n=0:n>1&&(n=1));const o=this._tmpB.copy(this._prevPlayerPos).addScaledVector(s,n),a=t.radius+Ba;o.distanceToSquared(t.position)<=a*a&&this._onGatePassed(t,e)}_onGatePassed(e,t){e.index===0&&!this._clockRunning&&(this._clockRunning=!0,this.elapsedMs=0,this._sampleAccum=0,this._samples=[],this._pushSample(t),this._ghostActive=!!this.ghostReplay,this._ghostCursor=0);const s=Math.round(this.elapsedMs);this.splits.push(s),e.passed=!0,this.currentGateIndex++,this.engine.eventBus.emit("gatePassed",{index:e.index,splitMs:s}),this._toast(`Gate ${e.index+1}/${this.gateCount} passed`,e.index+1>=this.gateCount?"#66ffee":"#ffcc66",1800),this.currentGateIndex>=this.gates.length?this._finishRace(t):this._refreshGateVisuals(),this._hudDirty=!0,this._panelDirty=!0}_finishRace(e){this.state="finished",this._clockRunning=!1,this._finalTimeMs=Math.round(this.elapsedMs),this._pushSample(e);const t=this.engine.systems.get("world"),s=t&&t.seed!==void 0&&t.seed!==null?t.seed:0,i=this._actionLog.slice(),n={version:Rt,schemaVersion:Rt,pilot:this._resolvePilot(),worldSeed:s,courseSeed:this.courseSeed,date:new Date().toISOString(),finalTimeMs:this._finalTimeMs,splits:this.splits.slice(),samples:this._samples,actionLog:i,fairnessConfig:this._getFairnessConfig(),verificationStatus:i.length>0?"action-log-present":"ghost-only",buildVersion:Bs,userAgent:typeof navigator<"u"?navigator.userAgent:"unknown"};this._samples=[],this._actionLog=[],this._saveReplay(n),this._latestReplay=n,this._refreshGateVisuals(),this._hudDirty=!0,this._panelDirty=!0,this.engine.eventBus.emit("raceFinished",{timeMs:this._finalTimeMs,replay:n}),this._toast(`Finished ${this._formatTime(this._finalTimeMs,3)} — replay saved`,"#66ffee",5e3),y.info(`RaceSystem: race finished in ${this._finalTimeMs} ms (pilot: ${n.pilot})`)}_pushSample(e){this._samples.push([Math.round(this.elapsedMs),Math.round(e.position.x*100)/100,Math.round(e.position.y*100)/100,Math.round(e.position.z*100)/100,Math.round(e.rotation.y*1e3)/1e3])}_trackPilot(){const e=this.engine.systems.get("playerInput"),t=e?e.inputSourcesThisFrame:null;t&&(t.keyboard&&(this._sawKeyboard=!0),t.virtual&&(this._sawVirtual=!0))}_resolvePilot(){return this._sawKeyboard&&this._sawVirtual?"mixed":this._sawKeyboard?"human":this._sawVirtual?"agent":"unknown"}_loadReplayStore(){try{const e=window.localStorage.getItem(Fs);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return this._warnStorageOnce(e),[]}}_saveReplay(e){for(this.replays.push(e);this.replays.length>Xa;){const t=new Map;for(let i=0;it[t.length-1][0]){this.ghostMesh.visible=!1;return}let i=this._ghostCursor;for(;i0?(s-n[0])/a:1;r<0?r=0:r>1&&(r=1),this.ghostMesh.position.set(n[1]+(o[1]-n[1])*r,n[2]+(o[2]-n[2])*r,n[3]+(o[3]-n[3])*r);let l=o[4]-n[4];l=Math.atan2(Math.sin(l),Math.cos(l)),this.ghostMesh.rotation.y=n[4]+l*r,this.ghostMesh.visible=!0}_createHud(){const e=document.createElement("div");e.id="race-hud",Object.assign(e.style,{position:"fixed",top:"16px",left:"50%",transform:"translateX(-50%)",display:"flex",flexDirection:"column",alignItems:"center",gap:"6px",zIndex:"1000",pointerEvents:"none",fontFamily:"var(--app-font, sans-serif)"});const t=document.createElement("div");Object.assign(t.style,{padding:"8px 20px",borderRadius:"18px",background:"rgba(20, 30, 60, 0.75)",color:"#fff",fontSize:"16px",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums",display:"none"});const s=document.createElement("div");Object.assign(s.style,{padding:"4px 14px",borderRadius:"14px",background:"rgba(20, 30, 60, 0.6)",color:"#aaffee",fontSize:"13px",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums",display:"none"}),e.appendChild(t),e.appendChild(s),document.body.appendChild(e),this._hudRoot=e,this._raceChip=t,this._ghostChip=s}_updateHud(){if(!this._raceChip)return;let e=null;if(this.state==="running")e=this._clockRunning?`Gate ${this.currentGateIndex}/${this.gateCount} — ${this._formatTime(this.elapsedMs,1)}`:"Race ready — fly through the lit ring";else if(this.state==="finished"&&this.gates.length>0){const s=this.getBestReplay(this.courseSeed),i=s&&s.finalTimeMs{const g=document.createElement("button");g.type="button",g.className=f?"vc-btn-primary":"vc-btn-ghost",g.textContent=u,g.style.minHeight="30px",g.style.padding="6px 8px",g.style.fontSize="12px",g.style.borderRadius="999px",g.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),m()}),r.appendChild(g),this._panelButtons[d]=g};l("start","Start Race",()=>this.start(),!0),l("restart","Same Seed",()=>this.restartSameSeed()),l("abort","Stop Race",()=>{this.abort(),this._toast("Race stopped")}),l("loadGhost","Load Ghost",()=>this.loadBestGhost()),l("clearGhost","Clear Ghost",()=>{this.clearGhost(),this._toast("Ghost cleared")}),l("runBot","Run SimpleBot",()=>this.runSimpleBot()),l("stopBot","Stop Bot",()=>this.stopSimpleBot()),l("export","Export JSON",()=>{const d=this.exportResult(null,{download:!0});this._toast(d?"Benchmark JSON exported":"Finish a race before export",d?"#66ffee":"#ffcc66")}),t.appendChild(r);const c=this.engine.systems.get("ui");(!c||typeof c.registerSettingsPane!="function"||!c.registerSettingsPane("race",t))&&e.appendChild(t),this._panelToggle=null,this._panelRoot=t,this._updatePanel()}_updatePanel(){if(!this._panelRoot&&this._isGamePlaying()&&this._createPanel(),!this._panelRoot)return;if(!this._isGamePlaying()){this._panelRoot.style.display="none";return}this._panelRoot.style.display="block";const t=this.courseSeed?this.getBestReplay(this.courseSeed):this.getPanelBestReplay(),s=this.getLatestReplay(),i=this.ghostReplay,n=this.gateCount?`${Math.min(this.currentGateIndex+1,this.gateCount)} / ${this.gateCount}`:"--",o=this.state==="finished"?this._finalTimeMs:this.state==="running"?this.elapsedMs:null,a={seed:this.courseSeed?String(this.courseSeed):"--",gate:n,elapsed:o===null?"--":this._formatTime(o,1),best:t?`${this._formatTime(t.finalTimeMs,1)} ${t.pilot||"unknown"}`:"--",pilot:this._currentPilotLabel(),ghost:i?`${i.pilot||"unknown"} ${this._formatTime(i.finalTimeMs,1)}`:"none"};for(const l of Object.keys(a))this._lastPanelText[l]!==a[l]&&(this._lastPanelText[l]=a[l],this._panelFields[l]&&(this._panelFields[l].textContent=a[l]));const r=this._panelButtons;r.restart&&(r.restart.disabled=!this.courseSeed),r.abort&&(r.abort.disabled=this.state!=="running"),r.loadGhost&&(r.loadGhost.disabled=!t),r.clearGhost&&(r.clearGhost.disabled=!i),r.runBot&&(r.runBot.disabled=this._simpleBotRunning),r.stopBot&&(r.stopBot.disabled=!this._simpleBotRunning),r.export&&(r.export.disabled=!s)}_currentPilotLabel(){return this.state==="finished"&&this._latestReplay&&this._latestReplay.courseSeed===this.courseSeed?this._latestReplay.pilot||"unknown":this._sawKeyboard&&this._sawVirtual?"mixed":this._sawKeyboard?"human":this._sawVirtual||this._simpleBotRunning?"agent":"unknown"}_isGamePlaying(){try{return this.engine.gameStarted&&le.getState().currentState===G.PLAYING}catch{return!!this.engine.gameStarted}}_removePanelNodes(){typeof document>"u"||(document.querySelectorAll("#race-panel, #race-panel-toggle").forEach(e=>e.remove()),this._panelRoot=null,this._panelToggle=null,this._panelOpen=!1)}_resolveReplayRef(e){return e==null?null:Number.isInteger(e)?this.replays[e]||null:e&&typeof e=="object"?!Array.isArray(e.samples)&&Number.isInteger(e.id)?this.replays[e.id]||null:e:null}_buildExportResult(e){const t=Array.isArray(e.actionLog)?e.actionLog:[],s=e.verificationStatus||(t.length>0?"action-log-present":"ghost-only");return{type:"skybloom.benchmark-result",version:Rt,game:"SkyBloom",buildVersion:e.buildVersion||Bs,date:e.date,exportedAt:new Date().toISOString(),courseSeed:e.courseSeed,worldSeed:e.worldSeed,finalTimeMs:e.finalTimeMs,splits:Array.isArray(e.splits)?e.splits.slice():[],pilot:e.pilot||"unknown",fairnessConfig:e.fairnessConfig||this._getFairnessConfig(),verificationStatus:s,trustModel:"client-recorded path replay; not verified by deterministic re-simulation",replay:{sampleFormat:["tMs","x","y","z","heading"],pathSamples:Array.isArray(e.samples)?e.samples:[],actionLog:t},userAgent:e.userAgent||(typeof navigator<"u"?navigator.userAgent:"unknown")}}_getFairnessConfig(){const e=typeof window<"u"?window.agentAPI:null,t=e&&typeof e.getConfig=="function"?e.getConfig():{actionHz:10,observationHz:20,observationLatencyMs:0,perceptionRadius:{mana:800,landmarks:2e3}};return{profile:this._fairnessProfile(t),actionHz:t.actionHz,observationHz:t.observationHz,observationLatencyMs:t.observationLatencyMs,perceptionRadius:t.perceptionRadius?{...t.perceptionRadius}:void 0}}_fairnessProfile(e){return e.actionHz===10&&e.observationLatencyMs===150?"strict":e.actionHz===20&&e.observationLatencyMs===0?"open":"custom"}_downloadJson(e,t){if(typeof document>"u"||typeof Blob>"u")return;const s=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(s),n=document.createElement("a");n.href=i,n.download=t,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}_resultFilename(e){const t=e&&e.courseSeed!==void 0?e.courseSeed:"unknown-seed",s=e&&Number.isFinite(e.finalTimeMs)?e.finalTimeMs:"unfinished";return`skybloom-${t}-${s}.json`}_toast(e,t="#66ffee",s=3e3){try{this.engine.systems.get("ui")?.showMessage?.(e,s,t)}catch{}}_formatTime(e,t){(!Number.isFinite(e)||e<0)&&(e=0);const s=Math.pow(10,t),i=Math.round(e/1e3*s)/s,n=Math.floor(i/60),o=i-n*60,a=o.toFixed(t);return`${n}:${o<10?"0"+a:a}`}_getLocalPlayer(){const e=this.engine.systems.get("playerState");return e?e.localPlayer:null}}const Gs="vc.onboarded";class tr extends U{constructor(e){super(e,"onboarding"),this.steps=[{text:"Hold W — throttle",done:({input:t})=>t&&t.currentThrottle>.5,timeout:1/0},{text:"A / D — bank into the turn",done:({player:t})=>t&&Math.abs(t.bankAngle||0)>.2,timeout:20},{text:"Space climbs · Ctrl sinks",done:({player:t})=>t&&Math.abs(t.altitudeVelocity||0)>12,timeout:20},{text:"Nose down to dive — gravity is free speed",done:({player:t})=>{if(!t)return!1;const s=t.velocity;return Math.hypot(s.x,s.z)>230},timeout:25},{text:"R — race · Q — quests · E — cast",done:()=>this._finalKeySeen,timeout:12}],this.stepIndex=-1,this.stepElapsed=0,this.active=!1,this.finished=!1,this.chip=null,this._finalKeySeen=!1,this._keyHandler=null}async _initialize(){try{if(localStorage.getItem(Gs)==="1"){this.finished=!0;return}}catch{}Qe(),this._keyHandler=e=>{(e.code==="KeyR"||e.code==="KeyQ"||e.code==="KeyE")&&(this._finalKeySeen=!0)},window.addEventListener("keydown",this._keyHandler)}_update(e){if(this.finished)return;if(!this.active){if(!this.engine.gameStarted)return;this.active=!0,this._advance();return}const t=this.steps[this.stepIndex];if(!t)return;const s=this.engine.systems.get("playerInput"),i=this.engine.systems.get("playerState")?.localPlayer;this.stepElapsed+=e,(t.done({input:s,player:i})||this.stepElapsed>t.timeout)&&this._advance()}_advance(){if(this.stepIndex++,this.stepElapsed=0,this.stepIndex>=this.steps.length){this.finished=!0;try{localStorage.setItem(Gs,"1")}catch{}this._fadeOutAndRemove();return}this._showText(this.steps[this.stepIndex].text)}_showText(e){if(!this.chip){const s=document.createElement("div");s.className="vc-chip",s.style.position="fixed",s.style.bottom="9%",s.style.left="50%",s.style.transform="translateX(-50%) translateY(6px)",s.style.padding="10px 18px",s.style.fontSize="15px",s.style.borderLeft="3px solid var(--vc-gold)",s.style.pointerEvents="none",s.style.zIndex="1001",s.style.opacity="0",s.style.transition="opacity 0.25s ease, transform 0.25s ease",document.body.appendChild(s),this.chip=s}const t=this.chip;t.style.opacity="0",t.style.transform="translateX(-50%) translateY(6px)",setTimeout(()=>{t.textContent=e,t.style.opacity="1",t.style.transform="translateX(-50%) translateY(0)"},260)}_fadeOutAndRemove(){if(this.chip){this.chip.style.opacity="0";const e=this.chip;this.chip=null,setTimeout(()=>e.remove(),400)}this._keyHandler&&(window.removeEventListener("keydown",this._keyHandler),this._keyHandler=null)}destroy(){this._fadeOutAndRemove(),super.destroy()}}class sr{constructor(e){this.engine=e,this.container=document.createElement("div"),this.visible=!1,this.initialized=!1,this.onPlayCallback=null,this._keyHandler=null,this._cinematicWatch=null}initialize(){Qe(),this._injectAnimations();const e=this.container;e.id="intro-screen",e.style.position="fixed",e.style.inset="0",e.style.zIndex="1000",e.style.pointerEvents="auto",e.style.fontFamily="var(--vc-font)",e.style.color="var(--vc-ink)",e.style.overflow="hidden";const t=document.createElement("div");t.style.position="absolute",t.style.inset="0",t.style.zIndex="0",t.style.transition="opacity 1.2s ease",t.style.background=["radial-gradient(1.5px 1.5px at 12% 18%, rgba(255,255,255,0.8), transparent 60%)","radial-gradient(1px 1px at 32% 9%, rgba(255,255,255,0.7), transparent 60%)","radial-gradient(1.5px 1.5px at 55% 22%, rgba(255,255,255,0.6), transparent 60%)","radial-gradient(1px 1px at 71% 12%, rgba(255,255,255,0.8), transparent 60%)","radial-gradient(1.5px 1.5px at 86% 27%, rgba(255,255,255,0.5), transparent 60%)","radial-gradient(1px 1px at 44% 31%, rgba(255,255,255,0.5), transparent 60%)","radial-gradient(1px 1px at 92% 7%, rgba(255,255,255,0.7), transparent 60%)","linear-gradient(180deg, #0b1026 0%, #2a2c5a 38%, #46518f 58%, #ff7744 72%, #6a3a52 80%, #2a1a3a 100%)"].join(", ");for(let v=0;v<2;v++){const M=document.createElement("div");M.style.position="absolute",M.style.top=`${52+v*11}%`,M.style.left=`${-30+v*45}%`,M.style.width="46%",M.style.height="9%",M.style.borderRadius="50%",M.style.background=v===0?"rgba(255, 160, 110, 0.20)":"rgba(180, 140, 220, 0.16)",M.style.filter="blur(28px)",M.style.animation=`vc-cloud-drift ${90+v*40}s linear infinite`,t.appendChild(M)}this._fallbackLayer=t,e.appendChild(t);const s=document.createElement("div");s.style.position="absolute",s.style.inset="0",s.style.zIndex="1",s.style.pointerEvents="none",s.style.background="linear-gradient(0deg, rgba(13,18,38,0.85) 0%, rgba(13,18,38,0.35) 30%, rgba(13,18,38,0) 48%),radial-gradient(120% 90% at 50% 40%, transparent 60%, rgba(8,10,24,0.45) 100%)",e.appendChild(s);const i=document.createElement("div");i.style.position="absolute",i.style.inset="0",i.style.zIndex="2",i.style.display="flex",i.style.flexDirection="column",i.style.justifyContent="center",i.style.padding="0 8%",i.style.maxWidth="720px";const n=document.createElement("div");n.className="vc-label",n.textContent="an open-sky game for humans and machines",n.style.marginBottom="14px",i.appendChild(n);const o=document.createElement("h1");o.textContent="SkyBloom",o.style.margin="0",o.style.fontWeight="800",o.style.fontSize="clamp(40px, 7vw, 76px)",o.style.letterSpacing="0.16em",o.style.lineHeight="1.05",o.style.textShadow="0 2px 24px rgba(13, 18, 38, 0.8)",i.appendChild(o);const a=document.createElementNS("http://www.w3.org/2000/svg","svg");a.setAttribute("width","280"),a.setAttribute("height","18"),a.setAttribute("viewBox","0 0 280 18"),a.style.margin="10px 0 18px 4px",a.innerHTML='',i.appendChild(a);const r=document.createElement("div");r.className="vc-label",r.textContent="fly · collect · race the machines",r.style.fontSize="13px",r.style.marginBottom="34px",i.appendChild(r);const l=document.createElement("button");l.className="vc-btn-primary",l.textContent="Play",l.style.alignSelf="flex-start",l.style.animation="vc-breathe 3s ease-in-out infinite",i.appendChild(l);const c=document.createElement("div");c.style.display="flex",c.style.flexWrap="wrap",c.style.gap="8px",c.style.marginTop="16px";const d=document.createElement("button");d.className="vc-btn-ghost",d.textContent="How to fly";const u=document.createElement("a");u.className="vc-btn-ghost",u.textContent="Agent API";const m="/skybloom/";u.href=`${m.endsWith("/")?m:`${m}/`}docs/AGENT_API.md`,u.target="_blank",u.style.textDecoration="none",u.style.display="inline-flex",u.style.alignItems="center",c.appendChild(d),c.appendChild(u),i.appendChild(c);const f=document.createElement("div");f.className="vc-panel",f.style.display="none",f.style.marginTop="16px",f.style.padding="14px 16px",f.style.maxWidth="380px",[["W / S · Shift","throttle · brake"],["A / D","bank into the turn"],["Space / Ctrl","climb / dive"],["Mouse","steer (click to lock)"],["1–4 · E","select · cast spells"],["R","start a 12-gate race"],["Menu","race · speed · time"]].forEach(([v,M])=>{const _=document.createElement("div");_.style.display="flex",_.style.justifyContent="space-between",_.style.gap="18px",_.style.padding="4px 0";const E=document.createElement("span");E.className="vc-label",E.style.color="var(--vc-gold)",E.textContent=v;const P=document.createElement("span");P.style.fontSize="13px",P.style.color="var(--vc-ink-dim)",P.textContent=M,_.appendChild(E),_.appendChild(P),f.appendChild(_)}),i.appendChild(f),d.addEventListener("click",()=>{f.style.display=f.style.display==="none"?"block":"none"}),e.appendChild(i);const p=document.createElement("div");p.style.position="absolute",p.style.left="8%",p.style.bottom="4%",p.style.zIndex="2",p.style.display="flex",p.style.alignItems="center",p.style.gap="8px";const b=document.createElement("span");b.style.width="8px",b.style.height="8px",b.style.borderRadius="50%",b.style.background="rgba(255,255,255,0.25)",b.title="multiplayer: unknown";const S=document.createElement("span");S.className="vc-label",S.textContent="open source · MIT",p.appendChild(b),p.appendChild(S),e.appendChild(p),this._statusDot=b,this.serverStatus=S;const x=this;function w(v){v.preventDefault(),l.removeEventListener("click",w),l.removeEventListener("touchend",w),x._unbindKeys(),x.container.style.display="none",x.visible=!1,le.getState().setGameState(G.PLAYING),x.onPlayCallback&&x.onPlayCallback(),document.body.requestPointerLock&&document.body.requestPointerLock()}this._handlePlayPress=w,l.addEventListener("click",w),l.addEventListener("touchend",w),window.innerWidth<700&&(i.style.padding="0 6%",l.style.alignSelf="stretch",c.style.flexDirection="column"),document.body.appendChild(e),e.style.display="none",this.initialized=!0}show(){this.initialized||this.initialize(),this.container.style.display="block",this.visible=!0,this.container.style.opacity="0",this.container.style.transition="opacity 0.5s",setTimeout(()=>{this.container.style.opacity="1"},10),this._keyHandler=e=>{(e.code==="Enter"||e.code==="Space")&&this.visible&&this._handlePlayPress&&this._handlePlayPress(e)},window.addEventListener("keydown",this._keyHandler),clearInterval(this._cinematicWatch),this._cinematicWatch=setInterval(()=>{if(!this.visible)return;const e=this.engine&&this.engine._menuCinematicActive&&!this.engine._menuCinematicDisabled;this._fallbackLayer.style.opacity=e?"0":"1"},500)}hide(){!this.initialized||!this.visible||(this._unbindKeys(),this.container.style.opacity="0",setTimeout(()=>{this.container.style.display="none",this.visible=!1},500))}onPlay(e){this.onPlayCallback=e}updateServerStatus(e,t="info"){!this.initialized||!this._statusDot||(this._statusDot.title=`multiplayer: ${e}`,this._statusDot.style.background=t==="success"?"#72e176":t==="error"?"rgba(255,255,255,0.25)":"rgba(255,255,255,0.4)")}_unbindKeys(){this._keyHandler&&(window.removeEventListener("keydown",this._keyHandler),this._keyHandler=null),clearInterval(this._cinematicWatch)}_injectAnimations(){if(document.getElementById("vc-intro-anim"))return;const e=document.createElement("style");e.id="vc-intro-anim",e.textContent=` - @keyframes vc-breathe { - 0%, 100% { box-shadow: 0 0 24px rgba(255, 204, 102, 0.35); } - 50% { box-shadow: 0 0 42px rgba(255, 204, 102, 0.6); } - } - @keyframes vc-cloud-drift { - from { transform: translateX(0); } - 50% { transform: translateX(38vw); } - to { transform: translateX(0); } - } - `,document.head.appendChild(e)}}class ir{constructor(e){this.engine=e,this.systems=new Map,this.updateOrder=[]}register(e){if(!e.name)throw new Error(`System must have a name property: ${e.constructor.name}`);this.systems.set(e.name,e);for(const t of[this,this.systems])e.name in t||Object.defineProperty(t,e.name,{get:()=>this.systems.get(e.name),configurable:!0});return this}get(e){return this.systems.get(e)}setUpdateOrder(e){return this.updateOrder=e,this}async initialize(){for(const e of this.updateOrder){const t=this.get(e);t&&await t.initialize()}}update(e,t){for(let s=0;s{o.material&&(Array.isArray(o.material)?n.push(...o.material):n.push(o.material))});for(const o of n)(o.isMeshStandardMaterial||o.isMeshPhysicalMaterial)&&(o.aoMap&&(o.aoMapIntensity=i.aoMapIntensity),o.normalMap&&o.normalScale.copy(i.normalScale),o.displacementMap&&(o.displacementScale=i.displacementScale),o.roughness=i.roughness,o.metalness=i.metalness,o.envMapIntensity=i.envMapIntensity,o.flatShading=i.flatShading,o.needsUpdate=!0);y.info(`Applied quality settings level ${e} to ${n.length} materials`)}render(e,t){if(this.isMobile&&this.deviceCapabilities.gpuTier==="low"){if(this._frameSkipAccumulator<.03333333333333333){if(this._frameSkipAccumulator+=this.engine.delta,this.engine.systemManager){const i=this.engine.systemManager.get("player");i&&i.update(this.engine.delta,this.engine.elapsed)}return}this._frameSkipAccumulator=0}if(this.renderer.shadowMap.enabled){const s=this.isMobile?this.deviceCapabilities.gpuTier==="low"?15:5:1;this._shadowUpdateCounter%s===0?this.renderer.shadowMap.needsUpdate=!0:this.renderer.shadowMap.needsUpdate=!1,this._shadowUpdateCounter++}this._optimizeBeforeRender(),this.renderer.render(e,t),this._cleanupAfterRender()}_optimizeBeforeRender(){if(this.isMobile&&this.scene){const e=this.deviceCapabilities.gpuTier==="low"?2:this.deviceCapabilities.gpuTier==="medium"?3:4,t=this.engine.systemManager?this.engine.systemManager.get("player")?.localPlayer?.position:null;if(t){const s=[];this.scene.traverse(i=>{if(i.isLight&&i.visible){const n=t.distanceTo(i.position),o=i.intensity*(1/(1+n*.01));s.push({light:i,importance:o,distance:n})}}),s.sort((i,n)=>n.importance-i.importance);for(let i=0;i{e.isLight&&e._wasEnabled!==void 0&&(e.visible=e._wasEnabled,delete e._wasEnabled)}),this.isMobile&&this.deviceCapabilities.gpuTier==="low"){const e=this.engine.systemManager?this.engine.systemManager.get("atmosphere"):null;e&&e._effectsWereEnabled!==void 0&&(e.setEffectsEnabled(e._effectsWereEnabled),delete e._effectsWereEnabled)}}handleVisibilityChange(e){this.engine.isVisible=e}destroy(){this.renderer&&(this.renderer.dispose(),this.renderer=null)}}class or{constructor(e){this.engine=e,this.targetFPS=60,this.currentFPS=60,this.sampleSize=20,this.fpsHistory=[],this.resolutionScale=1,this.highQualityMode=!1,this.batterySaving=!1,this.performanceMonitor=e.performanceMonitor,this.rendererManager=null}update(e){if(e<=0)return;const t=1e3/(e*1e3);if(this.fpsHistory.push(t),this.fpsHistory.length>this.sampleSize&&this.fpsHistory.shift(),this.currentFPS=this.fpsHistory.reduce((s,i)=>s+i,0)/this.fpsHistory.length,this.currentFPSthis.targetFPS*1.1&&(this.resolutionScale=Math.min(1,this.resolutionScale*1.05)),this.rendererManager&&this.rendererManager.renderer){const s=Math.min(window.devicePixelRatio,this.batterySaving?1:2);this.rendererManager.renderer.setPixelRatio(s*this.resolutionScale)}}setBatterySavingMode(e){if(this.batterySaving=e,this.targetFPS=e?30:60,e?this.resolutionScale=.8:this.resolutionScale=1,this.rendererManager&&this.rendererManager.renderer){const t=Math.min(window.devicePixelRatio,e?1:2);this.rendererManager.renderer.setPixelRatio(t*this.resolutionScale)}y.info(`Battery saving mode ${e?"enabled":"disabled"}`)}toggleHighQualityMode(){if(this.highQualityMode=!this.highQualityMode,this.targetFPS=this.highQualityMode?120:60,this.resolutionScale=this.highQualityMode?1:this.resolutionScale,this.rendererManager&&this.rendererManager.renderer){const e=Math.min(window.devicePixelRatio,2);this.rendererManager.renderer.setPixelRatio(e*this.resolutionScale)}y.info(`High quality mode ${this.highQualityMode?"enabled":"disabled"}`)}updateFromPerformance(e){return e&&e.fps&&e.fpss(t))}off(e,t){this.listeners.has(e)&&this.listeners.set(e,this.listeners.get(e).filter(s=>s!==t))}}let $t,jt,Kt;async function rr(){try{$t=(await St(()=>import("./MaterialSystemIntegration-CnfDoB_F.js"),__vite__mapDeps([0,1]))).MaterialSystemIntegration}catch{}try{jt=(await St(()=>import("./PhysicsSystem-DKc5nAHw.js"),__vite__mapDeps([2,1]))).PhysicsSystem}catch{}try{Kt=(await St(()=>import("./MobileUI-4RxndL5M.js"),[])).MobileUI}catch{}}class hr{constructor(){this.canvas=document.getElementById("game-canvas"),this.clock=new Zi,this.delta=0,this.elapsed=0,this.isRunning=!1,this.isVisible=!0,this.maxDeltaTime=1/15,this.minimapEnabled=!0,this.gameStarted=!1,this._frameCounter=0,this.performanceMonitor=new Un,this.settings=new qn,this.eventBus=new ar,this.deviceCapabilities=Se,this.isMobile=this.deviceCapabilities.isMobile,this.scene=new Ji,this.scene.fog=new Xs(8900331,15e-5),this.camera=new Zt(75,window.innerWidth/window.innerHeight,1,5e3),this.camera.layers.enable(10),this.input=new nn,this.assets=new Vn,this.systemManager=new ir(this),this.systems=this.systemManager.systems,this.rendererManager=new nr(this,this.canvas),this.qualityManager=new or(this),this.qualityManager.rendererManager=this.rendererManager,window.addEventListener("resize",this.onResize.bind(this)),document.addEventListener("visibilitychange",this.onVisibilityChange.bind(this))}async initialize(){await rr(),await this.assets.initialize();let e=this.systemManager;$t&&(this.materialSystem=new $t(this),y.info("MaterialSystemIntegration loaded (legacy, not managed by SystemManager)")),jt&&(this.physicsSystem=new jt(this),y.info("PhysicsSystem loaded (legacy, not managed by SystemManager)")),e=e.register(new Vo(this)),e=e.register(new Wn(this)),e=e.register(new jo(this)),e=e.register(new xa(this)),e=e.register(new Sa(this)),e=e.register(new va(this)),e=e.register(new ia(this)),e=e.register(new Zo(this)).register(new Ko(this)).register(new ta(this)).register(new sa(this)).register(new Qo(this)).register(new ba(this)).register(new ka(this)).register(new Ye(this)).register(new Aa(this)).register(new Ca(this)).register(new Ma(this)).register(new _a(this)).register(new Ea(this)).register(new er(this)).register(new tr(this)),this.minimapEnabled!==!1&&(e=e.register(new Ta(this))),e=e.register(new Uo(this)),this.isMobile&&Kt&&(this.mobileUI=new Kt(this)),this.materialSystem&&typeof this.materialSystem.initialize=="function"&&(await this.materialSystem.initialize(),y.info("MaterialSystem initialized")),this.physicsSystem&&typeof this.physicsSystem.initialize=="function"&&(await this.physicsSystem.initialize(),y.info("PhysicsSystem initialized"));const t=["network","mobileLOD","skybox","world","water","performanceBenchmark","simpleTrees","playerState","playerPhysics","agentAPI","playerInput","playerCamera","player","race","atmosphere","ambientLife","ui","proceduralAudio","proceduralMusic","carpetTrail","landmarks","minimap","questManager","onboarding"];this.systemManager.setUpdateOrder(t),await this.systemManager.initialize(),this.rendererManager.setup(),this.rendererManager.applyQualitySettings(this.isMobile?1:2),this.input.initialize(),this.input&&this.systemManager.get("player")&&setTimeout(()=>{try{this.input.setPlayerStateProvider(()=>{const n=this.systemManager.get("player");return n?n.getLocalPlayerState():null}),y.info("Player state provider configured successfully")}catch(n){y.warn("Error setting player state provider:",n)}},100),this.mobileUI&&typeof this.mobileUI.initialize=="function"&&(this.mobileUI.initialize(),y.info("Mobile UI initialized"),setTimeout(()=>{document.querySelectorAll('#ui-container .spell-slot, [id^="spell-button"]').forEach(a=>{a&&(a.style.display="none")}),document.querySelectorAll("#ui-container > div:not(#health-bar):not(#battery-toggle)").forEach(a=>{a&&!a.id.includes("battery")&&(a.style.display="none")})},500)),document.documentElement.style.setProperty("--ui-animation-speed",this.qualityManager.uiAnimationLevel==="high"?"1":"0.5"),this.input.on("keydown",n=>{n.code==="KeyM"&&le.getState().currentState===G.PLAYING&&this.toggleMinimap()}),document.getElementById("loading").style.display="none",this.isRunning=!0,this.animate(),this.introScreen=new sr(this),this.introScreen.onPlay(async()=>{this.gameStarted=!0;const n=this.systemManager.get("player");n&&typeof n.enable=="function"&&n.enable();const o=this.systemManager.get("playerInput");this.input.isTouchDevice&&o&&typeof o.showMobileControls=="function"&&o.showMobileControls(),this.input.isTouchDevice||this.input.requestPointerLock();const a=this.systemManager.get("network");a&&a.connect(),le.getState().setGameState(G.PLAYING),this.eventBus.emit("gameStarted")});const s=this.systemManager.get("atmosphere");s&&typeof s.timeOfDay=="number"&&(s.timeOfDay=.72),Qe();const i=()=>{const n=le.getState().currentState===G.PLAYING;document.body.classList.toggle("vc-playing",n)};i(),this._unsubscribeHud=le.subscribe(i),this.introScreen.show(),le.getState().setGameState(G.INTRO),this.canvas.addEventListener("click",()=>{le.getState().currentState===G.PLAYING&&!this.input.pointerLocked&&this.input.requestPointerLock()}),y.info("Engine initialized successfully")}animate(e){if(this.isRunning){if(requestAnimationFrame(this.animate.bind(this)),this.isVisible&&!this.gameStarted&&this.introScreen&&this.introScreen.visible&&!this._menuCinematicDisabled){try{this.delta=Math.min(this.clock.getDelta(),this.maxDeltaTime),this.elapsed=this.clock.getElapsedTime(),this._menuCinematicActive=!0;const t=this.elapsed*.02;this.camera.position.set(Math.cos(t)*900,220+Math.sin(t*.7)*40,Math.sin(t)*900),this.camera.lookAt(0,40,0);const s=this.systemManager.get("atmosphere");s&&typeof s.update=="function"&&s.update(this.delta,this.elapsed);const i=this.systemManager.get("water");i&&typeof i.update=="function"&&i.update(this.delta,this.elapsed),this.rendererManager.render(this.scene,this.camera)}catch{this._menuCinematicDisabled=!0,this._menuCinematicActive=!1}return}if(!(!this.isVisible||!this.gameStarted)){if(this.delta=Math.min(this.clock.getDelta(),this.maxDeltaTime),this.elapsed=this.clock.getElapsedTime(),this.qualityManager.update(this.delta),this.physicsSystem&&typeof this.physicsSystem.update=="function"){const t=this.systemManager.get("world");this.physicsSystem.update(this.delta,t,this.elapsed)}if(this.materialSystem&&typeof this.materialSystem.update=="function"&&this.materialSystem.update(this.delta,this.elapsed),this.systemManager.update(this.delta,this.elapsed),this.performanceMonitor.update(this.rendererManager.renderer,this,this.delta),this.rendererManager.render(this.scene,this.camera),this.isMobile&&this._frameCounter%120===0){const t=this.performanceMonitor.generateReport();this.qualityManager.updateFromPerformance(t)}if(this.mobileUI&&typeof this.mobileUI.update=="function"){const t=this.systemManager.get("player");t&&t.localPlayer&&this.mobileUI.update(this.delta,t.localPlayer)}this._frameCounter++,this.stats&&this.stats.update()}}}onResize(){this.rendererManager.updateResolution()}onVisibilityChange(){this.isVisible=document.visibilityState==="visible",this.systemManager.handleVisibilityChange(this.isVisible),this.rendererManager.handleVisibilityChange(this.isVisible),this.qualityManager.handleVisibilityChange(this.isVisible)}destroy(){this.systemManager.destroy(),this.rendererManager.destroy(),this.qualityManager.destroy(),this.input.destroy(),this.assets.destroy(),this.introScreen&&this.introScreen.destroy(),this.mobileUI&&typeof this.mobileUI.destroy=="function"&&this.mobileUI.destroy(),this.stats&&(document.body.removeChild(this.stats.dom),document.documentElement.style.removeProperty("--vc-dev-hud-offset")),this._unsubscribeHud&&this._unsubscribeHud(),this.isRunning=!1}toggleMinimap(){const e=this.systemManager.get("minimap");e&&typeof e.toggle=="function"&&e.toggle()}toggleHighQualityMode(){const e=!this.qualityManager.highQualityMode;this.qualityManager.highQualityMode=e,y.info(`High quality mode: ${e?"enabled":"disabled"}`);const t=this.systemManager.get("carpetTrail");t&&(t.enableRibbonTrail=!this.isMobile||e,t.enableSteamParticles=!this.isMobile||e,e?(t.maxParticles=this.isMobile?50:150,t.maxMotionLines=this.isMobile?4:10):(t.maxParticles=this.isMobile?25:75,t.maxMotionLines=this.isMobile?2:6));const s=this.systemManager.get("atmosphere");s&&(s.enableBirds=!this.isMobile||e,s.cloudCount=e?this.isMobile?40:80:this.isMobile?25:50);const i=this.systemManager.get("vegetation");return i&&(i.vegetationDistance=e?this.isMobile?2:3:this.isMobile?1:2),e}}export{hr as E}; diff --git a/dist/assets/index-CJXPofkh.js b/dist/assets/index-CJXPofkh.js deleted file mode 100644 index a83ec6e..0000000 --- a/dist/assets/index-CJXPofkh.js +++ /dev/null @@ -1 +0,0 @@ -import{E as c}from"./game-BePiI9nb.js";import"./three-CH6znIGP.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const o of e)if(o.type==="childList")for(const r of o.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&i(r)}).observe(document,{childList:!0,subtree:!0});function s(e){const o={};return e.integrity&&(o.integrity=e.integrity),e.referrerPolicy&&(o.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?o.credentials="include":e.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(e){if(e.ep)return;e.ep=!0;const o=s(e);fetch(e.href,o)}})();function l(){window.getPerformanceReport=function(){return window.gameEngine?window.gameEngine.getPerformanceReport():(console.error("Game engine not initialized yet"),null)}}document.documentElement.style.setProperty("--app-font",'"Helvetica Neue", Helvetica, sans-serif');function a(){console.log("Device Detection Info:"),console.log("- Touch Points:",navigator.maxTouchPoints),console.log("- ontouchstart:","ontouchstart"in window),console.log("- User Agent:",navigator.userAgent),console.log("- Screen Size:",window.innerWidth,"x",window.innerHeight)}document.addEventListener("DOMContentLoaded",async()=>{try{a(),await new c().initialize(),l(),console.log("SkyBloom initialized successfully!"),console.log("Use window.getPerformanceReport() to view performance metrics")}catch(t){console.error("Error initializing game:",t),document.getElementById("loading-text").textContent="Error loading game. Please refresh."}}); diff --git a/dist/assets/models/carpet.glb b/dist/assets/models/carpet.glb deleted file mode 100644 index 442769a..0000000 --- a/dist/assets/models/carpet.glb +++ /dev/null @@ -1,78 +0,0 @@ -{ - "asset": { - "generator": "Claude Placeholder", - "version": "2.0" - }, - "scene": 0, - "scenes": [ - { - "name": "PlaceholderScene", - "nodes": [0] - } - ], - "nodes": [ - { - "mesh": 0, - "name": "PlaceholderCarpet" - } - ], - "meshes": [ - { - "name": "Carpet", - "primitives": [ - { - "attributes": { - "POSITION": 0, - "NORMAL": 1 - }, - "indices": 2 - } - ] - } - ], - "accessors": [ - { - "bufferView": 0, - "componentType": 5126, - "count": 4, - "max": [1, 0, 1], - "min": [-1, 0, -1], - "type": "VEC3" - }, - { - "bufferView": 1, - "componentType": 5126, - "count": 4, - "type": "VEC3" - }, - { - "bufferView": 2, - "componentType": 5123, - "count": 6, - "type": "SCALAR" - } - ], - "bufferViews": [ - { - "buffer": 0, - "byteLength": 48, - "byteOffset": 0 - }, - { - "buffer": 0, - "byteLength": 48, - "byteOffset": 48 - }, - { - "buffer": 0, - "byteLength": 12, - "byteOffset": 96 - } - ], - "buffers": [ - { - "byteLength": 108, - "uri": "data:application/octet-stream;base64,AACAvwAAAAAAAIA/AACAPwAAAAAAAIA/AACAvwAAAAAAAIC/AACAPwAAAAAAAIC/AAAAAAAAgD8AAAAAAACAPwAAAAAAAIA/AAAAAAAAgD8AAAAAAACAPwAAAAAAAIA/AAAAAAAAgD8AAAAAAACAPwAAAAABAAIAAAACAAMA" - } - ] -} \ No newline at end of file diff --git a/dist/assets/models/default_tree.glb b/dist/assets/models/default_tree.glb deleted file mode 100644 index 1324744..0000000 Binary files a/dist/assets/models/default_tree.glb and /dev/null differ diff --git a/dist/assets/models/detailed_tree.glb b/dist/assets/models/detailed_tree.glb deleted file mode 100644 index 8d59ea4..0000000 Binary files a/dist/assets/models/detailed_tree.glb and /dev/null differ diff --git a/dist/assets/models/fat_tree.glb b/dist/assets/models/fat_tree.glb deleted file mode 100644 index 55862c4..0000000 Binary files a/dist/assets/models/fat_tree.glb and /dev/null differ diff --git a/dist/assets/models/mana.glb b/dist/assets/models/mana.glb deleted file mode 100644 index ace238fb..0000000 --- a/dist/assets/models/mana.glb +++ /dev/null @@ -1,78 +0,0 @@ -{ - "asset": { - "generator": "Claude Placeholder", - "version": "2.0" - }, - "scene": 0, - "scenes": [ - { - "name": "PlaceholderScene", - "nodes": [0] - } - ], - "nodes": [ - { - "mesh": 0, - "name": "PlaceholderMana" - } - ], - "meshes": [ - { - "name": "Mana", - "primitives": [ - { - "attributes": { - "POSITION": 0, - "NORMAL": 1 - }, - "indices": 2 - } - ] - } - ], - "accessors": [ - { - "bufferView": 0, - "componentType": 5126, - "count": 4, - "max": [1, 1, 1], - "min": [-1, -1, -1], - "type": "VEC3" - }, - { - "bufferView": 1, - "componentType": 5126, - "count": 4, - "type": "VEC3" - }, - { - "bufferView": 2, - "componentType": 5123, - "count": 6, - "type": "SCALAR" - } - ], - "bufferViews": [ - { - "buffer": 0, - "byteLength": 48, - "byteOffset": 0 - }, - { - "buffer": 0, - "byteLength": 48, - "byteOffset": 48 - }, - { - "buffer": 0, - "byteLength": 12, - "byteOffset": 96 - } - ], - "buffers": [ - { - "byteLength": 108, - "uri": "data:application/octet-stream;base64,AACAvwAAAAAAAIA/AACAPwAAAAAAAIA/AACAvwAAAAAAAIC/AACAPwAAAAAAAIC/AAAAAAAAgD8AAAAAAACAPwAAAAAAAIA/AAAAAAAAgD8AAAAAAACAPwAAAAAAAIA/AAAAAAAAgD8AAAAAAACAPwAAAAABAAIAAAACAAMA" - } - ] -} \ No newline at end of file diff --git a/dist/assets/models/oak_tree.glb b/dist/assets/models/oak_tree.glb deleted file mode 100644 index b136723..0000000 Binary files a/dist/assets/models/oak_tree.glb and /dev/null differ diff --git a/dist/assets/models/palm_tree.glb b/dist/assets/models/palm_tree.glb deleted file mode 100644 index f9bcf4d..0000000 Binary files a/dist/assets/models/palm_tree.glb and /dev/null differ diff --git a/dist/assets/models/pine_tree.glb b/dist/assets/models/pine_tree.glb deleted file mode 100644 index f11a595..0000000 Binary files a/dist/assets/models/pine_tree.glb and /dev/null differ diff --git a/dist/assets/quests.json b/dist/assets/quests.json deleted file mode 100644 index 998a074..0000000 --- a/dist/assets/quests.json +++ /dev/null @@ -1,69 +0,0 @@ -[ - { - "id": "collect_mana_50", - "name": "Collect 50 Mana", - "description": "Gather mana orbs scattered across the world to power your magical journey.", - "objectives": [ - { - "type": "collectMana", - "target": 50, - "current": 0 - } - ], - "rewards": { - "mana": 20, - "unlockSpell": true - }, - "status": "pending" - }, - { - "id": "visit_landmarks_3", - "name": "Visit 3 Landmarks", - "description": "Discover ancient ruins, magical circles, and crystal formations in the world.", - "objectives": [ - { - "type": "visitLandmarks", - "target": 3, - "current": 0 - } - ], - "rewards": { - "mana": 30 - }, - "status": "pending" - }, - { - "id": "cast_wind_glide", - "name": "Cast Wind Glide Once", - "description": "Use the Wind Glide spell to experience faster exploration.", - "objectives": [ - { - "type": "castSpell", - "spellId": "wind_glide", - "target": 1, - "current": 0 - } - ], - "rewards": { - "mana": 10, - "unlockSpell": true - }, - "status": "pending" - }, - { - "id": "explore_1km", - "name": "Explore 1km", - "description": "Travel a total distance of 1 kilometer through the magical world.", - "objectives": [ - { - "type": "exploreDistance", - "target": 1000, - "current": 0 - } - ], - "rewards": { - "mana": 25 - }, - "status": "pending" - } -] \ No newline at end of file diff --git a/dist/assets/spells.json b/dist/assets/spells.json deleted file mode 100644 index 90257bd..0000000 --- a/dist/assets/spells.json +++ /dev/null @@ -1,84 +0,0 @@ -[ - { - "id": "wind_glide", - "name": "Wind Glide", - "manaCost": 10, - "cooldown": 30, - "effect": { - "type": "speed_boost", - "duration": 10, - "value": 1.5 - }, - "unlockCondition": { - "type": "mana", - "value": 100 - }, - "vfx": { - "type": "aura", - "color": "cyan" - }, - "integration": ["PlayerPhysics"] - }, - { - "id": "aether_shield", - "name": "Aether Shield", - "manaCost": 15, - "cooldown": 60, - "effect": { - "type": "invulnerability", - "duration": 5, - "value": true - }, - "unlockCondition": { - "type": "mana", - "value": 200 - }, - "vfx": { - "type": "shield", - "color": "blue" - }, - "integration": ["PlayerSystem"] - }, - { - "id": "mana_reveal", - "name": "Mana Reveal", - "manaCost": 5, - "cooldown": 45, - "effect": { - "type": "scan", - "duration": 0, - "value": { - "radius": 500 - } - }, - "unlockCondition": { - "type": "landmarks", - "value": 3 - }, - "vfx": { - "type": "scan", - "color": "green" - }, - "integration": ["WorldSystem", "LandmarkSystem"] - }, - { - "id": "essence_surge", - "name": "Essence Surge", - "manaCost": 20, - "cooldown": 120, - "effect": { - "type": "mana_multiplier", - "duration": 20, - "value": 2 - }, - "unlockCondition": { - "type": "mana", - "value": 500 - }, - "vfx": { - "type": "aura", - "color": "purple" - }, - "integration": ["PlayerSystem"] - } -] \ No newline at end of file diff --git a/dist/assets/textures/carpet.jpg b/dist/assets/textures/carpet.jpg deleted file mode 100644 index 566a4c3..0000000 --- a/dist/assets/textures/carpet.jpg +++ /dev/null @@ -1,5 +0,0 @@ -<<<<<<< HEAD - -======= - ->>>>>>> 3ba54ef83a25f19ba1b39a083bea4b653822e498 diff --git a/dist/assets/textures/moon.jpg b/dist/assets/textures/moon.jpg deleted file mode 100644 index 81e639c..0000000 Binary files a/dist/assets/textures/moon.jpg and /dev/null differ diff --git a/dist/assets/textures/particles.jpg b/dist/assets/textures/particles.jpg deleted file mode 100644 index cd20159..0000000 Binary files a/dist/assets/textures/particles.jpg and /dev/null differ diff --git a/dist/assets/textures/particles.png b/dist/assets/textures/particles.png deleted file mode 100644 index d605a6c..0000000 Binary files a/dist/assets/textures/particles.png and /dev/null differ diff --git a/dist/assets/textures/sky.jpg b/dist/assets/textures/sky.jpg deleted file mode 100644 index 566a4c3..0000000 --- a/dist/assets/textures/sky.jpg +++ /dev/null @@ -1,5 +0,0 @@ -<<<<<<< HEAD - -======= - ->>>>>>> 3ba54ef83a25f19ba1b39a083bea4b653822e498 diff --git a/dist/assets/textures/terrain.jpg b/dist/assets/textures/terrain.jpg deleted file mode 100644 index 566a4c3..0000000 --- a/dist/assets/textures/terrain.jpg +++ /dev/null @@ -1,5 +0,0 @@ -<<<<<<< HEAD - -======= - ->>>>>>> 3ba54ef83a25f19ba1b39a083bea4b653822e498 diff --git a/dist/assets/three-CH6znIGP.js b/dist/assets/three-CH6znIGP.js deleted file mode 100644 index 75af0d8..0000000 --- a/dist/assets/three-CH6znIGP.js +++ /dev/null @@ -1,3686 +0,0 @@ -/** - * @license - * Copyright 2010-2023 Three.js Authors - * SPDX-License-Identifier: MIT - */const jr="160";const If=0;const Nf=2;const Ff=0,Of=1,Bf=2;const zf=1,Gf=2;const Vf=2;const Hf=4;const fs="attached",fo="detached";const kf=1e3,Wf=1001,Xf=1002,qf=1003,Yf=1004,Kf=1005,Jf=1006,jf=1007,Zf=1008,$f=1008;const Qf=1023;const tp=2300,ep=2301;const np=0,ip=1,rp=2;const Pe="",fe="srgb",Je="srgb-linear",Zr="display-p3",sr="display-p3-linear",$i="linear",Qt="srgb",Qi="rec709",tr="p3";const sp=35048,ps="300 es";class kn{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[t]===void 0&&(n[t]=[]),n[t].indexOf(e)===-1&&n[t].push(e)}hasEventListener(t,e){if(this._listeners===void 0)return!1;const n=this._listeners;return n[t]!==void 0&&n[t].indexOf(e)!==-1}removeEventListener(t,e){if(this._listeners===void 0)return;const i=this._listeners[t];if(i!==void 0){const s=i.indexOf(e);s!==-1&&i.splice(s,1)}}dispatchEvent(t){if(this._listeners===void 0)return;const n=this._listeners[t.type];if(n!==void 0){t.target=this;const i=n.slice(0);for(let s=0,o=i.length;s>8&255]+ge[r>>16&255]+ge[r>>24&255]+"-"+ge[t&255]+ge[t>>8&255]+"-"+ge[t>>16&15|64]+ge[t>>24&255]+"-"+ge[e&63|128]+ge[e>>8&255]+"-"+ge[e>>16&255]+ge[e>>24&255]+ge[n&255]+ge[n>>8&255]+ge[n>>16&255]+ge[n>>24&255]).toLowerCase()}function de(r,t,e){return Math.max(t,Math.min(e,r))}function $r(r,t){return(r%t+t)%t}function po(r,t,e,n,i){return n+(r-t)*(i-n)/(e-t)}function mo(r,t,e){return r!==t?(e-r)/(t-r):0}function oi(r,t,e){return(1-e)*r+e*t}function go(r,t,e,n){return oi(r,t,1-Math.exp(-e*n))}function _o(r,t=1){return t-Math.abs($r(r,t*2)-t)}function vo(r,t,e){return r<=t?0:r>=e?1:(r=(r-t)/(e-t),r*r*(3-2*r))}function xo(r,t,e){return r<=t?0:r>=e?1:(r=(r-t)/(e-t),r*r*r*(r*(r*6-15)+10))}function Mo(r,t){return r+Math.floor(Math.random()*(t-r+1))}function So(r,t){return r+Math.random()*(t-r)}function yo(r){return r*(.5-Math.random())}function Eo(r){r!==void 0&&(ms=r);let t=ms+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function To(r){return r*ai}function bo(r){return r*Vn}function Yr(r){return(r&r-1)===0&&r!==0}function Ao(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))}function er(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))}function wo(r,t,e,n,i){const s=Math.cos,o=Math.sin,a=s(e/2),l=o(e/2),c=s((t+n)/2),h=o((t+n)/2),u=s((t-n)/2),d=o((t-n)/2),p=s((n-t)/2),g=o((n-t)/2);switch(i){case"XYX":r.set(a*h,l*u,l*d,a*c);break;case"YZY":r.set(l*d,a*h,l*u,a*c);break;case"ZXZ":r.set(l*u,l*d,a*h,a*c);break;case"XZX":r.set(a*h,l*g,l*p,a*c);break;case"YXY":r.set(l*p,a*h,l*g,a*c);break;case"ZYZ":r.set(l*g,l*p,a*h,a*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Ge(r,t){switch(t.constructor){case Float32Array:return r;case Uint32Array:return r/4294967295;case Uint16Array:return r/65535;case Uint8Array:return r/255;case Int32Array:return Math.max(r/2147483647,-1);case Int16Array:return Math.max(r/32767,-1);case Int8Array:return Math.max(r/127,-1);default:throw new Error("Invalid component type.")}}function qt(r,t){switch(t.constructor){case Float32Array:return r;case Uint32Array:return Math.round(r*4294967295);case Uint16Array:return Math.round(r*65535);case Uint8Array:return Math.round(r*255);case Int32Array:return Math.round(r*2147483647);case Int16Array:return Math.round(r*32767);case Int8Array:return Math.round(r*127);default:throw new Error("Invalid component type.")}}const ap={DEG2RAD:ai,RAD2DEG:Vn,generateUUID:Oe,clamp:de,euclideanModulo:$r,mapLinear:po,inverseLerp:mo,lerp:oi,damp:go,pingpong:_o,smoothstep:vo,smootherstep:xo,randInt:Mo,randFloat:So,randFloatSpread:yo,seededRandom:Eo,degToRad:To,radToDeg:bo,isPowerOfTwo:Yr,ceilPowerOfTwo:Ao,floorPowerOfTwo:er,setQuaternionFromProperEuler:wo,normalize:qt,denormalize:Ge};class ct{constructor(t=0,e=0){ct.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,n=this.y,i=t.elements;return this.x=i[0]*e+i[3]*n+i[6],this.y=i[1]*e+i[4]*n+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(de(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),s=this.x-t.x,o=this.y-t.y;return this.x=s*n-o*i+t.x,this.y=s*i+o*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Bt{constructor(t,e,n,i,s,o,a,l,c){Bt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,n,i,s,o,a,l,c)}set(t,e,n,i,s,o,a,l,c){const h=this.elements;return h[0]=t,h[1]=i,h[2]=a,h[3]=e,h[4]=s,h[5]=l,h[6]=n,h[7]=o,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,s=this.elements,o=n[0],a=n[3],l=n[6],c=n[1],h=n[4],u=n[7],d=n[2],p=n[5],g=n[8],v=i[0],m=i[3],f=i[6],S=i[1],_=i[4],b=i[7],C=i[2],A=i[5],w=i[8];return s[0]=o*v+a*S+l*C,s[3]=o*m+a*_+l*A,s[6]=o*f+a*b+l*w,s[1]=c*v+h*S+u*C,s[4]=c*m+h*_+u*A,s[7]=c*f+h*b+u*w,s[2]=d*v+p*S+g*C,s[5]=d*m+p*_+g*A,s[8]=d*f+p*b+g*w,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[1],i=t[2],s=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8];return e*o*h-e*a*c-n*s*h+n*a*l+i*s*c-i*o*l}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],s=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8],u=h*o-a*c,d=a*l-h*s,p=c*s-o*l,g=e*u+n*d+i*p;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return t[0]=u*v,t[1]=(i*c-h*n)*v,t[2]=(a*n-i*o)*v,t[3]=d*v,t[4]=(h*e-i*l)*v,t[5]=(i*s-a*e)*v,t[6]=p*v,t[7]=(n*l-c*e)*v,t[8]=(o*e-n*s)*v,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,i,s,o,a){const l=Math.cos(s),c=Math.sin(s);return this.set(n*l,n*c,-n*(l*o+c*a)+o+t,-i*c,i*l,-i*(-c*o+l*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(mr.makeScale(t,e)),this}rotate(t){return this.premultiply(mr.makeRotation(-t)),this}translate(t,e){return this.premultiply(mr.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,n=t.elements;for(let i=0;i<9;i++)if(e[i]!==n[i])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return new this.constructor().fromArray(this.elements)}}const mr=new Bt;function Ta(r){for(let t=r.length-1;t>=0;--t)if(r[t]>=65535)return!0;return!1}function ui(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function Ro(){const r=ui("canvas");return r.style.display="block",r}const gs={};function li(r){r in gs||(gs[r]=!0,console.warn(r))}const _s=new Bt().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),vs=new Bt().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),_i={[Je]:{transfer:$i,primaries:Qi,toReference:r=>r,fromReference:r=>r},[fe]:{transfer:Qt,primaries:Qi,toReference:r=>r.convertSRGBToLinear(),fromReference:r=>r.convertLinearToSRGB()},[sr]:{transfer:$i,primaries:tr,toReference:r=>r.applyMatrix3(vs),fromReference:r=>r.applyMatrix3(_s)},[Zr]:{transfer:Qt,primaries:tr,toReference:r=>r.convertSRGBToLinear().applyMatrix3(vs),fromReference:r=>r.applyMatrix3(_s).convertLinearToSRGB()}},Co=new Set([Je,sr]),Kt={enabled:!0,_workingColorSpace:Je,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(r){if(!Co.has(r))throw new Error(`Unsupported working color space, "${r}".`);this._workingColorSpace=r},convert:function(r,t,e){if(this.enabled===!1||t===e||!t||!e)return r;const n=_i[t].toReference,i=_i[e].fromReference;return i(n(r))},fromWorkingColorSpace:function(r,t){return this.convert(r,this._workingColorSpace,t)},toWorkingColorSpace:function(r,t){return this.convert(r,t,this._workingColorSpace)},getPrimaries:function(r){return _i[r].primaries},getTransfer:function(r){return r===Pe?$i:_i[r].transfer}};function Gn(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function gr(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}let vn;class ba{static getDataURL(t){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{vn===void 0&&(vn=ui("canvas")),vn.width=t.width,vn.height=t.height;const n=vn.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),e=vn}return e.width>2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){const e=ui("canvas");e.width=t.width,e.height=t.height;const n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);const i=n.getImageData(0,0,t.width,t.height),s=i.data;for(let o=0;o0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==300)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case 1e3:t.x=t.x-Math.floor(t.x);break;case 1001:t.x=t.x<0?0:1;break;case 1002:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case 1e3:t.y=t.y-Math.floor(t.y);break;case 1001:t.y=t.y<0?0:1;break;case 1002:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return li("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===fe?3001:3e3}set encoding(t){li("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=t===3001?fe:Pe}}ve.DEFAULT_IMAGE=null;ve.DEFAULT_MAPPING=300;ve.DEFAULT_ANISOTROPY=1;class Jt{constructor(t=0,e=0,n=0,i=1){Jt.prototype.isVector4=!0,this.x=t,this.y=e,this.z=n,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,i){return this.x=t,this.y=e,this.z=n,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,s=this.w,o=t.elements;return this.x=o[0]*e+o[4]*n+o[8]*i+o[12]*s,this.y=o[1]*e+o[5]*n+o[9]*i+o[13]*s,this.z=o[2]*e+o[6]*n+o[10]*i+o[14]*s,this.w=o[3]*e+o[7]*n+o[11]*i+o[15]*s,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,i,s;const l=t.elements,c=l[0],h=l[4],u=l[8],d=l[1],p=l[5],g=l[9],v=l[2],m=l[6],f=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-v)<.01&&Math.abs(g-m)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+v)<.1&&Math.abs(g+m)<.1&&Math.abs(c+p+f-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const _=(c+1)/2,b=(p+1)/2,C=(f+1)/2,A=(h+d)/4,w=(u+v)/4,U=(g+m)/4;return _>b&&_>C?_<.01?(n=0,i=.707106781,s=.707106781):(n=Math.sqrt(_),i=A/n,s=w/n):b>C?b<.01?(n=.707106781,i=0,s=.707106781):(i=Math.sqrt(b),n=A/i,s=U/i):C<.01?(n=.707106781,i=.707106781,s=0):(s=Math.sqrt(C),n=w/s,i=U/s),this.set(n,i,s,e),this}let S=Math.sqrt((m-g)*(m-g)+(u-v)*(u-v)+(d-h)*(d-h));return Math.abs(S)<.001&&(S=1),this.x=(m-g)/S,this.y=(u-v)/S,this.z=(d-h)/S,this.w=Math.acos((c+p+f-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this.w=t.w+(e.w-t.w)*n,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Do extends kn{constructor(t=1,e=1,n={}){super(),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=1,this.scissor=new Jt(0,0,t,e),this.scissorTest=!1,this.viewport=new Jt(0,0,t,e);const i={width:t,height:e,depth:1};n.encoding!==void 0&&(li("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),n.colorSpace=n.encoding===3001?fe:Pe),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},n),this.texture=new ve(i,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=n.generateMipmaps,this.texture.internalFormat=n.internalFormat,this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.depthTexture=n.depthTexture,this.samples=n.samples}setSize(t,e,n=1){(this.width!==t||this.height!==e||this.depth!==n)&&(this.width=t,this.height=e,this.depth=n,this.texture.image.width=t,this.texture.image.height=e,this.texture.image.depth=n,this.dispose()),this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.texture=t.texture.clone(),this.texture.isRenderTargetTexture=!0;const e=Object.assign({},t.texture.image);return this.texture.source=new Aa(e),this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,t.depthTexture!==null&&(this.depthTexture=t.depthTexture.clone()),this.samples=t.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class gn extends Do{constructor(t=1,e=1,n={}){super(t,e,n),this.isWebGLRenderTarget=!0}}class wa extends ve{constructor(t=null,e=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:t,width:e,height:n,depth:i},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Uo extends ve{constructor(t=null,e=1,n=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:n,depth:i},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Wn{constructor(t=0,e=0,n=0,i=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=n,this._w=i}static slerpFlat(t,e,n,i,s,o,a){let l=n[i+0],c=n[i+1],h=n[i+2],u=n[i+3];const d=s[o+0],p=s[o+1],g=s[o+2],v=s[o+3];if(a===0){t[e+0]=l,t[e+1]=c,t[e+2]=h,t[e+3]=u;return}if(a===1){t[e+0]=d,t[e+1]=p,t[e+2]=g,t[e+3]=v;return}if(u!==v||l!==d||c!==p||h!==g){let m=1-a;const f=l*d+c*p+h*g+u*v,S=f>=0?1:-1,_=1-f*f;if(_>Number.EPSILON){const C=Math.sqrt(_),A=Math.atan2(C,f*S);m=Math.sin(m*A)/C,a=Math.sin(a*A)/C}const b=a*S;if(l=l*m+d*b,c=c*m+p*b,h=h*m+g*b,u=u*m+v*b,m===1-a){const C=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=C,c*=C,h*=C,u*=C}}t[e]=l,t[e+1]=c,t[e+2]=h,t[e+3]=u}static multiplyQuaternionsFlat(t,e,n,i,s,o){const a=n[i],l=n[i+1],c=n[i+2],h=n[i+3],u=s[o],d=s[o+1],p=s[o+2],g=s[o+3];return t[e]=a*g+h*u+l*p-c*d,t[e+1]=l*g+h*d+c*u-a*p,t[e+2]=c*g+h*p+a*d-l*u,t[e+3]=h*g-a*u-l*d-c*p,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,i){return this._x=t,this._y=e,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const n=t._x,i=t._y,s=t._z,o=t._order,a=Math.cos,l=Math.sin,c=a(n/2),h=a(i/2),u=a(s/2),d=l(n/2),p=l(i/2),g=l(s/2);switch(o){case"XYZ":this._x=d*h*u+c*p*g,this._y=c*p*u-d*h*g,this._z=c*h*g+d*p*u,this._w=c*h*u-d*p*g;break;case"YXZ":this._x=d*h*u+c*p*g,this._y=c*p*u-d*h*g,this._z=c*h*g-d*p*u,this._w=c*h*u+d*p*g;break;case"ZXY":this._x=d*h*u-c*p*g,this._y=c*p*u+d*h*g,this._z=c*h*g+d*p*u,this._w=c*h*u-d*p*g;break;case"ZYX":this._x=d*h*u-c*p*g,this._y=c*p*u+d*h*g,this._z=c*h*g-d*p*u,this._w=c*h*u+d*p*g;break;case"YZX":this._x=d*h*u+c*p*g,this._y=c*p*u+d*h*g,this._z=c*h*g-d*p*u,this._w=c*h*u-d*p*g;break;case"XZY":this._x=d*h*u-c*p*g,this._y=c*p*u-d*h*g,this._z=c*h*g+d*p*u,this._w=c*h*u+d*p*g;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const n=e/2,i=Math.sin(n);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,n=e[0],i=e[4],s=e[8],o=e[1],a=e[5],l=e[9],c=e[2],h=e[6],u=e[10],d=n+a+u;if(d>0){const p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-l)*p,this._y=(s-c)*p,this._z=(o-i)*p}else if(n>a&&n>u){const p=2*Math.sqrt(1+n-a-u);this._w=(h-l)/p,this._x=.25*p,this._y=(i+o)/p,this._z=(s+c)/p}else if(a>u){const p=2*Math.sqrt(1+a-n-u);this._w=(s-c)/p,this._x=(i+o)/p,this._y=.25*p,this._z=(l+h)/p}else{const p=2*Math.sqrt(1+u-n-a);this._w=(o-i)/p,this._x=(s+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return nMath.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(de(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(n===0)return this;const i=Math.min(1,e/n);return this.slerp(t,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,s=t._z,o=t._w,a=e._x,l=e._y,c=e._z,h=e._w;return this._x=n*h+o*a+i*c-s*l,this._y=i*h+o*l+s*a-n*c,this._z=s*h+o*c+n*l-i*a,this._w=o*h-n*a-i*l-s*c,this._onChangeCallback(),this}slerp(t,e){if(e===0)return this;if(e===1)return this.copy(t);const n=this._x,i=this._y,s=this._z,o=this._w;let a=o*t._w+n*t._x+i*t._y+s*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=o,this._x=n,this._y=i,this._z=s,this;const l=1-a*a;if(l<=Number.EPSILON){const p=1-e;return this._w=p*o+e*this._w,this._x=p*n+e*this._x,this._y=p*i+e*this._y,this._z=p*s+e*this._z,this.normalize(),this}const c=Math.sqrt(l),h=Math.atan2(c,a),u=Math.sin((1-e)*h)/c,d=Math.sin(e*h)/c;return this._w=o*u+this._w*d,this._x=n*u+this._x*d,this._y=i*u+this._y*d,this._z=s*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){const t=Math.random(),e=Math.sqrt(1-t),n=Math.sqrt(t),i=2*Math.PI*Math.random(),s=2*Math.PI*Math.random();return this.set(e*Math.cos(i),n*Math.sin(s),n*Math.cos(s),e*Math.sin(i))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class R{constructor(t=0,e=0,n=0){R.prototype.isVector3=!0,this.x=t,this.y=e,this.z=n}set(t,e,n){return n===void 0&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(xs.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(xs.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,s=t.elements;return this.x=s[0]*e+s[3]*n+s[6]*i,this.y=s[1]*e+s[4]*n+s[7]*i,this.z=s[2]*e+s[5]*n+s[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,s=t.elements,o=1/(s[3]*e+s[7]*n+s[11]*i+s[15]);return this.x=(s[0]*e+s[4]*n+s[8]*i+s[12])*o,this.y=(s[1]*e+s[5]*n+s[9]*i+s[13])*o,this.z=(s[2]*e+s[6]*n+s[10]*i+s[14])*o,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,s=t.x,o=t.y,a=t.z,l=t.w,c=2*(o*i-a*n),h=2*(a*e-s*i),u=2*(s*n-o*e);return this.x=e+l*c+o*u-a*h,this.y=n+l*h+a*c-s*u,this.z=i+l*u+s*h-o*c,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,n=this.y,i=this.z,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i,this.y=s[1]*e+s[5]*n+s[9]*i,this.z=s[2]*e+s[6]*n+s[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,s=t.z,o=e.x,a=e.y,l=e.z;return this.x=i*l-s*a,this.y=s*o-n*l,this.z=n*a-i*o,this}projectOnVector(t){const e=t.lengthSq();if(e===0)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return vr.copy(this).projectOnVector(t),this.sub(vr)}reflect(t){return this.sub(vr.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(de(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){const i=Math.sin(e)*t;return this.x=i*Math.sin(n),this.y=Math.cos(e)*t,this.z=i*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=(Math.random()-.5)*2,e=Math.random()*Math.PI*2,n=Math.sqrt(1-t**2);return this.x=n*Math.cos(e),this.y=n*Math.sin(e),this.z=t,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const vr=new R,xs=new Wn;class sn{constructor(t=new R(1/0,1/0,1/0),e=new R(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)}intersectsSphere(t){return this.clampPoint(t.center,Ue),Ue.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(jn),xi.subVectors(this.max,jn),xn.subVectors(t.a,jn),Mn.subVectors(t.b,jn),Sn.subVectors(t.c,jn),$e.subVectors(Mn,xn),Qe.subVectors(Sn,Mn),cn.subVectors(xn,Sn);let e=[0,-$e.z,$e.y,0,-Qe.z,Qe.y,0,-cn.z,cn.y,$e.z,0,-$e.x,Qe.z,0,-Qe.x,cn.z,0,-cn.x,-$e.y,$e.x,0,-Qe.y,Qe.x,0,-cn.y,cn.x,0];return!xr(e,xn,Mn,Sn,xi)||(e=[1,0,0,0,1,0,0,0,1],!xr(e,xn,Mn,Sn,xi))?!1:(Mi.crossVectors($e,Qe),e=[Mi.x,Mi.y,Mi.z],xr(e,xn,Mn,Sn,xi))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Ue).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(Ue).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(ke[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),ke[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),ke[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),ke[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),ke[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),ke[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),ke[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),ke[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(ke),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const ke=[new R,new R,new R,new R,new R,new R,new R,new R],Ue=new R,vi=new sn,xn=new R,Mn=new R,Sn=new R,$e=new R,Qe=new R,cn=new R,jn=new R,xi=new R,Mi=new R,hn=new R;function xr(r,t,e,n,i){for(let s=0,o=r.length-3;s<=o;s+=3){hn.fromArray(r,s);const a=i.x*Math.abs(hn.x)+i.y*Math.abs(hn.y)+i.z*Math.abs(hn.z),l=t.dot(hn),c=e.dot(hn),h=n.dot(hn);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>a)return!1}return!0}const Io=new sn,Zn=new R,Mr=new R;class je{constructor(t=new R,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const n=this.center;e!==void 0?n.copy(e):Io.setFromPoints(t).getCenter(n);let i=0;for(let s=0,o=t.length;sthis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Zn.subVectors(t,this.center);const e=Zn.lengthSq();if(e>this.radius*this.radius){const n=Math.sqrt(e),i=(n-this.radius)*.5;this.center.addScaledVector(Zn,i/n),this.radius+=i}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(Mr.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Zn.copy(t.center).add(Mr)),this.expandByPoint(Zn.copy(t.center).sub(Mr))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}}const We=new R,Sr=new R,Si=new R,tn=new R,yr=new R,yi=new R,Er=new R;class ar{constructor(t=new R,e=new R(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,We)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=We.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(We.copy(this.origin).addScaledVector(this.direction,e),We.distanceToSquared(t))}distanceSqToSegment(t,e,n,i){Sr.copy(t).add(e).multiplyScalar(.5),Si.copy(e).sub(t).normalize(),tn.copy(this.origin).sub(Sr);const s=t.distanceTo(e)*.5,o=-this.direction.dot(Si),a=tn.dot(this.direction),l=-tn.dot(Si),c=tn.lengthSq(),h=Math.abs(1-o*o);let u,d,p,g;if(h>0)if(u=o*l-a,d=o*a-l,g=s*h,u>=0)if(d>=-g)if(d<=g){const v=1/h;u*=v,d*=v,p=u*(u+o*d+2*a)+d*(o*u+d+2*l)+c}else d=s,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*l)+c;else d=-s,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*l)+c;else d<=-g?(u=Math.max(0,-(-o*s+a)),d=u>0?-s:Math.min(Math.max(-s,-l),s),p=-u*u+d*(d+2*l)+c):d<=g?(u=0,d=Math.min(Math.max(-s,-l),s),p=d*(d+2*l)+c):(u=Math.max(0,-(o*s+a)),d=u>0?s:Math.min(Math.max(-s,-l),s),p=-u*u+d*(d+2*l)+c);else d=o>0?-s:s,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(Sr).addScaledVector(Si,d),p}intersectSphere(t,e){We.subVectors(t.center,this.origin);const n=We.dot(this.direction),i=We.dot(We)-n*n,s=t.radius*t.radius;if(i>s)return null;const o=Math.sqrt(s-i),a=n-o,l=n+o;return l<0?null:a<0?this.at(l,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){const n=this.distanceToPlane(t);return n===null?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,s,o,a,l;const c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(t.min.x-d.x)*c,i=(t.max.x-d.x)*c):(n=(t.max.x-d.x)*c,i=(t.min.x-d.x)*c),h>=0?(s=(t.min.y-d.y)*h,o=(t.max.y-d.y)*h):(s=(t.max.y-d.y)*h,o=(t.min.y-d.y)*h),n>o||s>i||((s>n||isNaN(n))&&(n=s),(o=0?(a=(t.min.z-d.z)*u,l=(t.max.z-d.z)*u):(a=(t.max.z-d.z)*u,l=(t.min.z-d.z)*u),n>l||a>i)||((a>n||n!==n)&&(n=a),(l=0?n:i,e)}intersectsBox(t){return this.intersectBox(t,We)!==null}intersectTriangle(t,e,n,i,s){yr.subVectors(e,t),yi.subVectors(n,t),Er.crossVectors(yr,yi);let o=this.direction.dot(Er),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;tn.subVectors(this.origin,t);const l=a*this.direction.dot(yi.crossVectors(tn,yi));if(l<0)return null;const c=a*this.direction.dot(yr.cross(tn));if(c<0||l+c>o)return null;const h=-a*tn.dot(Er);return h<0?null:this.at(h/o,s)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Vt{constructor(t,e,n,i,s,o,a,l,c,h,u,d,p,g,v,m){Vt.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,n,i,s,o,a,l,c,h,u,d,p,g,v,m)}set(t,e,n,i,s,o,a,l,c,h,u,d,p,g,v,m){const f=this.elements;return f[0]=t,f[4]=e,f[8]=n,f[12]=i,f[1]=s,f[5]=o,f[9]=a,f[13]=l,f[2]=c,f[6]=h,f[10]=u,f[14]=d,f[3]=p,f[7]=g,f[11]=v,f[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Vt().fromArray(this.elements)}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){const e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,n=t.elements,i=1/yn.setFromMatrixColumn(t,0).length(),s=1/yn.setFromMatrixColumn(t,1).length(),o=1/yn.setFromMatrixColumn(t,2).length();return e[0]=n[0]*i,e[1]=n[1]*i,e[2]=n[2]*i,e[3]=0,e[4]=n[4]*s,e[5]=n[5]*s,e[6]=n[6]*s,e[7]=0,e[8]=n[8]*o,e[9]=n[9]*o,e[10]=n[10]*o,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,n=t.x,i=t.y,s=t.z,o=Math.cos(n),a=Math.sin(n),l=Math.cos(i),c=Math.sin(i),h=Math.cos(s),u=Math.sin(s);if(t.order==="XYZ"){const d=o*h,p=o*u,g=a*h,v=a*u;e[0]=l*h,e[4]=-l*u,e[8]=c,e[1]=p+g*c,e[5]=d-v*c,e[9]=-a*l,e[2]=v-d*c,e[6]=g+p*c,e[10]=o*l}else if(t.order==="YXZ"){const d=l*h,p=l*u,g=c*h,v=c*u;e[0]=d+v*a,e[4]=g*a-p,e[8]=o*c,e[1]=o*u,e[5]=o*h,e[9]=-a,e[2]=p*a-g,e[6]=v+d*a,e[10]=o*l}else if(t.order==="ZXY"){const d=l*h,p=l*u,g=c*h,v=c*u;e[0]=d-v*a,e[4]=-o*u,e[8]=g+p*a,e[1]=p+g*a,e[5]=o*h,e[9]=v-d*a,e[2]=-o*c,e[6]=a,e[10]=o*l}else if(t.order==="ZYX"){const d=o*h,p=o*u,g=a*h,v=a*u;e[0]=l*h,e[4]=g*c-p,e[8]=d*c+v,e[1]=l*u,e[5]=v*c+d,e[9]=p*c-g,e[2]=-c,e[6]=a*l,e[10]=o*l}else if(t.order==="YZX"){const d=o*l,p=o*c,g=a*l,v=a*c;e[0]=l*h,e[4]=v-d*u,e[8]=g*u+p,e[1]=u,e[5]=o*h,e[9]=-a*h,e[2]=-c*h,e[6]=p*u+g,e[10]=d-v*u}else if(t.order==="XZY"){const d=o*l,p=o*c,g=a*l,v=a*c;e[0]=l*h,e[4]=-u,e[8]=c*h,e[1]=d*u+v,e[5]=o*h,e[9]=p*u-g,e[2]=g*u-p,e[6]=a*h,e[10]=v*u+d}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(No,t,Fo)}lookAt(t,e,n){const i=this.elements;return be.subVectors(t,e),be.lengthSq()===0&&(be.z=1),be.normalize(),en.crossVectors(n,be),en.lengthSq()===0&&(Math.abs(n.z)===1?be.x+=1e-4:be.z+=1e-4,be.normalize(),en.crossVectors(n,be)),en.normalize(),Ei.crossVectors(be,en),i[0]=en.x,i[4]=Ei.x,i[8]=be.x,i[1]=en.y,i[5]=Ei.y,i[9]=be.y,i[2]=en.z,i[6]=Ei.z,i[10]=be.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,s=this.elements,o=n[0],a=n[4],l=n[8],c=n[12],h=n[1],u=n[5],d=n[9],p=n[13],g=n[2],v=n[6],m=n[10],f=n[14],S=n[3],_=n[7],b=n[11],C=n[15],A=i[0],w=i[4],U=i[8],M=i[12],T=i[1],z=i[5],H=i[9],tt=i[13],P=i[2],I=i[6],k=i[10],q=i[14],X=i[3],W=i[7],j=i[11],Q=i[15];return s[0]=o*A+a*T+l*P+c*X,s[4]=o*w+a*z+l*I+c*W,s[8]=o*U+a*H+l*k+c*j,s[12]=o*M+a*tt+l*q+c*Q,s[1]=h*A+u*T+d*P+p*X,s[5]=h*w+u*z+d*I+p*W,s[9]=h*U+u*H+d*k+p*j,s[13]=h*M+u*tt+d*q+p*Q,s[2]=g*A+v*T+m*P+f*X,s[6]=g*w+v*z+m*I+f*W,s[10]=g*U+v*H+m*k+f*j,s[14]=g*M+v*tt+m*q+f*Q,s[3]=S*A+_*T+b*P+C*X,s[7]=S*w+_*z+b*I+C*W,s[11]=S*U+_*H+b*k+C*j,s[15]=S*M+_*tt+b*q+C*Q,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[4],i=t[8],s=t[12],o=t[1],a=t[5],l=t[9],c=t[13],h=t[2],u=t[6],d=t[10],p=t[14],g=t[3],v=t[7],m=t[11],f=t[15];return g*(+s*l*u-i*c*u-s*a*d+n*c*d+i*a*p-n*l*p)+v*(+e*l*p-e*c*d+s*o*d-i*o*p+i*c*h-s*l*h)+m*(+e*c*u-e*a*p-s*o*u+n*o*p+s*a*h-n*c*h)+f*(-i*a*h-e*l*u+e*a*d+i*o*u-n*o*d+n*l*h)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){const i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=n),this}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],s=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8],u=t[9],d=t[10],p=t[11],g=t[12],v=t[13],m=t[14],f=t[15],S=u*m*c-v*d*c+v*l*p-a*m*p-u*l*f+a*d*f,_=g*d*c-h*m*c-g*l*p+o*m*p+h*l*f-o*d*f,b=h*v*c-g*u*c+g*a*p-o*v*p-h*a*f+o*u*f,C=g*u*l-h*v*l-g*a*d+o*v*d+h*a*m-o*u*m,A=e*S+n*_+i*b+s*C;if(A===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/A;return t[0]=S*w,t[1]=(v*d*s-u*m*s-v*i*p+n*m*p+u*i*f-n*d*f)*w,t[2]=(a*m*s-v*l*s+v*i*c-n*m*c-a*i*f+n*l*f)*w,t[3]=(u*l*s-a*d*s-u*i*c+n*d*c+a*i*p-n*l*p)*w,t[4]=_*w,t[5]=(h*m*s-g*d*s+g*i*p-e*m*p-h*i*f+e*d*f)*w,t[6]=(g*l*s-o*m*s-g*i*c+e*m*c+o*i*f-e*l*f)*w,t[7]=(o*d*s-h*l*s+h*i*c-e*d*c-o*i*p+e*l*p)*w,t[8]=b*w,t[9]=(g*u*s-h*v*s-g*n*p+e*v*p+h*n*f-e*u*f)*w,t[10]=(o*v*s-g*a*s+g*n*c-e*v*c-o*n*f+e*a*f)*w,t[11]=(h*a*s-o*u*s-h*n*c+e*u*c+o*n*p-e*a*p)*w,t[12]=C*w,t[13]=(h*v*i-g*u*i+g*n*d-e*v*d-h*n*m+e*u*m)*w,t[14]=(g*a*i-o*v*i-g*n*l+e*v*l+o*n*m-e*a*m)*w,t[15]=(o*u*i-h*a*i+h*n*l-e*u*l-o*n*d+e*a*d)*w,this}scale(t){const e=this.elements,n=t.x,i=t.y,s=t.z;return e[0]*=n,e[4]*=i,e[8]*=s,e[1]*=n,e[5]*=i,e[9]*=s,e[2]*=n,e[6]*=i,e[10]*=s,e[3]*=n,e[7]*=i,e[11]*=s,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,i))}makeTranslation(t,e,n){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const n=Math.cos(e),i=Math.sin(e),s=1-n,o=t.x,a=t.y,l=t.z,c=s*o,h=s*a;return this.set(c*o+n,c*a-i*l,c*l+i*a,0,c*a+i*l,h*a+n,h*l-i*o,0,c*l-i*a,h*l+i*o,s*l*l+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,i,s,o){return this.set(1,n,s,0,t,1,o,0,e,i,1,0,0,0,0,1),this}compose(t,e,n){const i=this.elements,s=e._x,o=e._y,a=e._z,l=e._w,c=s+s,h=o+o,u=a+a,d=s*c,p=s*h,g=s*u,v=o*h,m=o*u,f=a*u,S=l*c,_=l*h,b=l*u,C=n.x,A=n.y,w=n.z;return i[0]=(1-(v+f))*C,i[1]=(p+b)*C,i[2]=(g-_)*C,i[3]=0,i[4]=(p-b)*A,i[5]=(1-(d+f))*A,i[6]=(m+S)*A,i[7]=0,i[8]=(g+_)*w,i[9]=(m-S)*w,i[10]=(1-(d+v))*w,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,n){const i=this.elements;let s=yn.set(i[0],i[1],i[2]).length();const o=yn.set(i[4],i[5],i[6]).length(),a=yn.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),t.x=i[12],t.y=i[13],t.z=i[14],Ie.copy(this);const c=1/s,h=1/o,u=1/a;return Ie.elements[0]*=c,Ie.elements[1]*=c,Ie.elements[2]*=c,Ie.elements[4]*=h,Ie.elements[5]*=h,Ie.elements[6]*=h,Ie.elements[8]*=u,Ie.elements[9]*=u,Ie.elements[10]*=u,e.setFromRotationMatrix(Ie),n.x=s,n.y=o,n.z=a,this}makePerspective(t,e,n,i,s,o,a=2e3){const l=this.elements,c=2*s/(e-t),h=2*s/(n-i),u=(e+t)/(e-t),d=(n+i)/(n-i);let p,g;if(a===2e3)p=-(o+s)/(o-s),g=-2*o*s/(o-s);else if(a===2001)p=-o/(o-s),g=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=g,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,e,n,i,s,o,a=2e3){const l=this.elements,c=1/(e-t),h=1/(n-i),u=1/(o-s),d=(e+t)*c,p=(n+i)*h;let g,v;if(a===2e3)g=(o+s)*u,v=-2*u;else if(a===2001)g=s*u,v=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*h,l[9]=0,l[13]=-p,l[2]=0,l[6]=0,l[10]=v,l[14]=-g,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(t){const e=this.elements,n=t.elements;for(let i=0;i<16;i++)if(e[i]!==n[i])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}}const yn=new R,Ie=new Vt,No=new R(0,0,0),Fo=new R(1,1,1),en=new R,Ei=new R,be=new R,Ms=new Vt,Ss=new Wn;class or{constructor(t=0,e=0,n=0,i=or.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=n,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,i=this._order){return this._x=t,this._y=e,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){const i=t.elements,s=i[0],o=i[4],a=i[8],l=i[1],c=i[5],h=i[9],u=i[2],d=i[6],p=i[10];switch(e){case"XYZ":this._y=Math.asin(de(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-de(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,s),this._z=0);break;case"ZXY":this._x=Math.asin(de(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-de(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(de(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,s)):(this._x=0,this._y=Math.atan2(a,p));break;case"XZY":this._z=Math.asin(-de(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,n===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return Ms.makeRotationFromQuaternion(t),this.setFromRotationMatrix(Ms,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return Ss.setFromEuler(this),this.setFromQuaternion(Ss,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}or.DEFAULT_ORDER="XYZ";class Ra{constructor(){this.mask=1}set(t){this.mask=(1<>>0}enable(t){this.mask|=1<1){for(let e=0;e1){for(let n=0;n0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(a=>({boxInitialized:a.boxInitialized,boxMin:a.box.min.toArray(),boxMax:a.box.max.toArray(),sphereInitialized:a.sphereInitialized,sphereRadius:a.sphere.radius,sphereCenter:a.sphere.center.toArray()})),i.maxGeometryCount=this._maxGeometryCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(t),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()}));function s(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(t)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(t.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const l=a.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){i.children=[];for(let a=0;a0){i.animations=[];for(let a=0;a0&&(n.geometries=a),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),u.length>0&&(n.shapes=u),d.length>0&&(n.skeletons=d),p.length>0&&(n.animations=p),g.length>0&&(n.nodes=g)}return n.object=i,n;function o(a){const l=[];for(const c in a){const h=a[c];delete h.metadata,l.push(h)}return l}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let n=0;n0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(t,e,n,i,s){Ne.subVectors(i,e),qe.subVectors(n,e),Tr.subVectors(t,e);const o=Ne.dot(Ne),a=Ne.dot(qe),l=Ne.dot(Tr),c=qe.dot(qe),h=qe.dot(Tr),u=o*c-a*a;if(u===0)return s.set(0,0,0),null;const d=1/u,p=(c*l-a*h)*d,g=(o*h-a*l)*d;return s.set(1-p-g,g,p)}static containsPoint(t,e,n,i){return this.getBarycoord(t,e,n,i,Ye)===null?!1:Ye.x>=0&&Ye.y>=0&&Ye.x+Ye.y<=1}static getUV(t,e,n,i,s,o,a,l){return bi===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),bi=!0),this.getInterpolation(t,e,n,i,s,o,a,l)}static getInterpolation(t,e,n,i,s,o,a,l){return this.getBarycoord(t,e,n,i,Ye)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,Ye.x),l.addScaledVector(o,Ye.y),l.addScaledVector(a,Ye.z),l)}static isFrontFacing(t,e,n,i){return Ne.subVectors(n,e),qe.subVectors(t,e),Ne.cross(qe).dot(i)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this}setFromAttributeAndIndices(t,e,n,i){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,i),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Ne.subVectors(this.c,this.b),qe.subVectors(this.a,this.b),Ne.cross(qe).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return Le.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Le.getBarycoord(t,this.a,this.b,this.c,e)}getUV(t,e,n,i,s){return bi===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),bi=!0),Le.getInterpolation(t,this.a,this.b,this.c,e,n,i,s)}getInterpolation(t,e,n,i,s){return Le.getInterpolation(t,this.a,this.b,this.c,e,n,i,s)}containsPoint(t){return Le.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Le.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const n=this.a,i=this.b,s=this.c;let o,a;Tn.subVectors(i,n),bn.subVectors(s,n),br.subVectors(t,n);const l=Tn.dot(br),c=bn.dot(br);if(l<=0&&c<=0)return e.copy(n);Ar.subVectors(t,i);const h=Tn.dot(Ar),u=bn.dot(Ar);if(h>=0&&u<=h)return e.copy(i);const d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return o=l/(l-h),e.copy(n).addScaledVector(Tn,o);wr.subVectors(t,s);const p=Tn.dot(wr),g=bn.dot(wr);if(g>=0&&p<=g)return e.copy(s);const v=p*c-l*g;if(v<=0&&c>=0&&g<=0)return a=c/(c-g),e.copy(n).addScaledVector(bn,a);const m=h*g-p*u;if(m<=0&&u-h>=0&&p-g>=0)return As.subVectors(s,i),a=(u-h)/(u-h+(p-g)),e.copy(i).addScaledVector(As,a);const f=1/(m+v+d);return o=v*f,a=d*f,e.copy(n).addScaledVector(Tn,o).addScaledVector(bn,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}const Ca={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},nn={h:0,s:0,l:0},Ai={h:0,s:0,l:0};function Rr(r,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?r+(t-r)*6*e:e<1/2?t:e<2/3?r+(t-r)*6*(2/3-e):r}class zt{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(e===void 0&&n===void 0){const i=t;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=fe){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,Kt.toWorkingColorSpace(this,e),this}setRGB(t,e,n,i=Kt.workingColorSpace){return this.r=t,this.g=e,this.b=n,Kt.toWorkingColorSpace(this,i),this}setHSL(t,e,n,i=Kt.workingColorSpace){if(t=$r(t,1),e=de(e,0,1),n=de(n,0,1),e===0)this.r=this.g=this.b=n;else{const s=n<=.5?n*(1+e):n+e-n*e,o=2*n-s;this.r=Rr(o,s,t+1/3),this.g=Rr(o,s,t),this.b=Rr(o,s,t-1/3)}return Kt.toWorkingColorSpace(this,i),this}setStyle(t,e=fe){function n(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(t)){let s;const o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,e);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,e);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,e);break;default:console.warn("THREE.Color: Unknown color model "+t)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(t)){const s=i[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,e);if(o===6)return this.setHex(parseInt(s,16),e);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=fe){const n=Ca[t.toLowerCase()];return n!==void 0?this.setHex(n,e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Gn(t.r),this.g=Gn(t.g),this.b=Gn(t.b),this}copyLinearToSRGB(t){return this.r=gr(t.r),this.g=gr(t.g),this.b=gr(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=fe){return Kt.fromWorkingColorSpace(_e.copy(this),t),Math.round(de(_e.r*255,0,255))*65536+Math.round(de(_e.g*255,0,255))*256+Math.round(de(_e.b*255,0,255))}getHexString(t=fe){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Kt.workingColorSpace){Kt.fromWorkingColorSpace(_e.copy(this),e);const n=_e.r,i=_e.g,s=_e.b,o=Math.max(n,i,s),a=Math.min(n,i,s);let l,c;const h=(a+o)/2;if(a===o)l=0,c=0;else{const u=o-a;switch(c=h<=.5?u/(o+a):u/(2-o-a),o){case n:l=(i-s)/u+(i0!=t>0&&this.version++,this._alphaTest=t}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(const e in t){const n=t[e];if(n===void 0){console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);continue}const i=this[e];if(i===void 0){console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n}}toJSON(t){const e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function i(s){const o=[];for(const a in s){const l=s[a];delete l.metadata,o.push(l)}return o}if(e){const s=i(t.textures),o=i(t.images);s.length>0&&(n.textures=s),o.length>0&&(n.images=o)}return n}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let n=null;if(e!==null){const i=e.length;n=new Array(i);for(let s=0;s!==i;++s)n[s]=e[s].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}}class La extends an{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new zt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const ae=new R,wi=new ct;class De{constructor(t,e,n=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=n,this.usage=35044,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}get updateRange(){return console.warn("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let i=0,s=this.itemSize;i0&&(t.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(t[c]=l[c]);return t}t.data={attributes:{}};const e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const l in n){const c=n[l];t.data.attributes[l]=c.toJSON(t.data)}const i={};let s=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let u=0,d=c.length;u0&&(i[l]=h,s=!0)}s&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(t.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const n=t.index;n!==null&&this.setIndex(n.clone(e));const i=t.attributes;for(const c in i){const h=i[c];this.setAttribute(c,h.clone(e))}const s=t.morphAttributes;for(const c in s){const h=[],u=s[c];for(let d=0,p=u.length;d0){const i=e[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s(t.far-t.near)**2))&&(ws.copy(s).invert(),un.copy(t.ray).applyMatrix4(ws),!(n.boundingBox!==null&&un.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(t,e,un)))}_computeIntersections(t,e,n){let i;const s=this.geometry,o=this.material,a=s.index,l=s.attributes.position,c=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,d=s.groups,p=s.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=d.length;ge.far?null:{distance:c,point:Ii.clone(),object:r}}function Ni(r,t,e,n,i,s,o,a,l,c){r.getVertexPosition(a,wn),r.getVertexPosition(l,Rn),r.getVertexPosition(c,Cn);const h=Wo(r,t,e,n,wn,Rn,Cn,Ui);if(h){i&&(Li.fromBufferAttribute(i,a),Pi.fromBufferAttribute(i,l),Di.fromBufferAttribute(i,c),h.uv=Le.getInterpolation(Ui,wn,Rn,Cn,Li,Pi,Di,new ct)),s&&(Li.fromBufferAttribute(s,a),Pi.fromBufferAttribute(s,l),Di.fromBufferAttribute(s,c),h.uv1=Le.getInterpolation(Ui,wn,Rn,Cn,Li,Pi,Di,new ct),h.uv2=h.uv1),o&&(Cs.fromBufferAttribute(o,a),Ls.fromBufferAttribute(o,l),Ps.fromBufferAttribute(o,c),h.normal=Le.getInterpolation(Ui,wn,Rn,Cn,Cs,Ls,Ps,new R),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));const u={a,b:l,c,normal:new R,materialIndex:0};Le.getNormal(wn,Rn,Cn,u.normal),h.face=u}return h}class di extends pe{constructor(t=1,e=1,n=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:i,heightSegments:s,depthSegments:o};const a=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const l=[],c=[],h=[],u=[];let d=0,p=0;g("z","y","x",-1,-1,n,e,t,o,s,0),g("z","y","x",1,-1,n,e,-t,o,s,1),g("x","z","y",1,1,t,n,e,i,o,2),g("x","z","y",1,-1,t,n,-e,i,o,3),g("x","y","z",1,-1,t,e,n,i,s,4),g("x","y","z",-1,-1,t,e,-n,i,s,5),this.setIndex(l),this.setAttribute("position",new kt(c,3)),this.setAttribute("normal",new kt(h,3)),this.setAttribute("uv",new kt(u,2));function g(v,m,f,S,_,b,C,A,w,U,M){const T=b/w,z=C/U,H=b/2,tt=C/2,P=A/2,I=w+1,k=U+1;let q=0,X=0;const W=new R;for(let j=0;j0?1:-1,h.push(W.x,W.y,W.z),u.push(lt/w),u.push(1-j/U),q+=1}}for(let j=0;j0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const n={};for(const i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}class Ia extends re{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Vt,this.projectionMatrix=new Vt,this.projectionMatrixInverse=new Vt,this.coordinateSystem=2e3}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}class we extends Ia{constructor(t=50,e=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=t.view===null?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=Vn*2*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(ai*.5*this.fov);return .5*this.getFilmHeight()/t}getEffectiveFOV(){return Vn*2*Math.atan(Math.tan(ai*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(t,e,n,i,s,o){this.aspect=t/e,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(ai*.5*this.fov)/this.zoom,n=2*e,i=this.aspect*n,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const l=o.fullWidth,c=o.fullHeight;s+=o.offsetX*i/l,e-=o.offsetY*n/c,i*=o.width/l,n*=o.height/c}const a=this.filmOffset;a!==0&&(s+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,e,e-n,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,this.view!==null&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const Ln=-90,Pn=1;class Jo extends re{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new we(Ln,Pn,t,e);i.layers=this.layers,this.add(i);const s=new we(Ln,Pn,t,e);s.layers=this.layers,this.add(s);const o=new we(Ln,Pn,t,e);o.layers=this.layers,this.add(o);const a=new we(Ln,Pn,t,e);a.layers=this.layers,this.add(a);const l=new we(Ln,Pn,t,e);l.layers=this.layers,this.add(l);const c=new we(Ln,Pn,t,e);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[n,i,s,o,a,l]=e;for(const c of e)this.remove(c);if(t===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(t===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);for(const c of e)this.add(c),c.updateMatrixWorld()}update(t,e){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[s,o,a,l,c,h]=this.children,u=t.getRenderTarget(),d=t.getActiveCubeFace(),p=t.getActiveMipmapLevel(),g=t.xr.enabled;t.xr.enabled=!1;const v=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0,i),t.render(e,s),t.setRenderTarget(n,1,i),t.render(e,o),t.setRenderTarget(n,2,i),t.render(e,a),t.setRenderTarget(n,3,i),t.render(e,l),t.setRenderTarget(n,4,i),t.render(e,c),n.texture.generateMipmaps=v,t.setRenderTarget(n,5,i),t.render(e,h),t.setRenderTarget(u,d,p),t.xr.enabled=g,n.texture.needsPMREMUpdate=!0}}class Na extends ve{constructor(t,e,n,i,s,o,a,l,c,h){t=t!==void 0?t:[],e=e!==void 0?e:301,super(t,e,n,i,s,o,a,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class jo extends gn{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const n={width:t,height:t,depth:1},i=[n,n,n,n,n,n];e.encoding!==void 0&&(li("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),e.colorSpace=e.encoding===3001?fe:Pe),this.texture=new Na(i,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=e.generateMipmaps!==void 0?e.generateMipmaps:!1,this.texture.minFilter=e.minFilter!==void 0?e.minFilter:1006}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:` - - varying vec3 vWorldDirection; - - vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); - - } - - void main() { - - vWorldDirection = transformDirection( position, modelMatrix ); - - #include - #include - - } - `,fragmentShader:` - - uniform sampler2D tEquirect; - - varying vec3 vWorldDirection; - - #include - - void main() { - - vec3 direction = normalize( vWorldDirection ); - - vec2 sampleUV = equirectUv( direction ); - - gl_FragColor = texture2D( tEquirect, sampleUV ); - - } - `},i=new di(5,5,5),s=new _n({name:"CubemapFromEquirect",uniforms:Hn(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});s.uniforms.tEquirect.value=e;const o=new Fe(i,s),a=e.minFilter;return e.minFilter===1008&&(e.minFilter=1006),new Jo(1,10,this).update(t,o),e.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(t,e,n,i){const s=t.getRenderTarget();for(let o=0;o<6;o++)t.setRenderTarget(this,o),t.clear(e,n,i);t.setRenderTarget(s)}}const Pr=new R,Zo=new R,$o=new Bt;class fn{constructor(t=new R(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,i){return this.normal.set(t,e,n),this.constant=i,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){const i=Pr.subVectors(n,e).cross(Zo.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){const n=t.delta(Pr),i=this.normal.dot(n);if(i===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;const s=-(t.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:e.copy(t.start).addScaledVector(n,s)}intersectsLine(t){const e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const n=e||$o.getNormalMatrix(t),i=this.coplanarPoint(Pr).applyMatrix4(t),s=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(s),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}}const dn=new je,Fi=new R;class Qr{constructor(t=new fn,e=new fn,n=new fn,i=new fn,s=new fn,o=new fn){this.planes=[t,e,n,i,s,o]}set(t,e,n,i,s,o){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(i),a[4].copy(s),a[5].copy(o),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t,e=2e3){const n=this.planes,i=t.elements,s=i[0],o=i[1],a=i[2],l=i[3],c=i[4],h=i[5],u=i[6],d=i[7],p=i[8],g=i[9],v=i[10],m=i[11],f=i[12],S=i[13],_=i[14],b=i[15];if(n[0].setComponents(l-s,d-c,m-p,b-f).normalize(),n[1].setComponents(l+s,d+c,m+p,b+f).normalize(),n[2].setComponents(l+o,d+h,m+g,b+S).normalize(),n[3].setComponents(l-o,d-h,m-g,b-S).normalize(),n[4].setComponents(l-a,d-u,m-v,b-_).normalize(),e===2e3)n[5].setComponents(l+a,d+u,m+v,b+_).normalize();else if(e===2001)n[5].setComponents(a,u,v,_).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(t){if(t.boundingSphere!==void 0)t.boundingSphere===null&&t.computeBoundingSphere(),dn.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),dn.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(dn)}intersectsSprite(t){return dn.center.set(0,0,0),dn.radius=.7071067811865476,dn.applyMatrix4(t.matrixWorld),this.intersectsSphere(dn)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let s=0;s<6;s++)if(e[s].distanceToPoint(n)0?t.max.x:t.min.x,Fi.y=i.normal.y>0?t.max.y:t.min.y,Fi.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(Fi)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function Fa(){let r=null,t=!1,e=null,n=null;function i(s,o){e(s,o),n=r.requestAnimationFrame(i)}return{start:function(){t!==!0&&e!==null&&(n=r.requestAnimationFrame(i),t=!0)},stop:function(){r.cancelAnimationFrame(n),t=!1},setAnimationLoop:function(s){e=s},setContext:function(s){r=s}}}function Qo(r,t){const e=t.isWebGL2,n=new WeakMap;function i(c,h){const u=c.array,d=c.usage,p=u.byteLength,g=r.createBuffer();r.bindBuffer(h,g),r.bufferData(h,u,d),c.onUploadCallback();let v;if(u instanceof Float32Array)v=r.FLOAT;else if(u instanceof Uint16Array)if(c.isFloat16BufferAttribute)if(e)v=r.HALF_FLOAT;else throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");else v=r.UNSIGNED_SHORT;else if(u instanceof Int16Array)v=r.SHORT;else if(u instanceof Uint32Array)v=r.UNSIGNED_INT;else if(u instanceof Int32Array)v=r.INT;else if(u instanceof Int8Array)v=r.BYTE;else if(u instanceof Uint8Array)v=r.UNSIGNED_BYTE;else if(u instanceof Uint8ClampedArray)v=r.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+u);return{buffer:g,type:v,bytesPerElement:u.BYTES_PER_ELEMENT,version:c.version,size:p}}function s(c,h,u){const d=h.array,p=h._updateRange,g=h.updateRanges;if(r.bindBuffer(u,c),p.count===-1&&g.length===0&&r.bufferSubData(u,0,d),g.length!==0){for(let v=0,m=g.length;v 0 - vec4 plane; - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - bool clipped = true; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; - } - #pragma unroll_loop_end - if ( clipped ) discard; - #endif -#endif`,gl=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; - uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,_l=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; -#endif`,vl=`#if NUM_CLIPPING_PLANES > 0 - vClipPosition = - mvPosition.xyz; -#endif`,xl=`#if defined( USE_COLOR_ALPHA ) - diffuseColor *= vColor; -#elif defined( USE_COLOR ) - diffuseColor.rgb *= vColor; -#endif`,Ml=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) - varying vec3 vColor; -#endif`,Sl=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) - varying vec3 vColor; -#endif`,yl=`#if defined( USE_COLOR_ALPHA ) - vColor = vec4( 1.0 ); -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) - vColor = vec3( 1.0 ); -#endif -#ifdef USE_COLOR - vColor *= color; -#endif -#ifdef USE_INSTANCING_COLOR - vColor.xyz *= instanceColor.xyz; -#endif`,El=`#define PI 3.141592653589793 -#define PI2 6.283185307179586 -#define PI_HALF 1.5707963267948966 -#define RECIPROCAL_PI 0.3183098861837907 -#define RECIPROCAL_PI2 0.15915494309189535 -#define EPSILON 1e-6 -#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -#define whiteComplement( a ) ( 1.0 - saturate( a ) ) -float pow2( const in float x ) { return x*x; } -vec3 pow2( const in vec3 x ) { return x*x; } -float pow3( const in float x ) { return x*x*x; } -float pow4( const in float x ) { float x2 = x*x; return x2*x2; } -float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } -float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } -highp float rand( const in vec2 uv ) { - const highp float a = 12.9898, b = 78.233, c = 43758.5453; - highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); - return fract( sin( sn ) * c ); -} -#ifdef HIGH_PRECISION - float precisionSafeLength( vec3 v ) { return length( v ); } -#else - float precisionSafeLength( vec3 v ) { - float maxComponent = max3( abs( v ) ); - return length( v / maxComponent ) * maxComponent; - } -#endif -struct IncidentLight { - vec3 color; - vec3 direction; - bool visible; -}; -struct ReflectedLight { - vec3 directDiffuse; - vec3 directSpecular; - vec3 indirectDiffuse; - vec3 indirectSpecular; -}; -#ifdef USE_ALPHAHASH - varying vec3 vPosition; -#endif -vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); -} -vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); -} -mat3 transposeMat3( const in mat3 m ) { - mat3 tmp; - tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); - tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); - tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); - return tmp; -} -float luminance( const in vec3 rgb ) { - const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 ); - return dot( weights, rgb ); -} -bool isPerspectiveMatrix( mat4 m ) { - return m[ 2 ][ 3 ] == - 1.0; -} -vec2 equirectUv( in vec3 dir ) { - float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; - float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; - return vec2( u, v ); -} -vec3 BRDF_Lambert( const in vec3 diffuseColor ) { - return RECIPROCAL_PI * diffuseColor; -} -vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} -float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,Tl=`#ifdef ENVMAP_TYPE_CUBE_UV - #define cubeUV_minMipLevel 4.0 - #define cubeUV_minTileSize 16.0 - float getFace( vec3 direction ) { - vec3 absDirection = abs( direction ); - float face = - 1.0; - if ( absDirection.x > absDirection.z ) { - if ( absDirection.x > absDirection.y ) - face = direction.x > 0.0 ? 0.0 : 3.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } else { - if ( absDirection.z > absDirection.y ) - face = direction.z > 0.0 ? 2.0 : 5.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } - return face; - } - vec2 getUV( vec3 direction, float face ) { - vec2 uv; - if ( face == 0.0 ) { - uv = vec2( direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 1.0 ) { - uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); - } else if ( face == 2.0 ) { - uv = vec2( - direction.x, direction.y ) / abs( direction.z ); - } else if ( face == 3.0 ) { - uv = vec2( - direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 4.0 ) { - uv = vec2( - direction.x, direction.z ) / abs( direction.y ); - } else { - uv = vec2( direction.x, direction.y ) / abs( direction.z ); - } - return 0.5 * ( uv + 1.0 ); - } - vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { - float face = getFace( direction ); - float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); - mipInt = max( mipInt, cubeUV_minMipLevel ); - float faceSize = exp2( mipInt ); - highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; - if ( face > 2.0 ) { - uv.y += faceSize; - face -= 3.0; - } - uv.x += face * faceSize; - uv.x += filterInt * 3.0 * cubeUV_minTileSize; - uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); - uv.x *= CUBEUV_TEXEL_WIDTH; - uv.y *= CUBEUV_TEXEL_HEIGHT; - #ifdef texture2DGradEXT - return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; - #else - return texture2D( envMap, uv ).rgb; - #endif - } - #define cubeUV_r0 1.0 - #define cubeUV_m0 - 2.0 - #define cubeUV_r1 0.8 - #define cubeUV_m1 - 1.0 - #define cubeUV_r4 0.4 - #define cubeUV_m4 2.0 - #define cubeUV_r5 0.305 - #define cubeUV_m5 3.0 - #define cubeUV_r6 0.21 - #define cubeUV_m6 4.0 - float roughnessToMip( float roughness ) { - float mip = 0.0; - if ( roughness >= cubeUV_r1 ) { - mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; - } else if ( roughness >= cubeUV_r4 ) { - mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; - } else if ( roughness >= cubeUV_r5 ) { - mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; - } else if ( roughness >= cubeUV_r6 ) { - mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; - } else { - mip = - 2.0 * log2( 1.16 * roughness ); } - return mip; - } - vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { - float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); - float mipF = fract( mip ); - float mipInt = floor( mip ); - vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); - if ( mipF == 0.0 ) { - return vec4( color0, 1.0 ); - } else { - vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); - return vec4( mix( color0, color1, mipF ), 1.0 ); - } - } -#endif`,bl=`vec3 transformedNormal = objectNormal; -#ifdef USE_TANGENT - vec3 transformedTangent = objectTangent; -#endif -#ifdef USE_BATCHING - mat3 bm = mat3( batchingMatrix ); - transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); - transformedNormal = bm * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = bm * transformedTangent; - #endif -#endif -#ifdef USE_INSTANCING - mat3 im = mat3( instanceMatrix ); - transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); - transformedNormal = im * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = im * transformedTangent; - #endif -#endif -transformedNormal = normalMatrix * transformedNormal; -#ifdef FLIP_SIDED - transformedNormal = - transformedNormal; -#endif -#ifdef USE_TANGENT - transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; - #ifdef FLIP_SIDED - transformedTangent = - transformedTangent; - #endif -#endif`,Al=`#ifdef USE_DISPLACEMENTMAP - uniform sampler2D displacementMap; - uniform float displacementScale; - uniform float displacementBias; -#endif`,wl=`#ifdef USE_DISPLACEMENTMAP - transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,Rl=`#ifdef USE_EMISSIVEMAP - vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); - totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,Cl=`#ifdef USE_EMISSIVEMAP - uniform sampler2D emissiveMap; -#endif`,Ll="gl_FragColor = linearToOutputTexel( gl_FragColor );",Pl=` -const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3( - vec3( 0.8224621, 0.177538, 0.0 ), - vec3( 0.0331941, 0.9668058, 0.0 ), - vec3( 0.0170827, 0.0723974, 0.9105199 ) -); -const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3( - vec3( 1.2249401, - 0.2249404, 0.0 ), - vec3( - 0.0420569, 1.0420571, 0.0 ), - vec3( - 0.0196376, - 0.0786361, 1.0982735 ) -); -vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) { - return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a ); -} -vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) { - return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a ); -} -vec4 LinearTransferOETF( in vec4 value ) { - return value; -} -vec4 sRGBTransferOETF( in vec4 value ) { - return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -} -vec4 LinearToLinear( in vec4 value ) { - return value; -} -vec4 LinearTosRGB( in vec4 value ) { - return sRGBTransferOETF( value ); -}`,Dl=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vec3 cameraToFrag; - if ( isOrthographic ) { - cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToFrag = normalize( vWorldPosition - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vec3 reflectVec = reflect( cameraToFrag, worldNormal ); - #else - vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); - #endif - #else - vec3 reflectVec = vReflect; - #endif - #ifdef ENVMAP_TYPE_CUBE - vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); - #else - vec4 envColor = vec4( 0.0 ); - #endif - #ifdef ENVMAP_BLENDING_MULTIPLY - outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_MIX ) - outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_ADD ) - outgoingLight += envColor.xyz * specularStrength * reflectivity; - #endif -#endif`,Ul=`#ifdef USE_ENVMAP - uniform float envMapIntensity; - uniform float flipEnvMap; - #ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; - #else - uniform sampler2D envMap; - #endif - -#endif`,Il=`#ifdef USE_ENVMAP - uniform float reflectivity; - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - varying vec3 vWorldPosition; - uniform float refractionRatio; - #else - varying vec3 vReflect; - #endif -#endif`,Nl=`#ifdef USE_ENVMAP - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - - varying vec3 vWorldPosition; - #else - varying vec3 vReflect; - uniform float refractionRatio; - #endif -#endif`,Fl=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vWorldPosition = worldPosition.xyz; - #else - vec3 cameraToVertex; - if ( isOrthographic ) { - cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vReflect = reflect( cameraToVertex, worldNormal ); - #else - vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); - #endif - #endif -#endif`,Ol=`#ifdef USE_FOG - vFogDepth = - mvPosition.z; -#endif`,Bl=`#ifdef USE_FOG - varying float vFogDepth; -#endif`,zl=`#ifdef USE_FOG - #ifdef FOG_EXP2 - float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); - #else - float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); - #endif - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,Gl=`#ifdef USE_FOG - uniform vec3 fogColor; - varying float vFogDepth; - #ifdef FOG_EXP2 - uniform float fogDensity; - #else - uniform float fogNear; - uniform float fogFar; - #endif -#endif`,Vl=`#ifdef USE_GRADIENTMAP - uniform sampler2D gradientMap; -#endif -vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { - float dotNL = dot( normal, lightDirection ); - vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); - #ifdef USE_GRADIENTMAP - return vec3( texture2D( gradientMap, coord ).r ); - #else - vec2 fw = fwidth( coord ) * 0.5; - return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); - #endif -}`,Hl=`#ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - reflectedLight.indirectDiffuse += lightMapIrradiance; -#endif`,kl=`#ifdef USE_LIGHTMAP - uniform sampler2D lightMap; - uniform float lightMapIntensity; -#endif`,Wl=`LambertMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,Xl=`varying vec3 vViewPosition; -struct LambertMaterial { - vec3 diffuseColor; - float specularStrength; -}; -void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,ql=`uniform bool receiveShadow; -uniform vec3 ambientLightColor; -#if defined( USE_LIGHT_PROBES ) - uniform vec3 lightProbe[ 9 ]; -#endif -vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { - float x = normal.x, y = normal.y, z = normal.z; - vec3 result = shCoefficients[ 0 ] * 0.886227; - result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; - result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; - result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; - result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; - result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; - result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); - result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; - result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); - return result; -} -vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); - return irradiance; -} -vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { - vec3 irradiance = ambientLightColor; - return irradiance; -} -float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { - #if defined ( LEGACY_LIGHTS ) - if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) { - return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent ); - } - return 1.0; - #else - float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); - if ( cutoffDistance > 0.0 ) { - distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); - } - return distanceFalloff; - #endif -} -float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { - return smoothstep( coneCosine, penumbraCosine, angleCosine ); -} -#if NUM_DIR_LIGHTS > 0 - struct DirectionalLight { - vec3 direction; - vec3 color; - }; - uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; - void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { - light.color = directionalLight.color; - light.direction = directionalLight.direction; - light.visible = true; - } -#endif -#if NUM_POINT_LIGHTS > 0 - struct PointLight { - vec3 position; - vec3 color; - float distance; - float decay; - }; - uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; - void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = pointLight.position - geometryPosition; - light.direction = normalize( lVector ); - float lightDistance = length( lVector ); - light.color = pointLight.color; - light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } -#endif -#if NUM_SPOT_LIGHTS > 0 - struct SpotLight { - vec3 position; - vec3 direction; - vec3 color; - float distance; - float decay; - float coneCos; - float penumbraCos; - }; - uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; - void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = spotLight.position - geometryPosition; - light.direction = normalize( lVector ); - float angleCos = dot( light.direction, spotLight.direction ); - float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); - if ( spotAttenuation > 0.0 ) { - float lightDistance = length( lVector ); - light.color = spotLight.color * spotAttenuation; - light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } else { - light.color = vec3( 0.0 ); - light.visible = false; - } - } -#endif -#if NUM_RECT_AREA_LIGHTS > 0 - struct RectAreaLight { - vec3 color; - vec3 position; - vec3 halfWidth; - vec3 halfHeight; - }; - uniform sampler2D ltc_1; uniform sampler2D ltc_2; - uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; -#endif -#if NUM_HEMI_LIGHTS > 0 - struct HemisphereLight { - vec3 direction; - vec3 skyColor; - vec3 groundColor; - }; - uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; - vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { - float dotNL = dot( normal, hemiLight.direction ); - float hemiDiffuseWeight = 0.5 * dotNL + 0.5; - vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); - return irradiance; - } -#endif`,Yl=`#ifdef USE_ENVMAP - vec3 getIBLIrradiance( const in vec3 normal ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 ); - return PI * envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 reflectVec = reflect( - viewDir, normal ); - reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); - reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness ); - return envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - #ifdef USE_ANISOTROPY - vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 bentNormal = cross( bitangent, viewDir ); - bentNormal = normalize( cross( bentNormal, bitangent ) ); - bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); - return getIBLRadiance( viewDir, bentNormal, roughness ); - #else - return vec3( 0.0 ); - #endif - } - #endif -#endif`,Kl=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,Jl=`varying vec3 vViewPosition; -struct ToonMaterial { - vec3 diffuseColor; -}; -void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,jl=`BlinnPhongMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularColor = specular; -material.specularShininess = shininess; -material.specularStrength = specularStrength;`,Zl=`varying vec3 vViewPosition; -struct BlinnPhongMaterial { - vec3 diffuseColor; - vec3 specularColor; - float specularShininess; - float specularStrength; -}; -void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); - reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; -} -void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,$l=`PhysicalMaterial material; -material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); -vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); -float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); -material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; -material.roughness = min( material.roughness, 1.0 ); -#ifdef IOR - material.ior = ior; - #ifdef USE_SPECULAR - float specularIntensityFactor = specularIntensity; - vec3 specularColorFactor = specularColor; - #ifdef USE_SPECULAR_COLORMAP - specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; - #endif - material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); - #else - float specularIntensityFactor = 1.0; - vec3 specularColorFactor = vec3( 1.0 ); - material.specularF90 = 1.0; - #endif - material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); -#else - material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); - material.specularF90 = 1.0; -#endif -#ifdef USE_CLEARCOAT - material.clearcoat = clearcoat; - material.clearcoatRoughness = clearcoatRoughness; - material.clearcoatF0 = vec3( 0.04 ); - material.clearcoatF90 = 1.0; - #ifdef USE_CLEARCOATMAP - material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; - #endif - #ifdef USE_CLEARCOAT_ROUGHNESSMAP - material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; - #endif - material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); - material.clearcoatRoughness += geometryRoughness; - material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); -#endif -#ifdef USE_IRIDESCENCE - material.iridescence = iridescence; - material.iridescenceIOR = iridescenceIOR; - #ifdef USE_IRIDESCENCEMAP - material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; - #endif - #ifdef USE_IRIDESCENCE_THICKNESSMAP - material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; - #else - material.iridescenceThickness = iridescenceThicknessMaximum; - #endif -#endif -#ifdef USE_SHEEN - material.sheenColor = sheenColor; - #ifdef USE_SHEEN_COLORMAP - material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; - #endif - material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); - #ifdef USE_SHEEN_ROUGHNESSMAP - material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; - #endif -#endif -#ifdef USE_ANISOTROPY - #ifdef USE_ANISOTROPYMAP - mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); - vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; - vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; - #else - vec2 anisotropyV = anisotropyVector; - #endif - material.anisotropy = length( anisotropyV ); - if( material.anisotropy == 0.0 ) { - anisotropyV = vec2( 1.0, 0.0 ); - } else { - anisotropyV /= material.anisotropy; - material.anisotropy = saturate( material.anisotropy ); - } - material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); - material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; - material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,Ql=`struct PhysicalMaterial { - vec3 diffuseColor; - float roughness; - vec3 specularColor; - float specularF90; - #ifdef USE_CLEARCOAT - float clearcoat; - float clearcoatRoughness; - vec3 clearcoatF0; - float clearcoatF90; - #endif - #ifdef USE_IRIDESCENCE - float iridescence; - float iridescenceIOR; - float iridescenceThickness; - vec3 iridescenceFresnel; - vec3 iridescenceF0; - #endif - #ifdef USE_SHEEN - vec3 sheenColor; - float sheenRoughness; - #endif - #ifdef IOR - float ior; - #endif - #ifdef USE_TRANSMISSION - float transmission; - float transmissionAlpha; - float thickness; - float attenuationDistance; - vec3 attenuationColor; - #endif - #ifdef USE_ANISOTROPY - float anisotropy; - float alphaT; - vec3 anisotropyT; - vec3 anisotropyB; - #endif -}; -vec3 clearcoatSpecularDirect = vec3( 0.0 ); -vec3 clearcoatSpecularIndirect = vec3( 0.0 ); -vec3 sheenSpecularDirect = vec3( 0.0 ); -vec3 sheenSpecularIndirect = vec3(0.0 ); -vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { - float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); - float x2 = x * x; - float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); - return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); -} -float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { - float a2 = pow2( alpha ); - float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - return 0.5 / max( gv + gl, EPSILON ); -} -float D_GGX( const in float alpha, const in float dotNH ) { - float a2 = pow2( alpha ); - float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; - return RECIPROCAL_PI * a2 / pow2( denom ); -} -#ifdef USE_ANISOTROPY - float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { - float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); - float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); - float v = 0.5 / ( gv + gl ); - return saturate(v); - } - float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { - float a2 = alphaT * alphaB; - highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); - highp float v2 = dot( v, v ); - float w2 = a2 / v2; - return RECIPROCAL_PI * a2 * pow2 ( w2 ); - } -#endif -#ifdef USE_CLEARCOAT - vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { - vec3 f0 = material.clearcoatF0; - float f90 = material.clearcoatF90; - float roughness = material.clearcoatRoughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - return F * ( V * D ); - } -#endif -vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { - vec3 f0 = material.specularColor; - float f90 = material.specularF90; - float roughness = material.roughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - #ifdef USE_IRIDESCENCE - F = mix( F, material.iridescenceFresnel, material.iridescence ); - #endif - #ifdef USE_ANISOTROPY - float dotTL = dot( material.anisotropyT, lightDir ); - float dotTV = dot( material.anisotropyT, viewDir ); - float dotTH = dot( material.anisotropyT, halfDir ); - float dotBL = dot( material.anisotropyB, lightDir ); - float dotBV = dot( material.anisotropyB, viewDir ); - float dotBH = dot( material.anisotropyB, halfDir ); - float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); - float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); - #else - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - #endif - return F * ( V * D ); -} -vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { - const float LUT_SIZE = 64.0; - const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; - const float LUT_BIAS = 0.5 / LUT_SIZE; - float dotNV = saturate( dot( N, V ) ); - vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); - uv = uv * LUT_SCALE + LUT_BIAS; - return uv; -} -float LTC_ClippedSphereFormFactor( const in vec3 f ) { - float l = length( f ); - return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); -} -vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { - float x = dot( v1, v2 ); - float y = abs( x ); - float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; - float b = 3.4175940 + ( 4.1616724 + y ) * y; - float v = a / b; - float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; - return cross( v1, v2 ) * theta_sintheta; -} -vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { - vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; - vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; - vec3 lightNormal = cross( v1, v2 ); - if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); - vec3 T1, T2; - T1 = normalize( V - N * dot( V, N ) ); - T2 = - cross( N, T1 ); - mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); - vec3 coords[ 4 ]; - coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); - coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); - coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); - coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); - coords[ 0 ] = normalize( coords[ 0 ] ); - coords[ 1 ] = normalize( coords[ 1 ] ); - coords[ 2 ] = normalize( coords[ 2 ] ); - coords[ 3 ] = normalize( coords[ 3 ] ); - vec3 vectorFormFactor = vec3( 0.0 ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); - float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); - return vec3( result ); -} -#if defined( USE_SHEEN ) -float D_Charlie( float roughness, float dotNH ) { - float alpha = pow2( roughness ); - float invAlpha = 1.0 / alpha; - float cos2h = dotNH * dotNH; - float sin2h = max( 1.0 - cos2h, 0.0078125 ); - return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); -} -float V_Neubelt( float dotNV, float dotNL ) { - return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); -} -vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float D = D_Charlie( sheenRoughness, dotNH ); - float V = V_Neubelt( dotNV, dotNL ); - return sheenColor * ( D * V ); -} -#endif -float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - float r2 = roughness * roughness; - float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; - float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; - float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); - return saturate( DG * RECIPROCAL_PI ); -} -vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); - const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); - vec4 r = roughness * c0 + c1; - float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; - vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; - return fab; -} -vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { - vec2 fab = DFGApprox( normal, viewDir, roughness ); - return specularColor * fab.x + specularF90 * fab.y; -} -#ifdef USE_IRIDESCENCE -void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#else -void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#endif - vec2 fab = DFGApprox( normal, viewDir, roughness ); - #ifdef USE_IRIDESCENCE - vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); - #else - vec3 Fr = specularColor; - #endif - vec3 FssEss = Fr * fab.x + specularF90 * fab.y; - float Ess = fab.x + fab.y; - float Ems = 1.0 - Ess; - vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); - singleScatter += FssEss; - multiScatter += Fms * Ems; -} -#if NUM_RECT_AREA_LIGHTS > 0 - void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - vec3 normal = geometryNormal; - vec3 viewDir = geometryViewDir; - vec3 position = geometryPosition; - vec3 lightPos = rectAreaLight.position; - vec3 halfWidth = rectAreaLight.halfWidth; - vec3 halfHeight = rectAreaLight.halfHeight; - vec3 lightColor = rectAreaLight.color; - float roughness = material.roughness; - vec3 rectCoords[ 4 ]; - rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; - rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; - rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; - vec2 uv = LTC_Uv( normal, viewDir, roughness ); - vec4 t1 = texture2D( ltc_1, uv ); - vec4 t2 = texture2D( ltc_2, uv ); - mat3 mInv = mat3( - vec3( t1.x, 0, t1.y ), - vec3( 0, 1, 0 ), - vec3( t1.z, 0, t1.w ) - ); - vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); - reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); - reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); - } -#endif -void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - #ifdef USE_CLEARCOAT - float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); - vec3 ccIrradiance = dotNLcc * directLight.color; - clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); - #endif - #ifdef USE_SHEEN - sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); - #endif - reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { - #ifdef USE_CLEARCOAT - clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); - #endif - #ifdef USE_SHEEN - sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); - #endif - vec3 singleScattering = vec3( 0.0 ); - vec3 multiScattering = vec3( 0.0 ); - vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; - #ifdef USE_IRIDESCENCE - computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); - #else - computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); - #endif - vec3 totalScattering = singleScattering + multiScattering; - vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); - reflectedLight.indirectSpecular += radiance * singleScattering; - reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; - reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; -} -#define RE_Direct RE_Direct_Physical -#define RE_Direct_RectArea RE_Direct_RectArea_Physical -#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical -#define RE_IndirectSpecular RE_IndirectSpecular_Physical -float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { - return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,tc=` -vec3 geometryPosition = - vViewPosition; -vec3 geometryNormal = normal; -vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); -vec3 geometryClearcoatNormal = vec3( 0.0 ); -#ifdef USE_CLEARCOAT - geometryClearcoatNormal = clearcoatNormal; -#endif -#ifdef USE_IRIDESCENCE - float dotNVi = saturate( dot( normal, geometryViewDir ) ); - if ( material.iridescenceThickness == 0.0 ) { - material.iridescence = 0.0; - } else { - material.iridescence = saturate( material.iridescence ); - } - if ( material.iridescence > 0.0 ) { - material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); - material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); - } -#endif -IncidentLight directLight; -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - pointLight = pointLights[ i ]; - getPointLightInfo( pointLight, geometryPosition, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - SpotLight spotLight; - vec4 spotColor; - vec3 spotLightCoord; - bool inSpotLightMap; - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - spotLight = spotLights[ i ]; - getSpotLightInfo( spotLight, geometryPosition, directLight ); - #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX - #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS - #else - #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #endif - #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) - spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; - inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); - spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); - directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; - #endif - #undef SPOT_LIGHT_MAP_INDEX - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) - RectAreaLight rectAreaLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if defined( RE_IndirectDiffuse ) - vec3 iblIrradiance = vec3( 0.0 ); - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - #if defined( USE_LIGHT_PROBES ) - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - #endif - #if ( NUM_HEMI_LIGHTS > 0 ) - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - } - #pragma unroll_loop_end - #endif -#endif -#if defined( RE_IndirectSpecular ) - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,ec=`#if defined( RE_IndirectDiffuse ) - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - irradiance += lightMapIrradiance; - #endif - #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) - iblIrradiance += getIBLIrradiance( geometryNormal ); - #endif -#endif -#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) - #ifdef USE_ANISOTROPY - radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); - #else - radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); - #endif - #ifdef USE_CLEARCOAT - clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); - #endif -#endif`,nc=`#if defined( RE_IndirectDiffuse ) - RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif -#if defined( RE_IndirectSpecular ) - RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,ic=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) - gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,rc=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) - uniform float logDepthBufFC; - varying float vFragDepth; - varying float vIsPerspective; -#endif`,sc=`#ifdef USE_LOGDEPTHBUF - #ifdef USE_LOGDEPTHBUF_EXT - varying float vFragDepth; - varying float vIsPerspective; - #else - uniform float logDepthBufFC; - #endif -#endif`,ac=`#ifdef USE_LOGDEPTHBUF - #ifdef USE_LOGDEPTHBUF_EXT - vFragDepth = 1.0 + gl_Position.w; - vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); - #else - if ( isPerspectiveMatrix( projectionMatrix ) ) { - gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0; - gl_Position.z *= gl_Position.w; - } - #endif -#endif`,oc=`#ifdef USE_MAP - vec4 sampledDiffuseColor = texture2D( map, vMapUv ); - #ifdef DECODE_VIDEO_TEXTURE - sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w ); - - #endif - diffuseColor *= sampledDiffuseColor; -#endif`,lc=`#ifdef USE_MAP - uniform sampler2D map; -#endif`,cc=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - #if defined( USE_POINTS_UV ) - vec2 uv = vUv; - #else - vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; - #endif -#endif -#ifdef USE_MAP - diffuseColor *= texture2D( map, uv ); -#endif -#ifdef USE_ALPHAMAP - diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,hc=`#if defined( USE_POINTS_UV ) - varying vec2 vUv; -#else - #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - uniform mat3 uvTransform; - #endif -#endif -#ifdef USE_MAP - uniform sampler2D map; -#endif -#ifdef USE_ALPHAMAP - uniform sampler2D alphaMap; -#endif`,uc=`float metalnessFactor = metalness; -#ifdef USE_METALNESSMAP - vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); - metalnessFactor *= texelMetalness.b; -#endif`,dc=`#ifdef USE_METALNESSMAP - uniform sampler2D metalnessMap; -#endif`,fc=`#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE ) - vColor *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - #if defined( USE_COLOR_ALPHA ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; - #elif defined( USE_COLOR ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; - #endif - } -#endif`,pc=`#ifdef USE_MORPHNORMALS - objectNormal *= morphTargetBaseInfluence; - #ifdef MORPHTARGETS_TEXTURE - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; - } - #else - objectNormal += morphNormal0 * morphTargetInfluences[ 0 ]; - objectNormal += morphNormal1 * morphTargetInfluences[ 1 ]; - objectNormal += morphNormal2 * morphTargetInfluences[ 2 ]; - objectNormal += morphNormal3 * morphTargetInfluences[ 3 ]; - #endif -#endif`,mc=`#ifdef USE_MORPHTARGETS - uniform float morphTargetBaseInfluence; - #ifdef MORPHTARGETS_TEXTURE - uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - uniform sampler2DArray morphTargetsTexture; - uniform ivec2 morphTargetsTextureSize; - vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { - int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; - int y = texelIndex / morphTargetsTextureSize.x; - int x = texelIndex - y * morphTargetsTextureSize.x; - ivec3 morphUV = ivec3( x, y, morphTargetIndex ); - return texelFetch( morphTargetsTexture, morphUV, 0 ); - } - #else - #ifndef USE_MORPHNORMALS - uniform float morphTargetInfluences[ 8 ]; - #else - uniform float morphTargetInfluences[ 4 ]; - #endif - #endif -#endif`,gc=`#ifdef USE_MORPHTARGETS - transformed *= morphTargetBaseInfluence; - #ifdef MORPHTARGETS_TEXTURE - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; - } - #else - transformed += morphTarget0 * morphTargetInfluences[ 0 ]; - transformed += morphTarget1 * morphTargetInfluences[ 1 ]; - transformed += morphTarget2 * morphTargetInfluences[ 2 ]; - transformed += morphTarget3 * morphTargetInfluences[ 3 ]; - #ifndef USE_MORPHNORMALS - transformed += morphTarget4 * morphTargetInfluences[ 4 ]; - transformed += morphTarget5 * morphTargetInfluences[ 5 ]; - transformed += morphTarget6 * morphTargetInfluences[ 6 ]; - transformed += morphTarget7 * morphTargetInfluences[ 7 ]; - #endif - #endif -#endif`,_c=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; -#ifdef FLAT_SHADED - vec3 fdx = dFdx( vViewPosition ); - vec3 fdy = dFdy( vViewPosition ); - vec3 normal = normalize( cross( fdx, fdy ) ); -#else - vec3 normal = normalize( vNormal ); - #ifdef DOUBLE_SIDED - normal *= faceDirection; - #endif -#endif -#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) - #ifdef USE_TANGENT - mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn = getTangentFrame( - vViewPosition, normal, - #if defined( USE_NORMALMAP ) - vNormalMapUv - #elif defined( USE_CLEARCOAT_NORMALMAP ) - vClearcoatNormalMapUv - #else - vUv - #endif - ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn[0] *= faceDirection; - tbn[1] *= faceDirection; - #endif -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - #ifdef USE_TANGENT - mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn2[0] *= faceDirection; - tbn2[1] *= faceDirection; - #endif -#endif -vec3 nonPerturbedNormal = normal;`,vc=`#ifdef USE_NORMALMAP_OBJECTSPACE - normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - #ifdef FLIP_SIDED - normal = - normal; - #endif - #ifdef DOUBLE_SIDED - normal = normal * faceDirection; - #endif - normal = normalize( normalMatrix * normal ); -#elif defined( USE_NORMALMAP_TANGENTSPACE ) - vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - mapN.xy *= normalScale; - normal = normalize( tbn * mapN ); -#elif defined( USE_BUMPMAP ) - normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,xc=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,Mc=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,Sc=`#ifndef FLAT_SHADED - vNormal = normalize( transformedNormal ); - #ifdef USE_TANGENT - vTangent = normalize( transformedTangent ); - vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); - #endif -#endif`,yc=`#ifdef USE_NORMALMAP - uniform sampler2D normalMap; - uniform vec2 normalScale; -#endif -#ifdef USE_NORMALMAP_OBJECTSPACE - uniform mat3 normalMatrix; -#endif -#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) - mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { - vec3 q0 = dFdx( eye_pos.xyz ); - vec3 q1 = dFdy( eye_pos.xyz ); - vec2 st0 = dFdx( uv.st ); - vec2 st1 = dFdy( uv.st ); - vec3 N = surf_norm; - vec3 q1perp = cross( q1, N ); - vec3 q0perp = cross( N, q0 ); - vec3 T = q1perp * st0.x + q0perp * st1.x; - vec3 B = q1perp * st0.y + q0perp * st1.y; - float det = max( dot( T, T ), dot( B, B ) ); - float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); - return mat3( T * scale, B * scale, N ); - } -#endif`,Ec=`#ifdef USE_CLEARCOAT - vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,Tc=`#ifdef USE_CLEARCOAT_NORMALMAP - vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; - clearcoatMapN.xy *= clearcoatNormalScale; - clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,bc=`#ifdef USE_CLEARCOATMAP - uniform sampler2D clearcoatMap; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform sampler2D clearcoatNormalMap; - uniform vec2 clearcoatNormalScale; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform sampler2D clearcoatRoughnessMap; -#endif`,Ac=`#ifdef USE_IRIDESCENCEMAP - uniform sampler2D iridescenceMap; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform sampler2D iridescenceThicknessMap; -#endif`,wc=`#ifdef OPAQUE -diffuseColor.a = 1.0; -#endif -#ifdef USE_TRANSMISSION -diffuseColor.a *= material.transmissionAlpha; -#endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Rc=`vec3 packNormalToRGB( const in vec3 normal ) { - return normalize( normal ) * 0.5 + 0.5; -} -vec3 unpackRGBToNormal( const in vec3 rgb ) { - return 2.0 * rgb.xyz - 1.0; -} -const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.; -const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. ); -const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. ); -const float ShiftRight8 = 1. / 256.; -vec4 packDepthToRGBA( const in float v ) { - vec4 r = vec4( fract( v * PackFactors ), v ); - r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale; -} -float unpackRGBAToDepth( const in vec4 v ) { - return dot( v, UnpackFactors ); -} -vec2 packDepthToRG( in highp float v ) { - return packDepthToRGBA( v ).yx; -} -float unpackRGToDepth( const in highp vec2 v ) { - return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) ); -} -vec4 pack2HalfToRGBA( vec2 v ) { - vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); - return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); -} -vec2 unpackRGBATo2Half( vec4 v ) { - return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); -} -float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { - return ( viewZ + near ) / ( near - far ); -} -float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { - return depth * ( near - far ) - near; -} -float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { - return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); -} -float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { - return ( near * far ) / ( ( far - near ) * depth - far ); -}`,Cc=`#ifdef PREMULTIPLIED_ALPHA - gl_FragColor.rgb *= gl_FragColor.a; -#endif`,Lc=`vec4 mvPosition = vec4( transformed, 1.0 ); -#ifdef USE_BATCHING - mvPosition = batchingMatrix * mvPosition; -#endif -#ifdef USE_INSTANCING - mvPosition = instanceMatrix * mvPosition; -#endif -mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,Pc=`#ifdef DITHERING - gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,Dc=`#ifdef DITHERING - vec3 dithering( vec3 color ) { - float grid_position = rand( gl_FragCoord.xy ); - vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); - dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); - return color + dither_shift_RGB; - } -#endif`,Uc=`float roughnessFactor = roughness; -#ifdef USE_ROUGHNESSMAP - vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); - roughnessFactor *= texelRoughness.g; -#endif`,Ic=`#ifdef USE_ROUGHNESSMAP - uniform sampler2D roughnessMap; -#endif`,Nc=`#if NUM_SPOT_LIGHT_COORDS > 0 - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#if NUM_SPOT_LIGHT_MAPS > 0 - uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; -#endif -#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 ]; - 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 - 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 ); - 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 ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); - } - return occlusion; - } - float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - float shadow = 1.0; - shadowCoord.xyz /= shadowCoord.w; - shadowCoord.z += shadowBias; - bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; - bool frustumTest = inFrustum && shadowCoord.z <= 1.0; - if ( frustumTest ) { - #if defined( SHADOWMAP_TYPE_PCF ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx0 = - texelSize.x * shadowRadius; - float dy0 = - texelSize.y * shadowRadius; - float dx1 = + texelSize.x * shadowRadius; - float dy1 = + texelSize.y * shadowRadius; - float dx2 = dx0 / 2.0; - float dy2 = dy0 / 2.0; - float dx3 = dx1 / 2.0; - float dy3 = dy1 / 2.0; - shadow = ( - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) - ) * ( 1.0 / 17.0 ); - #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 - shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); - #endif - } - return shadow; - } - vec2 cubeToUV( vec3 v, float texelSizeY ) { - vec3 absV = abs( v ); - float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); - absV *= scaleToCube; - v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); - 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; - } - 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 ) { - vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); - vec3 lightToPosition = shadowCoord.xyz; - float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; - vec3 bd3D = normalize( lightToPosition ); - #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) - vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; - return ( - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) - ) * ( 1.0 / 9.0 ); - #else - return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); - #endif - } -#endif`,Fc=`#if NUM_SPOT_LIGHT_COORDS > 0 - uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform mat4 directionalShadowMatrix[ 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 - 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 mat4 pointShadowMatrix[ 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 -#endif`,Oc=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) - vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - vec4 shadowWorldPosition; -#endif -#if defined( USE_SHADOWMAP ) - #if NUM_DIR_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); - vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); - vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif -#endif -#if NUM_SPOT_LIGHT_COORDS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { - shadowWorldPosition = worldPosition; - #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; - #endif - vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end -#endif`,Bc=`float getShadowMask() { - float shadow = 1.0; - #ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - directionalLight = directionalLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { - spotLight = spotLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - pointLight = pointLightShadows[ i ]; - shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; - } - #pragma unroll_loop_end - #endif - #endif - return shadow; -}`,zc=`#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,Gc=`#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif`,Vc=`#ifdef USE_SKINNING - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,Hc=`#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - #ifdef USE_TANGENT - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - #endif -#endif`,kc=`float specularStrength; -#ifdef USE_SPECULARMAP - vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); - specularStrength = texelSpecular.r; -#else - specularStrength = 1.0; -#endif`,Wc=`#ifdef USE_SPECULARMAP - uniform sampler2D specularMap; -#endif`,Xc=`#if defined( TONE_MAPPING ) - gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,qc=`#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -uniform float toneMappingExposure; -vec3 LinearToneMapping( vec3 color ) { - return saturate( toneMappingExposure * color ); -} -vec3 ReinhardToneMapping( vec3 color ) { - color *= toneMappingExposure; - return saturate( color / ( vec3( 1.0 ) + color ) ); -} -vec3 OptimizedCineonToneMapping( vec3 color ) { - color *= toneMappingExposure; - color = max( vec3( 0.0 ), color - 0.004 ); - return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); -} -vec3 RRTAndODTFit( vec3 v ) { - vec3 a = v * ( v + 0.0245786 ) - 0.000090537; - vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; - return a / b; -} -vec3 ACESFilmicToneMapping( vec3 color ) { - const mat3 ACESInputMat = mat3( - vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), - vec3( 0.04823, 0.01566, 0.83777 ) - ); - const mat3 ACESOutputMat = mat3( - vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), - vec3( -0.07367, -0.00605, 1.07602 ) - ); - color *= toneMappingExposure / 0.6; - color = ACESInputMat * color; - color = RRTAndODTFit( color ); - color = ACESOutputMat * color; - return saturate( color ); -} -const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( - vec3( 1.6605, - 0.1246, - 0.0182 ), - vec3( - 0.5876, 1.1329, - 0.1006 ), - vec3( - 0.0728, - 0.0083, 1.1187 ) -); -const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( - vec3( 0.6274, 0.0691, 0.0164 ), - vec3( 0.3293, 0.9195, 0.0880 ), - vec3( 0.0433, 0.0113, 0.8956 ) -); -vec3 agxDefaultContrastApprox( vec3 x ) { - vec3 x2 = x * x; - vec3 x4 = x2 * x2; - return + 15.5 * x4 * x2 - - 40.14 * x4 * x - + 31.96 * x4 - - 6.868 * x2 * x - + 0.4298 * x2 - + 0.1191 * x - - 0.00232; -} -vec3 AgXToneMapping( vec3 color ) { - const mat3 AgXInsetMatrix = mat3( - vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), - vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), - vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) - ); - const mat3 AgXOutsetMatrix = mat3( - vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), - vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), - vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) - ); - const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; - color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; - color *= toneMappingExposure; - color = AgXInsetMatrix * color; - color = max( color, 1e-10 ); color = log2( color ); - color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); - color = clamp( color, 0.0, 1.0 ); - color = agxDefaultContrastApprox( color ); - color = AgXOutsetMatrix * color; - color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); - color = LINEAR_REC2020_TO_LINEAR_SRGB * color; - return color; -} -vec3 CustomToneMapping( vec3 color ) { return color; }`,Yc=`#ifdef USE_TRANSMISSION - material.transmission = transmission; - material.transmissionAlpha = 1.0; - material.thickness = thickness; - material.attenuationDistance = attenuationDistance; - material.attenuationColor = attenuationColor; - #ifdef USE_TRANSMISSIONMAP - material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; - #endif - #ifdef USE_THICKNESSMAP - material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; - #endif - vec3 pos = vWorldPosition; - vec3 v = normalize( cameraPosition - pos ); - vec3 n = inverseTransformDirection( normal, viewMatrix ); - vec4 transmitted = getIBLVolumeRefraction( - n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, - pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness, - material.attenuationColor, material.attenuationDistance ); - material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); - totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,Kc=`#ifdef USE_TRANSMISSION - uniform float transmission; - uniform float thickness; - uniform float attenuationDistance; - uniform vec3 attenuationColor; - #ifdef USE_TRANSMISSIONMAP - uniform sampler2D transmissionMap; - #endif - #ifdef USE_THICKNESSMAP - uniform sampler2D thicknessMap; - #endif - uniform vec2 transmissionSamplerSize; - uniform sampler2D transmissionSamplerMap; - uniform mat4 modelMatrix; - uniform mat4 projectionMatrix; - varying vec3 vWorldPosition; - float w0( float a ) { - return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); - } - float w1( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); - } - float w2( float a ){ - return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); - } - float w3( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * a ); - } - float g0( float a ) { - return w0( a ) + w1( a ); - } - float g1( float a ) { - return w2( a ) + w3( a ); - } - float h0( float a ) { - return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); - } - float h1( float a ) { - return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); - } - vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { - uv = uv * texelSize.zw + 0.5; - vec2 iuv = floor( uv ); - vec2 fuv = fract( uv ); - float g0x = g0( fuv.x ); - float g1x = g1( fuv.x ); - float h0x = h0( fuv.x ); - float h1x = h1( fuv.x ); - float h0y = h0( fuv.y ); - float h1y = h1( fuv.y ); - vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + - g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); - } - vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { - vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); - vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); - vec2 fLodSizeInv = 1.0 / fLodSize; - vec2 cLodSizeInv = 1.0 / cLodSize; - vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); - vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); - return mix( fSample, cSample, fract( lod ) ); - } - vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { - vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); - vec3 modelScale; - modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); - modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); - modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); - return normalize( refractionVector ) * thickness * modelScale; - } - float applyIorToRoughness( const in float roughness, const in float ior ) { - return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); - } - vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { - float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); - return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); - } - vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { - if ( isinf( attenuationDistance ) ) { - return vec3( 1.0 ); - } else { - vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; - vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; - } - } - vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, - const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, - const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness, - const in vec3 attenuationColor, const in float attenuationDistance ) { - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); - vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); - vec3 attenuatedColor = transmittance * transmittedLight.rgb; - vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); - float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; - return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); - } -#endif`,Jc=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - varying vec2 vNormalMapUv; -#endif -#ifdef USE_EMISSIVEMAP - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_SPECULARMAP - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,jc=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - uniform mat3 mapTransform; - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - uniform mat3 alphaMapTransform; - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - uniform mat3 lightMapTransform; - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - uniform mat3 aoMapTransform; - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - uniform mat3 bumpMapTransform; - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - uniform mat3 normalMapTransform; - varying vec2 vNormalMapUv; -#endif -#ifdef USE_DISPLACEMENTMAP - uniform mat3 displacementMapTransform; - varying vec2 vDisplacementMapUv; -#endif -#ifdef USE_EMISSIVEMAP - uniform mat3 emissiveMapTransform; - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - uniform mat3 metalnessMapTransform; - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - uniform mat3 roughnessMapTransform; - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - uniform mat3 anisotropyMapTransform; - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - uniform mat3 clearcoatMapTransform; - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform mat3 clearcoatNormalMapTransform; - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform mat3 clearcoatRoughnessMapTransform; - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - uniform mat3 sheenColorMapTransform; - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - uniform mat3 sheenRoughnessMapTransform; - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - uniform mat3 iridescenceMapTransform; - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform mat3 iridescenceThicknessMapTransform; - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SPECULARMAP - uniform mat3 specularMapTransform; - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - uniform mat3 specularColorMapTransform; - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - uniform mat3 specularIntensityMapTransform; - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,Zc=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - vUv = vec3( uv, 1 ).xy; -#endif -#ifdef USE_MAP - vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ALPHAMAP - vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_LIGHTMAP - vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_AOMAP - vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_BUMPMAP - vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_NORMALMAP - vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_DISPLACEMENTMAP - vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_EMISSIVEMAP - vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_METALNESSMAP - vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ROUGHNESSMAP - vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ANISOTROPYMAP - vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOATMAP - vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCEMAP - vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_COLORMAP - vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULARMAP - vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_COLORMAP - vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_TRANSMISSIONMAP - vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_THICKNESSMAP - vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,$c=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 - vec4 worldPosition = vec4( transformed, 1.0 ); - #ifdef USE_BATCHING - worldPosition = batchingMatrix * worldPosition; - #endif - #ifdef USE_INSTANCING - worldPosition = instanceMatrix * worldPosition; - #endif - worldPosition = modelMatrix * worldPosition; -#endif`;const Qc=`varying vec2 vUv; -uniform mat3 uvTransform; -void main() { - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,th=`uniform sampler2D t2D; -uniform float backgroundIntensity; -varying vec2 vUv; -void main() { - vec4 texColor = texture2D( t2D, vUv ); - #ifdef DECODE_VIDEO_TEXTURE - texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,eh=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,nh=`#ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; -#elif defined( ENVMAP_TYPE_CUBE_UV ) - uniform sampler2D envMap; -#endif -uniform float flipEnvMap; -uniform float backgroundBlurriness; -uniform float backgroundIntensity; -varying vec3 vWorldDirection; -#include -void main() { - #ifdef ENVMAP_TYPE_CUBE - vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); - #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness ); - #else - vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,ih=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,rh=`uniform samplerCube tCube; -uniform float tFlip; -uniform float opacity; -varying vec3 vWorldDirection; -void main() { - vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); - gl_FragColor = texColor; - gl_FragColor.a *= opacity; - #include - #include -}`,sh=`#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vHighPrecisionZW = gl_Position.zw; -}`,ah=`#if DEPTH_PACKING == 3200 - uniform float opacity; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - #include - vec4 diffuseColor = vec4( 1.0 ); - #if DEPTH_PACKING == 3200 - diffuseColor.a = opacity; - #endif - #include - #include - #include - #include - #include - float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; - #if DEPTH_PACKING == 3200 - gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); - #elif DEPTH_PACKING == 3201 - gl_FragColor = packDepthToRGBA( fragCoordZ ); - #endif -}`,oh=`#define DISTANCE -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vWorldPosition = worldPosition.xyz; -}`,lh=`#define DISTANCE -uniform vec3 referencePosition; -uniform float nearDistance; -uniform float farDistance; -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -#include -void main () { - #include - vec4 diffuseColor = vec4( 1.0 ); - #include - #include - #include - #include - float dist = length( vWorldPosition - referencePosition ); - dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); - dist = saturate( dist ); - gl_FragColor = packDepthToRGBA( dist ); -}`,ch=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include -}`,hh=`uniform sampler2D tEquirect; -varying vec3 vWorldDirection; -#include -void main() { - vec3 direction = normalize( vWorldDirection ); - vec2 sampleUV = equirectUv( direction ); - gl_FragColor = texture2D( tEquirect, sampleUV ); - #include - #include -}`,uh=`uniform float scale; -attribute float lineDistance; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vLineDistance = scale * lineDistance; - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,dh=`uniform vec3 diffuse; -uniform float opacity; -uniform float dashSize; -uniform float totalSize; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - if ( mod( vLineDistance, totalSize ) > dashSize ) { - discard; - } - vec3 outgoingLight = vec3( 0.0 ); - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,fh=`#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) - #include - #include - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,ph=`uniform vec3 diffuse; -uniform float opacity; -#ifndef FLAT_SHADED - varying vec3 vNormal; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; - #else - reflectedLight.indirectDiffuse += vec3( 1.0 ); - #endif - #include - reflectedLight.indirectDiffuse *= diffuseColor.rgb; - vec3 outgoingLight = reflectedLight.indirectDiffuse; - #include - #include - #include - #include - #include - #include - #include -}`,mh=`#define LAMBERT -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,gh=`#define LAMBERT -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - vec4 diffuseColor = vec4( diffuse, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,_h=`#define MATCAP -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; -}`,vh=`#define MATCAP -uniform vec3 diffuse; -uniform float opacity; -uniform sampler2D matcap; -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - vec3 viewDir = normalize( vViewPosition ); - vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); - vec3 y = cross( viewDir, x ); - vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; - #ifdef USE_MATCAP - vec4 matcapColor = texture2D( matcap, uv ); - #else - vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); - #endif - vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; - #include - #include - #include - #include - #include - #include -}`,xh=`#define NORMAL -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - vViewPosition = - mvPosition.xyz; -#endif -}`,Mh=`#define NORMAL -uniform float opacity; -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - gl_FragColor = vec4( packNormalToRGB( normal ), opacity ); - #ifdef OPAQUE - gl_FragColor.a = 1.0; - #endif -}`,Sh=`#define PHONG -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,yh=`#define PHONG -uniform vec3 diffuse; -uniform vec3 emissive; -uniform vec3 specular; -uniform float shininess; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - vec4 diffuseColor = vec4( diffuse, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,Eh=`#define STANDARD -varying vec3 vViewPosition; -#ifdef USE_TRANSMISSION - varying vec3 vWorldPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -#ifdef USE_TRANSMISSION - vWorldPosition = worldPosition.xyz; -#endif -}`,Th=`#define STANDARD -#ifdef PHYSICAL - #define IOR - #define USE_SPECULAR -#endif -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float roughness; -uniform float metalness; -uniform float opacity; -#ifdef IOR - uniform float ior; -#endif -#ifdef USE_SPECULAR - uniform float specularIntensity; - uniform vec3 specularColor; - #ifdef USE_SPECULAR_COLORMAP - uniform sampler2D specularColorMap; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - uniform sampler2D specularIntensityMap; - #endif -#endif -#ifdef USE_CLEARCOAT - uniform float clearcoat; - uniform float clearcoatRoughness; -#endif -#ifdef USE_IRIDESCENCE - uniform float iridescence; - uniform float iridescenceIOR; - uniform float iridescenceThicknessMinimum; - uniform float iridescenceThicknessMaximum; -#endif -#ifdef USE_SHEEN - uniform vec3 sheenColor; - uniform float sheenRoughness; - #ifdef USE_SHEEN_COLORMAP - uniform sampler2D sheenColorMap; - #endif - #ifdef USE_SHEEN_ROUGHNESSMAP - uniform sampler2D sheenRoughnessMap; - #endif -#endif -#ifdef USE_ANISOTROPY - uniform vec2 anisotropyVector; - #ifdef USE_ANISOTROPYMAP - uniform sampler2D anisotropyMap; - #endif -#endif -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - vec4 diffuseColor = vec4( diffuse, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; - vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; - #include - vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; - #ifdef USE_SHEEN - float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); - outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; - #endif - #ifdef USE_CLEARCOAT - float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); - vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); - outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; - #endif - #include - #include - #include - #include - #include - #include -}`,bh=`#define TOON -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -}`,Ah=`#define TOON -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - vec4 diffuseColor = vec4( diffuse, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include -}`,wh=`uniform float size; -uniform float scale; -#include -#include -#include -#include -#include -#include -#ifdef USE_POINTS_UV - varying vec2 vUv; - uniform mat3 uvTransform; -#endif -void main() { - #ifdef USE_POINTS_UV - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - #endif - #include - #include - #include - #include - #include - gl_PointSize = size; - #ifdef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); - #endif - #include - #include - #include - #include -}`,Rh=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - vec3 outgoingLight = vec3( 0.0 ); - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,Ch=`#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,Lh=`uniform vec3 color; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); - #include - #include - #include -}`,Ph=`uniform float rotation; -uniform vec2 center; -#include -#include -#include -#include -#include -void main() { - #include - vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ); - 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 ) ); - #ifndef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) scale *= - mvPosition.z; - #endif - vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; - vec2 rotatedPosition; - rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; - rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; - mvPosition.xy += rotatedPosition; - gl_Position = projectionMatrix * mvPosition; - #include - #include - #include -}`,Dh=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - vec3 outgoingLight = vec3( 0.0 ); - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include -}`,Dt={alphahash_fragment:tl,alphahash_pars_fragment:el,alphamap_fragment:nl,alphamap_pars_fragment:il,alphatest_fragment:rl,alphatest_pars_fragment:sl,aomap_fragment:al,aomap_pars_fragment:ol,batching_pars_vertex:ll,batching_vertex:cl,begin_vertex:hl,beginnormal_vertex:ul,bsdfs:dl,iridescence_fragment:fl,bumpmap_pars_fragment:pl,clipping_planes_fragment:ml,clipping_planes_pars_fragment:gl,clipping_planes_pars_vertex:_l,clipping_planes_vertex:vl,color_fragment:xl,color_pars_fragment:Ml,color_pars_vertex:Sl,color_vertex:yl,common:El,cube_uv_reflection_fragment:Tl,defaultnormal_vertex:bl,displacementmap_pars_vertex:Al,displacementmap_vertex:wl,emissivemap_fragment:Rl,emissivemap_pars_fragment:Cl,colorspace_fragment:Ll,colorspace_pars_fragment:Pl,envmap_fragment:Dl,envmap_common_pars_fragment:Ul,envmap_pars_fragment:Il,envmap_pars_vertex:Nl,envmap_physical_pars_fragment:Yl,envmap_vertex:Fl,fog_vertex:Ol,fog_pars_vertex:Bl,fog_fragment:zl,fog_pars_fragment:Gl,gradientmap_pars_fragment:Vl,lightmap_fragment:Hl,lightmap_pars_fragment:kl,lights_lambert_fragment:Wl,lights_lambert_pars_fragment:Xl,lights_pars_begin:ql,lights_toon_fragment:Kl,lights_toon_pars_fragment:Jl,lights_phong_fragment:jl,lights_phong_pars_fragment:Zl,lights_physical_fragment:$l,lights_physical_pars_fragment:Ql,lights_fragment_begin:tc,lights_fragment_maps:ec,lights_fragment_end:nc,logdepthbuf_fragment:ic,logdepthbuf_pars_fragment:rc,logdepthbuf_pars_vertex:sc,logdepthbuf_vertex:ac,map_fragment:oc,map_pars_fragment:lc,map_particle_fragment:cc,map_particle_pars_fragment:hc,metalnessmap_fragment:uc,metalnessmap_pars_fragment:dc,morphcolor_vertex:fc,morphnormal_vertex:pc,morphtarget_pars_vertex:mc,morphtarget_vertex:gc,normal_fragment_begin:_c,normal_fragment_maps:vc,normal_pars_fragment:xc,normal_pars_vertex:Mc,normal_vertex:Sc,normalmap_pars_fragment:yc,clearcoat_normal_fragment_begin:Ec,clearcoat_normal_fragment_maps:Tc,clearcoat_pars_fragment:bc,iridescence_pars_fragment:Ac,opaque_fragment:wc,packing:Rc,premultiplied_alpha_fragment:Cc,project_vertex:Lc,dithering_fragment:Pc,dithering_pars_fragment:Dc,roughnessmap_fragment:Uc,roughnessmap_pars_fragment:Ic,shadowmap_pars_fragment:Nc,shadowmap_pars_vertex:Fc,shadowmap_vertex:Oc,shadowmask_pars_fragment:Bc,skinbase_vertex:zc,skinning_pars_vertex:Gc,skinning_vertex:Vc,skinnormal_vertex:Hc,specularmap_fragment:kc,specularmap_pars_fragment:Wc,tonemapping_fragment:Xc,tonemapping_pars_fragment:qc,transmission_fragment:Yc,transmission_pars_fragment:Kc,uv_pars_fragment:Jc,uv_pars_vertex:jc,uv_vertex:Zc,worldpos_vertex:$c,background_vert:Qc,background_frag:th,backgroundCube_vert:eh,backgroundCube_frag:nh,cube_vert:ih,cube_frag:rh,depth_vert:sh,depth_frag:ah,distanceRGBA_vert:oh,distanceRGBA_frag:lh,equirect_vert:ch,equirect_frag:hh,linedashed_vert:uh,linedashed_frag:dh,meshbasic_vert:fh,meshbasic_frag:ph,meshlambert_vert:mh,meshlambert_frag:gh,meshmatcap_vert:_h,meshmatcap_frag:vh,meshnormal_vert:xh,meshnormal_frag:Mh,meshphong_vert:Sh,meshphong_frag:yh,meshphysical_vert:Eh,meshphysical_frag:Th,meshtoon_vert:bh,meshtoon_frag:Ah,points_vert:wh,points_frag:Rh,shadow_vert:Ch,shadow_frag:Lh,sprite_vert:Ph,sprite_frag:Dh},nt={common:{diffuse:{value:new zt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Bt},alphaMap:{value:null},alphaMapTransform:{value:new Bt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Bt}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Bt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Bt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Bt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Bt},normalScale:{value:new ct(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Bt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Bt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Bt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Bt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new zt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new zt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Bt},alphaTest:{value:0},uvTransform:{value:new Bt}},sprite:{diffuse:{value:new zt(16777215)},opacity:{value:1},center:{value:new ct(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Bt},alphaMap:{value:null},alphaMapTransform:{value:new Bt},alphaTest:{value:0}}},ze={basic:{uniforms:Ee([nt.common,nt.specularmap,nt.envmap,nt.aomap,nt.lightmap,nt.fog]),vertexShader:Dt.meshbasic_vert,fragmentShader:Dt.meshbasic_frag},lambert:{uniforms:Ee([nt.common,nt.specularmap,nt.envmap,nt.aomap,nt.lightmap,nt.emissivemap,nt.bumpmap,nt.normalmap,nt.displacementmap,nt.fog,nt.lights,{emissive:{value:new zt(0)}}]),vertexShader:Dt.meshlambert_vert,fragmentShader:Dt.meshlambert_frag},phong:{uniforms:Ee([nt.common,nt.specularmap,nt.envmap,nt.aomap,nt.lightmap,nt.emissivemap,nt.bumpmap,nt.normalmap,nt.displacementmap,nt.fog,nt.lights,{emissive:{value:new zt(0)},specular:{value:new zt(1118481)},shininess:{value:30}}]),vertexShader:Dt.meshphong_vert,fragmentShader:Dt.meshphong_frag},standard:{uniforms:Ee([nt.common,nt.envmap,nt.aomap,nt.lightmap,nt.emissivemap,nt.bumpmap,nt.normalmap,nt.displacementmap,nt.roughnessmap,nt.metalnessmap,nt.fog,nt.lights,{emissive:{value:new zt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Dt.meshphysical_vert,fragmentShader:Dt.meshphysical_frag},toon:{uniforms:Ee([nt.common,nt.aomap,nt.lightmap,nt.emissivemap,nt.bumpmap,nt.normalmap,nt.displacementmap,nt.gradientmap,nt.fog,nt.lights,{emissive:{value:new zt(0)}}]),vertexShader:Dt.meshtoon_vert,fragmentShader:Dt.meshtoon_frag},matcap:{uniforms:Ee([nt.common,nt.bumpmap,nt.normalmap,nt.displacementmap,nt.fog,{matcap:{value:null}}]),vertexShader:Dt.meshmatcap_vert,fragmentShader:Dt.meshmatcap_frag},points:{uniforms:Ee([nt.points,nt.fog]),vertexShader:Dt.points_vert,fragmentShader:Dt.points_frag},dashed:{uniforms:Ee([nt.common,nt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Dt.linedashed_vert,fragmentShader:Dt.linedashed_frag},depth:{uniforms:Ee([nt.common,nt.displacementmap]),vertexShader:Dt.depth_vert,fragmentShader:Dt.depth_frag},normal:{uniforms:Ee([nt.common,nt.bumpmap,nt.normalmap,nt.displacementmap,{opacity:{value:1}}]),vertexShader:Dt.meshnormal_vert,fragmentShader:Dt.meshnormal_frag},sprite:{uniforms:Ee([nt.sprite,nt.fog]),vertexShader:Dt.sprite_vert,fragmentShader:Dt.sprite_frag},background:{uniforms:{uvTransform:{value:new Bt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Dt.background_vert,fragmentShader:Dt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:Dt.backgroundCube_vert,fragmentShader:Dt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Dt.cube_vert,fragmentShader:Dt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Dt.equirect_vert,fragmentShader:Dt.equirect_frag},distanceRGBA:{uniforms:Ee([nt.common,nt.displacementmap,{referencePosition:{value:new R},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Dt.distanceRGBA_vert,fragmentShader:Dt.distanceRGBA_frag},shadow:{uniforms:Ee([nt.lights,nt.fog,{color:{value:new zt(0)},opacity:{value:1}}]),vertexShader:Dt.shadow_vert,fragmentShader:Dt.shadow_frag}};ze.physical={uniforms:Ee([ze.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Bt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Bt},clearcoatNormalScale:{value:new ct(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Bt},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Bt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Bt},sheen:{value:0},sheenColor:{value:new zt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Bt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Bt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Bt},transmissionSamplerSize:{value:new ct},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Bt},attenuationDistance:{value:0},attenuationColor:{value:new zt(0)},specularColor:{value:new zt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Bt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Bt},anisotropyVector:{value:new ct},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Bt}}]),vertexShader:Dt.meshphysical_vert,fragmentShader:Dt.meshphysical_frag};const Oi={r:0,b:0,g:0};function Uh(r,t,e,n,i,s,o){const a=new zt(0);let l=s===!0?0:1,c,h,u=null,d=0,p=null;function g(m,f){let S=!1,_=f.isScene===!0?f.background:null;_&&_.isTexture&&(_=(f.backgroundBlurriness>0?e:t).get(_)),_===null?v(a,l):_&&_.isColor&&(v(_,1),S=!0);const b=r.xr.getEnvironmentBlendMode();b==="additive"?n.buffers.color.setClear(0,0,0,1,o):b==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,o),(r.autoClear||S)&&r.clear(r.autoClearColor,r.autoClearDepth,r.autoClearStencil),_&&(_.isCubeTexture||_.mapping===306)?(h===void 0&&(h=new Fe(new di(1,1,1),new _n({name:"BackgroundCubeMaterial",uniforms:Hn(ze.backgroundCube.uniforms),vertexShader:ze.backgroundCube.vertexShader,fragmentShader:ze.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(C,A,w){this.matrixWorld.copyPosition(w.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(h)),h.material.uniforms.envMap.value=_,h.material.uniforms.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=f.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=f.backgroundIntensity,h.material.toneMapped=Kt.getTransfer(_.colorSpace)!==Qt,(u!==_||d!==_.version||p!==r.toneMapping)&&(h.material.needsUpdate=!0,u=_,d=_.version,p=r.toneMapping),h.layers.enableAll(),m.unshift(h,h.geometry,h.material,0,0,null)):_&&_.isTexture&&(c===void 0&&(c=new Fe(new ts(2,2),new _n({name:"BackgroundMaterial",uniforms:Hn(ze.background.uniforms),vertexShader:ze.background.vertexShader,fragmentShader:ze.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(c)),c.material.uniforms.t2D.value=_,c.material.uniforms.backgroundIntensity.value=f.backgroundIntensity,c.material.toneMapped=Kt.getTransfer(_.colorSpace)!==Qt,_.matrixAutoUpdate===!0&&_.updateMatrix(),c.material.uniforms.uvTransform.value.copy(_.matrix),(u!==_||d!==_.version||p!==r.toneMapping)&&(c.material.needsUpdate=!0,u=_,d=_.version,p=r.toneMapping),c.layers.enableAll(),m.unshift(c,c.geometry,c.material,0,0,null))}function v(m,f){m.getRGB(Oi,Ua(r)),n.buffers.color.setClear(Oi.r,Oi.g,Oi.b,f,o)}return{getClearColor:function(){return a},setClearColor:function(m,f=1){a.set(m),l=f,v(a,l)},getClearAlpha:function(){return l},setClearAlpha:function(m){l=m,v(a,l)},render:g}}function Ih(r,t,e,n){const i=r.getParameter(r.MAX_VERTEX_ATTRIBS),s=n.isWebGL2?null:t.get("OES_vertex_array_object"),o=n.isWebGL2||s!==null,a={},l=m(null);let c=l,h=!1;function u(P,I,k,q,X){let W=!1;if(o){const j=v(q,k,I);c!==j&&(c=j,p(c.object)),W=f(P,q,k,X),W&&S(P,q,k,X)}else{const j=I.wireframe===!0;(c.geometry!==q.id||c.program!==k.id||c.wireframe!==j)&&(c.geometry=q.id,c.program=k.id,c.wireframe=j,W=!0)}X!==null&&e.update(X,r.ELEMENT_ARRAY_BUFFER),(W||h)&&(h=!1,U(P,I,k,q),X!==null&&r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.get(X).buffer))}function d(){return n.isWebGL2?r.createVertexArray():s.createVertexArrayOES()}function p(P){return n.isWebGL2?r.bindVertexArray(P):s.bindVertexArrayOES(P)}function g(P){return n.isWebGL2?r.deleteVertexArray(P):s.deleteVertexArrayOES(P)}function v(P,I,k){const q=k.wireframe===!0;let X=a[P.id];X===void 0&&(X={},a[P.id]=X);let W=X[I.id];W===void 0&&(W={},X[I.id]=W);let j=W[q];return j===void 0&&(j=m(d()),W[q]=j),j}function m(P){const I=[],k=[],q=[];for(let X=0;X=0){const Y=X[lt];let at=W[lt];if(at===void 0&&(lt==="instanceMatrix"&&P.instanceMatrix&&(at=P.instanceMatrix),lt==="instanceColor"&&P.instanceColor&&(at=P.instanceColor)),Y===void 0||Y.attribute!==at||at&&Y.data!==at.data)return!0;j++}return c.attributesNum!==j||c.index!==q}function S(P,I,k,q){const X={},W=I.attributes;let j=0;const Q=k.getAttributes();for(const lt in Q)if(Q[lt].location>=0){let Y=W[lt];Y===void 0&&(lt==="instanceMatrix"&&P.instanceMatrix&&(Y=P.instanceMatrix),lt==="instanceColor"&&P.instanceColor&&(Y=P.instanceColor));const at={};at.attribute=Y,Y&&Y.data&&(at.data=Y.data),X[lt]=at,j++}c.attributes=X,c.attributesNum=j,c.index=q}function _(){const P=c.newAttributes;for(let I=0,k=P.length;I=0){let V=X[Q];if(V===void 0&&(Q==="instanceMatrix"&&P.instanceMatrix&&(V=P.instanceMatrix),Q==="instanceColor"&&P.instanceColor&&(V=P.instanceColor)),V!==void 0){const Y=V.normalized,at=V.itemSize,gt=e.get(V);if(gt===void 0)continue;const mt=gt.buffer,Rt=gt.type,Lt=gt.bytesPerElement,yt=n.isWebGL2===!0&&(Rt===r.INT||Rt===r.UNSIGNED_INT||V.gpuType===1013);if(V.isInterleavedBufferAttribute){const Ht=V.data,N=Ht.stride,xe=V.offset;if(Ht.isInstancedInterleavedBuffer){for(let vt=0;vt0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision>0)return"highp";w="mediump"}return w==="mediump"&&r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const o=typeof WebGL2RenderingContext<"u"&&r.constructor.name==="WebGL2RenderingContext";let a=e.precision!==void 0?e.precision:"highp";const l=s(a);l!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",l,"instead."),a=l);const c=o||t.has("WEBGL_draw_buffers"),h=e.logarithmicDepthBuffer===!0,u=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),d=r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS),p=r.getParameter(r.MAX_TEXTURE_SIZE),g=r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE),v=r.getParameter(r.MAX_VERTEX_ATTRIBS),m=r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS),f=r.getParameter(r.MAX_VARYING_VECTORS),S=r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS),_=d>0,b=o||t.has("OES_texture_float"),C=_&&b,A=o?r.getParameter(r.MAX_SAMPLES):0;return{isWebGL2:o,drawBuffers:c,getMaxAnisotropy:i,getMaxPrecision:s,precision:a,logarithmicDepthBuffer:h,maxTextures:u,maxVertexTextures:d,maxTextureSize:p,maxCubemapSize:g,maxAttributes:v,maxVertexUniforms:m,maxVaryings:f,maxFragmentUniforms:S,vertexTextures:_,floatFragmentTextures:b,floatVertexTextures:C,maxSamples:A}}function Oh(r){const t=this;let e=null,n=0,i=!1,s=!1;const o=new fn,a=new Bt,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){const p=u.length!==0||d||n!==0||i;return i=d,n=u.length,p},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(u,d){e=h(u,d,0)},this.setState=function(u,d,p){const g=u.clippingPlanes,v=u.clipIntersection,m=u.clipShadows,f=r.get(u);if(!i||g===null||g.length===0||s&&!m)s?h(null):c();else{const S=s?0:n,_=S*4;let b=f.clippingState||null;l.value=b,b=h(g,d,_,p);for(let C=0;C!==_;++C)b[C]=e[C];f.clippingState=b,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=S}};function c(){l.value!==e&&(l.value=e,l.needsUpdate=n>0),t.numPlanes=n,t.numIntersection=0}function h(u,d,p,g){const v=u!==null?u.length:0;let m=null;if(v!==0){if(m=l.value,g!==!0||m===null){const f=p+v*4,S=d.matrixWorldInverse;a.getNormalMatrix(S),(m===null||m.length0){const c=new jo(l.height/2);return c.fromEquirectangularTexture(r,o),t.set(o,c),o.addEventListener("dispose",i),e(c.texture,o.mapping)}else return null}}return o}function i(o){const a=o.target;a.removeEventListener("dispose",i);const l=t.get(a);l!==void 0&&(t.delete(a),l.dispose())}function s(){t=new WeakMap}return{get:n,dispose:s}}class Oa extends Ia{constructor(t=-1,e=1,n=1,i=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=n,this.bottom=i,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=t.view===null?null:Object.assign({},t.view),this}setViewOffset(t,e,n,i,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=n-t,o=n+t,a=i+e,l=i-e;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,o=s+c*this.view.width,a-=h*this.view.offsetY,l=a-h*this.view.height}this.projectionMatrix.makeOrthographic(s,o,a,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,this.view!==null&&(e.object.view=Object.assign({},this.view)),e}}const Bn=4,Ds=[.125,.215,.35,.446,.526,.582],mn=20,Dr=new Oa,Us=new zt;let Ur=null,Ir=0,Nr=0;const pn=(1+Math.sqrt(5))/2,Dn=1/pn,Is=[new R(1,1,1),new R(-1,1,1),new R(1,1,-1),new R(-1,1,-1),new R(0,pn,Dn),new R(0,pn,-Dn),new R(Dn,0,pn),new R(-Dn,0,pn),new R(pn,Dn,0),new R(-pn,Dn,0)];class Ns{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,n=.1,i=100){Ur=this._renderer.getRenderTarget(),Ir=this._renderer.getActiveCubeFace(),Nr=this._renderer.getActiveMipmapLevel(),this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(t,n,i,s),e>0&&this._blur(s,0,0,e),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Bs(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Os(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let t=0;t2?_:0,_,_),h.setRenderTarget(i),v&&h.render(g,a),h.render(t,a)}g.geometry.dispose(),g.material.dispose(),h.toneMapping=d,h.autoClear=u,t.background=m}_textureToCubeUV(t,e){const n=this._renderer,i=t.mapping===301||t.mapping===302;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=Bs()),this._cubemapMaterial.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Os());const s=i?this._cubemapMaterial:this._equirectMaterial,o=new Fe(this._lodPlanes[0],s),a=s.uniforms;a.envMap.value=t;const l=this._cubeSize;Bi(e,0,0,3*l,2*l),n.setRenderTarget(e),n.render(o,Dr)}_applyPMREM(t){const e=this._renderer,n=e.autoClear;e.autoClear=!1;for(let i=1;imn&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${mn}`);const f=[];let S=0;for(let w=0;w_-Bn?i-_+Bn:0),A=4*(this._cubeSize-b);Bi(e,C,A,3*b,2*b),l.setRenderTarget(e),l.render(u,Dr)}}function zh(r){const t=[],e=[],n=[];let i=r;const s=r-Bn+1+Ds.length;for(let o=0;or-Bn?l=Ds[o-r+Bn-1]:o===0&&(l=0),n.push(l);const c=1/(a-2),h=-c,u=1+c,d=[h,h,u,h,u,u,h,h,u,u,h,u],p=6,g=6,v=3,m=2,f=1,S=new Float32Array(v*g*p),_=new Float32Array(m*g*p),b=new Float32Array(f*g*p);for(let A=0;A2?0:-1,M=[w,U,0,w+2/3,U,0,w+2/3,U+1,0,w,U,0,w+2/3,U+1,0,w,U+1,0];S.set(M,v*g*A),_.set(d,m*g*A);const T=[A,A,A,A,A,A];b.set(T,f*g*A)}const C=new pe;C.setAttribute("position",new De(S,v)),C.setAttribute("uv",new De(_,m)),C.setAttribute("faceIndex",new De(b,f)),t.push(C),i>Bn&&i--}return{lodPlanes:t,sizeLods:e,sigmas:n}}function Fs(r,t,e){const n=new gn(r,t,e);return n.texture.mapping=306,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Bi(r,t,e,n,i){r.viewport.set(t,e,n,i),r.scissor.set(t,e,n,i)}function Gh(r,t,e){const n=new Float32Array(mn),i=new R(0,1,0);return new _n({name:"SphericalGaussianBlur",defines:{n:mn,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${r}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:es(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - uniform int samples; - uniform float weights[ n ]; - uniform bool latitudinal; - uniform float dTheta; - uniform float mipInt; - uniform vec3 poleAxis; - - #define ENVMAP_TYPE_CUBE_UV - #include - - vec3 getSample( float theta, vec3 axis ) { - - float cosTheta = cos( theta ); - // Rodrigues' axis-angle rotation - vec3 sampleDirection = vOutputDirection * cosTheta - + cross( axis, vOutputDirection ) * sin( theta ) - + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); - - return bilinearCubeUV( envMap, sampleDirection, mipInt ); - - } - - void main() { - - vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); - - if ( all( equal( axis, vec3( 0.0 ) ) ) ) { - - axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); - - } - - axis = normalize( axis ); - - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); - - for ( int i = 1; i < n; i++ ) { - - if ( i >= samples ) { - - break; - - } - - float theta = dTheta * float( i ); - gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); - gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); - - } - - } - `,blending:0,depthTest:!1,depthWrite:!1})}function Os(){return new _n({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:es(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - - #include - - void main() { - - vec3 outputDirection = normalize( vOutputDirection ); - vec2 uv = equirectUv( outputDirection ); - - gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); - - } - `,blending:0,depthTest:!1,depthWrite:!1})}function Bs(){return new _n({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:es(),fragmentShader:` - - precision mediump float; - precision mediump int; - - uniform float flipEnvMap; - - varying vec3 vOutputDirection; - - uniform samplerCube envMap; - - void main() { - - gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); - - } - `,blending:0,depthTest:!1,depthWrite:!1})}function es(){return` - - precision mediump float; - precision mediump int; - - attribute float faceIndex; - - varying vec3 vOutputDirection; - - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { - - uv = 2.0 * uv - 1.0; - - vec3 direction = vec3( uv, 1.0 ); - - if ( face == 0.0 ) { - - direction = direction.zyx; // ( 1, v, u ) pos x - - } else if ( face == 1.0 ) { - - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y - - } else if ( face == 2.0 ) { - - direction.x *= -1.0; // ( -u, v, 1 ) pos z - - } else if ( face == 3.0 ) { - - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x - - } else if ( face == 4.0 ) { - - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y - - } else if ( face == 5.0 ) { - - direction.z *= -1.0; // ( u, v, -1 ) neg z - - } - - return direction; - - } - - void main() { - - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); - - } - `}function Vh(r){let t=new WeakMap,e=null;function n(a){if(a&&a.isTexture){const l=a.mapping,c=l===303||l===304,h=l===301||l===302;if(c||h)if(a.isRenderTargetTexture&&a.needsPMREMUpdate===!0){a.needsPMREMUpdate=!1;let u=t.get(a);return e===null&&(e=new Ns(r)),u=c?e.fromEquirectangular(a,u):e.fromCubemap(a,u),t.set(a,u),u.texture}else{if(t.has(a))return t.get(a).texture;{const u=a.image;if(c&&u&&u.height>0||h&&u&&i(u)){e===null&&(e=new Ns(r));const d=c?e.fromEquirectangular(a):e.fromCubemap(a);return t.set(a,d),a.addEventListener("dispose",s),d.texture}else return null}}}return a}function i(a){let l=0;const c=6;for(let h=0;ht.maxTextureSize&&(T=Math.ceil(M/t.maxTextureSize),M=t.maxTextureSize);const z=new Float32Array(M*T*4*g),H=new wa(z,M,T,g);H.type=1015,H.needsUpdate=!0;const tt=U*4;for(let I=0;I0)return r;const i=t*e;let s=zs[i];if(s===void 0&&(s=new Float32Array(i),zs[i]=s),t!==0){n.toArray(s,0);for(let o=1,a=0;o!==t;++o)a+=e,r[o].toArray(s,a)}return s}function oe(r,t){if(r.length!==t.length)return!1;for(let e=0,n=r.length;e":" "} ${a}: ${e[o]}`)}return n.join(` -`)}function ku(r){const t=Kt.getPrimaries(Kt.workingColorSpace),e=Kt.getPrimaries(r);let n;switch(t===e?n="":t===tr&&e===Qi?n="LinearDisplayP3ToLinearSRGB":t===Qi&&e===tr&&(n="LinearSRGBToLinearDisplayP3"),r){case Je:case sr:return[n,"LinearTransferOETF"];case fe:case Zr:return[n,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",r),[n,"LinearTransferOETF"]}}function qs(r,t,e){const n=r.getShaderParameter(t,r.COMPILE_STATUS),i=r.getShaderInfoLog(t).trim();if(n&&i==="")return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const o=parseInt(s[1]);return e.toUpperCase()+` - -`+i+` - -`+Hu(r.getShaderSource(t),o)}else return i}function Wu(r,t){const e=ku(t);return`vec4 ${r}( vec4 value ) { return ${e[0]}( ${e[1]}( value ) ); }`}function Xu(r,t){let e;switch(t){case 1:e="Linear";break;case 2:e="Reinhard";break;case 3:e="OptimizedCineon";break;case 4:e="ACESFilmic";break;case 6:e="AgX";break;case 5:e="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),e="Linear"}return"vec3 "+r+"( vec3 color ) { return "+e+"ToneMapping( color ); }"}function qu(r){return[r.extensionDerivatives||r.envMapCubeUVHeight||r.bumpMap||r.normalMapTangentSpace||r.clearcoatNormalMap||r.flatShading||r.shaderID==="physical"?"#extension GL_OES_standard_derivatives : enable":"",(r.extensionFragDepth||r.logarithmicDepthBuffer)&&r.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",r.extensionDrawBuffers&&r.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(r.extensionShaderTextureLOD||r.envMap||r.transmission)&&r.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(zn).join(` -`)}function Yu(r){return[r.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":""].filter(zn).join(` -`)}function Ku(r){const t=[];for(const e in r){const n=r[e];n!==!1&&t.push("#define "+e+" "+n)}return t.join(` -`)}function Ju(r,t){const e={},n=r.getProgramParameter(t,r.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function Kr(r){return r.replace(ju,$u)}const Zu=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function $u(r,t){let e=Dt[t];if(e===void 0){const n=Zu.get(t);if(n!==void 0)e=Dt[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,n);else throw new Error("Can not resolve #include <"+t+">")}return Kr(e)}const Qu=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Js(r){return r.replace(Qu,td)}function td(r,t,e,n){let i="";for(let s=parseInt(t);s0&&(f+=` -`),S=[p,"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,v].filter(zn).join(` -`),S.length>0&&(S+=` -`)):(f=[js(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,v,e.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",e.batching?"#define USE_BATCHING":"",e.instancing?"#define USE_INSTANCING":"",e.instancingColor?"#define USE_INSTANCING_COLOR":"",e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+h:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.displacementMap?"#define USE_DISPLACEMENTMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.mapUv?"#define MAP_UV "+e.mapUv:"",e.alphaMapUv?"#define ALPHAMAP_UV "+e.alphaMapUv:"",e.lightMapUv?"#define LIGHTMAP_UV "+e.lightMapUv:"",e.aoMapUv?"#define AOMAP_UV "+e.aoMapUv:"",e.emissiveMapUv?"#define EMISSIVEMAP_UV "+e.emissiveMapUv:"",e.bumpMapUv?"#define BUMPMAP_UV "+e.bumpMapUv:"",e.normalMapUv?"#define NORMALMAP_UV "+e.normalMapUv:"",e.displacementMapUv?"#define DISPLACEMENTMAP_UV "+e.displacementMapUv:"",e.metalnessMapUv?"#define METALNESSMAP_UV "+e.metalnessMapUv:"",e.roughnessMapUv?"#define ROUGHNESSMAP_UV "+e.roughnessMapUv:"",e.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+e.anisotropyMapUv:"",e.clearcoatMapUv?"#define CLEARCOATMAP_UV "+e.clearcoatMapUv:"",e.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+e.clearcoatNormalMapUv:"",e.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+e.clearcoatRoughnessMapUv:"",e.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+e.iridescenceMapUv:"",e.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+e.iridescenceThicknessMapUv:"",e.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+e.sheenColorMapUv:"",e.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+e.sheenRoughnessMapUv:"",e.specularMapUv?"#define SPECULARMAP_UV "+e.specularMapUv:"",e.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+e.specularColorMapUv:"",e.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+e.specularIntensityMapUv:"",e.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+e.transmissionMapUv:"",e.thicknessMapUv?"#define THICKNESSMAP_UV "+e.thicknessMapUv:"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexColors?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.flatShading?"#define FLAT_SHADED":"",e.skinning?"#define USE_SKINNING":"",e.morphTargets?"#define USE_MORPHTARGETS":"",e.morphNormals&&e.flatShading===!1?"#define USE_MORPHNORMALS":"",e.morphColors&&e.isWebGL2?"#define USE_MORPHCOLORS":"",e.morphTargetsCount>0&&e.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",e.morphTargetsCount>0&&e.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+e.morphTextureStride:"",e.morphTargetsCount>0&&e.isWebGL2?"#define MORPHTARGETS_COUNT "+e.morphTargetsCount:"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.sizeAttenuation?"#define USE_SIZEATTENUATION":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.useLegacyLights?"#define LEGACY_LIGHTS":"",e.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",e.logarithmicDepthBuffer&&e.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` -`].filter(zn).join(` -`),S=[p,js(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,v,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.matcap?"#define USE_MATCAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+c:"",e.envMap?"#define "+h:"",e.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoat?"#define USE_CLEARCOAT":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.iridescence?"#define USE_IRIDESCENCE":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaTest?"#define USE_ALPHATEST":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.sheen?"#define USE_SHEEN":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexColors||e.instancingColor?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.gradientMap?"#define USE_GRADIENTMAP":"",e.flatShading?"#define FLAT_SHADED":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.useLegacyLights?"#define LEGACY_LIGHTS":"",e.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",e.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",e.logarithmicDepthBuffer&&e.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",e.toneMapping!==0?"#define TONE_MAPPING":"",e.toneMapping!==0?Dt.tonemapping_pars_fragment:"",e.toneMapping!==0?Xu("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.opaque?"#define OPAQUE":"",Dt.colorspace_pars_fragment,Wu("linearToOutputTexel",e.outputColorSpace),e.useDepthPacking?"#define DEPTH_PACKING "+e.depthPacking:"",` -`].filter(zn).join(` -`)),o=Kr(o),o=Ys(o,e),o=Ks(o,e),a=Kr(a),a=Ys(a,e),a=Ks(a,e),o=Js(o),a=Js(a),e.isWebGL2&&e.isRawShaderMaterial!==!0&&(_=`#version 300 es -`,f=[g,"precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join(` -`)+` -`+f,S=["precision mediump sampler2DArray;","#define varying in",e.glslVersion===ps?"":"layout(location = 0) out highp vec4 pc_fragColor;",e.glslVersion===ps?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` -`)+` -`+S);const b=_+f+o,C=_+S+a,A=Xs(i,i.VERTEX_SHADER,b),w=Xs(i,i.FRAGMENT_SHADER,C);i.attachShader(m,A),i.attachShader(m,w),e.index0AttributeName!==void 0?i.bindAttribLocation(m,0,e.index0AttributeName):e.morphTargets===!0&&i.bindAttribLocation(m,0,"position"),i.linkProgram(m);function U(H){if(r.debug.checkShaderErrors){const tt=i.getProgramInfoLog(m).trim(),P=i.getShaderInfoLog(A).trim(),I=i.getShaderInfoLog(w).trim();let k=!0,q=!0;if(i.getProgramParameter(m,i.LINK_STATUS)===!1)if(k=!1,typeof r.debug.onShaderError=="function")r.debug.onShaderError(i,m,A,w);else{const X=qs(i,A,"vertex"),W=qs(i,w,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(m,i.VALIDATE_STATUS)+` - -Program Info Log: `+tt+` -`+X+` -`+W)}else tt!==""?console.warn("THREE.WebGLProgram: Program Info Log:",tt):(P===""||I==="")&&(q=!1);q&&(H.diagnostics={runnable:k,programLog:tt,vertexShader:{log:P,prefix:f},fragmentShader:{log:I,prefix:S}})}i.deleteShader(A),i.deleteShader(w),M=new Zi(i,m),T=Ju(i,m)}let M;this.getUniforms=function(){return M===void 0&&U(this),M};let T;this.getAttributes=function(){return T===void 0&&U(this),T};let z=e.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return z===!1&&(z=i.getProgramParameter(m,Gu)),z},this.destroy=function(){n.releaseStatesOfProgram(this),i.deleteProgram(m),this.program=void 0},this.type=e.shaderType,this.name=e.shaderName,this.id=Vu++,this.cacheKey=t,this.usedTimes=1,this.program=m,this.vertexShader=A,this.fragmentShader=w,this}let od=0;class ld{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){const e=t.vertexShader,n=t.fragmentShader,i=this._getShaderStage(e),s=this._getShaderStage(n),o=this._getShaderCacheForMaterial(t);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(t){const e=this.materialCache.get(t);for(const n of e)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(t),this}getVertexShaderID(t){return this._getShaderStage(t.vertexShader).id}getFragmentShaderID(t){return this._getShaderStage(t.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){const e=this.materialCache;let n=e.get(t);return n===void 0&&(n=new Set,e.set(t,n)),n}_getShaderStage(t){const e=this.shaderCache;let n=e.get(t);return n===void 0&&(n=new cd(t),e.set(t,n)),n}}class cd{constructor(t){this.id=od++,this.code=t,this.usedTimes=0}}function hd(r,t,e,n,i,s,o){const a=new Ra,l=new ld,c=[],h=i.isWebGL2,u=i.logarithmicDepthBuffer,d=i.vertexTextures;let p=i.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(M){return M===0?"uv":`uv${M}`}function m(M,T,z,H,tt){const P=H.fog,I=tt.geometry,k=M.isMeshStandardMaterial?H.environment:null,q=(M.isMeshStandardMaterial?e:t).get(M.envMap||k),X=q&&q.mapping===306?q.image.height:null,W=g[M.type];M.precision!==null&&(p=i.getMaxPrecision(M.precision),p!==M.precision&&console.warn("THREE.WebGLProgram.getParameters:",M.precision,"not supported, using",p,"instead."));const j=I.morphAttributes.position||I.morphAttributes.normal||I.morphAttributes.color,Q=j!==void 0?j.length:0;let lt=0;I.morphAttributes.position!==void 0&&(lt=1),I.morphAttributes.normal!==void 0&&(lt=2),I.morphAttributes.color!==void 0&&(lt=3);let V,Y,at,gt;if(W){const Me=ze[W];V=Me.vertexShader,Y=Me.fragmentShader}else V=M.vertexShader,Y=M.fragmentShader,l.update(M),at=l.getVertexShaderID(M),gt=l.getFragmentShaderID(M);const mt=r.getRenderTarget(),Rt=tt.isInstancedMesh===!0,Lt=tt.isBatchedMesh===!0,yt=!!M.map,Ht=!!M.matcap,N=!!q,xe=!!M.aoMap,vt=!!M.lightMap,At=!!M.bumpMap,dt=!!M.normalMap,te=!!M.displacementMap,Ut=!!M.emissiveMap,E=!!M.metalnessMap,x=!!M.roughnessMap,O=M.anisotropy>0,Z=M.clearcoat>0,J=M.iridescence>0,$=M.sheen>0,ft=M.transmission>0,st=O&&!!M.anisotropyMap,ht=Z&&!!M.clearcoatMap,St=Z&&!!M.clearcoatNormalMap,It=Z&&!!M.clearcoatRoughnessMap,K=J&&!!M.iridescenceMap,Xt=J&&!!M.iridescenceThicknessMap,Gt=$&&!!M.sheenColorMap,bt=$&&!!M.sheenRoughnessMap,_t=!!M.specularMap,ut=!!M.specularColorMap,Pt=!!M.specularIntensityMap,Wt=ft&&!!M.transmissionMap,ne=ft&&!!M.thicknessMap,Ft=!!M.gradientMap,et=!!M.alphaMap,L=M.alphaTest>0,it=!!M.alphaHash,rt=!!M.extensions,Et=!!I.attributes.uv1,xt=!!I.attributes.uv2,jt=!!I.attributes.uv3;let Zt=0;return M.toneMapped&&(mt===null||mt.isXRRenderTarget===!0)&&(Zt=r.toneMapping),{isWebGL2:h,shaderID:W,shaderType:M.type,shaderName:M.name,vertexShader:V,fragmentShader:Y,defines:M.defines,customVertexShaderID:at,customFragmentShaderID:gt,isRawShaderMaterial:M.isRawShaderMaterial===!0,glslVersion:M.glslVersion,precision:p,batching:Lt,instancing:Rt,instancingColor:Rt&&tt.instanceColor!==null,supportsVertexTextures:d,outputColorSpace:mt===null?r.outputColorSpace:mt.isXRRenderTarget===!0?mt.texture.colorSpace:Je,map:yt,matcap:Ht,envMap:N,envMapMode:N&&q.mapping,envMapCubeUVHeight:X,aoMap:xe,lightMap:vt,bumpMap:At,normalMap:dt,displacementMap:d&&te,emissiveMap:Ut,normalMapObjectSpace:dt&&M.normalMapType===1,normalMapTangentSpace:dt&&M.normalMapType===0,metalnessMap:E,roughnessMap:x,anisotropy:O,anisotropyMap:st,clearcoat:Z,clearcoatMap:ht,clearcoatNormalMap:St,clearcoatRoughnessMap:It,iridescence:J,iridescenceMap:K,iridescenceThicknessMap:Xt,sheen:$,sheenColorMap:Gt,sheenRoughnessMap:bt,specularMap:_t,specularColorMap:ut,specularIntensityMap:Pt,transmission:ft,transmissionMap:Wt,thicknessMap:ne,gradientMap:Ft,opaque:M.transparent===!1&&M.blending===1,alphaMap:et,alphaTest:L,alphaHash:it,combine:M.combine,mapUv:yt&&v(M.map.channel),aoMapUv:xe&&v(M.aoMap.channel),lightMapUv:vt&&v(M.lightMap.channel),bumpMapUv:At&&v(M.bumpMap.channel),normalMapUv:dt&&v(M.normalMap.channel),displacementMapUv:te&&v(M.displacementMap.channel),emissiveMapUv:Ut&&v(M.emissiveMap.channel),metalnessMapUv:E&&v(M.metalnessMap.channel),roughnessMapUv:x&&v(M.roughnessMap.channel),anisotropyMapUv:st&&v(M.anisotropyMap.channel),clearcoatMapUv:ht&&v(M.clearcoatMap.channel),clearcoatNormalMapUv:St&&v(M.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:It&&v(M.clearcoatRoughnessMap.channel),iridescenceMapUv:K&&v(M.iridescenceMap.channel),iridescenceThicknessMapUv:Xt&&v(M.iridescenceThicknessMap.channel),sheenColorMapUv:Gt&&v(M.sheenColorMap.channel),sheenRoughnessMapUv:bt&&v(M.sheenRoughnessMap.channel),specularMapUv:_t&&v(M.specularMap.channel),specularColorMapUv:ut&&v(M.specularColorMap.channel),specularIntensityMapUv:Pt&&v(M.specularIntensityMap.channel),transmissionMapUv:Wt&&v(M.transmissionMap.channel),thicknessMapUv:ne&&v(M.thicknessMap.channel),alphaMapUv:et&&v(M.alphaMap.channel),vertexTangents:!!I.attributes.tangent&&(dt||O),vertexColors:M.vertexColors,vertexAlphas:M.vertexColors===!0&&!!I.attributes.color&&I.attributes.color.itemSize===4,vertexUv1s:Et,vertexUv2s:xt,vertexUv3s:jt,pointsUvs:tt.isPoints===!0&&!!I.attributes.uv&&(yt||et),fog:!!P,useFog:M.fog===!0,fogExp2:P&&P.isFogExp2,flatShading:M.flatShading===!0,sizeAttenuation:M.sizeAttenuation===!0,logarithmicDepthBuffer:u,skinning:tt.isSkinnedMesh===!0,morphTargets:I.morphAttributes.position!==void 0,morphNormals:I.morphAttributes.normal!==void 0,morphColors:I.morphAttributes.color!==void 0,morphTargetsCount:Q,morphTextureStride:lt,numDirLights:T.directional.length,numPointLights:T.point.length,numSpotLights:T.spot.length,numSpotLightMaps:T.spotLightMap.length,numRectAreaLights:T.rectArea.length,numHemiLights:T.hemi.length,numDirLightShadows:T.directionalShadowMap.length,numPointLightShadows:T.pointShadowMap.length,numSpotLightShadows:T.spotShadowMap.length,numSpotLightShadowsWithMaps:T.numSpotLightShadowsWithMaps,numLightProbes:T.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:M.dithering,shadowMapEnabled:r.shadowMap.enabled&&z.length>0,shadowMapType:r.shadowMap.type,toneMapping:Zt,useLegacyLights:r._useLegacyLights,decodeVideoTexture:yt&&M.map.isVideoTexture===!0&&Kt.getTransfer(M.map.colorSpace)===Qt,premultipliedAlpha:M.premultipliedAlpha,doubleSided:M.side===2,flipSided:M.side===1,useDepthPacking:M.depthPacking>=0,depthPacking:M.depthPacking||0,index0AttributeName:M.index0AttributeName,extensionDerivatives:rt&&M.extensions.derivatives===!0,extensionFragDepth:rt&&M.extensions.fragDepth===!0,extensionDrawBuffers:rt&&M.extensions.drawBuffers===!0,extensionShaderTextureLOD:rt&&M.extensions.shaderTextureLOD===!0,extensionClipCullDistance:rt&&M.extensions.clipCullDistance&&n.has("WEBGL_clip_cull_distance"),rendererExtensionFragDepth:h||n.has("EXT_frag_depth"),rendererExtensionDrawBuffers:h||n.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:h||n.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:M.customProgramCacheKey()}}function f(M){const T=[];if(M.shaderID?T.push(M.shaderID):(T.push(M.customVertexShaderID),T.push(M.customFragmentShaderID)),M.defines!==void 0)for(const z in M.defines)T.push(z),T.push(M.defines[z]);return M.isRawShaderMaterial===!1&&(S(T,M),_(T,M),T.push(r.outputColorSpace)),T.push(M.customProgramCacheKey),T.join()}function S(M,T){M.push(T.precision),M.push(T.outputColorSpace),M.push(T.envMapMode),M.push(T.envMapCubeUVHeight),M.push(T.mapUv),M.push(T.alphaMapUv),M.push(T.lightMapUv),M.push(T.aoMapUv),M.push(T.bumpMapUv),M.push(T.normalMapUv),M.push(T.displacementMapUv),M.push(T.emissiveMapUv),M.push(T.metalnessMapUv),M.push(T.roughnessMapUv),M.push(T.anisotropyMapUv),M.push(T.clearcoatMapUv),M.push(T.clearcoatNormalMapUv),M.push(T.clearcoatRoughnessMapUv),M.push(T.iridescenceMapUv),M.push(T.iridescenceThicknessMapUv),M.push(T.sheenColorMapUv),M.push(T.sheenRoughnessMapUv),M.push(T.specularMapUv),M.push(T.specularColorMapUv),M.push(T.specularIntensityMapUv),M.push(T.transmissionMapUv),M.push(T.thicknessMapUv),M.push(T.combine),M.push(T.fogExp2),M.push(T.sizeAttenuation),M.push(T.morphTargetsCount),M.push(T.morphAttributeCount),M.push(T.numDirLights),M.push(T.numPointLights),M.push(T.numSpotLights),M.push(T.numSpotLightMaps),M.push(T.numHemiLights),M.push(T.numRectAreaLights),M.push(T.numDirLightShadows),M.push(T.numPointLightShadows),M.push(T.numSpotLightShadows),M.push(T.numSpotLightShadowsWithMaps),M.push(T.numLightProbes),M.push(T.shadowMapType),M.push(T.toneMapping),M.push(T.numClippingPlanes),M.push(T.numClipIntersection),M.push(T.depthPacking)}function _(M,T){a.disableAll(),T.isWebGL2&&a.enable(0),T.supportsVertexTextures&&a.enable(1),T.instancing&&a.enable(2),T.instancingColor&&a.enable(3),T.matcap&&a.enable(4),T.envMap&&a.enable(5),T.normalMapObjectSpace&&a.enable(6),T.normalMapTangentSpace&&a.enable(7),T.clearcoat&&a.enable(8),T.iridescence&&a.enable(9),T.alphaTest&&a.enable(10),T.vertexColors&&a.enable(11),T.vertexAlphas&&a.enable(12),T.vertexUv1s&&a.enable(13),T.vertexUv2s&&a.enable(14),T.vertexUv3s&&a.enable(15),T.vertexTangents&&a.enable(16),T.anisotropy&&a.enable(17),T.alphaHash&&a.enable(18),T.batching&&a.enable(19),M.push(a.mask),a.disableAll(),T.fog&&a.enable(0),T.useFog&&a.enable(1),T.flatShading&&a.enable(2),T.logarithmicDepthBuffer&&a.enable(3),T.skinning&&a.enable(4),T.morphTargets&&a.enable(5),T.morphNormals&&a.enable(6),T.morphColors&&a.enable(7),T.premultipliedAlpha&&a.enable(8),T.shadowMapEnabled&&a.enable(9),T.useLegacyLights&&a.enable(10),T.doubleSided&&a.enable(11),T.flipSided&&a.enable(12),T.useDepthPacking&&a.enable(13),T.dithering&&a.enable(14),T.transmission&&a.enable(15),T.sheen&&a.enable(16),T.opaque&&a.enable(17),T.pointsUvs&&a.enable(18),T.decodeVideoTexture&&a.enable(19),M.push(a.mask)}function b(M){const T=g[M.type];let z;if(T){const H=ze[T];z=qo.clone(H.uniforms)}else z=M.uniforms;return z}function C(M,T){let z;for(let H=0,tt=c.length;H0?n.push(f):p.transparent===!0?i.push(f):e.push(f)}function l(u,d,p,g,v,m){const f=o(u,d,p,g,v,m);p.transmission>0?n.unshift(f):p.transparent===!0?i.unshift(f):e.unshift(f)}function c(u,d){e.length>1&&e.sort(u||dd),n.length>1&&n.sort(d||Zs),i.length>1&&i.sort(d||Zs)}function h(){for(let u=t,d=r.length;u=s.length?(o=new $s,s.push(o)):o=s[i],o}function e(){r=new WeakMap}return{get:t,dispose:e}}function pd(){const r={};return{get:function(t){if(r[t.id]!==void 0)return r[t.id];let e;switch(t.type){case"DirectionalLight":e={direction:new R,color:new zt};break;case"SpotLight":e={position:new R,direction:new R,color:new zt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":e={position:new R,color:new zt,distance:0,decay:0};break;case"HemisphereLight":e={direction:new R,skyColor:new zt,groundColor:new zt};break;case"RectAreaLight":e={color:new zt,position:new R,halfWidth:new R,halfHeight:new R};break}return r[t.id]=e,e}}}function md(){const r={};return{get:function(t){if(r[t.id]!==void 0)return r[t.id];let e;switch(t.type){case"DirectionalLight":e={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ct};break;case"SpotLight":e={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ct};break;case"PointLight":e={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ct,shadowCameraNear:1,shadowCameraFar:1e3};break}return r[t.id]=e,e}}}let gd=0;function _d(r,t){return(t.castShadow?2:0)-(r.castShadow?2:0)+(t.map?1:0)-(r.map?1:0)}function vd(r,t){const e=new pd,n=md(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let h=0;h<9;h++)i.probe.push(new R);const s=new R,o=new Vt,a=new Vt;function l(h,u){let d=0,p=0,g=0;for(let H=0;H<9;H++)i.probe[H].set(0,0,0);let v=0,m=0,f=0,S=0,_=0,b=0,C=0,A=0,w=0,U=0,M=0;h.sort(_d);const T=u===!0?Math.PI:1;for(let H=0,tt=h.length;H0&&(t.isWebGL2?r.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=nt.LTC_FLOAT_1,i.rectAreaLTC2=nt.LTC_FLOAT_2):(i.rectAreaLTC1=nt.LTC_HALF_1,i.rectAreaLTC2=nt.LTC_HALF_2):r.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=nt.LTC_FLOAT_1,i.rectAreaLTC2=nt.LTC_FLOAT_2):r.has("OES_texture_half_float_linear")===!0?(i.rectAreaLTC1=nt.LTC_HALF_1,i.rectAreaLTC2=nt.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),i.ambient[0]=d,i.ambient[1]=p,i.ambient[2]=g;const z=i.hash;(z.directionalLength!==v||z.pointLength!==m||z.spotLength!==f||z.rectAreaLength!==S||z.hemiLength!==_||z.numDirectionalShadows!==b||z.numPointShadows!==C||z.numSpotShadows!==A||z.numSpotMaps!==w||z.numLightProbes!==M)&&(i.directional.length=v,i.spot.length=f,i.rectArea.length=S,i.point.length=m,i.hemi.length=_,i.directionalShadow.length=b,i.directionalShadowMap.length=b,i.pointShadow.length=C,i.pointShadowMap.length=C,i.spotShadow.length=A,i.spotShadowMap.length=A,i.directionalShadowMatrix.length=b,i.pointShadowMatrix.length=C,i.spotLightMatrix.length=A+w-U,i.spotLightMap.length=w,i.numSpotLightShadowsWithMaps=U,i.numLightProbes=M,z.directionalLength=v,z.pointLength=m,z.spotLength=f,z.rectAreaLength=S,z.hemiLength=_,z.numDirectionalShadows=b,z.numPointShadows=C,z.numSpotShadows=A,z.numSpotMaps=w,z.numLightProbes=M,i.version=gd++)}function c(h,u){let d=0,p=0,g=0,v=0,m=0;const f=u.matrixWorldInverse;for(let S=0,_=h.length;S<_;S++){const b=h[S];if(b.isDirectionalLight){const C=i.directional[d];C.direction.setFromMatrixPosition(b.matrixWorld),s.setFromMatrixPosition(b.target.matrixWorld),C.direction.sub(s),C.direction.transformDirection(f),d++}else if(b.isSpotLight){const C=i.spot[g];C.position.setFromMatrixPosition(b.matrixWorld),C.position.applyMatrix4(f),C.direction.setFromMatrixPosition(b.matrixWorld),s.setFromMatrixPosition(b.target.matrixWorld),C.direction.sub(s),C.direction.transformDirection(f),g++}else if(b.isRectAreaLight){const C=i.rectArea[v];C.position.setFromMatrixPosition(b.matrixWorld),C.position.applyMatrix4(f),a.identity(),o.copy(b.matrixWorld),o.premultiply(f),a.extractRotation(o),C.halfWidth.set(b.width*.5,0,0),C.halfHeight.set(0,b.height*.5,0),C.halfWidth.applyMatrix4(a),C.halfHeight.applyMatrix4(a),v++}else if(b.isPointLight){const C=i.point[p];C.position.setFromMatrixPosition(b.matrixWorld),C.position.applyMatrix4(f),p++}else if(b.isHemisphereLight){const C=i.hemi[m];C.direction.setFromMatrixPosition(b.matrixWorld),C.direction.transformDirection(f),m++}}}return{setup:l,setupView:c,state:i}}function Qs(r,t){const e=new vd(r,t),n=[],i=[];function s(){n.length=0,i.length=0}function o(u){n.push(u)}function a(u){i.push(u)}function l(u){e.setup(n,u)}function c(u){e.setupView(n,u)}return{init:s,state:{lightsArray:n,shadowsArray:i,lights:e},setupLights:l,setupLightsView:c,pushLight:o,pushShadow:a}}function xd(r,t){let e=new WeakMap;function n(s,o=0){const a=e.get(s);let l;return a===void 0?(l=new Qs(r,t),e.set(s,[l])):o>=a.length?(l=new Qs(r,t),a.push(l)):l=a[o],l}function i(){e=new WeakMap}return{get:n,dispose:i}}class Md extends an{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class Sd extends an{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}const yd=`void main() { - gl_Position = vec4( position, 1.0 ); -}`,Ed=`uniform sampler2D shadow_pass; -uniform vec2 resolution; -uniform float radius; -#include -void main() { - const float samples = float( VSM_SAMPLES ); - float mean = 0.0; - float squared_mean = 0.0; - float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); - float uvStart = samples <= 1.0 ? 0.0 : - 1.0; - for ( float i = 0.0; i < samples; i ++ ) { - float uvOffset = uvStart + i * uvStride; - #ifdef HORIZONTAL_PASS - vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); - mean += distribution.x; - squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; - #else - float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); - mean += depth; - squared_mean += depth * depth; - #endif - } - mean = mean / samples; - squared_mean = squared_mean / samples; - float std_dev = sqrt( squared_mean - mean * mean ); - gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function Td(r,t,e){let n=new Qr;const i=new ct,s=new ct,o=new Jt,a=new Md({depthPacking:3201}),l=new Sd,c={},h=e.maxTextureSize,u={0:1,1:0,2:2},d=new _n({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ct},radius:{value:4}},vertexShader:yd,fragmentShader:Ed}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const g=new pe;g.setAttribute("position",new De(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Fe(g,d),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let f=this.type;this.render=function(A,w,U){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||A.length===0)return;const M=r.getRenderTarget(),T=r.getActiveCubeFace(),z=r.getActiveMipmapLevel(),H=r.state;H.setBlending(0),H.buffers.color.setClear(1,1,1,1),H.buffers.depth.setTest(!0),H.setScissorTest(!1);const tt=f!==3&&this.type===3,P=f===3&&this.type!==3;for(let I=0,k=A.length;Ih||i.y>h)&&(i.x>h&&(s.x=Math.floor(h/W.x),i.x=s.x*W.x,X.mapSize.x=s.x),i.y>h&&(s.y=Math.floor(h/W.y),i.y=s.y*W.y,X.mapSize.y=s.y)),X.map===null||tt===!0||P===!0){const Q=this.type!==3?{minFilter:1003,magFilter:1003}:{};X.map!==null&&X.map.dispose(),X.map=new gn(i.x,i.y,Q),X.map.texture.name=q.name+".shadowMap",X.camera.updateProjectionMatrix()}r.setRenderTarget(X.map),r.clear();const j=X.getViewportCount();for(let Q=0;Q0||w.map&&w.alphaTest>0){const H=T.uuid,tt=w.uuid;let P=c[H];P===void 0&&(P={},c[H]=P);let I=P[tt];I===void 0&&(I=T.clone(),P[tt]=I,w.addEventListener("dispose",C)),T=I}if(T.visible=w.visible,T.wireframe=w.wireframe,M===3?T.side=w.shadowSide!==null?w.shadowSide:w.side:T.side=w.shadowSide!==null?w.shadowSide:u[w.side],T.alphaMap=w.alphaMap,T.alphaTest=w.alphaTest,T.map=w.map,T.clipShadows=w.clipShadows,T.clippingPlanes=w.clippingPlanes,T.clipIntersection=w.clipIntersection,T.displacementMap=w.displacementMap,T.displacementScale=w.displacementScale,T.displacementBias=w.displacementBias,T.wireframeLinewidth=w.wireframeLinewidth,T.linewidth=w.linewidth,U.isPointLight===!0&&T.isMeshDistanceMaterial===!0){const H=r.properties.get(T);H.light=U}return T}function b(A,w,U,M,T){if(A.visible===!1)return;if(A.layers.test(w.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&T===3)&&(!A.frustumCulled||n.intersectsObject(A))){A.modelViewMatrix.multiplyMatrices(U.matrixWorldInverse,A.matrixWorld);const tt=t.update(A),P=A.material;if(Array.isArray(P)){const I=tt.groups;for(let k=0,q=I.length;k=1):j.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(j)[1]),X=W>=2);let Q=null,lt={};const V=r.getParameter(r.SCISSOR_BOX),Y=r.getParameter(r.VIEWPORT),at=new Jt().fromArray(V),gt=new Jt().fromArray(Y);function mt(L,it,rt,Et){const xt=new Uint8Array(4),jt=r.createTexture();r.bindTexture(L,jt),r.texParameteri(L,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(L,r.TEXTURE_MAG_FILTER,r.NEAREST);for(let Zt=0;Zt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),h=new WeakMap;let u;const d=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(E,x){return p?new OffscreenCanvas(E,x):ui("canvas")}function v(E,x,O,Z){let J=1;if((E.width>Z||E.height>Z)&&(J=Z/Math.max(E.width,E.height)),J<1||x===!0)if(typeof HTMLImageElement<"u"&&E instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&E instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&E instanceof ImageBitmap){const $=x?er:Math.floor,ft=$(J*E.width),st=$(J*E.height);u===void 0&&(u=g(ft,st));const ht=O?g(ft,st):u;return ht.width=ft,ht.height=st,ht.getContext("2d").drawImage(E,0,0,ft,st),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+E.width+"x"+E.height+") to ("+ft+"x"+st+")."),ht}else return"data"in E&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+E.width+"x"+E.height+")."),E;return E}function m(E){return Yr(E.width)&&Yr(E.height)}function f(E){return a?!1:E.wrapS!==1001||E.wrapT!==1001||E.minFilter!==1003&&E.minFilter!==1006}function S(E,x){return E.generateMipmaps&&x&&E.minFilter!==1003&&E.minFilter!==1006}function _(E){r.generateMipmap(E)}function b(E,x,O,Z,J=!1){if(a===!1)return x;if(E!==null){if(r[E]!==void 0)return r[E];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+E+"'")}let $=x;if(x===r.RED&&(O===r.FLOAT&&($=r.R32F),O===r.HALF_FLOAT&&($=r.R16F),O===r.UNSIGNED_BYTE&&($=r.R8)),x===r.RED_INTEGER&&(O===r.UNSIGNED_BYTE&&($=r.R8UI),O===r.UNSIGNED_SHORT&&($=r.R16UI),O===r.UNSIGNED_INT&&($=r.R32UI),O===r.BYTE&&($=r.R8I),O===r.SHORT&&($=r.R16I),O===r.INT&&($=r.R32I)),x===r.RG&&(O===r.FLOAT&&($=r.RG32F),O===r.HALF_FLOAT&&($=r.RG16F),O===r.UNSIGNED_BYTE&&($=r.RG8)),x===r.RGBA){const ft=J?$i:Kt.getTransfer(Z);O===r.FLOAT&&($=r.RGBA32F),O===r.HALF_FLOAT&&($=r.RGBA16F),O===r.UNSIGNED_BYTE&&($=ft===Qt?r.SRGB8_ALPHA8:r.RGBA8),O===r.UNSIGNED_SHORT_4_4_4_4&&($=r.RGBA4),O===r.UNSIGNED_SHORT_5_5_5_1&&($=r.RGB5_A1)}return($===r.R16F||$===r.R32F||$===r.RG16F||$===r.RG32F||$===r.RGBA16F||$===r.RGBA32F)&&t.get("EXT_color_buffer_float"),$}function C(E,x,O){return S(E,O)===!0||E.isFramebufferTexture&&E.minFilter!==1003&&E.minFilter!==1006?Math.log2(Math.max(x.width,x.height))+1:E.mipmaps!==void 0&&E.mipmaps.length>0?E.mipmaps.length:E.isCompressedTexture&&Array.isArray(E.image)?x.mipmaps.length:1}function A(E){return E===1003||E===1004||E===1005?r.NEAREST:r.LINEAR}function w(E){const x=E.target;x.removeEventListener("dispose",w),M(x),x.isVideoTexture&&h.delete(x)}function U(E){const x=E.target;x.removeEventListener("dispose",U),z(x)}function M(E){const x=n.get(E);if(x.__webglInit===void 0)return;const O=E.source,Z=d.get(O);if(Z){const J=Z[x.__cacheKey];J.usedTimes--,J.usedTimes===0&&T(E),Object.keys(Z).length===0&&d.delete(O)}n.remove(E)}function T(E){const x=n.get(E);r.deleteTexture(x.__webglTexture);const O=E.source,Z=d.get(O);delete Z[x.__cacheKey],o.memory.textures--}function z(E){const x=E.texture,O=n.get(E),Z=n.get(x);if(Z.__webglTexture!==void 0&&(r.deleteTexture(Z.__webglTexture),o.memory.textures--),E.depthTexture&&E.depthTexture.dispose(),E.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(O.__webglFramebuffer[J]))for(let $=0;$=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+E+" texture units while this GPU supports only "+i.maxTextures),H+=1,E}function I(E){const x=[];return x.push(E.wrapS),x.push(E.wrapT),x.push(E.wrapR||0),x.push(E.magFilter),x.push(E.minFilter),x.push(E.anisotropy),x.push(E.internalFormat),x.push(E.format),x.push(E.type),x.push(E.generateMipmaps),x.push(E.premultiplyAlpha),x.push(E.flipY),x.push(E.unpackAlignment),x.push(E.colorSpace),x.join()}function k(E,x){const O=n.get(E);if(E.isVideoTexture&&te(E),E.isRenderTargetTexture===!1&&E.version>0&&O.__version!==E.version){const Z=E.image;if(Z===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(Z.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{at(O,E,x);return}}e.bindTexture(r.TEXTURE_2D,O.__webglTexture,r.TEXTURE0+x)}function q(E,x){const O=n.get(E);if(E.version>0&&O.__version!==E.version){at(O,E,x);return}e.bindTexture(r.TEXTURE_2D_ARRAY,O.__webglTexture,r.TEXTURE0+x)}function X(E,x){const O=n.get(E);if(E.version>0&&O.__version!==E.version){at(O,E,x);return}e.bindTexture(r.TEXTURE_3D,O.__webglTexture,r.TEXTURE0+x)}function W(E,x){const O=n.get(E);if(E.version>0&&O.__version!==E.version){gt(O,E,x);return}e.bindTexture(r.TEXTURE_CUBE_MAP,O.__webglTexture,r.TEXTURE0+x)}const j={1e3:r.REPEAT,1001:r.CLAMP_TO_EDGE,1002:r.MIRRORED_REPEAT},Q={1003:r.NEAREST,1004:r.NEAREST_MIPMAP_NEAREST,1005:r.NEAREST_MIPMAP_LINEAR,1006:r.LINEAR,1007:r.LINEAR_MIPMAP_NEAREST,1008:r.LINEAR_MIPMAP_LINEAR},lt={512:r.NEVER,519:r.ALWAYS,513:r.LESS,515:r.LEQUAL,514:r.EQUAL,518:r.GEQUAL,516:r.GREATER,517:r.NOTEQUAL};function V(E,x,O){if(O?(r.texParameteri(E,r.TEXTURE_WRAP_S,j[x.wrapS]),r.texParameteri(E,r.TEXTURE_WRAP_T,j[x.wrapT]),(E===r.TEXTURE_3D||E===r.TEXTURE_2D_ARRAY)&&r.texParameteri(E,r.TEXTURE_WRAP_R,j[x.wrapR]),r.texParameteri(E,r.TEXTURE_MAG_FILTER,Q[x.magFilter]),r.texParameteri(E,r.TEXTURE_MIN_FILTER,Q[x.minFilter])):(r.texParameteri(E,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(E,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),(E===r.TEXTURE_3D||E===r.TEXTURE_2D_ARRAY)&&r.texParameteri(E,r.TEXTURE_WRAP_R,r.CLAMP_TO_EDGE),(x.wrapS!==1001||x.wrapT!==1001)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),r.texParameteri(E,r.TEXTURE_MAG_FILTER,A(x.magFilter)),r.texParameteri(E,r.TEXTURE_MIN_FILTER,A(x.minFilter)),x.minFilter!==1003&&x.minFilter!==1006&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),x.compareFunction&&(r.texParameteri(E,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(E,r.TEXTURE_COMPARE_FUNC,lt[x.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){const Z=t.get("EXT_texture_filter_anisotropic");if(x.magFilter===1003||x.minFilter!==1005&&x.minFilter!==1008||x.type===1015&&t.has("OES_texture_float_linear")===!1||a===!1&&x.type===1016&&t.has("OES_texture_half_float_linear")===!1)return;(x.anisotropy>1||n.get(x).__currentAnisotropy)&&(r.texParameterf(E,Z.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(x.anisotropy,i.getMaxAnisotropy())),n.get(x).__currentAnisotropy=x.anisotropy)}}function Y(E,x){let O=!1;E.__webglInit===void 0&&(E.__webglInit=!0,x.addEventListener("dispose",w));const Z=x.source;let J=d.get(Z);J===void 0&&(J={},d.set(Z,J));const $=I(x);if($!==E.__cacheKey){J[$]===void 0&&(J[$]={texture:r.createTexture(),usedTimes:0},o.memory.textures++,O=!0),J[$].usedTimes++;const ft=J[E.__cacheKey];ft!==void 0&&(J[E.__cacheKey].usedTimes--,ft.usedTimes===0&&T(x)),E.__cacheKey=$,E.__webglTexture=J[$].texture}return O}function at(E,x,O){let Z=r.TEXTURE_2D;(x.isDataArrayTexture||x.isCompressedArrayTexture)&&(Z=r.TEXTURE_2D_ARRAY),x.isData3DTexture&&(Z=r.TEXTURE_3D);const J=Y(E,x),$=x.source;e.bindTexture(Z,E.__webglTexture,r.TEXTURE0+O);const ft=n.get($);if($.version!==ft.__version||J===!0){e.activeTexture(r.TEXTURE0+O);const st=Kt.getPrimaries(Kt.workingColorSpace),ht=x.colorSpace===Pe?null:Kt.getPrimaries(x.colorSpace),St=x.colorSpace===Pe||st===ht?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,x.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,x.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,St);const It=f(x)&&m(x.image)===!1;let K=v(x.image,It,!1,i.maxTextureSize);K=Ut(x,K);const Xt=m(K)||a,Gt=s.convert(x.format,x.colorSpace);let bt=s.convert(x.type),_t=b(x.internalFormat,Gt,bt,x.colorSpace,x.isVideoTexture);V(Z,x,Xt);let ut;const Pt=x.mipmaps,Wt=a&&x.isVideoTexture!==!0&&_t!==36196,ne=ft.__version===void 0||J===!0,Ft=C(x,K,Xt);if(x.isDepthTexture)_t=r.DEPTH_COMPONENT,a?x.type===1015?_t=r.DEPTH_COMPONENT32F:x.type===1014?_t=r.DEPTH_COMPONENT24:x.type===1020?_t=r.DEPTH24_STENCIL8:_t=r.DEPTH_COMPONENT16:x.type===1015&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),x.format===1026&&_t===r.DEPTH_COMPONENT&&x.type!==1012&&x.type!==1014&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),x.type=1014,bt=s.convert(x.type)),x.format===1027&&_t===r.DEPTH_COMPONENT&&(_t=r.DEPTH_STENCIL,x.type!==1020&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),x.type=1020,bt=s.convert(x.type))),ne&&(Wt?e.texStorage2D(r.TEXTURE_2D,1,_t,K.width,K.height):e.texImage2D(r.TEXTURE_2D,0,_t,K.width,K.height,0,Gt,bt,null));else if(x.isDataTexture)if(Pt.length>0&&Xt){Wt&&ne&&e.texStorage2D(r.TEXTURE_2D,Ft,_t,Pt[0].width,Pt[0].height);for(let et=0,L=Pt.length;et>=1,L>>=1}}else if(Pt.length>0&&Xt){Wt&&ne&&e.texStorage2D(r.TEXTURE_2D,Ft,_t,Pt[0].width,Pt[0].height);for(let et=0,L=Pt.length;et0&&ne++,e.texStorage2D(r.TEXTURE_CUBE_MAP,ne,ut,K[0].width,K[0].height));for(let et=0;et<6;et++)if(It){Pt?e.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+et,0,0,0,K[et].width,K[et].height,bt,_t,K[et].data):e.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+et,0,ut,K[et].width,K[et].height,0,bt,_t,K[et].data);for(let L=0;L>$),K=Math.max(1,x.height>>$);J===r.TEXTURE_3D||J===r.TEXTURE_2D_ARRAY?e.texImage3D(J,$,ht,It,K,x.depth,0,ft,st,null):e.texImage2D(J,$,ht,It,K,0,ft,st,null)}e.bindFramebuffer(r.FRAMEBUFFER,E),dt(x)?l.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,Z,J,n.get(O).__webglTexture,0,At(x)):(J===r.TEXTURE_2D||J>=r.TEXTURE_CUBE_MAP_POSITIVE_X&&J<=r.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&r.framebufferTexture2D(r.FRAMEBUFFER,Z,J,n.get(O).__webglTexture,$),e.bindFramebuffer(r.FRAMEBUFFER,null)}function Rt(E,x,O){if(r.bindRenderbuffer(r.RENDERBUFFER,E),x.depthBuffer&&!x.stencilBuffer){let Z=a===!0?r.DEPTH_COMPONENT24:r.DEPTH_COMPONENT16;if(O||dt(x)){const J=x.depthTexture;J&&J.isDepthTexture&&(J.type===1015?Z=r.DEPTH_COMPONENT32F:J.type===1014&&(Z=r.DEPTH_COMPONENT24));const $=At(x);dt(x)?l.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,$,Z,x.width,x.height):r.renderbufferStorageMultisample(r.RENDERBUFFER,$,Z,x.width,x.height)}else r.renderbufferStorage(r.RENDERBUFFER,Z,x.width,x.height);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,E)}else if(x.depthBuffer&&x.stencilBuffer){const Z=At(x);O&&dt(x)===!1?r.renderbufferStorageMultisample(r.RENDERBUFFER,Z,r.DEPTH24_STENCIL8,x.width,x.height):dt(x)?l.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,Z,r.DEPTH24_STENCIL8,x.width,x.height):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,x.width,x.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,E)}else{const Z=x.isWebGLMultipleRenderTargets===!0?x.texture:[x.texture];for(let J=0;J0){O.__webglFramebuffer[st]=[];for(let ht=0;ht0){O.__webglFramebuffer=[];for(let st=0;st0&&dt(E)===!1){const st=$?x:[x];O.__webglMultisampledFramebuffer=r.createFramebuffer(),O.__webglColorRenderbuffer=[],e.bindFramebuffer(r.FRAMEBUFFER,O.__webglMultisampledFramebuffer);for(let ht=0;ht0)for(let ht=0;ht0)for(let ht=0;ht0&&dt(E)===!1){const x=E.isWebGLMultipleRenderTargets?E.texture:[E.texture],O=E.width,Z=E.height;let J=r.COLOR_BUFFER_BIT;const $=[],ft=E.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,st=n.get(E),ht=E.isWebGLMultipleRenderTargets===!0;if(ht)for(let St=0;St0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&x.__useRenderToTexture!==!1}function te(E){const x=o.render.frame;h.get(E)!==x&&(h.set(E,x),E.update())}function Ut(E,x){const O=E.colorSpace,Z=E.format,J=E.type;return E.isCompressedTexture===!0||E.isVideoTexture===!0||E.format===1035||O!==Je&&O!==Pe&&(Kt.getTransfer(O)===Qt?a===!1?t.has("EXT_sRGB")===!0&&Z===1023?(E.format=1035,E.minFilter=1006,E.generateMipmaps=!1):x=ba.sRGBToLinear(x):(Z!==1023||J!==1009)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",O)),x}this.allocateTextureUnit=P,this.resetTextureUnits=tt,this.setTexture2D=k,this.setTexture2DArray=q,this.setTexture3D=X,this.setTextureCube=W,this.rebindTextures=Ht,this.setupRenderTarget=N,this.updateRenderTargetMipmap=xe,this.updateMultisampleRenderTarget=vt,this.setupDepthRenderbuffer=yt,this.setupFrameBufferTexture=mt,this.useMultisampledRTT=dt}function wd(r,t,e){const n=e.isWebGL2;function i(s,o=Pe){let a;const l=Kt.getTransfer(o);if(s===1009)return r.UNSIGNED_BYTE;if(s===1017)return r.UNSIGNED_SHORT_4_4_4_4;if(s===1018)return r.UNSIGNED_SHORT_5_5_5_1;if(s===1010)return r.BYTE;if(s===1011)return r.SHORT;if(s===1012)return r.UNSIGNED_SHORT;if(s===1013)return r.INT;if(s===1014)return r.UNSIGNED_INT;if(s===1015)return r.FLOAT;if(s===1016)return n?r.HALF_FLOAT:(a=t.get("OES_texture_half_float"),a!==null?a.HALF_FLOAT_OES:null);if(s===1021)return r.ALPHA;if(s===1023)return r.RGBA;if(s===1024)return r.LUMINANCE;if(s===1025)return r.LUMINANCE_ALPHA;if(s===1026)return r.DEPTH_COMPONENT;if(s===1027)return r.DEPTH_STENCIL;if(s===1035)return a=t.get("EXT_sRGB"),a!==null?a.SRGB_ALPHA_EXT:null;if(s===1028)return r.RED;if(s===1029)return r.RED_INTEGER;if(s===1030)return r.RG;if(s===1031)return r.RG_INTEGER;if(s===1033)return r.RGBA_INTEGER;if(s===33776||s===33777||s===33778||s===33779)if(l===Qt)if(a=t.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(s===33776)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(s===33777)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(s===33778)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(s===33779)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=t.get("WEBGL_compressed_texture_s3tc"),a!==null){if(s===33776)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(s===33777)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(s===33778)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(s===33779)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(s===35840||s===35841||s===35842||s===35843)if(a=t.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(s===35840)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(s===35841)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(s===35842)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(s===35843)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(s===36196)return a=t.get("WEBGL_compressed_texture_etc1"),a!==null?a.COMPRESSED_RGB_ETC1_WEBGL:null;if(s===37492||s===37496)if(a=t.get("WEBGL_compressed_texture_etc"),a!==null){if(s===37492)return l===Qt?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(s===37496)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(s===37808||s===37809||s===37810||s===37811||s===37812||s===37813||s===37814||s===37815||s===37816||s===37817||s===37818||s===37819||s===37820||s===37821)if(a=t.get("WEBGL_compressed_texture_astc"),a!==null){if(s===37808)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(s===37809)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(s===37810)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(s===37811)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(s===37812)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(s===37813)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(s===37814)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(s===37815)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(s===37816)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(s===37817)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(s===37818)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(s===37819)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(s===37820)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(s===37821)return l===Qt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(s===36492||s===36494||s===36495)if(a=t.get("EXT_texture_compression_bptc"),a!==null){if(s===36492)return l===Qt?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(s===36494)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(s===36495)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(s===36283||s===36284||s===36285||s===36286)if(a=t.get("EXT_texture_compression_rgtc"),a!==null){if(s===36492)return a.COMPRESSED_RED_RGTC1_EXT;if(s===36284)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(s===36285)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(s===36286)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return s===1020?n?r.UNSIGNED_INT_24_8:(a=t.get("WEBGL_depth_texture"),a!==null?a.UNSIGNED_INT_24_8_WEBGL:null):r[s]!==void 0?r[s]:null}return{convert:i}}class Rd extends we{constructor(t=[]){super(),this.isArrayCamera=!0,this.cameras=t}}class zi extends re{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Cd={type:"move"};class Or{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new zi,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new zi,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new R,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new R),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new zi,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new R,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new R),this._grip}dispatchEvent(t){return this._targetRay!==null&&this._targetRay.dispatchEvent(t),this._grip!==null&&this._grip.dispatchEvent(t),this._hand!==null&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const n of t.hand.values())this._getHandJoint(e,n)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(t,e,n){let i=null,s=null,o=null;const a=this._targetRay,l=this._grip,c=this._hand;if(t&&e.session.visibilityState!=="visible-blurred"){if(c&&t.hand){o=!0;for(const v of t.hand.values()){const m=e.getJointPose(v,n),f=this._getHandJoint(c,v);m!==null&&(f.matrix.fromArray(m.transform.matrix),f.matrix.decompose(f.position,f.rotation,f.scale),f.matrixWorldNeedsUpdate=!0,f.jointRadius=m.radius),f.visible=m!==null}const h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=h.position.distanceTo(u.position),p=.02,g=.005;c.inputState.pinching&&d>p+g?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!c.inputState.pinching&&d<=p-g&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else l!==null&&t.gripSpace&&(s=e.getPose(t.gripSpace,n),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1));a!==null&&(i=e.getPose(t.targetRaySpace,n),i===null&&s!==null&&(i=s),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Cd)))}return a!==null&&(a.visible=i!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){const n=new zi;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}}class Ld extends kn{constructor(t,e){super();const n=this;let i=null,s=1,o=null,a="local-floor",l=1,c=null,h=null,u=null,d=null,p=null,g=null;const v=e.getContextAttributes();let m=null,f=null;const S=[],_=[],b=new ct;let C=null;const A=new we;A.layers.enable(1),A.viewport=new Jt;const w=new we;w.layers.enable(2),w.viewport=new Jt;const U=[A,w],M=new Rd;M.layers.enable(1),M.layers.enable(2);let T=null,z=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(V){let Y=S[V];return Y===void 0&&(Y=new Or,S[V]=Y),Y.getTargetRaySpace()},this.getControllerGrip=function(V){let Y=S[V];return Y===void 0&&(Y=new Or,S[V]=Y),Y.getGripSpace()},this.getHand=function(V){let Y=S[V];return Y===void 0&&(Y=new Or,S[V]=Y),Y.getHandSpace()};function H(V){const Y=_.indexOf(V.inputSource);if(Y===-1)return;const at=S[Y];at!==void 0&&(at.update(V.inputSource,V.frame,c||o),at.dispatchEvent({type:V.type,data:V.inputSource}))}function tt(){i.removeEventListener("select",H),i.removeEventListener("selectstart",H),i.removeEventListener("selectend",H),i.removeEventListener("squeeze",H),i.removeEventListener("squeezestart",H),i.removeEventListener("squeezeend",H),i.removeEventListener("end",tt),i.removeEventListener("inputsourceschange",P);for(let V=0;V=0&&(_[gt]=null,S[gt].disconnect(at))}for(let Y=0;Y=_.length){_.push(at),gt=Rt;break}else if(_[Rt]===null){_[Rt]=at,gt=Rt;break}if(gt===-1)break}const mt=S[gt];mt&&mt.connect(at)}}const I=new R,k=new R;function q(V,Y,at){I.setFromMatrixPosition(Y.matrixWorld),k.setFromMatrixPosition(at.matrixWorld);const gt=I.distanceTo(k),mt=Y.projectionMatrix.elements,Rt=at.projectionMatrix.elements,Lt=mt[14]/(mt[10]-1),yt=mt[14]/(mt[10]+1),Ht=(mt[9]+1)/mt[5],N=(mt[9]-1)/mt[5],xe=(mt[8]-1)/mt[0],vt=(Rt[8]+1)/Rt[0],At=Lt*xe,dt=Lt*vt,te=gt/(-xe+vt),Ut=te*-xe;Y.matrixWorld.decompose(V.position,V.quaternion,V.scale),V.translateX(Ut),V.translateZ(te),V.matrixWorld.compose(V.position,V.quaternion,V.scale),V.matrixWorldInverse.copy(V.matrixWorld).invert();const E=Lt+te,x=yt+te,O=At-Ut,Z=dt+(gt-Ut),J=Ht*yt/x*E,$=N*yt/x*E;V.projectionMatrix.makePerspective(O,Z,J,$,E,x),V.projectionMatrixInverse.copy(V.projectionMatrix).invert()}function X(V,Y){Y===null?V.matrixWorld.copy(V.matrix):V.matrixWorld.multiplyMatrices(Y.matrixWorld,V.matrix),V.matrixWorldInverse.copy(V.matrixWorld).invert()}this.updateCamera=function(V){if(i===null)return;M.near=w.near=A.near=V.near,M.far=w.far=A.far=V.far,(T!==M.near||z!==M.far)&&(i.updateRenderState({depthNear:M.near,depthFar:M.far}),T=M.near,z=M.far);const Y=V.parent,at=M.cameras;X(M,Y);for(let gt=0;gt0&&(m.alphaTest.value=f.alphaTest);const S=t.get(f).envMap;if(S&&(m.envMap.value=S,m.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=f.reflectivity,m.ior.value=f.ior,m.refractionRatio.value=f.refractionRatio),f.lightMap){m.lightMap.value=f.lightMap;const _=r._useLegacyLights===!0?Math.PI:1;m.lightMapIntensity.value=f.lightMapIntensity*_,e(f.lightMap,m.lightMapTransform)}f.aoMap&&(m.aoMap.value=f.aoMap,m.aoMapIntensity.value=f.aoMapIntensity,e(f.aoMap,m.aoMapTransform))}function o(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,f.map&&(m.map.value=f.map,e(f.map,m.mapTransform))}function a(m,f){m.dashSize.value=f.dashSize,m.totalSize.value=f.dashSize+f.gapSize,m.scale.value=f.scale}function l(m,f,S,_){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.size.value=f.size*S,m.scale.value=_*.5,f.map&&(m.map.value=f.map,e(f.map,m.uvTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,e(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function c(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.rotation.value=f.rotation,f.map&&(m.map.value=f.map,e(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,e(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function h(m,f){m.specular.value.copy(f.specular),m.shininess.value=Math.max(f.shininess,1e-4)}function u(m,f){f.gradientMap&&(m.gradientMap.value=f.gradientMap)}function d(m,f){m.metalness.value=f.metalness,f.metalnessMap&&(m.metalnessMap.value=f.metalnessMap,e(f.metalnessMap,m.metalnessMapTransform)),m.roughness.value=f.roughness,f.roughnessMap&&(m.roughnessMap.value=f.roughnessMap,e(f.roughnessMap,m.roughnessMapTransform)),t.get(f).envMap&&(m.envMapIntensity.value=f.envMapIntensity)}function p(m,f,S){m.ior.value=f.ior,f.sheen>0&&(m.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen),m.sheenRoughness.value=f.sheenRoughness,f.sheenColorMap&&(m.sheenColorMap.value=f.sheenColorMap,e(f.sheenColorMap,m.sheenColorMapTransform)),f.sheenRoughnessMap&&(m.sheenRoughnessMap.value=f.sheenRoughnessMap,e(f.sheenRoughnessMap,m.sheenRoughnessMapTransform))),f.clearcoat>0&&(m.clearcoat.value=f.clearcoat,m.clearcoatRoughness.value=f.clearcoatRoughness,f.clearcoatMap&&(m.clearcoatMap.value=f.clearcoatMap,e(f.clearcoatMap,m.clearcoatMapTransform)),f.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=f.clearcoatRoughnessMap,e(f.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),f.clearcoatNormalMap&&(m.clearcoatNormalMap.value=f.clearcoatNormalMap,e(f.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(f.clearcoatNormalScale),f.side===1&&m.clearcoatNormalScale.value.negate())),f.iridescence>0&&(m.iridescence.value=f.iridescence,m.iridescenceIOR.value=f.iridescenceIOR,m.iridescenceThicknessMinimum.value=f.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=f.iridescenceThicknessRange[1],f.iridescenceMap&&(m.iridescenceMap.value=f.iridescenceMap,e(f.iridescenceMap,m.iridescenceMapTransform)),f.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=f.iridescenceThicknessMap,e(f.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),f.transmission>0&&(m.transmission.value=f.transmission,m.transmissionSamplerMap.value=S.texture,m.transmissionSamplerSize.value.set(S.width,S.height),f.transmissionMap&&(m.transmissionMap.value=f.transmissionMap,e(f.transmissionMap,m.transmissionMapTransform)),m.thickness.value=f.thickness,f.thicknessMap&&(m.thicknessMap.value=f.thicknessMap,e(f.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=f.attenuationDistance,m.attenuationColor.value.copy(f.attenuationColor)),f.anisotropy>0&&(m.anisotropyVector.value.set(f.anisotropy*Math.cos(f.anisotropyRotation),f.anisotropy*Math.sin(f.anisotropyRotation)),f.anisotropyMap&&(m.anisotropyMap.value=f.anisotropyMap,e(f.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=f.specularIntensity,m.specularColor.value.copy(f.specularColor),f.specularColorMap&&(m.specularColorMap.value=f.specularColorMap,e(f.specularColorMap,m.specularColorMapTransform)),f.specularIntensityMap&&(m.specularIntensityMap.value=f.specularIntensityMap,e(f.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,f){f.matcap&&(m.matcap.value=f.matcap)}function v(m,f){const S=t.get(f).light;m.referencePosition.value.setFromMatrixPosition(S.matrixWorld),m.nearDistance.value=S.shadow.camera.near,m.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:i}}function Dd(r,t,e,n){let i={},s={},o=[];const a=e.isWebGL2?r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(S,_){const b=_.program;n.uniformBlockBinding(S,b)}function c(S,_){let b=i[S.id];b===void 0&&(g(S),b=h(S),i[S.id]=b,S.addEventListener("dispose",m));const C=_.program;n.updateUBOMapping(S,C);const A=t.render.frame;s[S.id]!==A&&(d(S),s[S.id]=A)}function h(S){const _=u();S.__bindingPointIndex=_;const b=r.createBuffer(),C=S.__size,A=S.usage;return r.bindBuffer(r.UNIFORM_BUFFER,b),r.bufferData(r.UNIFORM_BUFFER,C,A),r.bindBuffer(r.UNIFORM_BUFFER,null),r.bindBufferBase(r.UNIFORM_BUFFER,_,b),b}function u(){for(let S=0;S0&&(b+=C-A),S.__size=b,S.__cache={},this}function v(S){const _={boundary:0,storage:0};return typeof S=="number"||typeof S=="boolean"?(_.boundary=4,_.storage=4):S.isVector2?(_.boundary=8,_.storage=8):S.isVector3||S.isColor?(_.boundary=16,_.storage=12):S.isVector4?(_.boundary=16,_.storage=16):S.isMatrix3?(_.boundary=48,_.storage=48):S.isMatrix4?(_.boundary=64,_.storage=64):S.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",S),_}function m(S){const _=S.target;_.removeEventListener("dispose",m);const b=o.indexOf(_.__bindingPointIndex);o.splice(b,1),r.deleteBuffer(i[_.id]),delete i[_.id],delete s[_.id]}function f(){for(const S in i)r.deleteBuffer(i[S]);o=[],i={},s={}}return{bind:l,update:c,dispose:f}}class Ud{constructor(t={}){const{canvas:e=Ro(),context:n=null,depth:i=!0,stencil:s=!0,alpha:o=!1,antialias:a=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1}=t;this.isWebGLRenderer=!0;let d;n!==null?d=n.getContextAttributes().alpha:d=o;const p=new Uint32Array(4),g=new Int32Array(4);let v=null,m=null;const f=[],S=[];this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=fe,this._useLegacyLights=!1,this.toneMapping=0,this.toneMappingExposure=1;const _=this;let b=!1,C=0,A=0,w=null,U=-1,M=null;const T=new Jt,z=new Jt;let H=null;const tt=new zt(0);let P=0,I=e.width,k=e.height,q=1,X=null,W=null;const j=new Jt(0,0,I,k),Q=new Jt(0,0,I,k);let lt=!1;const V=new Qr;let Y=!1,at=!1,gt=null;const mt=new Vt,Rt=new ct,Lt=new R,yt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function Ht(){return w===null?q:1}let N=n;function xe(y,D){for(let B=0;B{function ot(){if(G.forEach(function(pt){Ut.get(pt).currentProgram.isReady()&&G.delete(pt)}),G.size===0){F(y);return}setTimeout(ot,10)}vt.get("KHR_parallel_shader_compile")!==null?ot():setTimeout(ot,10)})};let Zt=null;function ce(y){Zt&&Zt(y)}function Me(){Se.stop()}function $t(){Se.start()}const Se=new Fa;Se.setAnimationLoop(ce),typeof self<"u"&&Se.setContext(self),this.setAnimationLoop=function(y){Zt=y,Ft.setAnimationLoop(y),y===null?Se.stop():Se.start()},Ft.addEventListener("sessionstart",Me),Ft.addEventListener("sessionend",$t),this.render=function(y,D){if(D!==void 0&&D.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(b===!0)return;y.matrixWorldAutoUpdate===!0&&y.updateMatrixWorld(),D.parent===null&&D.matrixWorldAutoUpdate===!0&&D.updateMatrixWorld(),Ft.enabled===!0&&Ft.isPresenting===!0&&(Ft.cameraAutoUpdate===!0&&Ft.updateCamera(D),D=Ft.getCamera()),y.isScene===!0&&y.onBeforeRender(_,y,D,w),m=St.get(y,S.length),m.init(),S.push(m),mt.multiplyMatrices(D.projectionMatrix,D.matrixWorldInverse),V.setFromProjectionMatrix(mt),at=this.localClippingEnabled,Y=It.init(this.clippingPlanes,at),v=ht.get(y,f.length),v.init(),f.push(v),Be(y,D,0,_.sortObjects),v.finish(),_.sortObjects===!0&&v.sort(X,W),this.info.render.frame++,Y===!0&&It.beginShadows();const B=m.state.shadowsArray;if(K.render(B,y,D),Y===!0&&It.endShadows(),this.info.autoReset===!0&&this.info.reset(),Xt.render(v,y),m.setupLights(_._useLegacyLights),D.isArrayCamera){const G=D.cameras;for(let F=0,ot=G.length;F0?m=S[S.length-1]:m=null,f.pop(),f.length>0?v=f[f.length-1]:v=null};function Be(y,D,B,G){if(y.visible===!1)return;if(y.layers.test(D.layers)){if(y.isGroup)B=y.renderOrder;else if(y.isLOD)y.autoUpdate===!0&&y.update(D);else if(y.isLight)m.pushLight(y),y.castShadow&&m.pushShadow(y);else if(y.isSprite){if(!y.frustumCulled||V.intersectsSprite(y)){G&&Lt.setFromMatrixPosition(y.matrixWorld).applyMatrix4(mt);const pt=$.update(y),Mt=y.material;Mt.visible&&v.push(y,pt,Mt,B,Lt.z,null)}}else if((y.isMesh||y.isLine||y.isPoints)&&(!y.frustumCulled||V.intersectsObject(y))){const pt=$.update(y),Mt=y.material;if(G&&(y.boundingSphere!==void 0?(y.boundingSphere===null&&y.computeBoundingSphere(),Lt.copy(y.boundingSphere.center)):(pt.boundingSphere===null&&pt.computeBoundingSphere(),Lt.copy(pt.boundingSphere.center)),Lt.applyMatrix4(y.matrixWorld).applyMatrix4(mt)),Array.isArray(Mt)){const Tt=pt.groups;for(let Nt=0,wt=Tt.length;Nt0&&oo(F,ot,D,B),G&&dt.viewport(T.copy(G)),F.length>0&&mi(F,D,B),ot.length>0&&mi(ot,D,B),pt.length>0&&mi(pt,D,B),dt.buffers.depth.setTest(!0),dt.buffers.depth.setMask(!0),dt.buffers.color.setMask(!0),dt.setPolygonOffset(!1)}function oo(y,D,B,G){if((B.isScene===!0?B.overrideMaterial:null)!==null)return;const ot=At.isWebGL2;gt===null&&(gt=new gn(1,1,{generateMipmaps:!0,type:vt.has("EXT_color_buffer_half_float")?1016:1009,minFilter:1008,samples:ot?4:0})),_.getDrawingBufferSize(Rt),ot?gt.setSize(Rt.x,Rt.y):gt.setSize(er(Rt.x),er(Rt.y));const pt=_.getRenderTarget();_.setRenderTarget(gt),_.getClearColor(tt),P=_.getClearAlpha(),P<1&&_.setClearColor(16777215,.5),_.clear();const Mt=_.toneMapping;_.toneMapping=0,mi(y,B,G),E.updateMultisampleRenderTarget(gt),E.updateRenderTargetMipmap(gt);let Tt=!1;for(let Nt=0,wt=D.length;Nt0),Ct=!!B.morphAttributes.position,se=!!B.morphAttributes.normal,Te=!!B.morphAttributes.color;let he=0;G.toneMapped&&(w===null||w.isXRRenderTarget===!0)&&(he=_.toneMapping);const He=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,ee=He!==void 0?He.length:0,Ot=Ut.get(G),ur=m.state.lights;if(Y===!0&&(at===!0||y!==M)){const Re=y===M&&G.id===U;It.setState(G,y,Re)}let ie=!1;G.version===Ot.__version?(Ot.needsLights&&Ot.lightsStateVersion!==ur.state.version||Ot.outputColorSpace!==Mt||F.isBatchedMesh&&Ot.batching===!1||!F.isBatchedMesh&&Ot.batching===!0||F.isInstancedMesh&&Ot.instancing===!1||!F.isInstancedMesh&&Ot.instancing===!0||F.isSkinnedMesh&&Ot.skinning===!1||!F.isSkinnedMesh&&Ot.skinning===!0||F.isInstancedMesh&&Ot.instancingColor===!0&&F.instanceColor===null||F.isInstancedMesh&&Ot.instancingColor===!1&&F.instanceColor!==null||Ot.envMap!==Tt||G.fog===!0&&Ot.fog!==ot||Ot.numClippingPlanes!==void 0&&(Ot.numClippingPlanes!==It.numPlanes||Ot.numIntersection!==It.numIntersection)||Ot.vertexAlphas!==Nt||Ot.vertexTangents!==wt||Ot.morphTargets!==Ct||Ot.morphNormals!==se||Ot.morphColors!==Te||Ot.toneMapping!==he||At.isWebGL2===!0&&Ot.morphTargetsCount!==ee)&&(ie=!0):(ie=!0,Ot.__version=G.version);let on=Ot.currentProgram;ie===!0&&(on=gi(G,D,F));let us=!1,Jn=!1,dr=!1;const me=on.getUniforms(),ln=Ot.uniforms;if(dt.useProgram(on.program)&&(us=!0,Jn=!0,dr=!0),G.id!==U&&(U=G.id,Jn=!0),us||M!==y){me.setValue(N,"projectionMatrix",y.projectionMatrix),me.setValue(N,"viewMatrix",y.matrixWorldInverse);const Re=me.map.cameraPosition;Re!==void 0&&Re.setValue(N,Lt.setFromMatrixPosition(y.matrixWorld)),At.logarithmicDepthBuffer&&me.setValue(N,"logDepthBufFC",2/(Math.log(y.far+1)/Math.LN2)),(G.isMeshPhongMaterial||G.isMeshToonMaterial||G.isMeshLambertMaterial||G.isMeshBasicMaterial||G.isMeshStandardMaterial||G.isShaderMaterial)&&me.setValue(N,"isOrthographic",y.isOrthographicCamera===!0),M!==y&&(M=y,Jn=!0,dr=!0)}if(F.isSkinnedMesh){me.setOptional(N,F,"bindMatrix"),me.setOptional(N,F,"bindMatrixInverse");const Re=F.skeleton;Re&&(At.floatVertexTextures?(Re.boneTexture===null&&Re.computeBoneTexture(),me.setValue(N,"boneTexture",Re.boneTexture,E)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}F.isBatchedMesh&&(me.setOptional(N,F,"batchingTexture"),me.setValue(N,"batchingTexture",F._matricesTexture,E));const fr=B.morphAttributes;if((fr.position!==void 0||fr.normal!==void 0||fr.color!==void 0&&At.isWebGL2===!0)&&Gt.update(F,B,on),(Jn||Ot.receiveShadow!==F.receiveShadow)&&(Ot.receiveShadow=F.receiveShadow,me.setValue(N,"receiveShadow",F.receiveShadow)),G.isMeshGouraudMaterial&&G.envMap!==null&&(ln.envMap.value=Tt,ln.flipEnvMap.value=Tt.isCubeTexture&&Tt.isRenderTargetTexture===!1?-1:1),Jn&&(me.setValue(N,"toneMappingExposure",_.toneMappingExposure),Ot.needsLights&&co(ln,dr),ot&&G.fog===!0&&st.refreshFogUniforms(ln,ot),st.refreshMaterialUniforms(ln,G,q,k,gt),Zi.upload(N,cs(Ot),ln,E)),G.isShaderMaterial&&G.uniformsNeedUpdate===!0&&(Zi.upload(N,cs(Ot),ln,E),G.uniformsNeedUpdate=!1),G.isSpriteMaterial&&me.setValue(N,"center",F.center),me.setValue(N,"modelViewMatrix",F.modelViewMatrix),me.setValue(N,"normalMatrix",F.normalMatrix),me.setValue(N,"modelMatrix",F.matrixWorld),G.isShaderMaterial||G.isRawShaderMaterial){const Re=G.uniformsGroups;for(let pr=0,uo=Re.length;pr0&&E.useMultisampledRTT(y)===!1?F=Ut.get(y).__webglMultisampledFramebuffer:Array.isArray(wt)?F=wt[B]:F=wt,T.copy(y.viewport),z.copy(y.scissor),H=y.scissorTest}else T.copy(j).multiplyScalar(q).floor(),z.copy(Q).multiplyScalar(q).floor(),H=lt;if(dt.bindFramebuffer(N.FRAMEBUFFER,F)&&At.drawBuffers&&G&&dt.drawBuffers(y,F),dt.viewport(T),dt.scissor(z),dt.setScissorTest(H),ot){const Tt=Ut.get(y.texture);N.framebufferTexture2D(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_CUBE_MAP_POSITIVE_X+D,Tt.__webglTexture,B)}else if(pt){const Tt=Ut.get(y.texture),Nt=D||0;N.framebufferTextureLayer(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,Tt.__webglTexture,B||0,Nt)}U=-1},this.readRenderTargetPixels=function(y,D,B,G,F,ot,pt){if(!(y&&y.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Mt=Ut.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&pt!==void 0&&(Mt=Mt[pt]),Mt){dt.bindFramebuffer(N.FRAMEBUFFER,Mt);try{const Tt=y.texture,Nt=Tt.format,wt=Tt.type;if(Nt!==1023&&ut.convert(Nt)!==N.getParameter(N.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const Ct=wt===1016&&(vt.has("EXT_color_buffer_half_float")||At.isWebGL2&&vt.has("EXT_color_buffer_float"));if(wt!==1009&&ut.convert(wt)!==N.getParameter(N.IMPLEMENTATION_COLOR_READ_TYPE)&&!(wt===1015&&(At.isWebGL2||vt.has("OES_texture_float")||vt.has("WEBGL_color_buffer_float")))&&!Ct){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}D>=0&&D<=y.width-G&&B>=0&&B<=y.height-F&&N.readPixels(D,B,G,F,ut.convert(Nt),ut.convert(wt),ot)}finally{const Tt=w!==null?Ut.get(w).__webglFramebuffer:null;dt.bindFramebuffer(N.FRAMEBUFFER,Tt)}}},this.copyFramebufferToTexture=function(y,D,B=0){const G=Math.pow(2,-B),F=Math.floor(D.image.width*G),ot=Math.floor(D.image.height*G);E.setTexture2D(D,0),N.copyTexSubImage2D(N.TEXTURE_2D,B,0,0,y.x,y.y,F,ot),dt.unbindTexture()},this.copyTextureToTexture=function(y,D,B,G=0){const F=D.image.width,ot=D.image.height,pt=ut.convert(B.format),Mt=ut.convert(B.type);E.setTexture2D(B,0),N.pixelStorei(N.UNPACK_FLIP_Y_WEBGL,B.flipY),N.pixelStorei(N.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),N.pixelStorei(N.UNPACK_ALIGNMENT,B.unpackAlignment),D.isDataTexture?N.texSubImage2D(N.TEXTURE_2D,G,y.x,y.y,F,ot,pt,Mt,D.image.data):D.isCompressedTexture?N.compressedTexSubImage2D(N.TEXTURE_2D,G,y.x,y.y,D.mipmaps[0].width,D.mipmaps[0].height,pt,D.mipmaps[0].data):N.texSubImage2D(N.TEXTURE_2D,G,y.x,y.y,pt,Mt,D.image),G===0&&B.generateMipmaps&&N.generateMipmap(N.TEXTURE_2D),dt.unbindTexture()},this.copyTextureToTexture3D=function(y,D,B,G,F=0){if(_.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const ot=y.max.x-y.min.x+1,pt=y.max.y-y.min.y+1,Mt=y.max.z-y.min.z+1,Tt=ut.convert(G.format),Nt=ut.convert(G.type);let wt;if(G.isData3DTexture)E.setTexture3D(G,0),wt=N.TEXTURE_3D;else if(G.isDataArrayTexture||G.isCompressedArrayTexture)E.setTexture2DArray(G,0),wt=N.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}N.pixelStorei(N.UNPACK_FLIP_Y_WEBGL,G.flipY),N.pixelStorei(N.UNPACK_PREMULTIPLY_ALPHA_WEBGL,G.premultiplyAlpha),N.pixelStorei(N.UNPACK_ALIGNMENT,G.unpackAlignment);const Ct=N.getParameter(N.UNPACK_ROW_LENGTH),se=N.getParameter(N.UNPACK_IMAGE_HEIGHT),Te=N.getParameter(N.UNPACK_SKIP_PIXELS),he=N.getParameter(N.UNPACK_SKIP_ROWS),He=N.getParameter(N.UNPACK_SKIP_IMAGES),ee=B.isCompressedTexture?B.mipmaps[F]:B.image;N.pixelStorei(N.UNPACK_ROW_LENGTH,ee.width),N.pixelStorei(N.UNPACK_IMAGE_HEIGHT,ee.height),N.pixelStorei(N.UNPACK_SKIP_PIXELS,y.min.x),N.pixelStorei(N.UNPACK_SKIP_ROWS,y.min.y),N.pixelStorei(N.UNPACK_SKIP_IMAGES,y.min.z),B.isDataTexture||B.isData3DTexture?N.texSubImage3D(wt,F,D.x,D.y,D.z,ot,pt,Mt,Tt,Nt,ee.data):B.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),N.compressedTexSubImage3D(wt,F,D.x,D.y,D.z,ot,pt,Mt,Tt,ee.data)):N.texSubImage3D(wt,F,D.x,D.y,D.z,ot,pt,Mt,Tt,Nt,ee),N.pixelStorei(N.UNPACK_ROW_LENGTH,Ct),N.pixelStorei(N.UNPACK_IMAGE_HEIGHT,se),N.pixelStorei(N.UNPACK_SKIP_PIXELS,Te),N.pixelStorei(N.UNPACK_SKIP_ROWS,he),N.pixelStorei(N.UNPACK_SKIP_IMAGES,He),F===0&&G.generateMipmaps&&N.generateMipmap(wt),dt.unbindTexture()},this.initTexture=function(y){y.isCubeTexture?E.setTextureCube(y,0):y.isData3DTexture?E.setTexture3D(y,0):y.isDataArrayTexture||y.isCompressedArrayTexture?E.setTexture2DArray(y,0):E.setTexture2D(y,0),dt.unbindTexture()},this.resetState=function(){C=0,A=0,w=null,dt.reset(),Pt.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return 2e3}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=t===Zr?"display-p3":"srgb",e.unpackColorSpace=Kt.workingColorSpace===sr?"display-p3":"srgb"}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===fe?3001:3e3}set outputEncoding(t){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=t===3001?fe:Je}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(t){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=t}}class Id extends Ud{}Id.prototype.isWebGL1Renderer=!0;class Wa{constructor(t,e=25e-5){this.isFogExp2=!0,this.name="",this.color=new zt(t),this.density=e}clone(){return new Wa(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class op extends re{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),t.background!==null&&(this.background=t.background.clone()),t.environment!==null&&(this.environment=t.environment.clone()),t.fog!==null&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,t.overrideMaterial!==null&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e}}class Nd{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=t!==void 0?t.length/e:0,this.usage=35044,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Oe()}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}get updateRange(){return console.warn("THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,n){t*=this.stride,n*=e.stride;for(let i=0,s=this.stride;it.far||e.push({distance:l,point:ti.clone(),uv:Le.getInterpolation(ti,Gi,ni,Vi,ta,Br,ea,new ct),face:null,object:this})}copy(t,e){return super.copy(t,e),t.center!==void 0&&this.center.copy(t.center),this.material=t.material,this}}function Hi(r,t,e,n,i,s){Fn.subVectors(r,e).addScalar(.5).multiply(n),i!==void 0?(ei.x=s*Fn.x-i*Fn.y,ei.y=i*Fn.x+s*Fn.y):ei.copy(Fn),r.copy(t),r.x+=ei.x,r.y+=ei.y,r.applyMatrix4(Xa)}const na=new R,ia=new Jt,ra=new Jt,Od=new R,sa=new Vt,ki=new R,zr=new je,aa=new Vt,Gr=new ar;class cp extends Fe{constructor(t,e){super(t,e),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=fs,this.bindMatrix=new Vt,this.bindMatrixInverse=new Vt,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const t=this.geometry;this.boundingBox===null&&(this.boundingBox=new sn),this.boundingBox.makeEmpty();const e=t.getAttribute("position");for(let n=0;nl)continue;d.applyMatrix4(this.matrixWorld);const U=t.ray.origin.distanceTo(d);Ut.far||e.push({distance:U,point:u.clone().applyMatrix4(this.matrixWorld),index:_,face:null,faceIndex:null,object:this})}}else{const f=Math.max(0,o.start),S=Math.min(m.count,o.start+o.count);for(let _=f,b=S-1;_l)continue;d.applyMatrix4(this.matrixWorld);const A=t.ray.origin.distanceTo(d);At.far||e.push({distance:A,point:u.clone().applyMatrix4(this.matrixWorld),index:_,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const e=this.geometry.morphAttributes,n=Object.keys(e);if(n.length>0){const i=e[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s0){const i=e[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;si.far)return;s.push({distance:c,distanceToRay:Math.sqrt(a),point:l,index:t,face:null,object:o})}}class pp extends ve{constructor(t,e,n,i,s,o,a,l,c){super(t,e,n,i,s,o,a,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Ze{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(t,e){const n=this.getUtoTmapping(t);return this.getPoint(n,e)}getPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return e}getSpacedPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPointAt(n/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let n,i=this.getPoint(0),s=0;e.push(0);for(let o=1;o<=t;o++)n=this.getPoint(o/t),s+=n.distanceTo(i),e.push(s),i=n;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e){const n=this.getLengths();let i=0;const s=n.length;let o;e?o=e:o=t*n[s-1];let a=0,l=s-1,c;for(;a<=l;)if(i=Math.floor(a+(l-a)/2),c=n[i]-o,c<0)a=i+1;else if(c>0)l=i-1;else{l=i;break}if(i=l,n[i]===o)return i/(s-1);const h=n[i],d=n[i+1]-h,p=(o-h)/d;return(i+p)/(s-1)}getTangent(t,e){let i=t-1e-4,s=t+1e-4;i<0&&(i=0),s>1&&(s=1);const o=this.getPoint(i),a=this.getPoint(s),l=e||(o.isVector2?new ct:new R);return l.copy(a).sub(o).normalize(),l}getTangentAt(t,e){const n=this.getUtoTmapping(t);return this.getTangent(n,e)}computeFrenetFrames(t,e){const n=new R,i=[],s=[],o=[],a=new R,l=new Vt;for(let p=0;p<=t;p++){const g=p/t;i[p]=this.getTangentAt(g,new R)}s[0]=new R,o[0]=new R;let c=Number.MAX_VALUE;const h=Math.abs(i[0].x),u=Math.abs(i[0].y),d=Math.abs(i[0].z);h<=c&&(c=h,n.set(1,0,0)),u<=c&&(c=u,n.set(0,1,0)),d<=c&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),s[0].crossVectors(i[0],a),o[0].crossVectors(i[0],s[0]);for(let p=1;p<=t;p++){if(s[p]=s[p-1].clone(),o[p]=o[p-1].clone(),a.crossVectors(i[p-1],i[p]),a.length()>Number.EPSILON){a.normalize();const g=Math.acos(de(i[p-1].dot(i[p]),-1,1));s[p].applyMatrix4(l.makeRotationAxis(a,g))}o[p].crossVectors(i[p],s[p])}if(e===!0){let p=Math.acos(de(s[0].dot(s[t]),-1,1));p/=t,i[0].dot(a.crossVectors(s[0],s[t]))>0&&(p=-p);for(let g=1;g<=t;g++)s[g].applyMatrix4(l.makeRotationAxis(i[g],p*g)),o[g].crossVectors(i[g],s[g])}return{tangents:i,normals:s,binormals:o}}clone(){return new this.constructor().copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class Ka extends Ze{constructor(t=0,e=0,n=1,i=1,s=0,o=Math.PI*2,a=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=s,this.aEndAngle=o,this.aClockwise=a,this.aRotation=l}getPoint(t,e){const n=e||new ct,i=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const o=Math.abs(s)i;)s-=i;s0?0:(Math.floor(Math.abs(a)/s)+1)*s:l===0&&a===s-1&&(a=s-2,l=1);let c,h;this.closed||a>0?c=i[(a-1)%s]:(Ki.subVectors(i[0],i[1]).add(i[0]),c=Ki);const u=i[a%s],d=i[(a+1)%s];if(this.closed||a+2i.length-2?i.length-1:o+1],u=i[o>i.length-3?i.length-1:o+2];return n.set(va(a,l.x,c.x,h.x,u.x),va(a,l.y,c.y,h.y,u.y)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e0&&_(!0),e>0&&_(!1)),this.setIndex(h),this.setAttribute("position",new kt(u,3)),this.setAttribute("normal",new kt(d,3)),this.setAttribute("uv",new kt(p,2));function S(){const b=new R,C=new R;let A=0;const w=(e-t)/n;for(let U=0;U<=s;U++){const M=[],T=U/s,z=T*(e-t)+t;for(let H=0;H<=i;H++){const tt=H/i,P=tt*l+a,I=Math.sin(P),k=Math.cos(P);C.x=z*I,C.y=-T*n+m,C.z=z*k,u.push(C.x,C.y,C.z),b.set(I,w,k).normalize(),d.push(b.x,b.y,b.z),p.push(tt,1-T),M.push(g++)}v.push(M)}for(let U=0;U.9&&w<.1&&(_<.2&&(o[S+0]+=1),b<.2&&(o[S+2]+=1),C<.2&&(o[S+4]+=1))}}function d(S){s.push(S.x,S.y,S.z)}function p(S,_){const b=S*3;_.x=t[b+0],_.y=t[b+1],_.z=t[b+2]}function g(){const S=new R,_=new R,b=new R,C=new R,A=new ct,w=new ct,U=new ct;for(let M=0,T=0;M0)&&p.push(_,b,A),(f!==n-1||l0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}function Ji(r,t,e){return!r||!e&&r.constructor===t?r:typeof t.BYTES_PER_ELEMENT=="number"?new t(r):Array.prototype.slice.call(r)}function lf(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function cf(r){function t(i,s){return r[i]-r[s]}const e=r.length,n=new Array(e);for(let i=0;i!==e;++i)n[i]=i;return n.sort(t),n}function xa(r,t,e){const n=r.length,i=new r.constructor(n);for(let s=0,o=0;o!==n;++s){const a=e[s]*t;for(let l=0;l!==t;++l)i[o++]=r[a+l]}return i}function so(r,t,e,n){let i=1,s=r[0];for(;s!==void 0&&s[n]===void 0;)s=r[i++];if(s===void 0)return;let o=s[n];if(o!==void 0)if(Array.isArray(o))do o=s[n],o!==void 0&&(t.push(s.time),e.push.apply(e,o)),s=r[i++];while(s!==void 0);else if(o.toArray!==void 0)do o=s[n],o!==void 0&&(t.push(s.time),o.toArray(e,e.length)),s=r[i++];while(s!==void 0);else do o=s[n],o!==void 0&&(t.push(s.time),e.push(o)),s=r[i++];while(s!==void 0)}class cr{constructor(t,e,n,i){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new e.constructor(n),this.sampleValues=e,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(t){const e=this.parameterPositions;let n=this._cachedIndex,i=e[n],s=e[n-1];n:{t:{let o;e:{i:if(!(t=s)){const a=e[1];t=s)break t}o=n,n=0;break e}break n}for(;n>>1;te;)--o;if(++o,s!==0||o!==i){s>=o&&(o=Math.max(o,1),s=o-1);const a=this.getValueSize();this.times=n.slice(s,o),this.values=this.values.slice(s*a,o*a)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const n=this.times,i=this.values,s=n.length;s===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let o=null;for(let a=0;a!==s;a++){const l=n[a];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,a,l),t=!1;break}if(o!==null&&o>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,a,l,o),t=!1;break}o=l}if(i!==void 0&&lf(i))for(let a=0,l=i.length;a!==l;++a){const c=i[a];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,a,c),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===2302,s=t.length-1;let o=1;for(let a=1;a0){t[o]=t[s];for(let a=s*n,l=o*n,c=0;c!==n;++c)e[l+c]=e[a+c];++o}return o!==t.length?(this.times=t.slice(0,o),this.values=e.slice(0,o*n)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),n=this.constructor,i=new n(this.name,t,e);return i.createInterpolant=this.createInterpolant,i}}Ve.prototype.TimeBufferType=Float32Array;Ve.prototype.ValueBufferType=Float32Array;Ve.prototype.DefaultInterpolation=2301;class qn extends Ve{}qn.prototype.ValueTypeName="bool";qn.prototype.ValueBufferType=Array;qn.prototype.DefaultInterpolation=2300;qn.prototype.InterpolantFactoryMethodLinear=void 0;qn.prototype.InterpolantFactoryMethodSmooth=void 0;class ao extends Ve{}ao.prototype.ValueTypeName="color";class ir extends Ve{}ir.prototype.ValueTypeName="number";class ff extends cr{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const s=this.resultBuffer,o=this.sampleValues,a=this.valueSize,l=(n-e)/(i-e);let c=t*a;for(let h=c+a;c!==h;c+=4)Wn.slerpFlat(s,0,o,c-a,o,c,l);return s}}class pi extends Ve{InterpolantFactoryMethodLinear(t){return new ff(this.times,this.values,this.getValueSize(),t)}}pi.prototype.ValueTypeName="quaternion";pi.prototype.DefaultInterpolation=2301;pi.prototype.InterpolantFactoryMethodSmooth=void 0;class Yn extends Ve{}Yn.prototype.ValueTypeName="string";Yn.prototype.ValueBufferType=Array;Yn.prototype.DefaultInterpolation=2300;Yn.prototype.InterpolantFactoryMethodLinear=void 0;Yn.prototype.InterpolantFactoryMethodSmooth=void 0;class rr extends Ve{}rr.prototype.ValueTypeName="vector";class gp{constructor(t,e=-1,n,i=2500){this.name=t,this.tracks=n,this.duration=e,this.blendMode=i,this.uuid=Oe(),this.duration<0&&this.resetDuration()}static parse(t){const e=[],n=t.tracks,i=1/(t.fps||1);for(let o=0,a=n.length;o!==a;++o)e.push(mf(n[o]).scale(i));const s=new this(t.name,t.duration,e,t.blendMode);return s.uuid=t.uuid,s}static toJSON(t){const e=[],n=t.tracks,i={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let s=0,o=n.length;s!==o;++s)e.push(Ve.toJSON(n[s]));return i}static CreateFromMorphTargetSequence(t,e,n,i){const s=e.length,o=[];for(let a=0;a1){const u=h[1];let d=i[u];d||(i[u]=d=[]),d.push(c)}}const o=[];for(const a in i)o.push(this.CreateFromMorphTargetSequence(a,i[a],e,n));return o}static parseAnimation(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(u,d,p,g,v){if(p.length!==0){const m=[],f=[];so(p,m,f,g),m.length!==0&&v.push(new u(d,m,f))}},i=[],s=t.name||"default",o=t.fps||30,a=t.blendMode;let l=t.length||-1;const c=t.hierarchy||[];for(let u=0;u{e&&e(s),this.manager.itemEnd(t)},0),s;if(Ke[t]!==void 0){Ke[t].push({onLoad:e,onProgress:n,onError:i});return}Ke[t]=[],Ke[t].push({onLoad:e,onProgress:n,onError:i});const o=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,l=this.responseType;fetch(o).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const h=Ke[t],u=c.body.getReader(),d=c.headers.get("Content-Length")||c.headers.get("X-File-Size"),p=d?parseInt(d):0,g=p!==0;let v=0;const m=new ReadableStream({start(f){S();function S(){u.read().then(({done:_,value:b})=>{if(_)f.close();else{v+=b.byteLength;const C=new ProgressEvent("progress",{lengthComputable:g,loaded:v,total:p});for(let A=0,w=h.length;A{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(h=>new DOMParser().parseFromString(h,a));case"json":return c.json();default:if(a===void 0)return c.text();{const u=/charset="?([^;"\s]*)"?/i.exec(a),d=u&&u[1]?u[1].toLowerCase():void 0,p=new TextDecoder(d);return c.arrayBuffer().then(g=>p.decode(g))}}}).then(c=>{rn.add(t,c);const h=Ke[t];delete Ke[t];for(let u=0,d=h.length;u{const h=Ke[t];if(h===void 0)throw this.manager.itemError(t),c;delete Ke[t];for(let u=0,d=h.length;u{this.manager.itemEnd(t)}),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}}class Mf extends Kn{constructor(t){super(t)}load(t,e,n,i){this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);const s=this,o=rn.get(t);if(o!==void 0)return s.manager.itemStart(t),setTimeout(function(){e&&e(o),s.manager.itemEnd(t)},0),o;const a=ui("img");function l(){h(),rn.add(t,this),e&&e(this),s.manager.itemEnd(t)}function c(u){h(),i&&i(u),s.manager.itemError(t),s.manager.itemEnd(t)}function h(){a.removeEventListener("load",l,!1),a.removeEventListener("error",c,!1)}return a.addEventListener("load",l,!1),a.addEventListener("error",c,!1),t.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(a.crossOrigin=this.crossOrigin),s.manager.itemStart(t),a.src=t,a}}class _p extends Kn{constructor(t){super(t)}load(t,e,n,i){const s=new ve,o=new Mf(this.manager);return o.setCrossOrigin(this.crossOrigin),o.setPath(this.path),o.load(t,function(a){s.image=a,s.needsUpdate=!0,e!==void 0&&e(s)},n,i),s}}class hr extends re{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new zt(t),this.intensity=e}dispose(){}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,this.groundColor!==void 0&&(e.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(e.object.distance=this.distance),this.angle!==void 0&&(e.object.angle=this.angle),this.decay!==void 0&&(e.object.decay=this.decay),this.penumbra!==void 0&&(e.object.penumbra=this.penumbra),this.shadow!==void 0&&(e.object.shadow=this.shadow.toJSON()),e}}const Xr=new Vt,Ma=new R,Sa=new R;class rs{constructor(t){this.camera=t,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new ct(512,512),this.map=null,this.mapPass=null,this.matrix=new Vt,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Qr,this._frameExtents=new ct(1,1),this._viewportCount=1,this._viewports=[new Jt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,n=this.matrix;Ma.setFromMatrixPosition(t.matrixWorld),e.position.copy(Ma),Sa.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(Sa),e.updateMatrixWorld(),Xr.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Xr),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Xr)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const t={};return this.bias!==0&&(t.bias=this.bias),this.normalBias!==0&&(t.normalBias=this.normalBias),this.radius!==1&&(t.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}class Sf extends rs{constructor(){super(new we(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(t){const e=this.camera,n=Vn*2*t.angle*this.focus,i=this.mapSize.width/this.mapSize.height,s=t.distance||e.far;(n!==e.fov||i!==e.aspect||s!==e.far)&&(e.fov=n,e.aspect=i,e.far=s,e.updateProjectionMatrix()),super.updateMatrices(t)}copy(t){return super.copy(t),this.focus=t.focus,this}}class vp extends hr{constructor(t,e,n=0,i=Math.PI/3,s=0,o=2){super(t,e),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(re.DEFAULT_UP),this.updateMatrix(),this.target=new re,this.distance=n,this.angle=i,this.penumbra=s,this.decay=o,this.map=null,this.shadow=new Sf}get power(){return this.intensity*Math.PI}set power(t){this.intensity=t/Math.PI}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}const ya=new Vt,si=new R,qr=new R;class yf extends rs{constructor(){super(new we(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new ct(4,2),this._viewportCount=6,this._viewports=[new Jt(2,1,1,1),new Jt(0,1,1,1),new Jt(3,1,1,1),new Jt(1,1,1,1),new Jt(3,0,1,1),new Jt(1,0,1,1)],this._cubeDirections=[new R(1,0,0),new R(-1,0,0),new R(0,0,1),new R(0,0,-1),new R(0,1,0),new R(0,-1,0)],this._cubeUps=[new R(0,1,0),new R(0,1,0),new R(0,1,0),new R(0,1,0),new R(0,0,1),new R(0,0,-1)]}updateMatrices(t,e=0){const n=this.camera,i=this.matrix,s=t.distance||n.far;s!==n.far&&(n.far=s,n.updateProjectionMatrix()),si.setFromMatrixPosition(t.matrixWorld),n.position.copy(si),qr.copy(n.position),qr.add(this._cubeDirections[e]),n.up.copy(this._cubeUps[e]),n.lookAt(qr),n.updateMatrixWorld(),i.makeTranslation(-si.x,-si.y,-si.z),ya.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(ya)}}class xp extends hr{constructor(t,e,n=0,i=2){super(t,e),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new yf}get power(){return this.intensity*4*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}class Ef extends rs{constructor(){super(new Oa(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Mp extends hr{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(re.DEFAULT_UP),this.updateMatrix(),this.target=new re,this.shadow=new Ef}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}class Sp extends hr{constructor(t,e){super(t,e),this.isAmbientLight=!0,this.type="AmbientLight"}}class yp{static decodeText(t){if(typeof TextDecoder<"u")return new TextDecoder().decode(t);let e="";for(let n=0,i=t.length;n"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(t){return this.options=t,this}load(t,e,n,i){t===void 0&&(t=""),this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);const s=this,o=rn.get(t);if(o!==void 0){if(s.manager.itemStart(t),o.then){o.then(c=>{e&&e(c),s.manager.itemEnd(t)}).catch(c=>{i&&i(c)});return}return setTimeout(function(){e&&e(o),s.manager.itemEnd(t)},0),o}const a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader;const l=fetch(t,a).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(c){return rn.add(t,c),e&&e(c),s.manager.itemEnd(t),c}).catch(function(c){i&&i(c),rn.remove(t),s.manager.itemError(t),s.manager.itemEnd(t)});rn.add(t,l),s.manager.itemStart(t)}}let ji;class Tf{static getContext(){return ji===void 0&&(ji=new(window.AudioContext||window.webkitAudioContext)),ji}static setContext(t){ji=t}}class Tp extends Kn{constructor(t){super(t)}load(t,e,n,i){const s=this,o=new xf(this.manager);o.setResponseType("arraybuffer"),o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(t,function(l){try{const c=l.slice(0);Tf.getContext().decodeAudioData(c,function(u){e(u)}).catch(a)}catch(c){a(c)}},n,i);function a(l){i?i(l):console.error(l),s.manager.itemError(t)}}}class bp{constructor(t=!0){this.autoStart=t,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Ea(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let t=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const e=Ea();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}}function Ea(){return(typeof performance>"u"?Date:performance).now()}const ss="\\[\\]\\.:\\/",bf=new RegExp("["+ss+"]","g"),as="[^"+ss+"]",Af="[^"+ss.replace("\\.","")+"]",wf=/((?:WC+[\/:])*)/.source.replace("WC",as),Rf=/(WCOD+)?/.source.replace("WCOD",Af),Cf=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",as),Lf=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",as),Pf=new RegExp("^"+wf+Rf+Cf+Lf+"$"),Df=["material","materials","bones","map"];class Uf{constructor(t,e,n){const i=n||Yt.parseTrackName(e);this._targetGroup=t,this._bindings=t.subscribe_(e,i)}getValue(t,e){this.bind();const n=this._targetGroup.nCachedObjects_,i=this._bindings[n];i!==void 0&&i.getValue(t,e)}setValue(t,e){const n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,s=n.length;i!==s;++i)n[i].setValue(t,e)}bind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,n=t.length;e!==n;++e)t[e].bind()}unbind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,n=t.length;e!==n;++e)t[e].unbind()}}class Yt{constructor(t,e,n){this.path=e,this.parsedPath=n||Yt.parseTrackName(e),this.node=Yt.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,n){return t&&t.isAnimationObjectGroup?new Yt.Composite(t,e,n):new Yt(t,e,n)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(bf,"")}static parseTrackName(t){const e=Pf.exec(t);if(e===null)throw new Error("PropertyBinding: Cannot parse trackName: "+t);const n={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){const s=n.nodeName.substring(i+1);Df.indexOf(s)!==-1&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=s)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return n}static findNode(t,e){if(e===void 0||e===""||e==="."||e===-1||e===t.name||e===t.uuid)return t;if(t.skeleton){const n=t.skeleton.getBoneByName(e);if(n!==void 0)return n}if(t.children){const n=function(s){for(let o=0;o