类型:Site模板 · 收录:2026-09-21 12:38:04 · 源码:会员可见
<!doctype html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>menuchi — 面打</title>
<meta name="description" content="menuchi — a workshop carving masks in the old Japanese manner." />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter+Tight:wght@300;400&family=Noto+Serif+JP:wght@400;500&display=swap" rel="stylesheet" />
<link rel="preload" as="image" href="https://images.higgs.ai/?default=1&output=webp&url=https%3A%2F%2Fd8j0ntlcm91z4.cloudfront.net%2Fuser_3GJaYKPxdnQG0Q9O26lu6DPmcHu%2Fhf_20260911_091755_d10337df-41a1-40eb-b426-ece300e6f5dd.png&w=1920&q=85" />
<link rel="preload" as="image" href="https://images.higgs.ai/?default=1&output=webp&url=https%3A%2F%2Fd8j0ntlcm91z4.cloudfront.net%2Fuser_3GJaYKPxdnQG0Q9O26lu6DPmcHu%2Fhf_20260911_091841_01f0c297-6fca-42d6-87fe-da2865d9c364.png&w=1920&q=85" />
<link rel="preload" as="image" href="https://images.higgs.ai/?default=1&output=webp&url=https%3A%2F%2Fd8j0ntlcm91z4.cloudfront.net%2Fuser_3GJaYKPxdnQG0Q9O26lu6DPmcHu%2Fhf_20260911_091846_72c99800-57a9-4d39-80c2-7768d8f4d556.png&w=1920&q=85" />
<link rel="preload" as="image" href="https://images.higgs.ai/?default=1&output=webp&url=https%3A%2F%2Fd8j0ntlcm91z4.cloudfront.net%2Fuser_3GJaYKPxdnQG0Q9O26lu6DPmcHu%2Fhf_20260911_091854_76cd1a76-8b9d-4003-b289-ed39974c5a1e.png&w=1920&q=85" />
<style>
:root {
--bg: #070707;
--ink: #f6efda;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { height: 100%; background: var(--bg); }
body {
color: var(--ink);
font-family: 'Inter Tight', Inter, ui-sans-serif, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
/* The hero is pinned; the page scrolls so the mask can grow into the frame. */
overflow-x: hidden;
}
/* The 3D render fills the frame and bleeds slightly above, as in the design. */
#stage { position: fixed; inset: -28px 0 0 0; z-index: 0; }
.scroll-range { height: 210vh; pointer-events: none; }
#stage canvas { display: block; }
.sr-only {
position: absolute; width: 1px; height: 1px;
margin: -1px; padding: 0; overflow: hidden;
clip-path: inset(50%); white-space: nowrap; border: 0;
}
/* A top strip, not a full-bleed layer. Aligned to the logotype's INK, not its
line box: the glyph ink starts 0.049em below the box top (measured via
canvas text metrics), which is why box-centring always left the burger
visually lower — and by more at bigger sizes. flex-start puts the burger's
top edge at the padding line; .mark's negative top margin pulls the ink up
to the same line.
z-index 70 is above every section (slides 10-40, film 50, finale 60), so
both the burger and the logotype simply live here and are always on top.
That is the whole mechanism — no per-section copies, nothing to sync. */
.hero-chrome {
position: fixed;
inset: 0 0 auto 0;
z-index: 70;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
/* One 24px gutter on both sides, mirroring the left column. */
padding: clamp(0.8rem, 1.6vw, 1.8rem) 24px 0 24px;
pointer-events: none;
}
/* Sits above the canvas, so the mask passes behind it at any scroll position. */
.lede {
position: fixed;
left: 24px;
top: clamp(180px, 37.4vh, 420px);
z-index: 3;
width: 305px;
font-size: 14px;
line-height: 17px;
font-weight: 400;
letter-spacing: -0.03em;
color: var(--ink);
text-wrap: pretty;
}
.menu {
flex: none;
width: 24px; height: 24px;
display: grid; place-items: center;
background: none; border: 0; padding: 0; cursor: pointer;
pointer-events: auto;
color: var(--ink);
opacity: 0.9;
transition: opacity 180ms cubic-bezier(0.16, 1, 0.3, 1);
}
.menu:hover { opacity: 1; }
.menu svg rect { fill: currentColor; }
/* 面打 — "mask carving". Noto Serif JP carries the classical stroke contrast a
Latin script face cannot give these glyphs.
ONE element, living in the fixed header, so it is always on top of every
section and there is nothing to keep in sync. Two optical corrections, both
measured: the glyph ink starts 0.049em below its line box, so the negative
top margin lands the INK on the header's padding line beside the burger;
letter-spacing trails 0.06em after the last glyph, so the negative right
margin lands the ink at the same 24px as the left gutter rather than
visually short of it. */
.mark {
flex: none;
margin-top: -0.049em;
margin-right: -0.06em;
font-family: 'Noto Serif JP', 'Hiragino Mincho ProN', 'Yu Mincho', serif;
font-weight: 500;
font-size: clamp(3.2rem, 6.6vw, 7rem);
line-height: 0.92;
letter-spacing: 0.06em;
color: var(--ink);
}
/* ═══════════════════════════════════════════════════════════════════════════
ELEMENT SLIDES — the diagonal cut, ported from the costa-serenade archive.
An overflow-hidden box grows in WIDTH while rotating toward 45°; the inner
counter-rotates by reading the same variable, so the seam is diagonal but
the picture stays upright. --span is 0.707×(100vw+100vh) plus margin: the
strip reaches fullscreen exactly at --reveal 1 (an eyeballed 220vmax closes
at ~0.53 and wastes half the move).
═══════════════════════════════════════════════════════════════════════════ */
.slide {
--reveal: 0;
--copy: 0;
--zoom: 0;
--exit: 0;
/* 0.75, not the geometric minimum 0.7071: the corner slack at the minimum
is single-digit pixels (measured 6-18px across viewports), and a one-frame
jitter across the coverage threshold flickered the bottom-left corner.
The extra width buys ~50px of slack; coverage completes a touch before
reveal 1 while the rotation carries motion through to the end. */
--span: calc(75vw + 75vh);
position: fixed;
top: 50%;
left: 50%;
width: calc(var(--reveal) * var(--span));
height: var(--span);
transform: translate(-50%, -50%) rotate(calc(var(--reveal) * 45deg));
overflow: hidden;
background: var(--slide-bg);
pointer-events: none;
visibility: hidden;
will-change: width, transform;
}
.slide__inner {
position: absolute;
top: 50%;
left: 50%;
width: 100vw;
height: 100vh;
/* Reads the SAME --reveal as the frame's rotation: one source of truth, the
two can never drift. */
transform: translate(-50%, -50%) rotate(calc(var(--reveal) * -45deg));
background: var(--slide-bg);
}
.slide__mask {
position: absolute;
top: 50%;
left: 50%;
height: 100%;
/* --exit (air only, as the film rises) pulls the mask back and dims it. */
transform: translate(-50%, -50%)
scale(calc((1 + var(--zoom) * 0.24) * (1 - var(--exit) * 0.16)));
filter: brightness(calc(1 - var(--exit) * 0.55));
will-change: transform;
user-select: none;
}
/* Copy — geometry from the 1470×900 Figma frame, verticals as viewport
fractions (heading 296/900, id 648/900), the shared 24px gutter, and the
description/chip on a common 33px baseline. Each item eases over its own
sub-window of --copy, so they arrive in sequence as the scroll advances. */
/* Arrival is --k (per-item window of --copy); departure is --xk (per-item
window of --exit, REVERSE order: chip first, heading last), drifting up as
it leaves. Only the air slide ever gets a non-zero --exit. */
.slide__item {
opacity: calc(var(--k) * (1 - var(--xk, 0)));
transform: translateY(calc((1 - var(--k)) * 22px - var(--xk, 0) * 14px));
}
.slide__head { --xk: clamp(0, calc((var(--exit) - 0.45) / 0.3), 1); }
.slide__id { --xk: clamp(0, calc((var(--exit) - 0.3) / 0.3), 1); }
.slide__desc { --xk: clamp(0, calc((var(--exit) - 0.15) / 0.3), 1); }
.slide__chip { --xk: clamp(0, calc(var(--exit) / 0.3), 1); }
.slide__head {
--k: clamp(0, calc(var(--copy) / 0.35), 1);
position: absolute;
left: 24px;
top: 32.9vh;
width: min(381px, 46vw);
font-size: clamp(34px, 3.4vw, 50px);
line-height: 1;
font-weight: 400;
letter-spacing: -0.03em;
}
.slide__id {
--k: clamp(0, calc((var(--copy) - 0.22) / 0.33), 1);
position: absolute;
left: 24px;
/* Bottom-anchored, as in the Figma frame (232px at the 900px design height);
proportional below that so it clears both the heading above and the
description below on short viewports. */
bottom: min(232px, 25.8vh);
font-size: 20px;
line-height: 1;
letter-spacing: -0.03em;
}
.slide__desc {
--k: clamp(0, calc((var(--copy) - 0.42) / 0.33), 1);
position: absolute;
left: 24px;
bottom: 33px;
width: 305px;
font-size: 14px;
line-height: 17px;
letter-spacing: -0.03em;
text-wrap: pretty;
}
.slide__chip {
--k: clamp(0, calc((var(--copy) - 0.6) / 0.4), 1);
position: absolute;
right: 24px; /* the shared gutter, not the Figma 53px — one rhythm everywhere */
bottom: 33px;
width: 229px;
height: 128px;
overflow: hidden;
}
.slide__chip img { width: 100%; height: 100%; object-fit: cover; display: block; }
/* ═══════════════════════════════════════════════════════════════════════════
FILM — the workshop clip. Fixed above the slides; rises from the bottom on
--enter, holds while --draw traces the outline and --fcopy brings the copy.
═══════════════════════════════════════════════════════════════════════════ */
.film {
--enter: 0;
--fcopy: 0;
position: fixed;
inset: 0;
z-index: 50;
background: #030303;
transform: translate3d(0, calc((1 - var(--enter)) * 100vh), 0);
overflow: hidden;
pointer-events: none;
visibility: hidden;
will-change: transform;
}
.film__video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
/* Never lit before it has painted: 'loadeddata' sets data-ready, so the
section cannot slide up as a black rectangle with a popping video. */
opacity: 0;
transition: opacity 400ms linear;
}
.film[data-ready] .film__video { opacity: 1; }
/* The 30% wash from the design frame, so the copy holds against the footage. */
.film__scrim { position: absolute; inset: 0; background: rgba(3, 3, 3, 0.3); }
.film__item {
opacity: var(--fk);
transform: translateY(calc((1 - var(--fk)) * 22px));
}
/* Same scale as the slides' name (.slide__head, verbatim: 381px box,
clamp(34px, 3.4vw, 50px)) — this screen borrows the site's one heading
voice instead of inventing another. */
.film__head {
--fk: clamp(0, calc(var(--fcopy) / 0.5), 1);
position: absolute;
left: 24px;
top: 13.3vh; /* 120/900, the heading line of the design frame */
width: min(381px, 46vw);
font-size: clamp(34px, 3.4vw, 50px);
line-height: 1;
font-weight: 400;
letter-spacing: -0.03em;
}
.film__desc {
--fk: clamp(0, calc((var(--fcopy) - 0.35) / 0.5), 1);
position: absolute;
right: 24px;
top: 71.9vh; /* 647/900 */
width: 305px;
font-size: 14px;
line-height: 17px;
letter-spacing: -0.03em;
text-wrap: pretty;
}
/* ═══════════════════════════════════════════════════════════════════════════
FINALE — normal flow resumes. Scrolls up OVER the pinned stack, so it needs
only to out-stack the fixed layers (film z50, chrome stays above at 70).
Geometry from the Figma lower band (1470×1116), as percentages.
═══════════════════════════════════════════════════════════════════════════ */
.finale {
position: relative;
z-index: 60;
background: #030303;
height: 75.92vw; /* 1116/1470 */
min-height: 620px;
overflow: hidden;
}
/* --nk is written per element by src/hero/finale.ts, from that element's own
position in the viewport. A single section-wide progress does NOT work here:
the finale is in normal flow, so it rides up with the page and every item's
reveal was spent before the item was on screen (measured: the label and note
reached 100% some 34vh before they cleared the fold). */
.finale__item {
--nk: 0;
opacity: var(--nk);
transform: translateY(calc((1 - var(--nk)) * 26px));
}
.finale__micro {
position: absolute;
left: 50%;
top: 26.3%; /* 293/1116 */
translate: -50% 0;
width: 221px;
font-size: 14px;
line-height: 17px;
text-align: center;
letter-spacing: -0.03em;
}
.finale__head {
position: absolute;
left: 50%;
top: 38.1%; /* 425/1116 */
translate: -50% 0;
width: 74.4vw; /* 1094/1470 */
font-size: 10.2vw; /* 150px at 1470 */
line-height: 0.8;
font-weight: 400;
text-align: center;
letter-spacing: -0.03em;
}
/* The rows trade places on each hop: measured, the two rows sit 9.6vw apart
(141px at 1470 wide), so the top pair drops exactly onto the bottom row's
line and the bottom pair rises onto the top's. All four columns differ, so
nothing collides mid-flight. */
.finale__mask {
--hop: 9.6vw;
position: absolute;
width: 24.7vw; /* 363/1470; height follows the 1.792 ratio */
/* Keyframes own `transform`, so the scroll-in offset uses the individual
`translate` property — the two compose instead of overwriting. */
translate: 0 calc((1 - var(--nk)) * 26px);
transform: none;
animation: finale-hop var(--hop-dur, 2.8s) cubic-bezier(0.33, 0, 0.2, 1)
var(--hop-delay, 0s) infinite;
user-select: none;
}
/* Top row falls, bottom row rises. */
.finale__mask--1, .finale__mask--2 { --hop-to: var(--hop); }
.finale__mask--3, .finale__mask--4 { --hop-to: calc(var(--hop) * -1); }
/* Out-of-phase: distinct durations AND delays, so a big amplitude reads as
four separate creatures rather than one synchronised carousel. */
.finale__mask--1 { --hop-dur: 2.9s; --hop-delay: 0.2s; }
.finale__mask--2 { --hop-dur: 3.4s; --hop-delay: 1.1s; }
.finale__mask--3 { --hop-dur: 2.6s; --hop-delay: 1.9s; }
.finale__mask--4 { --hop-dur: 3.7s; --hop-delay: 2.7s; }
@keyframes finale-hop {
0% { transform: translateY(0); }
16% { transform: translateY(var(--hop-to)); } /* snap across to the other row */
30% { transform: translateY(var(--hop-to)); } /* hang there a beat */
46% { transform: translateY(0); } /* snap back */
100% { transform: translateY(0); } /* long pause before the next tick */
}
.finale__label {
position: absolute;
left: 24px;
bottom: 8.4%; /* 94/1116 above the band bottom, ≈ Figma's 1798 line */
font-size: 20px;
line-height: 1;
letter-spacing: -0.03em;
}
.finale__note {
position: absolute;
right: 24px;
bottom: 8.4%;
width: 305px;
font-size: 14px;
line-height: 17px;
letter-spacing: -0.03em;
text-wrap: pretty;
}
/* Footer breathing room: the page used to end the instant the bottom row
arrived, so it had no scroll left to animate in. Same colour as the finale,
so it reads as space rather than a seam. */
.finale-runway { height: 30vh; background: #030303; }
@media (prefers-reduced-motion: reduce) {
.slide__item, .film__item, .finale__item { transform: none; }
.finale__mask { animation: none; translate: 0 0; }
}
@media (max-width: 720px) {
.slide__chip { display: none; }
.slide__desc { width: min(305px, 74vw); }
.film__desc { width: min(305px, 74vw); top: auto; bottom: 33px; }
.finale { height: auto; min-height: 100vh; padding: 24vh 0 30vh; }
.finale__note { width: min(305px, 60vw); }
}
.menu[aria-expanded='true'] { opacity: 1; }
/* Above the slides, or tuning stops working the moment slide 1 opens. */
.lil-gui { --width: 300px; z-index: 200 !important; }
.lil-gui.hidden { display: none; }
#unsupported[hidden] { display: none; }
#unsupported {
position: fixed; inset: 0; z-index: 6;
display: flex; flex-direction: column; justify-content: center; gap: 1rem;
padding: clamp(1.5rem, 8vw, 6rem);
background: var(--bg);
}
#unsupported h2 { font-size: clamp(1.6rem, 4vw, 2.4rem); font-weight: 300; letter-spacing: -0.02em; }
#unsupported p { color: #8a7f79; max-width: 34rem; line-height: 1.6; }
#unsupported .muted { font-size: 0.85rem; opacity: 0.7; }
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: #ff8a3c; }
@media (max-width: 640px) {
.menu { top: 28px; }
}
</style>
</head>
<body>
<div id="stage" aria-hidden="true"></div>
<h1 class="sr-only">menuchi — 面打</h1>
<header class="hero-chrome">
<button id="menu" class="menu" type="button" aria-label="Open menu" aria-expanded="false">
<svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<rect x="3" y="5" width="18" height="2" rx="1" />
<rect x="3" y="11" width="14" height="2" rx="1" />
<rect x="3" y="17" width="9" height="2" rx="1" />
</svg>
</button>
<span class="mark" aria-hidden="true">面打</span>
</header>
<div id="slides"></div>
<section id="film" class="film" aria-label="The workshop"></section>
<p class="lede">
menuchi carves noh and kagura masks the old way — one block of hinoki, hand
tools, no moulds. Every face is cut once and never copied.
</p>
<div id="unsupported" hidden>
<h2>WebGPU required</h2>
<p>This page renders through <code>WebGPURenderer</code>. Your browser did not expose
<code>navigator.gpu</code>.</p>
<p class="muted">Chrome or Edge 113+, or Safari 18+ with WebGPU enabled.</p>
</div>
<div class="scroll-range" aria-hidden="true"></div>
<footer id="finale" class="finale" aria-label="Closing"></footer>
<div class="finale-runway" aria-hidden="true"></div>
<script type="module">
var FT="1.3.26";function UT(r,e,t){return Math.max(r,Math.min(e,t))}function oN(r,e,t){return(1-t)*r+t*e}function lN(r,e,t,n){return oN(r,e,1-Math.exp(-t*n))}function cN(r,e){return(r%e+e)%e}var uN=class{isRunning=!1;value=0;from=0;to=0;currentTime=0;lerp;duration;easing;onUpdate;advance(r){if(!this.isRunning)return;let e=!1;if(this.duration&&this.easing){this.currentTime+=r;let t=UT(0,this.currentTime/this.duration,1);e=t>=1;let n=e?1:this.easing(t);this.value=this.from+(this.to-this.from)*n}else this.lerp?(this.value=lN(this.value,this.to,this.lerp*60,r),Math.round(this.value)===Math.round(this.to)&&(this.value=this.to,e=!0)):(this.value=this.to,e=!0);e&&this.stop(),this.onUpdate?.(this.value,e)}stop(){this.isRunning=!1}fromTo(r,e,{lerp:t,duration:n,easing:i,onStart:s,onUpdate:a}){this.from=this.value=r,this.to=e,this.lerp=t,this.duration=n,this.easing=i,this.currentTime=0,this.isRunning=!0,s?.(),this.onUpdate=a}};function dN(r,e){let t;return function(...n){clearTimeout(t),t=setTimeout(()=>{t=void 0,r.apply(this,n)},e)}}var hN=class{width=0;height=0;scrollHeight=0;scrollWidth=0;debouncedResize;wrapperResizeObserver;contentResizeObserver;constructor(r,e,{autoResize:t=!0,debounce:n=250}={}){this.wrapper=r,this.content=e,t&&(this.debouncedResize=dN(this.resize,n),this.wrapper instanceof Window?window.addEventListener("resize",this.debouncedResize):(this.wrapperResizeObserver=new ResizeObserver(this.debouncedResize),this.wrapperResizeObserver.observe(this.wrapper)),this.contentResizeObserver=new ResizeObserver(this.debouncedResize),this.contentResizeObserver.observe(this.content)),this.resize()}destroy(){this.wrapperResizeObserver?.disconnect(),this.contentResizeObserver?.disconnect(),this.wrapper===window&&this.debouncedResize&&window.removeEventListener("resize",this.debouncedResize)}resize=()=>{this.onWrapperResize(),this.onContentResize()};onWrapperResize=()=>{this.wrapper instanceof Window?(this.width=window.innerWidth,this.height=window.innerHeight):(this.width=this.wrapper.clientWidth,this.height=this.wrapper.clientHeight)};onContentResize=()=>{this.wrapper instanceof Window?(this.scrollHeight=this.content.scrollHeight,this.scrollWidth=this.content.scrollWidth):(this.scrollHeight=this.wrapper.scrollHeight,this.scrollWidth=this.wrapper.scrollWidth)};get limit(){return{x:this.scrollWidth-this.width,y:this.scrollHeight-this.height}}},OT=class{events={};emit(r,...e){let t=this.events[r]||[];for(let n=0,i=t.length;n<i;n++)t[n]?.(...e)}on(r,e){return this.events[r]?this.events[r].push(e):this.events[r]=[e],()=>{this.events[r]=this.events[r]?.filter(t=>e!==t)}}off(r,e){this.events[r]=this.events[r]?.filter(t=>e!==t)}destroy(){this.events={}}},pN=100/6,na={passive:!1};function LT(r,e){return r===1?pN:r===2?e:1}var fN=class{touchStart={x:0,y:0};lastDelta={x:0,y:0};window={width:0,height:0};emitter=new OT;constructor(r,e={wheelMultiplier:1,touchMultiplier:1}){this.element=r,this.options=e,window.addEventListener("resize",this.onWindowResize),this.onWindowResize(),this.element.addEventListener("wheel",this.onWheel,na),this.element.addEventListener("touchstart",this.onTouchStart,na),this.element.addEventListener("touchmove",this.onTouchMove,na),this.element.addEventListener("touchend",this.onTouchEnd,na)}on(r,e){return this.emitter.on(r,e)}destroy(){this.emitter.destroy(),window.removeEventListener("resize",this.onWindowResize),this.element.removeEventListener("wheel",this.onWheel,na),this.element.removeEventListener("touchstart",this.onTouchStart,na),this.element.removeEventListener("touchmove",this.onTouchMove,na),this.element.removeEventListener("touchend",this.onTouchEnd,na)}onTouchStart=r=>{let{clientX:e,clientY:t}=r.targetTouches?r.targetTouches[0]:r;this.touchStart.x=e,this.touchStart.y=t,this.lastDelta={x:0,y:0},this.emitter.emit("scroll",{deltaX:0,deltaY:0,event:r})};onTouchMove=r=>{let{clientX:e,clientY:t}=r.targetTouches?r.targetTouches[0]:r,n=-(e-this.touchStart.x)*this.options.touchMultiplier,i=-(t-this.touchStart.y)*this.options.touchMultiplier;this.touchStart.x=e,this.touchStart.y=t,this.lastDelta={x:n,y:i},this.emitter.emit("scroll",{deltaX:n,deltaY:i,event:r})};onTouchEnd=r=>{this.emitter.emit("scroll",{deltaX:this.lastDelta.x,deltaY:this.lastDelta.y,event:r})};onWheel=r=>{let{deltaX:e,deltaY:t,deltaMode:n}=r,i=LT(n,this.window.width),s=LT(n,this.window.height);e*=i,t*=s,e*=this.options.wheelMultiplier,t*=this.options.wheelMultiplier,this.emitter.emit("scroll",{deltaX:e,deltaY:t,event:r})};onWindowResize=()=>{this.window={width:window.innerWidth,height:window.innerHeight}}},BT=r=>Math.min(1,1.001-2**(-10*r)),kT=class{_isScrolling=!1;_isStopped=!1;_isLocked=!1;_preventNextNativeScrollEvent=!1;_resetVelocityTimeout=null;_rafId=null;_isDraggingSelection=!1;reducedMotionMediaQuery=window.matchMedia("(prefers-reduced-motion: reduce)");isTouching;isIos;time=0;userData={};lastVelocity=0;velocity=0;direction=0;options;targetScroll;animatedScroll;animate=new uN;emitter=new OT;dimensions;virtualScroll;constructor({wrapper:r=window,content:e=document.documentElement,eventsTarget:t=r,smoothWheel:n=!0,syncTouch:i=!1,syncTouchLerp:s=.075,touchInertiaExponent:a=1.7,duration:o,easing:l,lerp:c=.1,infinite:u=!1,orientation:d="vertical",gestureOrientation:h=d==="horizontal"?"both":"vertical",touchMultiplier:p=1,wheelMultiplier:f=1,autoResize:m=!0,prevent:y,virtualScroll:x,overscroll:b=!0,autoRaf:_=!1,anchors:S=!1,autoToggle:M=!1,allowNestedScroll:w=!1,__experimental__naiveDimensions:T=!1,naiveDimensions:R=T,stopInertiaOnNavigate:D=!1,respectReducedMotion:L=!0}={}){window.lenisVersion=FT,window.lenis||(window.lenis={}),window.lenis.version=FT,d==="horizontal"&&(window.lenis.horizontal=!0),i===!0&&(window.lenis.touch=!0),this.isIos=/(iPad|iPhone|iPod)/g.test(navigator.userAgent),(!r||r===document.documentElement)&&(r=window),typeof o=="number"&&typeof l!="function"?l=BT:typeof l=="function"&&typeof o!="number"&&(o=1),this.options={wrapper:r,content:e,eventsTarget:t,smoothWheel:n,syncTouch:i,syncTouchLerp:s,touchInertiaExponent:a,duration:o,easing:l,lerp:c,infinite:u,gestureOrientation:h,orientation:d,touchMultiplier:p,wheelMultiplier:f,autoResize:m,prevent:y,virtualScroll:x,overscroll:b,autoRaf:_,anchors:S,autoToggle:M,allowNestedScroll:w,naiveDimensions:R,stopInertiaOnNavigate:D,respectReducedMotion:L},this.dimensions=new hN(r,e,{autoResize:m}),this.updateClassName(),this.targetScroll=this.animatedScroll=this.actualScroll,this.options.wrapper.addEventListener("scroll",this.onNativeScroll),this.options.wrapper.addEventListener("scrollend",this.onScrollEnd,{capture:!0}),(this.options.anchors||this.options.stopInertiaOnNavigate)&&this.options.wrapper.addEventListener("click",this.onClick),this.options.wrapper.addEventListener("pointerdown",this.onPointerDown),this.virtualScroll=new fN(t,{touchMultiplier:p,wheelMultiplier:f}),this.virtualScroll.on("scroll",this.onVirtualScroll),this.options.autoToggle&&(this.checkOverflow(),this.rootElement.addEventListener("transitionend",this.onTransitionEnd)),this.options.autoRaf&&(this._rafId=requestAnimationFrame(this.raf))}destroy(){this.emitter.destroy(),this.options.wrapper.removeEventListener("scroll",this.onNativeScroll),this.options.wrapper.removeEventListener("scrollend",this.onScrollEnd,{capture:!0}),this.options.wrapper.removeEventListener("pointerdown",this.onPointerDown),(this.options.anchors||this.options.stopInertiaOnNavigate)&&this.options.wrapper.removeEventListener("click",this.onClick),this.virtualScroll.destroy(),this.dimensions.destroy(),this.cleanUpClassName(),this._rafId&&cancelAnimationFrame(this._rafId)}on(r,e){return this.emitter.on(r,e)}off(r,e){return this.emitter.off(r,e)}onScrollEnd=r=>{r instanceof CustomEvent||(this.isScrolling==="smooth"||this.isScrolling===!1)&&r.stopPropagation()};dispatchScrollendEvent=()=>{this.options.wrapper.dispatchEvent(new CustomEvent("scrollend",{bubbles:this.options.wrapper===window,detail:{lenisScrollEnd:!0}}))};get overflow(){let r=this.isHorizontal?"overflow-x":"overflow-y";return getComputedStyle(this.rootElement)[r]}checkOverflow(){["hidden","clip"].includes(this.overflow)?this.internalStop():this.internalStart()}onTransitionEnd=r=>{r.propertyName?.includes("overflow")&&r.target===this.rootElement&&this.checkOverflow()};setScroll(r){this.isHorizontal?this.options.wrapper.scrollTo({left:r,behavior:"instant"}):this.options.wrapper.scrollTo({top:r,behavior:"instant"})}onClick=r=>{let e=r.composedPath().filter(n=>n instanceof HTMLAnchorElement&&n.href).map(n=>new URL(n.href)),t=new URL(window.location.href);if(this.options.anchors){let n=e.find(i=>t.host===i.host&&t.pathname===i.pathname&&i.hash);if(n){let i=typeof this.options.anchors=="object"&&this.options.anchors?this.options.anchors:void 0,s=decodeURIComponent(n.hash);this.scrollTo(s,i);return}}if(this.options.stopInertiaOnNavigate&&e.some(n=>t.host===n.host&&t.pathname!==n.pathname)){this.reset();return}};onPointerDown=r=>{r.button===1&&this.reset()};isTouchOnSelectionHandle(r){let e=window.getSelection();if(!e||e.isCollapsed||e.rangeCount===0)return!1;let t=r.targetTouches[0]??r.changedTouches[0];if(!t)return!1;let n=e.getRangeAt(0).getClientRects();if(n.length===0)return!1;let i=n[0],s=n[n.length-1],a=40,o=Math.hypot(t.clientX-i.left,t.clientY-i.top)<=a,l=Math.hypot(t.clientX-s.right,t.clientY-s.bottom)<=a;return o||l}onVirtualScroll=r=>{if(typeof this.options.virtualScroll=="function"&&this.options.virtualScroll(r)===!1)return;let{deltaX:e,deltaY:t,event:n}=r;if(this.emitter.emit("virtual-scroll",{deltaX:e,deltaY:t,event:n}),n.ctrlKey||n.lenisStopPropagation)return;let i=n.type.includes("touch"),s=n.type.includes("wheel");if(i&&this.isIos&&(n.type==="touchstart"&&(this._isDraggingSelection=this.isTouchOnSelectionHandle(n)),this._isDraggingSelection)){n.type==="touchend"&&(this._isDraggingSelection=!1);return}this.isTouching=n.type==="touchstart"||n.type==="touchmove";let a=e===0&&t===0;if(this.options.syncTouch&&i&&n.type==="touchstart"&&a&&!this.isStopped&&!this.isLocked){this.reset();return}let o=this.options.gestureOrientation==="vertical"&&t===0||this.options.gestureOrientation==="horizontal"&&e===0;if(a||o)return;let l=n.composedPath();l=l.slice(0,l.indexOf(this.rootElement));let c=this.options.prevent,u=Math.abs(e)>=Math.abs(t)?"horizontal":"vertical";if(l.find(f=>f instanceof HTMLElement&&(typeof c=="function"&&c?.(f)||f.hasAttribute?.("data-lenis-prevent")||u==="vertical"&&f.hasAttribute?.("data-lenis-prevent-vertical")||u==="horizontal"&&f.hasAttribute?.("data-lenis-prevent-horizontal")||i&&f.hasAttribute?.("data-lenis-prevent-touch")||s&&f.hasAttribute?.("data-lenis-prevent-wheel")||this.options.allowNestedScroll&&this.hasNestedScroll(f,{deltaX:e,deltaY:t}))))return;if(this.isStopped||this.isLocked){n.cancelable&&n.preventDefault();return}if(!(this.options.syncTouch&&i||this.options.smoothWheel&&s)){this.isScrolling="native",this.animate.stop(),n.lenisStopPropagation=!0;return}let d=t;this.options.gestureOrientation==="both"?d=Math.abs(t)>Math.abs(e)?t:e:this.options.gestureOrientation==="horizontal"&&(d=e),(!this.options.overscroll||this.options.infinite||this.options.wrapper!==window&&this.limit>0&&(this.animatedScroll>0&&this.animatedScroll<this.limit||this.animatedScroll===0&&t>0||this.animatedScroll===this.limit&&t<0))&&(n.lenisStopPropagation=!0),n.cancelable&&n.preventDefault();let h=i&&this.options.syncTouch,p=i&&n.type==="touchend";p&&(d=Math.sign(d)*Math.abs(this.velocity)**this.options.touchInertiaExponent),this.scrollTo(this.targetScroll+d,{programmatic:!1,...h?{lerp:p?this.options.syncTouchLerp:1}:{lerp:this.options.lerp,duration:this.options.duration,easing:this.options.easing}})};resize(){this.dimensions.resize(),this.animatedScroll=this.targetScroll=this.actualScroll,this.emit()}emit(){this.emitter.emit("scroll",this)}onNativeScroll=()=>{if(this._resetVelocityTimeout!==null&&(clearTimeout(this._resetVelocityTimeout),this._resetVelocityTimeout=null),this._preventNextNativeScrollEvent){this._preventNextNativeScrollEvent=!1;return}if(this.isScrolling===!1||this.isScrolling==="native"){let r=this.animatedScroll;this.animatedScroll=this.targetScroll=this.actualScroll,this.lastVelocity=this.velocity,this.velocity=this.animatedScroll-r,this.direction=Math.sign(this.animatedScroll-r),this.isStopped||(this.isScrolling="native"),this.emit(),this.velocity!==0&&(this._resetVelocityTimeout=setTimeout(()=>{this.lastVelocity=this.velocity,this.velocity=0,this.isScrolling=!1,this.emit()},400))}};reset(){this.isLocked=!1,this.isScrolling=!1,this.animatedScroll=this.targetScroll=this.actualScroll,this.lastVelocity=this.velocity=0,this.animate.stop()}start(){if(this.isStopped){if(this.options.autoToggle){this.rootElement.style.removeProperty("overflow");return}this.internalStart()}}internalStart(){this.isStopped&&(this.reset(),this.isStopped=!1,this.emit())}stop(){if(!this.isStopped){if(this.options.autoToggle){this.rootElement.style.setProperty("overflow","clip");return}this.internalStop()}}internalStop(){this.isStopped||(this.reset(),this.isStopped=!0,this.emit())}raf=r=>{let e=r-(this.time||r);this.time=r,this.animate.advance(e*.001),this.options.autoRaf&&(this._rafId=requestAnimationFrame(this.raf))};scrollTo(r,{offset:e=0,immediate:t=!1,lock:n=!1,programmatic:i=!0,lerp:s=i?this.options.lerp:void 0,duration:a=i?this.options.duration:void 0,easing:o=i?this.options.easing:void 0,onStart:l,onComplete:c,force:u=!1,userData:d}={}){if(this.prefersReducedMotion&&(i?t=!0:(s=1,a=void 0,o=void 0)),(this.isStopped||this.isLocked)&&!u)return;let h=r,p=e;if(typeof h=="string"&&["top","left","start","#"].includes(h))h=0;else if(typeof h=="string"&&["bottom","right","end"].includes(h))h=this.limit;else{let f=null;if(typeof h=="string"?(f=h.startsWith("#")?document.getElementById(h.slice(1)):document.querySelector(h),f||(h==="#top"?h=0:console.warn("Lenis: Target not found",h))):h instanceof HTMLElement&&h?.nodeType&&(f=h),f){if(this.options.wrapper!==window){let S=this.rootElement.getBoundingClientRect();p-=this.isHorizontal?S.left:S.top}let m=f.getBoundingClientRect(),y=getComputedStyle(f),x=this.isHorizontal?Number.parseFloat(y.scrollMarginLeft):Number.parseFloat(y.scrollMarginTop),b=getComputedStyle(this.rootElement),_=this.isHorizontal?Number.parseFloat(b.scrollPaddingLeft):Number.parseFloat(b.scrollPaddingTop);h=(this.isHorizontal?m.left:m.top)+this.animatedScroll-(Number.isNaN(x)?0:x)-(Number.isNaN(_)?0:_)}}if(typeof h=="number"){if(h+=p,this.options.infinite){if(i){this.targetScroll=this.animatedScroll=this.scroll;let f=h-this.animatedScroll;f>this.limit/2?h-=this.limit:f<-this.limit/2&&(h+=this.limit)}}else h=UT(0,h,this.limit);if(h===this.targetScroll){l?.(this),c?.(this);return}if(this.userData=d??{},t){this.animatedScroll=this.targetScroll=h,this.setScroll(this.scroll),this.reset(),this.preventNextNativeScrollEvent(),this.emit(),c?.(this),this.userData={},requestAnimationFrame(()=>{this.dispatchScrollendEvent()});return}i||(this.targetScroll=h),typeof a=="number"&&typeof o!="function"?o=BT:typeof o=="function"&&typeof a!="number"&&(a=1),this.animate.fromTo(this.animatedScroll,h,{duration:a,easing:o,lerp:s,onStart:()=>{n&&(this.isLocked=!0),this.isScrolling="smooth",l?.(this)},onUpdate:(f,m)=>{this.isScrolling="smooth",this.lastVelocity=this.velocity,this.velocity=f-this.animatedScroll,this.direction=Math.sign(this.velocity),this.animatedScroll=f,this.setScroll(this.scroll),i&&(this.targetScroll=f),m||this.emit(),m&&(this.reset(),this.emit(),c?.(this),this.userData={},requestAnimationFrame(()=>{this.dispatchScrollendEvent()}),this.preventNextNativeScrollEvent())}})}}preventNextNativeScrollEvent(){this._preventNextNativeScrollEvent=!0,requestAnimationFrame(()=>{this._preventNextNativeScrollEvent=!1})}hasNestedScroll(r,{deltaX:e,deltaY:t}){let n=Date.now();r._lenis||(r._lenis={});let i=r._lenis,s,a,o,l,c,u,d,h,p,f;if(n-(i.time??0)>2e3){i.time=Date.now();let w=window.getComputedStyle(r);if(i.computedStyle=w,s=["auto","overlay","scroll"].includes(w.overflowX),a=["auto","overlay","scroll"].includes(w.overflowY),c=["auto"].includes(w.overscrollBehaviorX),u=["auto"].includes(w.overscrollBehaviorY),i.hasOverflowX=s,i.hasOverflowY=a,!(s||a))return!1;d=r.scrollWidth,h=r.scrollHeight,p=r.clientWidth,f=r.clientHeight,o=d>p,l=h>f,i.isScrollableX=o,i.isScrollableY=l,i.scrollWidth=d,i.scrollHeight=h,i.clientWidth=p,i.clientHeight=f,i.hasOverscrollBehaviorX=c,i.hasOverscrollBehaviorY=u}else o=i.isScrollableX,l=i.isScrollableY,s=i.hasOverflowX,a=i.hasOverflowY,d=i.scrollWidth,h=i.scrollHeight,p=i.clientWidth,f=i.clientHeight,c=i.hasOverscrollBehaviorX,u=i.hasOverscrollBehaviorY;if(!(s&&o||a&&l))return!1;let m=Math.abs(e)>=Math.abs(t)?"horizontal":"vertical",y,x,b,_,S,M;if(m==="horizontal")y=Math.round(r.scrollLeft),x=d-p,b=e,_=s,S=o,M=c;else if(m==="vertical")y=Math.round(r.scrollTop),x=h-f,b=t,_=a,S=l,M=u;else return!1;return!M&&(y>=x||y<=0)?!0:(b>0?y<x:y>0)&&_&&S}get rootElement(){return this.options.wrapper===window?document.documentElement:this.options.wrapper}get limit(){return this.options.naiveDimensions?this.isHorizontal?this.rootElement.scrollWidth-this.rootElement.clientWidth:this.rootElement.scrollHeight-this.rootElement.clientHeight:this.dimensions.limit[this.isHorizontal?"x":"y"]}get isHorizontal(){return this.options.orientation==="horizontal"}get actualScroll(){let r=this.options.wrapper;return this.isHorizontal?r.scrollX??r.scrollLeft:r.scrollY??r.scrollTop}get scroll(){return this.options.infinite?cN(this.animatedScroll,this.limit):this.animatedScroll}get progress(){return this.limit===0?1:this.scroll/this.limit}get isScrolling(){return this._isScrolling}set isScrolling(r){this._isScrolling!==r&&(this._isScrolling=r,this.updateClassName())}get isStopped(){return this._isStopped}set isStopped(r){this._isStopped!==r&&(this._isStopped=r,this.updateClassName())}get isLocked(){return this._isLocked}set isLocked(r){this._isLocked!==r&&(this._isLocked=r,this.updateClassName())}get isSmooth(){return this.isScrolling==="smooth"}get prefersReducedMotion(){return this.options.respectReducedMotion&&this.reducedMotionMediaQuery.matches}get className(){let r="lenis";return this.options.autoToggle&&(r+=" lenis-autoToggle"),this.isStopped&&(r+=" lenis-stopped"),this.isLocked&&(r+=" lenis-locked"),this.isScrolling&&(r+=" lenis-scrolling"),this.isScrolling==="smooth"&&(r+=" lenis-smooth"),r}updateClassName(){this.cleanUpClassName(),this.className.split(" ").forEach(r=>{this.rootElement.classList.add(r)})}cleanUpClassName(){for(let r of Array.from(this.rootElement.classList))(r==="lenis"||r.startsWith("lenis-"))&&this.rootElement.classList.remove(r)}};var Cr={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Nr={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},O0=0,k0=1,V0=2;var G0=0,Fd=1,z0=2,Ta=3,oi=0,ln=1,Ri=2,_s=0,li=1,Ma=2,wa=3,Ea=4,Ra=5,Ld=6,ci=100,qp=101,$p=102,H0=103,W0=104,Ws=200,Xp=201,Yp=202,jp=203,fo=204,mo=205,Kp=206,Zp=207,Jp=208,Qp=209,ef=210;var Ll=0,Bl=1,Ul=2,ua=3,Ol=4,kl=5,Vl=6,Gl=7,No=0,tf=1,nf=2,Ki=0,Bd=1,Ud=2,Od=3,Aa=4,sf=5,kd=6,Vd=7;var Gd=300,Pr=301,Ca=302,zd=303,Hd=304,Po=306,Ei=1e3,ai=1001,da=1002,vt=1003,rf=1004;var Na=1005;var St=1006,Wd=1007;var bs=1008,q0=1008,Gt=1009,Dr=1010,Ir=1011,qs=1012,zt=1013,it=1014,en=1015,xt=1016,qd=1017,$d=1018,vs=1020,pc=35902,fc=35899,Xd=1021,Pa=1022,bn=1023,ui=1026,Zi=1027,Da=1028,Ia=1029,mi=1030,Fa=1031,Yd=1032,mc=1033,Do=33776,Io=33777,Fo=33778,Lo=33779,jd=35840,Kd=35841,Zd=35842,Jd=35843,gc=36196,yc=37492,xc=37496,_c=37488,bc=37489,Bo=37490,vc=37491,Sc=37808,Tc=37809,Mc=37810,wc=37811,Ec=37812,Rc=37813,Ac=37814,Cc=37815,Nc=37816,Pc=37817,Dc=37818,Ic=37819,Fc=37820,Lc=37821,Bc=36492,Uc=36494,Oc=36495,kc=36283,Vc=36284,Uo=36285,Gc=36286;var zl=2300,zu=2301,Bu=2302,Vp=2303,Gp=2400,zp=2401,Hp=2402;var Ss=0,$0=1,cn="",Vt="srgb",Hl="srgb-linear",Wl="linear",be="srgb",Qd="",af="rg",X0="ga",Y0=0,Sr=7680,j0=7681,K0=7682,Z0=7683,J0=34055,Q0=34056,ey=5386,ty=512,ny=513,iy=514,sy=515,ry=516,ay=517,oy=518,Hu=519,of=512,eh=513,lf=514,Oo=515,zc=516,cf=517,La=518,uf=519,ha=35044,ko=35048;var qn=2e3,di=2001,Ji={COMPUTE:"compute",RENDER:"render"};var Fr={TEXTURE_COMPARE:"depthTextureCompare"};function mN(r){for(let e=r.length-1;e>=0;--e)if(r[e]>=65535)return!0;return!1}function Hc(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function Wu(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function ly(){let r=Wu("canvas");return r.style.display="block",r}var VT={},ql=null;function qu(...r){let e="THREE."+r.shift();ql?ql("log",e,...r):console.log(e,...r)}function m1(r){let e=r[0];if(typeof e=="string"&&e.startsWith("TSL:")){let t=r[1];t&&t.isStackTrace?r[0]+=" "+t.getLocation():r[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return r}function X(...r){r=m1(r);let e="THREE."+r.shift();if(ql)ql("warn",e,...r);else{let t=r[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...r)}}function G(...r){r=m1(r);let e="THREE."+r.shift();if(ql)ql("error",e,...r);else{let t=r[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...r)}}function Ce(...r){let e=r.join(" ");e in VT||(VT[e]=!0,X(...r))}function cy(){return typeof self<"u"&&typeof self.scheduler<"u"&&typeof self.scheduler.yield<"u"?self.scheduler.yield():new Promise(r=>{requestAnimationFrame(r)})}var df={[Ll]:Bl,[Ul]:Vl,[Ol]:Gl,[ua]:kl,[Bl]:Ll,[Vl]:Ul,[Gl]:Ol,[kl]:ua},$n=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let i=n[e];if(i!==void 0){let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let i=n.slice(0);for(let s=0,a=i.length;s<a;s++)i[s].call(this,e);e.target=null}}},Cn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],GT=1234567,Uu=Math.PI/180,pa=180/Math.PI;function zs(){let r=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Cn[r&255]+Cn[r>>8&255]+Cn[r>>16&255]+Cn[r>>24&255]+"-"+Cn[e&255]+Cn[e>>8&255]+"-"+Cn[e>>16&15|64]+Cn[e>>24&255]+"-"+Cn[t&63|128]+Cn[t>>8&255]+"-"+Cn[t>>16&255]+Cn[t>>24&255]+Cn[n&255]+Cn[n>>8&255]+Cn[n>>16&255]+Cn[n>>24&255]).toLowerCase()}function Te(r,e,t){return Math.max(e,Math.min(t,r))}function uy(r,e){return(r%e+e)%e}function gN(r,e,t,n,i){return n+(r-e)*(i-n)/(t-e)}function yN(r,e,t){return r!==e?(t-r)/(e-r):0}function Ou(r,e,t){return(1-t)*r+t*e}function xN(r,e,t,n){return Ou(r,e,1-Math.exp(-t*n))}function _N(r,e=1){return e-Math.abs(uy(r,e*2)-e)}function bN(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*(3-2*r))}function vN(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*r*(r*(r*6-15)+10))}function SN(r,e){return r+Math.floor(Math.random()*(e-r+1))}function TN(r,e){return r+Math.random()*(e-r)}function MN(r){return r*(.5-Math.random())}function wN(r){r!==void 0&&(GT=r);let e=GT+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function EN(r){return r*Uu}function RN(r){return r*pa}function AN(r){return(r&r-1)===0&&r!==0}function CN(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))}function NN(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))}function PN(r,e,t,n,i){let s=Math.cos,a=Math.sin,o=s(t/2),l=a(t/2),c=s((e+n)/2),u=a((e+n)/2),d=s((e-n)/2),h=a((e-n)/2),p=s((n-e)/2),f=a((n-e)/2);switch(i){case"XYX":r.set(o*u,l*d,l*h,o*c);break;case"YZY":r.set(l*h,o*u,l*d,o*c);break;case"ZXZ":r.set(l*d,l*h,o*u,o*c);break;case"XZX":r.set(o*u,l*f,l*p,o*c);break;case"YXY":r.set(l*p,o*u,l*f,o*c);break;case"ZYZ":r.set(l*f,l*p,o*u,o*c);break;default:X("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Wn(r,e){switch(e.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("THREE.MathUtils: Invalid component type.")}}function Ee(r,e){switch(e.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("THREE.MathUtils: Invalid component type.")}}var Dn={DEG2RAD:Uu,RAD2DEG:pa,generateUUID:zs,clamp:Te,euclideanModulo:uy,mapLinear:gN,inverseLerp:yN,lerp:Ou,damp:xN,pingpong:_N,smoothstep:bN,smootherstep:vN,randInt:SN,randFloat:TN,randFloatSpread:MN,seededRandom:wN,degToRad:EN,radToDeg:RN,isPowerOfTwo:AN,ceilPowerOfTwo:CN,floorPowerOfTwo:NN,setQuaternionFromProperEuler:PN,normalize:Ee,denormalize:Wn},O=class r{static{r.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Te(this.x,e.x,t.x),this.y=Te(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Te(this.x,e,t),this.y=Te(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Te(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Te(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),i=Math.sin(t),s=this.x-e.x,a=this.y-e.y;return this.x=s*n-a*i+e.x,this.y=s*i+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},fn=class{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,s,a,o){let l=n[i+0],c=n[i+1],u=n[i+2],d=n[i+3],h=s[a+0],p=s[a+1],f=s[a+2],m=s[a+3];if(d!==m||l!==h||c!==p||u!==f){let y=l*h+c*p+u*f+d*m;y<0&&(h=-h,p=-p,f=-f,m=-m,y=-y);let x=1-o;if(y<.9995){let b=Math.acos(y),_=Math.sin(b);x=Math.sin(x*b)/_,o=Math.sin(o*b)/_,l=l*x+h*o,c=c*x+p*o,u=u*x+f*o,d=d*x+m*o}else{l=l*x+h*o,c=c*x+p*o,u=u*x+f*o,d=d*x+m*o;let b=1/Math.sqrt(l*l+c*c+u*u+d*d);l*=b,c*=b,u*=b,d*=b}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d}static multiplyQuaternionsFlat(e,t,n,i,s,a){let o=n[i],l=n[i+1],c=n[i+2],u=n[i+3],d=s[a],h=s[a+1],p=s[a+2],f=s[a+3];return e[t]=o*f+u*d+l*p-c*h,e[t+1]=l*f+u*h+c*d-o*p,e[t+2]=c*f+u*p+o*h-l*d,e[t+3]=u*f-o*d-l*h-c*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,i=e._y,s=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(n/2),u=o(i/2),d=o(s/2),h=l(n/2),p=l(i/2),f=l(s/2);switch(a){case"XYZ":this._x=h*u*d+c*p*f,this._y=c*p*d-h*u*f,this._z=c*u*f+h*p*d,this._w=c*u*d-h*p*f;break;case"YXZ":this._x=h*u*d+c*p*f,this._y=c*p*d-h*u*f,this._z=c*u*f-h*p*d,this._w=c*u*d+h*p*f;break;case"ZXY":this._x=h*u*d-c*p*f,this._y=c*p*d+h*u*f,this._z=c*u*f+h*p*d,this._w=c*u*d-h*p*f;break;case"ZYX":this._x=h*u*d-c*p*f,this._y=c*p*d+h*u*f,this._z=c*u*f-h*p*d,this._w=c*u*d+h*p*f;break;case"YZX":this._x=h*u*d+c*p*f,this._y=c*p*d+h*u*f,this._z=c*u*f-h*p*d,this._w=c*u*d-h*p*f;break;case"XZY":this._x=h*u*d-c*p*f,this._y=c*p*d-h*u*f,this._z=c*u*f+h*p*d,this._w=c*u*d+h*p*f;break;default:X("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],i=t[4],s=t[8],a=t[1],o=t[5],l=t[9],c=t[2],u=t[6],d=t[10],h=n+o+d;if(h>0){let p=.5/Math.sqrt(h+1);this._w=.25/p,this._x=(u-l)*p,this._y=(s-c)*p,this._z=(a-i)*p}else if(n>o&&n>d){let p=2*Math.sqrt(1+n-o-d);this._w=(u-l)/p,this._x=.25*p,this._y=(i+a)/p,this._z=(s+c)/p}else if(o>d){let p=2*Math.sqrt(1+o-n-d);this._w=(s-c)/p,this._x=(i+a)/p,this._y=.25*p,this._z=(l+u)/p}else{let p=2*Math.sqrt(1+d-n-o);this._w=(a-i)/p,this._x=(s+c)/p,this._y=(l+u)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Te(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,i=e._y,s=e._z,a=e._w,o=t._x,l=t._y,c=t._z,u=t._w;return this._x=n*u+a*o+i*c-s*l,this._y=i*u+a*l+s*o-n*c,this._z=s*u+a*c+n*l-i*o,this._w=a*u-n*o-i*l-s*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,i=e._y,s=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,i=-i,s=-s,a=-a,o=-o);let l=1-t;if(o<.9995){let c=Math.acos(o),u=Math.sin(c);l=Math.sin(l*c)/u,t=Math.sin(t*c)/u,this._x=this._x*l+n*t,this._y=this._y*l+i*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this._onChangeCallback()}else this._x=this._x*l+n*t,this._y=this._y*l+i*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},E=class r{static{r.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(zT.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(zT.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*i,this.y=s[1]*t+s[4]*n+s[7]*i,this.z=s[2]*t+s[5]*n+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,s=e.elements,a=1/(s[3]*t+s[7]*n+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*n+s[8]*i+s[12])*a,this.y=(s[1]*t+s[5]*n+s[9]*i+s[13])*a,this.z=(s[2]*t+s[6]*n+s[10]*i+s[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,i=this.z,s=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*i-o*n),u=2*(o*t-s*i),d=2*(s*n-a*t);return this.x=t+l*c+a*d-o*u,this.y=n+l*u+o*c-s*d,this.z=i+l*d+s*u-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i,this.y=s[1]*t+s[5]*n+s[9]*i,this.z=s[2]*t+s[6]*n+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Te(this.x,e.x,t.x),this.y=Te(this.y,e.y,t.y),this.z=Te(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Te(this.x,e,t),this.y=Te(this.y,e,t),this.z=Te(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Te(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,i=e.y,s=e.z,a=t.x,o=t.y,l=t.z;return this.x=i*l-s*o,this.y=s*a-n*l,this.z=n*o-i*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return a0.copy(this).projectOnVector(e),this.sub(a0)}reflect(e){return this.sub(a0.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Te(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},a0=new E,zT=new fn,ve=class r{static{r.prototype.isMatrix3=!0}constructor(e,t,n,i,s,a,o,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,i,s,a,o,l,c)}set(e,t,n,i,s,a,o,l,c){let u=this.elements;return u[0]=e,u[1]=i,u[2]=o,u[3]=t,u[4]=s,u[5]=l,u[6]=n,u[7]=a,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,s=this.elements,a=n[0],o=n[3],l=n[6],c=n[1],u=n[4],d=n[7],h=n[2],p=n[5],f=n[8],m=i[0],y=i[3],x=i[6],b=i[1],_=i[4],S=i[7],M=i[2],w=i[5],T=i[8];return s[0]=a*m+o*b+l*M,s[3]=a*y+o*_+l*w,s[6]=a*x+o*S+l*T,s[1]=c*m+u*b+d*M,s[4]=c*y+u*_+d*w,s[7]=c*x+u*S+d*T,s[2]=h*m+p*b+f*M,s[5]=h*y+p*_+f*w,s[8]=h*x+p*S+f*T,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],u=e[8];return t*a*u-t*o*c-n*s*u+n*o*l+i*s*c-i*a*l}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=u*a-o*c,h=o*l-u*s,p=c*s-a*l,f=t*d+n*h+i*p;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/f;return e[0]=d*m,e[1]=(i*c-u*n)*m,e[2]=(o*n-i*a)*m,e[3]=h*m,e[4]=(u*t-i*l)*m,e[5]=(i*s-o*t)*m,e[6]=p*m,e[7]=(n*l-c*t)*m,e[8]=(a*t-n*s)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,s,a,o){let l=Math.cos(s),c=Math.sin(s);return this.set(n*l,n*c,-n*(l*a+c*o)+a+e,-i*c,i*l,-i*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return Ce("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(o0.makeScale(e,t)),this}rotate(e){return Ce("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(o0.makeRotation(-e)),this}translate(e,t){return Ce("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(o0.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<9;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},o0=new ve,HT=new ve().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),WT=new ve().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function DN(){let r={enabled:!0,workingColorSpace:Hl,spaces:{},convert:function(i,s,a){return this.enabled===!1||s===a||!s||!a||(this.spaces[s].transfer===be&&(i.r=wr(i.r),i.g=wr(i.g),i.b=wr(i.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(i.applyMatrix3(this.spaces[s].toXYZ),i.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===be&&(i.r=Fl(i.r),i.g=Fl(i.g),i.b=Fl(i.b))),i},workingToColorSpace:function(i,s){return this.convert(i,this.workingColorSpace,s)},colorSpaceToWorking:function(i,s){return this.convert(i,s,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===cn?Wl:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,s=this.workingColorSpace){return i.fromArray(this.spaces[s].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,s,a){return i.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,s){return Ce("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),r.workingToColorSpace(i,s)},toWorkingColorSpace:function(i,s){return Ce("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),r.colorSpaceToWorking(i,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return r.define({[Hl]:{primaries:e,whitePoint:n,transfer:Wl,toXYZ:HT,fromXYZ:WT,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Vt},outputColorSpaceConfig:{drawingBufferColorSpace:Vt}},[Vt]:{primaries:e,whitePoint:n,transfer:be,toXYZ:HT,fromXYZ:WT,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Vt}}}),r}var Fe=DN();function wr(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function Fl(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}var vl,$u=class{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{vl===void 0&&(vl=Wu("canvas")),vl.width=e.width,vl.height=e.height;let i=vl.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),n=vl}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){let t=Wu("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let i=n.getImageData(0,0,e.width,e.height),s=i.data;for(let a=0;a<s.length;a++)s[a]=wr(s[a]/255)*255;return n.putImageData(i,0,0),t}else if(e.data){let t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(wr(t[n]/255)*255):t[n]=wr(t[n]);return{data:t,width:e.width,height:e.height}}else return X("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}},IN=0,go=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:IN++}),this.uuid=zs(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:""},i=this.data;if(i!==null){let s;if(Array.isArray(i)){s=[];for(let a=0,o=i.length;a<o;a++)i[a].isDataTexture?s.push(l0(i[a].image)):s.push(l0(i[a]))}else s=l0(i);n.url=s}return t||(e.images[this.uuid]=n),n}};function l0(r){return typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap?$u.getDataURL(r):r.data?{data:Array.from(r.data),width:r.width,height:r.height,type:r.data.constructor.name}:(X("Texture: Unable to serialize Texture."),{})}var FN=0,c0=new E,mn=class r extends $n{constructor(e=r.DEFAULT_IMAGE,t=r.DEFAULT_MAPPING,n=ai,i=ai,s=St,a=bs,o=bn,l=Gt,c=r.DEFAULT_ANISOTROPY,u=cn){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:FN++}),this.uuid=zs(),this.name="",this.source=new go(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=s,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new O(0,0),this.repeat=new O(1,1),this.center=new O(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ve,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(c0).x}get height(){return this.source.getSize(c0).y}get depth(){return this.source.getSize(c0).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){X(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){X(`Texture.setValues(): property '${t}' does not exist.`);continue}i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Gd)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Ei:e.x=e.x-Math.floor(e.x);break;case ai:e.x=e.x<0?0:1;break;case da:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Ei:e.y=e.y-Math.floor(e.y);break;case ai:e.y=e.y<0?0:1;break;case da:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};mn.DEFAULT_IMAGE=null;mn.DEFAULT_MAPPING=Gd;mn.DEFAULT_ANISOTROPY=1;var Ge=class r{static{r.prototype.isVector4=!0}constructor(e=0,t=0,n=0,i=1){this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*i+a[12]*s,this.y=a[1]*t+a[5]*n+a[9]*i+a[13]*s,this.z=a[2]*t+a[6]*n+a[10]*i+a[14]*s,this.w=a[3]*t+a[7]*n+a[11]*i+a[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,s,l=e.elements,c=l[0],u=l[4],d=l[8],h=l[1],p=l[5],f=l[9],m=l[2],y=l[6],x=l[10];if(Math.abs(u-h)<.01&&Math.abs(d-m)<.01&&Math.abs(f-y)<.01){if(Math.abs(u+h)<.1&&Math.abs(d+m)<.1&&Math.abs(f+y)<.1&&Math.abs(c+p+x-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let _=(c+1)/2,S=(p+1)/2,M=(x+1)/2,w=(u+h)/4,T=(d+m)/4,R=(f+y)/4;return _>S&&_>M?_<.01?(n=0,i=.707106781,s=.707106781):(n=Math.sqrt(_),i=w/n,s=T/n):S>M?S<.01?(n=.707106781,i=0,s=.707106781):(i=Math.sqrt(S),n=w/i,s=R/i):M<.01?(n=.707106781,i=.707106781,s=0):(s=Math.sqrt(M),n=T/s,i=R/s),this.set(n,i,s,t),this}let b=Math.sqrt((y-f)*(y-f)+(d-m)*(d-m)+(h-u)*(h-u));return Math.abs(b)<.001&&(b=1),this.x=(y-f)/b,this.y=(d-m)/b,this.z=(h-u)/b,this.w=Math.acos((c+p+x-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Te(this.x,e.x,t.x),this.y=Te(this.y,e.y,t.y),this.z=Te(this.z,e.z,t.z),this.w=Te(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Te(this.x,e,t),this.y=Te(this.y,e,t),this.z=Te(this.z,e,t),this.w=Te(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Te(n,e,t))}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(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}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(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}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}},Jt=class extends $n{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:St,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Ge(0,0,e,t),this.scissorTest=!1,this.viewport=new Ge(0,0,e,t),this.textures=[];let i={width:e,height:t,depth:n.depth},s=new mn(i),a=n.count;for(let o=0;o<a;o++)this.textures[o]=s.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){let t={minFilter:St,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let i=0,s=this.textures.length;i<s;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=n,this.textures[i].isData3DTexture!==!0&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let i=Object.assign({},e.textures[t].image);this.textures[t].source=new go(i)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}};var Xu=class extends mn{constructor(e=null,t=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=vt,this.minFilter=vt,this.wrapR=ai,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}};var Ne=class r{static{r.prototype.isMatrix4=!0}constructor(e,t,n,i,s,a,o,l,c,u,d,h,p,f,m,y){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,i,s,a,o,l,c,u,d,h,p,f,m,y)}set(e,t,n,i,s,a,o,l,c,u,d,h,p,f,m,y){let x=this.elements;return x[0]=e,x[4]=t,x[8]=n,x[12]=i,x[1]=s,x[5]=a,x[9]=o,x[13]=l,x[2]=c,x[6]=u,x[10]=d,x[14]=h,x[3]=p,x[7]=f,x[11]=m,x[15]=y,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 r().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();let t=this.elements,n=e.elements,i=1/Sl.setFromMatrixColumn(e,0).length(),s=1/Sl.setFromMatrixColumn(e,1).length(),a=1/Sl.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*s,t[5]=n[5]*s,t[6]=n[6]*s,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,i=e.y,s=e.z,a=Math.cos(n),o=Math.sin(n),l=Math.cos(i),c=Math.sin(i),u=Math.cos(s),d=Math.sin(s);if(e.order==="XYZ"){let h=a*u,p=a*d,f=o*u,m=o*d;t[0]=l*u,t[4]=-l*d,t[8]=c,t[1]=p+f*c,t[5]=h-m*c,t[9]=-o*l,t[2]=m-h*c,t[6]=f+p*c,t[10]=a*l}else if(e.order==="YXZ"){let h=l*u,p=l*d,f=c*u,m=c*d;t[0]=h+m*o,t[4]=f*o-p,t[8]=a*c,t[1]=a*d,t[5]=a*u,t[9]=-o,t[2]=p*o-f,t[6]=m+h*o,t[10]=a*l}else if(e.order==="ZXY"){let h=l*u,p=l*d,f=c*u,m=c*d;t[0]=h-m*o,t[4]=-a*d,t[8]=f+p*o,t[1]=p+f*o,t[5]=a*u,t[9]=m-h*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){let h=a*u,p=a*d,f=o*u,m=o*d;t[0]=l*u,t[4]=f*c-p,t[8]=h*c+m,t[1]=l*d,t[5]=m*c+h,t[9]=p*c-f,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){let h=a*l,p=a*c,f=o*l,m=o*c;t[0]=l*u,t[4]=m-h*d,t[8]=f*d+p,t[1]=d,t[5]=a*u,t[9]=-o*u,t[2]=-c*u,t[6]=p*d+f,t[10]=h-m*d}else if(e.order==="XZY"){let h=a*l,p=a*c,f=o*l,m=o*c;t[0]=l*u,t[4]=-d,t[8]=c*u,t[1]=h*d+m,t[5]=a*u,t[9]=p*d-f,t[2]=f*d-p,t[6]=o*u,t[10]=m*d+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(LN,e,BN)}lookAt(e,t,n){let i=this.elements;return Ti.subVectors(e,t),Ti.lengthSq()===0&&(Ti.z=1),Ti.normalize(),ia.crossVectors(n,Ti),ia.lengthSq()===0&&(Math.abs(n.z)===1?Ti.x+=1e-4:Ti.z+=1e-4,Ti.normalize(),ia.crossVectors(n,Ti)),ia.normalize(),yp.crossVectors(Ti,ia),i[0]=ia.x,i[4]=yp.x,i[8]=Ti.x,i[1]=ia.y,i[5]=yp.y,i[9]=Ti.y,i[2]=ia.z,i[6]=yp.z,i[10]=Ti.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,s=this.elements,a=n[0],o=n[4],l=n[8],c=n[12],u=n[1],d=n[5],h=n[9],p=n[13],f=n[2],m=n[6],y=n[10],x=n[14],b=n[3],_=n[7],S=n[11],M=n[15],w=i[0],T=i[4],R=i[8],D=i[12],L=i[1],B=i[5],W=i[9],q=i[13],ce=i[2],k=i[6],j=i[10],ee=i[14],ge=i[3],fe=i[7],he=i[11],ye=i[15];return s[0]=a*w+o*L+l*ce+c*ge,s[4]=a*T+o*B+l*k+c*fe,s[8]=a*R+o*W+l*j+c*he,s[12]=a*D+o*q+l*ee+c*ye,s[1]=u*w+d*L+h*ce+p*ge,s[5]=u*T+d*B+h*k+p*fe,s[9]=u*R+d*W+h*j+p*he,s[13]=u*D+d*q+h*ee+p*ye,s[2]=f*w+m*L+y*ce+x*ge,s[6]=f*T+m*B+y*k+x*fe,s[10]=f*R+m*W+y*j+x*he,s[14]=f*D+m*q+y*ee+x*ye,s[3]=b*w+_*L+S*ce+M*ge,s[7]=b*T+_*B+S*k+M*fe,s[11]=b*R+_*W+S*j+M*he,s[15]=b*D+_*q+S*ee+M*ye,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],i=e[8],s=e[12],a=e[1],o=e[5],l=e[9],c=e[13],u=e[2],d=e[6],h=e[10],p=e[14],f=e[3],m=e[7],y=e[11],x=e[15],b=l*p-c*h,_=o*p-c*d,S=o*h-l*d,M=a*p-c*u,w=a*h-l*u,T=a*d-o*u;return t*(m*b-y*_+x*S)-n*(f*b-y*M+x*w)+i*(f*_-m*M+x*T)-s*(f*S-m*w+y*T)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],i=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],u=e[10];return t*(a*u-o*c)-n*(s*u-o*l)+i*(s*c-a*l)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=e[9],h=e[10],p=e[11],f=e[12],m=e[13],y=e[14],x=e[15],b=t*o-n*a,_=t*l-i*a,S=t*c-s*a,M=n*l-i*o,w=n*c-s*o,T=i*c-s*l,R=u*m-d*f,D=u*y-h*f,L=u*x-p*f,B=d*y-h*m,W=d*x-p*m,q=h*x-p*y,ce=b*q-_*W+S*B+M*L-w*D+T*R;if(ce===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let k=1/ce;return e[0]=(o*q-l*W+c*B)*k,e[1]=(i*W-n*q-s*B)*k,e[2]=(m*T-y*w+x*M)*k,e[3]=(h*w-d*T-p*M)*k,e[4]=(l*L-a*q-c*D)*k,e[5]=(t*q-i*L+s*D)*k,e[6]=(y*S-f*T-x*_)*k,e[7]=(u*T-h*S+p*_)*k,e[8]=(a*W-o*L+c*R)*k,e[9]=(n*L-t*W-s*R)*k,e[10]=(f*w-m*S+x*b)*k,e[11]=(d*S-u*w-p*b)*k,e[12]=(o*D-a*B-l*R)*k,e[13]=(t*B-n*D+i*R)*k,e[14]=(m*_-f*M-y*b)*k,e[15]=(u*M-d*_+h*b)*k,this}scale(e){let t=this.elements,n=e.x,i=e.y,s=e.z;return t[0]*=n,t[4]*=i,t[8]*=s,t[1]*=n,t[5]*=i,t[9]*=s,t[2]*=n,t[6]*=i,t[10]*=s,t[3]*=n,t[7]*=i,t[11]*=s,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),i=Math.sin(t),s=1-n,a=e.x,o=e.y,l=e.z,c=s*a,u=s*o;return this.set(c*a+n,c*o-i*l,c*l+i*o,0,c*o+i*l,u*o+n,u*l-i*a,0,c*l-i*o,u*l+i*a,s*l*l+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,s,a){return this.set(1,n,s,0,e,1,a,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){let i=this.elements,s=t._x,a=t._y,o=t._z,l=t._w,c=s+s,u=a+a,d=o+o,h=s*c,p=s*u,f=s*d,m=a*u,y=a*d,x=o*d,b=l*c,_=l*u,S=l*d,M=n.x,w=n.y,T=n.z;return i[0]=(1-(m+x))*M,i[1]=(p+S)*M,i[2]=(f-_)*M,i[3]=0,i[4]=(p-S)*w,i[5]=(1-(h+x))*w,i[6]=(y+b)*w,i[7]=0,i[8]=(f+_)*T,i[9]=(y-b)*T,i[10]=(1-(h+m))*T,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){let i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];let s=this.determinantAffine();if(s===0)return n.set(1,1,1),t.identity(),this;let a=Sl.set(i[0],i[1],i[2]).length(),o=Sl.set(i[4],i[5],i[6]).length(),l=Sl.set(i[8],i[9],i[10]).length();s<0&&(a=-a),ms.copy(this);let c=1/a,u=1/o,d=1/l;return ms.elements[0]*=c,ms.elements[1]*=c,ms.elements[2]*=c,ms.elements[4]*=u,ms.elements[5]*=u,ms.elements[6]*=u,ms.elements[8]*=d,ms.elements[9]*=d,ms.elements[10]*=d,t.setFromRotationMatrix(ms),n.x=a,n.y=o,n.z=l,this}makePerspective(e,t,n,i,s,a,o=qn,l=!1){let c=this.elements,u=2*s/(t-e),d=2*s/(n-i),h=(t+e)/(t-e),p=(n+i)/(n-i),f,m;if(l)f=s/(a-s),m=a*s/(a-s);else if(o===qn)f=-(a+s)/(a-s),m=-2*a*s/(a-s);else if(o===di)f=-a/(a-s),m=-a*s/(a-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=d,c[9]=p,c[13]=0,c[2]=0,c[6]=0,c[10]=f,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,i,s,a,o=qn,l=!1){let c=this.elements,u=2/(t-e),d=2/(n-i),h=-(t+e)/(t-e),p=-(n+i)/(n-i),f,m;if(l)f=1/(a-s),m=a/(a-s);else if(o===qn)f=-2/(a-s),m=-(a+s)/(a-s);else if(o===di)f=-1/(a-s),m=-s/(a-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=0,c[12]=h,c[1]=0,c[5]=d,c[9]=0,c[13]=p,c[2]=0,c[6]=0,c[10]=f,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},Sl=new E,ms=new Ne,LN=new E(0,0,0),BN=new E(1,1,1),ia=new E,yp=new E,Ti=new E,qT=new Ne,$T=new fn,hi=class r{constructor(e=0,t=0,n=0,i=r.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let i=e.elements,s=i[0],a=i[4],o=i[8],l=i[1],c=i[5],u=i[9],d=i[2],h=i[6],p=i[10];switch(t){case"XYZ":this._y=Math.asin(Te(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,p),this._z=Math.atan2(-a,s)):(this._x=Math.atan2(h,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Te(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,s),this._z=0);break;case"ZXY":this._x=Math.asin(Te(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-d,p),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-Te(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(h,p),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(Te(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-d,s)):(this._x=0,this._y=Math.atan2(o,p));break;case"XZY":this._z=Math.asin(-Te(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(h,c),this._y=Math.atan2(o,s)):(this._x=Math.atan2(-u,p),this._y=0);break;default:X("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return qT.makeRotationFromQuaternion(e),this.setFromRotationMatrix(qT,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return $T.setFromEuler(this),this.setFromQuaternion($T,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};hi.DEFAULT_ORDER="XYZ";var yo=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}},UN=0,XT=new E,Tl=new fn,yr=new Ne,xp=new E,Pu=new E,ON=new E,kN=new fn,YT=new E(1,0,0),jT=new E(0,1,0),KT=new E(0,0,1),ZT={type:"added"},VN={type:"removed"},Ml={type:"childadded",child:null},u0={type:"childremoved",child:null},Qt=class r extends $n{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:UN++}),this.uuid=zs(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=r.DEFAULT_UP.clone();let e=new E,t=new hi,n=new fn,i=new E(1,1,1);function s(){n.setFromEuler(t,!1)}function a(){t.setFromQuaternion(n,void 0,!1)}t._onChange(s),n._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Ne},normalMatrix:{value:new ve}}),this.matrix=new Ne,this.matrixWorld=new Ne,this.matrixAutoUpdate=r.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=r.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new yo,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Tl.setFromAxisAngle(e,t),this.quaternion.multiply(Tl),this}rotateOnWorldAxis(e,t){return Tl.setFromAxisAngle(e,t),this.quaternion.premultiply(Tl),this}rotateX(e){return this.rotateOnAxis(YT,e)}rotateY(e){return this.rotateOnAxis(jT,e)}rotateZ(e){return this.rotateOnAxis(KT,e)}translateOnAxis(e,t){return XT.copy(e).applyQuaternion(this.quaternion),this.position.add(XT.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(YT,e)}translateY(e){return this.translateOnAxis(jT,e)}translateZ(e){return this.translateOnAxis(KT,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(yr.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?xp.copy(e):xp.set(e,t,n);let i=this.parent;this.updateWorldMatrix(!0,!1),Pu.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?yr.lookAt(Pu,xp,this.up):yr.lookAt(xp,Pu,this.up),this.quaternion.setFromRotationMatrix(yr),i&&(yr.extractRotation(i.matrixWorld),Tl.setFromRotationMatrix(yr),this.quaternion.premultiply(Tl.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(G("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(ZT),Ml.child=e,this.dispatchEvent(Ml),Ml.child=null):G("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(VN),u0.child=e,this.dispatchEvent(u0),u0.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),yr.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),yr.multiply(e.parent.matrixWorld)),e.applyMatrix4(yr),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(ZT),Ml.child=e,this.dispatchEvent(Ml),Ml.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,i=this.children.length;n<i;n++){let a=this.children[n].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let i=this.children;for(let s=0,a=i.length;s<a;s++)i[s].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Pu,e,ON),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Pu,kN,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,i=e.z,s=this.matrix.elements;s[12]+=t-s[0]*t-s[4]*n-s[8]*i,s[13]+=n-s[1]*t-s[5]*n-s[9]*i,s[14]+=i-s[2]*t-s[6]*n-s[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t,n=!1){let i=this.parent;if(e===!0&&i!==null&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||n)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,n=!0),t===!0){let s=this.children;for(let a=0,o=s.length;a<o;a++)s[a].updateWorldMatrix(!1,!0,n)}}toJSON(e){let t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});let i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),this.static!==!1&&(i.static=this.static),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.pivot!==null&&(i.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),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.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(o=>({...o})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function s(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let l=o.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c<u;c++){let d=l[c];s(e.shapes,d)}else s(e.shapes,l)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(s(e.materials,this.material[l]));i.material=o}else i.material=s(e.materials,this.material);if(this.children.length>0){i.children=[];for(let o=0;o<this.children.length;o++)i.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let o=0;o<this.animations.length;o++){let l=this.animations[o];i.animations.push(s(e.animations,l))}}if(t){let o=a(e.geometries),l=a(e.materials),c=a(e.textures),u=a(e.images),d=a(e.shapes),h=a(e.skeletons),p=a(e.animations),f=a(e.nodes);o.length>0&&(n.geometries=o),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),u.length>0&&(n.images=u),d.length>0&&(n.shapes=d),h.length>0&&(n.skeletons=h),p.length>0&&(n.animations=p),f.length>0&&(n.nodes=f)}return n.object=i,n;function a(o){let l=[];for(let c in o){let u=o[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){let i=e.children[n];this.add(i.clone())}return this}};Qt.DEFAULT_UP=new E(0,1,0);Qt.DEFAULT_MATRIX_AUTO_UPDATE=!0;Qt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var He=class extends Qt{constructor(){super(),this.isGroup=!0,this.type="Group"}},GN={type:"move"},Yu=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new He,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 He,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new E,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new E),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new He,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new E,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new E,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let i=null,s=null,a=null,o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(let m of e.hand.values()){let y=t.getJointPose(m,n),x=this._getHandJoint(c,m);y!==null&&(x.matrix.fromArray(y.transform.matrix),x.matrix.decompose(x.position,x.rotation,x.scale),x.matrixWorldNeedsUpdate=!0,x.jointRadius=y.radius),x.visible=y!==null}let u=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],h=u.position.distanceTo(d.position),p=.02,f=.005;c.inputState.pinching&&h>p+f?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&h<=p-f&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.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,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));o!==null&&(i=t.getPose(e.targetRaySpace,n),i===null&&s!==null&&(i=s),i!==null&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(GN)))}return o!==null&&(o.visible=i!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new He;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},g1={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},sa={h:0,s:0,l:0},_p={h:0,s:0,l:0};function d0(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+(e-r)*6*t:t<1/2?e:t<2/3?r+(e-r)*6*(2/3-t):r}var me=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Vt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Fe.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=Fe.workingColorSpace){return this.r=e,this.g=t,this.b=n,Fe.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=Fe.workingColorSpace){if(e=uy(e,1),t=Te(t,0,1),n=Te(n,0,1),t===0)this.r=this.g=this.b=n;else{let s=n<=.5?n*(1+t):n+t-n*t,a=2*n-s;this.r=d0(a,s,e+1/3),this.g=d0(a,s,e),this.b=d0(a,s,e-1/3)}return Fe.colorSpaceToWorking(this,i),this}setStyle(e,t=Vt){function n(s){s!==void 0&&parseFloat(s)<1&&X("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(w+)(([^)]*))/.exec(e)){let s,a=i[1],o=i[2];switch(a){case"rgb":case"rgba":if(s=/^s*(d+)s*,s*(d+)s*,s*(d+)s*(?:,s*(d*.?d+)s*)?$/.exec(o))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,t);if(s=/^s*(d+)%s*,s*(d+)%s*,s*(d+)%s*(?:,s*(d*.?d+)s*)?$/.exec(o))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,t);break;case"hsl":case"hsla":if(s=/^s*(d*.?d+)s*,s*(d*.?d+)%s*,s*(d*.?d+)%s*(?:,s*(d*.?d+)s*)?$/.exec(o))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:X("Color: Unknown color model "+e)}}else if(i=/^#([A-Fa-fd]+)$/.exec(e)){let s=i[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);X("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Vt){let n=g1[e.toLowerCase()];return n!==void 0?this.setHex(n,t):X("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=wr(e.r),this.g=wr(e.g),this.b=wr(e.b),this}copyLinearToSRGB(e){return this.r=Fl(e.r),this.g=Fl(e.g),this.b=Fl(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Vt){return Fe.workingToColorSpace(Nn.copy(this),e),Math.round(Te(Nn.r*255,0,255))*65536+Math.round(Te(Nn.g*255,0,255))*256+Math.round(Te(Nn.b*255,0,255))}getHexString(e=Vt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Fe.workingColorSpace){Fe.workingToColorSpace(Nn.copy(this),t);let n=Nn.r,i=Nn.g,s=Nn.b,a=Math.max(n,i,s),o=Math.min(n,i,s),l,c,u=(o+a)/2;if(o===a)l=0,c=0;else{let d=a-o;switch(c=u<=.5?d/(a+o):d/(2-a-o),a){case n:l=(i-s)/d+(i<s?6:0);break;case i:l=(s-n)/d+2;break;case s:l=(n-i)/d+4;break}l/=6}return e.h=l,e.s=c,e.l=u,e}getRGB(e,t=Fe.workingColorSpace){return Fe.workingToColorSpace(Nn.copy(this),t),e.r=Nn.r,e.g=Nn.g,e.b=Nn.b,e}getStyle(e=Vt){Fe.workingToColorSpace(Nn.copy(this),e);let t=Nn.r,n=Nn.g,i=Nn.b;return e!==Vt?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(i*255)})`}offsetHSL(e,t,n){return this.getHSL(sa),this.setHSL(sa.h+e,sa.s+t,sa.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(sa),e.getHSL(_p);let n=Ou(sa.h,_p.h,t),i=Ou(sa.s,_p.s,t),s=Ou(sa.l,_p.l,t);return this.setHSL(n,i,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,i=this.b,s=e.elements;return this.r=s[0]*t+s[3]*n+s[6]*i,this.g=s[1]*t+s[4]*n+s[7]*i,this.b=s[2]*t+s[5]*n+s[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Nn=new me;me.NAMES=g1;var fa=class extends Qt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new hi,this.environmentIntensity=1,this.environmentRotation=new hi,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},gs=new E,xr=new E,h0=new E,_r=new E,wl=new E,El=new E,JT=new E,p0=new E,f0=new E,m0=new E,g0=new Ge,y0=new Ge,x0=new Ge,Tr=class r{constructor(e=new E,t=new E,n=new E){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),gs.subVectors(e,t),i.cross(gs);let s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,t,n,i,s){gs.subVectors(i,t),xr.subVectors(n,t),h0.subVectors(e,t);let a=gs.dot(gs),o=gs.dot(xr),l=gs.dot(h0),c=xr.dot(xr),u=xr.dot(h0),d=a*c-o*o;if(d===0)return s.set(0,0,0),null;let h=1/d,p=(c*l-o*u)*h,f=(a*u-o*l)*h;return s.set(1-p-f,f,p)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,_r)===null?!1:_r.x>=0&&_r.y>=0&&_r.x+_r.y<=1}static getInterpolation(e,t,n,i,s,a,o,l){return this.getBarycoord(e,t,n,i,_r)===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,_r.x),l.addScaledVector(a,_r.y),l.addScaledVector(o,_r.z),l)}static getInterpolatedAttribute(e,t,n,i,s,a){return g0.setScalar(0),y0.setScalar(0),x0.setScalar(0),g0.fromBufferAttribute(e,t),y0.fromBufferAttribute(e,n),x0.fromBufferAttribute(e,i),a.setScalar(0),a.addScaledVector(g0,s.x),a.addScaledVector(y0,s.y),a.addScaledVector(x0,s.z),a}static isFrontFacing(e,t,n,i){return gs.subVectors(n,t),xr.subVectors(e,t),gs.cross(xr).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return gs.subVectors(this.c,this.b),xr.subVectors(this.a,this.b),gs.cross(xr).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return r.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return r.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,s){return r.getInterpolation(e,this.a,this.b,this.c,t,n,i,s)}containsPoint(e){return r.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return r.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,s=this.c,a,o;wl.subVectors(i,n),El.subVectors(s,n),p0.subVectors(e,n);let l=wl.dot(p0),c=El.dot(p0);if(l<=0&&c<=0)return t.copy(n);f0.subVectors(e,i);let u=wl.dot(f0),d=El.dot(f0);if(u>=0&&d<=u)return t.copy(i);let h=l*d-u*c;if(h<=0&&l>=0&&u<=0)return a=l/(l-u),t.copy(n).addScaledVector(wl,a);m0.subVectors(e,s);let p=wl.dot(m0),f=El.dot(m0);if(f>=0&&p<=f)return t.copy(s);let m=p*c-l*f;if(m<=0&&c>=0&&f<=0)return o=c/(c-f),t.copy(n).addScaledVector(El,o);let y=u*f-p*d;if(y<=0&&d-u>=0&&p-f>=0)return JT.subVectors(s,i),o=(d-u)/(d-u+(p-f)),t.copy(i).addScaledVector(JT,o);let x=1/(y+m+h);return a=m*x,o=h*x,t.copy(n).addScaledVector(wl,a).addScaledVector(El,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Yi=class{constructor(e=new E(1/0,1/0,1/0),t=new E(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(ys.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(ys.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=ys.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let s=n.getAttribute("position");if(t===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=s.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,ys):ys.fromBufferAttribute(s,a),ys.applyMatrix4(e.matrixWorld),this.expandByPoint(ys);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),bp.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),bp.copy(n.boundingBox)),bp.applyMatrix4(e.matrixWorld),this.union(bp)}let i=e.children;for(let s=0,a=i.length;s<a;s++)this.expandByObject(i[s],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ys),ys.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Du),vp.subVectors(this.max,Du),Rl.subVectors(e.a,Du),Al.subVectors(e.b,Du),Cl.subVectors(e.c,Du),ra.subVectors(Al,Rl),aa.subVectors(Cl,Al),co.subVectors(Rl,Cl);let t=[0,-ra.z,ra.y,0,-aa.z,aa.y,0,-co.z,co.y,ra.z,0,-ra.x,aa.z,0,-aa.x,co.z,0,-co.x,-ra.y,ra.x,0,-aa.y,aa.x,0,-co.y,co.x,0];return!_0(t,Rl,Al,Cl,vp)||(t=[1,0,0,0,1,0,0,0,1],!_0(t,Rl,Al,Cl,vp))?!1:(Sp.crossVectors(ra,aa),t=[Sp.x,Sp.y,Sp.z],_0(t,Rl,Al,Cl,vp))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ys).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ys).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(br[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),br[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),br[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),br[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),br[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),br[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),br[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),br[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(br),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},br=[new E,new E,new E,new E,new E,new E,new E,new E],ys=new E,bp=new Yi,Rl=new E,Al=new E,Cl=new E,ra=new E,aa=new E,co=new E,Du=new E,vp=new E,Sp=new E,uo=new E;function _0(r,e,t,n,i){for(let s=0,a=r.length-3;s<=a;s+=3){uo.fromArray(r,s);let o=i.x*Math.abs(uo.x)+i.y*Math.abs(uo.y)+i.z*Math.abs(uo.z),l=e.dot(uo),c=t.dot(uo),u=n.dot(uo);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}var Mr=zN();function zN(){let r=new ArrayBuffer(4),e=new Float32Array(r),t=new Uint32Array(r),n=new Uint32Array(512),i=new Uint32Array(512);for(let l=0;l<256;++l){let c=l-127;c<-27?(n[l]=0,n[l|256]=32768,i[l]=24,i[l|256]=24):c<-14?(n[l]=1024>>-c-14,n[l|256]=1024>>-c-14|32768,i[l]=-c-1,i[l|256]=-c-1):c<=15?(n[l]=c+15<<10,n[l|256]=c+15<<10|32768,i[l]=13,i[l|256]=13):c<128?(n[l]=31744,n[l|256]=64512,i[l]=24,i[l|256]=24):(n[l]=31744,n[l|256]=64512,i[l]=13,i[l|256]=13)}let s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;(c&8388608)===0;)c<<=1,u-=8388608;c&=-8388609,u+=947912704,s[l]=c|u}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:n,shiftTable:i,mantissaTable:s,exponentTable:a,offsetTable:o}}function Mi(r){Math.abs(r)>65504&&X("DataUtils.toHalfFloat(): Value out of range."),r=Te(r,-65504,65504),Mr.floatView[0]=r;let e=Mr.uint32View[0],t=e>>23&511;return Mr.baseTable[t]+((e&8388607)>>Mr.shiftTable[t])}function Tp(r){let e=r>>10;return Mr.uint32View[0]=Mr.mantissaTable[Mr.offsetTable[e]+(r&1023)]+Mr.exponentTable[e],Mr.floatView[0]}var Zt=new E,Mp=new O,HN=0,xn=class extends $n{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:HN++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=ha,this.updateRanges=[],this.gpuType=en,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,s=this.itemSize;i<s;i++)this.array[e+i]=t.array[n+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Mp.fromBufferAttribute(this,t),Mp.applyMatrix3(e),this.setXY(t,Mp.x,Mp.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Zt.fromBufferAttribute(this,t),Zt.applyMatrix3(e),this.setXYZ(t,Zt.x,Zt.y,Zt.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Zt.fromBufferAttribute(this,t),Zt.applyMatrix4(e),this.setXYZ(t,Zt.x,Zt.y,Zt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Zt.fromBufferAttribute(this,t),Zt.applyNormalMatrix(e),this.setXYZ(t,Zt.x,Zt.y,Zt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Zt.fromBufferAttribute(this,t),Zt.transformDirection(e),this.setXYZ(t,Zt.x,Zt.y,Zt.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Wn(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Ee(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Wn(t,this.array)),t}setX(e,t){return this.normalized&&(t=Ee(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Wn(t,this.array)),t}setY(e,t){return this.normalized&&(t=Ee(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Wn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Ee(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Wn(t,this.array)),t}setW(e,t){return this.normalized&&(t=Ee(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Ee(t,this.array),n=Ee(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=Ee(t,this.array),n=Ee(n,this.array),i=Ee(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,s){return e*=this.itemSize,this.normalized&&(t=Ee(t,this.array),n=Ee(n,this.array),i=Ee(i,this.array),s=Ee(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==ha&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:"dispose"})}};var $l=class extends xn{constructor(e,t,n){super(new Uint16Array(e),t,n)}};var Xl=class extends xn{constructor(e,t,n){super(new Uint32Array(e),t,n)}},Yl=class extends xn{constructor(e,t,n){super(new Uint16Array(e),t,n),this.isFloat16BufferAttribute=!0}getX(e){let t=Tp(this.array[e*this.itemSize]);return this.normalized&&(t=Wn(t,this.array)),t}setX(e,t){return this.normalized&&(t=Ee(t,this.array)),this.array[e*this.itemSize]=Mi(t),this}getY(e){let t=Tp(this.array[e*this.itemSize+1]);return this.normalized&&(t=Wn(t,this.array)),t}setY(e,t){return this.normalized&&(t=Ee(t,this.array)),this.array[e*this.itemSize+1]=Mi(t),this}getZ(e){let t=Tp(this.array[e*this.itemSize+2]);return this.normalized&&(t=Wn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Ee(t,this.array)),this.array[e*this.itemSize+2]=Mi(t),this}getW(e){let t=Tp(this.array[e*this.itemSize+3]);return this.normalized&&(t=Wn(t,this.array)),t}setW(e,t){return this.normalized&&(t=Ee(t,this.array)),this.array[e*this.itemSize+3]=Mi(t),this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Ee(t,this.array),n=Ee(n,this.array)),this.array[e+0]=Mi(t),this.array[e+1]=Mi(n),this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=Ee(t,this.array),n=Ee(n,this.array),i=Ee(i,this.array)),this.array[e+0]=Mi(t),this.array[e+1]=Mi(n),this.array[e+2]=Mi(i),this}setXYZW(e,t,n,i,s){return e*=this.itemSize,this.normalized&&(t=Ee(t,this.array),n=Ee(n,this.array),i=Ee(i,this.array),s=Ee(s,this.array)),this.array[e+0]=Mi(t),this.array[e+1]=Mi(n),this.array[e+2]=Mi(i),this.array[e+3]=Mi(s),this}},Ve=class extends xn{constructor(e,t,n){super(new Float32Array(e),t,n)}},WN=new Yi,Iu=new E,b0=new E,ma=class{constructor(e=new E,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t!==void 0?n.copy(t):WN.setFromPoints(e).getCenter(n);let i=0;for(let s=0,a=e.length;s<a;s++)i=Math.max(i,n.distanceToSquared(e[s]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Iu.subVectors(e,this.center);let t=Iu.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=(n-this.radius)*.5;this.center.addScaledVector(Iu,i/n),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(b0.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Iu.copy(e.center).add(b0)),this.expandByPoint(Iu.copy(e.center).sub(b0))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},qN=0,Xi=new Ne,v0=new Qt,Nl=new E,wi=new Yi,Fu=new Yi,pn=new E,on=class r extends $n{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:qN++}),this.uuid=zs(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(mN(e)?Xl:$l)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let s=new ve().getNormalMatrix(e);n.applyNormalMatrix(s),n.needsUpdate=!0}let i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return Xi.makeRotationFromQuaternion(e),this.applyMatrix4(Xi),this}rotateX(e){return Xi.makeRotationX(e),this.applyMatrix4(Xi),this}rotateY(e){return Xi.makeRotationY(e),this.applyMatrix4(Xi),this}rotateZ(e){return Xi.makeRotationZ(e),this.applyMatrix4(Xi),this}translate(e,t,n){return Xi.makeTranslation(e,t,n),this.applyMatrix4(Xi),this}scale(e,t,n){return Xi.makeScale(e,t,n),this.applyMatrix4(Xi),this}lookAt(e){return v0.lookAt(e),v0.updateMatrix(),this.applyMatrix4(v0.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Nl).negate(),this.translate(Nl.x,Nl.y,Nl.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let n=[];for(let i=0,s=e.length;i<s;i++){let a=e[i];n.push(a.x,a.y,a.z||0)}this.setAttribute("position",new Ve(n,3))}else{let n=Math.min(e.length,t.count);for(let i=0;i<n;i++){let s=e[i];t.setXYZ(i,s.x,s.y,s.z||0)}e.length>t.count&&X("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Yi);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){G("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new E(-1/0,-1/0,-1/0),new E(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n<i;n++){let s=t[n];wi.setFromBufferAttribute(s),this.morphTargetsRelative?(pn.addVectors(this.boundingBox.min,wi.min),this.boundingBox.expandByPoint(pn),pn.addVectors(this.boundingBox.max,wi.max),this.boundingBox.expandByPoint(pn)):(this.boundingBox.expandByPoint(wi.min),this.boundingBox.expandByPoint(wi.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&G('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new ma);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){G("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new E,1/0);return}if(e){let n=this.boundingSphere.center;if(wi.setFromBufferAttribute(e),t)for(let s=0,a=t.length;s<a;s++){let o=t[s];Fu.setFromBufferAttribute(o),this.morphTargetsRelative?(pn.addVectors(wi.min,Fu.min),wi.expandByPoint(pn),pn.addVectors(wi.max,Fu.max),wi.expandByPoint(pn)):(wi.expandByPoint(Fu.min),wi.expandByPoint(Fu.max))}wi.getCenter(n);let i=0;for(let s=0,a=e.count;s<a;s++)pn.fromBufferAttribute(e,s),i=Math.max(i,n.distanceToSquared(pn));if(t)for(let s=0,a=t.length;s<a;s++){let o=t[s],l=this.morphTargetsRelative;for(let c=0,u=o.count;c<u;c++)pn.fromBufferAttribute(o,c),l&&(Nl.fromBufferAttribute(e,c),pn.add(Nl)),i=Math.max(i,n.distanceToSquared(pn))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&G('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){G("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let n=t.position,i=t.normal,s=t.uv,a=this.getAttribute("tangent");(a===void 0||a.count!==n.count)&&(a=new xn(new Float32Array(4*n.count),4),this.setAttribute("tangent",a));let o=[],l=[];for(let R=0;R<n.count;R++)o[R]=new E,l[R]=new E;let c=new E,u=new E,d=new E,h=new O,p=new O,f=new O,m=new E,y=new E;function x(R,D,L){c.fromBufferAttribute(n,R),u.fromBufferAttribute(n,D),d.fromBufferAttribute(n,L),h.fromBufferAttribute(s,R),p.fromBufferAttribute(s,D),f.fromBufferAttribute(s,L),u.sub(c),d.sub(c),p.sub(h),f.sub(h);let B=1/(p.x*f.y-f.x*p.y);isFinite(B)&&(m.copy(u).multiplyScalar(f.y).addScaledVector(d,-p.y).multiplyScalar(B),y.copy(d).multiplyScalar(p.x).addScaledVector(u,-f.x).multiplyScalar(B),o[R].add(m),o[D].add(m),o[L].add(m),l[R].add(y),l[D].add(y),l[L].add(y))}let b=this.groups;b.length===0&&(b=[{start:0,count:e.count}]);for(let R=0,D=b.length;R<D;++R){let L=b[R],B=L.start,W=L.count;for(let q=B,ce=B+W;q<ce;q+=3)x(e.getX(q+0),e.getX(q+1),e.getX(q+2))}let _=new E,S=new E,M=new E,w=new E;function T(R){M.fromBufferAttribute(i,R),w.copy(M);let D=o[R];_.copy(D),_.sub(M.multiplyScalar(M.dot(D))).normalize(),S.crossVectors(w,D);let B=S.dot(l[R])<0?-1:1;a.setXYZW(R,_.x,_.y,_.z,B)}for(let R=0,D=b.length;R<D;++R){let L=b[R],B=L.start,W=L.count;for(let q=B,ce=B+W;q<ce;q+=3)T(e.getX(q+0)),T(e.getX(q+1)),T(e.getX(q+2))}this._transformed=!0}computeVertexNormals(){let e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0||n.count!==t.count)n=new xn(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let h=0,p=n.count;h<p;h++)n.setXYZ(h,0,0,0);let i=new E,s=new E,a=new E,o=new E,l=new E,c=new E,u=new E,d=new E;if(e)for(let h=0,p=e.count;h<p;h+=3){let f=e.getX(h+0),m=e.getX(h+1),y=e.getX(h+2);i.fromBufferAttribute(t,f),s.fromBufferAttribute(t,m),a.fromBufferAttribute(t,y),u.subVectors(a,s),d.subVectors(i,s),u.cross(d),o.fromBufferAttribute(n,f),l.fromBufferAttribute(n,m),c.fromBufferAttribute(n,y),o.add(u),l.add(u),c.add(u),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(m,l.x,l.y,l.z),n.setXYZ(y,c.x,c.y,c.z)}else for(let h=0,p=t.count;h<p;h+=3)i.fromBufferAttribute(t,h+0),s.fromBufferAttribute(t,h+1),a.fromBufferAttribute(t,h+2),u.subVectors(a,s),d.subVectors(i,s),u.cross(d),n.setXYZ(h+0,u.x,u.y,u.z),n.setXYZ(h+1,u.x,u.y,u.z),n.setXYZ(h+2,u.x,u.y,u.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)pn.fromBufferAttribute(e,t),pn.normalize(),e.setXYZ(t,pn.x,pn.y,pn.z)}toNonIndexed(){function e(o,l){let c=o.array,u=o.itemSize,d=o.normalized,h=new c.constructor(l.length*u),p=0,f=0;for(let m=0,y=l.length;m<y;m++){o.isInterleavedBufferAttribute?p=l[m]*o.data.stride+o.offset:p=l[m]*u;for(let x=0;x<u;x++)h[f++]=c[p++]}return new xn(h,u,d)}if(this.index===null)return X("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let t=new r,n=this.index.array,i=this.attributes;for(let o in i){let l=i[o],c=e(l,n);t.setAttribute(o,c)}let s=this.morphAttributes;for(let o in s){let l=[],c=s[o];for(let u=0,d=c.length;u<d;u++){let h=c[u],p=e(h,n);l.push(p)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;let a=this.groups;for(let o=0,l=a.length;o<l;o++){let c=a[o];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){let e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let l in n){let c=n[l];e.data.attributes[l]=c.toJSON(e.data)}let i={},s=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],u=[];for(let d=0,h=c.length;d<h;d++){let p=c[d];u.push(p.toJSON(e.data))}u.length>0&&(i[l]=u,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let i=e.attributes;for(let c in i){let u=i[c];this.setAttribute(c,u.clone(t))}let s=e.morphAttributes;for(let c in s){let u=[],d=s[c];for(let h=0,p=d.length;h<p;h++)u.push(d[h].clone(t));this.morphAttributes[c]=u}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let c=0,u=a.length;c<u;c++){let d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}},jl=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=ha,this.updateRanges=[],this.version=0,this.uuid=zs()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,s=this.stride;i<s;i++)this.array[e+i]=t.array[n+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=zs()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=zs()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},Hn=new E,ju=class r{constructor(e,t,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)Hn.fromBufferAttribute(this,t),Hn.applyMatrix4(e),this.setXYZ(t,Hn.x,Hn.y,Hn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Hn.fromBufferAttribute(this,t),Hn.applyNormalMatrix(e),this.setXYZ(t,Hn.x,Hn.y,Hn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Hn.fromBufferAttribute(this,t),Hn.transformDirection(e),this.setXYZ(t,Hn.x,Hn.y,Hn.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=Wn(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Ee(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=Ee(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Ee(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Ee(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Ee(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=Wn(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Wn(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Wn(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Wn(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ee(t,this.array),n=Ee(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ee(t,this.array),n=Ee(n,this.array),i=Ee(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this}setXYZW(e,t,n,i,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ee(t,this.array),n=Ee(n,this.array),i=Ee(i,this.array),s=Ee(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this.data.array[e+3]=s,this}clone(e){if(e===void 0){qu("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[i+s])}return new xn(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new r(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){qu("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[i+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},$N=0,_n=class extends $n{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:$N++}),this.uuid=zs(),this.name="",this.type="Material",this.blending=li,this.side=oi,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=fo,this.blendDst=mo,this.blendEquation=ci,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new me(0,0,0),this.blendAlpha=0,this.depthFunc=ua,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Hu,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Sr,this.stencilZFail=Sr,this.stencilZPass=Sr,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){X(`Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){X(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(n):i&&i.isVector2&&n&&n.isVector2||i&&i.isEuler&&n&&n.isEuler||i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,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!==void 0&&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(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),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(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).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(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),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(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).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!==li&&(n.blending=this.blending),this.side!==oi&&(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!==fo&&(n.blendSrc=this.blendSrc),this.blendDst!==mo&&(n.blendDst=this.blendDst),this.blendEquation!==ci&&(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!==ua&&(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!==Hu&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Sr&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Sr&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Sr&&(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.allowOverride===!1&&(n.allowOverride=!1),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){let a=[];for(let o in s){let l=s[o];delete l.metadata,a.push(l)}return a}if(t){let s=i(e.textures),a=i(e.images);s.length>0&&(n.textures=s),a.length>0&&(n.images=a)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new me().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let n=e.normalScale;Array.isArray(n)===!1&&(n=[n,n]),this.normalScale=new O().fromArray(n)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new O().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let i=t.length;n=new Array(i);for(let s=0;s!==i;++s)n[s]=t[s].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},Ku=class extends _n{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new me(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}};var vr=new E,S0=new E,wp=new E,oa=new E,T0=new E,Ep=new E,M0=new E,xo=class{constructor(e=new E,t=new E(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,vr)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=vr.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(vr.copy(this.origin).addScaledVector(this.direction,t),vr.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){S0.copy(e).add(t).multiplyScalar(.5),wp.copy(t).sub(e).normalize(),oa.copy(this.origin).sub(S0);let s=e.distanceTo(t)*.5,a=-this.direction.dot(wp),o=oa.dot(this.direction),l=-oa.dot(wp),c=oa.lengthSq(),u=Math.abs(1-a*a),d,h,p,f;if(u>0)if(d=a*l-o,h=a*o-l,f=s*u,d>=0)if(h>=-f)if(h<=f){let m=1/u;d*=m,h*=m,p=d*(d+a*h+2*o)+h*(a*d+h+2*l)+c}else h=s,d=Math.max(0,-(a*h+o)),p=-d*d+h*(h+2*l)+c;else h=-s,d=Math.max(0,-(a*h+o)),p=-d*d+h*(h+2*l)+c;else h<=-f?(d=Math.max(0,-(-a*s+o)),h=d>0?-s:Math.min(Math.max(-s,-l),s),p=-d*d+h*(h+2*l)+c):h<=f?(d=0,h=Math.min(Math.max(-s,-l),s),p=h*(h+2*l)+c):(d=Math.max(0,-(a*s+o)),h=d>0?s:Math.min(Math.max(-s,-l),s),p=-d*d+h*(h+2*l)+c);else h=a>0?-s:s,d=Math.max(0,-(a*h+o)),p=-d*d+h*(h+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,d),i&&i.copy(S0).addScaledVector(wp,h),p}intersectSphere(e,t){vr.subVectors(e.center,this.origin);let n=vr.dot(this.direction),i=vr.dot(vr)-n*n,s=e.radius*e.radius;if(i>s)return null;let a=Math.sqrt(s-i),o=n-a,l=n+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,s,a,o,l,c=1/this.direction.x,u=1/this.direction.y,d=1/this.direction.z,h=this.origin;return c>=0?(n=(e.min.x-h.x)*c,i=(e.max.x-h.x)*c):(n=(e.max.x-h.x)*c,i=(e.min.x-h.x)*c),u>=0?(s=(e.min.y-h.y)*u,a=(e.max.y-h.y)*u):(s=(e.max.y-h.y)*u,a=(e.min.y-h.y)*u),n>a||s>i||((s>n||isNaN(n))&&(n=s),(a<i||isNaN(i))&&(i=a),d>=0?(o=(e.min.z-h.z)*d,l=(e.max.z-h.z)*d):(o=(e.max.z-h.z)*d,l=(e.min.z-h.z)*d),n>l||o>i)||((o>n||n!==n)&&(n=o),(l<i||i!==i)&&(i=l),i<0)?null:this.at(n>=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,vr)!==null}intersectTriangle(e,t,n,i,s){T0.subVectors(t,e),Ep.subVectors(n,e),M0.crossVectors(T0,Ep);let a=this.direction.dot(M0),o;if(a>0){if(i)return null;o=1}else if(a<0)o=-1,a=-a;else return null;oa.subVectors(this.origin,e);let l=o*this.direction.dot(Ep.crossVectors(oa,Ep));if(l<0)return null;let c=o*this.direction.dot(T0.cross(oa));if(c<0||l+c>a)return null;let u=-o*oa.dot(M0);return u<0?null:this.at(u/a,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},ji=class extends _n{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new me(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hi,this.combine=No,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},QT=new Ne,ho=new xo,Rp=new ma,e1=new E,Ap=new E,Cp=new E,Np=new E,w0=new E,Pp=new E,t1=new E,Dp=new E,De=class extends Qt{constructor(e=new on,t=new ji){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=i.length;s<a;s++){let o=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}getVertexPosition(e,t){let n=this.geometry,i=n.attributes.position,s=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(i,e);let o=this.morphTargetInfluences;if(s&&o){Pp.set(0,0,0);for(let l=0,c=s.length;l<c;l++){let u=o[l],d=s[l];u!==0&&(w0.fromBufferAttribute(d,e),a?Pp.addScaledVector(w0,u):Pp.addScaledVector(w0.sub(t),u))}t.add(Pp)}return t}raycast(e,t){let n=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Rp.copy(n.boundingSphere),Rp.applyMatrix4(s),ho.copy(e.ray).recast(e.near),!(Rp.containsPoint(ho.origin)===!1&&(ho.intersectSphere(Rp,e1)===null||ho.origin.distanceToSquared(e1)>(e.far-e.near)**2))&&(QT.copy(s).invert(),ho.copy(e.ray).applyMatrix4(QT),!(n.boundingBox!==null&&ho.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,ho)))}_computeIntersections(e,t,n){let i,s=this.geometry,a=this.material,o=s.index,l=s.attributes.position,c=s.attributes.uv,u=s.attributes.uv1,d=s.attributes.normal,h=s.groups,p=s.drawRange;if(o!==null)if(Array.isArray(a))for(let f=0,m=h.length;f<m;f++){let y=h[f],x=a[y.materialIndex],b=Math.max(y.start,p.start),_=Math.min(o.count,Math.min(y.start+y.count,p.start+p.count));for(let S=b,M=_;S<M;S+=3){let w=o.getX(S),T=o.getX(S+1),R=o.getX(S+2);i=Ip(this,x,e,n,c,u,d,w,T,R),i&&(i.faceIndex=Math.floor(S/3),i.face.materialIndex=y.materialIndex,t.push(i))}}else{let f=Math.max(0,p.start),m=Math.min(o.count,p.start+p.count);for(let y=f,x=m;y<x;y+=3){let b=o.getX(y),_=o.getX(y+1),S=o.getX(y+2);i=Ip(this,a,e,n,c,u,d,b,_,S),i&&(i.faceIndex=Math.floor(y/3),t.push(i))}}else if(l!==void 0)if(Array.isArray(a))for(let f=0,m=h.length;f<m;f++){let y=h[f],x=a[y.materialIndex],b=Math.max(y.start,p.start),_=Math.min(l.count,Math.min(y.start+y.count,p.start+p.count));for(let S=b,M=_;S<M;S+=3){let w=S,T=S+1,R=S+2;i=Ip(this,x,e,n,c,u,d,w,T,R),i&&(i.faceIndex=Math.floor(S/3),i.face.materialIndex=y.materialIndex,t.push(i))}}else{let f=Math.max(0,p.start),m=Math.min(l.count,p.start+p.count);for(let y=f,x=m;y<x;y+=3){let b=y,_=y+1,S=y+2;i=Ip(this,a,e,n,c,u,d,b,_,S),i&&(i.faceIndex=Math.floor(y/3),t.push(i))}}}};function XN(r,e,t,n,i,s,a,o){let l;if(e.side===ln?l=n.intersectTriangle(a,s,i,!0,o):l=n.intersectTriangle(i,s,a,e.side===oi,o),l===null)return null;Dp.copy(o),Dp.applyMatrix4(r.matrixWorld);let c=t.ray.origin.distanceTo(Dp);return c<t.near||c>t.far?null:{distance:c,point:Dp.clone(),object:r}}function Ip(r,e,t,n,i,s,a,o,l,c){r.getVertexPosition(o,Ap),r.getVertexPosition(l,Cp),r.getVertexPosition(c,Np);let u=XN(r,e,t,n,Ap,Cp,Np,t1);if(u){let d=new E;Tr.getBarycoord(t1,Ap,Cp,Np,d),i&&(u.uv=Tr.getInterpolatedAttribute(i,o,l,c,d,new O)),s&&(u.uv1=Tr.getInterpolatedAttribute(s,o,l,c,d,new O)),a&&(u.normal=Tr.getInterpolatedAttribute(a,o,l,c,d,new E),u.normal.dot(n.direction)>0&&u.normal.multiplyScalar(-1));let h={a:o,b:l,c,normal:new E,materialIndex:0};Tr.getNormal(Ap,Cp,Np,h.normal),u.face=h,u.barycoord=d}return u}var ga=class extends mn{constructor(e=null,t=1,n=1,i,s,a,o,l,c=vt,u=vt,d,h){super(null,a,o,l,c,u,i,s,d,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};var Hs=class extends xn{constructor(e,t,n,i=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}};var E0=new E,YN=new E,jN=new ve,ri=class{constructor(e=new E(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let i=E0.subVectors(n,t).cross(YN.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let i=e.delta(E0),s=this.normal.dot(i);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/s;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||jN.getNormalMatrix(e),i=this.coplanarPoint(E0).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},po=new ma,KN=new O(.5,.5),Fp=new E,ya=class{constructor(e=new ri,t=new ri,n=new ri,i=new ri,s=new ri,a=new ri){this.planes=[e,t,n,i,s,a]}set(e,t,n,i,s,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(i),o[4].copy(s),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=qn,n=!1){let i=this.planes,s=e.elements,a=s[0],o=s[1],l=s[2],c=s[3],u=s[4],d=s[5],h=s[6],p=s[7],f=s[8],m=s[9],y=s[10],x=s[11],b=s[12],_=s[13],S=s[14],M=s[15];if(i[0].setComponents(c-a,p-u,x-f,M-b).normalize(),i[1].setComponents(c+a,p+u,x+f,M+b).normalize(),i[2].setComponents(c+o,p+d,x+m,M+_).normalize(),i[3].setComponents(c-o,p-d,x-m,M-_).normalize(),n)i[4].setComponents(l,h,y,S).normalize(),i[5].setComponents(c-l,p-h,x-y,M-S).normalize();else if(i[4].setComponents(c-l,p-h,x-y,M-S).normalize(),t===qn)i[5].setComponents(c+l,p+h,x+y,M+S).normalize();else if(t===di)i[5].setComponents(l,h,y,S).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),po.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),po.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(po)}intersectsSprite(e){po.center.set(0,0,0);let t=KN.distanceTo(e.center);return po.radius=.7071067811865476+t,po.applyMatrix4(e.matrixWorld),this.intersectsSphere(po)}intersectsSphere(e){let t=this.planes,n=e.center,i=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(n)<i)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let i=t[n];if(Fp.x=i.normal.x>0?e.max.x:e.min.x,Fp.y=i.normal.y>0?e.max.y:e.min.y,Fp.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Fp)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},n1=new Ne,Zu=class r{constructor(){this.coordinateSystem=qn,this._frustums=[],this._count=0}setFromArrayCamera(e){let t=e.cameras,n=this._frustums;for(let i=0;i<t.length;i++){let s=t[i];n1.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse),n[i]===void 0&&(n[i]=new ya),n[i].setFromProjectionMatrix(n1,s.coordinateSystem,s.reversedDepth)}return this._count=t.length,this}intersectsObject(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsObject(e))return!0;return!1}intersectsSprite(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsSprite(e))return!0;return!1}intersectsSphere(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsSphere(e))return!0;return!1}intersectsBox(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsBox(e))return!0;return!1}containsPoint(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].containsPoint(e))return!0;return!1}copy(e){this.coordinateSystem=e.coordinateSystem;let t=this._frustums,n=e._frustums;for(let i=0;i<e._count;i++)t[i]===void 0&&(t[i]=new ya),t[i].copy(n[i]);return this._count=e._count,this}clone(){return new r().copy(this)}};var Kl=class extends _n{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new me(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}};var Ju=class extends _n{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new me(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}};var _o=class extends mn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=vt,this.minFilter=vt,this.generateMipmaps=!1,this.needsUpdate=!0}};var xa=class extends mn{constructor(e=[],t=Pr,n,i,s,a,o,l,c,u){super(e,t,n,i,s,a,o,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},_a=class extends mn{constructor(e,t,n,i,s,a,o,l,c){super(e,t,n,i,s,a,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}};var Pn=class extends mn{constructor(e,t,n=it,i,s,a,o=vt,l=vt,c,u=ui,d=1){if(u!==ui&&u!==Zi)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let h={width:e,height:t,depth:d};super(h,i,s,a,o,l,u,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new go(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},Qu=class extends Pn{constructor(e,t=it,n=Pr,i,s,a=vt,o=vt,l,c=ui){let u={width:e,height:e,depth:1},d=[u,u,u,u,u,u];super(e,e,t,n,i,s,a,o,l,c),this.image=d,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}};var Zl=class r extends on{constructor(e=1,t=1,n=1,i=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:s,depthSegments:a};let o=this;i=Math.floor(i),s=Math.floor(s),a=Math.floor(a);let l=[],c=[],u=[],d=[],h=0,p=0;f("z","y","x",-1,-1,n,t,e,a,s,0),f("z","y","x",1,-1,n,t,-e,a,s,1),f("x","z","y",1,1,e,n,t,i,a,2),f("x","z","y",1,-1,e,n,-t,i,a,3),f("x","y","z",1,-1,e,t,n,i,s,4),f("x","y","z",-1,-1,e,t,-n,i,s,5),this.setIndex(l),this.setAttribute("position",new Ve(c,3)),this.setAttribute("normal",new Ve(u,3)),this.setAttribute("uv",new Ve(d,2));function f(m,y,x,b,_,S,M,w,T,R,D){let L=S/T,B=M/R,W=S/2,q=M/2,ce=w/2,k=T+1,j=R+1,ee=0,ge=0,fe=new E;for(let he=0;he<j;he++){let ye=he*B-q;for(let ze=0;ze<k;ze++){let Pe=ze*L-W;fe[m]=Pe*b,fe[y]=ye*_,fe[x]=ce,c.push(fe.x,fe.y,fe.z),fe[m]=0,fe[y]=0,fe[x]=w>0?1:-1,u.push(fe.x,fe.y,fe.z),d.push(ze/T),d.push(1-he/R),ee+=1}}for(let he=0;he<R;he++)for(let ye=0;ye<T;ye++){let ze=h+ye+k*he,Pe=h+ye+k*(he+1),ot=h+(ye+1)+k*(he+1),Se=h+(ye+1)+k*he;l.push(ze,Pe,Se),l.push(Pe,ot,Se),ge+=6}o.addGroup(p,ge,D),p+=ge,h+=ee}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}};var Jl=class r extends on{constructor(e=1,t=32,n=0,i=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:n,thetaLength:i},t=Math.max(3,t);let s=[],a=[],o=[],l=[],c=new E,u=new O;a.push(0,0,0),o.push(0,0,1),l.push(.5,.5);for(let d=0,h=3;d<=t;d++,h+=3){let p=n+d/t*i;c.x=e*Math.cos(p),c.y=e*Math.sin(p),a.push(c.x,c.y,c.z),o.push(0,0,1),u.x=(a[h]/e+1)/2,u.y=(a[h+1]/e+1)/2,l.push(u.x,u.y)}for(let d=1;d<=t;d++)s.push(d,d+1,0);this.setIndex(s),this.setAttribute("position",new Ve(a,3)),this.setAttribute("normal",new Ve(o,3)),this.setAttribute("uv",new Ve(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radius,e.segments,e.thetaStart,e.thetaLength)}},Pt=class r extends on{constructor(e=1,t=1,n=1,i=32,s=1,a=!1,o=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:i,heightSegments:s,openEnded:a,thetaStart:o,thetaLength:l};let c=this;i=Math.floor(i),s=Math.floor(s);let u=[],d=[],h=[],p=[],f=0,m=[],y=n/2,x=0;b(),a===!1&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(u),this.setAttribute("position",new Ve(d,3)),this.setAttribute("normal",new Ve(h,3)),this.setAttribute("uv",new Ve(p,2));function b(){let S=new E,M=new E,w=0,T=(t-e)/n;for(let R=0;R<=s;R++){let D=[],L=R/s,B=L*(t-e)+e;for(let W=0;W<=i;W++){let q=W/i,ce=q*l+o,k=Math.sin(ce),j=Math.cos(ce);M.x=B*k,M.y=-L*n+y,M.z=B*j,d.push(M.x,M.y,M.z),S.set(k,T,j).normalize(),h.push(S.x,S.y,S.z),p.push(q,1-L),D.push(f++)}m.push(D)}for(let R=0;R<i;R++)for(let D=0;D<s;D++){let L=m[D][R],B=m[D+1][R],W=m[D+1][R+1],q=m[D][R+1];(e>0||D!==0)&&(u.push(L,B,q),w+=3),(t>0||D!==s-1)&&(u.push(B,W,q),w+=3)}c.addGroup(x,w,0),x+=w}function _(S){let M=f,w=new O,T=new E,R=0,D=S===!0?e:t,L=S===!0?1:-1;for(let W=1;W<=i;W++)d.push(0,y*L,0),h.push(0,L,0),p.push(.5,.5),f++;let B=f;for(let W=0;W<=i;W++){let ce=W/i*l+o,k=Math.cos(ce),j=Math.sin(ce);T.x=D*j,T.y=y*L,T.z=D*k,d.push(T.x,T.y,T.z),h.push(0,L,0),w.x=k*.5+.5,w.y=j*.5*L+.5,p.push(w.x,w.y),f++}for(let W=0;W<i;W++){let q=M+W,ce=B+W;S===!0?u.push(ce,ce+1,q):u.push(ce+1,ce,q),R+=3}c.addGroup(x,R,S===!0?1:2),x+=R}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}};var pi=class{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){X("Curve: .getPoint() not implemented.")}getPointAt(e,t){let n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){let t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){let t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){let e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;let t=[],n,i=this.getPoint(0),s=0;t.push(0);for(let a=1;a<=e;a++)n=this.getPoint(a/e),s+=n.distanceTo(i),t.push(s),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){let n=this.getLengths(),i=0,s=n.length,a;t?a=t:a=e*n[s-1];let o=0,l=s-1,c;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),c=n[i]-a,c<0)o=i+1;else if(c>0)l=i-1;else{l=i;break}if(i=l,n[i]===a)return i/(s-1);let u=n[i],h=n[i+1]-u,p=(a-u)/h;return(i+p)/(s-1)}getTangent(e,t){let i=e-1e-4,s=e+1e-4;i<0&&(i=0),s>1&&(s=1);let a=this.getPoint(i),o=this.getPoint(s),l=t||(a.isVector2?new O:new E);return l.copy(o).sub(a).normalize(),l}getTangentAt(e,t){let n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){let n=new E,i=[],s=[],a=[],o=new E,l=new Ne;for(let p=0;p<=e;p++){let f=p/e;i[p]=this.getTangentAt(f,new E)}s[0]=new E,a[0]=new E;let c=Number.MAX_VALUE,u=Math.abs(i[0].x),d=Math.abs(i[0].y),h=Math.abs(i[0].z);u<=c&&(c=u,n.set(1,0,0)),d<=c&&(c=d,n.set(0,1,0)),h<=c&&n.set(0,0,1),o.crossVectors(i[0],n).normalize(),s[0].crossVectors(i[0],o),a[0].crossVectors(i[0],s[0]);for(let p=1;p<=e;p++){if(s[p]=s[p-1].clone(),a[p]=a[p-1].clone(),o.crossVectors(i[p-1],i[p]),o.length()>Number.EPSILON){o.normalize();let f=Math.acos(Te(i[p-1].dot(i[p]),-1,1));s[p].applyMatrix4(l.makeRotationAxis(o,f))}a[p].crossVectors(i[p],s[p])}if(t===!0){let p=Math.acos(Te(s[0].dot(s[e]),-1,1));p/=e,i[0].dot(o.crossVectors(s[0],s[e]))>0&&(p=-p);for(let f=1;f<=e;f++)s[f].applyMatrix4(l.makeRotationAxis(i[f],p*f)),a[f].crossVectors(i[f],s[f])}return{tangents:i,normals:s,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){let e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}},bo=class extends pi{constructor(e=0,t=0,n=1,i=1,s=0,a=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=s,this.aEndAngle=a,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new O){let n=t,i=Math.PI*2,s=this.aEndAngle-this.aStartAngle,a=Math.abs(s)<Number.EPSILON;for(;s<0;)s+=i;for(;s>i;)s-=i;s<Number.EPSILON&&(a?s=0:s=i),this.aClockwise===!0&&!a&&(s===i?s=-i:s=s-i);let o=this.aStartAngle+e*s,l=this.aX+this.xRadius*Math.cos(o),c=this.aY+this.yRadius*Math.sin(o);if(this.aRotation!==0){let u=Math.cos(this.aRotation),d=Math.sin(this.aRotation),h=l-this.aX,p=c-this.aY;l=h*u-p*d+this.aX,c=h*d+p*u+this.aY}return n.set(l,c)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){let e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}},ed=class extends bo{constructor(e,t,n,i,s,a){super(e,t,n,n,i,s,a),this.isArcCurve=!0,this.type="ArcCurve"}};function dy(){let r=0,e=0,t=0,n=0;function i(s,a,o,l){r=s,e=o,t=-3*s+3*a-2*o-l,n=2*s-2*a+o+l}return{initCatmullRom:function(s,a,o,l,c){i(a,o,c*(o-s),c*(l-a))},initNonuniformCatmullRom:function(s,a,o,l,c,u,d){let h=(a-s)/c-(o-s)/(c+u)+(o-a)/u,p=(o-a)/u-(l-a)/(u+d)+(l-o)/d;h*=u,p*=u,i(a,o,h,p)},calc:function(s){let a=s*s,o=a*s;return r+e*s+t*a+n*o}}}var i1=new E,s1=new E,R0=new dy,A0=new dy,C0=new dy,vo=class extends pi{constructor(e=[],t=!1,n="centripetal",i=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=e,this.closed=t,this.curveType=n,this.tension=i}getPoint(e,t=new E){let n=t,i=this.points,s=i.length,a=(s-(this.closed?0:1))*e,o=Math.floor(a),l=a-o;this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/s)+1)*s:l===0&&o===s-1&&(o=s-2,l=1);let c,u;this.closed||o>0?c=i[(o-1)%s]:(s1.subVectors(i[0],i[1]).add(i[0]),c=s1);let d=i[o%s],h=i[(o+1)%s];if(this.closed||o+2<s?u=i[(o+2)%s]:(i1.subVectors(i[s-1],i[s-2]).add(i[s-1]),u=i1),this.curveType==="centripetal"||this.curveType==="chordal"){let p=this.curveType==="chordal"?.5:.25,f=Math.pow(c.distanceToSquared(d),p),m=Math.pow(d.distanceToSquared(h),p),y=Math.pow(h.distanceToSquared(u),p);m<1e-4&&(m=1),f<1e-4&&(f=m),y<1e-4&&(y=m),R0.initNonuniformCatmullRom(c.x,d.x,h.x,u.x,f,m,y),A0.initNonuniformCatmullRom(c.y,d.y,h.y,u.y,f,m,y),C0.initNonuniformCatmullRom(c.z,d.z,h.z,u.z,f,m,y)}else this.curveType==="catmullrom"&&(R0.initCatmullRom(c.x,d.x,h.x,u.x,this.tension),A0.initCatmullRom(c.y,d.y,h.y,u.y,this.tension),C0.initCatmullRom(c.z,d.z,h.z,u.z,this.tension));return n.set(R0.calc(l),A0.calc(l),C0.calc(l)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let i=e.points[t];this.points.push(i.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){let e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){let i=this.points[t];e.points.push(i.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let i=e.points[t];this.points.push(new E().fromArray(i))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}};function r1(r,e,t,n,i){let s=(n-e)*.5,a=(i-t)*.5,o=r*r,l=r*o;return(2*t-2*n+s+a)*l+(-3*t+3*n-2*s-a)*o+s*r+t}function ZN(r,e){let t=1-r;return t*t*e}function JN(r,e){return 2*(1-r)*r*e}function QN(r,e){return r*r*e}function ku(r,e,t,n){return ZN(r,e)+JN(r,t)+QN(r,n)}function e2(r,e){let t=1-r;return t*t*t*e}function t2(r,e){let t=1-r;return 3*t*t*r*e}function n2(r,e){return 3*(1-r)*r*r*e}function i2(r,e){return r*r*r*e}function Vu(r,e,t,n,i){return e2(r,e)+t2(r,t)+n2(r,n)+i2(r,i)}var Ql=class extends pi{constructor(e=new O,t=new O,n=new O,i=new O){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new O){let n=t,i=this.v0,s=this.v1,a=this.v2,o=this.v3;return n.set(Vu(e,i.x,s.x,a.x,o.x),Vu(e,i.y,s.y,a.y,o.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}},td=class extends pi{constructor(e=new E,t=new E,n=new E,i=new E){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new E){let n=t,i=this.v0,s=this.v1,a=this.v2,o=this.v3;return n.set(Vu(e,i.x,s.x,a.x,o.x),Vu(e,i.y,s.y,a.y,o.y),Vu(e,i.z,s.z,a.z,o.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}},ec=class extends pi{constructor(e=new O,t=new O){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new O){let n=t;return e===1?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new O){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},nd=class extends pi{constructor(e=new E,t=new E){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new E){let n=t;return e===1?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new E){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},tc=class extends pi{constructor(e=new O,t=new O,n=new O){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new O){let n=t,i=this.v0,s=this.v1,a=this.v2;return n.set(ku(e,i.x,s.x,a.x),ku(e,i.y,s.y,a.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},nc=class extends pi{constructor(e=new E,t=new E,n=new E){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new E){let n=t,i=this.v0,s=this.v1,a=this.v2;return n.set(ku(e,i.x,s.x,a.x),ku(e,i.y,s.y,a.y),ku(e,i.z,s.z,a.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},ic=class extends pi{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new O){let n=t,i=this.points,s=(i.length-1)*e,a=Math.floor(s),o=s-a,l=i[a===0?a:a-1],c=i[a],u=i[a>i.length-2?i.length-1:a+1],d=i[a>i.length-3?i.length-1:a+2];return n.set(r1(o,l.x,c.x,u.x,d.x),r1(o,l.y,c.y,u.y,d.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let i=e.points[t];this.points.push(i.clone())}return this}toJSON(){let e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){let i=this.points[t];e.points.push(i.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let i=e.points[t];this.points.push(new O().fromArray(i))}return this}},Wp=Object.freeze({__proto__:null,ArcCurve:ed,CatmullRomCurve3:vo,CubicBezierCurve:Ql,CubicBezierCurve3:td,EllipseCurve:bo,LineCurve:ec,LineCurve3:nd,QuadraticBezierCurve:tc,QuadraticBezierCurve3:nc,SplineCurve:ic}),id=class extends pi{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(e){this.curves.push(e)}closePath(){let e=this.curves[0].getPoint(0),t=this.curves[this.curves.length-1].getPoint(1);if(!e.equals(t)){let n=e.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new Wp[n](t,e))}return this}getPoint(e,t){let n=e*this.getLength(),i=this.getCurveLengths(),s=0;for(;s<i.length;){if(i[s]>=n){let a=i[s]-n,o=this.curves[s],l=o.getLength(),c=l===0?0:1-a/l;return o.getPointAt(c,t)}s++}return null}getLength(){let e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let e=[],t=0;for(let n=0,i=this.curves.length;n<i;n++)t+=this.curves[n].getLength(),e.push(t);return this.cacheLengths=e,e}getSpacedPoints(e=40){let t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return this.autoClose&&t.push(t[0]),t}getPoints(e=12){let t=[],n;for(let i=0,s=this.curves;i<s.length;i++){let a=s[i],o=a.isEllipseCurve?e*2:a.isLineCurve||a.isLineCurve3?1:a.isSplineCurve?e*a.points.length:e,l=a.getPoints(o);for(let c=0;c<l.length;c++){let u=l[c];n&&n.equals(u)||(t.push(u),n=u)}}return this.autoClose&&t.length>1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t<n;t++){let i=e.curves[t];this.curves.push(i.clone())}return this.autoClose=e.autoClose,this}toJSON(){let e=super.toJSON();e.autoClose=this.autoClose,e.curves=[];for(let t=0,n=this.curves.length;t<n;t++){let i=this.curves[t];e.curves.push(i.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.autoClose=e.autoClose,this.curves=[];for(let t=0,n=e.curves.length;t<n;t++){let i=e.curves[t];this.curves.push(new Wp[i.type]().fromJSON(i))}return this}},ba=class extends id{constructor(e){super(),this.type="Path",this.currentPoint=new O,e&&this.setFromPoints(e)}setFromPoints(e){this.moveTo(e[0].x,e[0].y);for(let t=1,n=e.length;t<n;t++)this.lineTo(e[t].x,e[t].y);return this}moveTo(e,t){return this.currentPoint.set(e,t),this}lineTo(e,t){let n=new ec(this.currentPoint.clone(),new O(e,t));return this.curves.push(n),this.currentPoint.set(e,t),this}quadraticCurveTo(e,t,n,i){let s=new tc(this.currentPoint.clone(),new O(e,t),new O(n,i));return this.curves.push(s),this.currentPoint.set(n,i),this}bezierCurveTo(e,t,n,i,s,a){let o=new Ql(this.currentPoint.clone(),new O(e,t),new O(n,i),new O(s,a));return this.curves.push(o),this.currentPoint.set(s,a),this}splineThru(e){let t=[this.currentPoint.clone()].concat(e),n=new ic(t);return this.curves.push(n),this.currentPoint.copy(e[e.length-1]),this}arc(e,t,n,i,s,a){let o=this.currentPoint.x,l=this.currentPoint.y;return this.absarc(e+o,t+l,n,i,s,a),this}absarc(e,t,n,i,s,a){return this.absellipse(e,t,n,n,i,s,a),this}ellipse(e,t,n,i,s,a,o,l){let c=this.currentPoint.x,u=this.currentPoint.y;return this.absellipse(e+c,t+u,n,i,s,a,o,l),this}absellipse(e,t,n,i,s,a,o,l){let c=new bo(e,t,n,i,s,a,o,l);if(this.curves.length>0){let d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);let u=c.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){let e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}},So=class extends ba{constructor(e){super(e),this.uuid=zs(),this.type="Shape",this.holes=[]}getPointsHoles(e){let t=[];for(let n=0,i=this.holes.length;n<i;n++)t[n]=this.holes[n].getPoints(e);return t}extractPoints(e){return{shape:this.getPoints(e),holes:this.getPointsHoles(e)}}copy(e){super.copy(e),this.holes=[];for(let t=0,n=e.holes.length;t<n;t++){let i=e.holes[t];this.holes.push(i.clone())}return this}toJSON(){let e=super.toJSON();e.uuid=this.uuid,e.holes=[];for(let t=0,n=this.holes.length;t<n;t++){let i=this.holes[t];e.holes.push(i.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.uuid=e.uuid,this.holes=[];for(let t=0,n=e.holes.length;t<n;t++){let i=e.holes[t];this.holes.push(new ba().fromJSON(i))}return this}};function s2(r,e,t=2){let n=e&&e.length,i=n?e[0]*t:r.length,s=y1(r,0,i,t,!0),a=[];if(!s||s.next===s.prev)return a;let o,l,c;if(n&&(s=c2(r,e,s,t)),r.length>80*t){o=r[0],l=r[1];let u=o,d=l;for(let h=t;h<i;h+=t){let p=r[h],f=r[h+1];p<o&&(o=p),f<l&&(l=f),p>u&&(u=p),f>d&&(d=f)}c=Math.max(u-o,d-l),c=c!==0?32767/c:0}return sd(s,a,t,o,l,c,0),a}function y1(r,e,t,n,i){let s;if(i===b2(r,e,t,n)>0)for(let a=e;a<t;a+=n)s=a1(a/n|0,r[a],r[a+1],s);else for(let a=t-n;a>=e;a-=n)s=a1(a/n|0,r[a],r[a+1],s);return s&&sc(s,s.next)&&(ad(s),s=s.next),s}function To(r,e){if(!r)return r;e||(e=r);let t=r,n;do if(n=!1,!t.steiner&&(sc(t,t.next)||Nt(t.prev,t,t.next)===0)){if(ad(t),t=e=t.prev,t===t.next)break;n=!0}else t=t.next;while(n||t!==e);return e}function sd(r,e,t,n,i,s,a){if(!r)return;!a&&s&&f2(r,n,i,s);let o=r;for(;r.prev!==r.next;){let l=r.prev,c=r.next;if(s?a2(r,n,i,s):r2(r)){e.push(l.i,r.i,c.i),ad(r),r=c.next,o=c.next;continue}if(r=c,r===o){a?a===1?(r=o2(To(r),e),sd(r,e,t,n,i,s,2)):a===2&&l2(r,e,t,n,i,s):sd(To(r),e,t,n,i,s,1);break}}}function r2(r){let e=r.prev,t=r,n=r.next;if(Nt(e,t,n)>=0)return!1;let i=e.x,s=t.x,a=n.x,o=e.y,l=t.y,c=n.y,u=Math.min(i,s,a),d=Math.min(o,l,c),h=Math.max(i,s,a),p=Math.max(o,l,c),f=n.next;for(;f!==e;){if(f.x>=u&&f.x<=h&&f.y>=d&&f.y<=p&&Lu(i,o,s,l,a,c,f.x,f.y)&&Nt(f.prev,f,f.next)>=0)return!1;f=f.next}return!0}function a2(r,e,t,n){let i=r.prev,s=r,a=r.next;if(Nt(i,s,a)>=0)return!1;let o=i.x,l=s.x,c=a.x,u=i.y,d=s.y,h=a.y,p=Math.min(o,l,c),f=Math.min(u,d,h),m=Math.max(o,l,c),y=Math.max(u,d,h),x=P0(p,f,e,t,n),b=P0(m,y,e,t,n),_=r.prevZ,S=r.nextZ;for(;_&&_.z>=x&&S&&S.z<=b;){if(_.x>=p&&_.x<=m&&_.y>=f&&_.y<=y&&_!==i&&_!==a&&Lu(o,u,l,d,c,h,_.x,_.y)&&Nt(_.prev,_,_.next)>=0||(_=_.prevZ,S.x>=p&&S.x<=m&&S.y>=f&&S.y<=y&&S!==i&&S!==a&&Lu(o,u,l,d,c,h,S.x,S.y)&&Nt(S.prev,S,S.next)>=0))return!1;S=S.nextZ}for(;_&&_.z>=x;){if(_.x>=p&&_.x<=m&&_.y>=f&&_.y<=y&&_!==i&&_!==a&&Lu(o,u,l,d,c,h,_.x,_.y)&&Nt(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;S&&S.z<=b;){if(S.x>=p&&S.x<=m&&S.y>=f&&S.y<=y&&S!==i&&S!==a&&Lu(o,u,l,d,c,h,S.x,S.y)&&Nt(S.prev,S,S.next)>=0)return!1;S=S.nextZ}return!0}function o2(r,e){let t=r;do{let n=t.prev,i=t.next.next;!sc(n,i)&&_1(n,t,t.next,i)&&rd(n,i)&&rd(i,n)&&(e.push(n.i,t.i,i.i),ad(t),ad(t.next),t=r=i),t=t.next}while(t!==r);return To(t)}function l2(r,e,t,n,i,s){let a=r;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&y2(a,o)){let l=b1(a,o);a=To(a,a.next),l=To(l,l.next),sd(a,e,t,n,i,s,0),sd(l,e,t,n,i,s,0);return}o=o.next}a=a.next}while(a!==r)}function c2(r,e,t,n){let i=[];for(let s=0,a=e.length;s<a;s++){let o=e[s]*n,l=s<a-1?e[s+1]*n:r.length,c=y1(r,o,l,n,!1);c===c.next&&(c.steiner=!0),i.push(g2(c))}i.sort(u2);for(let s=0;s<i.length;s++)t=d2(i[s],t);return t}function u2(r,e){let t=r.x-e.x;if(t===0&&(t=r.y-e.y,t===0)){let n=(r.next.y-r.y)/(r.next.x-r.x),i=(e.next.y-e.y)/(e.next.x-e.x);t=n-i}return t}function d2(r,e){let t=h2(r,e);if(!t)return e;let n=b1(t,r);return To(n,n.next),To(t,t.next)}function h2(r,e){let t=e,n=r.x,i=r.y,s=-1/0,a;if(sc(r,t))return t;do{if(sc(r,t.next))return t.next;if(i<=t.y&&i>=t.next.y&&t.next.y!==t.y){let d=t.x+(i-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=n&&d>s&&(s=d,a=t.x<t.next.x?t:t.next,d===n))return a}t=t.next}while(t!==e);if(!a)return null;let o=a,l=a.x,c=a.y,u=1/0;t=a;do{if(n>=t.x&&t.x>=l&&n!==t.x&&x1(i<c?n:s,i,l,c,i<c?s:n,i,t.x,t.y)){let d=Math.abs(i-t.y)/(n-t.x);rd(t,r)&&(d<u||d===u&&(t.x>a.x||t.x===a.x&&p2(a,t)))&&(a=t,u=d)}t=t.next}while(t!==o);return a}function p2(r,e){return Nt(r.prev,r,e.prev)<0&&Nt(e.next,r,r.next)<0}function f2(r,e,t,n){let i=r;do i.z===0&&(i.z=P0(i.x,i.y,e,t,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==r);i.prevZ.nextZ=null,i.prevZ=null,m2(i)}function m2(r){let e,t=1;do{let n=r,i;r=null;let s=null;for(e=0;n;){e++;let a=n,o=0;for(let c=0;c<t&&(o++,a=a.nextZ,!!a);c++);let l=t;for(;o>0||l>0&&a;)o!==0&&(l===0||!a||n.z<=a.z)?(i=n,n=n.nextZ,o--):(i=a,a=a.nextZ,l--),s?s.nextZ=i:r=i,i.prevZ=s,s=i;n=a}s.nextZ=null,t*=2}while(e>1);return r}function P0(r,e,t,n,i){return r=(r-t)*i|0,e=(e-n)*i|0,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,r|e<<1}function g2(r){let e=r,t=r;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==r);return t}function x1(r,e,t,n,i,s,a,o){return(i-a)*(e-o)>=(r-a)*(s-o)&&(r-a)*(n-o)>=(t-a)*(e-o)&&(t-a)*(s-o)>=(i-a)*(n-o)}function Lu(r,e,t,n,i,s,a,o){return!(r===a&&e===o)&&x1(r,e,t,n,i,s,a,o)}function y2(r,e){return r.next.i!==e.i&&r.prev.i!==e.i&&!x2(r,e)&&(rd(r,e)&&rd(e,r)&&_2(r,e)&&(Nt(r.prev,r,e.prev)||Nt(r,e.prev,e))||sc(r,e)&&Nt(r.prev,r,r.next)>0&&Nt(e.prev,e,e.next)>0)}function Nt(r,e,t){return(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y)}function sc(r,e){return r.x===e.x&&r.y===e.y}function _1(r,e,t,n){let i=Bp(Nt(r,e,t)),s=Bp(Nt(r,e,n)),a=Bp(Nt(t,n,r)),o=Bp(Nt(t,n,e));return!!(i!==s&&a!==o||i===0&&Lp(r,t,e)||s===0&&Lp(r,n,e)||a===0&&Lp(t,r,n)||o===0&&Lp(t,e,n))}function Lp(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function Bp(r){return r>0?1:r<0?-1:0}function x2(r,e){let t=r;do{if(t.i!==r.i&&t.next.i!==r.i&&t.i!==e.i&&t.next.i!==e.i&&_1(t,t.next,r,e))return!0;t=t.next}while(t!==r);return!1}function rd(r,e){return Nt(r.prev,r,r.next)<0?Nt(r,e,r.next)>=0&&Nt(r,r.prev,e)>=0:Nt(r,e,r.prev)<0||Nt(r,r.next,e)<0}function _2(r,e){let t=r,n=!1,i=(r.x+e.x)/2,s=(r.y+e.y)/2;do t.y>s!=t.next.y>s&&t.next.y!==t.y&&i<(t.next.x-t.x)*(s-t.y)/(t.next.y-t.y)+t.x&&(n=!n),t=t.next;while(t!==r);return n}function b1(r,e){let t=D0(r.i,r.x,r.y),n=D0(e.i,e.x,e.y),i=r.next,s=e.prev;return r.next=e,e.prev=r,t.next=i,i.prev=t,n.next=t,t.prev=n,s.next=n,n.prev=s,n}function a1(r,e,t,n){let i=D0(r,e,t);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function ad(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ)}function D0(r,e,t){return{i:r,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function b2(r,e,t,n){let i=0;for(let s=e,a=t-n;s<t;s+=n)i+=(r[a]-r[s])*(r[s+1]+r[a+1]),a=s;return i}var I0=class{static triangulate(e,t,n=2){return s2(e,t,n)}},ca=class r{static area(e){let t=e.length,n=0;for(let i=t-1,s=0;s<t;i=s++)n+=e[i].x*e[s].y-e[s].x*e[i].y;return n*.5}static isClockWise(e){return r.area(e)<0}static triangulateShape(e,t){let n=[],i=[],s=[];o1(e),l1(n,e);let a=e.length;t.forEach(o1);for(let l=0;l<t.length;l++)i.push(a),a+=t[l].length,l1(n,t[l]);let o=I0.triangulate(n,i);for(let l=0;l<o.length;l+=3)s.push(o.slice(l,l+3));return s}};function o1(r){let e=r.length;e>2&&r[e-1].equals(r[0])&&r.pop()}function l1(r,e){for(let t=0;t<e.length;t++)r.push(e[t].x),r.push(e[t].y)}var rc=class r extends on{constructor(e=new So([new O(.5,.5),new O(-.5,.5),new O(-.5,-.5),new O(.5,-.5)]),t={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:e,options:t},e=Array.isArray(e)?e:[e];let n=this,i=[],s=[];for(let o=0,l=e.length;o<l;o++){let c=e[o];a(c)}this.setAttribute("position",new Ve(i,3)),this.setAttribute("uv",new Ve(s,2)),this.computeVertexNormals();function a(o){let l=[],c=t.curveSegments!==void 0?t.curveSegments:12,u=t.steps!==void 0?t.steps:1,d=t.depth!==void 0?t.depth:1,h=t.bevelEnabled!==void 0?t.bevelEnabled:!0,p=t.bevelThickness!==void 0?t.bevelThickness:.2,f=t.bevelSize!==void 0?t.bevelSize:p-.1,m=t.bevelOffset!==void 0?t.bevelOffset:0,y=t.bevelSegments!==void 0?t.bevelSegments:3,x=t.extrudePath,b=t.UVGenerator!==void 0?t.UVGenerator:v2,_,S=!1,M,w,T,R;if(x){_=x.getSpacedPoints(u),S=!0,h=!1;let K=x.isCatmullRomCurve3?x.closed:!1;M=x.computeFrenetFrames(u,K),w=new E,T=new E,R=new E}h||(y=0,p=0,f=0,m=0);let D=o.extractPoints(c),L=D.shape,B=D.holes;if(!ca.isClockWise(L)){L=L.reverse();for(let K=0,Q=B.length;K<Q;K++){let re=B[K];ca.isClockWise(re)&&(B[K]=re.reverse())}}function q(K){let re=10000000000000001e-36,ue=K[0];for(let U=1;U<=K.length;U++){let ae=U%K.length,Z=K[ae],we=Z.x-ue.x,_e=Z.y-ue.y,Ae=we*we+_e*_e,ct=Math.max(Math.abs(Z.x),Math.abs(Z.y),Math.abs(ue.x),Math.abs(ue.y)),nt=re*ct*ct;if(Ae<=nt){K.splice(ae,1),U--;continue}ue=Z}}q(L),B.forEach(q);let ce=B.length,k=L;for(let K=0;K<ce;K++){let Q=B[K];L=L.concat(Q)}function j(K,Q,re){return Q||G("ExtrudeGeometry: vec does not exist"),K.clone().addScaledVector(Q,re)}let ee=L.length;function ge(K,Q,re){let ue,U,ae,Z=K.x-Q.x,we=K.y-Q.y,_e=re.x-K.x,Ae=re.y-K.y,ct=Z*Z+we*we,nt=Z*Ae-we*_e;if(Math.abs(nt)>Number.EPSILON){let ft=Math.sqrt(ct),_t=Math.sqrt(_e*_e+Ae*Ae),ut=Q.x-we/ft,vi=Q.y+Z/ft,bt=re.x-Ae/_t,ni=re.y+_e/_t,mt=((bt-ut)*Ae-(ni-vi)*_e)/(Z*Ae-we*_e);ue=ut+Z*mt-K.x,U=vi+we*mt-K.y;let gt=ue*ue+U*U;if(gt<=2)return new O(ue,U);ae=Math.sqrt(gt/2)}else{let ft=!1;Z>Number.EPSILON?_e>Number.EPSILON&&(ft=!0):Z<-Number.EPSILON?_e<-Number.EPSILON&&(ft=!0):Math.sign(we)===Math.sign(Ae)&&(ft=!0),ft?(ue=-we,U=Z,ae=Math.sqrt(ct)):(ue=Z,U=we,ae=Math.sqrt(ct/2))}return new O(ue/ae,U/ae)}let fe=[];for(let K=0,Q=k.length,re=Q-1,ue=K+1;K<Q;K++,re++,ue++)re===Q&&(re=0),ue===Q&&(ue=0),fe[K]=ge(k[K],k[re],k[ue]);let he=[],ye,ze=fe.concat();for(let K=0,Q=ce;K<Q;K++){let re=B[K];ye=[];for(let ue=0,U=re.length,ae=U-1,Z=ue+1;ue<U;ue++,ae++,Z++)ae===U&&(ae=0),Z===U&&(Z=0),ye[ue]=ge(re[ue],re[ae],re[Z]);he.push(ye),ze=ze.concat(ye)}let Pe;if(y===0)Pe=ca.triangulateShape(k,B);else{let K=[],Q=[];for(let re=0;re<y;re++){let ue=re/y,U=p*Math.cos(ue*Math.PI/2),ae=f*Math.sin(ue*Math.PI/2)+m;for(let Z=0,we=k.length;Z<we;Z++){let _e=j(k[Z],fe[Z],ae);tt(_e.x,_e.y,-U),ue===0&&K.push(_e)}for(let Z=0,we=ce;Z<we;Z++){let _e=B[Z];ye=he[Z];let Ae=[];for(let ct=0,nt=_e.length;ct<nt;ct++){let ft=j(_e[ct],ye[ct],ae);tt(ft.x,ft.y,-U),ue===0&&Ae.push(ft)}ue===0&&Q.push(Ae)}}Pe=ca.triangulateShape(K,Q)}let ot=Pe.length,Se=f+m;for(let K=0;K<ee;K++){let Q=h?j(L[K],ze[K],Se):L[K];S?(T.copy(M.normals[0]).multiplyScalar(Q.x),w.copy(M.binormals[0]).multiplyScalar(Q.y),R.copy(_[0]).add(T).add(w),tt(R.x,R.y,R.z)):tt(Q.x,Q.y,0)}for(let K=1;K<=u;K++)for(let Q=0;Q<ee;Q++){let re=h?j(L[Q],ze[Q],Se):L[Q];S?(T.copy(M.normals[K]).multiplyScalar(re.x),w.copy(M.binormals[K]).multiplyScalar(re.y),R.copy(_[K]).add(T).add(w),tt(R.x,R.y,R.z)):tt(re.x,re.y,d/u*K)}for(let K=y-1;K>=0;K--){let Q=K/y,re=p*Math.cos(Q*Math.PI/2),ue=f*Math.sin(Q*Math.PI/2)+m;for(let U=0,ae=k.length;U<ae;U++){let Z=j(k[U],fe[U],ue);tt(Z.x,Z.y,d+re)}for(let U=0,ae=B.length;U<ae;U++){let Z=B[U];ye=he[U];for(let we=0,_e=Z.length;we<_e;we++){let Ae=j(Z[we],ye[we],ue);S?tt(Ae.x,Ae.y+_[u-1].y,_[u-1].x+re):tt(Ae.x,Ae.y,d+re)}}}Je(),lt();function Je(){let K=i.length/3;if(h){let Q=0,re=ee*Q;for(let ue=0;ue<ot;ue++){let U=Pe[ue];ti(U[2]+re,U[1]+re,U[0]+re)}Q=u+y*2,re=ee*Q;for(let ue=0;ue<ot;ue++){let U=Pe[ue];ti(U[0]+re,U[1]+re,U[2]+re)}}else{for(let Q=0;Q<ot;Q++){let re=Pe[Q];ti(re[2],re[1],re[0])}for(let Q=0;Q<ot;Q++){let re=Pe[Q];ti(re[0]+ee*u,re[1]+ee*u,re[2]+ee*u)}}n.addGroup(K,i.length/3-K,0)}function lt(){let K=i.length/3,Q=0;kt(k,Q),Q+=k.length;for(let re=0,ue=B.length;re<ue;re++){let U=B[re];kt(U,Q),Q+=U.length}n.addGroup(K,i.length/3-K,1)}function kt(K,Q){let re=K.length;for(;--re>=0;){let ue=re,U=re-1;U<0&&(U=K.length-1);for(let ae=0,Z=u+y*2;ae<Z;ae++){let we=ee*ae,_e=ee*(ae+1),Ae=Q+ue+we,ct=Q+U+we,nt=Q+U+_e,ft=Q+ue+_e;Rn(Ae,ct,nt,ft)}}}function tt(K,Q,re){l.push(K),l.push(Q),l.push(re)}function ti(K,Q,re){jt(K),jt(Q),jt(re);let ue=i.length/3,U=b.generateTopUV(n,i,ue-3,ue-2,ue-1);Ke(U[0]),Ke(U[1]),Ke(U[2])}function Rn(K,Q,re,ue){jt(K),jt(Q),jt(ue),jt(Q),jt(re),jt(ue);let U=i.length/3,ae=b.generateSideWallUV(n,i,U-6,U-3,U-2,U-1);Ke(ae[0]),Ke(ae[1]),Ke(ae[3]),Ke(ae[1]),Ke(ae[2]),Ke(ae[3])}function jt(K){i.push(l[K*3+0]),i.push(l[K*3+1]),i.push(l[K*3+2])}function Ke(K){s.push(K.x),s.push(K.y)}}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){let e=super.toJSON(),t=this.parameters.shapes,n=this.parameters.options;return S2(t,n,e)}static fromJSON(e,t){let n=[];for(let s=0,a=e.shapes.length;s<a;s++){let o=t[e.shapes[s]];n.push(o)}let i=e.options.extrudePath;return i!==void 0&&(e.options.extrudePath=new Wp[i.type]().fromJSON(i)),new r(n,e.options)}},v2={generateTopUV:function(r,e,t,n,i){let s=e[t*3],a=e[t*3+1],o=e[n*3],l=e[n*3+1],c=e[i*3],u=e[i*3+1];return[new O(s,a),new O(o,l),new O(c,u)]},generateSideWallUV:function(r,e,t,n,i,s){let a=e[t*3],o=e[t*3+1],l=e[t*3+2],c=e[n*3],u=e[n*3+1],d=e[n*3+2],h=e[i*3],p=e[i*3+1],f=e[i*3+2],m=e[s*3],y=e[s*3+1],x=e[s*3+2];return Math.abs(o-u)<Math.abs(a-c)?[new O(a,1-l),new O(c,1-d),new O(h,1-f),new O(m,1-x)]:[new O(o,1-l),new O(u,1-d),new O(p,1-f),new O(y,1-x)]}};function S2(r,e,t){if(t.shapes=[],Array.isArray(r))for(let n=0,i=r.length;n<i;n++){let s=r[n];t.shapes.push(s.uuid)}else t.shapes.push(r.uuid);return t.options=Object.assign({},e),e.extrudePath!==void 0&&(t.options.extrudePath=e.extrudePath.toJSON()),t}var ac=class r extends on{constructor(e=[new O(0,-.5),new O(.5,0),new O(0,.5)],t=12,n=0,i=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:n,phiLength:i},t=Math.floor(t),i=Te(i,0,Math.PI*2);let s=[],a=[],o=[],l=[],c=[],u=1/t,d=new E,h=new O,p=new E,f=new E,m=new E,y=0,x=0;for(let b=0;b<=e.length-1;b++)switch(b){case 0:y=e[b+1].x-e[b].x,x=e[b+1].y-e[b].y,p.x=x*1,p.y=-y,p.z=x*0,m.copy(p),p.normalize(),l.push(p.x,p.y,p.z);break;case e.length-1:l.push(m.x,m.y,m.z);break;default:y=e[b+1].x-e[b].x,x=e[b+1].y-e[b].y,p.x=x*1,p.y=-y,p.z=x*0,f.copy(p),p.x+=m.x,p.y+=m.y,p.z+=m.z,p.normalize(),l.push(p.x,p.y,p.z),m.copy(f)}for(let b=0;b<=t;b++){let _=n+b*u*i,S=Math.sin(_),M=Math.cos(_);for(let w=0;w<=e.length-1;w++){d.x=e[w].x*S,d.y=e[w].y,d.z=e[w].x*M,a.push(d.x,d.y,d.z),h.x=b/t,h.y=w/(e.length-1),o.push(h.x,h.y);let T=l[3*w+0]*S,R=l[3*w+1],D=l[3*w+0]*M;c.push(T,R,D)}}for(let b=0;b<t;b++)for(let _=0;_<e.length-1;_++){let S=_+b*e.length,M=S,w=S+e.length,T=S+e.length+1,R=S+1;s.push(M,w,R),s.push(T,R,w)}this.setIndex(s),this.setAttribute("position",new Ve(a,3)),this.setAttribute("uv",new Ve(o,2)),this.setAttribute("normal",new Ve(c,3))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.points,e.segments,e.phiStart,e.phiLength)}};var od=class r extends on{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};let s=e/2,a=t/2,o=Math.floor(n),l=Math.floor(i),c=o+1,u=l+1,d=e/o,h=t/l,p=[],f=[],m=[],y=[];for(let x=0;x<u;x++){let b=x*h-a;for(let _=0;_<c;_++){let S=_*d-s;f.push(S,-b,0),m.push(0,0,1),y.push(_/o),y.push(1-x/l)}}for(let x=0;x<l;x++)for(let b=0;b<o;b++){let _=b+c*x,S=b+c*(x+1),M=b+1+c*(x+1),w=b+1+c*x;p.push(_,S,w),p.push(S,M,w)}this.setIndex(p),this.setAttribute("position",new Ve(f,3)),this.setAttribute("normal",new Ve(m,3)),this.setAttribute("uv",new Ve(y,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.width,e.height,e.widthSegments,e.heightSegments)}};var ld=class r extends on{constructor(e=1,t=32,n=16,i=0,s=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:i,phiLength:s,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));let l=Math.min(a+o,Math.PI),c=0,u=[],d=new E,h=new E,p=[],f=[],m=[],y=[];for(let x=0;x<=n;x++){let b=[],_=x/n,S=a+_*o,M=e*Math.cos(S),w=Math.sqrt(e*e-M*M),T=0;x===0&&a===0?T=.5/t:x===n&&l===Math.PI&&(T=-.5/t);for(let R=0;R<=t;R++){let D=R/t,L=i+D*s;d.x=-w*Math.cos(L),d.y=M,d.z=w*Math.sin(L),f.push(d.x,d.y,d.z),h.copy(d).normalize(),m.push(h.x,h.y,h.z),y.push(D+T,1-_),b.push(c++)}u.push(b)}for(let x=0;x<n;x++)for(let b=0;b<t;b++){let _=u[x][b+1],S=u[x][b],M=u[x+1][b],w=u[x+1][b+1];(x!==0||a>0)&&p.push(_,S,w),(x!==n-1||l<Math.PI)&&p.push(S,M,w)}this.setIndex(p),this.setAttribute("position",new Ve(f,3)),this.setAttribute("normal",new Ve(m,3)),this.setAttribute("uv",new Ve(y,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}};var oc=class r extends on{constructor(e=new nc(new E(-1,-1,0),new E(-1,1,0),new E(1,1,0)),t=64,n=1,i=8,s=!1){super(),this.type="TubeGeometry",this.parameters={path:e,tubularSegments:t,radius:n,radialSegments:i,closed:s};let a=e.computeFrenetFrames(t,s);this.tangents=a.tangents,this.normals=a.normals,this.binormals=a.binormals;let o=new E,l=new E,c=new O,u=new E,d=[],h=[],p=[],f=[];m(),this.setIndex(f),this.setAttribute("position",new Ve(d,3)),this.setAttribute("normal",new Ve(h,3)),this.setAttribute("uv",new Ve(p,2));function m(){for(let _=0;_<t;_++)y(_);y(s===!1?t:0),b(),x()}function y(_){u=e.getPointAt(_/t,u);let S=a.normals[_],M=a.binormals[_];for(let w=0;w<=i;w++){let T=w/i*Math.PI*2,R=Math.sin(T),D=-Math.cos(T);l.x=D*S.x+R*M.x,l.y=D*S.y+R*M.y,l.z=D*S.z+R*M.z,l.normalize(),h.push(l.x,l.y,l.z),o.x=u.x+n*l.x,o.y=u.y+n*l.y,o.z=u.z+n*l.z,d.push(o.x,o.y,o.z)}}function x(){for(let _=1;_<=t;_++)for(let S=1;S<=i;S++){let M=(i+1)*(_-1)+(S-1),w=(i+1)*_+(S-1),T=(i+1)*_+S,R=(i+1)*(_-1)+S;f.push(M,w,R),f.push(w,T,R)}}function b(){for(let _=0;_<=t;_++)for(let S=0;S<=i;S++)c.x=_/t,c.y=S/i,p.push(c.x,c.y)}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){let e=super.toJSON();return e.path=this.parameters.path.toJSON(),e}static fromJSON(e){return new r(new Wp[e.path.type]().fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}};var cd=class extends _n{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new me(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}};function v1(r){let e={};for(let t in r){e[t]={};for(let n in r[t]){let i=r[t][n];if(c1(i))i.isRenderTargetTexture?(X("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=i.clone();else if(Array.isArray(i))if(c1(i[0])){let s=[];for(let a=0,o=i.length;a<o;a++)s[a]=i[a].clone();e[t][n]=s}else e[t][n]=i.slice();else e[t][n]=i}}return e}function Xn(r){let e={};for(let t=0;t<r.length;t++){let n=v1(r[t]);for(let i in n)e[i]=n[i]}return e}function c1(r){return r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)}var Et=class extends _n{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new me(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new me(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ss,this.normalScale=new O(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hi,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Mo=class extends Et{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new O(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Te(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new me(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new me(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new me(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},ud=class extends _n{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new me(16777215),this.specular=new me(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new me(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ss,this.normalScale=new O(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hi,this.combine=No,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},dd=class extends _n{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new me(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new me(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ss,this.normalScale=new O(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},hd=class extends _n{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ss,this.normalScale=new O(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}},pd=class extends _n{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new me(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new me(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ss,this.normalScale=new O(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hi,this.combine=No,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}};var fd=class extends _n{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new me(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ss,this.normalScale=new O(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}},md=class extends Kl{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}};function Up(r,e){return!r||r.constructor===e?r:typeof e.BYTES_PER_ELEMENT=="number"?new e(r):Array.prototype.slice.call(r)}var Er=class{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,i=t[n],s=t[n-1];e:{t:{let a;n:{i:if(!(e<i)){for(let o=n+2;;){if(i===void 0){if(e<s)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===o)break;if(s=i,i=t[++n],e<i)break t}a=t.length;break n}if(!(e>=s)){let o=t[1];e<o&&(n=2,s=o);for(let l=n-2;;){if(s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===l)break;if(i=s,s=t[--n-1],e>=s)break t}a=n,n=0;break n}break e}for(;n<a;){let o=n+a>>>1;e<t[o]?a=o:n=o+1}if(i=t[n],s=t[n-1],s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,s,i)}return this.interpolate_(n,s,e,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,s=e*i;for(let a=0;a!==i;++a)t[a]=n[s+a];return t}interpolate_(){throw new Error("THREE.Interpolant: Call to abstract method.")}intervalChanged_(){}},gd=class extends Er{constructor(e,t,n,i){super(e,t,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Gp,endingEnd:Gp}}intervalChanged_(e,t,n){let i=this.parameterPositions,s=e-2,a=e+1,o=i[s],l=i[a];if(o===void 0)switch(this.getSettings_().endingStart){case zp:s=e,o=2*t-n;break;case Hp:s=i.length-2,o=t+i[s]-i[s+1];break;default:s=e,o=n}if(l===void 0)switch(this.getSettings_().endingEnd){case zp:a=e,l=2*n-t;break;case Hp:a=1,l=n+i[1]-i[0];break;default:a=e-1,l=t}let c=(n-t)*.5,u=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(l-n),this._offsetPrev=s*u,this._offsetNext=a*u}interpolate_(e,t,n,i){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,u=this._offsetPrev,d=this._offsetNext,h=this._weightPrev,p=this._weightNext,f=(n-t)/(i-t),m=f*f,y=m*f,x=-h*y+2*h*m-h*f,b=(1+h)*y+(-1.5-2*h)*m+(-.5+h)*f+1,_=(-1-p)*y+(1.5+p)*m+.5*f,S=p*y-p*m;for(let M=0;M!==o;++M)s[M]=x*a[u+M]+b*a[c+M]+_*a[l+M]+S*a[d+M];return s}},yd=class extends Er{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,u=(n-t)/(i-t),d=1-u;for(let h=0;h!==o;++h)s[h]=a[c+h]*d+a[l+h]*u;return s}},xd=class extends Er{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e){return this.copySampleValue_(e-1)}},_d=class extends Er{interpolate_(e,t,n,i){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,u=this.inTangents,d=this.outTangents;if(!u||!d){let f=(n-t)/(i-t),m=1-f;for(let y=0;y!==o;++y)s[y]=a[c+y]*m+a[l+y]*f;return s}let h=o*2,p=e-1;for(let f=0;f!==o;++f){let m=a[c+f],y=a[l+f],x=p*h+f*2,b=d[x],_=d[x+1],S=e*h+f*2,M=u[S],w=u[S+1],T=(n-t)/(i-t),R,D,L,B,W;for(let q=0;q<8;q++){R=T*T,D=R*T,L=1-T,B=L*L,W=B*L;let k=W*t+3*B*T*b+3*L*R*M+D*i-n;if(Math.abs(k)<1e-10)break;let j=3*B*(b-t)+6*L*T*(M-b)+3*R*(i-M);if(Math.abs(j)<1e-10)break;T=T-k/j,T=Math.max(0,Math.min(1,T))}s[f]=W*m+3*B*T*_+3*L*R*w+D*y}return s}},fi=class{constructor(e,t,n,i){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=Up(t,this.TimeBufferType),this.values=Up(n,this.ValueBufferType),this.setInterpolation(i||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Up(e.times,Array),values:Up(e.values,Array)};let i=e.getInterpolation();i!==e.DefaultInterpolation&&(n.interpolation=i)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new xd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new yd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new gd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new _d(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents),t}setInterpolation(e){let t;switch(e){case zl:t=this.InterpolantFactoryMethodDiscrete;break;case zu:t=this.InterpolantFactoryMethodLinear;break;case Bu:t=this.InterpolantFactoryMethodSmooth;break;case Vp:t=this.InterpolantFactoryMethodBezier;break}if(t===void 0){let n="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(n);return X("KeyframeTrack:",n),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return zl;case this.InterpolantFactoryMethodLinear:return zu;case this.InterpolantFactoryMethodSmooth:return Bu;case this.InterpolantFactoryMethodBezier:return Vp}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]*=e}return this}trim(e,t){let n=this.times,i=n.length,s=0,a=i-1;for(;s!==i&&n[s]<e;)++s;for(;a!==-1&&n[a]>t;)--a;if(++a,s!==0||a!==i){s>=a&&(a=Math.max(a,1),s=a-1);let o=this.getValueSize();this.times=n.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(G("KeyframeTrack: Invalid value size in track.",this),e=!1);let n=this.times,i=this.values,s=n.length;s===0&&(G("KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){let l=n[o];if(typeof l=="number"&&isNaN(l)){G("KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){G("KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(i!==void 0&&Hc(i))for(let o=0,l=i.length;o!==l;++o){let c=i[o];if(isNaN(c)){G("KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===Bu,s=e.length-1,a=1;for(let o=1;o<s;++o){let l=!1,c=e[o],u=e[o+1];if(c!==u&&(o!==1||c!==e[0]))if(i)l=!0;else{let d=o*n,h=d-n,p=d+n;for(let f=0;f!==n;++f){let m=t[d+f];if(m!==t[h+f]||m!==t[p+f]){l=!0;break}}}if(l){if(o!==a){e[a]=e[o];let d=o*n,h=a*n;for(let p=0;p!==n;++p)t[h+p]=t[d+p]}++a}}if(s>0){e[a]=e[s];for(let o=s*n,l=a*n,c=0;c!==n;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*n)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,i=new n(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}};fi.prototype.ValueTypeName="";fi.prototype.TimeBufferType=Float32Array;fi.prototype.ValueBufferType=Float32Array;fi.prototype.DefaultInterpolation=zu;var Rr=class extends fi{constructor(e,t,n){super(e,t,n)}};Rr.prototype.ValueTypeName="bool";Rr.prototype.ValueBufferType=Array;Rr.prototype.DefaultInterpolation=zl;Rr.prototype.InterpolantFactoryMethodLinear=void 0;Rr.prototype.InterpolantFactoryMethodSmooth=void 0;var bd=class extends fi{constructor(e,t,n,i){super(e,t,n,i)}};bd.prototype.ValueTypeName="color";var vd=class extends fi{constructor(e,t,n,i){super(e,t,n,i)}};vd.prototype.ValueTypeName="number";var Sd=class extends Er{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(n-t)/(i-t),c=e*o;for(let u=c+o;c!==u;c+=4)fn.slerpFlat(s,0,a,c-o,a,c,l);return s}},lc=class extends fi{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new Sd(this.times,this.values,this.getValueSize(),e)}};lc.prototype.ValueTypeName="quaternion";lc.prototype.InterpolantFactoryMethodSmooth=void 0;var Ar=class extends fi{constructor(e,t,n){super(e,t,n)}};Ar.prototype.ValueTypeName="string";Ar.prototype.ValueBufferType=Array;Ar.prototype.DefaultInterpolation=zl;Ar.prototype.InterpolantFactoryMethodLinear=void 0;Ar.prototype.InterpolantFactoryMethodSmooth=void 0;var Td=class extends fi{constructor(e,t,n,i){super(e,t,n,i)}};Td.prototype.ValueTypeName="vector";var Gu={enabled:!1,files:{},add:function(r,e){this.enabled!==!1&&(u1(r)||(this.files[r]=e))},get:function(r){if(this.enabled!==!1&&!u1(r))return this.files[r]},remove:function(r){delete this.files[r]},clear:function(){this.files={}}};function u1(r){try{let e=r.slice(r.indexOf(":")+1);return new URL(e).protocol==="blob:"}catch{return!1}}var Md=class{constructor(e,t,n){let i=this,s=!1,a=0,o=0,l,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(u){o++,s===!1&&i.onStart!==void 0&&i.onStart(u,a,o),s=!0},this.itemEnd=function(u){a++,i.onProgress!==void 0&&i.onProgress(u,a,o),a===o&&(s=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(u){i.onError!==void 0&&i.onError(u)},this.resolveURL=function(u){return u=u.normalize("NFC"),l?l(u):u},this.setURLModifier=function(u){return l=u,this},this.addHandler=function(u,d){return c.push(u,d),this},this.removeHandler=function(u){let d=c.indexOf(u);return d!==-1&&c.splice(d,2),this},this.getHandler=function(u){for(let d=0,h=c.length;d<h;d+=2){let p=c[d],f=c[d+1];if(p.global&&(p.lastIndex=0),p.test(u))return f}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}},hy=new Md,wo=class{constructor(e){this.manager=e!==void 0?e:hy,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}load(){}loadAsync(e,t){let n=this;return new Promise(function(i,s){n.load(e,i,t,s)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};wo.DEFAULT_MATERIAL_NAME="__DEFAULT";var Pl=new WeakMap,wd=class extends wo{constructor(e){super(e)}load(e,t,n,i){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=Gu.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);else{let d=Pl.get(a);d===void 0&&(d=[],Pl.set(a,d)),d.push({onLoad:t,onError:i})}return a}let o=Wu("img");function l(){u(),t&&t(this);let d=Pl.get(this)||[];for(let h=0;h<d.length;h++){let p=d[h];p.onLoad&&p.onLoad(this)}Pl.delete(this),s.manager.itemEnd(e)}function c(d){u(),i&&i(d),Gu.remove(`image:${e}`);let h=Pl.get(this)||[];for(let p=0;p<h.length;p++){let f=h[p];f.onError&&f.onError(d)}Pl.delete(this),s.manager.itemError(e),s.manager.itemEnd(e)}function u(){o.removeEventListener("load",l,!1),o.removeEventListener("error",c,!1)}return o.addEventListener("load",l,!1),o.addEventListener("error",c,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),Gu.add(`image:${e}`,o),s.manager.itemStart(e),o.src=e,o}};var cc=class extends wo{constructor(e){super(e)}load(e,t,n,i){let s=new mn,a=new wd(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(o){s.image=o,s.needsUpdate=!0,t!==void 0&&t(s)},n,i),s}},xs=class extends Qt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new me(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}},va=class extends xs{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Qt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new me(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){let t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}},N0=new Ne,d1=new E,h1=new E,Ed=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new O(512,512),this.mapType=Gt,this.map=null,this.mapPass=null,this.matrix=new Ne,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new ya,this._frameExtents=new O(1,1),this._viewportCount=1,this._viewports=[new Ge(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;d1.setFromMatrixPosition(e.matrixWorld),t.position.copy(d1),h1.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(h1),t.updateMatrixWorld(),N0.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(N0,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===di||t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(N0)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},Op=new E,kp=new fn,Gs=new E,uc=class extends Qt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ne,this.projectionMatrix=new Ne,this.projectionMatrixInverse=new Ne,this.coordinateSystem=qn,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(Op,kp,Gs),Gs.x===1&&Gs.y===1&&Gs.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Op,kp,Gs.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(Op,kp,Gs),Gs.x===1&&Gs.y===1&&Gs.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Op,kp,Gs.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},la=new E,p1=new O,f1=new O,an=class extends uc{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=pa*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Uu*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return pa*2*Math.atan(Math.tan(Uu*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){la.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(la.x,la.y).multiplyScalar(-e/la.z),la.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(la.x,la.y).multiplyScalar(-e/la.z)}getViewSize(e,t){return this.getViewBounds(e,p1,f1),t.subVectors(f1,p1)}setViewOffset(e,t,n,i,s,a){this.aspect=e/t,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=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(Uu*.5*this.fov)/this.zoom,n=2*t,i=this.aspect*n,s=-.5*i,a=this.view;if(this.view!==null&&this.view.enabled){let l=a.fullWidth,c=a.fullHeight;s+=a.offsetX*i/l,t-=a.offsetY*n/c,i*=a.width/l,n*=a.height/c}let o=this.filmOffset;o!==0&&(s+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},F0=class extends Ed{constructor(){super(new an(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=pa*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,s=e.distance||t.far;(n!==t.fov||i!==t.aspect||s!==t.far)&&(t.fov=n,t.aspect=i,t.far=s,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},Eo=class extends xs{constructor(e,t,n=0,i=Math.PI/3,s=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Qt.DEFAULT_UP),this.updateMatrix(),this.target=new Qt,this.distance=n,this.angle=i,this.penumbra=s,this.decay=a,this.map=null,this.shadow=new F0}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}},L0=class extends Ed{constructor(){super(new an(90,1,.5,500)),this.isPointLightShadow=!0}},Ro=class extends xs{constructor(e,t,n=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new L0}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}},Ao=class extends uc{constructor(e=-1,t=1,n=1,i=-1,s=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=s,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,s,a){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=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2,s=n-e,a=n+e,o=i+t,l=i-t;if(this.view!==null&&this.view.enabled){let c=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,a=s+c*this.view.width,o-=u*this.view.offsetY,l=o-u*this.view.height}this.projectionMatrix.makeOrthographic(s,a,o,l,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},B0=class extends Ed{constructor(){super(new Ao(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},Sa=class extends xs{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Qt.DEFAULT_UP),this.updateMatrix(),this.target=new Qt,this.shadow=new B0}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}},Rd=class extends xs{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}},Ad=class extends xs{constructor(e,t,n=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){let t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}},Cd=class{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new E)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){let n=e.x,i=e.y,s=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.282095),t.addScaledVector(a[1],.488603*i),t.addScaledVector(a[2],.488603*s),t.addScaledVector(a[3],.488603*n),t.addScaledVector(a[4],1.092548*(n*i)),t.addScaledVector(a[5],1.092548*(i*s)),t.addScaledVector(a[6],.315392*(3*s*s-1)),t.addScaledVector(a[7],1.092548*(n*s)),t.addScaledVector(a[8],.546274*(n*n-i*i)),t}getIrradianceAt(e,t){let n=e.x,i=e.y,s=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.886227),t.addScaledVector(a[1],2*.511664*i),t.addScaledVector(a[2],2*.511664*s),t.addScaledVector(a[3],2*.511664*n),t.addScaledVector(a[4],2*.429043*n*i),t.addScaledVector(a[5],2*.429043*i*s),t.addScaledVector(a[6],.743125*s*s-.247708),t.addScaledVector(a[7],2*.429043*n*s),t.addScaledVector(a[8],.429043*(n*n-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){let n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(e,t+i*3);return this}toArray(e=[],t=0){let n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(e,t+i*3);return e}static getBasisAt(e,t){let n=e.x,i=e.y,s=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*s,t[3]=.488603*n,t[4]=1.092548*n*i,t[5]=1.092548*i*s,t[6]=.315392*(3*s*s-1),t[7]=1.092548*n*s,t[8]=.546274*(n*n-i*i)}},Nd=class extends xs{constructor(e=new Cd,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){let t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}};var Dl=-90,Il=1,Pd=class extends Qt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new an(Dl,Il,e,t);i.layers=this.layers,this.add(i);let s=new an(Dl,Il,e,t);s.layers=this.layers,this.add(s);let a=new an(Dl,Il,e,t);a.layers=this.layers,this.add(a);let o=new an(Dl,Il,e,t);o.layers=this.layers,this.add(o);let l=new an(Dl,Il,e,t);l.layers=this.layers,this.add(l);let c=new an(Dl,Il,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,s,a,o,l]=t;for(let c of t)this.remove(c);if(e===qn)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),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===di)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),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.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: "+e);for(let c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[s,a,o,l,c,u]=this.children,d=e.getRenderTarget(),h=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),f=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let y=!1;e.isWebGLRenderer===!0?y=e.state.buffers.depth.getReversed():y=e.reversedDepthBuffer,e.setRenderTarget(n,0,i),y&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,1,i),y&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,i),y&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,i),y&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(n,4,i),y&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,i),y&&e.autoClear===!1&&e.clearDepth(),e.render(t,u),e.setRenderTarget(d,h,p),e.xr.enabled=f,n.texture.needsPMREMUpdate=!0}},Dd=class extends an{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}};var py="\[\]\.:\/",T2=new RegExp("["+py+"]","g"),fy="[^"+py+"]",M2="[^"+py.replace("\.","")+"]",w2=/((?:WC+[/:])*)/.source.replace("WC",fy),E2=/(WCOD+)?/.source.replace("WCOD",M2),R2=/(?:.(WC+)(?:[(.+)])?)?/.source.replace("WC",fy),A2=/.(WC+)(?:[(.+)])?/.source.replace("WC",fy),C2=new RegExp("^"+w2+E2+R2+A2+"$"),N2=["material","materials","bones","map"],U0=class{constructor(e,t,n){let i=n||yt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,i=this._bindings[n];i!==void 0&&i.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,s=n.length;i!==s;++i)n[i].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},yt=class r{constructor(e,t,n){this.path=t,this.parsedPath=n||r.parseTrackName(t),this.node=r.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new r.Composite(e,t,n):new r(e,t,n)}static sanitizeNodeName(e){return e.replace(/s/g,"_").replace(T2,"")}static parseTrackName(e){let t=C2.exec(e);if(t===null)throw new Error("THREE.PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){let s=n.nodeName.substring(i+1);N2.indexOf(s)!==-1&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=s)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("THREE.PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(s){for(let a=0;a<s.length;a++){let o=s[a];if(o.name===t||o.uuid===t)return o;let l=n(o.children);if(l)return l}return null},i=n(e.children);if(i)return i}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++i)e[t++]=n[i]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++i)n[i]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++i)n[i]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++i)n[i]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let e=this.node,t=this.parsedPath,n=t.objectName,i=t.propertyName,s=t.propertyIndex;if(e||(e=r.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){X("PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let c=t.objectIndex;switch(n){case"materials":if(!e.material){G("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){G("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}e=e.material.materials;break;case"bones":if(!e.skeleton){G("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let u=0;u<e.length;u++)if(e[u].name===c){c=u;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){G("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){G("PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}e=e.material.map;break;default:if(e[n]===void 0){G("PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(c!==void 0){if(e[c]===void 0){G("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[c]}}let a=e[i];if(a===void 0){let c=t.nodeName;G("PropertyBinding: Trying to update property for track: "+c+"."+i+" but it wasn't found.",e);return}let o=this.Versioning.None;this.targetObject=e,e.isMaterial===!0?o=this.Versioning.NeedsUpdate:e.isObject3D===!0&&(o=this.Versioning.MatrixWorldNeedsUpdate);let l=this.BindingType.Direct;if(s!==void 0){if(i==="morphTargetInfluences"){if(!e.geometry){G("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){G("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}e.morphTargetDictionary[s]!==void 0&&(s=e.morphTargetDictionary[s])}l=this.BindingType.ArrayElement,this.resolvedProperty=a,this.propertyIndex=s}else a.fromArray!==void 0&&a.toArray!==void 0?(l=this.BindingType.HasFromToArray,this.resolvedProperty=a):Array.isArray(a)?(l=this.BindingType.EntireArray,this.resolvedProperty=a):this.propertyName=i;this.getValue=this.GetterByBindingType[l],this.setValue=this.SetterByBindingTypeAndVersioning[l][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};yt.Composite=U0;yt.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};yt.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};yt.prototype.GetterByBindingType=[yt.prototype._getValue_direct,yt.prototype._getValue_array,yt.prototype._getValue_arrayElement,yt.prototype._getValue_toArray];yt.prototype.SetterByBindingTypeAndVersioning=[[yt.prototype._setValue_direct,yt.prototype._setValue_direct_setNeedsUpdate,yt.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[yt.prototype._setValue_array,yt.prototype._setValue_array_setNeedsUpdate,yt.prototype._setValue_array_setMatrixWorldNeedsUpdate],[yt.prototype._setValue_arrayElement,yt.prototype._setValue_arrayElement_setNeedsUpdate,yt.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[yt.prototype._setValue_fromArray,yt.prototype._setValue_fromArray_setNeedsUpdate,yt.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var iz=new Float32Array(1);var Id=class extends jl{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){let t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){let t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}};var Co=class{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Te(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(Te(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}};var dc=class r{static{r.prototype.isMatrix2=!0}constructor(e,t,n,i){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,i){let s=this.elements;return s[0]=e,s[2]=t,s[1]=n,s[3]=i,this}};var hc=class extends $n{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){X("Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}};function my(r,e,t,n){let i=P2(n);switch(t){case Xd:return r*e;case Da:return r*e/i.components*i.byteLength;case Ia:return r*e/i.components*i.byteLength;case mi:return r*e*2/i.components*i.byteLength;case Fa:return r*e*2/i.components*i.byteLength;case Pa:return r*e*3/i.components*i.byteLength;case bn:return r*e*4/i.components*i.byteLength;case mc:return r*e*4/i.components*i.byteLength;case Do:case Io:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case Fo:case Lo:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case Kd:case Jd:return Math.max(r,16)*Math.max(e,8)/4;case jd:case Zd:return Math.max(r,8)*Math.max(e,8)/2;case gc:case yc:case _c:case bc:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case xc:case Bo:case vc:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case Sc:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case Tc:return Math.floor((r+4)/5)*Math.floor((e+3)/4)*16;case Mc:return Math.floor((r+4)/5)*Math.floor((e+4)/5)*16;case wc:return Math.floor((r+5)/6)*Math.floor((e+4)/5)*16;case Ec:return Math.floor((r+5)/6)*Math.floor((e+5)/6)*16;case Rc:return Math.floor((r+7)/8)*Math.floor((e+4)/5)*16;case Ac:return Math.floor((r+7)/8)*Math.floor((e+5)/6)*16;case Cc:return Math.floor((r+7)/8)*Math.floor((e+7)/8)*16;case Nc:return Math.floor((r+9)/10)*Math.floor((e+4)/5)*16;case Pc:return Math.floor((r+9)/10)*Math.floor((e+5)/6)*16;case Dc:return Math.floor((r+9)/10)*Math.floor((e+7)/8)*16;case Ic:return Math.floor((r+9)/10)*Math.floor((e+9)/10)*16;case Fc:return Math.floor((r+11)/12)*Math.floor((e+9)/10)*16;case Lc:return Math.floor((r+11)/12)*Math.floor((e+11)/12)*16;case Bc:case Uc:case Oc:return Math.ceil(r/4)*Math.ceil(e/4)*16;case kc:case Vc:return Math.ceil(r/4)*Math.ceil(e/4)*8;case Uo:case Gc:return Math.ceil(r/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function P2(r){switch(r){case Gt:case Dr:return{byteLength:1,components:1};case qs:case Ir:case xt:return{byteLength:2,components:1};case qd:case $d:return{byteLength:2,components:4};case it:case zt:case en:return{byteLength:4,components:1};case pc:case fc:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${r}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"185"}}));typeof window<"u"&&(window.__THREE__?X("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="185");var tD=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","envMapRotation","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],S1=new WeakMap,T1=new WeakMap,M1=new WeakMap,ex=class{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=tD,this.renderId=0}firstInitialization(e){return this.renderObjects.has(e)===!1?(this.getRenderObjectData(e),!0):!1}needsVelocity(e){let t=e.getMRT();return t!==null&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(t===void 0){let{geometry:n,object:i}=e;if(t={geometryId:n.id,worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),e.bundle!==null&&(t.version=e.bundle.version),e.material.transmission>0){let{width:o,height:l}=e.context;t.bufferWidth=o,t.bufferHeight=l}let{environmentIntensity:s,environmentRotation:a}=e.scene;t.environmentIntensity=s,t.environmentRotation=a.clone(),t.lights=this.getLightsData(e.lightsNode.getLights(),[]),this.renderObjects.set(e,t)}return t}getAttributesData(e){let t={};for(let n in e){let i=e[n];t[n]={id:i.isInterleavedBufferAttribute?i.data.uuid:i.id,version:i.isInterleavedBufferAttribute?i.data.version:i.version}}return t}containsNode(e){let t=e.material;for(let n in t)if(t[n]&&t[n].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getGeometryData(e){let t=M1.get(e);return t===void 0&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},M1.set(e,t)),t}getMaterialData(e){let t=T1.get(e);if(t===void 0){t={_renderId:-1,_equal:!1};for(let n of this.refreshUniforms){let i=e[n];i!=null&&(typeof i=="object"&&i.clone!==void 0?i.isTexture===!0?t[n]={id:i.id,version:0}:t[n]=i.clone():t[n]=i)}T1.set(e,t)}return t}equals(e,t,n){let{object:i,material:s,geometry:a}=e,o=this.getRenderObjectData(e);if(o.worldMatrix.equals(i.matrixWorld)!==!0)return o.worldMatrix.copy(i.matrixWorld),!1;let l=this.getMaterialData(e.material);if(l._renderId!==n){l._renderId=n;for(let d in l){let h=l[d],p=s[d];if(d!=="_renderId"&&d!=="_equal"){if(h.equals!==void 0){if(h.equals(p)===!1)return h.copy(p),l._equal=!1,!1}else if(p.isTexture===!0){if(h.id!==p.id||h.version!==p.version)return h.id=p.id,h.version=p.version,l._equal=!1,!1}else if(h!==p)return l[d]=p,l._equal=!1,!1}}if(l.transmission>0){let{width:d,height:h}=e.context;if(o.bufferWidth!==d||o.bufferHeight!==h)return o.bufferWidth=d,o.bufferHeight=h,l._equal=!1,!1}l._equal=!0}else if(l._equal===!1)return!1;if(o.geometryId!==a.id)return o.geometryId=a.id,!1;let c=this.getGeometryData(e.geometry);if(c._renderId!==n){c._renderId=n;let d=a.attributes,h=c.attributes,p=0,f=0;for(let S in d)p++;for(let S in h){f++;let M=h[S],w=d[S];if(w===void 0)return delete h[S],c._equal=!1,!1;let T=w.isInterleavedBufferAttribute?w.data.uuid:w.id,R=w.isInterleavedBufferAttribute?w.data.version:w.version;if(M.id!==T||M.version!==R)return M.id=T,M.version=R,c._equal=!1,!1}if(f!==p)return c.attributes=this.getAttributesData(d),c._equal=!1,!1;let m=a.index,y=c.indexId,x=c.indexVersion,b=m?m.id:null,_=m?m.version:null;if(y!==b||x!==_)return c.indexId=b,c.indexVersion=_,c._equal=!1,!1;if(c.drawRange.start!==a.drawRange.start||c.drawRange.count!==a.drawRange.count)return c.drawRange.start=a.drawRange.start,c.drawRange.count=a.drawRange.count,c._equal=!1,!1;c._equal=!0}else if(c._equal===!1)return!1;if(o.morphTargetInfluences){let d=!1;for(let h=0;h<o.morphTargetInfluences.length;h++)o.morphTargetInfluences[h]!==i.morphTargetInfluences[h]&&(o.morphTargetInfluences[h]=i.morphTargetInfluences[h],d=!0);if(d)return!1}if(o.lights){for(let d=0;d<t.length;d++)if(o.lights[d].map!==t[d].map)return!1}let u=e.scene;return u.environment!==null&&s.envMap===null&&(o.environmentIntensity!==u.environmentIntensity||o.environmentRotation.equals(u.environmentRotation)===!1)?(o.environmentIntensity=u.environmentIntensity,o.environmentRotation.copy(u.environmentRotation),!1):o.center&&o.center.equals(i.center)===!1?(o.center.copy(i.center),!1):(e.bundle!==null&&(o.version=e.bundle.version),!0)}getLightsData(e,t){t.length=0;for(let n of e)n.isSpotLight===!0&&n.map!==null&&t.push({map:n.map.version});return t}getLights(e,t){let n=S1.get(e);return n===void 0&&(n={renderId:-1,lightsData:[]},S1.set(e,n)),n.renderId===t||(n.renderId=t,this.getLightsData(e.getLights(),n.lightsData)),n.lightsData}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;let{renderId:n}=t;if(this.renderId!==n)return this.renderId=n,!0;let i=e.object.static===!0,s=e.bundle!==null&&e.bundle.static===!0&&this.getRenderObjectData(e).version===e.bundle.version;if(i||s)return!1;let a=this.getLights(e.lightsNode,n);return this.equals(e,a,n)!==!0}},nD=[/^StackTrace.js$/,/^TSLCore.js$/,/^.*Node.js$/,/^three.webgpu.*.js$/];function iD(r){let e=/(?:ats+(.+?)s+()?(?:(.+?)@)?([^@s()]+):(d+):(d+)/;return r.split(`
`).map(t=>{let n=t.match(e);if(!n)return null;let i=n[1]||n[2]||"",s=n[3].split("?")[0],a=parseInt(n[4],10),o=parseInt(n[5],10),l=s.split("/").pop();return{fn:i,file:l,line:a,column:o}}).filter(t=>t&&!nD.some(n=>n.test(t.file)))}var Dt=class{constructor(e=null){this.isStackTrace=!0,this.stack=iD(e||new Error().stack)}getLocation(){if(this.stack.length===0)return"[Unknown location]";let e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(this.stack.length===0)return e;let t=this.stack.map(n=>{let i=`${n.file}:${n.line}:${n.column}`;return n.fn?` at ${n.fn} (${i})`:` at ${i}`}).join(`
`);return`${e}
${t}`}};function kv(r,e=0){let t=3735928559^e,n=1103547991^e;if(Array.isArray(r))for(let i=0,s;i<r.length;i++)s=r[i],t=Math.imul(t^s,2654435761),n=Math.imul(n^s,1597334677);else for(let i=0,s;i<r.length;i++)s=r.charCodeAt(i),t=Math.imul(t^s,2654435761),n=Math.imul(n^s,1597334677);return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&n)+(t>>>0)}var Mu=r=>kv(r),Jh=r=>kv(r),vh=(...r)=>kv(r),sD=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),w1=new WeakMap;function XM(r){return sD.get(r)}function tm(r){if(/[iu]?vecd/.test(r))return r.startsWith("ivec")?Int32Array:r.startsWith("uvec")?Uint32Array:Float32Array;if(/matd/.test(r)||/float/.test(r))return Float32Array;if(/uint/.test(r))return Uint32Array;if(/int/.test(r))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${r}`)}function YM(r){if(/float|int|uint|bool/.test(r))return 1;if(/vec2/.test(r))return 2;if(/vec3/.test(r))return 3;if(/vec4/.test(r)||/mat2/.test(r))return 4;if(/mat3/.test(r))return 9;if(/mat4/.test(r))return 16;G(`TSL: Unsupported type: ${r}`,new Dt)}function rD(r){if(/float|int|uint|bool/.test(r))return 1;if(/vec2/.test(r))return 2;if(/vec3/.test(r))return 3;if(/vec4/.test(r)||/mat2/.test(r))return 4;if(/mat3/.test(r))return 12;if(/mat4/.test(r))return 16;G(`TSL: Unsupported type: ${r}`,new Dt)}function aD(r){if(/float|int|uint|bool/.test(r))return 1;if(/vec2/.test(r))return 2;if(/vec3/.test(r)||/vec4/.test(r))return 4;if(/mat2/.test(r))return 2;if(/mat3/.test(r)||/mat4/.test(r))return 4;G(`TSL: Unsupported type: ${r}`,new Dt)}function Xa(r){if(r==null)return null;let e=typeof r;return r.isNode===!0?"node":e==="number"?"float":e==="boolean"?"bool":e==="string"?"string":e==="function"?"shader":r.isVector2===!0?"vec2":r.isVector3===!0?"vec3":r.isVector4===!0?"vec4":r.isMatrix2===!0?"mat2":r.isMatrix3===!0?"mat3":r.isMatrix4===!0?"mat4":r.isColor===!0?"color":r instanceof ArrayBuffer?"ArrayBuffer":null}function Vv(r,...e){let t=r?r.slice(-4):void 0;return e.length===1&&(t==="vec2"?e=[e[0],e[0]]:t==="vec3"?e=[e[0],e[0],e[0]]:t==="vec4"&&(e=[e[0],e[0],e[0],e[0]])),r==="color"?new me(...e):t==="vec2"?new O(...e):t==="vec3"?new E(...e):t==="vec4"?new Ge(...e):t==="mat2"?new dc(...e):t==="mat3"?new ve(...e):t==="mat4"?new Ne(...e):r==="bool"?e[0]||!1:r==="float"||r==="int"||r==="uint"?e[0]||0:r==="string"?e[0]||"":r==="ArrayBuffer"?lD(e[0]):null}function jM(r){let e=w1.get(r);return e===void 0&&(e={},w1.set(r,e)),e}function oD(r){let e="",t=new Uint8Array(r);for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function lD(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer}var iu={VERTEX:"vertex",FRAGMENT:"fragment"},pe={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},cD={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Mn={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},KM=["fragment","vertex"],jf=["setup","analyze","generate"],Kf=[...KM,"compute"],fl=["x","y","z","w"],uD={analyze:"setup",generate:"analyze"},dD=0,le=class r extends $n{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=pe.NONE,this.updateBeforeType=pe.NONE,this.updateAfterType=pe.NONE,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=dD++,this.stackTrace=null,r.captureStackTrace===!0&&(this.stackTrace=new Dt)}set needsUpdate(e){e===!0&&this.version++}get uuid(){return this._uuid===null&&(this._uuid=Dn.generateUUID()),this._uuid}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,pe.FRAME)}onRenderUpdate(e){return this.onUpdate(e,pe.RENDER)}onObjectUpdate(e){return this.onUpdate(e,pe.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(let{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(let t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){let t=[];e.add(this);for(let n of Object.getOwnPropertyNames(this)){let i=this[n];if(!(n.startsWith("_")===!0||e.has(i))){if(Array.isArray(i)===!0)for(let s=0;s<i.length;s++){let a=i[s];a&&a.isNode===!0&&t.push({property:n,index:s,childNode:a})}else if(i&&i.isNode===!0)t.push({property:n,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(let s in i){if(s.startsWith("_")===!0)continue;let a=i[s];a&&a.isNode===!0&&t.push({property:n,index:s,childNode:a})}}}return t}getCacheKey(e=!1,t=null){if(e=e||this.version!==this._cacheKeyVersion,e===!0||this._cacheKey===null){t===null&&(t=new Set);let n=[];for(let{property:i,childNode:s}of this._getChildren(t))n.push(Mu(i.slice(0,-4)),s.getCacheKey(e,t));this._cacheKey=vh(Jh(n),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){let t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e,t=null){let n=e.getDataFromNode(this),i;return t!==null?(n.typeFromOutput=n.typeFromOutput||{},i=n.typeFromOutput[t],i===void 0&&(i=this.generateNodeType(e,t),n.typeFromOutput[t]=i)):(i=n.type,i===void 0&&(i=this.generateNodeType(e),n.type=i)),i}generateNodeType(e,t=null){let n=e.getNodeProperties(this);return n.outputNode?n.outputNode.getNodeType(e,t):this.nodeType}getShared(e){let t=this.getHash(e),n=e.getNodeFromHash(t),i=null;if(n&&n!==this)i=n;else if(e.context.overrideNodes){let s=e.context.overrideNodes.get(this);if(s){let a=e.getDataFromNode(this);a.isOverwritten!==!0?(a.isOverwritten=!0,i=s(e).overrideNode(this,null),a.sharedNode=i):i=a.sharedNode}}return i||this}getArrayCount(){return null}setup(e){let t=e.getNodeProperties(this),n=0;for(let i of this.getChildren())t["node"+n++]=i;return t.outputNode||null}analyze(e,t=null){let n=e.increaseUsage(this);if(this.parents===!0){let i=e.getDataFromNode(this,"any");i.stages=i.stages||{},i.stages[e.shaderStage]=i.stages[e.shaderStage]||[],i.stages[e.shaderStage].push(t)}if(n===1){let i=e.getNodeProperties(this);for(let s of Object.values(i))s&&s.isNode===!0&&s.build(e,this)}}generate(e,t){let{outputNode:n}=e.getNodeProperties(this);if(n&&n.isNode===!0)return n.build(e,t)}updateBefore(){X("Abstract function.")}updateAfter(){X("Abstract function.")}update(){X("Abstract function.")}before(e){return this._beforeNodes===null&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){let n=this.getShared(e);if(this!==n)return n.build(e,t);if(this._beforeNodes!==null){let l=this._beforeNodes;this._beforeNodes=null;for(let c of l)c.build(e,t);this._beforeNodes=l}let i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;let s=uD[e.buildStage];if(s&&i.buildStages[s]!==!0){let l=e.getBuildStage();e.setBuildStage(s),this.build(e),e.setBuildStage(l)}e.addChain(this);let a=null,o=e.getBuildStage();if(o==="setup"){e.addNode(this),this.updateReference(e);let l=e.getNodeProperties(this);if(l.initialized!==!0){l.initialized=!0,l.outputNode=this.setup(e)||l.outputNode||null;for(let c of Object.values(l))if(c&&c.isNode===!0){if(c.parents===!0){let u=e.getNodeProperties(c);u.parents=u.parents||[],u.parents.push(this)}c.build(e)}e.addSequentialNode(this)}a=l.outputNode}else if(o==="analyze")this.analyze(e,t);else if(o==="generate"){if(this.generate.length<2){let c=this.getNodeType(e),u=e.getDataFromNode(this);a=u.snippet,a===void 0?u.generated===void 0?(u.generated=!0,a=this.generate(e)||"",u.snippet=a):(X("Node: Recursion detected.",this),a="/* Recursion detected. */"):u.flowCodes!==void 0&&e.context.nodeBlock!==void 0&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),a=e.format(a,c,t)}else a=this.generate(e,t)||"";a===""&&t!==null&&t!=="void"&&t!=="OutputType"&&(G(`TSL: Invalid generated code, expected a "${t}".`),a=e.generateConst(t))}return e.removeChain(this),a}getSerializeChildren(){return this._getChildren()}serialize(e){let t=this.getSerializeChildren(),n={};for(let{property:i,index:s,childNode:a}of t)s!==void 0?(n[i]===void 0&&(n[i]=Number.isInteger(s)?[]:{}),n[i][s]=a.toJSON(e.meta).uuid):n[i]=a.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(e.inputNodes!==void 0){let t=e.meta.nodes;for(let n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){let i=[];for(let s of e.inputNodes[n])i.push(t[s]);this[n]=i}else if(typeof e.inputNodes[n]=="object"){let i={};for(let s in e.inputNodes[n]){let a=e.inputNodes[n][s];i[s]=t[a]}this[n]=i}else{let i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){let{uuid:t,type:n}=this,i=e===void 0||typeof e=="string";i&&(e={textures:{},images:{},nodes:{}});let s=e.nodes[t];s===void 0&&(s={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},i!==!0&&(e.nodes[s.uuid]=s),this.serialize(s),delete s.meta);function a(o){let l=[];for(let c in o){let u=o[c];delete u.metadata,l.push(u)}return l}if(i){let o=a(e.textures),l=a(e.images),c=a(e.nodes);o.length>0&&(s.textures=o),l.length>0&&(s.images=l),c.length>0&&(s.nodes=c)}return s}};le.captureStackTrace=!1;var Hr=class extends le{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){let t=this.indexNode.getNodeType(e),n=this.node.build(e),i=this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint");return`${n}[ ${i} ]`}},nm=class extends le{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){let t=this.node.getNodeType(e),n=null;for(let i of this.convertTo.split("|"))(n===null||e.getTypeLength(t)===e.getTypeLength(i))&&(n=i);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){let n=this.node,i=this.getNodeType(e),s=n.build(e,i);return e.format(s,i,t)}},ht=class extends le{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if(e.getBuildStage()==="generate"){let i=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(s.propertyName!==void 0)return e.format(s.propertyName,i,t);if(i!=="void"&&t!=="void"&&this.hasDependencies(e)){let a=super.build(e,i),o=e.getVarFromNode(this,null,i),l=e.getPropertyName(o);return e.addLineFlowCode(`${l} = ${a}`,this),s.snippet=a,s.propertyName=l,e.format(s.propertyName,i,t)}}return super.build(e,t)}},tx=class extends ht{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return this.nodeType!==null?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0))}generate(e,t){let n=this.getNodeType(e),i=e.getTypeLength(n),s=this.nodes,a=e.getComponentType(n),o=[],l=0;for(let u of s){if(l>=i){G(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`,this.stackTrace);break}let d=u.getNodeType(e),h=e.getTypeLength(d),p;if(l+h>i&&(G(`TSL: Length of '${n}()' data exceeds maximum length of output type.`,this.stackTrace),h=i-l,d=e.getTypeFromLength(h)),l+=h,p=u.build(e,d),e.getComponentType(d)!==a){let m=e.getTypeFromLength(h,a);p=e.format(p,d,m)}o.push(p)}let c=`${e.getType(n)}( ${o.join(", ")} )`;return e.format(c,n,t)}},hD=fl.join(""),im=class extends le{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(let t of this.components)e=Math.max(fl.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){let n=this.node,i=e.getTypeLength(n.getNodeType(e)),s=null;if(i>1){let a=null;this.getVectorLength()>=i&&(a=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));let l=n.build(e,a);this.components.length===i&&this.components===hD.slice(0,this.components.length)?s=e.format(l,a,t):s=e.format(`${l}.${this.components}`,this.getNodeType(e),t)}else s=n.build(e,t);return s}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}},nx=class extends ht{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){let{sourceNode:t,components:n,targetNode:i}=this,s=this.getNodeType(e),a=e.getComponentType(i.getNodeType(e)),o=e.getTypeFromLength(n.length,a),l=i.build(e,o),c=t.build(e,s),u=e.getTypeLength(s),d=[];for(let h=0;h<u;h++){let p=fl[h];p===n[0]?(d.push(l),h+=n.length-1):d.push(c+"."+p)}return`${e.getType(s)}( ${d.join(", ")} )`}},ix=class extends ht{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){let{components:t,sourceNode:n}=this,i=this.getNodeType(e),s=n.build(e),a=e.getVarFromNode(this),o=e.getPropertyName(a);e.addLineFlowCode(o+" = "+s,this);let l=e.getTypeLength(i),c=[],u=0;for(let d=0;d<l;d++){let h=fl[d];h===t[u]?(c.push("1.0 - "+(o+"."+h)),u++):c.push(o+"."+h)}return`${e.getType(i)}( ${c.join(", ")} )`}},Nh=class extends le{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}generateNodeType(){return this.nodeType===null?Xa(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=Xa(this.value),e.nodeType=this.nodeType,e.valueType==="ArrayBuffer"&&(e.value=oD(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Vv(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){X("Abstract function.")}},E1=/float|u?int/,os=class extends Nh{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){let n=this.getNodeType(e);return E1.test(n)&&E1.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}},sx=class extends le{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return this.structNode.isMemberNode&&this.structNode.hasMember(e)===!1?!1:this.structNode.getMemberType(e,this.property)!=="void"}generateNodeType(e){return this.hasMember(e)===!1?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(this.hasMember(e)===!1)return"float";let n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}generate(e){if(this.hasMember(e)===!1){X(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);let n=this.getNodeType(e);return e.generateConst(n)}return this.structNode.build(e)+"."+this.property}},Za=null,rx=new Map;function F(r,e){if(rx.has(r)){X(`TSL: Redefinition of method chaining '${r}'.`);return}if(typeof e!="function")throw new Error(`THREE.TSL: Node element ${r} is not a function`);rx.set(r,e),r!=="assign"&&(le.prototype[r]=function(...t){return this.isStackNode?this.addToStack(e(...t)):e(this,...t)},le.prototype[r+"Assign"]=function(...t){return this.isStackNode?this.assign(t[0],e(...t)):this.assign(e(this,...t))})}var pD=r=>r.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),R1=r=>pD(r).split("").sort().join("");le.prototype.assign=function(...r){if(this.isStackNode!==!0)return Za!==null?Za.assign(this,...r):G("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Dt),this;{let e=rx.get("assign");return this.addToStack(e(...r))}};le.prototype.toVarIntent=function(){return this};le.prototype.get=function(r){return new sx(this,r)};var Sh={};function hf(r,e,t){Sh[r]=Sh[e]=Sh[t]={get(){this._cache=this._cache||{};let a=this._cache[r];return a===void 0&&(a=new im(this,r),this._cache[r]=a),a},set(a){this[r].assign(ne(a))}};let n=r.toUpperCase(),i=e.toUpperCase(),s=t.toUpperCase();le.prototype["set"+n]=le.prototype["set"+i]=le.prototype["set"+s]=function(a){let o=R1(r);return new nx(this,o,ne(a))},le.prototype["flip"+n]=le.prototype["flip"+i]=le.prototype["flip"+s]=function(){let a=R1(r);return new ix(this,a)}}var $s=["x","y","z","w"],Xs=["r","g","b","a"],Ys=["s","t","p","q"];for(let r=0;r<4;r++){let e=$s[r],t=Xs[r],n=Ys[r];hf(e,t,n);for(let i=0;i<4;i++){e=$s[r]+$s[i],t=Xs[r]+Xs[i],n=Ys[r]+Ys[i],hf(e,t,n);for(let s=0;s<4;s++){e=$s[r]+$s[i]+$s[s],t=Xs[r]+Xs[i]+Xs[s],n=Ys[r]+Ys[i]+Ys[s],hf(e,t,n);for(let a=0;a<4;a++)e=$s[r]+$s[i]+$s[s]+$s[a],t=Xs[r]+Xs[i]+Xs[s]+Xs[a],n=Ys[r]+Ys[i]+Ys[s]+Ys[a],hf(e,t,n)}}}for(let r=0;r<32;r++)Sh[r]={get(){this._cache=this._cache||{};let e=this._cache[r];return e===void 0&&(e=new Hr(this,new os(r,"uint")),this._cache[r]=e),e},set(e){this[r].assign(ne(e))}};Object.defineProperties(le.prototype,Sh);var fD=function(r,e=null){let t=Xa(r);return t==="node"?r:e===null&&(t==="float"||t==="boolean")||t&&t!=="shader"&&t!=="string"?ne(lx(r,e)):t==="shader"?r.isFn?r:P(r):r},mD=function(r,e=null){for(let t in r)r[t]=ne(r[t],e);return r},gD=function(r,e=null){let t=r.length;for(let n=0;n<t;n++)r[n]=ne(r[n],e);return r},ZM=function(r,e=null,t=null,n=null){function i(u){return n!==null?(u=ne(Object.assign(u,n)),n.intent===!0&&(u=u.toVarIntent())):u=ne(u),u}let s,a=e,o,l;function c(u){let d;return a?d=/[a-z]/i.test(a)?a+"()":a:d=r.type,o!==void 0&&u.length<o?(G(`TSL: "${d}" parameter length is less than minimum required.`,new Dt),u.concat(new Array(o-u.length).fill(0))):l!==void 0&&u.length>l?(G(`TSL: "${d}" parameter length exceeds limit.`,new Dt),u.slice(0,l)):u}return e===null?s=(...u)=>i(new r(...Qo(c(u)))):t!==null?(t=ne(t),s=(...u)=>i(new r(e,...Qo(c(u)),t))):s=(...u)=>i(new r(e,...Qo(c(u)))),s.setParameterLength=(...u)=>(u.length===1?o=l=u[0]:u.length===2&&([o,l]=u),s),s.setName=u=>(a=u,s),s},yD=function(r,...e){return new r(...Qo(e))},ax=class extends le{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){let{shaderNode:t,rawInputs:n}=this,i=e.getNodeProperties(t),s=e.getClosestSubBuild(t.subBuilds)||"",a=s||"default";if(i[a])return i[a];let o=e.subBuildFn,l=e.fnCall;e.subBuildFn=s,e.fnCall=this;let c=null;if(t.layout){if(n){let h=t.layout.inputs;if(JM(n)){let p=n;for(let f=0;f<h.length;f++){let m=p[f];m&&m.isNode&&m.build(e)}}else{let p=n[0];for(let f of h){let m=p[f.name];m&&m.isNode&&m.build(e)}}}let u=e.buildFunctionNode(t);e.addInclude(u);let d=n?xD(n):null;c=u.call(d)}else{let u=new Proxy(e,{get:(m,y,x)=>{let b;return Symbol.iterator===y?b=function*(){yield void 0}:b=Reflect.get(m,y,x),b}}),d=n?_D(n):null,h=Array.isArray(n)?n.length>0:n!==null,p=t.jsFunc,f=h||p.length>1?p(d,u):p(u);c=ne(f)}return e.subBuildFn=o,e.fnCall=l,t.once&&(i[a]=c),c}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){let t=e.getNodeProperties(this),n=e.getSubBuildOutput(this);return t[n]=t[n]||this.setupOutput(e),t[n].subBuild=e.getClosestSubBuild(this),t[n]}build(e,t=null){let n=null,i=e.getBuildStage(),s=e.getNodeProperties(this),a=e.getSubBuildOutput(this),o=this.getOutputNode(e),l=e.fnCall;if(e.fnCall=this,i==="setup"){let c=e.getSubBuildProperty("initialized",this);if(s[c]!==!0&&(s[c]=!0,s[a]=this.getOutputNode(e),s[a].build(e),this.shaderNode.subBuilds))for(let u of e.chaining){let d=e.getDataFromNode(u,"any");d.subBuilds=d.subBuilds||new Set;for(let h of this.shaderNode.subBuilds)d.subBuilds.add(h)}n=s[a]}else i==="analyze"?o.build(e,t):i==="generate"&&(n=o.build(e,t)||"");return e.fnCall=l,n}};function JM(r){return r[0]&&(r[0].isNode||Object.getPrototypeOf(r[0])!==Object.prototype)}function xD(r){let e;return xg(r),JM(r)?e=[...r]:e=r[0],e}function _D(r){let e=0;return xg(r),new Proxy(r,{get:(t,n,i)=>{let s;if(n==="length")return s=r.length,s;if(Symbol.iterator===n)s=function*(){for(let a of r)yield ne(a)};else{if(r.length>0)if(Object.getPrototypeOf(r[0])===Object.prototype){let a=r[0];a[n]===void 0?s=a[e++]:s=Reflect.get(a,n,i)}else r[0]instanceof le&&(r[n]===void 0?s=r[e++]:s=Reflect.get(r,n,i));else s=Reflect.get(t,n,i);s=ne(s)}return s}})}var ox=class extends le{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new ax(this,e)}setup(){return this.call()}},bD=[!1,!0],vD=[0,1,2,3],SD=[-1,-2],QM=[.5,1.5,1/3,1e-6,1e6,Math.PI,Math.PI*2,1/Math.PI,2/Math.PI,1/(Math.PI*2),Math.PI/2],Gv=new Map;for(let r of bD)Gv.set(r,new os(r));var zv=new Map;for(let r of vD)zv.set(r,new os(r,"uint"));var Hv=new Map([...zv].map(r=>new os(r.value,"int")));for(let r of SD)Hv.set(r,new os(r,"int"));var gg=new Map([...Hv].map(r=>new os(r.value)));for(let r of QM)gg.set(r,new os(r));for(let r of QM)gg.set(-r,new os(-r));var yg={bool:Gv,uint:zv,ints:Hv,float:gg},A1=new Map([...Gv,...gg]),lx=(r,e)=>A1.has(r)?A1.get(r):r.isNode===!0?r:new os(r,e),nn=function(r,e=null){return(...t)=>{for(let i of t)if(i===void 0)return G(`TSL: Invalid parameter for the type "${r}".`,new Dt),new os(0,r);if((t.length===0||!["bool","float","int","uint"].includes(r)&&t.every(i=>{let s=typeof i;return s!=="object"&&s!=="function"}))&&(t=[Vv(r,...t)]),t.length===1&&e!==null&&e.has(t[0]))return _h(e.get(t[0]));if(t.length===1){let i=lx(t[0],r);return i.nodeType===r?_h(i):_h(new nm(i,r))}let n=t.map(i=>lx(i));return _h(new tx(n,r))}};function fu(r){return r&&r.isNode&&r.traverse(e=>{e.isConstNode&&(r=e.value)}),!!r}var ew=r=>r!=null?r.nodeType||r.convertTo||(typeof r=="string"?r:null):null;function au(r,e){return new ox(r,e)}var ne=(r,e=null)=>fD(r,e),_h=(r,e=null)=>ne(r,e).toVarIntent(),xg=(r,e=null)=>new mD(r,e),Qo=(r,e=null)=>new gD(r,e),Me=(r,e=null,t=null,n=null)=>new ZM(r,e,t,n),Y=(r,...e)=>new yD(r,...e),H=(r,e=null,t=null,n={})=>new ZM(r,e,t,{...n,intent:!0}),Wv=(r,e)=>new Proxy(r,{get(t,n,i){return Reflect.get(e,n,i)},set(t,n,i){return Reflect.set(e,n,i)}}),TD=0,cx=class extends le{constructor(e,t=null){super();let n=null;t!==null&&(typeof t=="object"?n=t.return:(typeof t=="string"?n=t:G("TSL: Invalid layout type.",new Dt),t=null)),this.shaderNode=new au(e,n),t!==null&&this.setLayout(t),this.isFn=!0}setLayout(e){let t=this.shaderNode.nodeType;if(typeof e.inputs!="object"){let n={name:"fn"+TD++,type:t,inputs:[]};for(let i in e)i!=="return"&&n.inputs.push({name:i,type:e[i]});e=n}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){let t=this.shaderNode.call(e);return this.shaderNode.nodeType==="void"&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){let t=this.getNodeType(e);return G('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}};function P(r,e=null){let t=new cx(r,e);return new Proxy(()=>{},{apply(n,i,s){return t.call(...s)},get(n,i,s){return Reflect.get(t,i,s)},set(n,i,s,a){return Reflect.set(t,i,s,a)}})}var Ph=r=>{Za=r},qv=()=>Za,oe=(...r)=>Za.If(...r),MD=(...r)=>Za.Switch(...r);function _g(r){return Za&&Za.addToStack(r),r}F("toStack",_g);var tw=new nn("color"),v=new nn("float",yg.float),C=new nn("int",yg.ints),V=new nn("uint",yg.uint),Bi=new nn("bool",yg.bool),$=new nn("vec2"),Rt=new nn("ivec2"),$v=new nn("uvec2"),nw=new nn("bvec2"),N=new nn("vec3"),Xv=new nn("ivec3"),ml=new nn("uvec3"),Yv=new nn("bvec3"),J=new nn("vec4"),jv=new nn("ivec4"),Kv=new nn("uvec4"),iw=new nn("bvec4"),bg=new nn("mat2"),yn=new nn("mat3"),ja=new nn("mat4");F("toColor",tw);F("toFloat",v);F("toInt",C);F("toUint",V);F("toBool",Bi);F("toVec2",$);F("toIVec2",Rt);F("toUVec2",$v);F("toBVec2",nw);F("toVec3",N);F("toIVec3",Xv);F("toUVec3",ml);F("toBVec3",Yv);F("toVec4",J);F("toIVec4",jv);F("toUVec4",Kv);F("toBVec4",iw);F("toMat2",bg);F("toMat3",yn);F("toMat4",ja);var sw=Me(Hr).setParameterLength(2),rw=(r,e)=>new nm(ne(r),e),wD=(r,e)=>new im(ne(r),e);F("element",sw);F("convert",rw);var ED=r=>(X("TSL: append() has been renamed to Stack().",new Dt),_g(r));F("append",r=>(X("TSL: .append() has been renamed to .toStack().",new Dt),_g(r)));var Oe=class extends le{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1,i=null){super(e),this.name=t,this.varying=n,this.placeholderNode=ne(i),this.isPropertyNode=!0,this.global=!0}getNodeType(e){let t=super.getNodeType(e);return t==="output"?e.getOutputType():t}customCacheKey(){return Mu(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;if(this.varying===!0)t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0;else if(t=e.getVarFromNode(this,this.name),this.placeholderNode!==null&&e.hasWriteUsage(this)===!1){let n=this.placeholderNode.build(e,this.getNodeType(e));e.addLineFlowCode(`${e.getPropertyName(t)} = ${n}`,this)}return e.getPropertyName(t)}},$r=(r,e,t=null)=>new Oe(r,e,!1,t),gl=(r,e,t=null)=>new Oe(r,e,!0,t),$e=Y(Oe,"vec4","DiffuseColor"),Xo=Y(Oe,"vec3","DiffuseContribution"),ux=Y(Oe,"vec3","EmissiveColor"),tr=Y(Oe,"float","Roughness"),zr=Y(Oe,"float","Metalness"),sm=Y(Oe,"float","Clearcoat"),lu=Y(Oe,"float","ClearcoatRoughness"),Di=Y(Oe,"vec3","Sheen"),za=Y(Oe,"float","SheenRoughness"),vg=Y(Oe,"float","Iridescence"),rm=Y(Oe,"float","IridescenceIOR"),am=Y(Oe,"float","IridescenceThickness"),om=Y(Oe,"float","AlphaT"),Ga=Y(Oe,"float","Anisotropy"),Th=Y(Oe,"vec3","AnisotropyT"),el=Y(Oe,"vec3","AnisotropyB"),Ja=Y(Oe,"color","SpecularColor"),jo=Y(Oe,"color","SpecularColorBlended"),Ko=Y(Oe,"float","SpecularF90"),lm=Y(Oe,"float","Shininess"),cu=Y(Oe,"output","Output"),tl=Y(Oe,"float","dashSize"),Dh=Y(Oe,"float","gapSize"),RD=Y(Oe,"float","pointWidth"),Mh=Y(Oe,"float","IOR"),cm=Y(Oe,"float","Transmission"),Zv=Y(Oe,"float","Thickness"),Jv=Y(Oe,"float","AttenuationDistance"),Qv=Y(Oe,"color","AttenuationColor"),eS=Y(Oe,"float","Dispersion"),dx=Y(Oe,"float","AmbientOcclusion",!1,1),um=class extends le{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1,i=null){super("string"),this.name=e,this.shared=t,this.order=n,this.updateType=i,this.isUniformGroup=!0}update(){this.needsUpdate=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}},aw=(r,e=1,t=null)=>new um(r,!1,e,t),Sg=(r,e=0,t=null)=>new um(r,!0,e,t),AD=Sg("frame",0,pe.FRAME),de=Sg("render",0,pe.RENDER),ow=aw("object",1,pe.OBJECT),al=class extends Nh{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=ow}setName(e){return this.name=e,this}label(e){return X('TSL: "label()" has been deprecated. Use "setName()" instead.',new Dt),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(n=>{let i=e(n,this);i!==void 0&&(this.value=i)},t)}getInputType(e){let t=super.getInputType(e);return t==="bool"&&(t="uint"),t}generate(e,t){let n=this.getNodeType(e),i=this.getUniformHash(e),s=e.getNodeFromHash(i);s===void 0&&(e.setHashNode(this,i),s=this);let a=s.getInputType(e),o=e.getUniformFromNode(s,a,e.shaderStage,this.name||e.context.nodeName),l=e.getPropertyName(o);e.context.nodeName!==void 0&&delete e.context.nodeName;let c=l;if(n==="bool"){let u=e.getDataFromNode(this),d=u.propertyName;if(d===void 0){let h=e.getVarFromNode(this,null,"bool");d=e.getPropertyName(h),u.propertyName=d,c=e.format(l,a,n),e.addLineFlowCode(`${d} = ${c}`,this)}c=d}return e.format(c,n,t)}},ie=(r,e)=>{let t=ew(e||r);if(t===r&&(r=Vv(t)),r&&r.isNode===!0){let n=r.value;r.traverse(i=>{i.isConstNode===!0&&(n=i.value)}),r=n}return new al(r,t)},dm=class extends ht{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getArrayCount(){return this.count}generateNodeType(e){return this.nodeType===null?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return this.nodeType===null?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){let t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}},lw=(...r)=>{let e;if(r.length===1){let t=r[0];e=new dm(null,t.length,t)}else{let t=r[0],n=r[1];e=new dm(t,n)}return ne(e)};F("toArray",(r,e)=>lw(Array(e).fill(r)));var hx=class extends ht{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(e,t){return t!=="void"?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){let{targetNode:t}=this;if(e.isAvailable("swizzleAssign")===!1&&t.isSplitNode&&t.components.length>1){let n=e.getTypeLength(t.node.getNodeType(e));return fl.join("").slice(0,n)!==t.components}return!1}setup(e){let{targetNode:t,sourceNode:n}=this,i=t.getScope(),s=e.getDataFromNode(i);s.assign=!0;let a=e.getNodeProperties(this);a.sourceNode=n,a.targetNode=t.context({assign:!0})}generate(e,t){let{targetNode:n,sourceNode:i}=e.getNodeProperties(this),s=this.needsSplitAssign(e),a=n.build(e),o=n.getNodeType(e),l=i.build(e,o),c=i.getNodeType(e),u=e.getDataFromNode(this),d;if(u.initialized===!0)t!=="void"&&(d=a);else if(s){let h=e.getVarFromNode(this,null,o),p=e.getPropertyName(h);e.addLineFlowCode(`${p} = ${l}`,this);let f=n.node,y=f.node.context({assign:!0}).build(e);for(let x=0;x<f.components.length;x++){let b=f.components[x];e.addLineFlowCode(`${y}.${b} = ${p}[ ${x} ]`,this)}t!=="void"&&(d=a)}else d=`${a} = ${l}`,(t==="void"||c==="void")&&(e.addLineFlowCode(d,this),t!=="void"&&(d=a));return u.initialized=!0,e.format(d,o,t)}},cw=Me(hx).setParameterLength(2);F("assign",cw);var px=class extends ht{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}generateNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){let t=[],n=this.functionNode,i=n.getInputs(e),s=this.parameters,a=(l,c)=>{let u=c.type,d=u==="pointer",h;return d?h="&"+l.build(e):h=l.build(e,u),h};if(Array.isArray(s)){if(s.length>i.length)G("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),s.length=i.length;else if(s.length<i.length)for(G("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");s.length<i.length;)s.push(v(0));for(let l=0;l<s.length;l++)t.push(a(s[l],i[l]))}else for(let l of i){let c=s[l.name];c!==void 0?t.push(a(c,l)):(G(`TSL: Input '${l.name}' not found in 'Fn()'.`),t.push(a(v(0),l)))}return`${n.build(e,"property")}( ${t.join(", ")} )`}},uw=(r,...e)=>(e=e.length>1||e[0]&&e[0].isNode===!0?Qo(e):xg(e[0]),new px(ne(r),e));F("call",uw);var CD={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"},It=class r extends ht{static get type(){return"OperatorNode"}constructor(e,t,n,...i){if(super(),i.length>0){let s=new r(e,t,n);for(let a=0;a<i.length-1;a++)s=new r(e,s,i[a]);t=s,n=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=n,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(CD[this.op],t)}generateNodeType(e,t=null){let n=this.op,i=this.aNode,s=this.bNode,a=i.getNodeType(e),o=s?s.getNodeType(e):null;if(a==="void"||o==="void")return t||"void";if(n==="%")return a;if(n==="~"||n==="&"||n==="|"||n==="^"||n===">>"||n==="<<")return e.getIntegerType(a);if(n==="&&"||n==="||"||n==="^^")return"bool";if(n==="!"){let l=e.getTypeLength(a);return l>1?`bvec${l}`:"bool"}else if(n==="=="||n==="!="||n==="<"||n===">"||n==="<="||n===">="){let l=Math.max(e.getTypeLength(a),e.getTypeLength(o));return l>1?`bvec${l}`:"bool"}else{if(e.isMatrix(a)){if(o==="float")return a;if(e.isVector(o))return e.getVectorFromMatrix(a);if(e.isMatrix(o))return a}else if(e.isMatrix(o)){if(a==="float")return o;if(e.isVector(a))return e.getVectorFromMatrix(o)}return e.getTypeLength(o)>e.getTypeLength(a)?o:a}}generate(e,t){let n=this.op,{aNode:i,bNode:s}=this,a=this.getNodeType(e,t),o=null,l=null;a!=="void"?(o=i.getNodeType(e),l=s?s.getNodeType(e):null,n==="<"||n===">"||n==="<="||n===">="||n==="=="||n==="!="?e.isVector(o)?l=o:e.isVector(l)?o=l:o!==l&&(o=l="float"):n===">>"||n==="<<"?(o=a,l=e.changeComponentType(l,"uint")):n==="%"?(o=a,l=e.isInteger(o)&&e.isInteger(l)?l:o):e.isMatrix(o)?l==="float"?l="float":e.isVector(l)?l=e.getVectorFromMatrix(o):e.isMatrix(l)||(o=l=a):e.isMatrix(l)?o==="float"?o="float":e.isVector(o)?o=e.getVectorFromMatrix(l):o=l=a:o=l=a):o=l=a;let c=i.build(e,o),u=s?s.build(e,l):null,d=e.getFunctionOperator(n);if(t!=="void"){let h=e.renderer.coordinateSystem===qn;if(n==="=="||n==="!="||n==="<"||n===">"||n==="<="||n===">=")return h?e.isVector(o)?e.format(`${this.getOperatorMethod(e,t)}( ${c}, ${u} )`,a,t):e.format(`( ${c} ${n} ${u} )`,a,t):e.format(`( ${c} ${n} ${u} )`,a,t);if(n==="%")return e.isInteger(l)?e.format(`( ${c} % ${u} )`,a,t):e.format(`${this.getOperatorMethod(e,a)}( ${c}, ${u} )`,a,t);if(n==="!")return h&&e.isVector(o)?e.format(`not( ${c} )`,t):e.format(`( ${n} ${c} )`,o,t);if(n==="~")return e.format(`( ${n} ${c} )`,o,t);if(d)return e.format(`${d}( ${c}, ${u} )`,a,t);if(e.isMatrix(o)&&l==="float")return e.format(`( ${u} ${n} ${c} )`,a,t);if(o==="float"&&e.isMatrix(l))return e.format(`${c} ${n} ${u}`,a,t);{let p=`( ${c} ${n} ${u} )`;return!h&&a==="bool"&&e.isVector(o)&&e.isVector(l)&&(p=`all${p}`),e.format(p,a,t)}}else if(o!=="void")return d?e.format(`${d}( ${c}, ${u} )`,a,t):e.isMatrix(o)&&l==="float"?e.format(`${u} ${n} ${c}`,a,t):e.format(`${c} ${n} ${u}`,a,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}},Wt=H(It,"+").setParameterLength(2,1/0).setName("add"),Ie=H(It,"-").setParameterLength(2,1/0).setName("sub"),xe=H(It,"*").setParameterLength(2,1/0).setName("mul"),Ui=H(It,"/").setParameterLength(2,1/0).setName("div"),Tg=H(It,"%").setParameterLength(2).setName("mod"),dw=H(It,"==").setParameterLength(2).setName("equal"),hw=H(It,"!=").setParameterLength(2).setName("notEqual"),pw=H(It,"<").setParameterLength(2).setName("lessThan"),tS=H(It,">").setParameterLength(2).setName("greaterThan"),fw=H(It,"<=").setParameterLength(2).setName("lessThanEqual"),mw=H(It,">=").setParameterLength(2).setName("greaterThanEqual"),gw=H(It,"&&").setParameterLength(2,1/0).setName("and"),yw=H(It,"||").setParameterLength(2,1/0).setName("or"),xw=H(It,"!").setParameterLength(1).setName("not"),_w=H(It,"^^").setParameterLength(2).setName("xor"),bw=H(It,"&").setParameterLength(2).setName("bitAnd"),vw=H(It,"~").setParameterLength(1).setName("bitNot"),Sw=H(It,"|").setParameterLength(2).setName("bitOr"),Tw=H(It,"^").setParameterLength(2).setName("bitXor"),Mw=H(It,"<<").setParameterLength(2).setName("shiftLeft"),ww=H(It,">>").setParameterLength(2).setName("shiftRight"),Ew=P(([r])=>(r.addAssign(1),r)),Rw=P(([r])=>(r.subAssign(1),r)),Aw=P(([r])=>{let e=C(r).toConst();return r.addAssign(1),e}),Cw=P(([r])=>{let e=C(r).toConst();return r.subAssign(1),e});F("add",Wt);F("sub",Ie);F("mul",xe);F("div",Ui);F("mod",Tg);F("equal",dw);F("notEqual",hw);F("lessThan",pw);F("greaterThan",tS);F("lessThanEqual",fw);F("greaterThanEqual",mw);F("and",gw);F("or",yw);F("not",xw);F("xor",_w);F("bitAnd",bw);F("bitNot",vw);F("bitOr",Sw);F("bitXor",Tw);F("shiftLeft",Mw);F("shiftRight",ww);F("incrementBefore",Ew);F("decrementBefore",Rw);F("increment",Aw);F("decrement",Cw);var I=class r extends ht{static get type(){return"MathNode"}constructor(e,t,n=null,i=null){if(super(),(e===r.MAX||e===r.MIN)&&arguments.length>3){let s=new r(e,t,n);for(let a=3;a<arguments.length-1;a++)s=new r(e,s,arguments[a]);t=s,n=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=n,this.cNode=i,this.isMathNode=!0}getInputType(e){let t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,s=e.isMatrix(t)?0:e.getTypeLength(t),a=e.isMatrix(n)?0:e.getTypeLength(n),o=e.isMatrix(i)?0:e.getTypeLength(i);return s>a&&s>o?t:a>o?n:o>s?i:t}generateNodeType(e){let t=this.method;return t===r.LENGTH||t===r.DISTANCE||t===r.DOT?"float":t===r.CROSS?"vec3":t===r.ALL||t===r.ANY?"bool":t===r.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){let{aNode:t,bNode:n,method:i}=this,s=null;if(i===r.ONE_MINUS)s=Ie(1,t);else if(i===r.RECIPROCAL)s=Ui(1,t);else if(i===r.DIFFERENCE)s=rt(Ie(t,n));else if(i===r.TRANSFORM_DIRECTION){let a,o;e.isMatrix(t.getNodeType(e))?(a=t,o=n):(a=n,o=t),s=kn(xe(a,J(N(o),0)).xyz)}return s!==null?s:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let i=this.method,s=this.getNodeType(e),a=this.getInputType(e),o=this.aNode,l=this.bNode,c=this.cNode,u=e.renderer.coordinateSystem;if(i===r.NEGATE)return e.format("( - "+o.build(e,a)+" )",s,t);{let d=[];return i===r.CROSS?d.push(o.build(e,s),l.build(e,s)):u===qn&&i===r.STEP?d.push(o.build(e,e.getTypeLength(o.getNodeType(e))===1?"float":a),l.build(e,a)):u===qn&&(i===r.MIN||i===r.MAX)?d.push(o.build(e,a),l.build(e,e.getTypeLength(l.getNodeType(e))===1?"float":a)):i===r.REFRACT?d.push(o.build(e,a),l.build(e,a),c.build(e,"float")):i===r.MIX?d.push(o.build(e,a),l.build(e,a),c.build(e,e.getTypeLength(c.getNodeType(e))===1?"float":a)):(u===di&&i===r.ATAN&&l!==null&&(i="atan2"),e.shaderStage!=="fragment"&&(i===r.DFDX||i===r.DFDY)&&(X(`TSL: '${i}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),i="/*"+i+"*/"),d.push(o.build(e,a)),l!==null&&d.push(l.build(e,a)),c!==null&&d.push(c.build(e,a))),e.format(`${e.getMethod(i,s)}( ${d.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}};I.ALL="all";I.ANY="any";I.RADIANS="radians";I.DEGREES="degrees";I.EXP="exp";I.EXP2="exp2";I.LOG="log";I.LOG2="log2";I.SQRT="sqrt";I.INVERSE_SQRT="inversesqrt";I.FLOOR="floor";I.CEIL="ceil";I.NORMALIZE="normalize";I.FRACT="fract";I.SIN="sin";I.SINH="sinh";I.COS="cos";I.COSH="cosh";I.TAN="tan";I.TANH="tanh";I.ASIN="asin";I.ASINH="asinh";I.ACOS="acos";I.ACOSH="acosh";I.ATAN="atan";I.ATANH="atanh";I.ABS="abs";I.SIGN="sign";I.LENGTH="length";I.NEGATE="negate";I.ONE_MINUS="oneMinus";I.DFDX="dFdx";I.DFDY="dFdy";I.ROUND="round";I.RECIPROCAL="reciprocal";I.TRUNC="trunc";I.FWIDTH="fwidth";I.TRANSPOSE="transpose";I.DETERMINANT="determinant";I.INVERSE="inverse";I.EQUALS="equals";I.MIN="min";I.MAX="max";I.STEP="step";I.REFLECT="reflect";I.DISTANCE="distance";I.DIFFERENCE="difference";I.DOT="dot";I.CROSS="cross";I.POW="pow";I.TRANSFORM_DIRECTION="transformDirection";I.MIX="mix";I.CLAMP="clamp";I.REFRACT="refract";I.SMOOTHSTEP="smoothstep";I.FACEFORWARD="faceforward";var Mg=v(1e-6),ND=v(1e6),hm=v(Math.PI),PD=v(Math.PI*2),DD=v(Math.PI*2),ID=v(Math.PI*.5),Nw=H(I,I.ALL).setParameterLength(1),Pw=H(I,I.ANY).setParameterLength(1),Dw=H(I,I.RADIANS).setParameterLength(1),Iw=H(I,I.DEGREES).setParameterLength(1),nS=H(I,I.EXP).setParameterLength(1),mu=H(I,I.EXP2).setParameterLength(1),wg=H(I,I.LOG).setParameterLength(1),ir=H(I,I.LOG2).setParameterLength(1),Qn=H(I,I.SQRT).setParameterLength(1),iS=H(I,I.INVERSE_SQRT).setParameterLength(1),sr=H(I,I.FLOOR).setParameterLength(1),Eg=H(I,I.CEIL).setParameterLength(1),kn=H(I,I.NORMALIZE).setParameterLength(1),Cs=H(I,I.FRACT).setParameterLength(1),Kn=H(I,I.SIN).setParameterLength(1),Fw=H(I,I.SINH).setParameterLength(1),ws=H(I,I.COS).setParameterLength(1),Lw=H(I,I.COSH).setParameterLength(1),Bw=H(I,I.TAN).setParameterLength(1),Uw=H(I,I.TANH).setParameterLength(1),Ow=H(I,I.ASIN).setParameterLength(1),kw=H(I,I.ASINH).setParameterLength(1),sS=H(I,I.ACOS).setParameterLength(1),Vw=H(I,I.ACOSH).setParameterLength(1),rS=H(I,I.ATAN).setParameterLength(1,2),Gw=H(I,I.ATANH).setParameterLength(1),rt=H(I,I.ABS).setParameterLength(1),aS=H(I,I.SIGN).setParameterLength(1),rr=H(I,I.LENGTH).setParameterLength(1),oS=H(I,I.NEGATE).setParameterLength(1),zw=H(I,I.ONE_MINUS).setParameterLength(1),lS=H(I,I.DFDX).setParameterLength(1),cS=H(I,I.DFDY).setParameterLength(1),Hw=H(I,I.ROUND).setParameterLength(1),Ww=H(I,I.RECIPROCAL).setParameterLength(1),uS=H(I,I.TRUNC).setParameterLength(1),dS=H(I,I.FWIDTH).setParameterLength(1),qw=H(I,I.TRANSPOSE).setParameterLength(1),$w=H(I,I.DETERMINANT).setParameterLength(1),Xw=H(I,I.INVERSE).setParameterLength(1),gi=H(I,I.MIN).setParameterLength(2,1/0),At=H(I,I.MAX).setParameterLength(2,1/0),ol=H(I,I.STEP).setParameterLength(2),Yw=H(I,I.REFLECT).setParameterLength(2),jw=H(I,I.DISTANCE).setParameterLength(2),Kw=H(I,I.DIFFERENCE).setParameterLength(2),ls=H(I,I.DOT).setParameterLength(2),Wr=H(I,I.CROSS).setParameterLength(2),ss=H(I,I.POW).setParameterLength(2),hS=r=>xe(r,r),Zw=r=>xe(r,r,r),pS=r=>xe(r,r,r,r),Jw=H(I,I.TRANSFORM_DIRECTION).setParameterLength(2),Qw=(r,e)=>kn(xe(e,J(N(r),0)).xyz),eE=(r,e)=>kn(J(N(r),0).mul(e).xyz),tE=r=>xe(aS(r),ss(rt(r),1/3)),fS=r=>ls(r,r),Re=H(I,I.MIX).setParameterLength(3),Ns=(r,e=0,t=1)=>new I(I.CLAMP,ne(r),ne(e),ne(t)),Rg=r=>Ns(r),mS=H(I,I.REFRACT).setParameterLength(3),Oi=H(I,I.SMOOTHSTEP).setParameterLength(3),gS=H(I,I.FACEFORWARD).setParameterLength(3),nE=P(([r])=>{let n=43758.5453,i=ls(r.xy,$(12.9898,78.233)),s=Tg(i,hm);return Cs(Kn(s).mul(n))}),iE=(r,e,t)=>Re(e,t,r),sE=(r,e,t)=>Oi(e,t,r),rE=(r,e)=>ol(e,r),FD=gS,LD=iS;F("all",Nw);F("any",Pw);F("radians",Dw);F("degrees",Iw);F("exp",nS);F("exp2",mu);F("log",wg);F("log2",ir);F("sqrt",Qn);F("inverseSqrt",iS);F("floor",sr);F("ceil",Eg);F("normalize",kn);F("fract",Cs);F("sin",Kn);F("sinh",Fw);F("cos",ws);F("cosh",Lw);F("tan",Bw);F("tanh",Uw);F("asin",Ow);F("asinh",kw);F("acos",sS);F("acosh",Vw);F("atan",rS);F("atanh",Gw);F("abs",rt);F("sign",aS);F("length",rr);F("lengthSq",fS);F("negate",oS);F("oneMinus",zw);F("dFdx",lS);F("dFdy",cS);F("round",Hw);F("reciprocal",Ww);F("trunc",uS);F("fwidth",dS);F("min",gi);F("max",At);F("step",rE);F("reflect",Yw);F("distance",jw);F("dot",ls);F("cross",Wr);F("pow",ss);F("pow2",hS);F("pow3",Zw);F("pow4",pS);F("transformDirection",Jw);F("transformNormalByViewMatrix",Qw);F("transformNormalByInverseViewMatrix",eE);F("mix",iE);F("clamp",Ns);F("refract",mS);F("smoothstep",sE);F("faceForward",gS);F("difference",Kw);F("saturate",Rg);F("cbrt",tE);F("transpose",qw);F("determinant",$w);F("inverse",Xw);F("rand",nE);var fx=class extends le{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}generateNodeType(e){let{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(t===void 0)return e.flowBuildStage(this,"setup"),this.getNodeType(e);let i=t.getNodeType(e);if(n!==null){let s=n.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(i))return s}return i}setup(e){let t=this.condNode,n=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,s=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=s,i!==null&&(e.getDataFromNode(i).parentNodeBlock=s);let a=e.context.uniformFlow,o=e.getNodeProperties(this);o.condNode=t,o.ifNode=a?n:n.context({nodeBlock:n}),o.elseNode=i?a?i:i.context({nodeBlock:i}):null}generate(e,t){let n=this.getNodeType(e),i=e.getDataFromNode(this);if(i.nodeProperty!==void 0)return i.nodeProperty;let{condNode:s,ifNode:a,elseNode:o}=e.getNodeProperties(this),l=e.currentFunctionNode,c=t!=="void",u=c?$r(n).build(e):"";i.nodeProperty=u;let d=s.build(e,"bool");if(e.context.uniformFlow&&o!==null){let f=a.build(e,n),m=o.build(e,n),y=e.getTernary(d,f,m);return e.format(y,n,t)}e.addFlowCode(`
${e.tab}if ( ${d} ) {
`).addFlowTab();let p=a.build(e,n);if(p&&(c?p=u+" = "+p+";":(p="return "+p+";",l===null&&(X("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),p="// "+p))),e.removeFlowTab().addFlowCode(e.tab+" "+p+`
`+e.tab+"}"),o!==null){e.addFlowCode(` else {
`).addFlowTab();let f=o.build(e,n);f&&(c?f=u+" = "+f+";":(f="return "+f+";",l===null&&(X("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),f="// "+f))),e.removeFlowTab().addFlowCode(e.tab+" "+f+`
`+e.tab+`}
`)}else e.addFlowCode(`
`);return e.format(u,n,t)}},On=Me(fx).setParameterLength(2,3);F("select",On);var Ih=class extends le{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){let e=[];return this.traverse(t=>{t.isContextNode===!0&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){let t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){let t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){let n=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(n),i}},Xr=(r=null,e={})=>{let t=r;return(t===null||t.isNode!==!0)&&(e=t||e,t=null),new Ih(t,e)},aE=r=>Xr(r,{uniformFlow:!0}),yS=(r,e)=>Xr(r,{nodeName:e});function oE(r,e,t=null){return Xr(t,{getShadow:({light:n,shadowColorNode:i})=>e===n?i.mul(r):i})}function lE(r,e=null){return Xr(e,{getAO:(t,{material:n})=>n.transparent===!0?t:t!==null?t.mul(r):r})}function cE(r,e){return X('TSL: "label()" has been deprecated. Use "setName()" instead.'),yS(r,e)}F("context",Xr);F("label",cE);F("uniformFlow",aE);F("setName",yS);F("builtinShadowContext",(r,e,t)=>oE(e,t,r));F("builtinAOContext",(r,e)=>lE(e,r));var uu=class extends le{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return e.getDataFromNode(this).forceDeclaration===!0?!1:this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){let t=e[0],n=this.getShared(t);if(this!==n)return n.build(...e);if(this._hasStack(t)===!1&&t.buildStage==="setup"&&(t.context.nodeLoop||t.context.nodeBlock)){let i=!1;if(this.node.isShaderCallNodeInternal&&this.node.shaderNode.getLayout()===null&&t.fnCall&&t.fnCall.shaderNode&&t.getDataFromNode(this.node.shaderNode).hasLoop){let o=t.getDataFromNode(this);o.forceDeclaration=!0,i=!0}let s=t.getBaseStack();i?s.addToStackBefore(this):s.addToStack(this)}return this.isIntent(t)&&this.isAssign(t)!==!0?this.node.build(...e):super.build(...e)}generate(e){let{node:t,name:n,readOnly:i}=this,{renderer:s}=e,a=s.backend.isWebGPUBackend===!0,o=!1,l=!1;i&&(o=e.isDeterministic(t),l=a?i:o);let c=this.getNodeType(e);if(c=="void")return this.isIntent(e)!==!0&&G('TSL: ".toVar()" can not be used with void type.',this.stackTrace),t.build(e);let u=e.getVectorType(c),d=t.build(e,u),h=e.getVarFromNode(this,n,u,void 0,l),p=e.getPropertyName(h),f=p;if(l)if(a)f=o?`const ${p}`:`let ${p}`;else{let m=t.getArrayCount(e);f=`const ${e.getVar(h.type,p,m)}`}return e.addLineFlowCode(`${f} = ${d}`,this),p}_hasStack(e){return e.getDataFromNode(this).stack!==void 0}},xS=Me(uu),uE=(r,e=null)=>xS(r,e).toStack(),dE=(r,e=null)=>xS(r,e,!0).toStack(),hE=r=>xS(r).setIntent(!0).toStack();F("toVar",uE);F("toConst",dE);F("toVarIntent",hE);var mx=class extends le{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(e){if(this.nodeType!==null)return this.nodeType;e.addSubBuild(this.name);let t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);let n=this.node.build(e,...t);return e.removeSubBuild(),n}},nl=(r,e,t=null)=>new mx(ne(r),e,t),gx=class extends le{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=nl(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}generateNodeType(e){return this.node.getNodeType(e)}setupVarying(e){let t=e.getNodeProperties(this),n=t.varying;if(n===void 0){let i=this.name,s=this.getNodeType(e),a=this.interpolationType,o=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,i,s,a,o),t.node=nl(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation=e.shaderStage==="fragment"),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(iu.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(iu.VERTEX,this.node)}generate(e){let t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),i=this.setupVarying(e);if(n[t]===void 0){let s=this.getNodeType(e),a=e.getPropertyName(i,iu.VERTEX);if(e.shaderStage===iu.VERTEX){let o=n.node.build(e,s);e.addLineFlowCode(`${a} = ${o}`,this)}else e.flowNodeFromShaderStage(iu.VERTEX,n.node,s,a);n[t]=a}return e.getPropertyName(i)}},no=Me(gx).setParameterLength(1,2),pE=r=>no(r);F("toVarying",no);F("toVertexStage",pE);var fE=P(([r])=>{let e=r.mul(.9478672986).add(.0521327014).pow(2.4),t=r.mul(.0773993808),n=r.lessThanEqual(.04045);return Re(e,t,n)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),mE=P(([r])=>{let e=r.pow(.41666).mul(1.055).sub(.055),t=r.mul(12.92),n=r.lessThanEqual(.0031308);return Re(e,t,n)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),_S="WorkingColorSpace",BD="OutputColorSpace",Fh=class extends ht{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===_S?Fe.workingColorSpace:t===BD?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){let{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target),s=t;return Fe.enabled===!1||n===i||!n||!i||(Fe.getTransfer(n)===be&&(s=J(fE(s.rgb),s.a)),Fe.getPrimaries(n)!==Fe.getPrimaries(i)&&(s=J(yn(Fe._getMatrix(new ve,n,i)).mul(s.rgb),s.a)),Fe.getTransfer(i)===be&&(s=J(mE(s.rgb),s.a))),s}},gE=(r,e)=>new Fh(ne(r),_S,e),Ag=(r,e)=>new Fh(ne(r),e,_S),UD=(r,e,t)=>new Fh(ne(r),e,t);F("workingToColorSpace",gE);F("colorSpaceToWorking",Ag);var OD=class extends Hr{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){let t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}},pm=class extends le{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=pe.OBJECT}setGroup(e){return this.group=e,this}element(e){return new OD(this,ne(e))}setNodeType(e){let t=ie(null,e);this.group!==null&&t.setGroup(this.group),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){let{properties:t}=this,n=e[t[0]];for(let i=1;i<t.length;i++)n=n[t[i]];return n}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);let e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}},kD=(r,e,t)=>new pm(r,e,t),yx=class extends pm{static get type(){return"RendererReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(de)}updateReference(e){return this.reference=this.renderer!==null?this.renderer:e.renderer,this.reference}},yE=(r,e,t=null)=>new yx(r,e,t),xx=class extends ht{static get type(){return"ToneMappingNode"}constructor(e,t=_E,n=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return vh(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){let t=this.colorNode||e.context.color,n=this._toneMapping;if(n===Ki)return t;let i=null,s=e.renderer.library.getToneMappingFunction(n);return s!==null?i=J(s(t.rgb,this.exposureNode),t.a):(G("ToneMappingNode: Unsupported Tone Mapping configuration.",n),i=t),i}},xE=(r,e,t)=>new xx(r,ne(e),ne(t)),_E=yE("toneMappingExposure","float");F("toneMapping",(r,e,t)=>xE(e,t,r));var C1=new WeakMap;function N1(r,e){let t=C1.get(r);return t===void 0&&(t=new jl(r,e),C1.set(r,t)),t}var er=class extends Nh{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=ha,this.instanced=!1,this.attribute=null,this.global=!0,e&&e.isBufferAttribute===!0&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){let t;if(this.bufferStride===0&&this.bufferOffset===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}generateNodeType(e){return this.bufferType===null&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(this.attribute!==null)return;let t=this.getNodeType(e),n=e.getTypeLength(t),i=this.value,s=this.bufferStride||n,a=this.bufferOffset,o;i.isInterleavedBuffer===!0?o=i:i.isBufferAttribute===!0?o=N1(i.array,s):o=N1(i,s);let l=new ju(o,n,a);o.setUsage(this.usage),this.attribute=l,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){let t=this.getNodeType(e),n=e.context.nodeName;n!==void 0&&delete e.context.nodeName;let i=e.getBufferAttributeFromNode(this,t,n),s=e.getPropertyName(i),a=null;if(e.shaderStage==="vertex"||e.shaderStage==="compute")this.name=s,a=s;else{let o;n&&(o=n+"Varying"),a=no(this,o).build(e,t)}return a}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&this.attribute.isBufferAttribute===!0&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}};function Cg(r,e=null,t=0,n=0,i=ha,s=!1){return e==="mat3"||e===null&&r.itemSize===9?yn(new er(r,"vec3",9,0).setUsage(i).setInstanced(s),new er(r,"vec3",9,3).setUsage(i).setInstanced(s),new er(r,"vec3",9,6).setUsage(i).setInstanced(s)):e==="mat4"||e===null&&r.itemSize===16?ja(new er(r,"vec4",16,0).setUsage(i).setInstanced(s),new er(r,"vec4",16,4).setUsage(i).setInstanced(s),new er(r,"vec4",16,8).setUsage(i).setInstanced(s),new er(r,"vec4",16,12).setUsage(i).setInstanced(s)):new er(r,e,t,n).setUsage(i)}var bS=(r,e=null,t=0,n=0)=>Cg(r,e,t,n),VD=(r,e=null,t=0,n=0)=>Cg(r,e,t,n,ko),Ng=(r,e=null,t=0,n=0)=>Cg(r,e,t,n,ha,!0),vS=(r,e=null,t=0,n=0)=>Cg(r,e,t,n,ko,!0);F("toAttribute",r=>bS(r.value));var tn=class r extends le{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){let t=this.getNodeType(e),n=this.scope,i;if(n===r.VERTEX)i=e.getVertexIndex();else if(n===r.INSTANCE)i=e.getInstanceIndex();else if(n===r.DRAW)i=e.getDrawIndex();else if(n===r.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(n===r.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else if(n===r.SUBGROUP)i=e.getSubgroupIndex();else throw new Error("THREE.IndexNode: Unknown scope: "+n);let s;return e.shaderStage==="vertex"||e.shaderStage==="compute"?s=i:s=no(this).build(e,t),s}};tn.VERTEX="vertex";tn.INSTANCE="instance";tn.SUBGROUP="subgroup";tn.INVOCATION_LOCAL="invocationLocal";tn.INVOCATION_SUBGROUP="invocationSubgroup";tn.DRAW="draw";var bE=Y(tn,tn.VERTEX),As=Y(tn,tn.INSTANCE),GD=Y(tn,tn.SUBGROUP),zD=Y(tn,tn.INVOCATION_SUBGROUP),HD=Y(tn,tn.INVOCATION_LOCAL),vE=Y(tn,tn.DRAW),_x=class extends le{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=pe.OBJECT,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return X('TSL: "label()" has been deprecated. Use "setName()" instead.',new Dt),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){this.count!==null&&this.countNode===null&&(this.countNode=ie(this.count,"uint").onObjectUpdate(()=>this.count));let t=this.computeNode.build(e);if(t){let n=e.getNodeProperties(this);n.outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){let{shaderStage:n}=e;if(n==="compute"){let i=this.computeNode.build(e,"void");if(i!==""&&e.addLineFlowCode(i,this),this.count!==null&&e.allowEarlyReturns===!0){let s=this.countNode.build(e,"uint"),a=As.build(e,"uint");e.flow.code=`${e.tab}if ( ${a} >= ${s} ) { return; }
${e.flow.code}`}}else{let s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}},SS=(r,e=[64])=>{(e.length===0||e.length>3)&&G("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Dt);for(let t=0;t<e.length;t++){let n=e[t];(typeof n!="number"||n<=0||!Number.isInteger(n))&&G(`TSL: compute() workgroupSize element at index [ ${t} ] must be a positive integer`,new Dt)}for(;e.length<3;)e.push(1);return new _x(ne(r),e)},SE=(r,e,t)=>{let n=SS(r,t);return typeof e=="number"?n.count=e:n.dispatchSize=e,n};F("compute",SE);F("computeKernel",SS);var bx=class extends le{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(e){let t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);let i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){let n=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);let s=this.node.build(e,...t);return e.setCache(n),s}setParent(e){return this.parent=e,this}getParent(){return this.parent}},du=r=>new bx(ne(r));function TE(r,e=!0){return X('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),du(r).setParent(e)}F("cache",TE);F("isolate",du);var vx=class extends le{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(e){return this.outputNode.getNodeType(e)}generate(e){let t=this.callNode.build(e,"void");return t!==""&&e.addLineFlowCode(t,this),this.outputNode.build(e)}},ME=Me(vx).setParameterLength(2);F("bypass",ME);var TS=P(([r,e,t,n=v(0),i=v(1),s=Bi(!1)])=>{let a=r.sub(e).div(t.sub(e));return fu(s)&&(a=a.clamp()),a.mul(i.sub(n)).add(n)});function wE(r,e,t,n=v(0),i=v(1)){return TS(r,e,t,n,i,!0)}F("remap",TS);F("remapClamp",wE);var hu=class extends le{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){let n=this.getNodeType(e),i=this.snippet;if(n==="void")e.addLineFlowCode(i,this);else return e.format(i,n,t)}},Fi=Me(hu).setParameterLength(1,2),EE=r=>(r?On(r,Fi("discard")):Fi("discard")).toStack(),WD=()=>Fi("return").toStack();F("discard",EE);var MS=P(([r])=>J(r.rgb.mul(r.a),r.a),{color:"vec4",return:"vec4"}),RE=P(([r])=>r.a.equal(0).select(J(0),J(r.rgb.div(r.a),r.a)),{color:"vec4",return:"vec4"}),Sx=class extends ht{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;t=J(t.rgb,t.a.clamp(0,1)),t=RE(t);let n=(this._toneMapping!==null?this._toneMapping:e.toneMapping)||Ki,i=(this.outputColorSpace!==null?this.outputColorSpace:e.outputColorSpace)||cn;return n!==Ki&&(t=t.toneMapping(n)),i!==cn&&i!==Fe.workingColorSpace&&(t=t.workingToColorSpace(i)),t=MS(t),t}},Pg=(r,e=null,t=null)=>new Sx(ne(r),e,t);F("renderOutput",Pg);var Tx=class extends ht{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){let t=this.callback,n=this.node.build(e);if(t!==null)t(e,n);else{let i="--- TSL debug - "+e.shaderStage+" shader ---",s="-".repeat(i.length),a="";a+="// #"+i+`#
`,a+=e.flow.code.replace(/^t/mg,"")+`
`,a+="/* ... */ "+n+` /* ... */
`,a+="// #"+s+`#
`,qu(a)}return n}},AE=(r,e=null)=>new Tx(ne(r),e).toStack();F("debug",AE);var fm=class extends $n{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}},Mx=class extends le{static get type(){return"InspectorNode"}constructor(e,t="",n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=pe.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return e.context.inspector===!0&&this.callback!==null&&(t=this.callback(t)),e.renderer.backend.isWebGPUBackend!==!0&&e.renderer.inspector.constructor!==fm&&Ce('TSL: ".toInspector()" is only available with WebGPU.'),t}};function CE(r,e="",t=null){return r=ne(r),r.before(new Mx(r,e,t))}F("toInspector",CE);function qD(r){X("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",r)}var mm=class extends le{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(e){let t=this.nodeType;if(t===null){let n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){let i=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){let t=this.getAttributeName(e),n=this.getNodeType(e);if(e.hasGeometryAttribute(t)===!0){let s=e.geometry.getAttribute(t),a=e.getTypeFromAttribute(s),o=e.getAttribute(t,a);return e.shaderStage==="vertex"?e.format(o.name,a,n):no(this).build(e,n)}else return X(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}},Li=(r,e=null)=>new mm(r,e),Ye=(r=0)=>Li("uv"+(r>0?r:""),"vec2"),wx=class extends le{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){let n=this.textureNode.build(e,"property"),i=this.levelNode===null?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${i} )`,this.getNodeType(e),t)}},ll=Me(wx).setParameterLength(1,2),Ex=class extends al{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=pe.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){let e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&n.width!==void 0){let{width:i,height:s}=n;this.value=Math.log2(Math.max(i,s))}}},wS=Me(Ex).setParameterLength(1),gm=class extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}},ES=new mn,cs=class extends al{static get type(){return"TextureNode"}constructor(e=ES,t=null,n=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.gatherNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=pe.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(t===null)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return this.value.isDepthTexture===!0?this.gatherNode===null?"float":"vec4":this.value.type===it?"uvec4":this.value.type===zt?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Ye(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=ie(this.value.matrix)),this._matrixUniform.mul(N(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(this._flipYUniform===null&&(this._flipYUniform=ie(!1)),t=t.toVar(),this.sampler?t=this._flipYUniform.select(t.flipY(),t):t=this._flipYUniform.select(t.setY(C(ll(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){let t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;let n=this.value;if(!n||n.isTexture!==!0)throw new gm("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);let i=P(()=>{let l=this.uvNode;return(l===null||e.context.forceUVContext===!0)&&e.context.getUV&&(l=e.context.getUV(this,e)),l||(l=this.getDefaultUV()),this.updateMatrix===!0&&(l=this.getTransformedUV(l)),l=this.setupUV(e,l),this.updateType=this._matrixUniform!==null||this._flipYUniform!==null?pe.OBJECT:pe.NONE,l})(),s=this.levelNode;s===null&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this));let a=null,o=null;if(this.compareNode!==null)if(e.renderer.hasCompatibility(Fr.TEXTURE_COMPARE))a=this.compareNode;else{let l=n.compareFunction;l===null||l===eh||l===Oo||l===zc||l===La?o=this.compareNode:(a=this.compareNode,Ce('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=s,t.biasNode=this.biasNode,t.compareNode=a,t.compareStepNode=o,t.gradNode=this.gradNode,t.gatherNode=this.gatherNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,this.sampler===!0?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,n,i,s,a,o,l,c,u,d){let h=this.value,p;return s?p=e.generateTextureBias(h,t,n,s,a,u):l?p=e.generateTextureGrad(h,t,n,l,a,u):c?o?p=e.generateTextureGatherCompare(h,t,n,o,a,u,d):p=e.generateTextureGather(h,t,n,c,a,u,d):o?p=e.generateTextureCompare(h,t,n,o,a,u):this.sampler===!1?p=e.generateTextureLoad(h,t,n,i,a,u):i?p=e.generateTextureLevel(h,t,n,i,a,u):p=e.generateTexture(h,t,n,a,u),p}generate(e,t){let n=this.value,i=e.getNodeProperties(this),s=super.generate(e,"property");if(/^sampler/.test(t))return s+"_sampler";if(e.isReference(t))return s;{let a=e.getDataFromNode(this),o=this.getNodeType(e),l=a.propertyName;if(l===void 0){let{uvNode:u,levelNode:d,biasNode:h,compareNode:p,compareStepNode:f,depthNode:m,gradNode:y,gatherNode:x,offsetNode:b}=i,_=this.generateUV(e,u),S=d?d.build(e,"float"):null,M=h?h.build(e,"float"):null,w=m?m.build(e,"int"):null,T=p?p.build(e,"float"):null,R=f?f.build(e,"float"):null,D=y?[y[0].build(e,"vec2"),y[1].build(e,"vec2")]:null,L=x?x.build(e,"int"):null,B=b?this.generateOffset(e,b):null,W=this._flipYUniform?this._flipYUniform.build(e,"bool"):null;L&&(o="vec4");let q=w;q===null&&n.isArrayTexture&&this.isTexture3DNode!==!0&&(q="0");let ce=e.getVarFromNode(this);l=e.getPropertyName(ce);let k=this.generateSnippet(e,s,_,S,M,q,T,D,L,B,W);if(R!==null){let j=n.compareFunction;j===zc||j===La?k=ol(Fi(k,o),Fi(R,"float")).build(e,o):k=ol(Fi(R,"float"),Fi(k,o)).build(e,o)}e.addLineFlowCode(`${l} = ${k}`,this),a.snippet=k,a.propertyName=l}let c=l;return e.needsToWorkingColorSpace(n)&&(c=Ag(Fi(c,o),n.colorSpace).setup(e).build(e,o)),e.format(c,o,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){let t=this.clone();return t.uvNode=ne(e),t.referenceNode=this.getBase(),ne(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){let t=this.clone();t.biasNode=ne(e).mul(wS(t)),t.referenceNode=this.getBase();let n=t.value;return t.generateMipmaps===!1&&(n&&n.generateMipmaps===!1||n.minFilter===vt||n.magFilter===vt)&&(X("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),ne(t)}level(e){let t=this.clone();return t.levelNode=ne(e),t.referenceNode=this.getBase(),ne(t)}size(e){return ll(this,e)}bias(e){let t=this.clone();return t.biasNode=ne(e),t.referenceNode=this.getBase(),ne(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){let t=this.clone();return t.compareNode=ne(e),t.referenceNode=this.getBase(),ne(t)}grad(e,t){let n=this.clone();return n.gradNode=[ne(e),ne(t)],n.referenceNode=this.getBase(),ne(n)}gather(e=0){let t=this.clone();return t.gatherNode=ne(e),t.referenceNode=this.getBase(),ne(t)}depth(e){let t=this.clone();return t.depthNode=ne(e),t.referenceNode=this.getBase(),ne(t)}offset(e){let t=this.clone();return t.offsetNode=ne(e),t.referenceNode=this.getBase(),ne(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){let e=this.value,t=this._matrixUniform;t!==null&&(t.value=e.matrix),e.matrixAutoUpdate===!0&&e.updateMatrix();let n=this._flipYUniform;n!==null&&(n.value=e.image instanceof ImageBitmap&&e.flipY===!0||e.isRenderTargetTexture===!0||e.isFramebufferTexture===!0||e.isDepthTexture===!0)}clone(){let e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}},$D=Me(cs).setParameterLength(1,4).setName("texture"),Ue=(r=ES,e=null,t=null,n=null)=>{let i;return r&&r.isTextureNode===!0?(i=ne(r.clone()),i.referenceNode=r.getBase(),e!==null&&(i.uvNode=ne(e)),t!==null&&(i.levelNode=ne(t)),n!==null&&(i.biasNode=ne(n))):i=$D(r,e,t,n),i},XD=(r=ES)=>Ue(r),Ut=(...r)=>Ue(...r).setSampler(!1),YD=(r,e,t)=>Ue(r,e).level(t),jD=r=>(r.isNode===!0?r:Ue(r)).convert("sampler"),KD=r=>(r.isNode===!0?r:Ue(r)).convert("samplerComparison"),Lh=class extends al{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}},wu=(r,e,t)=>new Lh(r,e,t),Rx=class extends Hr{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){let t=super.generate(e),n=this.getNodeType(e),i=this.node.getPaddedType();return e.format(t,i,n)}},Ax=class extends Lh{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?Xa(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=pe.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){let e=this.elementType,t="vec4";return e==="mat2"?t="mat2":/mat/.test(e)===!0?t="mat4":e.charAt(0)==="i"?t="ivec4":e.charAt(0)==="u"&&(t="uvec4"),t}update(){let{array:e,value:t}=this,n=this.elementType;if(n==="float"||n==="int"||n==="uint")for(let i=0;i<e.length;i++){let s=i*4;t[s]=e[i]}else if(n==="color")for(let i=0;i<e.length;i++){let s=i*4,a=e[i];t[s]=a.r,t[s+1]=a.g,t[s+2]=a.b||0}else if(n==="mat2")for(let i=0;i<e.length;i++){let s=i*4,a=e[i];t[s]=a.elements[0],t[s+1]=a.elements[1],t[s+2]=a.elements[2],t[s+3]=a.elements[3]}else if(n==="mat3")for(let i=0;i<e.length;i++){let s=i*16,a=e[i];t[s]=a.elements[0],t[s+1]=a.elements[1],t[s+2]=a.elements[2],t[s+4]=a.elements[3],t[s+5]=a.elements[4],t[s+6]=a.elements[5],t[s+8]=a.elements[6],t[s+9]=a.elements[7],t[s+10]=a.elements[8],t[s+15]=1}else if(n==="mat4")for(let i=0;i<e.length;i++){let s=i*16,a=e[i];for(let o=0;o<a.elements.length;o++)t[s+o]=a.elements[o]}else for(let i=0;i<e.length;i++){let s=i*4,a=e[i];t[s]=a.x,t[s+1]=a.y,t[s+2]=a.z||0,t[s+3]=a.w||0}}setup(e){let t=this.array.length,n=this.elementType,i=Float32Array,s=this.paddedType,a=e.getTypeLength(s);return n.charAt(0)==="i"&&(i=Int32Array),n.charAt(0)==="u"&&(i=Uint32Array),this.value=new i(t*a),this.bufferCount=t,this.bufferType=s,this.update(),super.setup(e)}element(e){return new Rx(this,ne(e))}},Tn=(r,e)=>new Ax(r,e),Cx=class extends le{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}},Yr=Me(Cx).setParameterLength(1),th,nh,wn=class r extends le{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===r.DPR?"float":this.scope===r.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=pe.NONE;return(this.scope===r.SIZE||this.scope===r.VIEWPORT||this.scope===r.DPR)&&(e=pe.RENDER),this.updateType=e,e}update({renderer:e}){let t=e.getRenderTarget();this.scope===r.VIEWPORT?t!==null?nh.copy(t.viewport):(e.getViewport(nh),nh.multiplyScalar(e.getPixelRatio())):this.scope===r.DPR?this._output.value=e.getPixelRatio():t!==null?(th.width=t.width,th.height=t.height):e.getDrawingBufferSize(th)}setup(){let e=this.scope,t=null;return e===r.SIZE?t=ie(th||(th=new O)):e===r.VIEWPORT?t=ie(nh||(nh=new Ge)):e===r.DPR?t=ie(1):t=$(yl.div(cl)),this._output=t,t}generate(e){if(this.scope===r.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){let n=e.getNodeProperties(cl).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}};wn.COORDINATE="coordinate";wn.VIEWPORT="viewport";wn.SIZE="size";wn.UV="uv";wn.DPR="dpr";var RS=Y(wn,wn.DPR),Rs=Y(wn,wn.UV),cl=Y(wn,wn.SIZE),yl=Y(wn,wn.COORDINATE),pu=Y(wn,wn.VIEWPORT),AS=pu.zw,NE=yl.sub(pu.xy),ZD=NE.div(AS),JD=P(()=>(X('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.',new Dt),cl),"vec2").once()(),gy=null,pf=null,yy=null,ff=null,xy=null,mf=null,_y=null,gf=null,by=null,yf=null,vy=null,xf=null,Sy=null,_f=null,io=ie(0,"uint").setName("u_cameraIndex").setGroup(Sg("cameraIndex")).toVarying("v_cameraIndex"),Ha=ie("float").setName("cameraNear").setGroup(de).onRenderUpdate(({camera:r})=>r.near),Wa=ie("float").setName("cameraFar").setGroup(de).onRenderUpdate(({camera:r})=>r.far),Jn=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){let t=[];for(let n of r.cameras)t.push(n.projectionMatrix);pf===null?pf=Tn(t).setGroup(de).setName("cameraProjectionMatrices"):pf.array=t,e=pf.element(r.isMultiViewCamera?Yr("gl_ViewID_OVR"):io)}else gy===null&&(gy=ie(r.projectionMatrix).setName("cameraProjectionMatrix").setGroup(de).onRenderUpdate(({camera:t})=>t.projectionMatrix)),e=gy;return e}).once()(),PE=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){let t=[];for(let n of r.cameras)t.push(n.projectionMatrixInverse);ff===null?ff=Tn(t).setGroup(de).setName("cameraProjectionMatricesInverse"):ff.array=t,e=ff.element(r.isMultiViewCamera?Yr("gl_ViewID_OVR"):io)}else yy===null&&(yy=ie(r.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(de).onRenderUpdate(({camera:t})=>t.projectionMatrixInverse)),e=yy;return e}).once()(),so=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){let t=[];for(let n of r.cameras)t.push(n.matrixWorldInverse);mf===null?mf=Tn(t).setGroup(de).setName("cameraViewMatrices"):mf.array=t,e=mf.element(r.isMultiViewCamera?Yr("gl_ViewID_OVR"):io)}else xy===null&&(xy=ie(r.matrixWorldInverse).setName("cameraViewMatrix").setGroup(de).onRenderUpdate(({camera:t})=>t.matrixWorldInverse)),e=xy;return e}).once()(),Qh=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){let t=[];for(let n of r.cameras)t.push(n.matrixWorld);gf===null?gf=Tn(t).setGroup(de).setName("cameraWorldMatrices"):gf.array=t,e=gf.element(r.isMultiViewCamera?Yr("gl_ViewID_OVR"):io)}else _y===null&&(_y=ie(r.matrixWorld).setName("cameraWorldMatrix").setGroup(de).onRenderUpdate(({camera:t})=>t.matrixWorld)),e=_y;return e}).once()(),QD=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){let t=[];for(let n of r.cameras)t.push(n.normalMatrix);yf===null?yf=Tn(t).setGroup(de).setName("cameraNormalMatrices"):yf.array=t,e=yf.element(r.isMultiViewCamera?Yr("gl_ViewID_OVR"):io)}else by===null&&(by=ie(r.normalMatrix).setName("cameraNormalMatrix").setGroup(de).onRenderUpdate(({camera:t})=>t.normalMatrix)),e=by;return e}).once()(),DE=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){let t=[];for(let n=0,i=r.cameras.length;n<i;n++)t.push(new E);xf===null?xf=Tn(t).setGroup(de).setName("cameraPositions").onRenderUpdate(({camera:n},i)=>{let s=n.cameras,a=i.array;for(let o=0,l=s.length;o<l;o++)a[o].setFromMatrixPosition(s[o].matrixWorld)}):xf.array=t,e=xf.element(r.isMultiViewCamera?Yr("gl_ViewID_OVR"):io)}else vy===null&&(vy=ie(new E).setName("cameraPosition").setGroup(de).onRenderUpdate(({camera:t},n)=>n.value.setFromMatrixPosition(t.matrixWorld))),e=vy;return e}).once()(),eI=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){let t=[];for(let n of r.cameras)t.push(n.viewport);_f===null?_f=Tn(t,"vec4").setGroup(de).setName("cameraViewports"):_f.array=t,e=_f.element(io)}else Sy===null&&(Sy=J(0,0,cl.x,cl.y).toConst("cameraViewport")),e=Sy;return e}).once()(),P1=new ma,qt=class r extends le{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=pe.OBJECT,this.uniformNode=new al(null)}generateNodeType(){let e=this.scope;if(e===r.WORLD_MATRIX)return"mat4";if(e===r.POSITION||e===r.VIEW_POSITION||e===r.DIRECTION||e===r.SCALE)return"vec3";if(e===r.RADIUS)return"float"}update(e){let t=this.object3d,n=this.uniformNode,i=this.scope;if(i===r.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===r.POSITION)n.value=n.value||new E,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===r.SCALE)n.value=n.value||new E,n.value.setFromMatrixScale(t.matrixWorld);else if(i===r.DIRECTION)n.value=n.value||new E,t.getWorldDirection(n.value);else if(i===r.VIEW_POSITION){let s=e.camera;n.value=n.value||new E,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(s.matrixWorldInverse)}else if(i===r.RADIUS){let s=e.object.geometry;s.boundingSphere===null&&s.computeBoundingSphere(),P1.copy(s.boundingSphere).applyMatrix4(t.matrixWorld),n.value=P1.radius}}generate(e){let t=this.scope;return t===r.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===r.POSITION||t===r.VIEW_POSITION||t===r.DIRECTION||t===r.SCALE?this.uniformNode.nodeType="vec3":t===r.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}};qt.WORLD_MATRIX="worldMatrix";qt.POSITION="position";qt.SCALE="scale";qt.VIEW_POSITION="viewPosition";qt.DIRECTION="direction";qt.RADIUS="radius";var tI=Me(qt,qt.DIRECTION).setParameterLength(1),nI=Me(qt,qt.WORLD_MATRIX).setParameterLength(1),iI=Me(qt,qt.POSITION).setParameterLength(1),sI=Me(qt,qt.SCALE).setParameterLength(1),rI=Me(qt,qt.VIEW_POSITION).setParameterLength(1),aI=Me(qt,qt.RADIUS).setParameterLength(1),yi=class extends qt{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}},oI=Y(yi,yi.DIRECTION),rs=Y(yi,yi.WORLD_MATRIX),lI=Y(yi,yi.POSITION),cI=Y(yi,yi.SCALE),uI=Y(yi,yi.VIEW_POSITION),dI=Y(yi,yi.RADIUS),IE=ie(new ve).onObjectUpdate(({object:r},e)=>e.value.getNormalMatrix(r.matrixWorld)),hI=ie(new Ne).onObjectUpdate(({object:r},e)=>e.value.copy(r.matrixWorld).invert()),cr=P(r=>r.context.modelViewMatrix||FE).once()().toVar("modelViewMatrix"),FE=so.mul(rs),Nx=P(r=>(r.context.isHighPrecisionModelViewMatrix=!0,ie("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),Px=P(r=>{let e=r.context.isHighPrecisionModelViewMatrix;return ie("mat3").onObjectUpdate(({object:t,camera:n})=>(e!==!0&&t.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),LE=P(r=>r.shaderStage!=="fragment"?(Ce("TSL: `clipSpace` is only available in fragment stage."),J()):r.context.clipSpace.toVarying("v_clipSpace")).once()(),Bn=Li("position","vec3"),Mt=Bn.toVarying("positionLocal"),ul=Bn.toVarying("positionPrevious"),ar=P(r=>rs.mul(Mt).xyz.toVarying(r.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),CS=P(()=>Mt.transformDirection(rs).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Ot=P(r=>{if(r.shaderStage==="fragment"&&r.material.vertexNode){let e=PE.mul(LE);return e.xyz.div(e.w).toVar("positionView")}return r.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Qe=P(r=>{let e;return r.camera.isOrthographicCamera?e=N(0,0,1):e=Ot.negate().toVarying("v_positionViewDirection").normalize(),e.toVar("positionViewDirection")},"vec3").once(["POSITION"])(),Dx=class extends le{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if(e.shaderStage!=="fragment")return"true";let{material:t}=e;return t.side===ln?"false":e.getFrontFacing()}},BE=Y(Dx),NS=v(BE).mul(2).sub(1),xl=P(([r],{material:e})=>{let t=e.side;return t===ln?r=r.mul(-1):t===Ri&&(r=r.mul(NS)),r}),pI=r=>(Ce('TSL: "directionToFaceDirection()" has been renamed to "negateOnBackSide()".'),xl(r)),Dg=Li("normal","vec3"),Gn=P(r=>r.geometry.hasAttribute("normal")===!1?(X('TSL: Vertex attribute "normal" not found on geometry.'),N(0,1,0)):Dg,"vec3").once()().toVar("normalLocal"),UE=Ot.dFdx().cross(Ot.dFdy()).normalize().toVar("normalFlat"),gu=P(r=>{let e;return r.isFlatShading()?e=UE:e=DS(Gn).toVarying("v_normalViewGeometry").normalize(),e},"vec3").once()().toVar("normalViewGeometry"),OE=P(r=>{let e=gu.transformNormalByInverseViewMatrix(so);return r.isFlatShading()!==!0&&(e=e.toVarying("v_normalWorldGeometry")),e.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Be=P(r=>{let e;return r.subBuildFn==="NORMAL"||r.subBuildFn==="VERTEX"?(e=gu,r.isFlatShading()!==!0&&(e=xl(e))):e=r.context.setupNormal().context({getUV:null,getTextureLevel:null}),e},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),ro=Be.transformNormalByInverseViewMatrix(so).toVar("normalWorld"),qa=P(({subBuildFn:r,context:e})=>{let t;return r==="NORMAL"||r==="VERTEX"?t=Be:t=e.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),PS=P(([r,e=rs])=>yn(e).inverse().transpose().mul(r).normalize());F("transformNormal",PS);var DS=P(([r],e)=>{let t=e.context.modelNormalViewMatrix;return t?r.transformNormalByViewMatrix(t):IE.mul(r).transformNormalByViewMatrix(so)}),fI=P(()=>(X('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Be)).once(["NORMAL","VERTEX"])(),mI=P(()=>(X('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),ro)).once(["NORMAL","VERTEX"])(),gI=P(()=>(X('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),qa)).once(["NORMAL","VERTEX"])(),Ty=new Ne,kE=ie(0).onReference(({material:r})=>r).onObjectUpdate(({material:r})=>r.refractionRatio),Zf=ie(1).onReference(({material:r})=>r).onObjectUpdate(function({material:r,scene:e}){return r.envMap?r.envMapIntensity:e.environmentIntensity}),ym=ie(new Ne).onReference(function(r){return r.material}).onObjectUpdate(function({material:r,scene:e}){let n=(e.environment!==null||e.environmentNode&&e.environmentNode.isNode)&&r.envMap===null?e.environmentRotation:r.envMapRotation;return n?Ty.makeRotationFromEuler(n).transpose():Ty.identity(),Ty}),VE=Qe.negate().reflect(Be),GE=Qe.negate().refract(Be,kE),zE=VE.transformDirection(Qh).toVar("reflectVector"),HE=GE.transformDirection(Qh).toVar("refractVector"),WE=new xa,Ix=class extends cs{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,i=null){super(e,t,n,i),this.isCubeTextureNode=!0}getInputType(){return this.value.isDepthTexture===!0?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){let e=this.value;return e.mapping===Pr?zE:e.mapping===Ca?HE:(G('CubeTextureNode: Mapping "%s" not supported.',e.mapping),N(0,0,0))}setUpdateMatrix(){}setupUV(e,t){let n=this.value;return n.isDepthTexture===!0?e.renderer.coordinateSystem===di?N(t.x,t.y.negate(),t.z):t:(t=ym.mul(t),(e.renderer.coordinateSystem===di||!n.isRenderTargetTexture)&&(t=N(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}},IS=Me(Ix).setParameterLength(1,4).setName("cubeTexture"),Zn=(r=WE,e=null,t=null,n=null)=>{let i;return r&&r.isCubeTextureNode===!0?(i=ne(r.clone()),i.referenceNode=r,e!==null&&(i.uvNode=ne(e)),t!==null&&(i.levelNode=ne(t)),n!==null&&(i.biasNode=ne(n))):i=IS(r,e,t,n),i},yI=(r=WE)=>IS(r),Fx=class extends Hr{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){let t=super.generate(e),n=this.referenceNode.getNodeType(e),i=this.getNodeType(e);return e.format(t,n,i)}},yu=class extends le{static get type(){return"ReferenceNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=pe.OBJECT}element(e){return new Fx(this,ne(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return X('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;this.count!==null?t=wu(null,e,this.count):Array.isArray(this.getValueFromReference())?(t=Tn(null,e),t.updateType=pe.OBJECT):e==="texture"?t=Ue(null):e==="cubeTexture"?t=Zn(null):t=ie(null,e),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.setName(this.name),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){let{properties:t}=this,n=e[t[0]];for(let i=1;i<t.length;i++)n=n[t[i]];return n}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);let e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}},dt=(r,e,t)=>new yu(r,e,t),qE=(r,e,t,n)=>new yu(r,e,n,t),Lx=class extends yu{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=this.material!==null?this.material:e.material,this.reference}},Vr=(r,e,t=null)=>new Lx(r,e,t),$E=Ye(),xI=Ot.dFdx(),_I=Ot.dFdy(),XE=$E.dFdx(),YE=$E.dFdy(),jE=Be,KE=_I.cross(jE),ZE=jE.cross(xI),Bx=KE.mul(XE.x).add(ZE.mul(YE.x)),Ux=KE.mul(XE.y).add(ZE.mul(YE.y)),D1=Bx.dot(Bx).max(Ux.dot(Ux)),JE=D1.equal(0).select(0,D1.inverseSqrt()),bI=Bx.mul(JE).toVar("tangentViewFrame"),vI=Ux.mul(JE).toVar("bitangentViewFrame"),Ig=Li("tangent","vec4"),Qa=Ig.xyz.toVar("tangentLocal"),Fg=P(r=>{let e;return r.subBuildFn==="VERTEX"||r.geometry.hasAttribute("tangent")?e=cr.mul(J(Qa,0)).xyz.toVarying("v_tangentView").normalize():e=bI,r.isFlatShading()!==!0&&(e=xl(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),QE=Fg.transformDirection(Qh).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),Lg=P(([r,e],t)=>{let n=r.mul(Ig.w).xyz;return t.subBuildFn==="NORMAL"&&t.isFlatShading()!==!0&&(n=n.toVarying(e)),n}).once(["NORMAL"]),SI=Lg(Dg.cross(Ig),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),TI=Lg(Gn.cross(Qa),"v_bitangentLocal").normalize().toVar("bitangentLocal"),eR=P(r=>{let e;return r.subBuildFn==="VERTEX"||r.geometry.hasAttribute("tangent")?e=Lg(Be.cross(Fg),"v_bitangentView").normalize():e=vI,r.isFlatShading()!==!0&&(e=xl(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),MI=Lg(ro.cross(QE),"v_bitangentWorld").normalize().toVar("bitangentWorld"),Zo=yn(Fg,eR,Be).toVar("TBNViewMatrix"),tR=Qe.mul(Zo),wI=(r,e)=>r.sub(tR.mul(e)),nR=P(()=>{let r=el.cross(Qe);return r=r.cross(el).normalize(),r=Re(r,Be,Ga.mul(tr.oneMinus()).oneMinus().pow2().pow2()).normalize(),r}).once()(),FS=r=>ne(r).mul(.5).add(.5),iR=r=>ne(r).mul(2).sub(1),Ox=r=>N(r,Qn(Rg(v(1).sub(ls(r,r))))),EI=r=>(Ce('TSL: "directionToColor()" has been renamed to "packNormalToRGB()".'),FS(r)),RI=r=>(Ce('TSL: "colorToDirection()" has been renamed to "unpackRGBToNormal()".'),iR(r)),kx=class extends ht{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=Ss,this.unpackNormalMode=Qd}setup(e){let{normalMapType:t,scaleNode:n,unpackNormalMode:i}=this,s=this.node.mul(2).sub(1);if(t===Ss?i===af?s=Ox(s.xy):i===X0?s=Ox(s.yw):i!==Qd&&G(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):i!==Qd&&G(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),n!==null){let o=n;e.isFlatShading()===!0&&(o=xl(o)),s=N(s.xy.mul(o),s.z)}let a=null;return t===$0?a=DS(s):t===Ss?a=Zo.mul(s).normalize():(G(`NodeMaterial: Unsupported normal map type: ${t}`),a=Be),a}},Vx=Me(kx).setParameterLength(1,2),AI=P(({textureNode:r,bumpScale:e})=>{let t=i=>r.isolate().context({getUV:s=>i(s.uvNode||Ye()),forceUVContext:!0}),n=v(t(i=>i));return $(v(t(i=>i.add(i.dFdx()))).sub(n),v(t(i=>i.add(i.dFdy()))).sub(n)).mul(e)}),CI=P(r=>{let{surf_pos:e,surf_norm:t,dHdxy:n}=r,i=e.dFdx().normalize(),s=e.dFdy().normalize(),a=t,o=s.cross(a),l=a.cross(i),c=i.dot(o).mul(NS),u=c.sign().mul(n.x.mul(o).add(n.y.mul(l)));return c.abs().mul(t).sub(u).normalize()}),Gx=class extends ht{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(e){if(e.material.wireframe===!0)return Be;let t=this.scaleNode!==null?this.scaleNode:1,n=AI({textureNode:this.textureNode,bumpScale:t});return CI({surf_pos:Ot,surf_norm:Be,dHdxy:n})}},LS=Me(Gx).setParameterLength(1,2),I1=new Map,z=class r extends le{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=I1.get(e);return n===void 0&&(n=Vr(e,t),I1.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache(e==="map"?"map":e+"Map","texture")}setup(e){let t=e.context.material,n=this.scope,i=null;if(n===r.COLOR){let s=t.color!==void 0?this.getColor(n):N();t.map&&t.map.isTexture===!0?i=s.mul(this.getTexture("map")):i=s}else if(n===r.OPACITY){let s=this.getFloat(n);t.alphaMap&&t.alphaMap.isTexture===!0?i=s.mul(this.getTexture("alpha")):i=s}else if(n===r.SPECULAR_STRENGTH)t.specularMap&&t.specularMap.isTexture===!0?i=this.getTexture("specular").r:i=v(1);else if(n===r.SPECULAR_INTENSITY){let s=this.getFloat(n);t.specularIntensityMap&&t.specularIntensityMap.isTexture===!0?i=s.mul(this.getTexture(n).a):i=s}else if(n===r.SPECULAR_COLOR){let s=this.getColor(n);t.specularColorMap&&t.specularColorMap.isTexture===!0?i=s.mul(this.getTexture(n).rgb):i=s}else if(n===r.ROUGHNESS){let s=this.getFloat(n);t.roughnessMap&&t.roughnessMap.isTexture===!0?i=s.mul(this.getTexture(n).g):i=s}else if(n===r.METALNESS){let s=this.getFloat(n);t.metalnessMap&&t.metalnessMap.isTexture===!0?i=s.mul(this.getTexture(n).b):i=s}else if(n===r.EMISSIVE){let s=this.getFloat("emissiveIntensity"),a=this.getColor(n).mul(s);t.emissiveMap&&t.emissiveMap.isTexture===!0?i=a.mul(this.getTexture(n)):i=a}else if(n===r.NORMAL)t.normalMap?(i=Vx(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,(t.normalMap.format==mi||t.normalMap.format==Uo||t.normalMap.format==Bo)&&(i.unpackNormalMode=af)):t.bumpMap?i=LS(this.getTexture("bump").r,this.getFloat("bumpScale")):i=Be;else if(n===r.CLEARCOAT){let s=this.getFloat(n);t.clearcoatMap&&t.clearcoatMap.isTexture===!0?i=s.mul(this.getTexture(n).r):i=s}else if(n===r.CLEARCOAT_ROUGHNESS){let s=this.getFloat(n);t.clearcoatRoughnessMap&&t.clearcoatRoughnessMap.isTexture===!0?i=s.mul(this.getTexture(n).r):i=s}else if(n===r.CLEARCOAT_NORMAL)t.clearcoatNormalMap?i=Vx(this.getTexture(n),this.getCache(n+"Scale","vec2")):i=Be;else if(n===r.SHEEN){let s=this.getColor("sheenColor").mul(this.getFloat("sheen"));t.sheenColorMap&&t.sheenColorMap.isTexture===!0?i=s.mul(this.getTexture("sheenColor").rgb):i=s}else if(n===r.SHEEN_ROUGHNESS){let s=this.getFloat(n);t.sheenRoughnessMap&&t.sheenRoughnessMap.isTexture===!0?i=s.mul(this.getTexture(n).a):i=s,i=i.clamp(1e-4,1)}else if(n===r.ANISOTROPY)if(t.anisotropyMap&&t.anisotropyMap.isTexture===!0){let s=this.getTexture(n);i=bg(su.x,su.y,su.y.negate(),su.x).mul(s.rg.mul(2).sub($(1)).normalize().mul(s.b))}else i=su;else if(n===r.IRIDESCENCE_THICKNESS){let s=dt("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){let a=dt("0","float",t.iridescenceThicknessRange);i=s.sub(a).mul(this.getTexture(n).g).add(a)}else i=s}else if(n===r.TRANSMISSION){let s=this.getFloat(n);t.transmissionMap?i=s.mul(this.getTexture(n).r):i=s}else if(n===r.THICKNESS){let s=this.getFloat(n);t.thicknessMap?i=s.mul(this.getTexture(n).g):i=s}else if(n===r.IOR)i=this.getFloat(n);else if(n===r.LIGHT_MAP)t.lightMap?i=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity")):i=N(0);else if(n===r.AO)t.aoMap?i=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1):i=v(1);else if(n===r.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(n):v(0);else{let s=this.getNodeType(e);i=this.getCache(n,s)}return i}};z.ALPHA_TEST="alphaTest";z.COLOR="color";z.OPACITY="opacity";z.SHININESS="shininess";z.SPECULAR="specular";z.SPECULAR_STRENGTH="specularStrength";z.SPECULAR_INTENSITY="specularIntensity";z.SPECULAR_COLOR="specularColor";z.REFLECTIVITY="reflectivity";z.ROUGHNESS="roughness";z.METALNESS="metalness";z.NORMAL="normal";z.CLEARCOAT="clearcoat";z.CLEARCOAT_ROUGHNESS="clearcoatRoughness";z.CLEARCOAT_NORMAL="clearcoatNormal";z.EMISSIVE="emissive";z.ROTATION="rotation";z.SHEEN="sheen";z.SHEEN_ROUGHNESS="sheenRoughness";z.ANISOTROPY="anisotropy";z.IRIDESCENCE="iridescence";z.IRIDESCENCE_IOR="iridescenceIOR";z.IRIDESCENCE_THICKNESS="iridescenceThickness";z.IOR="ior";z.TRANSMISSION="transmission";z.THICKNESS="thickness";z.ATTENUATION_DISTANCE="attenuationDistance";z.ATTENUATION_COLOR="attenuationColor";z.LINE_SCALE="scale";z.LINE_DASH_SIZE="dashSize";z.LINE_GAP_SIZE="gapSize";z.LINE_WIDTH="linewidth";z.LINE_DASH_OFFSET="dashOffset";z.POINT_SIZE="size";z.DISPERSION="dispersion";z.LIGHT_MAP="light";z.AO="ao";var sR=Y(z,z.ALPHA_TEST),rR=Y(z,z.COLOR),aR=Y(z,z.SHININESS),oR=Y(z,z.EMISSIVE),BS=Y(z,z.OPACITY),lR=Y(z,z.SPECULAR),zx=Y(z,z.SPECULAR_INTENSITY),cR=Y(z,z.SPECULAR_COLOR),wh=Y(z,z.SPECULAR_STRENGTH),Jf=Y(z,z.REFLECTIVITY),uR=Y(z,z.ROUGHNESS),dR=Y(z,z.METALNESS),hR=Y(z,z.NORMAL),pR=Y(z,z.CLEARCOAT),fR=Y(z,z.CLEARCOAT_ROUGHNESS),mR=Y(z,z.CLEARCOAT_NORMAL),gR=Y(z,z.ROTATION),yR=Y(z,z.SHEEN),xR=Y(z,z.SHEEN_ROUGHNESS),_R=Y(z,z.ANISOTROPY),bR=Y(z,z.IRIDESCENCE),vR=Y(z,z.IRIDESCENCE_IOR),SR=Y(z,z.IRIDESCENCE_THICKNESS),TR=Y(z,z.TRANSMISSION),MR=Y(z,z.THICKNESS),wR=Y(z,z.IOR),ER=Y(z,z.ATTENUATION_DISTANCE),RR=Y(z,z.ATTENUATION_COLOR),US=Y(z,z.LINE_SCALE),OS=Y(z,z.LINE_DASH_SIZE),kS=Y(z,z.LINE_GAP_SIZE),xm=Y(z,z.LINE_WIDTH),VS=Y(z,z.LINE_DASH_OFFSET),AR=Y(z,z.POINT_SIZE),CR=Y(z,z.DISPERSION),GS=Y(z,z.LIGHT_MAP),NR=Y(z,z.AO),su=ie(new O).onReference(function(r){return r.material}).onRenderUpdate(function({material:r}){this.value.set(r.anisotropy*Math.cos(r.anisotropyRotation),r.anisotropy*Math.sin(r.anisotropyRotation))}),PR=P(r=>r.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection"),ei=class r extends le{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===r.OBJECT?this.updateType=pe.OBJECT:e===r.MATERIAL?this.updateType=pe.RENDER:e===r.FRAME?this.updateType=pe.FRAME:e===r.BEFORE_OBJECT?this.updateBeforeType=pe.OBJECT:e===r.BEFORE_MATERIAL?this.updateBeforeType=pe.RENDER:e===r.BEFORE_FRAME&&(this.updateBeforeType=pe.FRAME)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}};ei.OBJECT="object";ei.MATERIAL="material";ei.FRAME="frame";ei.BEFORE_OBJECT="beforeObject";ei.BEFORE_MATERIAL="beforeMaterial";ei.BEFORE_FRAME="beforeFrame";var Eu=(r,e)=>new ei(r,e).toStack(),ep=r=>Eu(ei.OBJECT,r),NI=r=>Eu(ei.MATERIAL,r),DR=r=>Eu(ei.FRAME,r),PI=r=>Eu(ei.BEFORE_OBJECT,r),DI=r=>Eu(ei.BEFORE_MATERIAL,r),II=r=>Eu(ei.BEFORE_FRAME,r),Hx=class extends Hr{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){let n=this.storageBufferNode.structTypeNode;return n?n.getMemberType(e,t):"void"}setup(e){return e.isAvailable("storageBuffer")===!1&&this.node.isPBO===!0&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let n,i=e.isContextAssign();if(e.isAvailable("storageBuffer")===!1?this.node.isPBO===!0&&i!==!0&&(this.node.value.isInstancedBufferAttribute||e.shaderStage!=="compute")?n=e.generatePBO(this):n=this.node.build(e):n=super.generate(e),i!==!0){let s=this.getNodeType(e);n=e.format(n,s,t)}return n}},FI=Me(Hx).setParameterLength(2),Wx=class extends Lh{static get type(){return"StorageBufferNode"}constructor(e,t=null,n=0){let i,s=null;t&&t.isStructTypeNode?(i="struct",s=t,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):t===null&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=XM(e.itemSize),n=e.count):i=t,super(e,i,n),this.isStorageBufferNode=!0,this.structTypeNode=s,this.access=Mn.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,e.isStorageBufferAttribute!==!0&&e.isStorageInstancedBufferAttribute!==!0&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){let t;if(this.bufferCount===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return FI(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Mn.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return this._attribute===null&&(this._attribute=bS(this.value),this._varying=no(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(this.structTypeNode!==null)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generateNodeType(e);let{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return this.structTypeNode!==null?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(this.structTypeNode!==null&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);let{attribute:t,varying:n}=this.getAttributeData(),i=n.build(e);return e.registerTransform(i,t),i}},Ka=(r,e=null,t=0)=>new Wx(r,e,t),qx=new WeakMap,F1=new WeakMap,$x=new WeakMap;function IR(r,e){let t,n=Math.max(e.count,1);if(e.isStorageInstancedBufferAttribute===!0)t=Ka(e,"mat4",n).element(As);else if(n*16*4<=r.getUniformBufferLimit())t=wu(e.array,"mat4",n).element(As);else{let a=qx.get(e);a||(a=new Id(e.array,16,1),qx.set(e,a));let o=e.usage===ko?vS:Ng,l=[o(a,"vec4",16,0),o(a,"vec4",16,4),o(a,"vec4",16,8),o(a,"vec4",16,12)];t=ja(...l)}return t}function LI(r,e,t){let n=$x.get(r);if(n===void 0){let i=e.clone();n={previousInstanceMatrix:i,node:IR(t,i)},$x.set(r,n)}return n.node}var zS=gl("vec3","vInstanceColor"),FR=P(([r,e=null],t)=>{let n=r.isStorageInstancedBufferAttribute===!0,i=e&&e.isStorageInstancedBufferAttribute===!0,s=IR(t,r),a=null;n||Math.max(r.count,1)*16*4>t.getUniformBufferLimit()&&(a=qx.get(r));let o=null,l=null;if(e)if(i)o=Ka(e,"vec3",Math.max(e.count,1)).element(As);else{let u=F1.get(e);u||(u=new Hs(e.array,3),F1.set(e,u)),l=u;let d=e.usage===ko?vS:Ng;o=N(d(u,"vec3",3,0))}(a!==null||l!==null)&&DR(()=>{a!==null&&(a.clearUpdateRanges(),a.updateRanges.push(...r.updateRanges),r.version!==a.version&&(a.version=r.version)),e&&l!==null&&(l.clearUpdateRanges(),l.updateRanges.push(...e.updateRanges),e.version!==l.version&&(l.version=e.version))});let c=s.mul(Mt).xyz;if(Mt.assign(c),t.needsPreviousData()){let u=t.object;ep(({object:h})=>{$x.get(h).previousInstanceMatrix.array.set(r.array)});let d=LI(u,r,t);ul.assign(d.mul(ul).xyz)}if(t.hasGeometryAttribute("normal")){let u=PS(Gn,s);Gn.assign(u)}o!==null&&zS.assign(o)},"void"),LR=P(([r])=>{let{instanceMatrix:e,instanceColor:t}=r;FR(e,t)},"void"),BI=P(([r,e])=>{let t=C(ll(Ut(r),0).x).toConst(),n=C(e),i=n.mod(t).toConst(),s=n.div(t).toConst();return Ut(r,Rt(i,s))}),UI=P(([r,e])=>{let t=C(ll(Ut(r),0).x).toConst(),n=C(e).mod(t).toConst(),i=C(e).div(t).toConst();return Ut(r,Rt(n,i)).x}),HS=gl("vec4","vBatchColor"),BR=P(([r],e)=>{let t=e.getDrawIndex()===null?As:vE,n=UI(r._indirectTexture,C(t)),i=r._matricesTexture,s=C(ll(Ut(i),0).x).toConst(),a=v(n).mul(4).toInt().toConst(),o=a.mod(s).toConst(),l=a.div(s).toConst(),c=ja(Ut(i,Rt(o,l)),Ut(i,Rt(o.add(1),l)),Ut(i,Rt(o.add(2),l)),Ut(i,Rt(o.add(3),l))),u=r._colorsTexture;if(u!==null){let f=BI(u,n);HS.assign(f)}let d=yn(c);Mt.assign(c.mul(Mt));let h=Gn.div(N(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),p=d.mul(h).xyz;Gn.assign(p),e.hasGeometryAttribute("tangent")&&Qa.mulAssign(d)},"void"),_m=new WeakMap,bm=new WeakMap;function WS(r,e,t,n,i,s){let a=r.element(i.x),o=r.element(i.y),l=r.element(i.z),c=r.element(i.w),u=t.mul(e),d=Wt(a.mul(s.x).mul(u),o.mul(s.y).mul(u),l.mul(s.z).mul(u),c.mul(s.w).mul(u));return n.mul(d).xyz}function UR(r,e,t,n,i,s,a){let o=r.element(s.x),l=r.element(s.y),c=r.element(s.z),u=r.element(s.w),d=Wt(a.x.mul(o),a.y.mul(l),a.z.mul(c),a.w.mul(u));d=i.mul(d).mul(n);let h=d.transformDirection(e).xyz,p=d.transformDirection(t).xyz;return{skinNormal:h,skinTangent:p}}function OR(r,e,t,n,i){let s=r.skeleton,a=bm.get(s);if(a===void 0){s.update();let o=new Float32Array(s.boneMatrices);a={previousBoneMatrices:o,node:wu(o,"mat4",s.bones.length)},bm.set(s,a)}return WS(a.node,ul,e,t,n,i)}var kR=P(([r],e)=>{let t=Li("skinIndex","uvec4"),n=Li("skinWeight","vec4"),i=dt("bindMatrix","mat4"),s=dt("bindMatrixInverse","mat4"),a=qE("skeleton.boneMatrices","mat4",r.skeleton.bones.length);if(ep(({object:l,frameId:c})=>{let u=l.skeleton;if(_m.get(u)!==c){_m.set(u,c);let d=bm.get(u);d!==void 0&&d.previousBoneMatrices.set(u.boneMatrices),u.update()}}),e.needsPreviousData()){let l=OR(r,i,s,t,n);ul.assign(l)}let o=WS(a,Mt,i,s,t,n);if(Mt.assign(o),e.hasGeometryAttribute("normal")){let{skinNormal:l,skinTangent:c}=UR(a,Gn,Qa,i,s,t,n);Gn.assign(l),e.hasGeometryAttribute("tangent")&&Qa.assign(c)}},"void"),OI=P(([r,e=null],t)=>{let n=Ka(new Hs(r.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(As).toVar(),i=Ka(new Hs(new Uint32Array(r.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(As).toVar(),s=Ka(new Hs(r.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(As).toVar(),a=ie(r.bindMatrix,"mat4"),o=ie(r.bindMatrixInverse,"mat4"),l=wu(r.skeleton.boneMatrices,"mat4",r.skeleton.bones.length),c=r.skeleton;if(ep(({frameId:d})=>{if(_m.get(c)!==d){_m.set(c,d);let h=bm.get(c);h!==void 0&&h.previousBoneMatrices.set(c.boneMatrices),c.update()}}),t.needsPreviousData()){let d=OR(r,a,o,i,s);ul.assign(d)}let u=WS(l,n,a,o,i,s);if(e!==null&&e.assign(u),t.hasGeometryAttribute("normal")){let{skinNormal:d,skinTangent:h}=UR(l,Gn,Qa,a,o,i,s);Gn.assign(d),t.hasGeometryAttribute("tangent")&&Qa.assign(h)}return u}),Xx=class extends le{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode(105+e)}getProperties(e){let t=e.getNodeProperties(this);if(t.stackNode!==void 0)return t;let n={};for(let o=0,l=this.params.length-1;o<l;o++){let c=this.params[o],u=c.isNode!==!0&&c.name||this.getVarName(o),d=c.isNode!==!0&&c.type||"int";n[u]=Fi(u,d)}let i=e.addStack(),s=this.params[this.params.length-1](n);t.returnsNode=s.context({nodeLoop:s}),t.stackNode=i;let a=this.params[0];if(a.isNode!==!0&&typeof a.update=="function"){let o=P(this.params[0].update)(n);t.updateNode=o.context({nodeLoop:o})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){let t=e.getDataFromNode(e.fnCall.shaderNode);t.hasLoop=!0}}generate(e){let t=this.getProperties(e),n=this.params,i=t.stackNode;for(let a=0,o=n.length-1;a<o;a++){let l=n[a],c=!1,u=null,d=null,h=null,p=null,f=null,m=null;l.isNode?l.getNodeType(e)==="bool"?(c=!0,p="bool",d=l.build(e,p)):(p="int",h=this.getVarName(a),u="0",d=l.build(e,p),f="<"):(p=l.type||"int",h=l.name||this.getVarName(a),u=l.start,d=l.end,f=l.condition,m=l.update,typeof u=="number"?u=e.generateConst(p,u):u&&u.isNode&&(u=u.build(e,p)),typeof d=="number"?d=e.generateConst(p,d):d&&d.isNode&&(d=d.build(e,p)),u!==void 0&&d===void 0?(u=u+" - 1",d="0",f=">="):d!==void 0&&u===void 0&&(u="0",f="<"),f===void 0&&(Number(u)>Number(d)?f=">=":f="<"));let y;if(c)y=`while ( ${d} )`;else{let x={start:u,end:d},b=x.start,_=x.end,S,M=()=>f.includes("<")?"+=":"-=";if(m!=null)switch(typeof m){case"function":S=e.flowStagesNode(t.updateNode,"void").code.replace(/t|;/g,"");break;case"number":S=h+" "+M()+" "+e.generateConst(p,m);break;case"string":S=h+" "+m;break;default:m.isNode?S=h+" "+M()+" "+m.build(e):(G("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),S="break /* invalid update */")}else p==="int"||p==="uint"?m=f.includes("<")?"++":"--":m=M()+" 1.",S=h+" "+m;let w=e.getVar(p,h)+" = "+b,T=h+" "+f+" "+_;y=`for ( ${w}; ${T}; ${S} )`}e.addFlowCode((a===0?`
`:"")+e.tab+y+` {
`).addFlowTab()}let s=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode(`
`+e.tab+s);for(let a=0,o=this.params.length-1;a<o;a++)e.addFlowCode((a===0?"":e.tab)+`}
`).removeFlowTab();e.addFlowTab()}},Xe=(...r)=>new Xx(Qo(r,"int")).toStack(),kI=()=>Fi("continue").toStack(),VR=()=>Fi("break").toStack(),My=new WeakMap,Ai=new Ge,L1=new WeakMap,B1=P(({bufferMap:r,influence:e,stride:t,width:n,depth:i,offset:s})=>{let a=C(bE).mul(t).add(s),o=a.div(n),l=a.sub(o.mul(n));return Ut(r,Rt(l,o)).depth(i).xyz.mul(e)});function VI(r){let e=r.morphAttributes.position!==void 0,t=r.morphAttributes.normal!==void 0,n=r.morphAttributes.color!==void 0,i=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,s=i!==void 0?i.length:0,a=My.get(r);if(a===void 0||a.count!==s){let x=function(){m.dispose(),My.delete(r),r.removeEventListener("dispose",x)};a!==void 0&&a.texture.dispose();let o=r.morphAttributes.position||[],l=r.morphAttributes.normal||[],c=r.morphAttributes.color||[],u=0;e===!0&&(u=1),t===!0&&(u=2),n===!0&&(u=3);let d=r.attributes.position.count*u,h=1,p=4096;d>p&&(h=Math.ceil(d/p),d=p);let f=new Float32Array(d*h*4*s),m=new Xu(f,d,h,s);m.type=en,m.needsUpdate=!0;let y=u*4;for(let b=0;b<s;b++){let _=o[b],S=l[b],M=c[b],w=d*h*4*b;for(let T=0;T<_.count;T++){let R=T*y;e===!0&&(Ai.fromBufferAttribute(_,T),f[w+R+0]=Ai.x,f[w+R+1]=Ai.y,f[w+R+2]=Ai.z,f[w+R+3]=0),t===!0&&(Ai.fromBufferAttribute(S,T),f[w+R+4]=Ai.x,f[w+R+5]=Ai.y,f[w+R+6]=Ai.z,f[w+R+7]=0),n===!0&&(Ai.fromBufferAttribute(M,T),f[w+R+8]=Ai.x,f[w+R+9]=Ai.y,f[w+R+10]=Ai.z,f[w+R+11]=M.itemSize===4?Ai.w:1)}}a={count:s,texture:m,stride:u,size:new O(d,h)},My.set(r,a),r.addEventListener("dispose",x)}return a}var GR=P(([r])=>{let{geometry:e}=r,t=e.morphAttributes.position!==void 0,n=e.hasAttribute("normal")&&e.morphAttributes.normal!==void 0,i=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=i!==void 0?i.length:0;if(s===0)return;let a=L1.get(r);(a===void 0||a.count!==s)&&(a={base:ie(1),influences:r.morphTargetInfluences?Tn(r.morphTargetInfluences,"float"):null,count:s},L1.set(r,a));let{base:o,influences:l}=a,{texture:c,stride:u,size:d}=VI(e);t===!0&&Mt.mulAssign(o),n===!0&&Gn.mulAssign(o);let h=C(d.width);Xe(s,({i:p})=>{let f=v(0).toVar();r.count>1&&r.morphTexture!==null&&r.morphTexture!==void 0?f.assign(Ut(r.morphTexture,Rt(C(p).add(1),C(As))).r):f.assign(l.element(p).toVar()),oe(f.notEqual(0),()=>{t===!0&&Mt.addAssign(B1({bufferMap:c,influence:f,stride:u,width:h,depth:p,offset:C(0)})),n===!0&&Gn.addAssign(B1({bufferMap:c,influence:f,stride:u,width:h,depth:p,offset:C(1)}))})}),ep(({object:p})=>{let{base:f,influences:m}=a;p.geometry.morphTargetsRelative?f.value=1:f.value=1-p.morphTargetInfluences.reduce((y,x)=>y+x,0),m&&(m.array=p.morphTargetInfluences,m.update())})},"void"),eo=class extends le{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}},Yx=class extends eo{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}},jx=class extends Ih{static get type(){return"LightingContextNode"}constructor(e,t=null,n=[],i=null,s=null){super(e),this.lightingModel=t,this.materialLightings=n,this.backdropNode=i,this.backdropAlphaNode=s,this._value=null}getContext(){let{materialLightings:e,backdropNode:t,backdropAlphaNode:n}=this,i=N().toVar("directDiffuse"),s=N().toVar("directSpecular"),a=N().toVar("indirectDiffuse"),o=N().toVar("indirectSpecular"),l={directDiffuse:i,directSpecular:s,indirectDiffuse:a,indirectSpecular:o};return{radiance:N().toVar("radiance"),irradiance:N().toVar("irradiance"),iblIrradiance:N().toVar("iblIrradiance"),ambientOcclusion:v(1).toVar("ambientOcclusion"),reflectedLight:l,materialLightings:e,backdrop:t,backdropAlpha:n}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}},zR=Me(jx),Kx=class extends eo{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}},Vo=new O,xu=class extends cs{static get type(){return"ViewportTextureNode"}constructor(e=Rs,t=null,n=null){let i=null;n===null?(i=new _o,i.minFilter=bs,n=i):i=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=pe.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,n;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,n=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,n=this._cacheTextures),e===null)return t;if(n.has(e)===!1){let i=t.clone();n.set(e,i)}return n.get(e)}updateReference(e){let t=e.renderer,n=t.getRenderTarget(),i=t.getCanvasTarget(),s=n||i;return this.value=this.getTextureForReference(s),this.value}updateBefore(e){let t=e.renderer,n=t.getRenderTarget(),i=t.getCanvasTarget(),s=n||i;s===null?t.getDrawingBufferSize(Vo):s.getDrawingBufferSize?s.getDrawingBufferSize(Vo):Vo.set(s.width,s.height);let a=this.getTextureForReference(s);(a.image.width!==Vo.width||a.image.height!==Vo.height)&&(a.image.width=Vo.width,a.image.height=Vo.height,a.needsUpdate=!0);let o=a.generateMipmaps;a.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(a),a.generateMipmaps=o}clone(){let e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}},GI=Me(xu).setParameterLength(0,3),qS=Me(xu,null,null,{generateMipmaps:!0}).setParameterLength(0,3),zI=qS(),HR=(r=Rs,e=null)=>zI.sample(r,e),wy=null,Zx=class extends xu{static get type(){return"ViewportDepthTextureNode"}constructor(e=Rs,t=null,n=null){n===null&&(wy===null&&(wy=new Pn),n=wy),super(e,t,n)}},$S=Me(Zx).setParameterLength(0,3),Ps=class r extends le{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){let{scope:t}=this;return t===r.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){let{scope:t}=this,n=this.valueNode,i=null;if(t===r.DEPTH_BASE)n!==null&&(i=$R().assign(n));else if(t===r.DEPTH)e.isPerspectiveCamera?i=XS(Ot.z,Ha,Wa):i=il(Ot.z,Ha,Wa);else if(t===r.LINEAR_DEPTH)if(n!==null)if(e.isPerspectiveCamera){let s=Bg(n,Ha,Wa);i=il(s,Ha,Wa)}else i=n;else i=il(Ot.z,Ha,Wa);return i}};Ps.DEPTH_BASE="depthBase";Ps.DEPTH="depth";Ps.LINEAR_DEPTH="linearDepth";var il=(r,e,t)=>r.add(e).div(e.sub(t)),HI=(r,e,t)=>r.add(t).div(t.sub(e)),WR=P(([r,e,t],n)=>n.renderer.reversedDepthBuffer===!0?t.sub(e).mul(r).sub(t):e.sub(t).mul(r).sub(e)),XS=(r,e,t)=>e.add(r).mul(t).div(t.sub(e).mul(r)),qR=(r,e,t)=>e.mul(r.add(t)).div(r.mul(e.sub(t))),Bg=P(([r,e,t],n)=>n.renderer.reversedDepthBuffer===!0?e.mul(t).div(e.sub(t).mul(r).sub(e)):e.mul(t).div(t.sub(e).mul(r).sub(t))),Ug=(r,e,t)=>{e=e.max(1e-6).toVar();let n=ir(r.negate().div(e)),i=ir(t.div(e));return n.div(i)},WI=(r,e,t)=>{let n=r.mul(wg(t.div(e)));return v(Math.E).pow(n).mul(e).negate()},$R=Me(Ps,Ps.DEPTH_BASE),YS=Y(Ps,Ps.DEPTH),vm=Me(Ps,Ps.LINEAR_DEPTH).setParameterLength(0,1),qI=vm($S());YS.assign=r=>$R(r);var ur=class r extends le{static get type(){return"ClippingNode"}constructor(e=r.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);let t=e.clippingContext,{intersectionPlanes:n,unionPlanes:i}=t;return this.hardwareClipping=e.hardwareClipping,this.scope===r.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,i):this.scope===r.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(n,i)}setupAlphaToCoverage(e,t){return P(()=>{let n=v().toVar("distanceToPlane"),i=v().toVar("distanceToGradient"),s=v(1).toVar("clipOpacity"),a=t.length;if(this.hardwareClipping===!1&&a>0){let l=Tn(t).setGroup(de);Xe(a,({i:c})=>{let u=l.element(c);n.assign(Ot.dot(u.xyz).negate().add(u.w)),i.assign(n.fwidth().div(2)),s.mulAssign(Oi(i.negate(),i,n))})}let o=e.length;if(o>0){let l=Tn(e).setGroup(de),c=v(1).toVar("intersectionClipOpacity");Xe(o,({i:u})=>{let d=l.element(u);n.assign(Ot.dot(d.xyz).negate().add(d.w)),i.assign(n.fwidth().div(2)),c.mulAssign(Oi(i.negate(),i,n).oneMinus())}),s.mulAssign(c.oneMinus())}$e.a.mulAssign(s),$e.a.equal(0).discard()})()}setupDefault(e,t){return P(()=>{let n=t.length;if(this.hardwareClipping===!1&&n>0){let s=Tn(t).setGroup(de);Xe(n,({i:a})=>{let o=s.element(a);Ot.dot(o.xyz).greaterThan(o.w).discard()})}let i=e.length;if(i>0){let s=Tn(e).setGroup(de),a=Bi(!0).toVar("clipped");Xe(i,({i:o})=>{let l=s.element(o);a.assign(Ot.dot(l.xyz).greaterThan(l.w).and(a))}),a.discard()}})()}setupHardwareClipping(e,t){let n=e.length;return t.enableHardwareClipping(n),P(()=>{let i=Tn(e).setGroup(de),s=Yr(t.getClipDistance());Xe(n,({i:a})=>{let o=i.element(a),l=Ot.dot(o.xyz).sub(o.w).negate();s.element(a).assign(l)})})()}};ur.ALPHA_TO_COVERAGE="alphaToCoverage";ur.DEFAULT="default";ur.HARDWARE="hardware";var $I=()=>new ur,XI=()=>new ur(ur.ALPHA_TO_COVERAGE),YI=()=>new ur(ur.HARDWARE),jI=.05,U1=P(([r])=>Cs(xe(1e4,Kn(xe(17,r.x).add(xe(.1,r.y)))).mul(Wt(.1,rt(Kn(xe(13,r.y).add(r.x))))))),O1=P(([r])=>U1($(U1(r.xy),r.z))),KI=P(([r])=>{let e=At(rr(lS(r.xyz)),rr(cS(r.xyz))),t=v(1).div(v(jI).mul(e)).toVar("pixScale"),n=$(mu(sr(ir(t))),mu(Eg(ir(t)))),i=$(O1(sr(n.x.mul(r.xyz))),O1(sr(n.y.mul(r.xyz)))),s=Cs(ir(t)),a=Wt(xe(s.oneMinus(),i.x),xe(s,i.y)),o=gi(s,s.oneMinus()),l=N(a.mul(a).div(xe(2,o).mul(Ie(1,o))),a.sub(xe(.5,o)).div(Ie(1,o)),Ie(1,Ie(1,a).mul(Ie(1,a)).div(xe(2,o).mul(Ie(1,o))))),c=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return Ns(c,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]}),Jx=class extends mm{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){let e=this.index;return"color"+(e>0?e:"")}generate(e){let t=this.getAttributeName(e),n=e.hasGeometryAttribute(t),i;return n===!0?i=super.generate(e):i=e.generateConst(this.nodeType,new Ge(1,1,1,1)),i}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}},XR=(r=0)=>new Jx(r),We=class extends _n{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){let e=[];for(let t of Object.getOwnPropertyNames(this)){if(t.startsWith("_")===!0)continue;let n=this[t];n&&n.isNode===!0&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){let e=[];for(let{property:t,childNode:n}of this._getNodeChildren())e.push(Mu(t.slice(0,-4)),n.getCacheKey());return this.type+Jh(e)}build(e){this.setup(e)}setupObserver(e){return new ex(e)}setup(e){e.context.setupNormal=()=>nl(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);let t=e.renderer,n=t.getRenderTarget();e.addStack();let i=this.setupVertex(e),s=nl(this.vertexNode||i,"VERTEX");e.context.clipSpace=s,e.stack.outputNode=s,this.setupHardwareClipping(e),this.geometryNode!==null&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();let a,o=this.setupClipping(e);if((this.depthWrite===!0||this.depthTest===!0)&&(n!==null?n.depthBuffer===!0&&this.setupDepth(e):t.depth===!0&&this.setupDepth(e)),this.fragmentNode===null){this.setupDiffuseColor(e),this.setupAmbientOcclusion(e),this.setupVariants(e);let l=this.setupLighting(e);o!==null&&e.stack.addToStack(o);let c=J(l,$e.a).max(0);a=this.setupOutput(e,c),cu.assign(a);let u=this.outputNode!==null;if(u&&(a=this.outputNode),e.context.getOutput&&(a=e.context.getOutput(a,e)),n!==null){let d=t.getMRT(),h=this.mrtNode;d!==null?(u&&cu.assign(a),a=d,h!==null&&(a=d.merge(h))):h!==null&&(a=h)}}else{let l=this.fragmentNode;l.isOutputStructNode!==!0&&(l=l.convert(e.getOutputType())),a=this.setupOutput(e,l)}e.stack.outputNode=a,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(e.clippingContext===null)return null;let{unionPlanes:t,intersectionPlanes:n}=e.clippingContext,i=null;if(t.length>0||n.length>0){let s=e.renderer.currentSamples;this.alphaToCoverage&&s>1?i=XI():e.stack.addToStack($I())}return i}setupHardwareClipping(e){if(e.hardwareClipping=!1,e.clippingContext===null)return;let t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(YI()),e.hardwareClipping=!0)}setupDepth(e){let{renderer:t,camera:n}=e,i=this.depthNode;if(i===null){let s=t.getMRT();s&&s.has("depth")?i=s.get("depth"):t.logarithmicDepthBuffer===!0&&(n.isPerspectiveCamera?i=Ug(Ot.z,Ha,Wa):i=il(Ot.z,Ha,Wa))}i!==null&&YS.assign(i).toStack()}setupPositionView(){return cr.mul(Mt).xyz}setupModelViewProjection(){return Jn.mul(Ot)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),PR}setupPosition(e){let{object:t,geometry:n}=e;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&GR(t),t.isSkinnedMesh===!0&&kR(t),this.displacementMap){let i=Vr("displacementMap","texture"),s=Vr("displacementScale","float"),a=Vr("displacementBias","float");Mt.addAssign(Gn.normalize().mul(i.x.mul(s).add(a)))}return t.isBatchedMesh&&BR(t),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&LR(t),this.positionNode!==null&&Mt.assign(nl(this.positionNode,"POSITION","vec3")),Mt}setupDiffuseColor(e){let{object:t,geometry:n}=e;this.maskNode!==null&&Bi(this.maskNode).not().discard();let i=this.colorNode?J(this.colorNode):rR;this.vertexColors===!0&&n.hasAttribute("color")&&(i=i.mul(XR())),t.instanceColor&&(i=zS.mul(i)),t.isBatchedMesh&&t._colorsTexture&&(i=HS.mul(i)),$e.assign(i);let s=this.opacityNode?v(this.opacityNode):BS;$e.a.assign($e.a.mul(s));let a=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(a=this.alphaTestNode!==null?v(this.alphaTestNode):sR,this.alphaToCoverage===!0?($e.a=Oi(a,a.add(dS($e.a)),$e.a),$e.a.lessThanEqual(0).discard()):$e.a.lessThanEqual(a).discard()),this.alphaHash===!0&&$e.a.lessThan(KI(Mt)).discard(),e.isOpaque()&&$e.a.assign(1)}setupVariants(){}setupOutgoingLight(){return this.lights===!0?N(0):$e.rgb}setupNormal(){return this.normalNode?N(this.normalNode):hR}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Vr("envMap","cubeTexture"):Vr("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Kx(GS)),t}setupMaterialLightings(e){let t=[];if(e.renderer.lighting.enabled===!1)return t;let n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);let i=this.setupLightMap(e);return i&&i.isLightingNode&&t.push(i),e.context.ambientOcclusion&&t.push(new Yx(e.context.ambientOcclusion)),t}setupAmbientOcclusion(e){let t=this.aoNode;t===null&&e.material.aoMap&&(t=NR),e.context.getAO&&(t=e.context.getAO(t,e)),t!==null&&(dx.assign(t),e.context.ambientOcclusion=dx)}setupLightingModel(){}setupLighting(e){let{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:s}=this,a=this.lights===!0||this.lightsNode!==null,o=this.lights===!0?this.setupMaterialLightings(e):[],l=a?this.lightsNode||e.lightsNode:null,c=this.setupOutgoingLight(e);if(l&&(o.length>0||l.getScope().hasLights)){let u=this.setupLightingModel(e)||null;c=zR(l,u,o,n,i)}else n!==null&&(c=N(i!==null?Re(c,n,i):n));return(s&&s.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(ux.assign(N(s||oR)),c=c.add(ux)),c}setupFog(e,t){let n=e.fogNode;return n&&(cu.assign(t),t=J(n.toVar())),t}setupPremultipliedAlpha(e,t){return MS(t)}setupOutput(e,t){return this.fog===!0&&(t=this.setupFog(e,t)),this.premultipliedAlpha===!0&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(let n in e){let i=e[n];this[n]===void 0&&(this[n]=i,i&&i.clone&&(this[n]=i.clone()))}let t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(let n in t)Object.getOwnPropertyDescriptor(this.constructor.prototype,n)===void 0&&t[n].get!==void 0&&Object.defineProperty(this.constructor.prototype,n,t[n])}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{},nodes:{}});let n=_n.prototype.toJSON.call(this,e);n.inputNodes={};for(let{property:s,childNode:a}of this._getNodeChildren())n.inputNodes[s]=a.toJSON(e).uuid;function i(s){let a=[];for(let o in s){let l=s[o];delete l.metadata,a.push(l)}return a}if(t){let s=i(e.textures),a=i(e.images),o=i(e.nodes);s.length>0&&(n.textures=s),a.length>0&&(n.images=a),o.length>0&&(n.nodes=o)}return n}copy(e){let t=Object.getOwnPropertyDescriptors(this.constructor.prototype);for(let n in t)if(t[n].set!==void 0&&e[n]!==void 0){let i=e[n];this[n]&&this[n].copy!==void 0?this[n].copy(i):this[n]=i}for(let n in this)if(!/^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test(n)&&this[n]!==void 0&&e[n]!==void 0){let i=e[n];this[n]&&this[n].copy!==void 0?this[n].copy(i):this[n]=i}return this.clippingPlanes=e.clippingPlanes?e.clippingPlanes.map(n=>n.clone()):null,this.userData=JSON.parse(JSON.stringify(e.userData)),this}},ZI=new Kl,Qx=class extends We{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(ZI),this.setValues(e)}},JI=new md,e_=class extends We{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(JI),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){let e=this.offsetNode?v(this.offsetNode):VS,t=this.dashScaleNode?v(this.dashScaleNode):US,n=this.dashSizeNode?v(this.dashSizeNode):OS,i=this.gapSizeNode?v(this.gapSizeNode):kS;tl.assign(n),Dh.assign(i);let s=no(Li("lineDistance").mul(t));(e?s.add(e):s).mod(tl.add(Dh)).greaterThan(tl).discard()}};var Qf=gl("vec3","worldStart"),t_=gl("vec3","worldEnd"),YR=gl("float","lineDistance"),$o=gl("vec4","worldPos"),k1=P(({start:r,end:e})=>{let t=Jn.element(2).element(2),n=Jn.element(3).element(2);return t.greaterThan(0).select(n.negate().div(t.add(1)),n.mul(-.5).div(t)).sub(r.z).div(e.z.sub(r.z))},{start:"vec4",end:"vec4",return:"float"}),QI=P(({p1:r,p2:e,p3:t,p4:n})=>{let i=r.sub(t),s=n.sub(t),a=e.sub(r),o=i.dot(s),l=s.dot(a),c=i.dot(a),u=s.dot(s),h=a.dot(a).mul(u).sub(l.mul(l)),f=o.mul(l).sub(c.mul(u)).div(h).clamp(),m=o.add(l.mul(f)).div(u).clamp();return $(f,m)},{p1:"vec3",p2:"vec3",p3:"vec3",p4:"vec3",return:"vec2"}),oz=P(({material:r})=>{let e=r._useDash,t=r._useWorldUnits,n=Li("instanceStart"),i=Li("instanceEnd"),s=J(cr.mul(J(n,1))).toVar("start"),a=J(cr.mul(J(i,1))).toVar("end"),o,l;e&&(o=v(Li("instanceDistanceStart")).toVar("distanceStart"),l=v(Li("instanceDistanceEnd")).toVar("distanceEnd")),t&&(Qf.assign(s.xyz),t_.assign(a.xyz));let c=pu.z.div(pu.w),u=Jn.element(2).element(3).equal(-1);if(oe(u,()=>{oe(s.z.lessThan(0).and(a.z.greaterThan(0)),()=>{let x=k1({start:s,end:a});a.assign(J(Re(s.xyz,a.xyz,x),a.w)),e&&l.assign(Re(o,l,x))}).ElseIf(a.z.lessThan(0).and(s.z.greaterThanEqual(0)),()=>{let x=k1({start:a,end:s});s.assign(J(Re(a.xyz,s.xyz,x),s.w)),e&&o.assign(Re(l,o,x))})}),e){let x=r.dashScaleNode?v(r.dashScaleNode):US,b=r.offsetNode?v(r.offsetNode):VS,_=Bn.y.lessThan(.5).select(x.mul(o),x.mul(l));_=_.add(b),YR.assign(_)}let d=Jn.mul(s),h=Jn.mul(a),p=d.xyz.div(d.w),f=h.xyz.div(h.w),m=f.xy.sub(p.xy).toVar();m.x.assign(m.x.mul(c)),m.assign(m.normalize());let y=J().toVar();if(t){let x=a.xyz.sub(s.xyz).normalize(),b=Re(s.xyz,a.xyz,.5).normalize(),_=x.cross(b).normalize(),S=x.cross(_);$o.assign(Bn.y.lessThan(.5).select(s,a));let M=xm.mul(.5);$o.addAssign(J(Bn.x.lessThan(0).select(_.mul(M),_.mul(M).negate()),0)),e||($o.addAssign(J(Bn.y.lessThan(.5).select(x.mul(M).negate(),x.mul(M)),0)),$o.addAssign(J(S.mul(M),0)),oe(Bn.y.greaterThan(1).or(Bn.y.lessThan(0)),()=>{$o.subAssign(J(S.mul(2).mul(M),0))})),y.assign(Jn.mul($o));let w=N().toVar();w.assign(Bn.y.lessThan(.5).select(p,f)),y.z.assign(w.z.mul(y.w))}else{let x=$(m.y,m.x.negate()).toVar("offset");m.x.assign(m.x.div(c)),x.x.assign(x.x.div(c)),x.assign(Bn.x.lessThan(0).select(x.negate(),x)),oe(Bn.y.lessThan(0),()=>{x.assign(x.sub(m))}).ElseIf(Bn.y.greaterThan(1),()=>{x.assign(x.add(m))}),x.assign(x.mul(xm)),x.assign(x.div(pu.w.div(RS))),y.assign(Bn.y.lessThan(.5).select(d,h)),x.assign(x.mul(y.w)),y.assign(y.add(J(x,0,0)))}return y})(),lz=P(({material:r,renderer:e})=>{let t=r._useAlphaToCoverage,n=r._useDash,i=r._useWorldUnits,s=Ye();if(n){let o=r.dashSizeNode?v(r.dashSizeNode):OS,l=r.gapSizeNode?v(r.gapSizeNode):kS;tl.assign(o),Dh.assign(l),s.y.lessThan(-1).or(s.y.greaterThan(1)).discard(),YR.mod(tl.add(Dh)).greaterThan(tl).discard()}let a=v(1).toVar("alpha");if(i){let o=$o.xyz.normalize().mul(1e5),l=t_.sub(Qf),c=QI({p1:Qf,p2:t_,p3:N(0,0,0),p4:o}),u=Qf.add(l.mul(c.x)),d=o.mul(c.y),f=u.sub(d).length().div(xm);if(!n)if(t&&e.currentSamples>0){let m=f.fwidth();a.assign(Oi(m.negate().add(.5),m.add(.5),f).oneMinus())}else f.greaterThan(.5).discard()}else if(t&&e.currentSamples>0){let o=s.x,l=s.y.greaterThan(0).select(s.y.sub(1),s.y.add(1)),c=o.mul(o).add(l.mul(l)),u=v(c.fwidth()).toVar("dlen");oe(s.y.abs().greaterThan(1),()=>{a.assign(Oi(u.oneMinus(),u.add(1),c).oneMinus())})}else oe(s.y.abs().greaterThan(1),()=>{let o=s.x,l=s.y.greaterThan(0).select(s.y.sub(1),s.y.add(1));o.mul(o).add(l.mul(l)).greaterThan(1).discard()});return a})();var eF=new hd,n_=class extends We{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(eF),this.setValues(e)}setupDiffuseColor(){let e=this.opacityNode?v(this.opacityNode):BS;$e.assign(Ag(J(FS(Be),e),Vt))}},jS=P(([r=CS])=>{let e=r.z.atan(r.x).mul(1/(Math.PI*2)).add(.5),t=r.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return $(e,t)}),i_=P(([r=Ye()])=>{let e=r.x.sub(.5).mul(Math.PI*2),t=r.y.sub(.5).mul(Math.PI),n=t.cos(),i=n.mul(e.cos()),s=t.sin(),a=n.mul(e.sin());return N(i,s,a)}),Sm=class extends Jt{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;let n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new xa(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){let n=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let s=new Zl(5,5,5),a=jS(CS),o=new We;o.colorNode=Ue(t,a,0),o.side=ln,o.blending=_s;let l=new De(s,o),c=new fa;c.add(l),t.minFilter===bs&&(t.minFilter=St);let u=new Pd(1,10,this),d=e.getMRT();return e.setMRT(null),u.update(e,c),e.setMRT(d),t.minFilter=n,t.generateMipmaps=i,l.geometry.dispose(),l.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){let s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,i);e.setRenderTarget(s)}},Eh=new WeakMap,s_=class extends ht{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Zn(null);let t=new xa;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=pe.RENDER}updateBefore(e){let{renderer:t,material:n}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){let s=i.isTextureNode?i.value:n[i.property];if(s&&s.isTexture){let a=s.mapping;if(a===zd||a===Hd){if(Eh.has(s)){let o=Eh.get(s);V1(o,s.mapping),this._cubeTexture=o}else{let o=s.image;if(tF(o)){let l=new Sm(o.height);l.fromEquirectangularTexture(t,s),V1(l.texture,s.mapping),this._cubeTexture=l.texture,Eh.set(s,l.texture),s.addEventListener("dispose",jR)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}};function tF(r){return r==null?!1:r.height>0}function jR(r){let e=r.target;e.removeEventListener("dispose",jR);let t=Eh.get(e);t!==void 0&&(Eh.delete(e),t.dispose())}function V1(r,e){e===zd?r.mapping=Pr:e===Hd&&(r.mapping=Ca)}var KR=Me(s_).setParameterLength(1),Bh=class extends eo{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=KR(this.envNode)}},r_=class extends eo{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){let t=v(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}},_u=class{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}},Tm=class extends _u{constructor(){super()}indirect({context:e}){let t=e.ambientOcclusion,n=e.reflectedLight,i=e.irradianceLightMap;n.indirectDiffuse.assign(J(0)),i?n.indirectDiffuse.addAssign(i):n.indirectDiffuse.addAssign(J(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign($e.rgb)}finish(e){let{material:t,context:n}=e,i=n.outgoingLight,s=e.context.environment;if(s)switch(t.combine){case No:i.rgb.assign(Re(i.rgb,i.rgb.mul(s.rgb),wh.mul(Jf)));break;case tf:i.rgb.assign(Re(i.rgb,s.rgb,wh.mul(Jf)));break;case nf:i.rgb.addAssign(s.rgb.mul(wh.mul(Jf)));break;default:X("BasicLightingModel: Unsupported .combine value:",t.combine);break}}},nF=new ji,Uh=class extends We{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(nF),this.setValues(e)}setupNormal(){return xl(gu)}setupEnvironment(e){let t=super.setupEnvironment(e);return t?new Bh(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new r_(GS)),t}setupOutgoingLight(){return $e.rgb}setupLightingModel(){return new Tm}},bu=P(({f0:r,f90:e,dotVH:t})=>{let n=t.mul(-5.55473).sub(6.98316).mul(t).exp2();return r.mul(n.oneMinus()).add(e.mul(n))}),dl=P(r=>r.diffuseColor.mul(1/Math.PI)),iF=()=>v(.25),sF=P(({dotNH:r})=>lm.mul(v(.5)).add(1).mul(v(1/Math.PI)).mul(r.pow(lm))),rF=P(({lightDirection:r})=>{let e=r.add(Qe).normalize(),t=Be.dot(e).clamp(),n=Qe.dot(e).clamp(),i=bu({f0:Ja,f90:1,dotVH:n}),s=iF(),a=sF({dotNH:t});return i.mul(s).mul(a)}),Mm=class extends Tm{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){let s=Be.dot(e).clamp().mul(t);n.directDiffuse.addAssign(s.mul(dl({diffuseColor:$e.rgb}))),this.specular===!0&&n.directSpecular.addAssign(s.mul(rF({lightDirection:e})).mul(wh))}indirect(e){let{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(dl({diffuseColor:$e}))),i.indirectDiffuse.mulAssign(t)}},aF=new pd,a_=class extends We{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(aF),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t?new Bh(t):null}setupLightingModel(){return new Mm(!1)}},oF=new ud,o_=class extends We{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(oF),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t?new Bh(t):null}setupLightingModel(){return new Mm}setupVariants(){let e=(this.shininessNode?v(this.shininessNode):aR).max(1e-4);lm.assign(e);let t=this.specularNode||lR;Ja.assign(t)}},ZR=P(r=>{if(r.geometry.hasAttribute("normal")===!1)return v(0);let e=gu.dFdx().abs().max(gu.dFdy().abs());return e.x.max(e.y).max(e.z)}),KS=P(r=>{let{roughness:e}=r,t=ZR(),n=e.max(.0525);return n=n.add(t),n=n.min(1),n}),JR=P(({alpha:r,dotNL:e,dotNV:t})=>{let n=r.pow2(),i=e.mul(n.add(n.oneMinus().mul(t.pow2())).sqrt()),s=t.mul(n.add(n.oneMinus().mul(e.pow2())).sqrt());return Ui(.5,i.add(s).max(Mg))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),lF=P(({alphaT:r,alphaB:e,dotTV:t,dotBV:n,dotTL:i,dotBL:s,dotNV:a,dotNL:o})=>{let l=o.mul(N(r.mul(t),e.mul(n),a).length()),c=a.mul(N(r.mul(i),e.mul(s),o).length());return Ui(.5,l.add(c).max(Mg))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),QR=P(({alpha:r,dotNH:e})=>{let t=r.pow2(),n=e.pow2().mul(t.oneMinus()).oneMinus();return t.div(n.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),cF=v(1/Math.PI),uF=P(({alphaT:r,alphaB:e,dotNH:t,dotTH:n,dotBH:i})=>{let s=r.mul(e),a=N(e.mul(n),r.mul(i),s.mul(t)),o=a.dot(a),l=s.div(o);return cF.mul(s.mul(l.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),ZS=P(({lightDirection:r,f0:e,f90:t,roughness:n,f:i,normalView:s=Be,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{let l=n.pow2(),c=r.add(Qe).normalize(),u=s.dot(r).clamp(),d=s.dot(Qe).clamp(),h=s.dot(c).clamp(),p=Qe.dot(c).clamp(),f=bu({f0:e,f90:t,dotVH:p}),m,y;if(fu(a)&&(f=vg.mix(f,i)),fu(o)){let x=Th.dot(r),b=Th.dot(Qe),_=Th.dot(c),S=el.dot(r),M=el.dot(Qe),w=el.dot(c);m=lF({alphaT:om,alphaB:l,dotTV:b,dotBV:M,dotTL:x,dotBL:S,dotNV:d,dotNL:u}),y=uF({alphaT:om,alphaB:l,dotNH:h,dotTH:_,dotBH:w})}else m=JR({alpha:l,dotNL:u,dotNV:d}),y=QR({alpha:l,dotNH:h});return f.mul(m).mul(y)}),dF=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),js=null,Oh=P(({roughness:r,dotNV:e})=>{js===null&&(js=new ga(dF,16,16,mi,xt),js.name="DFG_LUT",js.minFilter=St,js.magFilter=St,js.wrapS=ai,js.wrapT=ai,js.generateMipmaps=!1,js.needsUpdate=!0);let t=$(r,e);return Ue(js,t).rg}),hF=P(({lightDirection:r,f0:e,f90:t,roughness:n,f:i,USE_IRIDESCENCE:s,USE_ANISOTROPY:a})=>{let o=ZS({lightDirection:r,f0:e,f90:t,roughness:n,f:i,USE_IRIDESCENCE:s,USE_ANISOTROPY:a}),l=Be.dot(r).clamp(),c=Be.dot(Qe).clamp(),u=Oh({roughness:n,dotNV:c}),d=Oh({roughness:n,dotNV:l}),h=e.mul(u.x).add(t.mul(u.y)),p=e.mul(d.x).add(t.mul(d.y)),f=u.x.add(u.y),m=d.x.add(d.y),y=v(1).sub(f),x=v(1).sub(m),b=e.add(e.oneMinus().mul(.047619)),_=h.mul(p).mul(b).div(v(1).sub(y.mul(x).mul(b).mul(b)).add(Mg)),S=y.mul(x),M=_.mul(S);return o.add(M)}),eA=P(r=>{let{dotNV:e,specularColor:t,specularF90:n,roughness:i}=r,s=Oh({dotNV:e,roughness:i});return t.mul(s.x).add(n.mul(s.y))}),l_=P(({f:r,f90:e,dotVH:t})=>{let n=t.oneMinus().saturate(),i=n.mul(n),s=n.mul(i,i).clamp(0,.9999);return r.sub(N(e).mul(s)).div(s.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),pF=P(({roughness:r,dotNH:e})=>{let t=r.pow2(),n=v(1).div(t),s=e.pow2().oneMinus().max(.0078125);return v(2).add(n).mul(s.pow(n.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),fF=P(({dotNV:r,dotNL:e})=>v(1).div(v(4).mul(e.add(r).sub(e.mul(r))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),mF=P(({lightDirection:r})=>{let e=r.add(Qe).normalize(),t=Be.dot(r).clamp(),n=Be.dot(Qe).clamp(),i=Be.dot(e).clamp(),s=pF({roughness:za,dotNH:i}),a=fF({dotNV:n,dotNL:t});return Di.mul(s).mul(a)}),G1=P(({N:r,V:e,roughness:t})=>{let s=.0078125,a=r.dot(e).saturate(),o=$(t,a.oneMinus().sqrt());return o.assign(o.mul(.984375).add(s)),o}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),gF=P(({f:r})=>{let e=r.length();return At(e.mul(e).add(r.z).div(e.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),bf=P(({v1:r,v2:e})=>{let t=r.dot(e),n=t.abs().toVar(),i=n.mul(.0145206).add(.4965155).mul(n).add(.8543985).toVar(),s=n.add(4.1616724).mul(n).add(3.417594).toVar(),a=i.div(s),o=t.greaterThan(0).select(a,At(t.mul(t).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return r.cross(e).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),Ey=P(({N:r,V:e,P:t,mInv:n,p0:i,p1:s,p2:a,p3:o})=>{let l=s.sub(i).toVar(),c=o.sub(i).toVar(),u=l.cross(c),d=N().toVar();return oe(u.dot(t.sub(i)).greaterThanEqual(0),()=>{let h=e.sub(r.mul(e.dot(r))).normalize(),p=r.cross(h).negate(),f=n.mul(yn(h,p,r).transpose()).toVar(),m=f.mul(i.sub(t)).normalize().toVar(),y=f.mul(s.sub(t)).normalize().toVar(),x=f.mul(a.sub(t)).normalize().toVar(),b=f.mul(o.sub(t)).normalize().toVar(),_=N(0).toVar();_.addAssign(bf({v1:m,v2:y})),_.addAssign(bf({v1:y,v2:x})),_.addAssign(bf({v1:x,v2:b})),_.addAssign(bf({v1:b,v2:m})),d.assign(N(gF({f:_})))}),d}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]});var Og=1/6,tA=r=>xe(Og,xe(r,xe(r,r.negate().add(3)).sub(3)).add(1)),c_=r=>xe(Og,xe(r,xe(r,xe(3,r).sub(6))).add(4)),nA=r=>xe(Og,xe(r,xe(r,xe(-3,r).add(3)).add(3)).add(1)),u_=r=>xe(Og,ss(r,3)),z1=r=>tA(r).add(c_(r)),H1=r=>nA(r).add(u_(r)),W1=r=>Wt(-1,c_(r).div(tA(r).add(c_(r)))),q1=r=>Wt(1,u_(r).div(nA(r).add(u_(r)))),$1=(r,e,t)=>{let n=r.uvNode,i=xe(n,e.zw).add(.5),s=sr(i),a=Cs(i),o=z1(a.x),l=H1(a.x),c=W1(a.x),u=q1(a.x),d=W1(a.y),h=q1(a.y),p=$(s.x.add(c),s.y.add(d)).sub(.5).mul(e.xy),f=$(s.x.add(u),s.y.add(d)).sub(.5).mul(e.xy),m=$(s.x.add(c),s.y.add(h)).sub(.5).mul(e.xy),y=$(s.x.add(u),s.y.add(h)).sub(.5).mul(e.xy),x=z1(a.y).mul(Wt(o.mul(r.sample(p).level(t)),l.mul(r.sample(f).level(t)))),b=H1(a.y).mul(Wt(o.mul(r.sample(m).level(t)),l.mul(r.sample(y).level(t))));return x.add(b)},JS=P(([r,e])=>{let t=$(r.size(C(e))),n=$(r.size(C(e.add(1)))),i=Ui(1,t),s=Ui(1,n),a=$1(r,J(i,t),sr(e)),o=$1(r,J(s,n),Eg(e));return Cs(e).mix(a,o)}),yF=P(([r,e])=>{let t=e.mul(wS(r));return JS(r,t)}),X1=P(([r,e,t,n,i])=>{let s=N(mS(e.negate(),kn(r),Ui(1,n))),a=N(rr(i[0].xyz),rr(i[1].xyz),rr(i[2].xyz));return kn(s).mul(t.mul(a))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),xF=P(([r,e])=>r.mul(Ns(e.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),_F=qS(),bF=HR(),Y1=P(([r,e,t],{material:n})=>{let s=(n.side===ln?_F:bF).sample(r),a=ir(cl.x).mul(xF(e,t));return JS(s,a)}),j1=P(([r,e,t])=>(oe(t.notEqual(0),()=>{let n=wg(e).negate().div(t);return nS(n.negate().mul(r))}),N(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),vF=P(([r,e,t,n,i,s,a,o,l,c,u,d,h,p,f])=>{let m,y;if(f){m=J().toVar(),y=N().toVar();let M=u.sub(1).mul(f.mul(.025)),w=N(u.sub(M),u,u.add(M));Xe({start:0,end:3},({i:T})=>{let R=w.element(T),D=X1(r,e,d,R,o),L=a.add(D),B=c.mul(l.mul(J(L,1))),W=$(B.xy.div(B.w)).toVar();W.addAssign(1),W.divAssign(2),W.assign($(W.x,W.y.oneMinus()));let q=Y1(W,t,R);m.element(T).assign(q.element(T)),m.a.addAssign(q.a),y.element(T).assign(n.element(T).mul(j1(rr(D),h,p).element(T)))}),m.a.divAssign(3)}else{let M=X1(r,e,d,u,o),w=a.add(M),T=c.mul(l.mul(J(w,1))),R=$(T.xy.div(T.w)).toVar();R.addAssign(1),R.divAssign(2),R.assign($(R.x,R.y.oneMinus())),m=Y1(R,t,u),y=n.mul(j1(rr(M),h,p))}let x=y.rgb.mul(m.rgb),b=r.dot(e).clamp(),_=N(eA({dotNV:b,specularColor:i,specularF90:s,roughness:t})),S=y.r.add(y.g,y.b).div(3);return J(_.oneMinus().mul(x),m.a.oneMinus().mul(S).oneMinus())}),SF=yn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),TF=r=>{let e=r.sqrt();return N(1).add(e).div(N(1).sub(e))},K1=(r,e)=>r.sub(e).div(r.add(e)).pow2(),MF=(r,e)=>{let t=r.mul(2*Math.PI*1e-9),n=N(54856e-17,44201e-17,52481e-17),i=N(1681e3,1795300,2208400),s=N(43278e5,93046e5,66121e5),a=v(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(t.mul(2239900).add(e.x).cos()).mul(t.pow2().mul(-45282e5).exp()),o=n.mul(s.mul(2*Math.PI).sqrt()).mul(i.mul(t).add(e).cos()).mul(t.pow2().negate().mul(s).exp());return o=N(o.x.add(a),o.y,o.z).div(10685e-11),SF.mul(o)},Z1=P(({outsideIOR:r,eta2:e,cosTheta1:t,thinFilmThickness:n,baseF0:i})=>{let s=Re(r,e,Oi(0,.03,n)),o=r.div(s).pow2().mul(t.pow2().oneMinus()).oneMinus();oe(o.lessThan(0),()=>N(1));let l=o.sqrt(),c=K1(s,r),u=bu({f0:c,f90:1,dotVH:t}),d=u.oneMinus(),h=s.lessThan(r).select(Math.PI,0),p=v(Math.PI).sub(h),f=TF(i.clamp(0,.9999)),m=K1(f,s.toVec3()),y=bu({f0:m,f90:1,dotVH:l}),x=N(f.x.lessThan(s).select(Math.PI,0),f.y.lessThan(s).select(Math.PI,0),f.z.lessThan(s).select(Math.PI,0)),b=s.mul(n,l,2),_=N(p).add(x),S=u.mul(y).clamp(1e-5,.9999),M=S.sqrt(),w=d.pow2().mul(y).div(N(1).sub(S)),R=u.add(w).toVar(),D=w.sub(d).toVar();return Xe({start:1,end:2,condition:"<=",name:"m"},({m:L})=>{D.mulAssign(M);let B=MF(v(L).mul(b),v(L).mul(_)).mul(2);R.addAssign(D.mul(B))}),R.max(N(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),ih=P(({normal:r,viewDir:e,roughness:t})=>{let n=r.dot(e).saturate(),i=t.mul(t),s=t.add(.1).reciprocal(),a=v(-1.9362).add(t.mul(1.0678)).add(i.mul(.4573)).sub(s.mul(.8469)),o=v(-.6014).add(t.mul(.5538)).sub(i.mul(.467)).sub(s.mul(.1255));return a.mul(n).add(o).exp().saturate()}),sh=N(.04),vf=v(1),wm=class extends _u{constructor(e=!1,t=!1,n=!1,i=!1,s=!1,a=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=i,this.transmission=s,this.dispersion=a,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(this.clearcoat===!0&&(this.clearcoatRadiance=N().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=N().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=N().toVar("clearcoatSpecularIndirect")),this.sheen===!0&&(this.sheenSpecularDirect=N().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=N().toVar("sheenSpecularIndirect")),this.iridescence===!0){let t=Be.dot(Qe).clamp(),n=Z1({outsideIOR:v(1),eta2:rm,cosTheta1:t,thinFilmThickness:am,baseF0:Ja}),i=Z1({outsideIOR:v(1),eta2:rm,cosTheta1:t,thinFilmThickness:am,baseF0:$e.rgb});this.iridescenceFresnel=Re(n,i,zr),this.iridescenceF0Dielectric=l_({f:n,f90:1,dotVH:t}),this.iridescenceF0Metallic=l_({f:i,f90:1,dotVH:t}),this.iridescenceF0=Re(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,zr)}if(this.transmission===!0){let t=ar,n=DE.sub(ar).normalize(),i=ro,s=e.context;s.backdrop=vF(i,n,tr,Xo,jo,Ko,t,rs,so,Jn,Mh,Zv,Qv,Jv,this.dispersion?eS:null),s.backdropAlpha=cm,$e.a.mulAssign(Re(1,s.backdrop.a,cm))}super.start(e)}computeMultiscattering(e,t,n,i,s=null){let a=Be.dot(Qe).clamp(),o=Oh({roughness:tr,dotNV:a}),l=s?vg.mix(i,s):i,c=l.mul(o.x).add(n.mul(o.y)),d=o.x.add(o.y).oneMinus(),h=l.add(l.oneMinus().mul(.047619)),p=c.mul(h).div(d.mul(h).oneMinus());e.addAssign(c),t.addAssign(p.mul(d))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){let s=Be.dot(e).clamp().mul(t).toVar();if(this.sheen===!0){this.sheenSpecularDirect.addAssign(s.mul(mF({lightDirection:e})));let a=ih({normal:Be,viewDir:Qe,roughness:za}),o=ih({normal:Be,viewDir:e,roughness:za}),l=Di.r.max(Di.g).max(Di.b).mul(a.max(o)).oneMinus();s.mulAssign(l)}if(this.clearcoat===!0){let o=qa.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(o.mul(ZS({lightDirection:e,f0:sh,f90:vf,roughness:lu,normalView:qa})))}n.directDiffuse.addAssign(s.mul(dl({diffuseColor:Xo}))),n.directSpecular.addAssign(s.mul(hF({lightDirection:e,f0:jo,f90:1,roughness:tr,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:i,reflectedLight:s,ltc_1:a,ltc_2:o}){let l=t.add(n).sub(i),c=t.sub(n).sub(i),u=t.sub(n).add(i),d=t.add(n).add(i),h=Be,p=Qe,f=Ot.toVar(),m=G1({N:h,V:p,roughness:tr}),y=a.sample(m).toVar(),x=o.sample(m).toVar(),b=yn(N(y.x,0,y.y),N(0,1,0),N(y.z,0,y.w)).toVar(),_=jo.mul(x.x).add(Ko.sub(jo).mul(x.y)).toVar();if(s.directSpecular.addAssign(e.mul(_).mul(Ey({N:h,V:p,P:f,mInv:b,p0:l,p1:c,p2:u,p3:d}))),s.directDiffuse.addAssign(e.mul(Xo).mul(Ey({N:h,V:p,P:f,mInv:yn(1,0,0,0,1,0,0,0,1),p0:l,p1:c,p2:u,p3:d}))),this.clearcoat===!0){let S=qa,M=G1({N:S,V:p,roughness:lu}),w=a.sample(M),T=o.sample(M),R=yn(N(w.x,0,w.y),N(0,1,0),N(w.z,0,w.w)),D=sh.mul(T.x).add(vf.sub(sh).mul(T.y));this.clearcoatSpecularDirect.addAssign(e.mul(D).mul(Ey({N:S,V:p,P:f,mInv:R,p0:l,p1:c,p2:u,p3:d})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){let{irradiance:t,reflectedLight:n}=e.context,i=t.mul(dl({diffuseColor:Xo})).toVar();if(this.sheen===!0){let s=ih({normal:Be,viewDir:Qe,roughness:za}),a=Di.r.max(Di.g).max(Di.b).mul(s).oneMinus();i.mulAssign(a)}n.indirectDiffuse.addAssign(i)}indirectSpecular(e){let{radiance:t,iblIrradiance:n,reflectedLight:i}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(n.mul(Di,ih({normal:Be,viewDir:Qe,roughness:za}))),this.clearcoat===!0){let y=qa.dot(Qe).clamp(),x=eA({dotNV:y,specularColor:sh,specularF90:vf,roughness:lu});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(x))}let s=N().toVar("singleScatteringDielectric"),a=N().toVar("multiScatteringDielectric"),o=N().toVar("singleScatteringMetallic"),l=N().toVar("multiScatteringMetallic");this.computeMultiscattering(s,a,Ko,Ja,this.iridescenceF0Dielectric),this.computeMultiscattering(o,l,Ko,$e.rgb,this.iridescenceF0Metallic);let c=Re(s,o,zr),u=Re(a,l,zr),d=s.add(a),h=Xo.mul(d.oneMinus()),p=n.mul(1/Math.PI),f=t.mul(c).add(u.mul(p)).toVar(),m=h.mul(p).toVar();if(this.sheen===!0){let y=ih({normal:Be,viewDir:Qe,roughness:za}),x=Di.r.max(Di.g).max(Di.b).mul(y).oneMinus();f.mulAssign(x),m.mulAssign(x)}i.indirectSpecular.addAssign(f),i.indirectDiffuse.addAssign(m)}ambientOcclusion(e){let{ambientOcclusion:t,reflectedLight:n}=e.context,s=Be.dot(Qe).clamp().add(t),a=tr.mul(-16).oneMinus().negate().exp2(),o=t.sub(s.pow(a).oneMinus()).clamp();this.clearcoat===!0&&this.clearcoatSpecularIndirect.mulAssign(t),this.sheen===!0&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(o)}finish({context:e}){let{outgoingLight:t}=e;if(this.clearcoat===!0){let n=qa.dot(Qe).clamp(),i=bu({dotVH:n,f0:sh,f90:vf}),s=t.mul(sm.mul(i).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(sm));t.assign(s)}if(this.sheen===!0){let n=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(n)}}},J1=v(1),d_=v(-2),Sf=v(.8),Ry=v(-1),Tf=v(.4),Ay=v(2),Mf=v(.305),Cy=v(3),Q1=v(.21),wF=v(4),eM=v(4),EF=v(16),RF=P(([r])=>{let e=N(rt(r)).toVar(),t=v(-1).toVar();return oe(e.x.greaterThan(e.z),()=>{oe(e.x.greaterThan(e.y),()=>{t.assign(On(r.x.greaterThan(0),0,3))}).Else(()=>{t.assign(On(r.y.greaterThan(0),1,4))})}).Else(()=>{oe(e.z.greaterThan(e.y),()=>{t.assign(On(r.z.greaterThan(0),2,5))}).Else(()=>{t.assign(On(r.y.greaterThan(0),1,4))})}),t}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),AF=P(([r,e])=>{let t=$().toVar();return oe(e.equal(0),()=>{t.assign($(r.z,r.y).div(rt(r.x)))}).ElseIf(e.equal(1),()=>{t.assign($(r.x.negate(),r.z.negate()).div(rt(r.y)))}).ElseIf(e.equal(2),()=>{t.assign($(r.x.negate(),r.y).div(rt(r.z)))}).ElseIf(e.equal(3),()=>{t.assign($(r.z.negate(),r.y).div(rt(r.x)))}).ElseIf(e.equal(4),()=>{t.assign($(r.x.negate(),r.z).div(rt(r.y)))}).Else(()=>{t.assign($(r.x,r.y).div(rt(r.z)))}),xe(.5,t.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),CF=P(([r])=>{let e=v(0).toVar();return oe(r.greaterThanEqual(Sf),()=>{e.assign(J1.sub(r).mul(Ry.sub(d_)).div(J1.sub(Sf)).add(d_))}).ElseIf(r.greaterThanEqual(Tf),()=>{e.assign(Sf.sub(r).mul(Ay.sub(Ry)).div(Sf.sub(Tf)).add(Ry))}).ElseIf(r.greaterThanEqual(Mf),()=>{e.assign(Tf.sub(r).mul(Cy.sub(Ay)).div(Tf.sub(Mf)).add(Ay))}).ElseIf(r.greaterThanEqual(Q1),()=>{e.assign(Mf.sub(r).mul(wF.sub(Cy)).div(Mf.sub(Q1)).add(Cy))}).Else(()=>{e.assign(v(-2).mul(ir(xe(1.16,r))))}),e}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),iA=P(([r,e])=>{let t=r.toVar();t.assign(xe(2,t).sub(1));let n=N(t,1).toVar();return oe(e.equal(0),()=>{n.assign(n.zyx)}).ElseIf(e.equal(1),()=>{n.assign(n.xzy),n.xz.mulAssign(-1)}).ElseIf(e.equal(2),()=>{n.x.mulAssign(-1)}).ElseIf(e.equal(3),()=>{n.assign(n.zyx),n.xz.mulAssign(-1)}).ElseIf(e.equal(4),()=>{n.assign(n.xzy),n.xy.mulAssign(-1)}).ElseIf(e.equal(5),()=>{n.z.mulAssign(-1)}),n}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),sA=P(([r,e,t,n,i,s])=>{let a=v(t),o=N(e),l=Ns(CF(a),d_,s),c=Cs(l),u=sr(l),d=N(kh(r,o,u,n,i,s)).toVar();return oe(c.notEqual(0),()=>{let h=N(kh(r,o,u.add(1),n,i,s)).toVar();d.assign(Re(d,h,c))}),d}),kh=P(([r,e,t,n,i,s])=>{let a=v(t).toVar(),o=N(e),l=v(RF(o)).toVar(),c=v(At(eM.sub(a),0)).toVar();a.assign(At(a,eM));let u=v(mu(a)).toVar(),d=$(AF(o,l).mul(u.sub(2)).add(1)).toVar();return oe(l.greaterThan(2),()=>{d.y.addAssign(u),l.subAssign(3)}),d.x.addAssign(l.mul(u)),d.x.addAssign(c.mul(xe(3,EF))),d.y.addAssign(xe(4,mu(s).sub(u))),d.x.mulAssign(n),d.y.mulAssign(i),r.sample(d).grad($(),$())}),Ny=P(({envMap:r,mipInt:e,outputDirection:t,theta:n,axis:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{let l=ws(n),c=t.mul(l).add(i.cross(t).mul(Kn(n))).add(i.mul(i.dot(t).mul(l.oneMinus())));return kh(r,c,e,s,a,o)}),rA=P(({n:r,latitudinal:e,poleAxis:t,outputDirection:n,weights:i,samples:s,dTheta:a,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:d})=>{let h=N(On(e,t,Wr(t,n))).toVar();oe(h.equal(N(0)),()=>{h.assign(N(n.z,0,n.x.negate()))}),h.assign(kn(h));let p=N().toVar();return p.addAssign(i.element(0).mul(Ny({theta:0,axis:h,outputDirection:n,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:d}))),Xe({start:C(1),end:r},({i:f})=>{oe(f.greaterThanEqual(s),()=>{VR()});let m=v(a.mul(v(f))).toVar();p.addAssign(i.element(f).mul(Ny({theta:m.mul(-1),axis:h,outputDirection:n,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:d}))),p.addAssign(i.element(f).mul(Ny({theta:m,axis:h,outputDirection:n,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:d})))}),J(p,1)}),NF=P(([r])=>{let e=V(r).toVar();return e.assign(e.shiftLeft(V(16)).bitOr(e.shiftRight(V(16)))),e.assign(e.bitAnd(V(1431655765)).shiftLeft(V(1)).bitOr(e.bitAnd(V(2863311530)).shiftRight(V(1)))),e.assign(e.bitAnd(V(858993459)).shiftLeft(V(2)).bitOr(e.bitAnd(V(3435973836)).shiftRight(V(2)))),e.assign(e.bitAnd(V(252645135)).shiftLeft(V(4)).bitOr(e.bitAnd(V(4042322160)).shiftRight(V(4)))),e.assign(e.bitAnd(V(16711935)).shiftLeft(V(8)).bitOr(e.bitAnd(V(4278255360)).shiftRight(V(8)))),v(e).mul(23283064365386963e-26)}),PF=P(([r,e])=>$(v(r).div(v(e)),NF(r))),DF=P(([r,e,t])=>{let n=t.mul(t).toConst(),i=N(1,0,0).toConst(),s=Wr(e,i).toConst(),a=Qn(r.x).toConst(),o=xe(2,3.14159265359).mul(r.y).toConst(),l=a.mul(ws(o)).toConst(),c=a.mul(Kn(o)).toVar(),u=xe(.5,e.z.add(1)).toConst();c.assign(u.oneMinus().mul(Qn(l.mul(l).oneMinus())).add(u.mul(c)));let d=i.mul(l).add(s.mul(c)).add(e.mul(Qn(At(0,l.mul(l).add(c.mul(c)).oneMinus()))));return kn(N(n.mul(d.x),n.mul(d.y),At(0,d.z)))}),aA=P(({roughness:r,mipInt:e,envMap:t,N_immutable:n,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{let l=N(n).toVar(),c=N(0).toVar(),u=v(0).toVar();return oe(r.lessThan(.001),()=>{c.assign(kh(t,l,e,s,a,o))}).Else(()=>{let d=On(rt(l.z).lessThan(.999),N(0,0,1),N(1,0,0)),h=kn(Wr(d,l)).toVar(),p=Wr(l,h).toVar();Xe({start:V(0),end:i},({i:f})=>{let m=PF(f,i),y=DF(m,N(0,0,1),r),x=kn(h.mul(y.x).add(p.mul(y.y)).add(l.mul(y.z))),b=kn(x.mul(ls(l,x).mul(2)).sub(l)),_=At(ls(l,b),0);oe(_.greaterThan(0),()=>{let S=kh(t,b,e,s,a,o);c.addAssign(S.mul(_)),u.addAssign(_)})}),oe(u.greaterThan(0),()=>{c.assign(c.div(u))})}),J(c,1)}),Ya=4,tM=[.125,.215,.35,.446,.526,.582],Yo=20,IF=512,rh=new Ao(-1,1,1,-1,0,1),FF=new an(90,1),nM=new me,Py=null,Dy=0,Iy=0,LF=new E,Em=new WeakMap,BF=[3,1,5,0,4,2],Fy=iA(Ye(),Li("faceIndex")).normalize(),kg=N(Fy.x,Fy.y,Fy.z),h_=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,i=100,s={}){let{size:a=256,position:o=LF,renderTarget:l=null}=s;if(this._setSize(a),this._hasInitialized===!1)throw new Error('THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.');Py=this._renderer.getRenderTarget(),Dy=this._renderer.getActiveCubeFace(),Iy=this._renderer.getActiveMipmapLevel();let c=l||this._allocateTarget(!0);return this._init(c),this._sceneToCubeUV(e,n,i,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}async fromSceneAsync(e,t=0,n=.1,i=100,s={}){return Ce('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,n,i,s)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1)throw new Error('THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Ce('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(this._hasInitialized===!1)throw new Error('THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Ce('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=sM(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=rM(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===Pr||e.mapping===Ca?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Py,Dy,Iy),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Py=this._renderer.getRenderTarget(),Dy=this._renderer.getActiveCubeFace(),Iy=this._renderer.getActiveMipmapLevel();let n=t||this._allocateTarget(!1);return this._init(n),this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTarget(e){let t=3*Math.max(this._cubeSize,112),n=4*this._cubeSize;return iM(t,n,e)}_init(e){if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=iM(e.width,e.height);let{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=UF(t)),this._blurMaterial=OF(t,e.width,e.height),this._ggxMaterial=kF(t,e.width,e.height)}}async _compileMaterial(e){let t=new De(new on,e);await this._renderer.compile(t,rh)}_sceneToCubeUV(e,t,n,i,s){let a=FF;a.near=t,a.far=n;let o=[1,1,1,1,-1,1],l=[1,-1,1,-1,1,-1],c=this._renderer,u=c.autoClear;c.getClearColor(nM),c.autoClear=!1,this._backgroundBox===null&&(this._backgroundBox=new De(new Zl,new ji({name:"PMREM.Background",side:ln,depthWrite:!1,depthTest:!1})));let d=this._backgroundBox,h=d.material,p=!1,f=e.background;f?f.isColor&&(h.color.copy(f),e.background=null,p=!0):(h.color.copy(nM),p=!0),c.setRenderTarget(i),c.clear(),p&&c.render(d,a);for(let m=0;m<6;m++){let y=m%3;y===0?(a.up.set(0,o[m],0),a.position.set(s.x,s.y,s.z),a.lookAt(s.x+l[m],s.y,s.z)):y===1?(a.up.set(0,0,o[m]),a.position.set(s.x,s.y,s.z),a.lookAt(s.x,s.y+l[m],s.z)):(a.up.set(0,o[m],0),a.position.set(s.x,s.y,s.z),a.lookAt(s.x,s.y,s.z+l[m]));let x=this._cubeSize;this._setViewport(i,y*x,m>2?x:0,x,x),c.render(e,a)}c.autoClear=u,e.background=f}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===Pr||e.mapping===Ca;i?this._cubemapMaterial===null&&(this._cubemapMaterial=sM(e)):this._equirectMaterial===null&&(this._equirectMaterial=rM(e));let s=i?this._cubemapMaterial:this._equirectMaterial;s.fragmentNode.value=e;let a=this._lodMeshes[0];a.material=s;let o=this._cubeSize;this._setViewport(t,0,0,3*o,2*o),n.setRenderTarget(t),n.render(a,rh)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let i=this._lodMeshes.length;for(let s=1;s<i;s++)this._applyGGXFilter(e,s-1,s);t.autoClear=n}_applyGGXFilter(e,t,n){let i=this._renderer,s=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let l=Em.get(a),c=n/(this._lodMeshes.length-1),u=t/(this._lodMeshes.length-1),d=Math.sqrt(c*c-u*u),h=0+c*1.25,p=d*h,{_lodMax:f}=this,m=this._sizeLods[n],y=3*m*(n>f-Ya?n-f+Ya:0),x=4*(this._cubeSize-m);e.texture.frame=(e.texture.frame||0)+1,l.envMap.value=e.texture,l.roughness.value=p,l.mipInt.value=f-t,this._setViewport(s,y,x,3*m,2*m),i.setRenderTarget(s),i.render(o,rh),s.texture.frame=(s.texture.frame||0)+1,l.envMap.value=s.texture,l.roughness.value=0,l.mipInt.value=f-n,this._setViewport(e,y,x,3*m,2*m),i.setRenderTarget(e),i.render(o,rh)}_blur(e,t,n,i,s){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,i,"latitudinal",s),this._halfBlur(a,e,n,n,i,"longitudinal",s)}_halfBlur(e,t,n,i,s,a,o){let l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&G("blur direction must be either latitudinal or longitudinal!");let u=3,d=this._lodMeshes[i];d.material=c;let h=Em.get(c),p=this._sizeLods[n]-1,f=isFinite(s)?Math.PI/(2*p):2*Math.PI/(2*Yo-1),m=s/f,y=isFinite(s)?1+Math.floor(u*m):Yo;y>Yo&&X(`sigmaRadians, ${s}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${Yo}`);let x=[],b=0;for(let T=0;T<Yo;++T){let R=T/m,D=Math.exp(-R*R/2);x.push(D),T===0?b+=D:T<y&&(b+=2*D)}for(let T=0;T<x.length;T++)x[T]=x[T]/b;e.texture.frame=(e.texture.frame||0)+1,h.envMap.value=e.texture,h.samples.value=y,h.weights.array=x,h.latitudinal.value=a==="latitudinal"?1:0,o&&(h.poleAxis.value=o);let{_lodMax:_}=this;h.dTheta.value=f,h.mipInt.value=_-n;let S=this._sizeLods[i],M=3*S*(i>_-Ya?i-_+Ya:0),w=4*(this._cubeSize-S);this._setViewport(t,M,w,3*S,2*S),l.setRenderTarget(t),l.render(d,rh)}_setViewport(e,t,n,i,s){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-s-n,i,s),e.scissor.set(t,e.height-s-n,i,s)):(e.viewport.set(t,n,i,s),e.scissor.set(t,n,i,s))}};function UF(r){let e=[],t=[],n=[],i=r,s=r-Ya+1+tM.length;for(let a=0;a<s;a++){let o=Math.pow(2,i);e.push(o);let l=1/o;a>r-Ya?l=tM[a-r+Ya-1]:a===0&&(l=0),t.push(l);let c=1/(o-2),u=-c,d=1+c,h=[u,u,d,u,d,d,u,u,d,d,u,d],p=6,f=6,m=3,y=2,x=1,b=new Float32Array(m*f*p),_=new Float32Array(y*f*p),S=new Float32Array(x*f*p);for(let w=0;w<p;w++){let T=w%3*2/3-1,R=w>2?0:-1,D=[T,R,0,T+2/3,R,0,T+2/3,R+1,0,T,R,0,T+2/3,R+1,0,T,R+1,0],L=BF[w];b.set(D,m*f*L),_.set(h,y*f*L);let B=[L,L,L,L,L,L];S.set(B,x*f*L)}let M=new on;M.setAttribute("position",new xn(b,m)),M.setAttribute("uv",new xn(_,y)),M.setAttribute("faceIndex",new xn(S,x)),n.push(new De(M,null)),i>Ya&&i--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function iM(r,e,t){let n={magFilter:St,minFilter:St,generateMipmaps:!1,type:xt,format:bn,colorSpace:Hl,depthBuffer:t},i=new Jt(r,e,n);return i.texture.mapping=Po,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function Vg(r){let e=new We;return e.depthTest=!1,e.depthWrite=!1,e.blending=_s,e.name=`PMREM_${r}`,e}function OF(r,e,t){let n=Tn(new Array(Yo).fill(0)),i=ie(new E(0,1,0)),s=ie(0),a=v(Yo),o=ie(0),l=ie(1),c=Ue(),u=ie(0),d=v(1/e),h=v(1/t),p=v(r),f={n:a,latitudinal:o,weights:n,poleAxis:i,outputDirection:kg,dTheta:s,samples:l,envMap:c,mipInt:u,CUBEUV_TEXEL_WIDTH:d,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:p},m=Vg("blur");return m.fragmentNode=rA({...f,latitudinal:o.equal(1)}),Em.set(m,f),m}function kF(r,e,t){let n=Ue(),i=ie(0),s=ie(0),a=v(1/e),o=v(1/t),l=v(r),c={envMap:n,roughness:i,mipInt:s,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:l},u=Vg("ggx");return u.fragmentNode=aA({...c,N_immutable:kg,GGX_SAMPLES:V(IF)}),Em.set(u,c),u}function sM(r){let e=Vg("cubemap");return e.fragmentNode=Zn(r,kg),e}function rM(r){let e=Vg("equirect");return e.fragmentNode=Ue(r,jS(kg),0),e}var aM=new WeakMap;function VF(r){let e=Math.log2(r)-2,t=1/r;return{texelWidth:1/(3*Math.max(Math.pow(2,e),112)),texelHeight:t,maxMip:e}}function GF(r,e,t){let n=zF(e),i=n.get(r);if((i!==void 0?i.pmremVersion:-1)!==r.pmremVersion){let a=r.image;if(r.isCubeTexture)if(HF(a))i=t.fromCubemap(r,i);else return null;else if(WF(a))i=t.fromEquirectangular(r,i);else return null;if(i.pmremVersion=r.pmremVersion,n.has(r)===!1){let o=()=>{r.removeEventListener("dispose",o);let l=n.get(r);l!==void 0&&(l.dispose(),n.delete(r))};r.addEventListener("dispose",o)}n.set(r,i)}return i.texture}function zF(r){let e=aM.get(r);return e===void 0&&(e=new WeakMap,aM.set(r,e)),e}var p_=class extends ht{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;let i=new mn;i.isRenderTargetTexture=!0,this._texture=Ue(i),this._width=ie(0),this._height=ie(0),this._maxMip=ie(0),this.updateBeforeType=pe.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){let t=VF(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem,n=t?t.pmremVersion:-1,i=this._value;n!==i.pmremVersion&&(i.isPMREMTexture===!0||i.mapping===Po?t=i:t=GF(i,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new h_(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this,e)),t=this._pmrem.isRenderTargetTexture?ym.mul(N(t.x,t.y.negate(),t.z)):ym.mul(t);let n=this.levelNode;return n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),sA(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}};function HF(r){if(r==null)return!1;let e=0,t=6;for(let n=0;n<t;n++)r[n]!==void 0&&e++;return e===t}function WF(r){return r==null?!1:r.height>0}var QS=Me(p_).setParameterLength(1,3),oM=new WeakMap,f_=class extends eo{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){let{material:t}=e,n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){let d=n.isTextureNode?n.value:t[n.property],h=this._getPMREMNodeCache(e.renderer),p=h.get(d);p===void 0&&(p=QS(d),h.set(d,p)),n=p}let s=t.useAnisotropy===!0||t.anisotropy>0?nR:Be,a=n.context(lM(tr,s)).mul(Zf),o=n.context(qF(ro)).mul(Math.PI).mul(Zf),l=du(a),c=du(o);e.context.radiance.addAssign(l),e.context.iblIrradiance.addAssign(c);let u=e.context.lightingModel.clearcoatRadiance;if(u){let d=n.context(lM(lu,qa)).mul(Zf),h=du(d);u.addAssign(h)}}_getPMREMNodeCache(e){let t=oM.get(e);return t===void 0&&(t=new WeakMap,oM.set(e,t)),t}},lM=(r,e)=>{let t=null;return{getUV:()=>(t===null&&(t=Qe.negate().reflect(e),t=pS(r).mix(t,e).normalize(),t=t.transformDirection(Qh)),t),getTextureLevel:()=>r}},qF=r=>({getUV:()=>r,getTextureLevel:()=>v(1)}),$F=new Et,vu=class extends We{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues($F),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new f_(t):null}setupLightingModel(){return new wm}setupSpecular(){let e=Re(N(.04),$e.rgb,zr);Ja.assign(N(.04)),jo.assign(e),Ko.assign(1)}setupVariants(){let e=this.metalnessNode?v(this.metalnessNode):dR;zr.assign(e);let t=this.roughnessNode?v(this.roughnessNode):uR;t=KS({roughness:t}),tr.assign(t),this.setupSpecular(),Xo.assign($e.rgb.mul(e.oneMinus()))}},XF=new Mo,Vh=class extends vu{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(XF),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||this.clearcoatNode!==null}get useIridescence(){return this.iridescence>0||this.iridescenceNode!==null}get useSheen(){return this.sheen>0||this.sheenNode!==null}get useAnisotropy(){return this.anisotropy>0||this.anisotropyNode!==null}get useTransmission(){return this.transmission>0||this.transmissionNode!==null}get useDispersion(){return this.dispersion>0||this.dispersionNode!==null}setupSpecular(){let e=this.iorNode?v(this.iorNode):wR;Mh.assign(e),Ja.assign(gi(hS(Mh.sub(1).div(Mh.add(1))).mul(cR),N(1)).mul(zx)),jo.assign(Re(Ja,$e.rgb,zr)),Ko.assign(Re(zx,1,zr))}setupLightingModel(){return new wm(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){let t=this.clearcoatNode?v(this.clearcoatNode):pR,n=this.clearcoatRoughnessNode?v(this.clearcoatRoughnessNode):fR;sm.assign(t),lu.assign(KS({roughness:n}))}if(this.useSheen){let t=this.sheenNode?N(this.sheenNode):yR,n=this.sheenRoughnessNode?v(this.sheenRoughnessNode):xR;Di.assign(t),za.assign(n)}if(this.useIridescence){let t=this.iridescenceNode?v(this.iridescenceNode):bR,n=this.iridescenceIORNode?v(this.iridescenceIORNode):vR,i=this.iridescenceThicknessNode?v(this.iridescenceThicknessNode):SR;vg.assign(t),rm.assign(n),am.assign(i)}if(this.useAnisotropy){let t=(this.anisotropyNode?$(this.anisotropyNode):_R).toVar();Ga.assign(t.length()),oe(Ga.equal(0),()=>{t.assign($(1,0))}).Else(()=>{t.divAssign($(Ga)),Ga.assign(Ga.saturate())}),om.assign(Ga.pow2().mix(tr.pow2(),1)),Th.assign(Zo[0].mul(t.x).add(Zo[1].mul(t.y))),el.assign(Zo[1].mul(t.x).sub(Zo[0].mul(t.y)))}if(this.useTransmission){let t=this.transmissionNode?v(this.transmissionNode):TR,n=this.thicknessNode?v(this.thicknessNode):MR,i=this.attenuationDistanceNode?v(this.attenuationDistanceNode):ER,s=this.attenuationColorNode?N(this.attenuationColorNode):RR;if(cm.assign(t),Zv.assign(n),Jv.assign(i),Qv.assign(s),this.useDispersion){let a=this.dispersionNode?v(this.dispersionNode):CR;eS.assign(a)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?N(this.clearcoatNormalNode):mR}setup(e){e.context.setupClearcoatNormal=()=>nl(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}};var YF=P(({normal:r,lightDirection:e,builder:t})=>{let n=r.dot(e),i=$(n.mul(.5).add(.5),0);if(t.material.gradientMap){let s=Vr("gradientMap","texture").context({getUV:()=>i});return N(s.r)}else{let s=i.fwidth().mul(.5);return Re(N(.7),N(1),Oi(v(.7).sub(s.x),v(.7).add(s.x),i.x))}}),m_=class extends _u{direct({lightDirection:e,lightColor:t,reflectedLight:n},i){let s=YF({normal:Dg,lightDirection:e,builder:i}).mul(t);n.directDiffuse.addAssign(s.mul(dl({diffuseColor:$e.rgb})))}indirect(e){let{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(dl({diffuseColor:$e}))),i.indirectDiffuse.mulAssign(t)}},jF=new dd,g_=class extends We{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(jF),this.setValues(e)}setupLightingModel(){return new m_}},oA=P(()=>{let r=N(Qe.z,0,Qe.x.negate()).normalize(),e=Qe.cross(r);return $(r.dot(Be),e.dot(Be)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),KF=new fd,y_=class extends We{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(KF),this.setValues(e)}setupVariants(e){let t=oA,n;e.material.matcap?n=Vr("matcap","texture").context({getUV:()=>t}):n=N(Re(.2,.8,t.y)),$e.rgb.mulAssign(n.rgb)}},x_=class extends ht{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){let{rotationNode:t,positionNode:n}=this;if(this.getNodeType(e)==="vec2"){let s=t.cos(),a=t.sin();return bg(s,a,a.negate(),s).mul(n)}else{let s=t,a=ja(J(1,0,0,0),J(0,ws(s.x),Kn(s.x).negate(),0),J(0,Kn(s.x),ws(s.x),0),J(0,0,0,1)),o=ja(J(ws(s.y),0,Kn(s.y),0),J(0,1,0,0),J(Kn(s.y).negate(),0,ws(s.y),0),J(0,0,0,1)),l=ja(J(ws(s.z),Kn(s.z).negate(),0,0),J(Kn(s.z),ws(s.z),0,0),J(0,0,1,0),J(0,0,0,1));return a.mul(o).mul(l).mul(J(n,1)).xyz}}},tp=Me(x_).setParameterLength(2),ZF=new Ku,Rm=class extends We{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(ZF),this.setValues(e)}setupPositionView(e){let{object:t,camera:n}=e,{positionNode:i,rotationNode:s,scaleNode:a,sizeAttenuation:o}=this,l=cr.mul(N(i||0)),c=$(rs[0].xyz.length(),rs[1].xyz.length());a!==null&&(c=c.mul($(a))),n.isPerspectiveCamera&&o===!1&&(c=c.mul(l.z.negate()));let u=Bn.xy;if(t.center&&t.center.isVector2===!0){let p=kD("center","vec2",t);u=u.sub(p.sub(.5))}u=u.mul(c);let d=v(s||gR),h=tp(u,d);return J(l.xy.add(h),l.zw)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}},JF=new Ju,QF=new O,__=class extends Rm{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(JF),this.setValues(e)}setupPositionView(){let{positionNode:e}=this;return cr.mul(N(e||Mt)).xyz}setupVertexSprite(e){let{material:t,camera:n}=e,{rotationNode:i,scaleNode:s,sizeNode:a,sizeAttenuation:o}=this,l=super.setupVertex(e);if(t.isNodeMaterial!==!0)return l;let c=a!==null?$(a):AR;c=c.mul(RS),n.isPerspectiveCamera&&o===!0&&(c=c.mul(eL.div(Ot.z.negate()))),s&&s.isNode&&(c=c.mul($(s)));let u=Bn.xy;if(i&&i.isNode){let d=v(i);u=tp(u,d)}return u=u.mul(c),u=u.div(AS.div(2)),u=u.mul(l.w),l=l.add(J(u,0,0)),l}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}},eL=ie(1).onFrameUpdate(function({renderer:r}){let e=r.getSize(QF);this.value=.5*e.y}),b_=class extends _u{constructor(){super(),this.shadowNode=v(1).toVar("shadowMask")}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){$e.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign($e.rgb)}},tL=new cd,v_=class extends We{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(tL),this.setValues(e)}setupLightingModel(){return new b_}},cz=$r("vec3"),uz=$r("vec3"),dz=$r("vec3");var S_=class{constructor(e,t,n){this.renderer=e,this.nodes=t,this.info=n,this._context=typeof self<"u"?self:null,this._animationLoop=null,this._requestId=null}start(){let e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),this.info.autoReset===!0&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),this._animationLoop!==null&&this._animationLoop(t,n),this.renderer._inspector.finish()};e()}stop(){this._context!==null&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}},dr=class{constructor(){this.weakMaps={}}_getWeakMap(e){let t=e.length,n=this.weakMaps[t];return n===void 0&&(n=new WeakMap,this.weakMaps[t]=n),n}get(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),t===void 0)return;return t.get(e[e.length-1])}set(e,t){let n=this._getWeakMap(e);for(let i=0;i<e.length-1;i++){let s=e[i];n.has(s)===!1&&n.set(s,new WeakMap),n=n.get(s)}return n.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),t===void 0)return!1;return t.delete(e[e.length-1])}},nL=0,cM=new WeakMap;function iL(r){let e=Object.keys(r),t=cM.get(r.constructor);if(t===void 0){t=[];let n=Object.getPrototypeOf(r);for(;n;){let i=Object.getOwnPropertyDescriptors(n);for(let s in i){let a=i[s];a&&typeof a.get=="function"&&t.push(s)}n=Object.getPrototypeOf(n)}cM.set(r.constructor,t)}for(let n=0;n<t.length;n++)e.push(t[n]);return e}var T_=class{constructor(e,t,n,i,s,a,o,l,c,u){this.id=nL++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=i,this.material=s,this.scene=a,this.camera=o,this.lightsNode=l,this.context=c,this.geometry=i.geometry,this.version=s.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=u,this.clippingContextCacheKey=u!==null?u.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this._sourceMaterial=n._currentSourceMaterial,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose),this._sourceMaterial!==null&&this._sourceMaterial.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return this.clippingContext===null||this.clippingContext.cacheKey===this.clippingContextCacheKey?!1:(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return this.getNodeBuilderState().hardwareClipping===!0?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(let t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(this.attributes!==null)return this.attributes;let e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set,s={};for(let a of e){let o;if(a.node&&a.node.attribute?o=a.node.attribute:(o=t.getAttribute(a.name),o!==void 0&&(o.isInterleavedBufferAttribute?s[a.name]=o.data.uuid:s[a.name]=o.id)),o===void 0)continue;n.push(o);let l=o.isInterleavedBufferAttribute?o.data:o;i.add(l)}return this.attributes=n,this.attributesId=s,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){let{object:e,material:t,geometry:n,group:i,drawRange:s}=this,a=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),o=this.getIndex(),l=o!==null,c=1;if(n.isInstancedBufferGeometry===!0?c=n.instanceCount:e.count!==void 0&&(c=Math.max(0,e.count)),c===0)return null;if(a.instanceCount=c,e.isBatchedMesh===!0)return a;let u=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(u=2);let d=s.start*u,h=(s.start+s.count)*u;i!==null&&(d=Math.max(d,i.start*u),h=Math.min(h,(i.start+i.count)*u));let p=n.attributes.position,f=1/0;l?f=o.count:p!=null&&(f=p.count),d=Math.max(d,0),h=Math.min(h,f);let m=h-d;return m<0||m===1/0?null:(a.vertexCount=m,a.firstVertex=d,a)}getGeometryCacheKey(){let{geometry:e}=this,t="";for(let n of Object.keys(e.attributes).sort()){let i=e.attributes[n];t+=n+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(let n of Object.keys(e.morphAttributes).sort()){let i=e.morphAttributes[n];t+="morph-"+n+",";for(let s=0,a=i.length;s<a;s++){let o=i[s];t+=o.id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){let{object:e,material:t,renderer:n}=this,i=t.customProgramCacheKey();for(let s of iL(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(s))continue;let a=t[s],o;if(a!==null){let l=typeof a;l==="number"?s==="side"?o=String(a):o=a!==0?"1":"0":l==="object"?(o="{",a.isTexture&&(o+=a.mapping,n.backend.isWebGPUBackend===!0&&(o+=a.magFilter,o+=a.minFilter,o+=a.wrapS,o+=a.wrapT,o+=a.wrapR)),o+="}"):o=String(a)}else o=String(a);i+=o+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",e._colorsTexture!==null&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1)&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",Mu(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(this.attributes!==null){let e=this.attributesId;for(let t in e){let n=this.geometry.getAttribute(t);if(n===void 0)return!0;let i=n.isInterleavedBufferAttribute?n.data.uuid:n.id;if(e[t]!==i)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return this.material.isShadowPassMaterial!==!0&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=vh(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=vh(e,1)),e=vh(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this._sourceMaterial!==null&&this._sourceMaterial.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}},Ks=[],M_=class{constructor(e,t,n,i,s,a){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=s,this.info=a,this.chainMaps={}}get(e,t,n,i,s,a,o,l){let c=this.getChainMap(l);Ks[0]=e,Ks[1]=t,Ks[2]=a,Ks[3]=s;let u=c.get(Ks);return u===void 0?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,s,a,o,l),c.set(Ks,u)):(u.camera=i,u.updateClipping(o),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,n,i,s,a,o,l)):u.version=t.version)),Ks[0]=null,Ks[1]=null,Ks[2]=null,Ks[3]=null,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new dr)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,i,s,a,o,l,c,u,d){let h=this.getChainMap(d),p=new T_(e,t,n,i,s,a,o,l,c,u);return p.onDispose=()=>{this.pipelines.delete(p),this.bindings.deleteForRender(p),this.nodes.delete(p),h.delete(p.getChainArray())},p}},hr=class{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}},as={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},$a=16,sL=211,rL=212,w_=class extends hr{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){let t=super.delete(e);return t!==null&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){let n=this.get(e);if(n.version===void 0)t===as.VERTEX?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===as.INDEX?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===as.STORAGE?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===as.INDIRECT&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),n.version=this._getBufferAttribute(e).version;else{let i=this._getBufferAttribute(e);(n.version<i.version||i.usage===ko)&&(this.backend.updateAttribute(e),n.version=i.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}};function lA(r){return r.index!==null?r.index.version:r.attributes.position.version}function cA(r){return r.index!==null?r.index.id:r.attributes.position.id}function uM(r){let e=[],t=r.index,n=r.attributes.position;if(t!==null){let s=t.array;for(let a=0,o=s.length;a<o;a+=3){let l=s[a+0],c=s[a+1],u=s[a+2];e.push(l,c,c,u,u,l)}}else{let s=n.array;for(let a=0,o=s.length/3-1;a<o;a+=3){let l=a+0,c=a+1,u=a+2;e.push(l,c,c,u,u,l)}}let i=new(n.count>=65535?Xl:$l)(e,1);return i.version=lA(r),i.__id=cA(r),i}var E_=class extends hr{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){let t=e.geometry;return super.has(t)&&this.get(t).initialized===!0}updateForRender(e){this.has(e)===!1&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){let t=e.geometry,n=this.get(t);n.initialized=!0,this.info.memory.geometries++;let i=()=>{this.info.memory.geometries--;let s=t.index,a=e.getAttributes();s!==null&&this.attributes.delete(s);for(let l of a)this.attributes.delete(l);let o=this.wireframes.get(t);o!==void 0&&this.attributes.delete(o),t.removeEventListener("dispose",i),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",i),this._geometryDisposeListeners.set(t,i)}updateAttributes(e){let t=e.getAttributes();for(let s of t)s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute?this.updateAttribute(s,as.STORAGE):this.updateAttribute(s,as.VERTEX);let n=this.getIndex(e);n!==null&&this.updateAttribute(n,as.INDEX);let i=e.geometry.indirect;i!==null&&this.updateAttribute(i,as.INDIRECT)}updateAttribute(e,t){let n=this.info.render.calls;e.isInterleavedBufferAttribute?this.attributeCall.get(e)===void 0?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){let{geometry:t,material:n}=e,i=t.index;if(n.wireframe===!0){let s=this.wireframes,a=s.get(t);a===void 0?(a=uM(t),s.set(t,a)):(a.version!==lA(t)||a.__id!==cA(t))&&(this.attributes.delete(a),a=uM(t),s.set(t,a)),i=a}return i}dispose(){for(let[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}},R_=class{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={attributes:0,attributesSize:0,geometries:0,indexAttributes:0,indexAttributesSize:0,indirectStorageAttributes:0,indirectStorageAttributesSize:0,programs:0,programsSize:0,readbackBuffers:0,readbackBuffersSize:0,renderTargets:0,storageAttributes:0,storageAttributesSize:0,textures:0,texturesSize:0,uniformBuffers:0,uniformBuffersSize:0,total:0},this.memoryMap=new Map}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):G("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(let e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){let t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){let t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){let n=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:n,type:t}),this.memory[t]++,this.memory.total+=n,this.memory[t+"Size"]+=n}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){let t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){let t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){let{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createUniformBuffer(e){let t=e.byteLength;this.memoryMap.set(e,{size:t,type:"uniformBuffers"}),this.memory.uniformBuffers++,this.memory.total+=t,this.memory.uniformBuffersSize+=t}destroyUniformBuffer(e){let t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory.uniformBuffers--,this.memory.total-=t.size,this.memory.uniformBuffersSize-=t.size)}createProgram(e){let t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){let t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===Dr||e.type===Gt?t=1:e.type===Ir||e.type===qs||e.type===xt?t=2:(e.type===zt||e.type===it||e.type===en)&&(t=4);let n=4;e.format===Xd||e.format===Da||e.format===Ia||e.format===ui||e.format===Zi?n=1:e.format===mi||e.format===Fa?n=2:(e.format===Pa||e.format===Yd)&&(n=3);let i=t*n;e.type===qd||e.type===$d?i=2:(e.type===vs||e.type===pc||e.type===fc)&&(i=4);let s=e.width||1,a=e.height||1,o=e.isCubeTexture?6:e.depth||1,l=s*a*o*i,c=e.mipmaps;if(c&&c.length>0){let u=0;for(let d=0;d<c.length;d++){let h=c[d];if(h.data)u+=h.data.byteLength;else{let p=h.width||Math.max(1,s>>d),f=h.height||Math.max(1,a>>d);u+=p*f*o*i}}l+=u}else e.generateMipmaps&&(l=l*1.333);return Math.round(l)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}},Am=class{constructor(e){this.cacheKey=e,this.usedTimes=0}},A_=class extends Am{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}},C_=class extends Am{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}},aL=0,Rh=class{constructor(e,t,n,i=null,s=null){this.id=aL++,this.code=e,this.stage=t,this.name=n,this.transforms=i,this.attributes=s,this.usedTimes=0}},N_=class extends hr{constructor(e,t,n){super(),this.backend=e,this.nodes=t,this.info=n,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){let{backend:n}=this,i=this.get(e);if(this._needsComputeUpdate(e)){let s=i.pipeline;s&&(s.usedTimes--,s.computeProgram.usedTimes--);let a=this.nodes.getForCompute(e),o=this.programs.compute.get(a.computeShader);o===void 0&&(s&&s.computeProgram.usedTimes===0&&this._releaseProgram(s.computeProgram),o=new Rh(a.computeShader,"compute",e.name,a.transforms,a.nodeAttributes),this.programs.compute.set(a.computeShader,o),n.createProgram(o),this.info.createProgram(o));let l=this._getComputeCacheKey(e,o),c=this.caches.get(l);c===void 0&&(s&&s.usedTimes===0&&this._releasePipeline(s),c=this._getComputePipeline(e,o,l,t)),c.usedTimes++,o.usedTimes++,i.version=e.version,i.pipeline=c}return i.pipeline}getForRender(e,t=null){let{backend:n}=this,i=this.get(e);if(this._needsRenderUpdate(e)){let s=i.pipeline;s&&(s.usedTimes--,s.vertexProgram.usedTimes--,s.fragmentProgram.usedTimes--);let a=e.getNodeBuilderState(),o=e.material?e.material.name:"",l=this.programs.vertex.get(a.vertexShader);l===void 0&&(s&&s.vertexProgram.usedTimes===0&&this._releaseProgram(s.vertexProgram),l=new Rh(a.vertexShader,"vertex",o),this.programs.vertex.set(a.vertexShader,l),n.createProgram(l),this.info.createProgram(l));let c=this.programs.fragment.get(a.fragmentShader);c===void 0&&(s&&s.fragmentProgram.usedTimes===0&&this._releaseProgram(s.fragmentProgram),c=new Rh(a.fragmentShader,"fragment",o),this.programs.fragment.set(a.fragmentShader,c),n.createProgram(c),this.info.createProgram(c));let u=this._getRenderCacheKey(e,l,c),d=this.caches.get(u);d===void 0?(s&&s.usedTimes===0&&this._releasePipeline(s),d=this._getRenderPipeline(e,l,c,u,t)):e.pipeline=d,d.usedTimes++,l.usedTimes++,c.usedTimes++,i.pipeline=d}return i.pipeline}isReady(e){let n=this.get(e).pipeline;if(n===void 0)return!1;let i=this.backend.get(n);return i.pipeline!==void 0&&i.pipeline!==null}delete(e){let t=this.get(e).pipeline;return t&&(t.usedTimes--,t.usedTimes===0&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,t.computeProgram.usedTimes===0&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,t.vertexProgram.usedTimes===0&&this._releaseProgram(t.vertexProgram),t.fragmentProgram.usedTimes===0&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,i){n=n||this._getComputeCacheKey(e,t);let s=this.caches.get(n);return s===void 0&&(s=new C_(n,t),this.caches.set(n,s),this.backend.createComputePipeline(s,i)),s}_getRenderPipeline(e,t,n,i,s){i=i||this._getRenderCacheKey(e,t,n);let a=this.caches.get(i);return a===void 0&&(a=new A_(i,t,n),this.caches.set(i,a),e.pipeline=a,this.backend.createRenderPipeline(e,s)),a}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){let t=e.code,n=e.stage;this.programs[n].delete(t),this.info.destroyProgram(e)}_needsComputeUpdate(e){let t=this.get(e);return t.pipeline===void 0||t.version!==e.version}_needsRenderUpdate(e){return this.get(e).pipeline===void 0||this.backend.needsRenderUpdate(e)}},P_=class extends hr{constructor(e,t,n,i,s,a){super(),this.backend=e,this.textures=n,this.pipelines=s,this.attributes=i,this.nodes=t,this.info=a,this.pipelines.bindings=this}getForRender(e){let t=e.getBindings(),n=this.get(e);return n.initialized!==!0&&(this._createBindings(t),n.initialized=!0),t}getForCompute(e){let t=this.nodes.getForCompute(e).bindings,n=this.get(e);return(n.initialized!==!0||n.bindings!==t)&&(n.bindings!==void 0&&this._destroyBindings(n.bindings),this._createBindings(t),n.initialized=!0,n.bindings=t),t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){let n=this.get(e).bindings||this.nodes.getForCompute(e).bindings;this._destroyBindings(n),this.delete(e)}deleteForRender(e){let t=e.getBindings();this._destroyBindings(t),this.delete(e)}_createBindings(e){for(let t of e){let n=this.get(t);if(n.bindGroup===void 0){for(let i of t.bindings)if(i.isUniformBuffer)this.backend.createUniformBuffer(i),this.info.createUniformBuffer(i);else if(i.isSampledTexture)this.textures.updateTexture(i.texture);else if(i.isSampler)this.textures.updateSampler(i);else if(i.isStorageBuffer){let s=i.attribute,a=s.isIndirectStorageBufferAttribute?as.INDIRECT:as.STORAGE;this.attributes.update(s,a)}this.backend.createBindings(t,e,0),n.bindGroup=t,n.usedTimes=1}else n.usedTimes++}}_destroyBindings(e){for(let t of e){let n=this.get(t);if(n.usedTimes--,n.usedTimes===0){for(let i of t.bindings)i.isUniformBuffer?(this.backend.destroyUniformBuffer(i),this.info.destroyUniformBuffer(i),i.release()):i.isSampler&&(i.isSampledTexture!==!0&&this.backend.destroySampler(i),i.release());this.backend.deleteBindGroupData(t),this.delete(t)}}}_updateBindings(e){for(let t of e)this._update(t,e)}_update(e,t){let{backend:n}=this,i=!1,s=!0,a=0,o=0;for(let l of e.bindings)if(this.nodes.updateGroup(l)!==!1){if(l.isStorageBuffer){let u=l.attribute,d=u.isIndirectStorageBufferAttribute?as.INDIRECT:as.STORAGE,h=n.get(l);this.attributes.update(u,d),h.attribute!==u&&(h.attribute=u,i=!0)}if(l.isUniformBuffer)l.update()&&n.updateBinding(l);else if(l.isSampledTexture){let u=l.update(),d=l.texture,h=this.textures.get(d);if(u&&(this.textures.updateTexture(d),l.generation!==h.generation&&(l.generation=h.generation,i=!0),h.bindGroups.add(e)),n.get(d).externalTexture!==void 0||h.isDefaultTexture?s=!1:(a=a*10+d.id,o+=d.version),d.isStorageTexture===!0&&d.mipmapsAutoUpdate===!0){let f=this.get(d);l.store===!0?f.needsMipmap=!0:this.textures.needsMipmaps(d)&&f.needsMipmap===!0&&(this.backend.generateMipmaps(d),f.needsMipmap=!1)}}else if(l.isSampler&&l.update()){let d=this.textures.updateSampler(l);l.samplerKey!==d&&(l.samplerKey=d,i=!0)}l.isBuffer&&l.updateRanges.length>0&&l.clearUpdateRanges()}i===!0&&this.backend.updateBindings(e,t,s?a:0,o)}},oL=Object.freeze([]);function lL(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?r.z-e.z:r.id-e.id}function dM(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?e.z-r.z:r.id-e.id}function hM(r){return(r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode)&&r.side===Ri&&r.forceSinglePass===!1}var D_=class{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lighting=e,this.lightsNode=e.getNode(t),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0,this._lastOcclusionObject=null}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,i,s,a,o){let l=this.renderItems[this.renderItemsIndex];return l===void 0?(l={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:s,group:a,clippingContext:o},this.renderItems[this.renderItemsIndex]=l):(l.id=e.id,l.object=e,l.geometry=t,l.material=n,l.groupOrder=i,l.renderOrder=e.renderOrder,l.z=s,l.group=a,l.clippingContext=o),this.renderItemsIndex++,l}push(e,t,n,i,s,a,o){let l=this.getNextRenderItem(e,t,n,i,s,a,o);e.occlusionTest===!0&&this._lastOcclusionObject!==e&&(this.occlusionQueryCount++,this._lastOcclusionObject=e),n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(hM(n)&&this.transparentDoublePass.push(l),this.transparent.push(l)):this.opaque.push(l)}unshift(e,t,n,i,s,a,o){let l=this.getNextRenderItem(e,t,n,i,s,a,o);n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(hM(n)&&this.transparentDoublePass.unshift(l),this.transparent.unshift(l)):this.opaque.unshift(l)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t,n){this.opaque.length>1&&this.opaque.sort(e||lL),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||dM),this.transparent.length>1&&this.transparent.sort(t||dM),n&&(this.opaque.reverse(),this.transparentDoublePass.reverse(),this.transparent.reverse())}finish(){this.lightsNode.setLights(this.lighting.enabled?this.lightsArray:oL);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){let n=this.renderItems[e];if(n.id===null)break;n.id=null,n.object=null,n.geometry=null,n.material=null,n.groupOrder=null,n.renderOrder=null,n.z=null,n.group=null,n.clippingContext=null}this._lastOcclusionObject=null}},Wc=[],I_=class{constructor(e){this.lighting=e,this.lists=new dr}get(e,t){let n=this.lists;Wc[0]=e,Wc[1]=t;let i=n.get(Wc);return i===void 0&&(i=new D_(this.lighting,e,t),n.set(Wc,i)),Wc[0]=null,Wc[1]=null,i}dispose(){this.lists=new dr}},cL=0,F_=class{constructor(){this.id=cL++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new Ge,this.scissor=!1,this.scissorValue=new Ge,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.isRenderContext=!0}getCacheKey(){return uA(this)}};function uA(r){let{textures:e,activeCubeFace:t,activeMipmapLevel:n}=r,i=[t,n];for(let s of e)i.push(s.id);return Jh(i)}var L_=class{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,n=0){let i;if(e===null)i="default";else{let l=e.texture.format,c=e.texture.type;i=`${e.textures.length}:${l}:${c}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}let s=t!==null?t.id:"default",a=i+"-"+s+"-"+n,o=this._renderContexts[a];return o===void 0&&(o=new F_,o.mrt=t,this._renderContexts[a]=o),e!==null&&(o.sampleCount=e.samples===0?1:e.samples),o.clearDepthValue=this.renderer.getClearDepth(),o.clearStencilValue=this.renderer.getClearStencil(),o}dispose(){this._renderContexts={}}},uL=new E,B_=class extends hr{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n,this._htmlTextures=new Set}updateRenderTarget(e,t=0){let n=this.get(e),i=e.samples===0?1:e.samples,s=n.depthTextureMips||(n.depthTextureMips={}),a=e.textures,o=this.getSize(a[0]),l=o.width>>t,c=o.height>>t,u=e.depthTexture||s[t],d=e.depthBuffer===!0||e.stencilBuffer===!0,h=!1,p=u!==void 0&&u.image!==void 0&&u.image.depth>1,f=o.depth>1&&(e.useArrayDepthTexture||e.multiview||p);u===void 0&&d&&(u=new Pn,u.format=e.stencilBuffer?Zi:ui,u.type=e.stencilBuffer?vs:it,u.image.width=l,u.image.height=c,u.image.depth=o.depth,u.renderTarget=e,s[t]=u),u&&(u.isArrayTexture=f),(n.width!==o.width||o.height!==n.height)&&(h=!0,u&&(u.needsUpdate=!0,u.image.width=l,u.image.height=c,u.image.depth=f?o.depth:1)),n.width=o.width,n.height=o.height,n.textures=a,n.depthTexture=u||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==i&&(h=!0,u&&(u.needsUpdate=!0),n.sampleCount=i);let m={sampleCount:i};if(e.isXRRenderTarget!==!0){for(let y=0;y<a.length;y++){let x=a[y];h&&(x.needsUpdate=!0),this.updateTexture(x,m)}u&&this.updateTexture(u,m)}n.initialized!==!0&&(n.initialized=!0,this.info.memory.renderTargets++,n.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",n.onDispose))}updateTexture(e,t={}){let n=this.get(e);if(n.initialized===!0&&n.version===e.version)return;let i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,s=this.backend;if(i&&n.initialized===!0&&s.destroyTexture(e),e.isFramebufferTexture){let c=this.renderer.getRenderTarget();c?e.type=c.texture.type:e.type=Gt}if(e.isHTMLTexture&&e.image){let c=this.renderer.domElement;if("requestPaint"in c){if(c.hasAttribute("layoutsubtree")||c.setAttribute("layoutsubtree","true"),e.image.parentNode!==c&&c.appendChild(e.image),this._htmlTextures.size===0){let u=this._htmlTextures;c.onpaint=d=>{let h=d&&d.changedElements;for(let p of u)(!h||h.includes(p.image))&&(p.needsUpdate=!0)}}this._htmlTextures.add(e)}}let{width:a,height:o,depth:l}=this.getSize(e);if(t.width=a,t.height=o,t.depth=l,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,a,o):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||e.isStorageTexture===!0||e.isExternalTexture===!0)s.createTexture(e,t),n.generation=e.version;else if(e.version>0){let c=e.image;if(c===void 0)X("Renderer: Texture marked for update but image is undefined.");else if(c.complete===!1)X("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){let d=[];for(let h of e.images)d.push(h);t.images=d}else t.image=c;(n.isDefaultTexture===void 0||n.isDefaultTexture===!0)&&(s.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),e.source.dataReady===!0&&s.updateTexture(e,t);let u=e.isStorageTexture===!0&&e.mipmapsAutoUpdate===!1;t.needsMipmaps&&e.mipmaps.length===0&&!u&&s.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else s.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;n.initialized!==!0&&(n.initialized=!0,n.generation=e.version,n.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&Fe.enabled===!0&&Fe.getTransfer(e.colorSpace)!==be&&X("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),n.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",n.onDispose)),n.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=uL){let n=e.images?e.images[0]:e.image;return n?(n.image!==void 0&&(n=n.image),e.isHTMLTexture?(t.width=n.offsetWidth||1,t.height=n.offsetHeight||1,t.depth=1):typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement?(t.width=n.videoWidth||1,t.height=n.videoHeight||1,t.depth=1):typeof VideoFrame<"u"&&n instanceof VideoFrame?(t.width=n.displayWidth||1,t.height=n.displayHeight||1,t.depth=1):(t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let i;return e.mipmaps.length>0?i=e.mipmaps.length:e.isCompressedTexture===!0?i=1:i=Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return e.generateMipmaps===!0||e.mipmaps.length>0}_destroyRenderTarget(e){if(this.has(e)===!0){let t=this.get(e),n=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let s=0;s<n.length;s++)this._destroyTexture(n[s]);i&&this._destroyTexture(i),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(this.has(e)===!0){let t=this.get(e);e.removeEventListener("dispose",t.onDispose);let n=t.isDefaultTexture;if(this.backend.destroyTexture(e,n),t.bindGroups)for(let i of t.bindGroups){let s=this.backend.get(i);s.groups=void 0,s.versions=void 0;for(let a of i.bindings)a.isSampler&&a.texture===e&&(a.isSampledTexture!==!0&&this.backend.destroySampler(a),a.reset(),a.release())}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}},Gh=class extends me{constructor(e,t,n,i=1){super(e,t,n),this.a=i}set(e,t,n,i=1){return this.a=i,super.set(e,t,n)}copy(e){return e.a!==void 0&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}},Cm=class extends Ih{static get type(){return"OverrideContextNode"}constructor(e,t=null){super(t,{overrideNodes:e}),this.isOverrideContextNode=!0}getFlowContextData(){let e=[];this.traverse(i=>{i.isOverrideContextNode===!0&&e.push(i.value.overrideNodes)});let t=new Map(e.flatMap(i=>Array.from(i.entries()))),n=super.getFlowContextData();return n.overrideNodes=t,n}};function dA(r,e=null,t=null){if(e&&e.isNode){let n=e;e=()=>n}return new Cm(new Map([[r,e]]),t)}F("overrideNode",(r,e,t)=>dA(e,t,r));function hA(r,e=null){let t=new Map;for(let[n,i]of r){let s=i!==null?typeof i=="function"?i:()=>i:null;t.set(n,s)}return new Cm(t,e)}F("overrideNodes",(r,e)=>hA(e,r));var Nm=class extends Oe{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){let n=this.getNodeType(e),i=e.getStructTypeNode(n),s;return i!==null?s=i.getMemberType(e,t):(G(`TSL: Member "${t}" not found in struct "${n}".`,new Dt),s="float"),s}getHash(){return String(this.id)}generate(){return this.name}},dL=(r,e)=>new Nm(r,e),U_=class extends le{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this._nodeDataLibrary=new Map,this.isStackNode=!0}getElementType(e){return this.outputNode?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=-1){if(e.isNode!==!0)return G("TSL: Invalid node added to stack.",new Dt),this;if(t===-1)if(this._currentNode){let n=this._nodeDataLibrary.get(this._currentNode);n===void 0&&(n={delta:0},this._nodeDataLibrary.set(this._currentNode,n)),n.delta++,t=this.nodes.indexOf(this._currentNode)+n.delta}else t=this.nodes.length;return this.nodes.splice(t,0,e),this}addToStackBefore(e){let t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){let n=new au(t);return this._currentCond=On(e,n),this.addToStack(this._currentCond)}ElseIf(e,t){let n=new au(t),i=On(e,n);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new au(e),this}Switch(e){return this._expressionNode=ne(e),this}Case(...e){let t=[];if(e.length>=2)for(let o=0;o<e.length-1;o++)t.push(this._expressionNode.equal(ne(e[o])));else G("TSL: Invalid parameter length. Case() requires at least two parameters.",new Dt);let n=e[e.length-1],i=new au(n),s=t[0];for(let o=1;o<t.length;o++)s=s.or(t[o]);let a=On(s,i);return this._currentCond===null?(this._currentCond=a,this.addToStack(this._currentCond)):(this._currentCond.elseNode=a,this._currentCond=a,this)}Default(e){return this.Else(e),this}setup(e){let t=e.getNodeProperties(this),n=0;for(let i of this.getChildren())i.isVarNode&&i.isIntent(e)&&i.isAssign(e)!==!0||(t["node"+n++]=i);return t.outputNode||null}build(e,...t){let n=qv(),i=e.buildStage;Ph(this),e.setActiveStack(this);for(let a=0;a<this.nodes.length;a++){let o=this.nodes[a],l=this._currentNode;if(this._currentNode=o,!(o.isVarNode&&o.isIntent(e)&&o.isAssign(e)!==!0)){if(i==="setup")o.build(e);else if(i==="analyze")o.build(e,this);else if(i==="generate"){let c=e.getDataFromNode(o,"any").stages,u=c&&c[e.shaderStage];if(o.isVarNode&&u&&u.length===1&&u[0]&&u[0].isStackNode)continue;o.build(e,"void")}this._currentNode=l}}let s;if(this.outputNode){let a=this.outputNode.build(e,...t);(e.buildStage!=="generate"||this.outputNode.getNodeType(e)!=="void")&&(s=a)}else s=super.build(e,...t);return Ph(n),e.removeActiveStack(this),s}},em=Me(U_).setParameterLength(0,1);function hL(r){return Object.entries(r).map(([e,t])=>typeof t=="string"?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})}var O_=class extends le{static get type(){return"StructTypeNode"}constructor(e,t=null){super("struct"),this.membersLayout=hL(e),this.name=t,this.isStructTypeNode=!0}getLength(){let e=1,t=0;for(let n of this.membersLayout){let i=n.type,s=rD(i),a=aD(i);e=Math.max(e,a);let l=t%e%a;l!==0&&(t+=a-l),t+=s}return Math.ceil(t/e)*e}getMemberType(e,t){let n=this.membersLayout.find(i=>i.name===t);return n?n.type:"void"}generateNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}},k_=class extends le{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}generateNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}_getChildren(){let e=super._getChildren(),t=e.find(n=>n.childNode===this.structTypeNode);return e.splice(e.indexOf(t),1),e.push(t),e}generate(e){let t=e.getVarFromNode(this),n=t.type,i=e.getPropertyName(t);return e.addLineFlowCode(`${i} = ${e.generateStruct(n,this.structTypeNode.membersLayout,this.values)}`,this),t.name}},pL=(r,e=null)=>{let t=new O_(r,e);return Wv((...i)=>{let s=null;if(i.length>0)if(i[0].isNode){s={};let a=Object.keys(r);for(let o=0;o<i.length;o++)s[a[o]]=i[o]}else s=i[0];return new k_(t,s)},t)},Pm=class extends le{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}generateNodeType(){return"OutputType"}generate(e){let t=e.getDataFromNode(this);if(t.membersLayout===void 0){let a=this.members,o=[];for(let l=0;l<a.length;l++){let c="m"+l,u=a[l].getNodeType(e);o.push({name:c,type:u,index:l})}t.membersLayout=o,t.structType=e.getOutputStructTypeFromNode(this,t.membersLayout)}let n=e.getOutputStructName(),i=this.members,s=n!==""?n+".":"";for(let a=0;a<i.length;a++){let o=i[a].build(e,t.membersLayout[a].type);e.addLineFlowCode(`${s}m${a} = ${o}`,this)}return n}},fL=Me(Pm),Dm=class{constructor(e=li){this.blending=e,this.blendSrc=fo,this.blendDst=mo,this.blendEquation=ci,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.premultiplyAlpha=!1}copy(e){return this.blending=e.blending,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.premultiplyAlpha=e.premultiplyAlpha,this}clone(){return new this.constructor().copy(this)}},mL=new Dm(_s),gL=new Dm(Ld);function pA(r,e){for(let t=0;t<r.length;t++)if(r[t].name===e)return t;return-1}var V_=class extends Pm{static get type(){return"MRTNode"}constructor(e){super(),this.outputNodes=e,this.blendModes={output:gL},this.isMRTNode=!0}setBlendMode(e,t){return this.blendModes[e]=t,this}getBlendMode(e){return this.blendModes[e]||mL}has(e){return this.outputNodes[e]!==void 0}get(e){return this.outputNodes[e]}merge(e){let t={...this.outputNodes,...e.outputNodes},n={...this.blendModes,...e.blendModes},i=fA(t);return i.blendings=n,i}setup(e){let t=this.outputNodes,n=e.renderer.getRenderTarget(),i=[],s=n.textures;for(let a in t){let o=pA(s,a);if(o===-1)continue;let l=e.getOutputType(o);i[o]=t[a].convert(l)}return this.members=i,super.setup(e)}},fA=Me(V_),hl=class extends ht{static get type(){return"BitcastNode"}constructor(e,t,n=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=n,this.isBitcastNode=!0}generateNodeType(e){if(this.inputType!==null){let t=this.valueNode.getNodeType(e),n=e.getTypeLength(t);return e.getTypeFromLength(n,this.conversionType)}return this.conversionType}generate(e){let t=this.getNodeType(e),n="";if(this.inputType!==null){let i=this.valueNode.getNodeType(e);n=e.getTypeLength(i)===1?this.inputType:e.changeComponentType(i,this.inputType)}else n=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,n)}( ${this.valueNode.build(e,n)} )`}},mA=H(hl).setParameterLength(2),yL=r=>new hl(r,"int","float"),gA=r=>new hl(r,"uint","float"),xL=r=>new hl(r,"float","int"),_L=r=>new hl(r,"float","uint"),wf={},Ds=class r extends I{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,n){n==="int"?t.assign(mA(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return V;case"int":return C;case"uvec2":return $v;case"uvec3":return ml;case"uvec4":return Kv;case"ivec2":return Rt;case"ivec3":return Xv;case"ivec4":return jv}}_createTrailingZerosBaseLayout(e,t){let n=this._returnDataNode(t);return P(([s])=>{let a=V(0);this._resolveElementType(s,a,t);let o=v(a.bitAnd(oS(a))),c=gA(o).shiftRight(23).sub(127);return n(c)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){let n=this._returnDataNode(t);return P(([s])=>{oe(s.equal(V(0)),()=>V(32));let a=V(0),o=V(0);return this._resolveElementType(s,a,t),oe(a.shiftRight(16).equal(0),()=>{o.addAssign(16),a.shiftLeftAssign(16)}),oe(a.shiftRight(24).equal(0),()=>{o.addAssign(8),a.shiftLeftAssign(8)}),oe(a.shiftRight(28).equal(0),()=>{o.addAssign(4),a.shiftLeftAssign(4)}),oe(a.shiftRight(30).equal(0),()=>{o.addAssign(2),a.shiftLeftAssign(2)}),oe(a.shiftRight(31).equal(0),()=>{o.addAssign(1)}),n(o)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){let n=this._returnDataNode(t);return P(([s])=>{let a=V(0);this._resolveElementType(s,a,t),a.assign(a.sub(a.shiftRight(V(1)).bitAnd(V(1431655765)))),a.assign(a.bitAnd(V(858993459)).add(a.shiftRight(V(2)).bitAnd(V(858993459))));let o=a.add(a.shiftRight(V(4))).bitAnd(V(252645135)).mul(V(16843009)).shiftRight(V(24));return n(o)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,n,i){let s=this._returnDataNode(t);return P(([o])=>{if(n===1)return s(i(o));{let l=s(0),c=["x","y","z","w"];for(let u=0;u<n;u++){let d=c[u];l[d].assign(i(o[d]))}return l}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}setup(e){let{method:t,aNode:n}=this,{renderer:i}=e;if(i.backend.isWebGPUBackend)return super.setup(e);let s=this.getInputType(e),a=e.getElementType(s),o=e.getTypeLength(s),l=`${t}_base_${a}`,c=`${t}_${s}`,u=wf[l];if(u===void 0){switch(t){case r.COUNT_LEADING_ZEROS:{u=this._createLeadingZerosBaseLayout(l,a);break}case r.COUNT_TRAILING_ZEROS:{u=this._createTrailingZerosBaseLayout(l,a);break}case r.COUNT_ONE_BITS:{u=this._createOneBitsBaseLayout(l,a);break}}wf[l]=u}let d=wf[c];return d===void 0&&(d=this._createMainLayout(c,s,o,u),wf[c]=d),P(()=>d(n))()}};Ds.COUNT_TRAILING_ZEROS="countTrailingZeros";Ds.COUNT_LEADING_ZEROS="countLeadingZeros";Ds.COUNT_ONE_BITS="countOneBits";var bL=H(Ds,Ds.COUNT_TRAILING_ZEROS).setParameterLength(1),vL=H(Ds,Ds.COUNT_LEADING_ZEROS).setParameterLength(1),SL=H(Ds,Ds.COUNT_ONE_BITS).setParameterLength(1),TL=P(([r])=>{let e=r.toUint().mul(747796405).add(2891336453),t=e.shiftRight(e.shiftRight(28).add(4)).bitXor(e).mul(277803737);return t.shiftRight(22).bitXor(t).toFloat().mul(1/2**32)}),G_=(r,e)=>ss(xe(4,r.mul(Ie(1,r))),e),ML=(r,e)=>r.lessThan(.5)?G_(r.mul(2),e).div(2):Ie(1,G_(xe(Ie(1,r),2),e).div(2)),wL=(r,e,t)=>ss(Ui(ss(r,e),Wt(ss(r,e),ss(Ie(1,r),t))),1/e),EL=(r,e)=>Kn(hm.mul(e.mul(r).sub(1))).div(hm.mul(e.mul(r).sub(1))),zh=class extends ht{static get type(){return"PackFloatNode"}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.isPackFloatNode=!0}generateNodeType(){return"uint"}generate(e){let t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding)}(${this.vectorNode.build(e,t)})`}},RL=H(zh,"snorm").setParameterLength(1),AL=H(zh,"unorm").setParameterLength(1),CL=H(zh,"float16").setParameterLength(1),Hh=class extends ht{static get type(){return"UnpackFloatNode"}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.isUnpackFloatNode=!0}generateNodeType(){return"vec2"}generate(e){let t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding)}(${this.uintNode.build(e,t)})`}},NL=H(Hh,"snorm").setParameterLength(1),PL=H(Hh,"unorm").setParameterLength(1),DL=H(Hh,"float16").setParameterLength(1),kr=P(([r])=>r.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),IL=P(([r])=>N(kr(r.z.add(kr(r.y.mul(1)))),kr(r.z.add(kr(r.x.mul(1)))),kr(r.y.add(kr(r.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),FL=P(([r,e,t])=>{let n=N(r).toVar(),i=v(1.4).toVar(),s=v(0).toVar(),a=N(n).toVar();return Xe({start:v(0),end:v(3),type:"float",condition:"<="},()=>{let o=N(IL(a.mul(2))).toVar();n.addAssign(o.add(t.mul(v(.1).mul(e)))),a.mulAssign(1.8),i.mulAssign(1.5),n.mulAssign(1.2);let l=v(kr(n.z.add(kr(n.x.add(kr(n.y)))))).toVar();s.addAssign(l.div(i)),a.addAssign(.14)}),s}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]}),z_=class extends le{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}generateNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){let t=this.parametersNodes,n=this._candidateFn;if(n===null){let i=null,s=-1;for(let a of this.functionNodes){let l=a.shaderNode.layout;if(l===null)throw new Error("THREE.FunctionOverloadingNode: FunctionNode must be a layout.");let c=l.inputs;if(t.length===c.length){let u=0;for(let d=0;d<t.length;d++){let h=t[d],p=c[d];h.getNodeType(e)===p.type&&u++}u>s&&(i=a,s=u)}}this._candidateFn=n=i}return n}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}},LL=Me(z_),En=r=>(...e)=>LL(r,...e),Ru=ie(0).setGroup(de).onRenderUpdate(r=>r.time),BL=ie(0).setGroup(de).onRenderUpdate(r=>r.deltaTime),yA=ie(0,"uint").setGroup(de).onRenderUpdate(r=>r.frameId),UL=(r=Ru)=>r.add(.75).mul(Math.PI*2).sin().mul(.5).add(.5),OL=(r=Ru)=>r.fract().round(),kL=(r=Ru)=>r.add(.5).fract().mul(2).sub(1).abs(),VL=(r=Ru)=>r.fract();function GL(r,e=null){return Xr(e,{getUV:typeof r=="function"?r:()=>r})}var zL=P(([r,e,t=$(.5)])=>tp(r.sub(t),e).add(t)),HL=P(([r,e,t=$(.5)])=>{let n=r.sub(t),i=n.dot(n),a=i.mul(i).mul(e);return r.add(n.mul(a))}),WL=P(({position:r=null,horizontal:e=!0,vertical:t=!1})=>{let n;r!==null?(n=rs.toVar(),n[3][0]=r.x,n[3][1]=r.y,n[3][2]=r.z):n=rs;let i=so.mul(n);return fu(e)&&(i[0][0]=rs[0].length(),i[0][1]=0,i[0][2]=0),fu(t)&&(i[1][0]=0,i[1][1]=rs[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,Jn.mul(i).mul(Mt)}),qL=P(([r=null])=>{let e=vm();return vm($S(r)).sub(e).lessThan(0).select(Rs,r)}),$L=P(([r,e=Ye(),t=v(0)])=>{let n=r.x,i=r.y,s=t.mod(n.mul(i)).floor(),a=s.mod(n),o=i.sub(s.add(1).div(n).ceil()),l=r.reciprocal(),c=$(a,o);return e.add(c).mul(l)}),xA=P(([r,e=null,t=null,n=v(1),i=Mt,s=Gn])=>{let a=s.abs().normalize();a=a.div(a.dot(N(1)));let o=i.yz.mul(n),l=i.zx.mul(n),c=i.xy.mul(n),u=r.value,d=e!==null?e.value:u,h=t!==null?t.value:u,p=Ue(u,o).mul(a.x),f=Ue(d,l).mul(a.y),m=Ue(h,c).mul(a.z);return Wt(p,f,m)}),XL=(...r)=>xA(...r),qc=new ri,Go=new E,$c=new E,Ly=new E,ah=new Ne,Ef=new E(0,0,-1),Zs=new Ge,oh=new E,Rf=new E,lh=new Ge,Af=new O,Im=new Jt,YL=Rs.flipX();Im.depthTexture=new Pn(1,1);var Cf=!1,H_=class r extends cs{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||Im.texture,YL),this._reflectorBaseNode=e.reflector||new W_(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(this._depthNode===null){if(this._reflectorBaseNode.depth!==!0)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=new r({defaultTexture:Im.depthTexture,reflector:this._reflectorBaseNode})}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){let e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}},W_=class extends le{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();let{target:n=new Qt,resolutionScale:i=1,generateMipmaps:s=!1,bounces:a=!0,depth:o=!1,samples:l=0}=t;this.textureNode=e,this.target=n,this.resolutionScale=i,t.resolution!==void 0&&(Ce('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=s,this.bounces=a,this.depth=o,this.samples=l,this.updateBeforeType=a?pe.RENDER:pe.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){let n=this.resolutionScale;t.getDrawingBufferSize(Af),e.setSize(Math.round(Af.width*n),Math.round(Af.height*n))}setup(e){return this._updateResolution(Im,e.renderer),super.setup(e)}dispose(){super.dispose();for(let e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return t===void 0&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return t===void 0&&(t=new Jt(0,0,{type:xt,samples:this.samples}),this.generateMipmaps===!0&&(t.texture.minFilter=q0,t.texture.generateMipmaps=!0),this.depth===!0&&(t.depthTexture=new Pn),this.renderTargets.set(e,t)),t}updateBefore(e){if(this.bounces===!1&&Cf)return!1;Cf=!0;let{scene:t,camera:n,renderer:i,material:s}=e,{target:a}=this,o=this.getVirtualCamera(n),l=this.getRenderTarget(o);i.getDrawingBufferSize(Af),this._updateResolution(l,i),$c.setFromMatrixPosition(a.matrixWorld),Ly.setFromMatrixPosition(n.matrixWorld),ah.extractRotation(a.matrixWorld),Go.set(0,0,1),Go.applyMatrix4(ah),oh.subVectors($c,Ly);let c=oh.dot(Go)>0,u=!1;if(c===!0&&this.forceUpdate===!1){if(this.hasOutput===!1){Cf=!1;return}u=!0}oh.reflect(Go).negate(),oh.add($c),ah.extractRotation(n.matrixWorld),Ef.set(0,0,-1),Ef.applyMatrix4(ah),Ef.add(Ly),Rf.subVectors($c,Ef),Rf.reflect(Go).negate(),Rf.add($c),o.coordinateSystem=n.coordinateSystem,o.position.copy(oh),o.up.set(0,1,0),o.up.applyMatrix4(ah),o.up.reflect(Go),o.lookAt(Rf),o.near=n.near,o.far=n.far,o.updateMatrixWorld(),o.projectionMatrix.copy(n.projectionMatrix),qc.setFromNormalAndCoplanarPoint(Go,$c),qc.applyMatrix4(o.matrixWorldInverse),Zs.set(qc.normal.x,qc.normal.y,qc.normal.z,qc.constant);let d=o.projectionMatrix;lh.x=(Math.sign(Zs.x)+d.elements[8])/d.elements[0],lh.y=(Math.sign(Zs.y)+d.elements[9])/d.elements[5],lh.z=-1,lh.w=(1+d.elements[10])/d.elements[14],Zs.multiplyScalar(1/Zs.dot(lh));let h=0;d.elements[2]=Zs.x,d.elements[6]=Zs.y,d.elements[10]=i.coordinateSystem===di?Zs.z-h:Zs.z+1-h,d.elements[14]=Zs.w,this.textureNode.value=l.texture,this.depth===!0&&(this.textureNode.getDepthNode().value=l.depthTexture),s.visible=!1;let p=i.getRenderTarget(),f=i.getMRT(),m=i.autoClear;i.setMRT(null),i.setRenderTarget(l),i.autoClear=!0;let y=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",u?(i.clear(),this.hasOutput=!1):(i.render(t,o),this.hasOutput=!0),t.name=y,i.setMRT(f),i.setRenderTarget(p),i.autoClear=m,s.visible=!0,Cf=!1,this.forceUpdate=!1}get resolution(){return Ce('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){Ce('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}},jL=r=>new H_(r),By=new Ao(-1,1,1,-1,0,1),q_=class extends on{constructor(e=!1){super();let t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Ve([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Ve(t,2))}},KL=new q_,Is=class extends De{constructor(e=null){super(KL,e),this.camera=By,this.isQuadMesh=!0}async renderAsync(e){Ce('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,By)}render(e){e.render(this,By)}},ZL=new O,$_=class extends cs{static get type(){return"RTTNode"}constructor(e,t=null,n=null,i={type:xt}){let s=new Jt(t,n,i);super(s.texture,Ye()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=n,this.renderTarget=s,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._resolutionScale=1,this._rttNode=null,this._quadMesh=new Is(new We),this.updateBeforeType=pe.RENDER}get autoResize(){return this.width===null}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){let n=Math.floor(e*this._resolutionScale),i=Math.floor(t*this._resolutionScale);this.renderTarget.setSize(n,i),this.textureNeedsUpdate=!0}setResolutionScale(e){return this._resolutionScale=e,this.autoResize===!1&&this.setSize(this.width,this.height),this}getResolutionScale(){return this._resolutionScale}updateBefore({renderer:e}){if(this.textureNeedsUpdate===!1&&this.autoUpdate===!1)return;this.textureNeedsUpdate=!1;let t=e.getRenderTarget();if(this.autoResize===!0){let i=e.getDrawingBufferSize(ZL),s=Math.floor(i.width*this._resolutionScale),a=Math.floor(i.height*this._resolutionScale);(s!==this.renderTarget.width||a!==this.renderTarget.height)&&(this.renderTarget.setSize(s,a),this.textureNeedsUpdate=!0)}let n="RTT";this.node.name&&(n=this.node.name+" [ "+n+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=n,e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(t)}clone(){let e=new cs(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}},_A=(r,...e)=>new $_(ne(r),...e),JL=(r,...e)=>r.isSampleNode||r.isTextureNode?r:r.isPassNode?r.getTextureNode():_A(r,...e),ru=P(([r,e,t],n)=>{let i;n.renderer.coordinateSystem===di?(r=$(r.x,r.y.oneMinus()).mul(2).sub(1),i=J(N(r,e),1)):i=J(N(r.x,r.y.oneMinus(),e).mul(2).sub(1),1);let s=J(t.mul(i));return s.xyz.div(s.w)}),QL=P(([r,e])=>{let t=e.mul(J(r,1)),n=t.xy.div(t.w).mul(.5).add(.5).toVar();return $(n.x,n.y.oneMinus())}),eB=P(([r,e,t])=>{let n=ll(Ut(e)),i=Rt(r.mul(n)).toVar(),s=Ut(e,i).toVar(),a=Ut(e,i.sub(Rt(2,0))).toVar(),o=Ut(e,i.sub(Rt(1,0))).toVar(),l=Ut(e,i.add(Rt(1,0))).toVar(),c=Ut(e,i.add(Rt(2,0))).toVar(),u=Ut(e,i.add(Rt(0,2))).toVar(),d=Ut(e,i.add(Rt(0,1))).toVar(),h=Ut(e,i.sub(Rt(0,1))).toVar(),p=Ut(e,i.sub(Rt(0,2))).toVar(),f=rt(Ie(v(2).mul(o).sub(a),s)).toVar(),m=rt(Ie(v(2).mul(l).sub(c),s)).toVar(),y=rt(Ie(v(2).mul(d).sub(u),s)).toVar(),x=rt(Ie(v(2).mul(h).sub(p),s)).toVar(),b=ru(r,s,t).toVar(),_=f.lessThan(m).select(b.sub(ru(r.sub($(v(1).div(n.x),0)),o,t)),b.negate().add(ru(r.add($(v(1).div(n.x),0)),l,t))),S=y.lessThan(x).select(b.sub(ru(r.add($(0,v(1).div(n.y))),d,t)),b.negate().add(ru(r.sub($(0,v(1).div(n.y))),h,t)));return kn(Wr(_,S))}),eT=P(([r])=>Cs(v(52.9829189).mul(Cs(ls(r,$(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),Es=P(([r,e,t])=>{let n=v(2.399963229728653),i=Qn(v(r).add(.5).div(v(e))),s=v(r).mul(n).add(t);return $(ws(s),Kn(s)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]}),X_=class extends le{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(Ye())}sample(e){return this.callback(e)}},tB=(r,e=null)=>new X_(r,ne(e)),Y_=class extends Hs{constructor(e,t,n=Float32Array){let i=ArrayBuffer.isView(e)?e:new n(e*t);super(i,t),this.isStorageInstancedBufferAttribute=!0}},j_=class extends xn{constructor(e,t,n=Float32Array){let i=ArrayBuffer.isView(e)?e:new n(e*t);super(i,t),this.isStorageBufferAttribute=!0}},nB=(r,e="float")=>{let t,n;e.isStructTypeNode===!0?(t=e.getLength(),n=tm("float")):(t=YM(e),n=tm(e));let i=new j_(r,t,n);return Ka(i,e,r)},iB=(r,e="float")=>{let t,n;e.isStructTypeNode===!0?(t=e.getLength(),n=tm("float")):(t=YM(e),n=tm(e));let i=new Y_(r,t,n);return Ka(i,e,i.count)},K_=class extends le{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}},sB=Y(K_),Uy=new Ne,bA=ie(0).setGroup(de).onRenderUpdate(({scene:r})=>r.backgroundBlurriness),Z_=ie(1).setGroup(de).onRenderUpdate(({scene:r})=>r.backgroundIntensity),vA=ie(new Ne).setGroup(de).onRenderUpdate(({scene:r})=>{let e=r.background;return e!==null&&e.isTexture&&e.mapping!==Gd||r.backgroundNode&&r.backgroundNode.isNode?Uy.makeRotationFromEuler(r.backgroundRotation).transpose():Uy.identity(),Uy}),Fm=class extends cs{static get type(){return"StorageTextureNode"}constructor(e,t,n=null){super(e,t),this.storeNode=n,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=Mn.WRITE_ONLY}getInputType(){return"storageTexture"}getTransformedUV(e){return e}setup(e){super.setup(e);let t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){return this.storeNode!==null?(this.generateStore(e),""):super.generate(e,t)}generateSnippet(e,t,n,i,s,a,o,l,c){let u=this.value;return e.generateStorageTextureLoad(u,t,n,i,a,c)}toReadWrite(){return this.setAccess(Mn.READ_WRITE)}toReadOnly(){return this.setAccess(Mn.READ_ONLY)}toWriteOnly(){return this.setAccess(Mn.WRITE_ONLY)}store(e,t){let n=this.clone();return n.referenceNode=this.getBase(),n.uvNode=e,n.storeNode=t,t!==null&&n.toStack(),n}generateStore(e){let t=e.getNodeProperties(this),{uvNode:n,storeNode:i,depthNode:s}=t,a=super.generate(e,"property"),o=n.build(e,this.value.is3DTexture===!0?"uvec3":"uvec2"),l=i.build(e,"vec4"),c=s?s.build(e,"int"):null,u=e.generateTextureStore(this.value,a,o,c,l);e.addLineFlowCode(u,this)}clone(){let e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e.access=this.access,e}},SA=Me(Fm).setParameterLength(1,3),rB=(r,e,t)=>{let n;return r.isStorageTextureNode===!0?n=r.store(e,t):(n=SA(r,e,t),t!==null&&n.toStack()),n},J_=class extends Fm{static get type(){return"StorageTexture3DNode"}constructor(e,t,n=null){super(e,t,n),this.isStorageTexture3DNode=!0}getDefaultUV(){return N(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}},aB=Me(J_).setParameterLength(1,3),oB=P(({texture:r,uv:e})=>{let n=N().toVar();return oe(e.x.lessThan(1e-4),()=>{n.assign(N(1,0,0))}).ElseIf(e.y.lessThan(1e-4),()=>{n.assign(N(0,1,0))}).ElseIf(e.z.lessThan(1e-4),()=>{n.assign(N(0,0,1))}).ElseIf(e.x.greaterThan(1-1e-4),()=>{n.assign(N(-1,0,0))}).ElseIf(e.y.greaterThan(1-1e-4),()=>{n.assign(N(0,-1,0))}).ElseIf(e.z.greaterThan(1-1e-4),()=>{n.assign(N(0,0,-1))}).Else(()=>{let s=r.sample(e.add(N(-.01,0,0))).r.sub(r.sample(e.add(N(.01,0,0))).r),a=r.sample(e.add(N(0,-.01,0))).r.sub(r.sample(e.add(N(0,.01,0))).r),o=r.sample(e.add(N(0,0,-.01))).r.sub(r.sample(e.add(N(0,0,.01))).r);n.assign(N(s,a,o))}),n.normalize()}),Q_=class extends cs{static get type(){return"Texture3DNode"}constructor(e,t=null,n=null){super(e,t,n),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return N(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return oB({texture:this,uv:e})}},tT=Me(Q_).setParameterLength(1,3),lB=(...r)=>tT(...r).setSampler(!1),cB=(r,e,t)=>tT(r,e).level(t),eb=class extends yu{static get type(){return"UserDataNode"}constructor(e,t,n=null){super(e,t,n),this.userData=n}updateReference(e){return this.reference=this.userData!==null?this.userData:e.object.userData,this.reference}},uB=(r,e,t)=>new eb(r,e,t),pM=new WeakMap,tb=class extends ht{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=pe.OBJECT,this.updateAfterType=pe.OBJECT,this.previousModelWorldMatrix=ie(new Ne),this.previousProjectionMatrix=ie(new Ne).setGroup(de),this.previousCameraViewMatrix=ie(new Ne)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:n}){let i=fM(n);this.previousModelWorldMatrix.value.copy(i);let s=TA(t);s.frameId!==e&&(s.frameId=e,s.previousProjectionMatrix===void 0?(s.previousProjectionMatrix=new Ne,s.previousCameraViewMatrix=new Ne,s.currentProjectionMatrix=new Ne,s.currentCameraViewMatrix=new Ne,s.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),s.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(s.previousProjectionMatrix.copy(s.currentProjectionMatrix),s.previousCameraViewMatrix.copy(s.currentCameraViewMatrix)),s.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),s.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(s.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(s.previousCameraViewMatrix))}updateAfter({object:e}){fM(e).copy(e.matrixWorld)}setup(){let e=this.projectionMatrix===null?Jn:ie(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),n=e.mul(cr).mul(Mt),i=this.previousProjectionMatrix.mul(t).mul(ul),s=n.xy.div(n.w),a=i.xy.div(i.w);return Ie(s,a)}};function TA(r){let e=pM.get(r);return e===void 0&&(e={},pM.set(r,e)),e}function fM(r,e=0){let t=TA(r),n=t[e];return n===void 0&&(t[e]=n=new Ne,t[e].copy(r.matrixWorld)),n}var dB=Y(tb),hB=P(([r,e])=>gi(1,r.oneMinus().div(e)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),pB=P(([r,e])=>gi(r.div(e.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),fB=P(([r,e])=>r.oneMinus().mul(e.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),mB=P(([r,e])=>Re(r.mul(2).mul(e),r.oneMinus().mul(2).mul(e.oneMinus()).oneMinus(),ol(.5,r))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),gB=P(([r,e])=>{let t=e.a.add(r.a.mul(e.a.oneMinus()));return J(e.rgb.mul(e.a).add(r.rgb.mul(r.a).mul(e.a.oneMinus())).div(t),t)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),yB=P(([r])=>nT(r.rgb)),xB=P(([r,e=v(1)])=>e.mix(nT(r.rgb),r.rgb).max(0)),_B=P(([r,e=v(0)])=>{let t=Wt(r.r,r.g,r.b).div(3),n=r.r.max(r.g.max(r.b)),i=n.sub(t).mul(e).mul(-3);return Re(r.rgb,n,i).max(0)}),bB=P(([r,e=v(1)])=>{let t=N(.57735,.57735,.57735),n=e.cos();return N(r.rgb.mul(n).add(t.cross(r.rgb).mul(e.sin()).add(t.mul(ls(t,r.rgb).mul(n.oneMinus()))))).max(0)}),nT=(r,e=N(Fe.getLuminanceCoefficients(new E)))=>ls(r,e),vB=P(([r,e=N(1),t=N(0),n=N(1),i=v(1),s=N(Fe.getLuminanceCoefficients(new E,Hl))])=>{let a=r.rgb.dot(N(s)),o=At(r.rgb.mul(e).add(t),0),l=o.pow(n);return oe(o.r.greaterThan(0),()=>{o.r.assign(l.r)}),oe(o.g.greaterThan(0),()=>{o.g.assign(l.g)}),oe(o.b.greaterThan(0),()=>{o.b.assign(l.b)}),o.assign(a.add(o.sub(a).mul(i)).max(0)),J(o.rgb,r.a)}),SB=P(([r,e])=>r.mul(e).floor().div(e)),Nf=null,nb=class extends xu{static get type(){return"ViewportSharedTextureNode"}constructor(e=Rs,t=null){Nf===null&&(Nf=new _o),super(e,t,Nf)}getTextureForReference(){return Nf}updateReference(){return this}},TB=Me(nb).setParameterLength(0,2),Pf=new O,Lm=class extends cs{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){let t=e.getNodeProperties(this);return t.passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}},Bm=class extends Lm{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){let e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}},pr=class r extends ht{static get type(){return"PassNode"}constructor(e,t,n,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=i,this._width=1,this._height=1;let s=new Jt(this._width,this._height,{type:xt,...i});s.texture.name="output";let a=null;(this.scope===r.DEPTH||i.depthBuffer!==!1)&&(a=new Pn,a.isRenderTargetTexture=!0,a.name="depth",s.depthTexture=a),this.renderTarget=s,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:s.texture},a!==null&&(this._textures.depth=a),this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=ie(0),this._cameraFar=ie(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=pe.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return X("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return X("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(t===void 0){if(e==="depth")throw new Error("THREE.PassNode: Depth texture is not available for this pass.");t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return t===void 0&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){let t=this._previousTextures[e];if(t!==void 0){let n=this._textures[e],i=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=n,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return t===void 0&&(t=new Bm(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return t===void 0&&(this._textureNodes[e]===void 0&&this.getTextureNode(e),t=new Bm(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(t===void 0){let n=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=Bg(this.getTextureNode(e),n,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(t===void 0){let n=this._cameraNear,i=this._cameraFar,s=this.getViewZNode(e);this._linearDepthNodes[e]=t=il(s,n,i)}return t}async compileAsync(e){let t=e.getRenderTarget(),n=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(n)}setup({renderer:e}){return this.renderTarget.samples=this.options.samples===void 0?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),e.reversedDepthBuffer===!0&&this.renderTarget.depthTexture!==null&&(this.renderTarget.depthTexture.type=en),this.scope===r.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){let{renderer:t}=e,{scene:n}=this,i,s=t.getOutputRenderTarget();s&&s.isXRRenderTarget===!0?(i=t.xr.getCamera(),t.xr.updateCamera(i),Pf.set(s.width,s.height)):(i=this.camera,t.getDrawingBufferSize(Pf)),this.setSize(Pf.width,Pf.height);let a=t.getRenderTarget(),o=t.getMRT(),l=t.autoClear,c=t.transparent,u=t.opaque,d=i.layers.mask,h=t.contextNode,p=n.overrideMaterial;this._cameraNear.value=i.near,this._cameraFar.value=i.far,this._layers!==null&&(i.layers.mask=this._layers.mask);for(let m in this._previousTextures)this.toggleTexture(m);this.overrideMaterial!==null&&(n.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,this.contextNode!==null&&((this._contextNodeCache===null||this._contextNodeCache.version!==this.version)&&(this._contextNodeCache={version:this.version,context:Xr({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);let f=n.name;n.name=this.name?this.name:n.name,t.render(n,i),n.name=f,n.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=l,t.transparent=c,t.opaque=u,t.contextNode=h,i.layers.mask=d}setSize(e,t){this._width=e,this._height=t;let n=Math.floor(this._width*this._resolutionScale),i=Math.floor(this._height*this._resolutionScale);this.renderTarget.setSize(n,i),this._scissor!==null?(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,this._viewport!==null&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._resolutionScale).floor()}setScissor(e,t,n,i){e===null?this._scissor=null:(this._scissor===null&&(this._scissor=new Ge),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,n,i))}setViewport(e,t,n,i){e===null?this._viewport=null:(this._viewport===null&&(this._viewport=new Ge),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,n,i))}dispose(){this.renderTarget.dispose()}};pr.COLOR="color";pr.DEPTH="depth";var MB=(r,e,t)=>new pr(pr.COLOR,r,e,t),wB=(r,e)=>new Lm(r,e),EB=(r,e,t)=>new pr(pr.DEPTH,r,e,t),ib=class extends pr{static get type(){return"ToonOutlinePassNode"}constructor(e,t,n,i,s){super(pr.COLOR,e,t),this.colorNode=n,this.thicknessNode=i,this.alphaNode=s,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){let{renderer:t}=e,n=t.getRenderObjectFunction();t.setRenderObjectFunction((i,s,a,o,l,c,u,d)=>{if((l.isMeshToonMaterial||l.isMeshToonNodeMaterial)&&l.wireframe===!1){let h=this._getOutlineMaterial(l);t.renderObject(i,s,a,o,h,c,u,d)}t.renderObject(i,s,a,o,l,c,u,d)}),super.updateBefore(e),t.setRenderObjectFunction(n)}_createMaterial(){let e=new We;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=ln;let t=Gn.negate(),n=Jn.mul(cr),i=v(1),s=n.mul(J(Mt,1)),a=n.mul(J(Mt.add(t),1)),o=kn(s.sub(a));return e.vertexNode=s.add(o.mul(this.thicknessNode).mul(s.w).mul(i)),e.colorNode=J(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return t===void 0&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}},RB=(r,e,t=new me(0,0,0),n=.003,i=1)=>new ib(r,e,ne(t),ne(n),ne(i)),MA=P(([r,e])=>r.mul(e).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),wA=P(([r,e])=>(r=r.mul(e),r.div(r.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),EA=P(([r,e])=>{r=r.mul(e),r=r.sub(.004).max(0);let t=r.mul(r.mul(6.2).add(.5)),n=r.mul(r.mul(6.2).add(1.7)).add(.06);return t.div(n).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),AB=P(([r])=>{let e=r.mul(r.add(.0245786)).sub(90537e-9),t=r.mul(r.add(.432951).mul(.983729)).add(.238081);return e.div(t)}),RA=P(([r,e])=>{let t=yn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),n=yn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return r=r.mul(e).div(.6),r=t.mul(r),r=AB(r),r=n.mul(r),r.clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),CB=yn(N(1.6605,-.1246,-.0182),N(-.5876,1.1329,-.1006),N(-.0728,-.0083,1.1187)),NB=yn(N(.6274,.0691,.0164),N(.3293,.9195,.088),N(.0433,.0113,.8956)),PB=P(([r])=>{let e=N(r).toVar(),t=N(e.mul(e)).toVar(),n=N(t.mul(t)).toVar();return v(15.5).mul(n.mul(t)).sub(xe(40.14,n.mul(e))).add(xe(31.96,n).sub(xe(6.868,t.mul(e))).add(xe(.4298,t).add(xe(.1191,e).sub(.00232))))}),AA=P(([r,e])=>{let t=N(r).toVar(),n=yn(N(.856627153315983,.137318972929847,.11189821299995),N(.0951212405381588,.761241990602591,.0767994186031903),N(.0482516061458583,.101439036467562,.811302368396859)),i=yn(N(1.1271005818144368,-.1413297634984383,-.14132976349843826),N(-.11060664309660323,1.157823702216272,-.11060664309660294),N(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=v(-12.47393),a=v(4.026069);return t.mulAssign(e),t.assign(NB.mul(t)),t.assign(n.mul(t)),t.assign(At(t,1e-10)),t.assign(ir(t)),t.assign(t.sub(s).div(a.sub(s))),t.assign(Ns(t,0,1)),t.assign(PB(t)),t.assign(i.mul(t)),t.assign(ss(At(N(0),t),N(2.2))),t.assign(CB.mul(t)),t.assign(Ns(t,0,1)),t}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),CA=P(([r,e])=>{let t=v(.76),n=v(.15);r=r.mul(e);let i=gi(r.r,gi(r.g,r.b)),s=On(i.lessThan(.08),i.sub(xe(6.25,i.mul(i))),.04);r.subAssign(s);let a=At(r.r,At(r.g,r.b));oe(a.lessThan(t),()=>r);let o=Ie(1,t),l=Ie(1,o.mul(o).div(a.add(o.sub(t))));r.mulAssign(l.div(a));let c=Ie(1,Ui(1,n.mul(a.sub(l)).add(1)));return Re(r,N(l),c)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),st=class extends le{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=n}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){let t=this.getIncludes(e);for(let i of t)i.build(e);let n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}},Gg=Me(st).setParameterLength(1,3),DB=(r,e)=>Gg(r,e,"js"),IB=(r,e)=>Gg(r,e,"wgsl"),FB=(r,e)=>Gg(r,e,"glsl"),Um=class extends st{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){let n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){let t=e.getDataFromNode(this),n=t.nodeFunction;return n===void 0&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);let n=this.getNodeFunction(e),i=n.name,s=n.type,a=e.getCodeFromNode(this,s);i!==""&&(a.name=i);let o=e.getPropertyName(a),l=this.getNodeFunction(e).getCode(o);return a.code=l+`
`,t==="property"?o:e.format(`${o}()`,s,t)}},NA=(r,e=[],t="")=>{let n=new Um(r,e,t);return Wv((...s)=>n.call(...s),n)},LB=(r,e)=>NA(r,e,"glsl"),BB=(r,e)=>NA(r,e,"wgsl");function iT(r){let e,t=r.context.getViewZ;return t!==void 0&&(e=t(this)),(e||Ot.z).negate()}var PA=P(([r,e],t)=>{let n=iT(t);return Oi(r,e,n)}),DA=P(([r],e)=>{let t=iT(e);return r.mul(r,t,t).negate().exp().oneMinus()}),UB=P(([r,e],t)=>{let n=iT(t),s=e.sub(ar.y).max(0).toConst().mul(n).toConst();return r.mul(r,s,s).negate().exp().oneMinus()}),sb=P(([r,e])=>J(e.toFloat().mix(cu.rgb,r.toVec3()),cu.a)),zo=null,Ho=null,rb=class extends le{static get type(){return"RangeNode"}constructor(e=v(),t=v()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){let t=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),i=e.getTypeLength(Xa(t.value)),s=e.getTypeLength(Xa(n.value));return i>s?i:s}generateNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse(n=>{n.isConstNode===!0&&(t=n)}),t===null)throw new gm('THREE.TSL: No "ConstNode" found in node graph.',this.stackTrace);return t}setup(e){let t=e.object,n=null;if(t.count>1){let i=this.getConstNode(this.minNode),s=this.getConstNode(this.maxNode),a=i.value,o=s.value,l=e.getTypeLength(Xa(a)),c=e.getTypeLength(Xa(o));zo=zo||new Ge,Ho=Ho||new Ge,zo.setScalar(0),Ho.setScalar(0),l===1?zo.setScalar(a):a.isColor?zo.set(a.r,a.g,a.b,1):zo.set(a.x,a.y,a.z||0,a.w||0),c===1?Ho.setScalar(o):o.isColor?Ho.set(o.r,o.g,o.b,1):Ho.set(o.x,o.y,o.z||0,o.w||0);let u=4,d=u*t.count,h=new Float32Array(d);for(let m=0;m<d;m++){let y=m%u,x=zo.getComponent(y),b=Ho.getComponent(y);h[m]=Dn.lerp(x,b,Math.random())}let p=this.getNodeType(e);if(t.count*4*4<=e.getUniformBufferLimit())n=wu(h,"vec4",t.count).element(As).convert(p);else{let m=new Hs(h,4);e.geometry.setAttribute("__range"+this.id,m),n=Ng(m).convert(p)}}else n=v(0);return n}},OB=Me(rb).setParameterLength(2),ab=class extends le{static get type(){return"ComputeBuiltinNode"}constructor(e,t){super(t),this._builtinName=e}getHash(e){return this.getBuiltinName(e)}generateNodeType(){return this.nodeType}setBuiltinName(e){return this._builtinName=e,this}getBuiltinName(){return this._builtinName}hasBuiltin(e){return e.hasBuiltin(this._builtinName)}generate(e,t){let n=this.getBuiltinName(e),i=this.getNodeType(e);return e.shaderStage==="compute"?e.format(n,i,t):(X(`ComputeBuiltinNode: Compute built-in value ${n} can not be accessed in the ${e.shaderStage} stage`),e.generateConst(i))}serialize(e){super.serialize(e),e.global=this.global,e._builtinName=this._builtinName}deserialize(e){super.deserialize(e),this.global=e.global,this._builtinName=e._builtinName}},np=(r,e)=>new ab(r,e),kB=np("numWorkgroups","uvec3"),VB=np("workgroupId","uvec3"),GB=np("globalId","uvec3"),zB=np("localId","uvec3"),HB=np("subgroupSize","uint"),ob=class extends le{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){let{scope:t}=this,{renderer:n}=e;n.backend.isWebGLBackend===!0?e.addFlowCode(` // ${t}Barrier
`):e.addLineFlowCode(`${t}Barrier()`,this)}},sT=Me(ob),WB=()=>sT("workgroup").toStack(),qB=()=>sT("storage").toStack(),$B=()=>sT("texture").toStack(),lb=class extends Hr{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let n,i=e.isContextAssign();if(n=super.generate(e),i!==!0){let s=this.getNodeType(e);n=e.format(n,s,t)}return n}},cb=class extends le{constructor(e,t,n=0){super(t),this.bufferType=t,this.bufferCount=n,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return X('TSL: "label()" has been deprecated. Use "setName()" instead.',new Dt),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new lb(this,e)}generate(e){let t=this.name!==""?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}},XB=(r,e)=>new cb("Workgroup",r,e),$t=class extends le{static get type(){return"AtomicFunctionNode"}constructor(e,t,n){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=n,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}generateNodeType(e){return this.getInputType(e)}generate(e){let t=e.getNodeProperties(this),n=t.parents,i=this.method,s=this.getNodeType(e),a=this.getInputType(e),o=this.pointerNode,l=this.valueNode,c=[];c.push(`&${o.build(e,a)}`),l!==null&&c.push(l.build(e,a));let u=`${e.getMethod(i,s)}( ${c.join(", ")} )`;if(n?n.length===1&&n[0].isStackNode===!0:!1)e.addLineFlowCode(u,this);else return t.constNode===void 0&&(t.constNode=Fi(u,s).toConst()),t.constNode.build(e)}};$t.ATOMIC_LOAD="atomicLoad";$t.ATOMIC_STORE="atomicStore";$t.ATOMIC_ADD="atomicAdd";$t.ATOMIC_SUB="atomicSub";$t.ATOMIC_MAX="atomicMax";$t.ATOMIC_MIN="atomicMin";$t.ATOMIC_AND="atomicAnd";$t.ATOMIC_OR="atomicOr";$t.ATOMIC_XOR="atomicXor";var YB=Me($t),mr=(r,e,t)=>YB(r,e,t).toStack(),jB=r=>mr($t.ATOMIC_LOAD,r,null),KB=(r,e)=>mr($t.ATOMIC_STORE,r,e),ZB=(r,e)=>mr($t.ATOMIC_ADD,r,e),JB=(r,e)=>mr($t.ATOMIC_SUB,r,e),QB=(r,e)=>mr($t.ATOMIC_MAX,r,e),eU=(r,e)=>mr($t.ATOMIC_MIN,r,e),tU=(r,e)=>mr($t.ATOMIC_AND,r,e),nU=(r,e)=>mr($t.ATOMIC_OR,r,e),iU=(r,e)=>mr($t.ATOMIC_XOR,r,e),te=class r extends ht{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,n=null){super(),this.method=e,this.aNode=t,this.bNode=n}getInputType(e){let t=this.aNode?this.aNode.getNodeType(e):null,n=this.bNode?this.bNode.getNodeType(e):null,i=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n);return i>s?t:n}generateNodeType(e){let t=this.method;return t===r.SUBGROUP_ELECT?"bool":t===r.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){let n=this.method,i=this.getNodeType(e),s=this.getInputType(e),a=this.aNode,o=this.bNode,l=[];if(n===r.SUBGROUP_BROADCAST||n===r.SUBGROUP_SHUFFLE||n===r.QUAD_BROADCAST){let u=o.getNodeType(e);l.push(a.build(e,i),o.build(e,u==="float"?"int":i))}else n===r.SUBGROUP_SHUFFLE_XOR||n===r.SUBGROUP_SHUFFLE_DOWN||n===r.SUBGROUP_SHUFFLE_UP?l.push(a.build(e,i),o.build(e,"uint")):(a!==null&&l.push(a.build(e,s)),o!==null&&l.push(o.build(e,s)));let c=l.length===0?"()":`( ${l.join(", ")} )`;return e.format(`${e.getMethod(n,i)}${c}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}};te.SUBGROUP_ELECT="subgroupElect";te.SUBGROUP_BALLOT="subgroupBallot";te.SUBGROUP_ADD="subgroupAdd";te.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd";te.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd";te.SUBGROUP_MUL="subgroupMul";te.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul";te.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul";te.SUBGROUP_AND="subgroupAnd";te.SUBGROUP_OR="subgroupOr";te.SUBGROUP_XOR="subgroupXor";te.SUBGROUP_MIN="subgroupMin";te.SUBGROUP_MAX="subgroupMax";te.SUBGROUP_ALL="subgroupAll";te.SUBGROUP_ANY="subgroupAny";te.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst";te.QUAD_SWAP_X="quadSwapX";te.QUAD_SWAP_Y="quadSwapY";te.QUAD_SWAP_DIAGONAL="quadSwapDiagonal";te.SUBGROUP_BROADCAST="subgroupBroadcast";te.SUBGROUP_SHUFFLE="subgroupShuffle";te.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor";te.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp";te.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown";te.QUAD_BROADCAST="quadBroadcast";var sU=H(te,te.SUBGROUP_ELECT).setParameterLength(0),rU=H(te,te.SUBGROUP_BALLOT).setParameterLength(1),aU=H(te,te.SUBGROUP_ADD).setParameterLength(1),oU=H(te,te.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),lU=H(te,te.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),cU=H(te,te.SUBGROUP_MUL).setParameterLength(1),uU=H(te,te.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),dU=H(te,te.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),hU=H(te,te.SUBGROUP_AND).setParameterLength(1),pU=H(te,te.SUBGROUP_OR).setParameterLength(1),fU=H(te,te.SUBGROUP_XOR).setParameterLength(1),mU=H(te,te.SUBGROUP_MIN).setParameterLength(1),gU=H(te,te.SUBGROUP_MAX).setParameterLength(1),yU=H(te,te.SUBGROUP_ALL).setParameterLength(0),xU=H(te,te.SUBGROUP_ANY).setParameterLength(0),_U=H(te,te.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),bU=H(te,te.QUAD_SWAP_X).setParameterLength(1),vU=H(te,te.QUAD_SWAP_Y).setParameterLength(1),SU=H(te,te.QUAD_SWAP_DIAGONAL).setParameterLength(1),TU=H(te,te.SUBGROUP_BROADCAST).setParameterLength(2),MU=H(te,te.SUBGROUP_SHUFFLE).setParameterLength(2),wU=H(te,te.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),EU=H(te,te.SUBGROUP_SHUFFLE_UP).setParameterLength(2),RU=H(te,te.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),AU=H(te,te.QUAD_BROADCAST).setParameterLength(1),Df;function zg(r){Df=Df||new WeakMap;let e=Df.get(r);return e===void 0&&Df.set(r,e={}),e}function Hg(r){let e=zg(r);return e.shadowMatrix||(e.shadowMatrix=ie("mat4").setGroup(de).onRenderUpdate(t=>((r.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&(r.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(r.shadow.camera.coordinateSystem=t.camera.coordinateSystem,r.shadow.camera.updateProjectionMatrix()),r.shadow.updateMatrices(r)),r.shadow.matrix)))}function IA(r,e=ar){let t=Hg(r).mul(e);return t.xyz.div(t.w)}function rT(r){let e=zg(r);return e.position||(e.position=ie(new E).setGroup(de).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(r.matrixWorld)))}function FA(r){let e=zg(r);return e.targetPosition||(e.targetPosition=ie(new E).setGroup(de).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(r.target.matrixWorld)))}function aT(r){let e=zg(r);return e.viewPosition||(e.viewPosition=ie(new E).setGroup(de).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new E,n.value.setFromMatrixPosition(r.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}var oT=r=>so.transformDirection(rT(r).sub(FA(r))),CU=$r("vec3","totalDiffuse"),NU=$r("vec3","totalSpecular"),PU=$r("vec3","outgoingLight"),DU=r=>r.sort((e,t)=>e.id-t.id),IU=(r,e)=>{for(let t of e)if(t.isAnalyticLightNode&&t.light.id===r)return t;return null},Oy=new WeakMap,ch=[],Wh=class extends le{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=CU,this.totalSpecularNode=NU,this.outgoingLightNode=PU,this._lights=[],this.global=!0}customCacheKey(){let e=this._lights;for(let n=0;n<e.length;n++){let i=e[n];if(ch.push(i.id),ch.push(i.castShadow?1:0),i.isSpotLight===!0){let s=i.map!==null?i.map.id:-1,a=i.colorNode?i.colorNode.getCacheKey():-1;ch.push(s,a)}}let t=Jh(ch);return ch.length=0,t}getHash(e){let t=e.getDataFromNode(this);if(t.lightNodesHash===void 0){let n=this.setupLightsNode(e);t.lightNodes=n;let i=[];for(let s of n)i.push(s.getHash());t.lightNodesHash="lights-"+i.join(",")}return t.lightNodesHash}analyze(e){let t=e.getNodeProperties(this);for(let n of t.nodes)n.build(e);t.outputNode.build(e)}setupLightsNode(e){let t=e.getDataFromNode(this),n=[],i=t.lightNodes||null,s=e.context.materialLightings,a=DU([...s,...this._lights]),o=e.renderer.library;for(let l of a)if(l.isNode)n.push(l);else{let c=null;if(i!==null&&(c=IU(l.id,i)),c===null){let u=o.getLightNodeClass(l.constructor);if(u===null){X(`LightsNode.setupNodeLights: Light node not found for ${l.constructor.name}`);continue}Oy.has(l)===!1&&Oy.set(l,new u(l)),c=Oy.get(l)}n.push(c)}return n}setupDirectLight(e,t,n){let{lightingModel:i,reflectedLight:s}=e.context;i.direct({...n,lightNode:t,reflectedLight:s},e)}setupDirectRectAreaLight(e,t,n){let{lightingModel:i,reflectedLight:s}=e.context;i.directRectArea({...n,lightNode:t,reflectedLight:s},e)}setupLights(e,t){for(let n of t)n.build(e)}getLightNodes(e){let t=e.getDataFromNode(this);return t.lightNodes===void 0&&(t.lightNodes=this.setupLightsNode(e)),t.lightNodes}setup(e){let t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode,i=e.context,s=i.lightingModel,a=e.getNodeProperties(this);if(s){let{totalDiffuseNode:o,totalSpecularNode:l}=this;i.outgoingLight=n;let c=e.addStack();a.nodes=c.nodes,s.start(e);let{backdrop:u,backdropAlpha:d}=i,{directDiffuse:h,directSpecular:p,indirectDiffuse:f,indirectSpecular:m}=i.reflectedLight,y=h.add(f);u!==null&&(d!==null?y=N(d.mix(y,u)):y=N(u)),o.assign(y),l.assign(p.add(m)),n.assign(o.add(l)),s.finish(e),n=n.bypass(e.removeStack())}else a.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}},FU=(r=[])=>new Wh().setLights(r),ub=class extends le{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=pe.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){lT.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||ar)}},lT=$r("vec3","shadowPositionWorld");function cT(r,e={}){return e.toneMapping=r.toneMapping,e.toneMappingExposure=r.toneMappingExposure,e.outputColorSpace=r.outputColorSpace,e.renderTarget=r.getRenderTarget(),e.activeCubeFace=r.getActiveCubeFace(),e.activeMipmapLevel=r.getActiveMipmapLevel(),e.renderObjectFunction=r.getRenderObjectFunction(),e.pixelRatio=r.getPixelRatio(),e.mrt=r.getMRT(),e.clearColor=r.getClearColor(e.clearColor||new me),e.clearAlpha=r.getClearAlpha(),e.autoClear=r.autoClear,e.scissorTest=r.getScissorTest(),e}function LA(r,e){return e=cT(r,e),r.setMRT(null),r.setRenderObjectFunction(null),r.setClearColor(0,1),r.autoClear=!0,e}function BA(r,e){r.toneMapping=e.toneMapping,r.toneMappingExposure=e.toneMappingExposure,r.outputColorSpace=e.outputColorSpace,r.setRenderTarget(e.renderTarget,e.activeCubeFace,e.activeMipmapLevel),r.setRenderObjectFunction(e.renderObjectFunction),r.setPixelRatio(e.pixelRatio),r.setMRT(e.mrt),r.setClearColor(e.clearColor,e.clearAlpha),r.autoClear=e.autoClear,r.setScissorTest(e.scissorTest)}function uT(r,e={}){return e.background=r.background,e.backgroundNode=r.backgroundNode,e.overrideMaterial=r.overrideMaterial,e}function UA(r,e){return e=uT(r,e),r.background=null,r.backgroundNode=null,r.overrideMaterial=null,e}function OA(r,e){r.background=e.background,r.backgroundNode=e.backgroundNode,r.overrideMaterial=e.overrideMaterial}function LU(r,e,t={}){return t=cT(r,t),t=uT(e,t),t}function kA(r,e,t){return t=LA(r,t),t=UA(e,t),t}function VA(r,e,t){BA(r,t),OA(e,t)}var dT=Object.freeze({__proto__:null,resetRendererAndSceneState:kA,resetRendererState:LA,resetSceneState:UA,restoreRendererAndSceneState:VA,restoreRendererState:BA,restoreSceneState:OA,saveRendererAndSceneState:LU,saveRendererState:cT,saveSceneState:uT}),Om=new WeakMap,GA=P(({depthTexture:r,shadowCoord:e,depthLayer:t})=>{let n=Ue(r,e.xy).setName("t_basic");return r.isArrayTexture&&(n=n.depth(t)),n.compare(e.z)}),zA=P(({depthTexture:r,shadowCoord:e,shadow:t,depthLayer:n})=>{let i=(u,d)=>{let h=Ue(r,u);return r.isArrayTexture&&(h=h.depth(n)),h.compare(d)},s=dt("mapSize","vec2",t).setGroup(de),a=dt("radius","float",t).setGroup(de),o=$(1).div(s),l=a.mul(o.x),c=eT(yl.xy).mul(6.28318530718);return Wt(i(e.xy.add(Es(0,5,c).mul(l)),e.z),i(e.xy.add(Es(1,5,c).mul(l)),e.z),i(e.xy.add(Es(2,5,c).mul(l)),e.z),i(e.xy.add(Es(3,5,c).mul(l)),e.z),i(e.xy.add(Es(4,5,c).mul(l)),e.z)).mul(1/5)}),HA=P(({depthTexture:r,shadowCoord:e,shadow:t,depthLayer:n})=>{let i=dt("mapSize","vec2",t).setGroup(de),s=$(1).div(i),a=e.xy,o=Cs(a.mul(i).add(.5)).toConst();a.subAssign(o.sub(.5).mul(s));let l=p=>{let f=Ue(r,a).offset(p).gather();return r.isArrayTexture&&(f=f.depth(n)),f.compare(e.z)},c=l(Rt(-1,1)).toConst(),u=l(Rt(1,1)).toConst(),d=l(Rt(-1,-1)).toConst(),h=l(Rt(1,-1)).toConst();return Wt(Re(c.x,u.y,o.x).add(c.y).add(u.x).mul(o.y),Re(c.w,u.z,o.x).add(c.z).add(u.w),Re(d.x,h.y,o.x).add(d.y).add(h.x),Re(d.w,h.z,o.x).add(d.z).add(h.w).mul(o.y.oneMinus())).mul(1/9)}),WA=P(({depthTexture:r,shadowCoord:e,depthLayer:t},n)=>{let i=Ue(r).sample(e.xy);r.isArrayTexture&&(i=i.depth(t)),i=i.rg;let s=i.x,a=At(1e-7,i.y.mul(i.y)),o=n.renderer.reversedDepthBuffer?ol(s,e.z):ol(e.z,s),l=v(1).toVar();return oe(o.notEqual(1),()=>{let c=e.z.sub(s),u=a.div(a.add(c.mul(c)));u=Ns(Ie(u,.3).div(.65)),l.assign(At(o,u))}),l}),qA=r=>{let e=Om.get(r);return e===void 0&&(e=new We,e.colorNode=J(0,0,0,1),e.isShadowPassMaterial=!0,e.name="ShadowMaterial",e.blending=_s,e.fog=!1,Om.set(r,e)),e},$A=r=>{let e=Om.get(r);e!==void 0&&(e.dispose(),Om.delete(r))},mM=new dr,Xc=[],XA=(r,e,t,n)=>{Xc[0]=r,Xc[1]=e;let i=mM.get(Xc);return(i===void 0||i.shadowType!==t||i.useVelocity!==n)&&(i=(s,a,o,l,c,u,d,h,p)=>{(s.castShadow===!0||s.receiveShadow&&t===Ta)&&(n&&(jM(s).useVelocity=!0),s.onBeforeShadow(r,s,o,e.camera,l,a.overrideMaterial,u),r.renderObject(s,a,o,l,c,u,d,h,p),s.onAfterShadow(r,s,o,e.camera,l,a.overrideMaterial,u))},i.shadowType=t,i.useVelocity=n,mM.set(Xc,i)),Xc[0]=null,Xc[1]=null,i},BU=P(({samples:r,radius:e,size:t,shadowPass:n,depthLayer:i})=>{let s=v(0).toVar("meanVertical"),a=v(0).toVar("squareMeanVertical"),o=r.lessThanEqual(v(1)).select(v(0),v(2).div(r.sub(1))),l=r.lessThanEqual(v(1)).select(v(0),v(-1));Xe({start:C(0),end:C(r),type:"int",condition:"<"},({i:u})=>{let d=l.add(v(u).mul(o)),h=n.sample(Wt(yl.xy,$(0,d).mul(e)).div(t));n.value.isArrayTexture&&(h=h.depth(i)),h=h.x,s.addAssign(h),a.addAssign(h.mul(h))}),s.divAssign(r),a.divAssign(r);let c=Qn(a.sub(s.mul(s)).max(0));return $(s,c)}),UU=P(({samples:r,radius:e,size:t,shadowPass:n,depthLayer:i})=>{let s=v(0).toVar("meanHorizontal"),a=v(0).toVar("squareMeanHorizontal"),o=r.lessThanEqual(v(1)).select(v(0),v(2).div(r.sub(1))),l=r.lessThanEqual(v(1)).select(v(0),v(-1));Xe({start:C(0),end:C(r),type:"int",condition:"<"},({i:u})=>{let d=l.add(v(u).mul(o)),h=n.sample(Wt(yl.xy,$(d,0).mul(e)).div(t));n.value.isArrayTexture&&(h=h.depth(i)),s.addAssign(h.x),a.addAssign(Wt(h.y.mul(h.y),h.x.mul(h.x)))}),s.divAssign(r),a.divAssign(r);let c=Qn(a.sub(s.mul(s)).max(0));return $(s,c)}),OU=[GA,zA,HA,WA],ky,If=new Is,km=class extends ub{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:s,depthLayer:a}){let o=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),l=t({depthTexture:n,shadowCoord:i,shadow:s,depthLayer:a});return o.select(l,v(1))}setupShadowCoord(e,t){let{shadow:n}=this,{renderer:i}=e,s=n.biasNode||dt("bias","float",n).setGroup(de),a=t,o;if(n.camera.isOrthographicCamera||i.logarithmicDepthBuffer!==!0)a=a.xyz.div(a.w),o=a.z;else{let l=a.w;a=a.xy.div(l);let c=dt("near","float",n.camera).setGroup(de),u=dt("far","float",n.camera).setGroup(de);o=Ug(l.negate(),c,u)}return a=N(a.x,a.y.oneMinus(),i.reversedDepthBuffer?o.sub(s):o.add(s)),a}getShadowFilterFn(e){return OU[e]}setupRenderTarget(e,t){let n=new Pn(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?La:Oo;let i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=n,{shadowMap:i,depthTexture:n}}setupShadow(e){let{renderer:t,camera:n}=e,{light:i,shadow:s}=this,{depthTexture:a,shadowMap:o}=this.setupRenderTarget(s,e),l=t.shadowMap.type,c=t.hasCompatibility(Fr.TEXTURE_COMPARE);if((l===Fd||l===z0)&&c?(a.minFilter=St,a.magFilter=St):(a.minFilter=vt,a.magFilter=vt),s.camera.coordinateSystem=n.coordinateSystem,s.camera.updateProjectionMatrix(),l===Ta&&s.isPointLightShadow!==!0){a.compareFunction=null,o.depth>1?(o._vsmShadowMapVertical||(o._vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:mi,type:xt,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=o._vsmShadowMapVertical,o._vsmShadowMapHorizontal||(o._vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:mi,type:xt,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=o._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:mi,type:xt,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:mi,type:xt,depthBuffer:!1}));let w=Ue(a);a.isArrayTexture&&(w=w.depth(this.depthLayer));let T=Ue(this.vsmShadowMapVertical.texture);a.isArrayTexture&&(T=T.depth(this.depthLayer));let R=dt("blurSamples","float",s).setGroup(de),D=dt("radius","float",s).setGroup(de),L=dt("mapSize","vec2",s).setGroup(de),B=this.vsmMaterialVertical||(this.vsmMaterialVertical=new We);B.fragmentNode=BU({samples:R,radius:D,size:L,shadowPass:w,depthLayer:this.depthLayer}).context(e.getSharedContext()),B.name="VSMVertical",B=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new We),B.fragmentNode=UU({samples:R,radius:D,size:L,shadowPass:T,depthLayer:this.depthLayer}).context(e.getSharedContext()),B.name="VSMHorizontal"}let u=dt("intensity","float",s).setGroup(de),d=dt("normalBias","float",s).setGroup(de),h=Hg(i),p=ro.mul(d),f;!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld?f=h.mul(lT.add(p)):f=ie("mat4").onObjectUpdate(({object:T},R)=>R.value.multiplyMatrices(h.value,T.matrixWorld)).mul(Mt).add(h.mul(J(p,0)));let m=this.setupShadowCoord(e,f),y=s.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(y===null)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");let x=l===Ta&&s.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:a,b=this.setupShadowFilter(e,{filterFn:y,shadowTexture:o.texture,depthTexture:x,shadowCoord:m,shadow:s,depthLayer:this.depthLayer}),_;t.shadowMap.transmitted===!0&&(o.texture.isCubeTexture?_=Zn(o.texture,m.xyz):(_=Ue(o.texture,m),a.isArrayTexture&&(_=_.depth(this.depthLayer))));let S;_?S=Re(1,b.rgb.mix(_,1),u.mul(_.a)).toVar():S=Re(1,b,u).toVar(),this.shadowMap=o,this.shadow.map=o;let M=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return _&&S.toInspector(`${M} / Color`,()=>this.shadowMap.texture.isCubeTexture?Zn(this.shadowMap.texture,i_()):Ue(this.shadowMap.texture)),S.toInspector(`${M} / Depth`,()=>{let w=dt("near","float",this.shadow.camera),T=dt("far","float",this.shadow.camera),R;this.shadowMap.texture.isCubeTexture?R=Zn(this.shadowMap.depthTexture,i_()).r:R=Ue(this.shadowMap.depthTexture).r;let D;return this.shadow.camera.isPerspectiveCamera?D=Bg(R,w,T):D=WR(R,w,T),D=il(D,w,T),D.oneMinus()})}setup(e){if(e.renderer.shadowMap.enabled!==!1)return P(()=>{let t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let n=this._node;return this.setupShadowPosition(e),n===null&&(this._node=n=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}renderShadow(e){let{shadow:t,shadowMap:n,light:i}=this,{renderer:s,scene:a}=e;t.updateMatrices(i),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);let o=a.name;a.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,s.render(a,t.camera),a.name=o}updateShadow(e){let{shadowMap:t,light:n,shadow:i}=this,{renderer:s,scene:a,camera:o}=e,l=s.shadowMap.type,c=t.depthTexture.version;this._depthVersionCached=c;let u=i.camera.layers.mask;(i.camera.layers.mask&4294967294)===0&&(i.camera.layers.mask=o.layers.mask);let d=s.getRenderObjectFunction(),h=s.getMRT(),p=h?h.has("velocity"):!1;ky=kA(s,a,ky),a.overrideMaterial=qA(n),s.setRenderObjectFunction(XA(s,i,l,p)),s.setClearColor(0,0),s.setRenderTarget(t),this.renderShadow(e),s.setRenderObjectFunction(d),l===Ta&&i.isPointLightShadow!==!0&&this.vsmPass(s),i.camera.layers.mask=u,VA(s,a,ky)}vsmPass(e){let{shadow:t}=this,n=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,n),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,n),e.setRenderTarget(this.vsmShadowMapVertical),If.material=this.vsmMaterialVertical,If.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),If.material=this.vsmMaterialHorizontal,If.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,$A(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),this.vsmShadowMapVertical!==null&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),this.vsmShadowMapHorizontal!==null&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){let{shadow:t}=this,n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId[e.camera]===e.frameId&&(n=!1),this._cameraFrameId[e.camera]=e.frameId),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}},YA=(r,e)=>new km(r,e),kU=new me,gM=new Ne,uh=new E,Vy=new E,VU=[new E(1,0,0),new E(-1,0,0),new E(0,-1,0),new E(0,1,0),new E(0,0,1),new E(0,0,-1)],GU=[new E(0,-1,0),new E(0,-1,0),new E(0,0,-1),new E(0,0,1),new E(0,-1,0),new E(0,-1,0)],zU=[new E(1,0,0),new E(-1,0,0),new E(0,1,0),new E(0,-1,0),new E(0,0,1),new E(0,0,-1)],HU=[new E(0,-1,0),new E(0,-1,0),new E(0,0,1),new E(0,0,-1),new E(0,-1,0),new E(0,-1,0)],jA=P(({depthTexture:r,bd3D:e,dp:t})=>Zn(r,e).compare(t)),KA=P(({depthTexture:r,bd3D:e,dp:t,shadow:n})=>{let i=dt("radius","float",n).setGroup(de),s=dt("mapSize","vec2",n).setGroup(de),a=i.div(s.x),o=rt(e),l=kn(Wr(e,o.x.greaterThan(o.z).select(N(0,1,0),N(1,0,0)))),c=Wr(e,l),u=eT(yl.xy).mul(6.28318530718),d=Es(0,5,u),h=Es(1,5,u),p=Es(2,5,u),f=Es(3,5,u),m=Es(4,5,u);return Zn(r,e.add(l.mul(d.x).add(c.mul(d.y)).mul(a))).compare(t).add(Zn(r,e.add(l.mul(h.x).add(c.mul(h.y)).mul(a))).compare(t)).add(Zn(r,e.add(l.mul(p.x).add(c.mul(p.y)).mul(a))).compare(t)).add(Zn(r,e.add(l.mul(f.x).add(c.mul(f.y)).mul(a))).compare(t)).add(Zn(r,e.add(l.mul(m.x).add(c.mul(m.y)).mul(a))).compare(t)).mul(1/5)}),WU=P(({filterFn:r,depthTexture:e,shadowCoord:t,shadow:n},i)=>{let s=t.xyz.toConst(),a=s.abs().toConst(),o=a.x.max(a.y).max(a.z),l=ie("float").setGroup(de).onRenderUpdate(()=>n.camera.near),c=ie("float").setGroup(de).onRenderUpdate(()=>n.camera.far),u=dt("bias","float",n).setGroup(de),d=v(1).toVar();return oe(o.sub(c).lessThanEqual(0).and(o.sub(l).greaterThanEqual(0)),()=>{let h;i.renderer.reversedDepthBuffer?(h=qR(o.negate(),l,c),h.subAssign(u)):i.renderer.logarithmicDepthBuffer?(h=Ug(o.negate(),l,c),h.addAssign(u)):(h=XS(o.negate(),l,c),h.addAssign(u));let p=s.normalize();d.assign(r({depthTexture:e,bd3D:p,dp:h,shadow:n}))}),d}),db=class extends km{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===G0?jA:KA}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:s}){return WU({filterFn:t,depthTexture:n,shadowCoord:i,shadow:s})}setupRenderTarget(e,t){let n=new Qu(e.mapSize.width);n.name="PointShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?La:Oo;let i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=n,{shadowMap:i,depthTexture:n}}renderShadow(e){let{shadow:t,shadowMap:n,light:i}=this,{renderer:s,scene:a}=e,o=t.camera,l=t.matrix,c=s.coordinateSystem===di,u=c?VU:zU,d=c?GU:HU;n.setSize(t.mapSize.width,t.mapSize.width);let h=s.autoClear,p=s.getClearColor(kU),f=s.getClearAlpha();s.autoClear=!1,s.setClearColor(t.clearColor,t.clearAlpha);for(let m=0;m<6;m++){s.setRenderTarget(n,m),s.clear();let y=i.distance||o.far;y!==o.far&&(o.far=y,o.updateProjectionMatrix()),uh.setFromMatrixPosition(i.matrixWorld),o.position.copy(uh),Vy.copy(o.position),Vy.add(u[m]),o.up.copy(d[m]),o.lookAt(Vy),o.updateMatrixWorld(),l.makeTranslation(-uh.x,-uh.y,-uh.z),gM.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse),t._frustum.setFromProjectionMatrix(gM,o.coordinateSystem,o.reversedDepth);let x=a.name;a.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${m+1}`,s.render(a,o),a.name=x}s.autoClear=h,s.setClearColor(p,f)}},ZA=(r,e)=>new db(r,e),qr=class extends eo{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new me,this.colorNode=e&&e.colorNode||ie(this.color).setGroup(de),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=pe.FRAME,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,this.baseColorNode!==null&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return aT(this.light).sub(e.context.positionView||Ot)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return YA(this.light)}setupShadow(e){let{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let n=this.shadowColorNode;if(n===null){let i=this.light.shadow.shadowNode,s;i!==void 0?s=ne(i):s=this.setupShadowNode(),this.shadowNode=s,this.shadowColorNode=n=this.colorNode.mul(s),this.baseColorNode=this.colorNode}e.context.getShadow&&(n=e.context.getShadow(this,e)),this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);let t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){let{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}},hT=P(({lightDistance:r,cutoffDistance:e,decayExponent:t})=>{let n=r.pow(t).max(.01).reciprocal();return e.greaterThan(0).select(n.mul(r.div(e).pow4().oneMinus().clamp().pow2()),n)}),JA=({color:r,lightVector:e,cutoffDistance:t,decayExponent:n})=>{let i=e.normalize(),s=e.length(),a=hT({lightDistance:s,cutoffDistance:t,decayExponent:n}),o=r.mul(a);return{lightDirection:i,lightColor:o}},hb=class extends qr{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=ie(0).setGroup(de),this.decayExponentNode=ie(2).setGroup(de)}update(e){let{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return ZA(this.light)}setupDirect(e){return JA({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}},qU=P(([r=Ye()])=>{let e=r.mul(2),t=e.x.floor(),n=e.y.floor();return t.add(n).mod(2).sign()}),$U=P(([r=Ye()],{renderer:e,material:t})=>{let n=fS(r.mul(2).sub(1)),i;if(t.alphaToCoverage&&e.currentSamples>0){let s=v(n.fwidth()).toVar();i=Oi(s.oneMinus(),s.add(1),n).oneMinus()}else i=On(n.greaterThan(1),0,1);return i}),Ah=P(([r,e,t])=>{let n=v(t).toVar(),i=v(e).toVar(),s=Bi(r).toVar();return On(s,i,n).uniformFlow()}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),Vm=P(([r,e])=>{let t=Bi(e).toVar(),n=v(r).toVar();return On(t,n.negate(),n).uniformFlow()}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),Ht=P(([r])=>{let e=v(r).toVar();return C(sr(e))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),wt=P(([r,e])=>{let t=v(r).toVar();return e.assign(Ht(t)),t.sub(v(e))}),XU=P(([r,e,t,n,i,s])=>{let a=v(s).toVar(),o=v(i).toVar(),l=v(n).toVar(),c=v(t).toVar(),u=v(e).toVar(),d=v(r).toVar(),h=v(Ie(1,o)).toVar();return Ie(1,a).mul(d.mul(h).add(u.mul(o))).add(a.mul(c.mul(h).add(l.mul(o))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),YU=P(([r,e,t,n,i,s])=>{let a=v(s).toVar(),o=v(i).toVar(),l=N(n).toVar(),c=N(t).toVar(),u=N(e).toVar(),d=N(r).toVar(),h=v(Ie(1,o)).toVar();return Ie(1,a).mul(d.mul(h).add(u.mul(o))).add(a.mul(c.mul(h).add(l.mul(o))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]}),QA=En([XU,YU]),jU=P(([r,e,t,n,i,s,a,o,l,c,u])=>{let d=v(u).toVar(),h=v(c).toVar(),p=v(l).toVar(),f=v(o).toVar(),m=v(a).toVar(),y=v(s).toVar(),x=v(i).toVar(),b=v(n).toVar(),_=v(t).toVar(),S=v(e).toVar(),M=v(r).toVar(),w=v(Ie(1,p)).toVar(),T=v(Ie(1,h)).toVar();return v(Ie(1,d)).toVar().mul(T.mul(M.mul(w).add(S.mul(p))).add(h.mul(_.mul(w).add(b.mul(p))))).add(d.mul(T.mul(x.mul(w).add(y.mul(p))).add(h.mul(m.mul(w).add(f.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),KU=P(([r,e,t,n,i,s,a,o,l,c,u])=>{let d=v(u).toVar(),h=v(c).toVar(),p=v(l).toVar(),f=N(o).toVar(),m=N(a).toVar(),y=N(s).toVar(),x=N(i).toVar(),b=N(n).toVar(),_=N(t).toVar(),S=N(e).toVar(),M=N(r).toVar(),w=v(Ie(1,p)).toVar(),T=v(Ie(1,h)).toVar();return v(Ie(1,d)).toVar().mul(T.mul(M.mul(w).add(S.mul(p))).add(h.mul(_.mul(w).add(b.mul(p))))).add(d.mul(T.mul(x.mul(w).add(y.mul(p))).add(h.mul(m.mul(w).add(f.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),eC=En([jU,KU]),ZU=P(([r,e,t])=>{let n=v(t).toVar(),i=v(e).toVar(),s=V(r).toVar(),a=V(s.bitAnd(V(7))).toVar(),o=v(Ah(a.lessThan(V(4)),i,n)).toVar(),l=v(xe(2,Ah(a.lessThan(V(4)),n,i))).toVar();return Vm(o,Bi(a.bitAnd(V(1)))).add(Vm(l,Bi(a.bitAnd(V(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),JU=P(([r,e,t,n])=>{let i=v(n).toVar(),s=v(t).toVar(),a=v(e).toVar(),o=V(r).toVar(),l=V(o.bitAnd(V(15))).toVar(),c=v(Ah(l.lessThan(V(8)),a,s)).toVar(),u=v(Ah(l.lessThan(V(4)),s,Ah(l.equal(V(12)).or(l.equal(V(14))),a,i))).toVar();return Vm(c,Bi(l.bitAnd(V(1)))).add(Vm(u,Bi(l.bitAnd(V(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),gn=En([ZU,JU]),QU=P(([r,e,t])=>{let n=v(t).toVar(),i=v(e).toVar(),s=ml(r).toVar();return N(gn(s.x,i,n),gn(s.y,i,n),gn(s.z,i,n))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),eO=P(([r,e,t,n])=>{let i=v(n).toVar(),s=v(t).toVar(),a=v(e).toVar(),o=ml(r).toVar();return N(gn(o.x,a,s,i),gn(o.y,a,s,i),gn(o.z,a,s,i))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),ns=En([QU,eO]),tO=P(([r])=>{let e=v(r).toVar();return xe(.6616,e)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),nO=P(([r])=>{let e=v(r).toVar();return xe(.982,e)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),iO=P(([r])=>{let e=N(r).toVar();return xe(.6616,e)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),tC=En([tO,iO]),sO=P(([r])=>{let e=N(r).toVar();return xe(.982,e)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),nC=En([nO,sO]),Ii=P(([r,e])=>{let t=C(e).toVar(),n=V(r).toVar();return n.shiftLeft(t).bitOr(n.shiftRight(C(32).sub(t)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),iC=P(([r,e,t])=>{r.subAssign(t),r.bitXorAssign(Ii(t,C(4))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(Ii(r,C(6))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Ii(e,C(8))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(Ii(t,C(16))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(Ii(r,C(19))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Ii(e,C(4))),e.addAssign(r)}),ip=P(([r,e,t])=>{let n=V(t).toVar(),i=V(e).toVar(),s=V(r).toVar();return n.bitXorAssign(i),n.subAssign(Ii(i,C(14))),s.bitXorAssign(n),s.subAssign(Ii(n,C(11))),i.bitXorAssign(s),i.subAssign(Ii(s,C(25))),n.bitXorAssign(i),n.subAssign(Ii(i,C(16))),s.bitXorAssign(n),s.subAssign(Ii(n,C(4))),i.bitXorAssign(s),i.subAssign(Ii(s,C(14))),n.bitXorAssign(i),n.subAssign(Ii(i,C(24))),n}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),Vn=P(([r])=>{let e=V(r).toVar();return v(e).div(v(V(C(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),or=P(([r])=>{let e=v(r).toVar();return e.mul(e).mul(e).mul(e.mul(e.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),rO=P(([r])=>{let e=C(r).toVar(),t=V(V(1)).toVar(),n=V(V(C(3735928559)).add(t.shiftLeft(V(2))).add(V(13))).toVar();return ip(n.add(V(e)),n,n)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),aO=P(([r,e])=>{let t=C(e).toVar(),n=C(r).toVar(),i=V(V(2)).toVar(),s=V().toVar(),a=V().toVar(),o=V().toVar();return s.assign(a.assign(o.assign(V(C(3735928559)).add(i.shiftLeft(V(2))).add(V(13))))),s.addAssign(V(n)),a.addAssign(V(t)),ip(s,a,o)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),oO=P(([r,e,t])=>{let n=C(t).toVar(),i=C(e).toVar(),s=C(r).toVar(),a=V(V(3)).toVar(),o=V().toVar(),l=V().toVar(),c=V().toVar();return o.assign(l.assign(c.assign(V(C(3735928559)).add(a.shiftLeft(V(2))).add(V(13))))),o.addAssign(V(s)),l.addAssign(V(i)),c.addAssign(V(n)),ip(o,l,c)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),lO=P(([r,e,t,n])=>{let i=C(n).toVar(),s=C(t).toVar(),a=C(e).toVar(),o=C(r).toVar(),l=V(V(4)).toVar(),c=V().toVar(),u=V().toVar(),d=V().toVar();return c.assign(u.assign(d.assign(V(C(3735928559)).add(l.shiftLeft(V(2))).add(V(13))))),c.addAssign(V(o)),u.addAssign(V(a)),d.addAssign(V(s)),iC(c,u,d),c.addAssign(V(i)),ip(c,u,d)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),cO=P(([r,e,t,n,i])=>{let s=C(i).toVar(),a=C(n).toVar(),o=C(t).toVar(),l=C(e).toVar(),c=C(r).toVar(),u=V(V(5)).toVar(),d=V().toVar(),h=V().toVar(),p=V().toVar();return d.assign(h.assign(p.assign(V(C(3735928559)).add(u.shiftLeft(V(2))).add(V(13))))),d.addAssign(V(c)),h.addAssign(V(l)),p.addAssign(V(o)),iC(d,h,p),d.addAssign(V(a)),h.addAssign(V(s)),ip(d,h,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]}),Ze=En([rO,aO,oO,lO,cO]),uO=P(([r,e])=>{let t=C(e).toVar(),n=C(r).toVar(),i=V(Ze(n,t)).toVar(),s=ml().toVar();return s.x.assign(i.bitAnd(C(255))),s.y.assign(i.shiftRight(C(8)).bitAnd(C(255))),s.z.assign(i.shiftRight(C(16)).bitAnd(C(255))),s}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),dO=P(([r,e,t])=>{let n=C(t).toVar(),i=C(e).toVar(),s=C(r).toVar(),a=V(Ze(s,i,n)).toVar(),o=ml().toVar();return o.x.assign(a.bitAnd(C(255))),o.y.assign(a.shiftRight(C(8)).bitAnd(C(255))),o.z.assign(a.shiftRight(C(16)).bitAnd(C(255))),o}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),is=En([uO,dO]),hO=P(([r])=>{let e=$(r).toVar(),t=C().toVar(),n=C().toVar(),i=v(wt(e.x,t)).toVar(),s=v(wt(e.y,n)).toVar(),a=v(or(i)).toVar(),o=v(or(s)).toVar(),l=v(QA(gn(Ze(t,n),i,s),gn(Ze(t.add(C(1)),n),i.sub(1),s),gn(Ze(t,n.add(C(1))),i,s.sub(1)),gn(Ze(t.add(C(1)),n.add(C(1))),i.sub(1),s.sub(1)),a,o)).toVar();return tC(l)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),pO=P(([r])=>{let e=N(r).toVar(),t=C().toVar(),n=C().toVar(),i=C().toVar(),s=v(wt(e.x,t)).toVar(),a=v(wt(e.y,n)).toVar(),o=v(wt(e.z,i)).toVar(),l=v(or(s)).toVar(),c=v(or(a)).toVar(),u=v(or(o)).toVar(),d=v(eC(gn(Ze(t,n,i),s,a,o),gn(Ze(t.add(C(1)),n,i),s.sub(1),a,o),gn(Ze(t,n.add(C(1)),i),s,a.sub(1),o),gn(Ze(t.add(C(1)),n.add(C(1)),i),s.sub(1),a.sub(1),o),gn(Ze(t,n,i.add(C(1))),s,a,o.sub(1)),gn(Ze(t.add(C(1)),n,i.add(C(1))),s.sub(1),a,o.sub(1)),gn(Ze(t,n.add(C(1)),i.add(C(1))),s,a.sub(1),o.sub(1)),gn(Ze(t.add(C(1)),n.add(C(1)),i.add(C(1))),s.sub(1),a.sub(1),o.sub(1)),l,c,u)).toVar();return nC(d)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]}),pT=En([hO,pO]),fO=P(([r])=>{let e=$(r).toVar(),t=C().toVar(),n=C().toVar(),i=v(wt(e.x,t)).toVar(),s=v(wt(e.y,n)).toVar(),a=v(or(i)).toVar(),o=v(or(s)).toVar(),l=N(QA(ns(is(t,n),i,s),ns(is(t.add(C(1)),n),i.sub(1),s),ns(is(t,n.add(C(1))),i,s.sub(1)),ns(is(t.add(C(1)),n.add(C(1))),i.sub(1),s.sub(1)),a,o)).toVar();return tC(l)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),mO=P(([r])=>{let e=N(r).toVar(),t=C().toVar(),n=C().toVar(),i=C().toVar(),s=v(wt(e.x,t)).toVar(),a=v(wt(e.y,n)).toVar(),o=v(wt(e.z,i)).toVar(),l=v(or(s)).toVar(),c=v(or(a)).toVar(),u=v(or(o)).toVar(),d=N(eC(ns(is(t,n,i),s,a,o),ns(is(t.add(C(1)),n,i),s.sub(1),a,o),ns(is(t,n.add(C(1)),i),s,a.sub(1),o),ns(is(t.add(C(1)),n.add(C(1)),i),s.sub(1),a.sub(1),o),ns(is(t,n,i.add(C(1))),s,a,o.sub(1)),ns(is(t.add(C(1)),n,i.add(C(1))),s.sub(1),a,o.sub(1)),ns(is(t,n.add(C(1)),i.add(C(1))),s,a.sub(1),o.sub(1)),ns(is(t.add(C(1)),n.add(C(1)),i.add(C(1))),s.sub(1),a.sub(1),o.sub(1)),l,c,u)).toVar();return nC(d)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),sp=En([fO,mO]),gO=P(([r])=>{let e=v(r).toVar(),t=C(Ht(e)).toVar();return Vn(Ze(t))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),yO=P(([r])=>{let e=$(r).toVar(),t=C(Ht(e.x)).toVar(),n=C(Ht(e.y)).toVar();return Vn(Ze(t,n))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),xO=P(([r])=>{let e=N(r).toVar(),t=C(Ht(e.x)).toVar(),n=C(Ht(e.y)).toVar(),i=C(Ht(e.z)).toVar();return Vn(Ze(t,n,i))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),_O=P(([r])=>{let e=J(r).toVar(),t=C(Ht(e.x)).toVar(),n=C(Ht(e.y)).toVar(),i=C(Ht(e.z)).toVar(),s=C(Ht(e.w)).toVar();return Vn(Ze(t,n,i,s))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]}),bO=En([gO,yO,xO,_O]),vO=P(([r])=>{let e=v(r).toVar(),t=C(Ht(e)).toVar();return N(Vn(Ze(t,C(0))),Vn(Ze(t,C(1))),Vn(Ze(t,C(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),SO=P(([r])=>{let e=$(r).toVar(),t=C(Ht(e.x)).toVar(),n=C(Ht(e.y)).toVar();return N(Vn(Ze(t,n,C(0))),Vn(Ze(t,n,C(1))),Vn(Ze(t,n,C(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),TO=P(([r])=>{let e=N(r).toVar(),t=C(Ht(e.x)).toVar(),n=C(Ht(e.y)).toVar(),i=C(Ht(e.z)).toVar();return N(Vn(Ze(t,n,i,C(0))),Vn(Ze(t,n,i,C(1))),Vn(Ze(t,n,i,C(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),MO=P(([r])=>{let e=J(r).toVar(),t=C(Ht(e.x)).toVar(),n=C(Ht(e.y)).toVar(),i=C(Ht(e.z)).toVar(),s=C(Ht(e.w)).toVar();return N(Vn(Ze(t,n,i,s,C(0))),Vn(Ze(t,n,i,s,C(1))),Vn(Ze(t,n,i,s,C(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]}),Wg=En([vO,SO,TO,MO]),Gm=P(([r,e,t,n])=>{let i=v(n).toVar(),s=v(t).toVar(),a=C(e).toVar(),o=N(r).toVar(),l=v(0).toVar(),c=v(1).toVar();return Xe(a,()=>{l.addAssign(c.mul(pT(o))),c.mulAssign(i),o.mulAssign(s)}),l}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),qg=P(([r,e,t,n])=>{let i=v(n).toVar(),s=v(t).toVar(),a=C(e).toVar(),o=N(r).toVar(),l=N(0).toVar(),c=v(1).toVar();return Xe(a,()=>{l.addAssign(c.mul(sp(o))),c.mulAssign(i),o.mulAssign(s)}),l}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),wO=P(([r,e,t,n])=>{let i=v(n).toVar(),s=v(t).toVar(),a=C(e).toVar(),o=N(r).toVar();return $(Gm(o,a,s,i),Gm(o.add(N(C(19),C(193),C(17))),a,s,i))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),EO=P(([r,e,t,n])=>{let i=v(n).toVar(),s=v(t).toVar(),a=C(e).toVar(),o=N(r).toVar(),l=N(qg(o,a,s,i)).toVar(),c=v(Gm(o.add(N(C(19),C(193),C(17))),a,s,i)).toVar();return J(l,c)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),RO=P(([r,e,t,n,i,s,a])=>{let o=C(a).toVar(),l=v(s).toVar(),c=C(i).toVar(),u=C(n).toVar(),d=C(t).toVar(),h=C(e).toVar(),p=$(r).toVar(),f=N(Wg($(h.add(u),d.add(c)))).toVar(),m=$(f.x,f.y).toVar();m.subAssign(.5),m.mulAssign(l),m.addAssign(.5);let y=$($(v(h),v(d)).add(m)).toVar(),x=$(y.sub(p)).toVar();return oe(o.equal(C(2)),()=>rt(x.x).add(rt(x.y))),oe(o.equal(C(3)),()=>At(rt(x.x),rt(x.y))),ls(x,x)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),AO=P(([r,e,t,n,i,s,a,o,l])=>{let c=C(l).toVar(),u=v(o).toVar(),d=C(a).toVar(),h=C(s).toVar(),p=C(i).toVar(),f=C(n).toVar(),m=C(t).toVar(),y=C(e).toVar(),x=N(r).toVar(),b=N(Wg(N(y.add(p),m.add(h),f.add(d)))).toVar();b.subAssign(.5),b.mulAssign(u),b.addAssign(.5);let _=N(N(v(y),v(m),v(f)).add(b)).toVar(),S=N(_.sub(x)).toVar();return oe(c.equal(C(2)),()=>rt(S.x).add(rt(S.y)).add(rt(S.z))),oe(c.equal(C(3)),()=>At(rt(S.x),rt(S.y),rt(S.z))),ls(S,S)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Au=En([RO,AO]),CO=P(([r,e,t])=>{let n=C(t).toVar(),i=v(e).toVar(),s=$(r).toVar(),a=C().toVar(),o=C().toVar(),l=$(wt(s.x,a),wt(s.y,o)).toVar(),c=v(1e6).toVar();return Xe({start:-1,end:C(1),name:"x",condition:"<="},({x:u})=>{Xe({start:-1,end:C(1),name:"y",condition:"<="},({y:d})=>{let h=v(Au(l,u,d,a,o,i,n)).toVar();c.assign(gi(c,h))})}),oe(n.equal(C(0)),()=>{c.assign(Qn(c))}),c}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),NO=P(([r,e,t])=>{let n=C(t).toVar(),i=v(e).toVar(),s=$(r).toVar(),a=C().toVar(),o=C().toVar(),l=$(wt(s.x,a),wt(s.y,o)).toVar(),c=$(1e6,1e6).toVar();return Xe({start:-1,end:C(1),name:"x",condition:"<="},({x:u})=>{Xe({start:-1,end:C(1),name:"y",condition:"<="},({y:d})=>{let h=v(Au(l,u,d,a,o,i,n)).toVar();oe(h.lessThan(c.x),()=>{c.y.assign(c.x),c.x.assign(h)}).ElseIf(h.lessThan(c.y),()=>{c.y.assign(h)})})}),oe(n.equal(C(0)),()=>{c.assign(Qn(c))}),c}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),PO=P(([r,e,t])=>{let n=C(t).toVar(),i=v(e).toVar(),s=$(r).toVar(),a=C().toVar(),o=C().toVar(),l=$(wt(s.x,a),wt(s.y,o)).toVar(),c=N(1e6,1e6,1e6).toVar();return Xe({start:-1,end:C(1),name:"x",condition:"<="},({x:u})=>{Xe({start:-1,end:C(1),name:"y",condition:"<="},({y:d})=>{let h=v(Au(l,u,d,a,o,i,n)).toVar();oe(h.lessThan(c.x),()=>{c.z.assign(c.y),c.y.assign(c.x),c.x.assign(h)}).ElseIf(h.lessThan(c.y),()=>{c.z.assign(c.y),c.y.assign(h)}).ElseIf(h.lessThan(c.z),()=>{c.z.assign(h)})})}),oe(n.equal(C(0)),()=>{c.assign(Qn(c))}),c}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),DO=P(([r,e,t])=>{let n=C(t).toVar(),i=v(e).toVar(),s=N(r).toVar(),a=C().toVar(),o=C().toVar(),l=C().toVar(),c=N(wt(s.x,a),wt(s.y,o),wt(s.z,l)).toVar(),u=v(1e6).toVar();return Xe({start:-1,end:C(1),name:"x",condition:"<="},({x:d})=>{Xe({start:-1,end:C(1),name:"y",condition:"<="},({y:h})=>{Xe({start:-1,end:C(1),name:"z",condition:"<="},({z:p})=>{let f=v(Au(c,d,h,p,a,o,l,i,n)).toVar();u.assign(gi(u,f))})})}),oe(n.equal(C(0)),()=>{u.assign(Qn(u))}),u}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),IO=En([CO,DO]),FO=P(([r,e,t])=>{let n=C(t).toVar(),i=v(e).toVar(),s=N(r).toVar(),a=C().toVar(),o=C().toVar(),l=C().toVar(),c=N(wt(s.x,a),wt(s.y,o),wt(s.z,l)).toVar(),u=$(1e6,1e6).toVar();return Xe({start:-1,end:C(1),name:"x",condition:"<="},({x:d})=>{Xe({start:-1,end:C(1),name:"y",condition:"<="},({y:h})=>{Xe({start:-1,end:C(1),name:"z",condition:"<="},({z:p})=>{let f=v(Au(c,d,h,p,a,o,l,i,n)).toVar();oe(f.lessThan(u.x),()=>{u.y.assign(u.x),u.x.assign(f)}).ElseIf(f.lessThan(u.y),()=>{u.y.assign(f)})})})}),oe(n.equal(C(0)),()=>{u.assign(Qn(u))}),u}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),LO=En([NO,FO]),BO=P(([r,e,t])=>{let n=C(t).toVar(),i=v(e).toVar(),s=N(r).toVar(),a=C().toVar(),o=C().toVar(),l=C().toVar(),c=N(wt(s.x,a),wt(s.y,o),wt(s.z,l)).toVar(),u=N(1e6,1e6,1e6).toVar();return Xe({start:-1,end:C(1),name:"x",condition:"<="},({x:d})=>{Xe({start:-1,end:C(1),name:"y",condition:"<="},({y:h})=>{Xe({start:-1,end:C(1),name:"z",condition:"<="},({z:p})=>{let f=v(Au(c,d,h,p,a,o,l,i,n)).toVar();oe(f.lessThan(u.x),()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(f)}).ElseIf(f.lessThan(u.y),()=>{u.z.assign(u.y),u.y.assign(f)}).ElseIf(f.lessThan(u.z),()=>{u.z.assign(f)})})})}),oe(n.equal(C(0)),()=>{u.assign(Qn(u))}),u}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),fT=En([PO,BO]),UO=P(([r,e,t,n,i,s,a,o,l,c,u])=>{let d=C(r).toVar(),h=$(e).toVar(),p=$(t).toVar(),f=$(n).toVar(),m=v(i).toVar(),y=v(s).toVar(),x=v(a).toVar(),b=Bi(o).toVar(),_=C(l).toVar(),S=v(c).toVar(),M=v(u).toVar(),w=h.mul(p).add(f),T=v(0).toVar();return oe(d.equal(C(0)),()=>{T.assign(sp(w))}),oe(d.equal(C(1)),()=>{T.assign(Wg(w))}),oe(d.equal(C(2)),()=>{T.assign(fT(w,m,C(0)))}),oe(d.equal(C(3)),()=>{T.assign(qg(N(w,0),_,S,M))}),T.assign(T.mul(x.sub(y)).add(y)),oe(b,()=>{T.assign(Ns(T,y,x))}),T}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),OO=P(([r,e,t,n,i,s,a,o,l,c,u])=>{let d=C(r).toVar(),h=N(e).toVar(),p=N(t).toVar(),f=N(n).toVar(),m=v(i).toVar(),y=v(s).toVar(),x=v(a).toVar(),b=Bi(o).toVar(),_=C(l).toVar(),S=v(c).toVar(),M=v(u).toVar(),w=h.mul(p).add(f),T=v(0).toVar();return oe(d.equal(C(0)),()=>{T.assign(sp(w))}),oe(d.equal(C(1)),()=>{T.assign(Wg(w))}),oe(d.equal(C(2)),()=>{T.assign(fT(w,m,C(0)))}),oe(d.equal(C(3)),()=>{T.assign(qg(w,_,S,M))}),T.assign(T.mul(x.sub(y)).add(y)),oe(b,()=>{T.assign(Ns(T,y,x))}),T}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),kO=P(([r])=>{let e=r.y,t=r.z,n=N().toVar();return oe(e.lessThan(1e-4),()=>{n.assign(N(t,t,t))}).Else(()=>{let i=r.x;i=i.sub(sr(i)).mul(6).toVar();let s=C(uS(i)),a=i.sub(v(s)),o=t.mul(e.oneMinus()),l=t.mul(e.mul(a).oneMinus()),c=t.mul(e.mul(a.oneMinus()).oneMinus());oe(s.equal(C(0)),()=>{n.assign(N(t,c,o))}).ElseIf(s.equal(C(1)),()=>{n.assign(N(l,t,o))}).ElseIf(s.equal(C(2)),()=>{n.assign(N(o,t,c))}).ElseIf(s.equal(C(3)),()=>{n.assign(N(o,l,t))}).ElseIf(s.equal(C(4)),()=>{n.assign(N(c,o,t))}).Else(()=>{n.assign(N(t,o,l))})}),n}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),VO=P(([r])=>{let e=N(r).toVar(),t=v(e.x).toVar(),n=v(e.y).toVar(),i=v(e.z).toVar(),s=v(gi(t,gi(n,i))).toVar(),a=v(At(t,At(n,i))).toVar(),o=v(a.sub(s)).toVar(),l=v().toVar(),c=v().toVar(),u=v().toVar();return u.assign(a),oe(a.greaterThan(0),()=>{c.assign(o.div(a))}).Else(()=>{c.assign(0)}),oe(c.lessThanEqual(0),()=>{l.assign(0)}).Else(()=>{oe(t.greaterThanEqual(a),()=>{l.assign(n.sub(i).div(o))}).ElseIf(n.greaterThanEqual(a),()=>{l.assign(Wt(2,i.sub(t).div(o)))}).Else(()=>{l.assign(Wt(4,t.sub(n).div(o)))}),l.mulAssign(1/6),oe(l.lessThan(0),()=>{l.addAssign(1)})}),N(l,c,u)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),GO=P(([r])=>{let e=N(r).toVar(),t=Yv(tS(e,N(.04045))).toVar(),n=N(e.div(12.92)).toVar(),i=N(ss(At(e.add(N(.055)),N(0)).div(1.055),N(2.4))).toVar();return Re(n,i,t)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),sC=(r,e)=>{r=v(r),e=v(e);let t=$(e.dFdx(),e.dFdy()).length().mul(.7071067811865476);return Oi(r.sub(t),r.add(t),e)},rC=(r,e,t,n)=>Re(r,e,t[n].clamp()),zO=(r,e,t=Ye())=>rC(r,e,t,"x"),HO=(r,e,t=Ye())=>rC(r,e,t,"y"),WO=(r,e,t,n,i=Ye())=>{let s=i.x.clamp(),a=i.y.clamp(),o=Re(r,e,s),l=Re(t,n,s);return Re(o,l,a)},aC=(r,e,t,n,i)=>Re(r,e,sC(t,n[i])),qO=(r,e,t,n=Ye())=>aC(r,e,t,n,"x"),$O=(r,e,t,n=Ye())=>aC(r,e,t,n,"y"),XO=(r=1,e=0,t=Ye())=>t.mul(r).add(e),YO=(r,e=1)=>(r=v(r),r.abs().pow(e).mul(r.sign())),jO=(r,e=1,t=.5)=>v(r).sub(t).mul(e).add(t),KO=(r=Ye(),e=1,t=0)=>pT(r.convert("vec2|vec3")).mul(e).add(t),ZO=(r=Ye(),e=1,t=0)=>sp(r.convert("vec2|vec3")).mul(e).add(t),JO=(r=Ye(),e=1,t=0)=>(r=r.convert("vec2|vec3"),J(sp(r),pT(r.add($(19,73)))).mul(e).add(t)),QO=(r,e=Ye(),t=$(1,1),n=$(0,0),i=1,s=0,a=1,o=!1,l=1,c=2,u=.5)=>UO(r,e.convert("vec2|vec3"),t,n,i,s,a,o,l,c,u),ek=(r,e=Ye(),t=$(1,1),n=$(0,0),i=1,s=0,a=1,o=!1,l=1,c=2,u=.5)=>OO(r,e.convert("vec2|vec3"),t,n,i,s,a,o,l,c,u),tk=(r=Ye(),e=1)=>IO(r.convert("vec2|vec3"),e,C(1)),nk=(r=Ye(),e=1)=>LO(r.convert("vec2|vec3"),e,C(1)),ik=(r=Ye(),e=1)=>fT(r.convert("vec2|vec3"),e,C(1)),sk=(r=Ye())=>bO(r.convert("vec2|vec3")),rk=(r=Ye(),e=3,t=2,n=.5,i=1)=>Gm(r,C(e),t,n).mul(i),ak=(r=Ye(),e=3,t=2,n=.5,i=1)=>wO(r,C(e),t,n).mul(i),ok=(r=Ye(),e=3,t=2,n=.5,i=1)=>qg(r,C(e),t,n).mul(i),lk=(r=Ye(),e=3,t=2,n=.5,i=1)=>EO(r,C(e),t,n).mul(i),ck=(r,e=v(0))=>Wt(r,e),uk=(r,e=v(0))=>Ie(r,e),dk=(r,e=v(1))=>xe(r,e),hk=(r,e=v(1))=>Ui(r,e),pk=(r,e=v(1))=>Tg(r,e),fk=(r,e=v(1))=>ss(r,e),mk=(r=v(0),e=v(1))=>rS(r,e),gk=()=>Ru,yk=()=>yA,xk=(r,e=v(1))=>Ie(e,r),_k=(r,e,t,n)=>r.greaterThan(e).mix(t,n),bk=(r,e,t,n)=>r.greaterThanEqual(e).mix(t,n),vk=(r,e,t,n)=>r.equal(e).mix(t,n),Sk=(r,e=null)=>{if(typeof e=="string"){let t={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},n=e.replace(/^out/,"").toLowerCase();if(t[n]!==void 0)return r.element(t[n])}if(typeof e=="number")return r.element(e);if(typeof e=="string"&&e.length===1){let t={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(t[e]!==void 0)return r.element(t[e])}return r},Tk=(r,e=$(.5,.5),t=$(1,1),n=v(0),i=$(0,0))=>{let s=r;if(e&&(s=s.sub(e)),t&&(s=s.mul(t)),n){let a=n.mul(Math.PI/180),o=a.cos(),l=a.sin();s=$(s.x.mul(o).sub(s.y.mul(l)),s.x.mul(l).add(s.y.mul(o)))}return e&&(s=s.add(e)),i&&(s=s.add(i)),s},Mk=(r,e)=>{r=$(r),e=v(e);let t=e.mul(Math.PI/180);return tp(r,t)},wk=(r,e,t)=>{r=N(r),e=v(e),t=N(t);let n=e.mul(Math.PI/180),i=t.normalize(),s=n.cos(),a=n.sin(),o=v(1).sub(s);return r.mul(s).add(i.cross(r).mul(a)).add(i.mul(i.dot(r)).mul(o))},Ek=(r,e)=>(r=N(r),e=v(e),LS(r,e)),Rk=P(([r,e,t])=>{let n=kn(r).toVar(),i=Ie(v(.5).mul(e.sub(t)),ar).div(n).toVar(),s=Ie(v(-.5).mul(e.sub(t)),ar).div(n).toVar(),a=N().toVar();a.x=n.x.greaterThan(v(0)).select(i.x,s.x),a.y=n.y.greaterThan(v(0)).select(i.y,s.y),a.z=n.z.greaterThan(v(0)).select(i.z,s.z);let o=gi(a.x,a.y,a.z).toVar();return ar.add(n.mul(o)).toVar().sub(t)}),oC=P(([r,e])=>{let t=r.x,n=r.y,i=r.z,s=e.element(0).mul(.886227);return s=s.add(e.element(1).mul(2*.511664).mul(n)),s=s.add(e.element(2).mul(2*.511664).mul(i)),s=s.add(e.element(3).mul(2*.511664).mul(t)),s=s.add(e.element(4).mul(2*.429043).mul(t).mul(n)),s=s.add(e.element(5).mul(2*.429043).mul(n).mul(i)),s=s.add(e.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),s=s.add(e.element(7).mul(2*.429043).mul(t).mul(i)),s=s.add(e.element(8).mul(.429043).mul(xe(t,t).sub(xe(n,n)))),s}),g=Object.freeze({__proto__:null,BRDF_GGX:ZS,BRDF_Lambert:dl,BasicPointShadowFilter:jA,BasicShadowFilter:GA,Break:VR,Const:dE,Continue:kI,DFGLUT:Oh,D_GGX:QR,Discard:EE,EPSILON:Mg,F_Schlick:bu,Fn:P,HALF_PI:ID,INFINITY:ND,If:oe,Loop:Xe,NodeAccess:Mn,NodeShaderStage:iu,NodeType:cD,NodeUpdateType:pe,OnBeforeFrameUpdate:II,OnBeforeMaterialUpdate:DI,OnBeforeObjectUpdate:PI,OnFrameUpdate:DR,OnMaterialUpdate:NI,OnObjectUpdate:ep,PCFShadowFilter:zA,PCFSoftShadowFilter:HA,PI:hm,PI2:PD,PointShadowFilter:KA,Return:WD,Schlick_to_F0:l_,ShaderNode:au,Stack:_g,Switch:MD,TBNViewMatrix:Zo,TWO_PI:DD,VSMShadowFilter:WA,V_GGX_SmithCorrelated:JR,Var:uE,VarIntent:hE,abs:rt,acesFilmicToneMapping:RA,acos:sS,acosh:Vw,add:Wt,addMethodChaining:F,addNodeElement:qD,agxToneMapping:AA,all:Nw,alphaT:om,ambientOcclusion:dx,and:gw,anisotropy:Ga,anisotropyB:el,anisotropyT:Th,any:Pw,append:ED,array:lw,asin:Ow,asinh:kw,assign:cw,atan:rS,atanh:Gw,atomicAdd:ZB,atomicAnd:tU,atomicFunc:mr,atomicLoad:jB,atomicMax:QB,atomicMin:eU,atomicOr:nU,atomicStore:KB,atomicSub:JB,atomicXor:iU,attenuationColor:Qv,attenuationDistance:Jv,attribute:Li,attributeArray:nB,backgroundBlurriness:bA,backgroundIntensity:Z_,backgroundRotation:vA,batch:BR,batchColor:HS,bentNormalView:nR,billboarding:WL,bitAnd:bw,bitNot:vw,bitOr:Sw,bitXor:Tw,bitangentGeometry:SI,bitangentLocal:TI,bitangentView:eR,bitangentWorld:MI,bitcast:mA,blendBurn:hB,blendColor:gB,blendDodge:pB,blendOverlay:mB,blendScreen:fB,blur:rA,bool:Bi,buffer:wu,bufferAttribute:bS,builtin:Yr,builtinAOContext:lE,builtinShadowContext:oE,bumpMap:LS,bvec2:nw,bvec3:Yv,bvec4:iw,bypass:ME,cache:TE,call:uw,cameraFar:Wa,cameraIndex:io,cameraNear:Ha,cameraNormalMatrix:QD,cameraPosition:DE,cameraProjectionMatrix:Jn,cameraProjectionMatrixInverse:PE,cameraViewMatrix:so,cameraViewport:eI,cameraWorldMatrix:Qh,cbrt:tE,cdl:vB,ceil:Eg,checker:qU,cineonToneMapping:EA,clamp:Ns,clearcoat:sm,clearcoatNormalView:qa,clearcoatRoughness:lu,clipSpace:LE,code:Gg,color:tw,colorSpaceToWorking:Ag,colorToDirection:RI,compute:SE,computeKernel:SS,computeSkinning:OI,context:Xr,convert:rw,convertColorSpace:UD,convertToTexture:JL,cos:ws,cosh:Lw,countLeadingZeros:vL,countOneBits:SL,countTrailingZeros:bL,cross:Wr,cubeTexture:Zn,cubeTextureBase:IS,dFdx:lS,dFdy:cS,dashSize:tl,debug:AE,decrement:Cw,decrementBefore:Rw,defaultBuildStages:jf,defaultShaderStages:KM,defined:fu,degrees:Iw,deltaTime:BL,densityFogFactor:DA,depth:YS,depthPass:EB,determinant:$w,difference:Kw,diffuseColor:$e,diffuseContribution:Xo,directPointLight:JA,directionToColor:EI,directionToFaceDirection:pI,dispersion:eS,disposeShadowMaterial:$A,distance:jw,div:Ui,dot:ls,drawIndex:vE,dynamicBufferAttribute:VD,element:sw,emissive:ux,equal:dw,equirectDirection:i_,equirectUV:jS,exp:nS,exp2:mu,exponentialHeightFogFactor:UB,expression:Fi,faceDirection:NS,faceForward:gS,faceforward:FD,float:v,floatBitsToInt:yL,floatBitsToUint:gA,floor:sr,fog:sb,fract:Cs,frameGroup:AD,frameId:yA,frontFacing:BE,fwidth:dS,gain:ML,gapSize:Dh,getConstNodeType:ew,getCurrentStack:qv,getDirection:iA,getDistanceAttenuation:hT,getGeometryRoughness:ZR,getNormalFromDepth:eB,getParallaxCorrectNormal:Rk,getRoughness:KS,getScreenPosition:QL,getShIrradianceAt:oC,getShadowMaterial:qA,getShadowRenderObjectFunction:XA,getTextureIndex:pA,getViewPosition:ru,ggxConvolution:aA,globalId:GB,glsl:FB,glslFn:LB,grayscale:yB,greaterThan:tS,greaterThanEqual:mw,hash:TL,highpModelNormalViewMatrix:Px,highpModelViewMatrix:Nx,hue:bB,increment:Aw,incrementBefore:Ew,inspector:CE,instance:FR,instanceColor:zS,instanceIndex:As,instancedArray:iB,instancedBufferAttribute:Ng,instancedDynamicBufferAttribute:vS,instancedMesh:LR,int:C,intBitsToFloat:xL,interleavedGradientNoise:eT,inverse:Xw,inverseSqrt:iS,inversesqrt:LD,invocationLocalIndex:HD,invocationSubgroupIndex:zD,ior:Mh,iridescence:vg,iridescenceIOR:rm,iridescenceThickness:am,isolate:du,ivec2:Rt,ivec3:Xv,ivec4:jv,js:DB,label:cE,length:rr,lengthSq:fS,lessThan:pw,lessThanEqual:fw,lightPosition:rT,lightProjectionUV:IA,lightShadowMatrix:Hg,lightTargetDirection:oT,lightTargetPosition:FA,lightViewPosition:aT,lightingContext:zR,lights:FU,linearDepth:vm,linearToneMapping:MA,localId:zB,log:wg,log2:ir,logarithmicDepthToViewZ:WI,luminance:nT,mat2:bg,mat3:yn,mat4:ja,matcapUV:oA,materialAO:NR,materialAlphaTest:sR,materialAnisotropy:_R,materialAnisotropyVector:su,materialAttenuationColor:RR,materialAttenuationDistance:ER,materialClearcoat:pR,materialClearcoatNormal:mR,materialClearcoatRoughness:fR,materialColor:rR,materialDispersion:CR,materialEmissive:oR,materialEnvIntensity:Zf,materialEnvRotation:ym,materialIOR:wR,materialIridescence:bR,materialIridescenceIOR:vR,materialIridescenceThickness:SR,materialLightMap:GS,materialLineDashOffset:VS,materialLineDashSize:OS,materialLineGapSize:kS,materialLineScale:US,materialLineWidth:xm,materialMetalness:dR,materialNormal:hR,materialOpacity:BS,materialPointSize:AR,materialReference:Vr,materialReflectivity:Jf,materialRefractionRatio:kE,materialRotation:gR,materialRoughness:uR,materialSheen:yR,materialSheenRoughness:xR,materialShininess:aR,materialSpecular:lR,materialSpecularColor:cR,materialSpecularIntensity:zx,materialSpecularStrength:wh,materialThickness:MR,materialTransmission:TR,max:At,maxMipLevel:wS,mediumpModelViewMatrix:FE,metalness:zr,min:gi,mix:Re,mixElement:iE,mod:Tg,modelDirection:oI,modelNormalMatrix:IE,modelPosition:lI,modelRadius:dI,modelScale:cI,modelViewMatrix:cr,modelViewPosition:uI,modelViewProjection:PR,modelWorldMatrix:rs,modelWorldMatrixInverse:hI,morphReference:GR,mrt:fA,mul:xe,mx_aastep:sC,mx_add:ck,mx_atan2:mk,mx_cell_noise_float:sk,mx_contrast:jO,mx_divide:hk,mx_fractal_noise_float:rk,mx_fractal_noise_vec2:ak,mx_fractal_noise_vec3:ok,mx_fractal_noise_vec4:lk,mx_frame:yk,mx_heighttonormal:Ek,mx_hsvtorgb:kO,mx_ifequal:vk,mx_ifgreater:_k,mx_ifgreatereq:bk,mx_invert:xk,mx_modulo:pk,mx_multiply:dk,mx_noise_float:KO,mx_noise_vec3:ZO,mx_noise_vec4:JO,mx_place2d:Tk,mx_power:fk,mx_ramp4:WO,mx_ramplr:zO,mx_ramptb:HO,mx_rgbtohsv:VO,mx_rotate2d:Mk,mx_rotate3d:wk,mx_safepower:YO,mx_separate:Sk,mx_splitlr:qO,mx_splittb:$O,mx_srgb_texture_to_lin_rec709:GO,mx_subtract:uk,mx_timer:gk,mx_transform_uv:XO,mx_unifiednoise2d:QO,mx_unifiednoise3d:ek,mx_worley_noise_float:tk,mx_worley_noise_vec2:nk,mx_worley_noise_vec3:ik,negate:oS,negateOnBackSide:xl,neutralToneMapping:CA,nodeArray:Qo,nodeImmutable:Y,nodeObject:ne,nodeObjectIntent:_h,nodeObjects:xg,nodeProxy:Me,nodeProxyConstructor:Wv,nodeProxyIntent:H,normalFlat:UE,normalGeometry:Dg,normalLocal:Gn,normalMap:Vx,normalView:Be,normalViewGeometry:gu,normalWorld:ro,normalWorldGeometry:OE,normalize:kn,not:xw,notEqual:hw,numWorkgroups:kB,objectDirection:tI,objectGroup:ow,objectPosition:iI,objectRadius:aI,objectScale:sI,objectViewPosition:rI,objectWorldMatrix:nI,oneMinus:zw,or:yw,orthographicDepthToViewZ:WR,oscSawtooth:VL,oscSine:UL,oscSquare:OL,oscTriangle:kL,output:cu,outputStruct:fL,overloadingFn:En,overrideNode:dA,overrideNodes:hA,packHalf2x16:CL,packNormalToRGB:FS,packSnorm2x16:RL,packUnorm2x16:AL,parabola:G_,parallaxDirection:tR,parallaxUV:wI,parameter:dL,pass:MB,passTexture:wB,pcurve:wL,perspectiveDepthToViewZ:Bg,pmremTexture:QS,pointShadow:ZA,pointUV:sB,pointWidth:RD,positionGeometry:Bn,positionLocal:Mt,positionPrevious:ul,positionView:Ot,positionViewDirection:Qe,positionWorld:ar,positionWorldDirection:CS,posterize:SB,pow:ss,pow2:hS,pow3:Zw,pow4:pS,premultiplyAlpha:MS,property:$r,quadBroadcast:AU,quadSwapDiagonal:SU,quadSwapX:bU,quadSwapY:vU,radians:Dw,rand:nE,range:OB,rangeFogFactor:PA,reciprocal:Ww,reference:dt,referenceBuffer:qE,reflect:Yw,reflectVector:zE,reflectView:VE,reflector:jL,refract:mS,refractVector:HE,refractView:GE,reinhardToneMapping:wA,remap:TS,remapClamp:wE,renderGroup:de,renderOutput:Pg,rendererReference:yE,replaceDefaultUV:GL,rotate:tp,rotateUV:zL,roughness:tr,round:Hw,rtt:_A,sRGBTransferEOTF:fE,sRGBTransferOETF:mE,sample:tB,sampler:jD,samplerComparison:KD,saturate:Rg,saturation:xB,screenCoordinate:yl,screenDPR:RS,screenSize:cl,screenUV:Rs,select:On,setCurrentStack:Ph,setName:yS,shaderStages:Kf,shadow:YA,shadowPositionWorld:lT,shapeCircle:$U,sharedUniformGroup:Sg,sheen:Di,sheenRoughness:za,shiftLeft:Mw,shiftRight:ww,shininess:lm,sign:aS,sin:Kn,sinc:EL,sinh:Fw,skinning:kR,smoothstep:Oi,smoothstepElement:sE,specularColor:Ja,specularColorBlended:jo,specularF90:Ko,spherizeUV:HL,split:wD,spritesheetUV:$L,sqrt:Qn,stack:em,step:ol,stepElement:rE,storage:Ka,storageBarrier:qB,storageTexture:SA,storageTexture3D:aB,struct:pL,sub:Ie,subBuild:nl,subgroupAdd:aU,subgroupAll:yU,subgroupAnd:hU,subgroupAny:xU,subgroupBallot:rU,subgroupBroadcast:TU,subgroupBroadcastFirst:_U,subgroupElect:sU,subgroupExclusiveAdd:lU,subgroupExclusiveMul:dU,subgroupInclusiveAdd:oU,subgroupInclusiveMul:uU,subgroupIndex:GD,subgroupMax:gU,subgroupMin:mU,subgroupMul:cU,subgroupOr:pU,subgroupShuffle:MU,subgroupShuffleDown:RU,subgroupShuffleUp:EU,subgroupShuffleXor:wU,subgroupSize:HB,subgroupXor:fU,tan:Bw,tangentGeometry:Ig,tangentLocal:Qa,tangentView:Fg,tangentWorld:QE,tanh:Uw,texture:Ue,texture3D:tT,texture3DLevel:cB,texture3DLoad:lB,textureBarrier:$B,textureBicubic:yF,textureBicubicLevel:JS,textureCubeUV:sA,textureLevel:YD,textureLoad:Ut,textureSize:ll,textureStore:rB,thickness:Zv,time:Ru,toneMapping:xE,toneMappingExposure:_E,toonOutlinePass:RB,transformDirection:Jw,transformNormal:PS,transformNormalByInverseViewMatrix:eE,transformNormalByViewMatrix:Qw,transformNormalToView:DS,transformedClearcoatNormalView:gI,transformedNormalView:fI,transformedNormalWorld:mI,transmission:cm,transpose:qw,triNoise3D:FL,triplanarTexture:XL,triplanarTextures:xA,trunc:uS,uint:V,uintBitsToFloat:_L,uniform:ie,uniformArray:Tn,uniformCubeTexture:yI,uniformFlow:aE,uniformGroup:aw,uniformTexture:XD,unpackHalf2x16:DL,unpackNormal:Ox,unpackRGBToNormal:iR,unpackSnorm2x16:NL,unpackUnorm2x16:PL,unpremultiplyAlpha:RE,userData:uB,uv:Ye,uvec2:$v,uvec3:ml,uvec4:Kv,varying:no,varyingProperty:gl,vec2:$,vec3:N,vec4:J,vectorComponents:fl,velocity:dB,vertexColor:XR,vertexIndex:bE,vertexStage:pE,vibrance:_B,viewZToLogarithmicDepth:Ug,viewZToOrthographicDepth:il,viewZToPerspectiveDepth:XS,viewZToReversedOrthographicDepth:HI,viewZToReversedPerspectiveDepth:qR,viewport:pu,viewportCoordinate:NE,viewportDepthTexture:$S,viewportLinearDepth:qI,viewportMipTexture:qS,viewportOpaqueMipTexture:HR,viewportResolution:JD,viewportSafeUV:qL,viewportSharedTexture:TB,viewportSize:AS,viewportTexture:GI,viewportUV:ZD,vogelDiskSample:Es,wgsl:IB,wgslFn:BB,workgroupArray:XB,workgroupBarrier:WB,workgroupId:VB,workingToColorSpace:gE,xor:_w}),Ts=new Gh,pb=class extends hr{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){let i=this.renderer,s=this.nodes.getBackgroundNode(e)||e.background,a=!1;if(s===null)i._clearColor.getRGB(Ts),Ts.a=i._clearColor.a;else if(s.isColor===!0)s.getRGB(Ts),Ts.a=1,a=!0;else if(s.isNode===!0){let l=this.get(e),c=s;Ts.copy(i._clearColor);let u=l.backgroundMesh;if(u===void 0){let _=function(){s.removeEventListener("dispose",_),u.material.dispose(),u.geometry.dispose()},h=J(c).mul(Z_).context({getUV:()=>vA.mul(OE),getTextureLevel:()=>bA}),p=Jn.element(3).element(3).equal(1),f=Ui(1,Jn.element(1).element(1)).mul(3),m=p.select(Mt.mul(f),Mt),y=cr.mul(J(m,0)),x=Jn.mul(J(y.xyz,1));x=x.setZ(x.w);let b=new We;b.name="Background.material",b.side=ln,b.depthTest=!1,b.depthWrite=!1,b.allowOverride=!1,b.fog=!1,b.lights=!1,b.vertexNode=x,b.colorNode=h,l.backgroundMeshNode=h,l.backgroundMesh=u=new De(new ld(1,32,32),b),u.frustumCulled=!1,u.name="Background.mesh",s.addEventListener("dispose",_)}let d=c.getCacheKey();l.backgroundCacheKey!==d&&(l.backgroundMeshNode.node=J(c).mul(Z_),l.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,l.backgroundCacheKey=d),t.unshift(u,u.geometry,u.material,0,0,null,null)}else G("Renderer: Unsupported background configuration.",s);let o=i.xr.getEnvironmentBlendMode();if(o==="additive"?Ts.set(0,0,0,1):o==="alpha-blend"&&Ts.set(0,0,0,0),i.autoClear===!0||a===!0){let l=n.clearColorValue;l.r=Ts.r,l.g=Ts.g,l.b=Ts.b,l.a=Ts.a,(i.backend.isWebGLBackend===!0||i.alpha===!0)&&(l.r*=l.a,l.g*=l.a,l.b*=l.a),n.depthClearValue=i.getClearDepth(),n.stencilClearValue=i.getClearStencil(),n.clearColor=i.autoClearColor===!0,n.clearDepth=i.autoClearDepth===!0,n.clearStencil=i.autoClearStencil===!0}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}},Ak=0,qh=class{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=Ak++}},fb=class{constructor(e,t,n,i,s,a,o,l,c,u,d=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=d,this.nodeAttributes=i,this.bindings=s,this.updateNodes=a,this.updateBeforeNodes=o,this.updateAfterNodes=l,this.observer=c,this.hardwareClipping=u,this.usedTimes=0}createBindings(){let e=[];for(let t of this.bindings)if(t.bindings[0].groupNode.shared!==!0){let i=new qh(t.name,[]);e.push(i);for(let s of t.bindings)i.bindings.push(s.clone())}else e.push(t);return e}},zm=class{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}},mb=class{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}},Hm=class{constructor(e,t,n=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=i}},gb=class extends Hm{constructor(e,t,n=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=i}},yb=class{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}},Ck=0,Ch=class{constructor(e=null){this.id=Ck++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return t===void 0&&this.parent!==null&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}},xb=class{constructor(e,t){this.name=e,this.members=t,this.output=!1}},fr=class{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}},_b=class extends fr{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}},bb=class extends fr{constructor(e,t=new O){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}},vb=class extends fr{constructor(e,t=new E){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}},Sb=class extends fr{constructor(e,t=new Ge){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}},Tb=class extends fr{constructor(e,t=new me){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}},Mb=class extends fr{constructor(e,t=new dc){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}},wb=class extends fr{constructor(e,t=new ve){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}},Eb=class extends fr{constructor(e,t=new Ne){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}},Rb=class extends _b{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},Ab=class extends bb{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},Cb=class extends vb{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},Nb=class extends Sb{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},Pb=class extends Tb{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},Db=class extends Mb{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},Ib=class extends wb{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},Fb=class extends Eb{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},Nk=0,yM=new WeakMap,xM=new WeakMap,Pk=new WeakMap,Dk=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Ff=r=>/e/g.test(r)?String(r).replace(/+/g,""):(r=Number(r),r+(r%1?"":".0")),lC=r=>{if(r.writeUsageCount>0)return!0;if(r.subBuildsCache!==void 0){for(let e in r.subBuildsCache)if(lC(r.subBuildsCache[e]))return!0}return!1},Wm=class{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=new Set,this.sequentialNodes=new Set,this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.hardwareClipping=!1,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=em(),this.stacks=[],this.tab=" ",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Ch,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:Nk++})}isFlatShading(){return this.material.flatShading===!0||this.geometry.hasAttribute("normal")===!1}isOpaque(){let e=this.material;return e.transparent===!1&&e.blending===li&&e.alphaToCoverage===!1}createRenderTarget(e,t,n){return new Jt(e,t,n)}createCubeRenderTarget(e,t){return new Sm(e,t)}includes(e){return this.nodes.has(e)}getOutputType(e=0){let t="vec4",n=this.renderer.getRenderTarget();if(n!==null){let i=n.textures[e].type,s=n.textures[e].format,a="vec";i===zt?a="ivec":i===it&&(a="uvec"),s===Da||s===Ia?i===zt?t="int":i===it?t="uint":t="float":s===mi||s===Fa?t=`${a}2`:s===Pa||s===Yd?t=`${a}3`:t=`${a}4`}return t}getOutputStructName(){}_getBindGroup(e,t){let n=t[0].groupNode,i=n.shared;if(i)for(let a=1;a<t.length;a++)n!==t[a].groupNode&&(i=!1);let s;if(i){let a="";for(let u of t)if(u.isNodeUniformsGroup){u.uniforms.sort((d,h)=>d.nodeUniform.node.id-h.nodeUniform.node.id);for(let d of u.uniforms)a+=d.nodeUniform.node.id}else a+=u.nodeUniform.id;let o=this.renderer._currentRenderContext||this.renderer,l=yM.get(o);l===void 0&&(l=new Map,yM.set(o,l));let c=Mu(a);s=l.get(c),s===void 0&&(s=new qh(e,t),l.set(c,s))}else s=new qh(e,t);return s}getBindGroupArray(e,t){let n=this.bindings[t],i=n[e];return i===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(e===null){let t={},n=this.bindings;for(let i of Kf)for(let s in n[i]){let a=n[i][s],o=t[s]||(t[s]=[]);for(let l of a)o.includes(l)===!1&&o.push(l)}e=[];for(let i in t){let s=t[i],a=this._getBindGroup(i,s);e.push(a)}this.bindGroups=e}return e}sortBindingGroups(){let e=this.getBindings();e.sort((t,n)=>t.bindings[0].groupNode.order-n.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){let n=e[t];this.bindingsIndexes[n.name].group=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){this.nodes.has(e)===!1&&(this.nodes.add(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){let t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();(t!==pe.NONE||n!==pe.NONE)&&this.sequentialNodes.add(e)}buildUpdateNodes(){for(let e of this.nodes)e.getUpdateType()!==pe.NONE&&this.updateNodes.push(e);for(let e of this.sequentialNodes){let t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();t!==pe.NONE&&this.updateBeforeNodes.push(e),n!==pe.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===St||e.magFilter===Wd||e.magFilter===Na||e.magFilter===bs||e.minFilter===St||e.minFilter===Wd||e.minFilter===Na||e.minFilter===bs}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("THREE.NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){let t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){let e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){let n=this.getDataFromNode(e);return n.cache===void 0&&(n.cache=new Ch(t?this.getCache():null)),n.cache}isAvailable(){return!1}getVertexIndex(){X("Abstract function.")}getInstanceIndex(){X("Abstract function.")}getDrawIndex(){X("Abstract function.")}getFrontFacing(){X("Abstract function.")}getFragCoord(){X("Abstract function.")}isFlipY(){return!1}isContextAssign(){return this.context.assign===!0}increaseUsage(e){let t=this.getDataFromNode(e);return t.usageCount=t.usageCount===void 0?1:t.usageCount+1,this.isContextAssign()?t.writeUsageCount=t.writeUsageCount===void 0?1:t.writeUsageCount+1:t.readUsageCount=t.readUsageCount===void 0?1:t.readUsageCount+1,t.usageCount}hasWriteUsage(e){let t=e.getShared(this),i=(t.isGlobal(this)?this.globalCache:this.cache).getData(t);if(i!==void 0){for(let s in i)if(lC(i[s]))return!0}return!1}generateTexture(){X("Abstract function.")}generateTextureLod(){X("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,n=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let s=0;s<t;s++){let a=n?n[s]:null;a!==null?i+=a.build(this,e):i+=this.generateConst(e),s<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,n=null){let i=[];for(let s of t){let{name:a,type:o}=s;n&&n[a]&&n[a].isNode?i.push(n[a].build(this,o)):i.push(this.generateConst(o))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(t===null&&(e==="float"||e==="int"||e==="uint"?t=0:e==="bool"?t=!1:e==="color"?t=new me:e==="vec2"||e==="uvec2"||e==="ivec2"?t=new O:e==="vec3"||e==="uvec3"||e==="ivec3"?t=new E:(e==="vec4"||e==="uvec4"||e==="ivec4")&&(t=new Ge)),e==="float")return Ff(t);if(e==="int")return`${Math.round(t)}`;if(e==="uint")return t>=0?`${Math.round(t)}u`:"0u";if(e==="bool")return t?"true":"false";if(e==="color")return`${this.getType("vec3")}( ${Ff(t.r)}, ${Ff(t.g)}, ${Ff(t.b)} )`;let n=this.getTypeLength(e),i=this.getComponentType(e),s=a=>this.generateConst(i,a);if(n===2)return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)} )`;if(n===3)return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)}, ${s(t.z)} )`;if(n===4&&e!=="mat2")return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)}, ${s(t.z)}, ${s(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(s).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`THREE.NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return e==="color"?"vec3":e}hasGeometryAttribute(e){return this.geometry&&this.geometry.getAttribute(e)!==void 0}getAttribute(e,t){let n=this.attributes;for(let s of n)if(s.name===e)return s;let i=new zm(e,t);return this.registerDeclaration(i),n.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vecd/.test(e)}isMatrix(e){return/matd/.test(e)}isReference(e){return e==="void"||e==="property"||e==="sampler"||e==="samplerComparison"||e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="depthTexture"||e==="texture3D"}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){let t=e.type;return e.isDepthTexture===!0?"float":t===zt?"int":t===it?"uint":"float"}getElementType(e){return e==="mat2"?"vec2":e==="mat3"?"vec3":e==="mat4"?"vec4":this.getComponentType(e)}getComponentType(e){if(e=this.getVectorType(e),e==="float"||e==="bool"||e==="int"||e==="uint")return e;let t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return t===null?null:t[1]==="b"?"bool":t[1]==="i"?"int":t[1]==="u"?"uint":"float"}getVectorType(e){return e==="color"?"vec3":e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="texture3D"?"vec4":e}getTypeFromLength(e,t="float"){if(e===1)return t;let n=XM(e),i=t==="float"?"":t[0];return/mat2/.test(t)===!0&&(n=n.replace("vec","mat")),i+n}getTypeFromArray(e){return Dk.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);let n=t.array,i=e.itemSize,s=e.normalized,a;return!(e instanceof Yl)&&s!==!0&&(a=this.getTypeFromArray(n)),this.getTypeFromLength(i,a)}getTypeLength(e){let t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return n!==null?Number(n[1]):t==="float"||t==="bool"||t==="int"||t==="uint"?1:/mat2/.test(e)===!0?4:/mat3/.test(e)===!0?9:/mat4/.test(e)===!0?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){let t=this.getComponentType(e);return t==="int"||t==="uint"?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]===e)this.activeStacks.pop();else throw new Error("THREE.NodeBuilder: Invalid active stack removal.")}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=em(this.stack);let e=qv();return this.stacks.push(e),Ph(this.stack),this.stack}removeStack(){let e=this.stack;for(let t of e.nodes){let n=this.getDataFromNode(t);n.stack=e}return this.stack=e.parent,Ph(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){n=n===null?e.isGlobal(this)?this.globalCache:this.cache:n;let i=n.getData(e);i===void 0&&(i={},n.setData(e,i)),i[t]===void 0&&(i[t]={});let s=i[t];if(this.subBuildLayers.length===0)return s;let a=i.any?i.any.subBuilds:null,o=this.getClosestSubBuild(a);return o&&(s.subBuildsCache===void 0&&(s.subBuildsCache={}),s=s.subBuildsCache[o]||(s.subBuildsCache[o]={}),s.subBuilds=a),s}getNodeProperties(e,t="any"){let n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t,n=null){let i=this.getDataFromNode(e,"vertex"),s=i.bufferAttribute;if(s===void 0){let a=this.uniforms.index++;n===null&&(n="nodeAttribute"+a),s=new zm(n,t,e),this.bufferAttributes.push(s),i.bufferAttribute=s}return s}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,i=this.shaderStage){let s=this.getDataFromNode(e,i,this.globalCache),a=s.structType;if(a===void 0){let o=this.structs.index++;n===null&&(n="StructType"+o),a=new xb(n,t),this.structs[i].push(a),this.types[i][n]=e,s.structType=a}return a}getOutputStructTypeFromNode(e,t){let n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,i=null){let s=this.getDataFromNode(e,n,this.globalCache),a=s.uniform;if(a===void 0){let o=this.uniforms.index++;a=new mb(i||"nodeUniform"+o,t,e),this.uniforms[n].push(a),this.registerDeclaration(a),s.uniform=a}return a}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage,s=!1){let a=this.getDataFromNode(e,i),o=this.getSubBuildProperty("variable",a.subBuilds),l=a[o];if(l===void 0){let c=s?"_const":"_var",u=this.vars[i]||(this.vars[i]=[]),d=this.vars[c]||(this.vars[c]=0);t===null&&(t=(s?"nodeConst":"nodeVar")+d,this.vars[c]++),o!=="variable"&&(t=this.getSubBuildProperty(t,a.subBuilds));let h=e.getArrayCount(this);l=new Hm(t,n,s,h),s||u.push(l),this.registerDeclaration(l),a[o]=l}return l}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0)&&(e.cNode?this.isDeterministic(e.cNode):!0);if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0);if(e.isArrayNode){if(e.values!==null){for(let t of e.values)if(!this.isDeterministic(t))return!1}return!0}else if(e.isConstNode)return!0;return!1}getVaryingFromNode(e,t=null,n=e.getNodeType(this),i=null,s=null){let a=this.getDataFromNode(e,"any"),o=this.getSubBuildProperty("varying",a.subBuilds),l=a[o];if(l===void 0){let c=this.varyings,u=c.length;t===null&&(t="nodeVarying"+u),o!=="varying"&&(t=this.getSubBuildProperty(t,a.subBuilds)),l=new gb(t,n,i,s),c.push(l),this.registerDeclaration(l),a[o]=l}return l}registerDeclaration(e){let t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),i=e.name,s=i,a=this.getPropertyName(e),o=1;for(;n[a]!==void 0;)s=i+"_"+o++,e.name=s,a=this.getPropertyName(e);s!==i&&X(`TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${s}'.`),n[a]=e}getCodeFromNode(e,t,n=this.shaderStage){let i=this.getDataFromNode(e),s=i.code;if(s===void 0){let a=this.codes[n]||(this.codes[n]=[]),o=a.length;s=new yb("nodeCode"+o,t),a.push(s),i.code=s}return s}addFlowCodeHierarchy(e,t){let{flowCodes:n,flowCodeBlock:i}=this.getDataFromNode(e),s=!0,a=t;for(;a;){if(i.get(a)===!0){s=!1;break}a=this.getDataFromNode(a).parentNodeBlock}if(s)for(let o of n)this.addLineFlowCode(o)}addLineFlowCodeBlock(e,t,n){let i=this.getDataFromNode(e),s=i.flowCodes||(i.flowCodes=[]),a=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);s.push(t),a.set(n,!0)}addLineFlowCode(e,t=null){return e===""?this:(t!==null&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;s*$/.test(e)||(e=e+`;
`),this.flow.code+=e,this)}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+=" ",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){let t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){let t=this.renderer.backend,n=xM.get(t);n===void 0&&(n=new WeakMap,xM.set(t,n));let i=n.get(e);if(i===void 0){i=new Um;let s=this.currentFunctionNode;this.currentFunctionNode=i,i.code=this.buildFunctionCode(e),this.currentFunctionNode=s,n.set(e,i)}return i}flowShaderNode(e){let t=e.layout,n={[Symbol.iterator](){let a=0,o=Object.values(this);return{next:()=>({value:o[a],done:a++>=o.length})}}};for(let a of t.inputs)n[a.name]=new Nm(a.type,a.name);e.layout=null;let i=e.call(n),s=this.flowStagesNode(i,t.type);return e.layout=t,s}flowBuildStage(e,t,n=null){let i=this.getBuildStage();this.setBuildStage(t);let s=e.build(this,n);return this.setBuildStage(i),s}flowStagesNode(e,t=null){let n=this.flow,i=this.vars,s=this.declarations,a=this.cache,o=this.buildStage,l=this.stack,c={code:""};this.flow=c,this.vars={},this.declarations={},this.cache=new Ch,this.stack=em();for(let u of jf)this.setBuildStage(u),c.result=e.build(this,t);return c.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.declarations=s,this.cache=a,this.stack=l,this.setBuildStage(o),c}getFunctionOperator(){return null}buildFunctionCode(){X("Abstract function.")}flowChildNode(e,t=null){let n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){let s=this.tab,a=this.cache,o=this.shaderStage,l=this.context;this.setShaderStage(e);let c={...this.context};delete c.nodeBlock,this.cache=this.globalCache,this.tab=" ",this.context=c;let u=null;if(this.buildStage==="generate"){let d=this.flowChildNode(t,n);i!==null&&(d.code+=`${this.tab+i} = ${d.result};
`),this.flowCode[e]=this.flowCode[e]+d.code,u=d}else u=t.build(this);return this.setShaderStage(o),this.cache=a,this.tab=s,this.context=l,u}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){X("Abstract function.")}getVaryings(){X("Abstract function.")}getVar(e,t,n=null){return`${n!==null?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e,t=!1){let n=[],i=this.vars[e];if(i!==void 0)for(let s of i)n.push(`${this.getVar(s.type,s.name,s.count)};`);return n.join(t?`
`:`
`)}getUniforms(){X("Abstract function.")}getCodes(e){let t=this.codes[e],n="";if(t!==void 0)for(let i of t)n+=i.code+`
`;return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){X("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(e&&e.isNode?e.isShaderCallNodeInternal?t=e.shaderNode.subBuilds:e.isStackNode?t=[e.subBuild]:t=this.getDataFromNode(e,"any").subBuilds:e instanceof Set?t=[...e]:t=e,!t)return null;let n=this.subBuildLayers;for(let i=t.length-1;i>=0;i--){let s=t[i];if(n.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let n;t!==null?n=this.getClosestSubBuild(t):n=this.subBuildFn;let i;return n?i=e?n+"_"+e:n:i=e,i}prebuild(){let{object:e,renderer:t,material:n}=this;if(t.contextNode.isContextNode===!0?this.context={...this.context,...t.contextNode.getFlowContextData()}:G('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),n&&n.contextNode&&(n.contextNode.isContextNode===!0?this.context={...this.context,...n.contextNode.getFlowContextData()}:G('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),n!==null){let i=t.library.fromMaterial(n);i===null&&(G(`NodeBuilder: Material "${n.type}" is not compatible.`),i=new We),i.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(let e of jf){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(let t of Kf){this.setShaderStage(t);let n=this.flowNodes[t];for(let i of n)e==="generate"?this.flowNode(i):i.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(let e of jf){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(let t of Kf){this.setShaderStage(t);let n=this.flowNodes[t];for(let i of n)e==="generate"?this.flowNode(i):i.build(this);await cy()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=Pk.get(e);return t===void 0&&(t={}),t}getNodeUniform(e,t){let n=this.getSharedDataFromNode(e),i=n.cache;if(i===void 0){if(t==="float"||t==="int"||t==="uint")i=new Rb(e);else if(t==="vec2"||t==="ivec2"||t==="uvec2")i=new Ab(e);else if(t==="vec3"||t==="ivec3"||t==="uvec3")i=new Cb(e);else if(t==="vec4"||t==="ivec4"||t==="uvec4")i=new Nb(e);else if(t==="color")i=new Pb(e);else if(t==="mat2")i=new Db(e);else if(t==="mat3")i=new Ib(e);else if(t==="mat4")i=new Fb(e);else throw new Error(`THREE.NodeBuilder: Uniform "${t}" not implemented.`);n.cache=i}return i}format(e,t,n){if(t=this.getVectorType(t),n=this.getVectorType(n),t===n||n===null||this.isReference(n))return e;let i=this.getTypeLength(t),s=this.getTypeLength(n);return i===16&&s===9?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:i===9&&s===4?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||s>4||s===0?e:i===s?`${this.getType(n)}( ${e} )`:i>s?(e=n==="bool"?`all( ${e} )`:`${e}.${"xyz".slice(0,s)}`,this.format(e,this.getTypeFromLength(s,this.getComponentType(t)),n)):s===4&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:i===2?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(i===1&&s>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${"185"} - Node System
`}needsPreviousData(){let e=this.renderer.getMRT();return e&&e.has("velocity")||jM(this.object).useVelocity===!0}},qm=class{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let n=e.get(t);return n===void 0&&(n={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){let t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===pe.FRAME){let i=this._getMaps(this.updateBeforeMap,n);if(i.frameId!==this.frameId){let s=i.frameId;i.frameId=this.frameId,e.updateBefore(this)===!1&&(i.frameId=s)}}else if(t===pe.RENDER){let i=this._getMaps(this.updateBeforeMap,n);if(i.renderId!==this.renderId){let s=i.renderId;i.renderId=this.renderId,e.updateBefore(this)===!1&&(i.renderId=s)}}else t===pe.OBJECT&&e.updateBefore(this)}updateAfterNode(e){let t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===pe.FRAME){let i=this._getMaps(this.updateAfterMap,n);i.frameId!==this.frameId&&e.updateAfter(this)!==!1&&(i.frameId=this.frameId)}else if(t===pe.RENDER){let i=this._getMaps(this.updateAfterMap,n);i.renderId!==this.renderId&&e.updateAfter(this)!==!1&&(i.renderId=this.renderId)}else t===pe.OBJECT&&e.updateAfter(this)}updateNode(e){let t=e.getUpdateType(),n=e.updateReference(this);if(t===pe.FRAME){let i=this._getMaps(this.updateMap,n);i.frameId!==this.frameId&&e.update(this)!==!1&&(i.frameId=this.frameId)}else if(t===pe.RENDER){let i=this._getMaps(this.updateMap,n);i.renderId!==this.renderId&&e.update(this)!==!1&&(i.renderId=this.renderId)}else t===pe.OBJECT&&e.update(this)}update(){this.frameId++,this.lastTime===void 0&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}},$h=class{constructor(e,t,n=null,i="",s=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=s}};$h.isNodeFunctionInput=!0;var Lb=class extends qr{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}},Bb=class extends qr{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){let e=this.colorNode;return{lightDirection:oT(this.light),lightColor:e}}},Ub=class extends qr{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=rT(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=ie(new me).setGroup(de)}update(e){let{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){let{colorNode:t,groundColorNode:n,lightDirectionNode:i}=this,a=ro.dot(i).mul(.5).add(.5),o=Re(n,t,a);e.context.irradiance.addAssign(o)}},Xh=class extends qr{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=ie(0).setGroup(de),this.penumbraCosNode=ie(0).setGroup(de),this.cutoffDistanceNode=ie(0).setGroup(de),this.decayExponentNode=ie(0).setGroup(de),this.colorNode=ie(this.color).setGroup(de)}update(e){super.update(e);let{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){let{coneCosNode:n,penumbraCosNode:i}=this;return Oi(n,i,t)}getLightCoord(e){let t=e.getNodeProperties(this),n=t.projectionUV;return n===void 0&&(n=IA(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){let{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:s}=this,a=this.getLightVector(e),o=a.normalize(),l=o.dot(oT(s)),c=this.getSpotAttenuation(e,l),u=a.length(),d=hT({lightDistance:u,cutoffDistance:n,decayExponent:i}),h=t.mul(c).mul(d),p,f;return s.colorNode?(f=this.getLightCoord(e),p=s.colorNode(f)):s.map&&(f=this.getLightCoord(e),p=Ue(s.map,f.xy).onRenderUpdate(()=>s.map)),p&&(h=f.mul(2).sub(1).abs().lessThan(1).all().select(h.mul(p),h)),{lightColor:h,lightDirection:o}}},Ob=class extends Xh{static get type(){return"IESSpotLightNode"}constructor(e=null){super(e),this._iesTextureNode=null}getSpotAttenuation(e,t){let n=this.light.iesMap,i=null;if(n&&n.isTexture===!0){let s=t.acos().mul(1/Math.PI);this._iesTextureNode=Ue(n,$(s,0),0),i=this._iesTextureNode.r}else i=super.getSpotAttenuation(e,t);return i}update(e){super.update(e),this._iesTextureNode!==null&&this.light.iesMap&&(this._iesTextureNode.value=this.light.iesMap)}},kb=class extends qr{static get type(){return"LightProbeNode"}constructor(e=null){super(e);let t=[];for(let n=0;n<9;n++)t.push(new E);this.lightProbe=Tn(t)}update(e){let{light:t}=this;super.update(e);for(let n=0;n<9;n++)this.lightProbe.array[n].copy(t.sh.coefficients[n]).multiplyScalar(t.intensity)}setup(e){let t=oC(ro,this.lightProbe);e.context.irradiance.addAssign(t)}},Ik=P(([r,e])=>{let t=r.abs().sub(e);return rr(At(t,0)).add(gi(At(t.x,t.y),0))}),Vb=class extends Xh{static get type(){return"ProjectorLightNode"}update(e){super.update(e);let t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),t.aspect===null){let n=1;t.map!==null&&(n=t.map.width/t.map.height),t.shadow.aspect=n}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){let t=v(0),n=this.penumbraCosNode,i=Hg(this.light).mul(e.context.positionWorld||ar);return oe(i.w.greaterThan(0),()=>{let s=i.xyz.div(i.w),a=Ik(s.xy.sub($(.5)),$(.5)),o=Ui(-1,Ie(1,sS(n)).sub(1));t.assign(Rg(a.mul(-2).mul(o)))}),t}},Gy=new Ne,Lf=new Ne,dh=null,Gb=class extends qr{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=ie(new E).setGroup(de),this.halfWidth=ie(new E).setGroup(de),this.updateType=pe.RENDER}update(e){super.update(e);let{light:t}=this,n=e.camera.matrixWorldInverse;Lf.identity(),Gy.copy(t.matrixWorld),Gy.premultiply(n),Lf.extractRotation(Gy),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(Lf),this.halfHeight.value.applyMatrix4(Lf)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=Ue(dh.LTC_FLOAT_1),n=Ue(dh.LTC_FLOAT_2)):(t=Ue(dh.LTC_HALF_1),n=Ue(dh.LTC_HALF_2));let{colorNode:i,light:s}=this,a=aT(s);return{lightColor:i,lightPosition:a,halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){dh=e}},$m=class{parseFunction(){X("Abstract function.")}},Yh=class{constructor(e,t,n="",i=""){this.type=e,this.inputs=t,this.name=n,this.precision=i}getCode(){X("Abstract function.")}};Yh.isNodeFunction=!0;var Fk=/^s*(highp|mediump|lowp)?s*([a-z_0-9]+)s*([a-z_0-9]+)?s*(([sS]*?))/i,Lk=/[a-z_0-9]+/ig,_M="#pragma main",Bk=r=>{r=r.trim();let e=r.indexOf(_M),t=e!==-1?r.slice(e+_M.length):r,n=t.match(Fk);if(n!==null&&n.length===5){let i=n[4],s=[],a=null;for(;(a=Lk.exec(i))!==null;)s.push(a);let o=[],l=0;for(;l<s.length;){let f=s[l][0]==="const";f===!0&&l++;let m=s[l][0];m==="in"||m==="out"||m==="inout"?l++:m="";let y=s[l++][0],x=Number.parseInt(s[l][0]);Number.isNaN(x)===!1?l++:x=null;let b=s[l++][0];o.push(new $h(y,b,x,m,f))}let c=t.substring(n[0].length),u=n[3]!==void 0?n[3]:"",d=n[2],h=n[1]!==void 0?n[1]:"",p=e!==-1?r.slice(0,e):"";return{type:d,inputs:o,name:u,precision:h,inputsCode:i,blockCode:c,headerCode:p}}else throw new Error("THREE.FunctionNode: Function is not a GLSL code.")},zb=class extends Yh{constructor(e){let{type:t,inputs:n,name:i,precision:s,inputsCode:a,blockCode:o,headerCode:l}=Bk(e);super(t,n,i,s),this.inputsCode=a,this.blockCode=o,this.headerCode=l}getCode(e=this.name){let t,n=this.blockCode;if(n!==""){let{type:i,inputsCode:s,headerCode:a,precision:o}=this,l=`${i} ${e} ( ${s.trim()} )`;o!==""&&(l=`${o} ${l}`),t=a+l+n}else t="";return t}},Hb=class extends $m{parseFunction(e){return new zb(e)}},Qi=[],Lr=[],bM=ie(0,"int").setGroup(de),Wb=class extends hr{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new qm,this.nodeBuilderCache=new Map,this.callHashCache=new dr,this.groupsData=new dr,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){let t=e.groupNode;if(t.updateType===pe.OBJECT)return!0;Qi[0]=t,Qi[1]=e;let n=this.groupsData.get(Qi);return n===void 0&&this.groupsData.set(Qi,n={}),Qi[0]=null,Qi[1]=null,n.version!==t.version?(n.version=t.version,!0):!1}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){let n=this.backend.createNodeBuilder(e.object,this.renderer);return n.scene=e.scene,n.material=t,n.camera=e.camera,n.context.material=t,n.lightsNode=e.lightsNode,n.environmentNode=this.getEnvironmentNode(e.scene),n.fogNode=this.getFogNode(e.scene),n.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&n.enableMultiview(),n}getForRender(e,t=!1){let n=this.get(e),i=n.nodeBuilderState;if(i===void 0){let{nodeBuilderCache:s}=this,a=this.getForRenderCacheKey(e);if(i=s.get(a),i===void 0){let o=async()=>{let l=this._createNodeBuilder(e,e.material);try{t?await l.buildAsync():l.build()}catch(c){l=this._createNodeBuilder(e,new We),t?await l.buildAsync():l.build(),G("TSL: "+c)}return l};if(t)return o().then(l=>(i=this._createNodeBuilderState(l),s.set(a,i),i.usedTimes++,n.nodeBuilderState=i,i));{let l=this._createNodeBuilder(e,e.material);try{l.build()}catch(c){l=this._createNodeBuilder(e,new We),l.build();let u=c.stackTrace;!u&&c.stack&&(u=new Dt(c.stack)),G("TSL: "+c,u)}i=this._createNodeBuilderState(l),s.set(a,i)}}i.usedTimes++,n.nodeBuilderState=i}return i}getForRenderAsync(e){let t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){let t=this.get(e);if(t.nodeBuilderState!==void 0)return t.nodeBuilderState;let n=this.getForRenderCacheKey(e),i=this.nodeBuilderCache.get(n);return i!==void 0?(i.usedTimes++,t.nodeBuilderState=i,i):(t.pendingBuild!==!0&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||this._buildQueue.length===0)return;this._buildInProgress=!0,this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){let t=this.get(e).nodeBuilderState;t!==void 0&&(t.usedTimes--,t.usedTimes===0&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e){let t=this.get(e),n=t.nodeBuilderState;if(n===void 0||t.version!==e.version){let i=this.backend.createNodeBuilder(e,this.renderer);i.build(),n=this._createNodeBuilderState(i),t.nodeBuilderState=n,t.version=e.version}return n}_createNodeBuilderState(e){return new fb(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.hardwareClipping,e.transforms)}getEnvironmentNode(e){if(this.renderer.lighting.enabled===!1)return null;this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{let n=this.get(e);n.environmentNode&&(t=n.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{let n=this.get(e);n.backgroundNode&&(t=n.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){Qi[0]=e,Qi[1]=t;let n=this.renderer.info.calls,i=this.callHashCache.get(Qi)||{};if(i.callId!==n){if(Lr.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),Lr.push(this.renderer.lighting.enabled?1:0),this.renderer.lighting.enabled){Lr.push(t.getCacheKey(!0)),Lr.push(this.renderer.shadowMap.enabled?1:0),Lr.push(this.renderer.shadowMap.type);let a=this.getEnvironmentNode(e);a&&Lr.push(a.getCacheKey())}let s=this.getFogNode(e);s&&Lr.push(s.getCacheKey()),i.callId=n,i.cacheKey=Jh(Lr),this.callHashCache.set(Qi,i),Lr.length=0}return Qi[0]=null,Qi[1]=null,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){let t=this.get(e),n=e.background;if(n){let i=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;if(t.background!==n||i){let s=this.getCacheNode("background",n,()=>{if(n.isCubeTexture===!0||n.mapping===zd||n.mapping===Hd||n.mapping===Po){if(e.backgroundBlurriness>0||n.mapping===Po)return QS(n);{let a;return n.isCubeTexture===!0?a=Zn(n):a=Ue(n),KR(a)}}else{if(n.isTexture===!0)return Ue(n,Rs.flipY()).setUpdateMatrix(!0);n.isColor!==!0&&G("WebGPUNodes: Unsupported background configuration.",n)}},i);t.backgroundNode=s,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,i=!1){let s=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap),a=s.get(t);return(a===void 0||i)&&(a=n(),s.set(t,a)),a}updateFog(e){let t=this.get(e),n=e.fog;if(n){if(t.fog!==n){let i=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){let s=dt("color","color",n).setGroup(de),a=dt("density","float",n).setGroup(de);return sb(s,DA(a))}else if(n.isFog){let s=dt("color","color",n).setGroup(de),a=dt("near","float",n).setGroup(de),o=dt("far","float",n).setGroup(de);return sb(s,PA(a,o))}else G("Renderer: Unsupported fog configuration.",n)});t.fogNode=i,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){let t=this.get(e),n=e.environment;if(n){if(t.environment!==n){let i=this.getCacheNode("environment",n,()=>{if(n.isCubeTexture===!0)return Zn(n);if(n.isTexture===!0)return Ue(n);G("Nodes: Unsupported environment configuration.",n)});t.environmentNode=i,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,s=null){let a=this.nodeFrame;return a.renderer=e,a.scene=t,a.object=n,a.camera=i,a.material=s,a}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){let e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){let t=this.renderer,n;return e.isArrayTexture?this.backend.isWebGLBackend?n=Ue(e,Rs).depth(Yr("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):n=Ue(e,Rs).depth(bM).renderOutput(t.toneMapping,t.currentColorSpace):n=Ue(e,Rs).renderOutput(t.toneMapping,t.currentColorSpace),n}setOutputLayerIndex(e){bM.value=e}updateBefore(e){let t=e.getNodeBuilderState();for(let n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){let t=e.getNodeBuilderState();for(let n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateForCompute(e){let t=this.getNodeFrame(),n=this.getForCompute(e);for(let i of n.updateNodes)t.updateNode(i)}updateForRender(e){let t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(let i of n.updateNodes)t.updateNode(i)}needsRefresh(e){let t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new qm,this.nodeBuilderCache=new Map,this.cacheLib={}}},zy=new ri,Xm=class r{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewMatrix=new Ne,this.viewNormalMatrix=new ve,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,e!==null&&(this.viewMatrix=e.viewMatrix,this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass)}projectPlanes(e,t,n){let i=e.length;for(let s=0;s<i;s++){zy.copy(e[s]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);let a=t[n+s],o=zy.normal;a.x=-o.x,a.y=-o.y,a.z=-o.z,a.w=zy.constant}}updateGlobal(e,t){this.shadowPass=e.overrideMaterial!==null&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix.copy(t.matrixWorldInverse),this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let n=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);let i=t.clippingPlanes,s=i.length,a,o;if(this.clipIntersection?(a=this.intersectionPlanes,o=e.intersectionPlanes.length):(a=this.unionPlanes,o=e.unionPlanes.length),a.length!==o+s){a.length=o+s;for(let l=0;l<s;l++)a[o+l]=new Ge;n=!0}this.projectPlanes(i,a,o),n&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return t===void 0&&(t=new r(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}},qb=class{constructor(e,t,n){this.bundleGroup=e,this.camera=t,this.renderContext=n}},Ba=[],$b=class{constructor(){this.bundles=new dr}get(e,t,n){let i=this.bundles;Ba[0]=e,Ba[1]=t,Ba[2]=n;let s=i.get(Ba);return s===void 0&&(s=new qb(e,t,n),i.set(Ba,s)),Ba[0]=null,Ba[1]=null,Ba[2]=null,s}dispose(){this.bundles=new dr}},Ym=class{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null,n=this.getMaterialNodeClass(e.type);if(n!==null){t=new n;for(let i in e)t[i]=e[i]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,n){if(n.has(t)){X(`Redefinition of node ${t}`);return}if(typeof e!="function")throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if(typeof t=="function"||typeof t=="object")throw new Error(`THREE.NodeLibrary: Base class ${t} is not a class.`);n.set(t,e)}addClass(e,t,n){if(n.has(t)){X(`Redefinition of node ${t.name}`);return}if(typeof e!="function")throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if(typeof t!="function")throw new Error(`THREE.NodeLibrary: Base class ${t.name} is not a class.`);n.set(t,e)}},Uk=new Wh,vM=new WeakMap,Xb=class{constructor(){this.enabled=!0,this._cache=[]}createNode(e=[]){return new Wh().setLights(e)}getNode(e){if(e.isScene!==!0&&e.isGroup!==!0)return Uk;let t=vM.get(e);return t===void 0&&(t=this.createNode(),vM.set(e,t)),t}beginRender(e){this._cache.push(this.getNode(e).getLights())}finishRender(e){this.getNode(e).setLights(this._cache.pop())}},Jo=class extends Jt{constructor(e=1,t=1,n={}){super(e,t,n),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}},SM=new E,TM=new E,MM=new WeakMap,Yb=class extends $n{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new an,this._cameraL.viewport=new Ge,this._cameraL.matrixWorldAutoUpdate=!1,this._cameraR=new an,this._cameraR.viewport=new Ge,this._cameraR.matrixWorldAutoUpdate=!1,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Dd,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding=typeof XRWebGLBinding<"u",this._supportsWebGPUBinding=typeof globalThis.XRGPUBinding<"u",this._createXRLayer=Hk.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSamples=null,this._currentSize=new O,this._onSessionEvent=Vk.bind(this),this._onSessionEnd=Gk.bind(this),this._onInputSourcesChange=zk.bind(this),this._onAnimationFrame=Wk.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._webgpuBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){return this._foveation}setFoveation(e){this._foveation=e,this._glProjLayer!==null&&(this._glProjLayer.fixedFoveation=e),this._glBaseLayer!==null&&this._glBaseLayer.fixedFoveation!==void 0&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,this.isPresenting===!0&&X("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,this.isPresenting===!0&&X("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(this._session!==null)return this._session.environmentBlendMode}getBaseLayer(){return this._glProjLayer!==null?this._glProjLayer:this._glBaseLayer}getBinding(){return this._glBinding===null&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}foveateBoundTexture(e){if(e.isPostProcessingRenderTarget!==!0||this.isPresenting!==!0||this._glProjLayer===null)return;let t=this._renderer.backend;if(t===void 0||t.isWebGLBackend!==!0||t.state===null)return;let n=this._renderer.getOutputRenderTarget();if(n===null||n.isXRRenderTarget!==!0)return;let i=this.getBinding();if(i===null||typeof i.foveateBoundTexture!="function")return;this._renderer._textures.updateRenderTarget(e);let{textureGPU:s,glTextureType:a}=t.get(e.texture);if(!(s===void 0||a===void 0)&&e._xrFoveationTextureGPU!==s){e._xrFoveationTextureGPU=s,t.state.bindTexture(a,s);try{i.foveateBoundTexture(a,this.getFoveation())}catch(o){Ce(`XRManager: Unable to foveate bound XR post-processing texture. ${o.name}: ${o.message}`)}finally{t.state.unbindTexture()}}}getWebGPUBinding(){return this._webgpuBinding===null&&this._supportsWebGPUBinding&&(this._webgpuBinding=new globalThis.XRGPUBinding(this._session,this._renderer.backend.device)),this._webgpuBinding}_isWebGPUSession(){return this._renderer.backend.isWebGPUBackend===!0&&this._session!==null&&this._session.enabledFeatures.includes("webgpu")}_validateWebGPUSession(){let e=this._renderer;if(e.backend.isWebGPUBackend===!0){if(this._session.enabledFeatures.includes("webgpu")===!1)throw new Error('THREE.XRManager: WebGPU XR sessions require the "webgpu" session feature. Use VRButtonGPU/XRButton with "webgpu" enabled or use a WebGL backend.');e.samples>0&&(Ce("THREE.XRManager: WebGPU XR does not support MSAA yet. Disabling MSAA for this XR session."),this._currentSamples===null&&(this._currentSamples=e.samples),e._samples=0)}}async _initWebGPUSession(e){let t=this.getWebGPUBinding(),n=t.createProjectionLayer({colorFormat:t.getPreferredColorFormat(),depthStencilFormat:"depth24plus"});this._glProjLayer=n,e.updateRenderState({layers:[n]}),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._xrRenderTarget=new Jt(n.textureWidth,n.textureHeight,{depth:2,minFilter:St,magFilter:St,depthBuffer:!0,multiview:!1,useArrayDepthTexture:!0,samples:0}),this._xrRenderTarget.texture.isArrayTexture=!0,this._useMultiviewIfPossible===!0&&Ce("THREE.XRManager: WebGPU XR does not support multiview yet. Disabling multiview for this XR session."),this._useMultiview=!1}_disposeWebGPUSession(){let e=this._renderer,t=this._xrRenderTarget;if(t===null||e.backend.isWebGPUBackend!==!0)return;let n=e.backend,i=e._textures,s=n.get?n.get(t):null;s&&(s.descriptors=void 0);let a=o=>{o!=null&&(n.delete&&n.delete(o),i.delete&&i.delete(o))};for(let o=0;o<t.textures.length;o++)a(t.textures[o]);a(t.depthTexture),a(t),e._renderContexts&&e._renderContexts.dispose&&e._renderContexts.dispose(),t.dispose()}_getWebGPUViewData(e){let t=this.getWebGPUBinding(),n={colorTexture:null,viewDescriptors:[],viewports:[]};for(let i=0;i<e.length;i++){let s=t.getViewSubImage(this._glProjLayer,e[i]);n.colorTexture===null&&(n.colorTexture=s.colorTexture),n.viewports.push(s.viewport),s.getViewDescriptor&&n.viewDescriptors.push(s.getViewDescriptor())}return n}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,n,i,s,a,o,l={}){let c=new od(e,t),u=new Jo(s,a,{format:bn,type:Gt,depthTexture:new Pn(s,a,l.stencil?vs:it,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?Zi:ui),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;let d=new ji({color:16777215,side:oi});d.map=u.texture,d.map.offset.y=1,d.map.repeat.y=-1;let h=new De(c,d);h.position.copy(n),h.quaternion.copy(i);let p={type:"quad",width:e,height:t,translation:n,quaternion:i,pixelwidth:s,pixelheight:a,plane:h,material:d,rendercall:o,renderTarget:u};if(this._layers.push(p),this._session!==null){p.plane.material=new ji({color:16777215,side:oi}),p.plane.material.blending=Ra,p.plane.material.blendEquation=ci,p.plane.material.blendSrc=Ws,p.plane.material.blendDst=Ws,p.xrlayer=this._createXRLayer(p);let f=this._session.renderState.layers;f.unshift(p.xrlayer),this._session.updateRenderState({layers:f})}else u.isXRRenderTarget=!1;return h}createCylinderLayer(e,t,n,i,s,a,o,l,c={}){let u=new Pt(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),d=new Jo(a,o,{format:bn,type:Gt,depthTexture:new Pn(a,o,c.stencil?vs:it,void 0,void 0,void 0,void 0,void 0,void 0,c.stencil?Zi:ui),stencilBuffer:c.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});d._autoAllocateDepthBuffer=!0;let h=new ji({color:16777215,side:ln});h.map=d.texture,h.map.offset.y=1,h.map.repeat.y=-1;let p=new De(u,h);p.position.copy(i),p.quaternion.copy(s);let f={type:"cylinder",radius:e,centralAngle:t,aspectratio:n,translation:i,quaternion:s,pixelwidth:a,pixelheight:o,plane:p,material:h,rendercall:l,renderTarget:d};if(this._layers.push(f),this._session!==null){f.plane.material=new ji({color:16777215,side:ln}),f.plane.material.blending=Ra,f.plane.material.blendEquation=ci,f.plane.material.blendSrc=Ws,f.plane.material.blendDst=Ws,f.xrlayer=this._createXRLayer(f);let m=this._session.renderState.layers;m.unshift(f.xrlayer),this._session.updateRenderState({layers:m})}else d.isXRRenderTarget=!1;return p}renderLayers(){let e=new E,t=new fn,n=this._renderer,i=this.isPresenting;this.isPresenting=!1;let s=new O;n.getSize(s);let a=n.getRenderTarget();for(let o of this._layers){o.renderTarget.isXRRenderTarget=this._session!==null,o.renderTarget._hasExternalTextures=o.renderTarget.isXRRenderTarget;let l=n.contextNode,c;if(o.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){o.xrlayer.transform=new XRRigidTransform(o.plane.getWorldPosition(e),o.plane.getWorldQuaternion(t));let u=this._glBinding.getSubImage(o.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(o.renderTarget,u.colorTexture,void 0),n._setXRLayerSize(o.renderTarget.width,o.renderTarget.height),c=MM.get(l),c===void 0&&(c=l.context({getOutput:d=>Pg(d,n.toneMapping,n.outputColorSpace)}),MM.set(l,c))}else c=l;n.contextNode=c,n.setRenderTarget(o.renderTarget),o.rendercall(),n.contextNode=l}n.setRenderTarget(a),n._setXRLayerSize(s.x,s.y),this.isPresenting=i}getSession(){return this._session}async setSession(e){let t=this._renderer;t.initialized===!1&&await t.init(),this._gl=t.getContext();let n=this._gl;if(this._session=e,e!==null){if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),this._validateWebGPUSession(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._isWebGPUSession())await this._initWebGPUSession(e);else if(this._supportsLayers===!0){let i=null,s=null,a=null,o=n.getContextAttributes();await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation()),t.depth&&(a=t.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,i=t.stencil?Zi:ui,s=t.stencil?vs:it);let l={colorFormat:n.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(l.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();let c=this._glBinding.createProjectionLayer(l),u=[c];this._glProjLayer=c,t.setPixelRatio(1),t._setXRLayerSize(c.textureWidth,c.textureHeight);let d=this._useMultiview?2:1,h=new Pn(c.textureWidth,c.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,i,d);if(this._xrRenderTarget=new Jo(c.textureWidth,c.textureHeight,{format:bn,type:Gt,colorSpace:t.outputColorSpace,depthTexture:h,stencilBuffer:t.stencil,samples:o.antialias?4:0,resolveDepthBuffer:c.ignoreDepthValues===!1,resolveStencilBuffer:c.ignoreDepthValues===!1,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(let p of this._layers)p.plane.material=new ji({color:16777215,side:p.type==="cylinder"?ln:oi}),p.plane.material.blending=Ra,p.plane.material.blendEquation=ci,p.plane.material.blendSrc=Ws,p.plane.material.blendDst=Ws,p.xrlayer=this._createXRLayer(p),u.unshift(p.xrlayer);e.updateRenderState({layers:u})}else{await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation());let i={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},s=new XRWebGLLayer(e,n,i);this._glBaseLayer=s,e.updateRenderState({baseLayer:s}),t.setPixelRatio(1),t._setXRLayerSize(s.framebufferWidth,s.framebufferHeight),this._xrRenderTarget=new Jo(s.framebufferWidth,s.framebufferHeight,{format:bn,type:Gt,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:s.ignoreDepthValues===!1,resolveStencilBuffer:s.ignoreDepthValues===!1}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){let t=this._session;if(t===null)return;let n=e.near,i=e.far,s=this._cameraXR,a=this._cameraL,o=this._cameraR;s.near=o.near=a.near=n,s.far=o.far=a.far=i,s.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==s.near||this._currentDepthFar!==s.far)&&(t.updateRenderState({depthNear:s.near,depthFar:s.far}),this._currentDepthNear=s.near,this._currentDepthFar=s.far),s.layers.mask=e.layers.mask|6,a.layers.mask=s.layers.mask&-5,o.layers.mask=s.layers.mask&-3;let l=e.parent,c=s.cameras;wM(s,l);for(let u=0;u<c.length;u++)wM(c[u],l);c.length===2?Ok(s,a,o):s.projectionMatrix.copy(a.projectionMatrix),kk(e,s,l)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new Yu,this._controllers[e]=t),t}};function Ok(r,e,t){SM.setFromMatrixPosition(e.matrixWorld),TM.setFromMatrixPosition(t.matrixWorld);let n=SM.distanceTo(TM),i=e.projectionMatrix.elements,s=t.projectionMatrix.elements,a=i[14]/(i[10]-1),o=i[14]/(i[10]+1),l=(i[9]+1)/i[5],c=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(s[8]+1)/s[0],h=a*u,p=a*d,f=n/(-u+d),m=f*-u;if(e.matrixWorld.decompose(r.position,r.quaternion,r.scale),r.translateX(m),r.translateZ(f),r.matrixWorld.compose(r.position,r.quaternion,r.scale),r.matrixWorldInverse.copy(r.matrixWorld).invert(),i[10]===-1)r.projectionMatrix.copy(e.projectionMatrix),r.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{let y=a+f,x=o+f,b=h-m,_=p+(n-m),S=l*o/x*y,M=c*o/x*y;r.projectionMatrix.makePerspective(b,_,S,M,y,x),r.projectionMatrixInverse.copy(r.projectionMatrix).invert()}}function wM(r,e){e===null?r.matrixWorld.copy(r.matrix):r.matrixWorld.multiplyMatrices(e.matrixWorld,r.matrix),r.matrixWorldInverse.copy(r.matrixWorld).invert()}function kk(r,e,t){t===null?r.matrix.copy(e.matrixWorld):(r.matrix.copy(t.matrixWorld),r.matrix.invert(),r.matrix.multiply(e.matrixWorld)),r.matrix.decompose(r.position,r.quaternion,r.scale),r.updateMatrixWorld(!0),r.projectionMatrix.copy(e.projectionMatrix),r.projectionMatrixInverse.copy(e.projectionMatrixInverse),r.isPerspectiveCamera&&(r.fov=pa*2*Math.atan(1/r.projectionMatrix.elements[5]),r.zoom=1)}function Vk(r){let e=this._controllerInputSources.indexOf(r.inputSource);if(e===-1)return;let t=this._controllers[e];if(t!==void 0){let n=this.getReferenceSpace();t.update(r.inputSource,r.frame,n),t.dispatchEvent({type:r.type,data:r.inputSource})}}function Gk(){let r=this._session,e=this._renderer;r.removeEventListener("select",this._onSessionEvent),r.removeEventListener("selectstart",this._onSessionEvent),r.removeEventListener("selectend",this._onSessionEvent),r.removeEventListener("squeeze",this._onSessionEvent),r.removeEventListener("squeezestart",this._onSessionEvent),r.removeEventListener("squeezeend",this._onSessionEvent),r.removeEventListener("end",this._onSessionEnd),r.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let t=0;t<this._controllers.length;t++){let n=this._controllerInputSources[t];n!==null&&(this._controllerInputSources[t]=null,this._controllers[t].disconnect(n))}if(this._currentDepthNear=null,this._currentDepthFar=null,this._currentSamples!==null&&(e._samples=this._currentSamples,this._currentSamples=null),e._resetXRState(),this._disposeWebGPUSession(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._webgpuBinding=null,this._glBaseLayer=null,this._glProjLayer=null,this._sessionUsesLayers===!0)for(let t of this._layers)t.renderTarget=new Jo(t.pixelwidth,t.pixelheight,{format:bn,type:Gt,depthTexture:new Pn(t.pixelwidth,t.pixelheight,t.stencilBuffer?vs:it,void 0,void 0,void 0,void 0,void 0,void 0,t.stencilBuffer?Zi:ui),stencilBuffer:t.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),t.renderTarget.isXRRenderTarget=!1,t.plane.material=t.material,t.material.map=t.renderTarget.texture,t.material.map.offset.y=1,t.material.map.repeat.y=-1,delete t.xrlayer;this.isPresenting=!1,this._useMultiview=!1,e._animation.stop(),e._animation.setAnimationLoop(this._currentAnimationLoop),e._animation.setContext(this._currentAnimationContext),e._animation.start(),e.setPixelRatio(this._currentPixelRatio),e.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function zk(r){let e=this._controllers,t=this._controllerInputSources;for(let n=0;n<r.removed.length;n++){let i=r.removed[n],s=t.indexOf(i);s>=0&&(t[s]=null,e[s].disconnect(i))}for(let n=0;n<r.added.length;n++){let i=r.added[n],s=t.indexOf(i);if(s===-1){for(let o=0;o<e.length;o++)if(o>=t.length){t.push(i),s=o;break}else if(t[o]===null){t[o]=i,s=o;break}if(s===-1)break}let a=e[s];a&&a.connect(i)}}function Hk(r){return r.type==="quad"?this._glBinding.createQuadLayer({transform:new XRRigidTransform(r.translation,r.quaternion),width:r.width/2,height:r.height/2,space:this._referenceSpace,viewPixelWidth:r.pixelwidth,viewPixelHeight:r.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(r.translation,r.quaternion),radius:r.radius,centralAngle:r.centralAngle,aspectRatio:r.aspectRatio,space:this._referenceSpace,viewPixelWidth:r.pixelwidth,viewPixelHeight:r.pixelheight,clearOnAccess:!1})}function Wk(r,e){if(e===void 0)return;let t=this._cameraXR,n=this._renderer,i=n.backend,s=this._glBaseLayer,a=this.getReferenceSpace(),o=e.getViewerPose(a);if(this._xrFrame=e,o!==null){let l=o.views,c=this._isWebGPUSession()?this._getWebGPUViewData(l):null;this._glBaseLayer!==null&&c===null&&i.setXRTarget(s.framebuffer);let u=!1;l.length!==t.cameras.length&&(t.cameras.length=0,u=!0);for(let h=0;h<l.length;h++){let p=l[h],f;if(c!==null)f=c.viewports[h];else if(this._supportsLayers===!0){let y=this._glBinding.getViewSubImage(this._glProjLayer,p);f=y.viewport,h===0&&i.setXRRenderTargetTextures(this._xrRenderTarget,y.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:y.depthStencilTexture)}else f=s.getViewport(p);let m=this._cameras[h];m===void 0&&(m=new an,m.layers.enable(h),m.viewport=new Ge,m.matrixWorldAutoUpdate=!1,this._cameras[h]=m),m.matrix.fromArray(p.transform.matrix),m.matrix.decompose(m.position,m.quaternion,m.scale),m.projectionMatrix.fromArray(p.projectionMatrix),m.projectionMatrixInverse.copy(m.projectionMatrix).invert(),m.viewport.set(f.x,f.y,f.width,f.height),h===0&&(t.matrix.copy(m.matrix),t.matrix.decompose(t.position,t.quaternion,t.scale)),u===!0&&t.cameras.push(m)}c!==null&&c.colorTexture!==null&&i.setXRRenderTargetTextures(this._xrRenderTarget,c.colorTexture,c.viewDescriptors),n.setOutputRenderTarget(this._xrRenderTarget);let d=n._getFrameBufferTarget();n.xr.foveateBoundTexture(d)}for(let l=0;l<this._controllers.length;l++){let c=this._controllerInputSources[l],u=this._controllers[l];c!==null&&u!==void 0&&u.update(c,e,a)}this._currentAnimationLoop&&this._currentAnimationLoop(r,e),e.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:e}),this._xrFrame=null}var jb=class extends $n{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Ge(0,0,this._width,this._height),this._scissor=new Ge(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new _o,this.depthTexture=new Pn}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),n===!0&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){let t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,n,i){let s=this._scissor;e.isVector4?s.copy(e):s.set(e,t,n,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,i,s=0,a=1){let o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,n,i),o.minDepth=s,o.maxDepth=a}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}},EM=new fa,Yc=new O,Hy=new Ge,Bf=new ya,Uf=new Zu,jc=new Ne,Br=new Ge,qk={[oi]:ln,[ln]:oi,[Ri]:Ri},Kb=class{constructor(e,t={}){this.isRenderer=!0;let{logarithmicDepthBuffer:n=!1,reversedDepthBuffer:i=!1,alpha:s=!0,depth:a=!0,stencil:o=!1,antialias:l=!1,samples:c=0,getFallback:u=null,outputBufferType:d=xt,multiview:h=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=s,this.logarithmicDepthBuffer=n,this.reversedDepthBuffer=i,this.outputColorSpace=Vt,this.toneMapping=Ki,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=a,this.stencil=o,this.info=new R_,this.contextNode=Xr(),this.library=new Ym,this.lighting=new Xb,this._samples=c||l===!0?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new jb(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new fm,this._inspector.setRenderer(this),this._getFallback=u,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;let p=this.alpha===!0?0:1;this._clearColor=new Gh(0,0,0,p),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this.onError=this._onError,this._outputBufferType=d,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this._currentSourceMaterial=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:Fd},this.xr=new Yb(this,h),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(f,m,y)=>{await this.compileAsync(y,m,f);let b=this.needsFrameBufferTarget&&this._renderTarget===null?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,_=this._renderLists.get(f,m),S=this._renderContexts.get(b,this._mrt),M=f.overrideMaterial||y.material,w=this._objects.get(y,M,f,m,_.lightsNode,S,S.clippingContext),{fragmentShader:T,vertexShader:R}=w.getNodeBuilderState();return{fragmentShader:T,vertexShader:R}}}}async init(){return this._initPromise!==null?this._initPromise:(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(i){if(this._getFallback!==null)try{this.backend=n=this._getFallback(i),await n.init(this)}catch(s){t(s);return}else{t(i);return}}this._nodes=new Wb(this,n),this._animation=new S_(this,this._nodes,this.info),this._attributes=new w_(n,this.info),this._background=new pb(this,this._nodes),this._geometries=new E_(this._attributes,this.info),this._textures=new B_(this,n,this.info),this._pipelines=new N_(n,this._nodes,this.info),this._bindings=new P_(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new M_(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new I_(this.lighting),this._bundles=new $b,this._renderContexts=new L_(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)}),this._initPromise)}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init();let i=this._nodes.nodeFrame,s=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._handleObjectFunction,c=this._compilationPromises;n===null&&(n=e);let u=e.isScene===!0?e:n.isScene===!0?n:EM,h=this.needsFrameBufferTarget&&this._renderTarget===null?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,p=this._renderContexts.get(h,this._mrt),f=this._activeMipmapLevel,m=[];this._currentRenderContext=p,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=m,i.renderId++,i.update(),p.depth=this.depth,p.stencil=this.stencil,p.clippingContext||(p.clippingContext=new Xm),p.clippingContext.updateGlobal(u,t),e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t=this._updateCamera(t),u.onBeforeRender(this,e,t,h);let y=t.isArrayCamera?Uf:Bf;t.isArrayCamera?y.setFromArrayCamera(t):(jc.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),y.setFromProjectionMatrix(jc,t.coordinateSystem,t.reversedDepth));let x=this._renderLists.get(u,t);if(x.begin(),this._projectObject(e,t,0,x,p.clippingContext),n!==e&&n.traverseVisible(function(w){w.isLight&&w.layers.test(t.layers)&&x.pushLight(w)}),x.finish(),h!==null){this._textures.updateRenderTarget(h,f);let w=this._textures.get(h);p.textures=w.textures,p.depthTexture=w.depthTexture}else p.textures=null,p.depthTexture=null;n!==e?this._background.update(n,x,p):this._background.update(u,x,p);let b=x.opaque,_=x.transparent,S=x.transparentDoublePass,M=x.lightsNode;this.opaque===!0&&b.length>0&&this._renderObjects(b,t,u,M),this.transparent===!0&&_.length>0&&this._renderTransparents(_,S,t,u,M),i.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this._compilationPromises=c;for(let w of m){let T=this._objects.get(w.object,w.material,w.scene,w.camera,w.lightsNode,w.renderContext,w.clippingContext,w.passId);T.drawRange=w.object.geometry.drawRange,T.group=w.group,await this._nodes.getForRenderAsync(T),this._nodes.updateBefore(T),this._geometries.updateForRender(T),this._nodes.updateForRender(T),this._bindings.updateForRender(T);let R=[];this._pipelines.getForRender(T,R),R.length>0&&await Promise.all(R),this._nodes.updateAfter(T),await cy()}}async renderAsync(e,t){Ce('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){G("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){this._inspector!==null&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){let t=this.contextNode.value;e===!0?(t.modelViewMatrix=Nx,t.modelNormalViewMatrix=Px):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){let e=this.contextNode.value;return e.modelViewMatrix===Nx&&e.modelNormalViewMatrix===Px}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Ce('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:
Message: ${e.message}`;e.reason&&(t+=`
Reason: ${e.reason}`),G(t),this._isDeviceLost=!0}_onError(e){let t=`WebGPURenderer: Uncaptured ${e.api} ${e.type}`;e.message&&(t+=`: ${e.message}`),G(t)}_bundleNeedsUpdate(e,t){return t.bundleGPU===void 0||e.version!==t.version}_renderBundle(e,t,n){let{bundleGroup:i,camera:s,renderList:a}=e,o=this._currentRenderContext,l=this._bundles.get(i,s,o),c=this.backend.get(l);if(this._bundleNeedsUpdate(i,c)){this.backend.beginBundle(o),this._currentRenderBundle=l;let{transparentDoublePass:d,transparent:h,opaque:p}=a;this.opaque===!0&&p.length>0&&this._renderObjects(p,s,t,n),this.transparent===!0&&h.length>0&&this._renderTransparents(h,d,s,t,n),this._currentRenderBundle=null,this.backend.finishBundle(o,l),c.version=i.version}else{let{renderObjects:d}=c;for(let h=0,p=d.length;h<p;h++){let f=d[h];this._nodes.needsRefresh(f)&&(this._nodes.updateBefore(f),this._geometries.updateForRender(f),this._nodes.updateForRender(f),this._bindings.updateForRender(f),this._nodes.updateAfter(f))}}this.backend.addBundle(o,l)}render(e,t){if(this._initialized===!1)throw new Error('THREE.Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_renderOutputLayers(e,t){if(t.texture.isArrayTexture!==!0||t.texture.image.depth<=1){this._renderScene(e,e.camera,!1);return}let n=this._activeCubeFace;try{for(let i=0;i<t.texture.image.depth;i++)this._nodes.setOutputLayerIndex(i),this._activeCubeFace=i,this._renderScene(e,e.camera,!1)}finally{this._nodes.setOutputLayerIndex(0),this._activeCubeFace=n}}_getFrameBufferTarget(){let{currentToneMapping:e,currentColorSpace:t}=this,n=e!==Ki,i=t!==Fe.workingColorSpace;if(n===!1&&i===!1)return null;let{width:s,height:a}=this.getDrawingBufferSize(Yc),{depth:o,stencil:l}=this,c=this._outputRenderTarget||this._canvasTarget,u=this._frameBufferTargets.get(c);if(u===void 0){u=new Jt(s,a,{depthBuffer:o,stencilBuffer:l,type:this._outputBufferType,format:bn,colorSpace:Fe.workingColorSpace,generateMipmaps:!1,minFilter:St,magFilter:St,samples:this.samples}),u.isPostProcessingRenderTarget=!0;let y=()=>{c.removeEventListener("dispose",y),u.dispose(),this._frameBufferTargets.delete(c)};c.addEventListener("dispose",y),this._frameBufferTargets.set(c,u)}let d=this.getOutputRenderTarget();u.depthBuffer=o,u.stencilBuffer=l,d!==null?u.setSize(d.width,d.height,d.depth):u.setSize(s,a,1);let h=this._outputRenderTarget?this._outputRenderTarget.viewport:c._viewport,p=this._outputRenderTarget?this._outputRenderTarget.scissor:c._scissor,f=this._outputRenderTarget?1:c._pixelRatio,m=this._outputRenderTarget?this._outputRenderTarget.scissorTest:c._scissorTest;return u.viewport.copy(h),u.scissor.copy(p),u.viewport.multiplyScalar(f),u.scissor.multiplyScalar(f),u.scissorTest=m,u.multiview=d!==null?d.multiview:!1,u.useArrayDepthTexture=d!==null?d.useArrayDepthTexture:!1,u.resolveDepthBuffer=d!==null?d.resolveDepthBuffer:!0,u._autoAllocateDepthBuffer=d!==null?d._autoAllocateDepthBuffer:!1,u}_renderScene(e,t,n=!0){if(this._isDeviceLost===!0)return;let i=n?this._getFrameBufferTarget():null,s=this._nodes.nodeFrame,a=s.renderId,o=this._currentRenderContext,l=this._currentRenderObjectFunction,c=this._handleObjectFunction;this.lighting.beginRender(e),this._callDepth++;let u=e.isScene===!0?e:EM,d=this._renderTarget||this._outputRenderTarget,h=this._activeCubeFace,p=this._activeMipmapLevel,f;if(i!==null?(f=i,this.setRenderTarget(f)):f=d,f!==null&&f.depthBuffer===!0){let q=this._textures.get(f);q.depthInitialized!==!0&&((this.autoClear===!1||this.autoClear===!0&&this.autoClearDepth===!1)&&this.clearDepth(),q.depthInitialized=!0)}let m=this._renderContexts.get(f,this._mrt,this._callDepth);this._currentRenderContext=m,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,s.renderId=this.info.calls,this.backend.updateTimeStampUID(m),this.inspector.beginRender(this.backend.getTimestampUID(m),e,t,f),e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t=this._updateCamera(t);let y=this._canvasTarget,x=y._viewport,b=y._scissor,_=y._pixelRatio;f!==null&&(x=f.viewport,b=f.scissor,_=1),this.getDrawingBufferSize(Yc),Hy.set(0,0,Yc.width,Yc.height);let S=x.minDepth===void 0?0:x.minDepth,M=x.maxDepth===void 0?1:x.maxDepth;m.viewportValue.copy(x).multiplyScalar(_).floor(),m.viewportValue.width>>=p,m.viewportValue.height>>=p,m.viewportValue.minDepth=S,m.viewportValue.maxDepth=M,m.viewport=m.viewportValue.equals(Hy)===!1,m.scissorValue.copy(b).multiplyScalar(_).floor(),m.scissor=y._scissorTest&&m.scissorValue.equals(Hy)===!1,m.scissorValue.width>>=p,m.scissorValue.height>>=p,m.clippingContext||(m.clippingContext=new Xm),m.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,f);let w=t.isArrayCamera?Uf:Bf;t.isArrayCamera?w.setFromArrayCamera(t):(jc.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),w.setFromProjectionMatrix(jc,t.coordinateSystem,t.reversedDepth));let T=this._renderLists.get(e,t);if(T.begin(),this._projectObject(e,t,0,T,m.clippingContext),T.finish(),this.sortObjects===!0&&T.sort(this._opaqueSort,this._transparentSort,t.reversedDepth),f!==null){this._textures.updateRenderTarget(f,p);let q=this._textures.get(f);m.textures=q.textures,m.depthTexture=q.depthTexture,m.width=q.width,m.height=q.height,m.renderTarget=f,m.depth=f.depthBuffer,m.stencil=f.stencilBuffer}else m.textures=null,m.depthTexture=null,m.width=Yc.width,m.height=Yc.height,m.depth=this.depth,m.stencil=this.stencil;m.width>>=p,m.height>>=p,m.activeCubeFace=h,m.activeMipmapLevel=p,m.occlusionQueryCount=T.occlusionQueryCount,m.scissorValue.max(Br.set(0,0,0,0)),m.scissorValue.x+m.scissorValue.width>m.width&&(m.scissorValue.width=Math.max(m.width-m.scissorValue.x,0)),m.scissorValue.y+m.scissorValue.height>m.height&&(m.scissorValue.height=Math.max(m.height-m.scissorValue.y,0)),this._background.update(u,T,m),m.camera=t,this.backend.beginRender(m);let{bundles:R,lightsNode:D,transparentDoublePass:L,transparent:B,opaque:W}=T;return R.length>0&&this._renderBundles(R,u,D),this.opaque===!0&&W.length>0&&this._renderObjects(W,t,u,D),this.transparent===!0&&B.length>0&&this._renderTransparents(B,L,t,u,D),this.backend.finishRender(m),s.renderId=a,this._currentRenderContext=o,this._currentRenderObjectFunction=l,this._handleObjectFunction=c,this.lighting.finishRender(e),this._callDepth--,i!==null&&(this.setRenderTarget(d,h,p),this._renderOutput(f)),u.onAfterRender(this,e,t,f),this.inspector.finishRender(this.backend.getTimestampUID(m)),m}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){let t=this._nodes.getOutputCacheKey(),n=this._quadCache.get(e.texture),i;if(n===void 0){i=new Is(new We),i.name="Output Color Transform",i.material.name="outputColorTransform",i.material.fragmentNode=this._nodes.getOutputNode(e.texture),n={quad:i,cacheKey:t},this._quadCache.set(e.texture,n);let o=()=>{i.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",o)};e.texture.addEventListener("dispose",o)}else i=n.quad,n.cacheKey!==t&&(i.material.fragmentNode=this._nodes.getOutputNode(e.texture),i.material.needsUpdate=!0,n.cacheKey=t);let s=this.autoClear,a=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderOutputLayers(i,e),this.autoClear=s,this.xr.enabled=a}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){this._initialized===!1&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,n=0,i=-1){if(t!==null&&t.isReadbackBuffer&&this.info.memoryMap.has(t)===!1){this.info.createReadbackBuffer(t);let s=()=>{t.removeEventListener("dispose",s),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",s)}if(n%4!==0||i>0&&i%4!==0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,n,i)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,n)}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,n)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,n,i){this._canvasTarget.setScissor(e,t,n,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,i,s=0,a=1){this._canvasTarget.setViewport(e,t,n,i,s,a)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this.reversedDepthBuffer===!0?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){let t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(this._initialized===!1)throw new Error('THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before using this method.');let i=this._renderTarget||this._getFrameBufferTarget(),s=null;if(i!==null){this._textures.updateRenderTarget(i);let a=this._textures.get(i);s=this._renderContexts.get(i,null,-1),s.textures=a.textures,s.depthTexture=a.depthTexture,s.width=a.width,s.height=a.height,s.renderTarget=i,s.depth=i.depthBuffer,s.stencil=i.stencilBuffer;let o=this.backend.getClearColor();s.clearColorValue.r=o.r,s.clearColorValue.g=o.g,s.clearColorValue.b=o.b,s.clearColorValue.a=o.a,s.clearDepthValue=this.getClearDepth(),s.clearStencilValue=this.getClearStencil(),s.activeCubeFace=this.getActiveCubeFace(),s.activeMipmapLevel=this.getActiveMipmapLevel(),i.depthBuffer===!0&&(a.depthInitialized=!0)}this.backend.clear(e,t,n,s),i!==null&&this._renderTarget===null&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){Ce('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,n)}async clearColorAsync(){Ce('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Ce('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Ce('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){let e=this.currentToneMapping!==Ki,t=this.currentColorSpace!==Fe.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return this._renderTarget!==null?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:Ki}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Fe.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}dispose(){if(this._initialized===!0){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(let e of this._frameBufferTargets.keys())e.dispose();Object.values(this.backend.timestampQueryPool).forEach(e=>{e!==null&&e.dispose()})}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null);for(let e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(this._isDeviceLost===!0)return;if(this._initialized===!1)return X("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);let n=this._nodes.nodeFrame,i=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);let s=this.backend,a=this._pipelines,o=this._bindings,l=this._nodes,c=Array.isArray(e)?e:[e];if(c[0]===void 0||c[0].isComputeNode!==!0)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");s.beginCompute(e);for(let u of c){if(a.has(u)===!1){let p=()=>{u.removeEventListener("dispose",p),a.delete(u),o.deleteForCompute(u),l.delete(u)};u.addEventListener("dispose",p);let f=u.onInitFunction;f!==null&&f.call(u,{renderer:this})}l.updateForCompute(u),o.updateForCompute(u);let d=o.getForCompute(u),h=a.getForCompute(u,d);s.compute(e,u,d,h,t)}s.finishCompute(e),n.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){this._initialized===!1&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Ce('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return this._initialized===!1&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(this._initialized===!1)throw new Error('THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Ce('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(this._initialized===!1)throw new Error('THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(this._initialized===!1)throw new Error('THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateRenderTarget(e);let t=this._textures.get(e),n=this._renderContexts.get(e);n.textures=t.textures,n.depthTexture=t.depthTexture,n.width=t.width,n.height=t.height,n.renderTarget=e,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,this.backend.initRenderTarget(n)}copyFramebufferToTexture(e,t=null){if(t!==null)if(t.isVector2)t=Br.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=Br.copy(t).floor();else{G("Renderer.copyFramebufferToTexture: Invalid rectangle.");return}else t=Br.set(0,0,e.image.width,e.image.height);let n=this._currentRenderContext,i;n!==null?i=n.renderTarget:(i=this._renderTarget||this._getFrameBufferTarget(),i!==null&&(this._textures.updateRenderTarget(i),n=this._textures.get(i))),this._textures.updateTexture(e,{renderTarget:i}),this.backend.copyFramebufferToTexture(e,n,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,i=null,s=0,a=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,i,s,a),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,i,s,a=0,o=0){return this.backend.copyTextureToBuffer(e.textures[a],t,n,i,s,o)}_projectObject(e,t,n,i,s){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(s=s.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){let l=t.isArrayCamera?Uf:Bf;if(!e.frustumCulled||l.intersectsSprite(e)){this.sortObjects===!0&&Br.setFromMatrixPosition(e.matrixWorld).applyMatrix4(jc);let{geometry:c,material:u}=e;u.visible&&i.push(e,c,u,n,Br.z,null,s)}}else if(e.isLineLoop)G("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){let l=t.isArrayCamera?Uf:Bf;if(!e.frustumCulled||l.intersectsObject(e)){let{geometry:c,material:u}=e;if(this.sortObjects===!0&&(c.boundingSphere===null&&c.computeBoundingSphere(),Br.copy(c.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(jc)),Array.isArray(u)){let d=c.groups;for(let h=0,p=d.length;h<p;h++){let f=d[h],m=u[f.materialIndex];m&&m.visible&&i.push(e,c,m,n,Br.z,f,s)}}else u.visible&&i.push(e,c,u,n,Br.z,null,s)}}}if(e.isBundleGroup===!0&&this.backend.beginBundle!==void 0){let l=i;i=this._renderLists.get(e,t);let c=this._bundles.get(e,t,this._currentRenderContext),u=this.backend.get(c);if(this._bundleNeedsUpdate(e,u)){i.begin(),u.renderObjects===void 0?u.renderObjects=[]:u.renderObjects.length=0;let h=e.children;for(let p=0,f=h.length;p<f;p++)this._projectObject(h[p],t,n,i,s);i.finish()}l.pushBundle({bundleGroup:e,camera:t,renderList:i});return}let o=e.children;for(let l=0,c=o.length;l<c;l++)this._projectObject(o[l],t,n,i,s)}_renderBundles(e,t,n){for(let i of e)this._renderBundle(i,t,n)}_renderTransparents(e,t,n,i,s){if(t.length>0){for(let{material:a}of t)a.side=ln;this._renderObjects(t,n,i,s,"backSide");for(let{material:a}of t)a.side=oi;this._renderObjects(e,n,i,s);for(let{material:a}of t)a.side=Ri}else this._renderObjects(e,n,i,s)}_renderObjects(e,t,n,i,s=null){for(let a=0,o=e.length;a<o;a++){let{object:l,geometry:c,material:u,group:d,clippingContext:h}=e[a];this._currentRenderObjectFunction(l,n,t,c,u,d,i,h,s)}}_getShadowNodes(e){let t=e.version,n=this._cacheShadowNodes.get(e);if(n===void 0||n.version!==t){let i=e.map&&e.map.isTexture,s=e.colorNode&&e.colorNode.isNode,a=e.castShadowNode&&e.castShadowNode.isNode,o=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode,l=null,c=null,u=null;if(i||s||a||o){let d,h;if(a?(d=e.castShadowNode.rgb,h=e.castShadowNode.a,this.shadowMap.transmitted!==!0&&Ce("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(d=N(0),h=v(1)),i&&(h=h.mul(dt("map","texture",e).a)),s&&(h=h.mul(e.colorNode.a)),c=J(d,h),o){let p=e.maskShadowNode||e.maskNode;c=P(([f])=>(p.not().discard(),f))(c)}}e.depthNode&&e.depthNode.isNode&&(u=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?l=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(l=e.positionNode),n={version:t,colorNode:c,depthNode:u,positionNode:l},this._cacheShadowNodes.set(e,n)}return n}_updateCamera(e){let t=this.xr;if(t.isPresenting===!1){let n=!1;if(this.reversedDepthBuffer===!0&&e.reversedDepth!==!0){if(e._reversedDepth=!0,e.isArrayCamera)for(let s of e.cameras)s._reversedDepth=!0;n=!0}let i=this.coordinateSystem;if(e.coordinateSystem!==i){if(e.coordinateSystem=i,e.isArrayCamera)for(let s of e.cameras)s.coordinateSystem=i;n=!0}if(n===!0&&(e.updateProjectionMatrix(),e.isArrayCamera))for(let s of e.cameras)s.updateProjectionMatrix()}return e.parent===null&&e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.enabled===!0&&t.isPresenting===!0&&(t.cameraAutoUpdate===!0&&t.updateCamera(e),e=t.getCamera()),e}renderObject(e,t,n,i,s,a,o,l=null,c=null){let u=!1,d,h,p,f,m,y,x,b=this._currentSourceMaterial;if(e.onBeforeRender(this,t,n,i,s,a),s.allowOverride===!0&&t.overrideMaterial!==null){this._currentSourceMaterial=s;let _=t.overrideMaterial;if(u=!0,d=_.isNodeMaterial?_.colorNode:null,h=_.isNodeMaterial?_.depthNode:null,p=_.isNodeMaterial?_.positionNode:null,f=t.overrideMaterial.side,m=_.displacementMap,y=_.displacementScale,x=_.displacementBias,s.positionNode&&s.positionNode.isNode&&(_.positionNode=s.positionNode),_.alphaTest=s.alphaTest,_.alphaMap=s.alphaMap,_.displacementMap=s.displacementMap,_.displacementScale=s.displacementScale,_.displacementBias=s.displacementBias,_.transparent=s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode,_.isShadowPassMaterial){let{colorNode:S,depthNode:M,positionNode:w}=this._getShadowNodes(s);this.shadowMap.type===Ta?_.side=s.shadowSide!==null?s.shadowSide:s.side:_.side=s.shadowSide!==null?s.shadowSide:qk[s.side],S!==null&&(_.colorNode=S),M!==null&&(_.depthNode=M),w!==null&&(_.positionNode=w)}s=_}s.transparent===!0&&s.side===Ri&&s.forceSinglePass===!1?(s.side=ln,this._handleObjectFunction(e,s,t,n,o,a,l,"backSide"),s.side=oi,this._handleObjectFunction(e,s,t,n,o,a,l,c),s.side=Ri):this._handleObjectFunction(e,s,t,n,o,a,l,c),u&&(t.overrideMaterial.colorNode=d,t.overrideMaterial.depthNode=h,t.overrideMaterial.positionNode=p,t.overrideMaterial.side=f,t.overrideMaterial.displacementMap=m,t.overrideMaterial.displacementScale=y,t.overrideMaterial.displacementBias=x),this._currentSourceMaterial=b,e.onAfterRender(this,t,n,i,s,a)}hasCompatibility(e){if(this._initialized===!1)throw new Error('THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,n,i,s,a,o,l){let c=this._objects.get(e,t,n,i,s,this._currentRenderContext,o,l);c.drawRange=e.geometry.drawRange,c.group=a,this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(c),c.bundle=this._currentRenderBundle.bundleGroup);let u=this._nodes.needsRefresh(c);u&&(this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c)),this._pipelines.updateForRender(c),this._pipelines.isReady(c)&&(this.backend.draw(c,this.info),u&&this._nodes.updateAfter(c))}_createObjectPipeline(e,t,n,i,s,a,o,l){if(this._compilationPromises!==null){this._compilationPromises.push({object:e,material:t,scene:n,camera:i,lightsNode:s,group:a,clippingContext:o,passId:l,renderContext:this._currentRenderContext});return}let c=this._objects.get(e,t,n,i,s,this._currentRenderContext,o,l);c.drawRange=e.geometry.drawRange,c.group=a,this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c),this._pipelines.getForRender(c,this._compilationPromises),this._nodes.updateAfter(c)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}},jm=class{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}};function cC(r){return r+($a-r%$a)%$a}var Km=class extends jm{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return cC(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}release(){this._buffer=null}},Zm=class extends Km{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}},$k=0,Jm=class extends Zm{constructor(e,t){super("UniformBuffer_"+$k++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get byteLength(){return cC(this.buffer.byteLength)}get buffer(){return this.nodeUniform.value}},Zb=class extends Zm{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map,this._addedIndices=new Set}addUniformUpdateRange(e){let t=e.index;if(this._addedIndices.has(t))return;let n=this._updateRangeCache.get(t);n===void 0&&(n={start:0,count:0},this._updateRangeCache.set(t,n)),n.start=e.offset,n.count=e.itemSize,this._addedIndices.add(t),this.updateRanges.push(n)}clearUpdateRanges(){this._addedIndices.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){let t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}get values(){return this._values===null&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(e===null){let t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){let e=this.bytesPerElement,t=0;for(let n=0,i=this.uniforms.length;n<i;n++){let s=this.uniforms[n],a=s.boundary,o=s.itemSize*e,l=t%$a,c=l%a,u=l+c;t+=c,u!==0&&$a-u<o&&(t+=$a-u),s.offset=t/e,s.index=n,t+=o}return Math.ceil(t/$a)*$a}update(){let e=!1;for(let t of this.uniforms)this.updateByType(t)===!0&&(e=!0);return e}release(){super.release(),this._values=null}updateByType(e){if(e.isNumberUniform)return this.updateNumber(e);if(e.isVector2Uniform)return this.updateVector2(e);if(e.isVector3Uniform)return this.updateVector3(e);if(e.isVector4Uniform)return this.updateVector4(e);if(e.isColorUniform)return this.updateColor(e);if(e.isMatrix3Uniform)return this.updateMatrix3(e);if(e.isMatrix4Uniform)return this.updateMatrix4(e);G("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1,n=this.values,i=e.getValue(),s=e.offset,a=e.getType();if(n[s]!==i){let o=this._getBufferForType(a);o[s]=n[s]=i,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1,n=this.values,i=e.getValue(),s=e.offset,a=e.getType();if(n[s+0]!==i.x||n[s+1]!==i.y){let o=this._getBufferForType(a);o[s+0]=n[s+0]=i.x,o[s+1]=n[s+1]=i.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1,n=this.values,i=e.getValue(),s=e.offset,a=e.getType();if(n[s+0]!==i.x||n[s+1]!==i.y||n[s+2]!==i.z){let o=this._getBufferForType(a);o[s+0]=n[s+0]=i.x,o[s+1]=n[s+1]=i.y,o[s+2]=n[s+2]=i.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1,n=this.values,i=e.getValue(),s=e.offset,a=e.getType();if(n[s+0]!==i.x||n[s+1]!==i.y||n[s+2]!==i.z||n[s+3]!==i.w){let o=this._getBufferForType(a);o[s+0]=n[s+0]=i.x,o[s+1]=n[s+1]=i.y,o[s+2]=n[s+2]=i.z,o[s+3]=n[s+3]=i.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1,n=this.values,i=e.getValue(),s=e.offset;if(n[s+0]!==i.r||n[s+1]!==i.g||n[s+2]!==i.b){let a=this.buffer;a[s+0]=n[s+0]=i.r,a[s+1]=n[s+1]=i.g,a[s+2]=n[s+2]=i.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1,n=this.values,i=e.getValue().elements,s=e.offset;if(n[s+0]!==i[0]||n[s+1]!==i[1]||n[s+2]!==i[2]||n[s+4]!==i[3]||n[s+5]!==i[4]||n[s+6]!==i[5]||n[s+8]!==i[6]||n[s+9]!==i[7]||n[s+10]!==i[8]){let a=this.buffer;a[s+0]=n[s+0]=i[0],a[s+1]=n[s+1]=i[1],a[s+2]=n[s+2]=i[2],a[s+4]=n[s+4]=i[3],a[s+5]=n[s+5]=i[4],a[s+6]=n[s+6]=i[5],a[s+8]=n[s+8]=i[6],a[s+9]=n[s+9]=i[7],a[s+10]=n[s+10]=i[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1,n=this.values,i=e.getValue().elements,s=e.offset;return Yk(n,i,s)===!1&&(this.buffer.set(i,s),Xk(n,i,s),t=!0,this.addUniformUpdateRange(e)),t}_getBufferForType(e){return e==="int"||e==="ivec2"||e==="ivec3"||e==="ivec4"?new Int32Array(this.buffer.buffer):e==="uint"||e==="uvec2"||e==="uvec3"||e==="uvec4"?new Uint32Array(this.buffer.buffer):this.buffer}};function Xk(r,e,t){for(let n=0,i=e.length;n<i;n++)r[t+n]=e[n]}function Yk(r,e,t){for(let n=0,i=e.length;n<i;n++)if(r[t+n]!==e[n])return!1;return!0}var jk=0,Qm=class extends Zb{constructor(e,t){super(e),this.id=jk++,this.groupNode=t,this.isNodeUniformsGroup=!0}},eg=class extends jm{constructor(e,t){super(e),this._texture=t,this.version=-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture=e,this.reset())}get texture(){return this._texture}update(){let{texture:e,version:t}=this;return t!==e.version?(this.version=e.version,!0):!1}reset(){this.generation=null,this.version=-1}release(){this._texture=null}},Kk=0,Jb=class extends eg{constructor(e,t){super(e,t),this.id=Kk++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}},Su=class extends Jb{constructor(e,t,n,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=i}update(){let{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}},tg=class extends Su{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledCubeTexture=!0}},jh=class extends Su{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledTexture3D=!0}},RM={bitcast_int_uint:new st("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new st("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }"),textureGather:new st(`
vec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {
if ( flipY ) offset.y = - offset.y;
vec2 size = vec2( textureSize( map, 0 ) );
vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
vec4 ret = vec4(
textureLod( map, ij.xw, 0.0 )[ comp ],
textureLod( map, ij.zw, 0.0 )[ comp ],
textureLod( map, ij.zy, 0.0 )[ comp ],
textureLod( map, ij.xy, 0.0 )[ comp ]
);
return flipY ? ret.wzyx : ret;
}
`),textureGatherArray:new st(`
vec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {
if ( flipY ) offset.y = - offset.y;
vec2 size = vec2( textureSize( map, 0 ).xy );
vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
vec4 ret = vec4(
textureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],
textureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],
textureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],
textureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]
);
return flipY ? ret.wzyx : ret;
}
`),textureGatherCompare:new st(`
vec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {
if ( flipY ) offset.y = - offset.y;
vec2 size = vec2( textureSize( map, 0 ) );
vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
vec4 ret = vec4(
textureLod( map, vec3( ij.xw, ref ), 0.0 ),
textureLod( map, vec3( ij.zw, ref ), 0.0 ),
textureLod( map, vec3( ij.zy, ref ), 0.0 ),
textureLod( map, vec3( ij.xy, ref ), 0.0 )
);
return flipY ? ret.wzyx : ret;
}
`),textureGatherCompareArray:new st(`
vec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {
if ( flipY ) offset.y = - offset.y;
vec2 size = vec2( textureSize( map, 0 ).xy );
vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
vec4 ret = vec4(
texture( map, vec4( ij.xw, coord.z, ref ) ),
texture( map, vec4( ij.zw, coord.z, ref ) ),
texture( map, vec4( ij.zy, coord.z, ref ) ),
texture( map, vec4( ij.xy, coord.z, ref ) )
);
return flipY ? ret.wzyx : ret;
}
`)},Zk={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},AM={low:"lowp",medium:"mediump",high:"highp"},CM={swizzleAssign:!0,storageBuffer:!1},NM={perspective:"smooth",linear:"noperspective"},PM={centroid:"centroid"},DM=`
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp sampler3D;
precision highp samplerCube;
precision highp sampler2DArray;
precision highp usampler2D;
precision highp usampler3D;
precision highp usamplerCube;
precision highp usampler2DArray;
precision highp isampler2D;
precision highp isampler3D;
precision highp isamplerCube;
precision highp isampler2DArray;
precision highp sampler2DShadow;
precision highp sampler2DArrayShadow;
precision highp samplerCubeShadow;
`,Qb=class extends Wm{constructor(e,t){super(e,t,new Hb),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==cn}_include(e){let t=RM[e];return t.build(this),this.addInclude(t),t}getMethod(e){return RM[e]!==void 0&&this._include(e),Zk[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`${e} ? ${t} : ${n}`}getOutputStructName(){return""}buildFunctionCode(e){let t=e.layout,n=this.flowShaderNode(e),i=[];for(let a of t.inputs)i.push(this.getType(a.type)+" "+a.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {
${n.vars}
${n.code}
return ${n.result};
}`}setupPBO(e){let t=e.value;if(t.pbo===void 0){let n=t.array,i=t.count*t.itemSize,{itemSize:s}=t,a=t.array.constructor.name.toLowerCase().includes("int"),o=a?Ia:Da;s===2?o=a?Fa:mi:s===3?o=a?Yd:Pa:s===4&&(o=a?mc:bn);let l={Float32Array:en,Uint8Array:Gt,Uint16Array:qs,Uint32Array:it,Int8Array:Dr,Int16Array:Ir,Int32Array:zt,Uint8ClampedArray:Gt},c=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(i/s)))),u=Math.ceil(i/s/c);c*u*s<i&&u++;let d=c*u*s,h=new n.constructor(d);h.set(n,0),t.array=h;let p=new ga(t.array,c,u,o,l[t.array.constructor.name]||en);p.needsUpdate=!0,p.isPBOTexture=!0;let f=new cs(p,null,null);f.setPrecision("high"),t.pboNode=f,t.pbo=f.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&e.node.isTextureNode!==!0&&e.node.isBufferNode!==!0?e.name:super.getPropertyName(e,t)}generatePBO(e){let{node:t,indexNode:n}=e,i=t.value;if(this.renderer.backend.has(i)){let u=this.renderer.backend.get(i);u.pbo=i.pbo}let s=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),a=this.getPropertyName(s);this.increaseUsage(n);let o=n.build(this,"uint"),l=this.getDataFromNode(e),c=l.propertyName;if(c===void 0){let u=this.getVarFromNode(e);c=this.getPropertyName(u);let d=this.getDataFromNode(t),h=d.propertySizeName;h===void 0&&(h=c+"Size",this.getVarFromNode(t,h,"uint"),this.addLineFlowCode(`${h} = uint( textureSize( ${a}, 0 ).x )`,e),d.propertySizeName=h);let{itemSize:p}=i,f="."+fl.join("").slice(0,p),m=`ivec2(${o} % ${h}, ${o} / ${h})`,y=this.generateTextureLoad(null,a,m,"0",null,null),x="vec4";i.pbo.type===it?x="uvec4":i.pbo.type===zt&&(x="ivec4"),this.addLineFlowCode(`${c} = ${x}(${y})${f}`,e),l.propertyName=c}return c}generateTextureLoad(e,t,n,i,s,a){i===null&&(i="0");let o;return s?a?o=`texelFetchOffset( ${t}, ivec3( ${n}, ${s} ), int( ${i} ), ${a} )`:o=`texelFetch( ${t}, ivec3( ${n}, ${s} ), int( ${i} ) )`:a?o=`texelFetchOffset( ${t}, ${n}, int( ${i} ), ${a} )`:o=`texelFetch( ${t}, ${n}, int( ${i} ) )`,e!==null&&e.isDepthTexture&&(o+=".x"),o}generateTexture(e,t,n,i,s){return i&&(n=`vec3( ${n}, ${i} )`),e.isDepthTexture?s?`textureOffset( ${t}, ${n}, ${s} ).x`:`texture( ${t}, ${n} ).x`:s?`textureOffset( ${t}, ${n}, ${s} )`:`texture( ${t}, ${n} )`}generateTextureLevel(e,t,n,i,s,a){return s&&(n=`vec3( ${n}, ${s} )`),a?`textureLodOffset( ${t}, ${n}, ${i}, ${a} )`:`textureLod( ${t}, ${n}, ${i} )`}generateTextureBias(e,t,n,i,s,a){return s&&(n=`vec3( ${n}, ${s} )`),a?`textureOffset( ${t}, ${n}, ${a}, ${i} )`:`texture( ${t}, ${n}, ${i} )`}generateTextureGrad(e,t,n,i,s,a){return s&&(n=`vec3( ${n}, ${s} )`),a?`textureGradOffset( ${t}, ${n}, ${i[0]}, ${i[1]}, ${a} )`:`textureGrad( ${t}, ${n}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,n,i,s,a,o=this.shaderStage){if(o==="fragment")return e.isCubeTexture?`texture( ${t}, vec4( ${n}, ${i} ) )`:s?a?`textureOffset( ${t}, vec4( ${n}, ${s}, ${i} ), ${a} )`:`texture( ${t}, vec4( ${n}, ${s}, ${i} ) )`:a?`textureOffset( ${t}, vec3( ${n}, ${i} ), ${a} )`:`texture( ${t}, vec3( ${n}, ${i} ) )`;G(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}generateTextureGather(e,t,n,i,s,a,o){return e.isDepthTexture&&(i="0"),a===null&&(a="ivec2( 0 )"),o===null&&(o="false"),s?(this._include("textureGatherArray"),`tsl_textureGather_array( ${i}, ${t}, vec3( ${n}, ${s} ), ${a}, ${o} )`):(this._include("textureGather"),`tsl_textureGather( ${i}, ${t}, ${n}, ${a}, ${o} )`)}generateTextureGatherCompare(e,t,n,i,s,a,o){return a===null&&(a="ivec2( 0 )"),o===null&&(o="false"),s?(this._include("textureGatherCompareArray"),`tsl_textureGatherCompare_array( ${t}, vec3( ${n}, ${s} ), ${a}, ${i}, ${o} )`):(this._include("textureGatherCompare"),`tsl_textureGatherCompare( ${t}, ${n}, ${a}, ${i}, ${o} )`)}getUniforms(e){let t=this.uniforms[e],n=[],i={};for(let a of t){let o=null,l=!1;if(a.type==="texture"||a.type==="texture3D"){let c=a.node,u=c.value,d="";(u.isDataTexture===!0||u.isData3DTexture===!0)&&(u.type===it?d="u":u.type===zt&&(d="i")),a.type==="texture3D"&&u.isArrayTexture===!1?o=`${d}sampler3D ${a.name};`:u.compareFunction&&c.compareNode!==null?u.isArrayTexture===!0?o=`sampler2DArrayShadow ${a.name};`:o=`sampler2DShadow ${a.name};`:u.isArrayTexture===!0||u.isDataArrayTexture===!0||u.isCompressedArrayTexture===!0?o=`${d}sampler2DArray ${a.name};`:o=`${d}sampler2D ${a.name};`}else if(a.type==="cubeTexture")o=`samplerCube ${a.name};`;else if(a.type==="cubeDepthTexture")a.node.value.compareFunction?o=`samplerCubeShadow ${a.name};`:o=`samplerCube ${a.name};`;else if(a.type==="buffer"){let c=a.node,u=this.getType(c.bufferType),d=c.bufferCount,h=d>0?d:"";o=`${c.name} {
${u} ${a.name}[${h}];
};
`}else{let c=a.groupNode.name;if(i[c]===void 0){let u=this.uniformGroups[c];if(u!==void 0){let d=[];for(let h of u.uniforms){let p=h.getType(),f=this.getVectorType(p),m=h.nodeUniform.node.precision,y=`${f} ${h.name};`;m!==null&&(y=AM[m]+" "+y),d.push(" "+y)}i[c]=d}}l=!0}if(!l){let c=a.node.precision;c!==null&&(o=AM[c]+" "+o),o="uniform "+o,n.push(o)}}let s="";for(let a in i){let o=i[a];s+=this._getGLSLUniformStruct(a,o.join(`
`))+`
`}return s+=n.join(`
`),s}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==zt){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);let i=n.array;i instanceof Uint32Array||i instanceof Int32Array||(t=t.slice(1))}return t}getAttributes(e){let t="";if(e==="vertex"||e==="compute"){let n=this.getAttributesArray(),i=0;for(let s of n)t+=`layout( location = ${i++} ) in ${s.type} ${s.name};
`}return t}getStructMembers(e){let t=[];for(let n of e.members)t.push(` ${n.type} ${n.name};`);return t.join(`
`)}getStructs(e){let t=[],n=this.structs[e],i=[];for(let s of n)if(s.output)for(let a of s.members)i.push(`layout( location = ${a.index} ) out ${a.type} ${a.name};`);else{let a="struct "+s.name+` {
`;a+=this.getStructMembers(s),a+=`
};
`,t.push(a)}return e==="fragment"&&i.length===0&&i.push(`layout( location = 0 ) out ${this.getOutputType()} fragColor;`),`
`+i.join(`
`)+`
`+t.join(`
`)}getVaryings(e){let t="",n=this.varyings;if(e==="vertex"||e==="compute")for(let i of n){e==="compute"&&(i.needsInterpolation=!0);let s=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){let a=NM[i.interpolationType]||i.interpolationType,o=PM[i.interpolationSampling]||"";t+=`${a} ${o} out ${s} ${i.name};
`}else{let a=s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":"";t+=`${a}out ${s} ${i.name};
`}else t+=`${s} ${i.name};
`}else if(e==="fragment"){for(let i of n)if(i.needsInterpolation){let s=this.getType(i.type);if(i.interpolationType){let a=NM[i.interpolationType]||i.interpolationType,o=PM[i.interpolationSampling]||"";t+=`${a} ${o} in ${s} ${i.name};
`}else{let a=s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":"";t+=`${a}in ${s} ${i.name};
`}}}for(let i of this.builtins[e])t+=`${i};
`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((n,i)=>n*i,1)}u`}getSubgroupSize(){G("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){G("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){G("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){let i=this.extensions[n]||(this.extensions[n]=new Map);i.has(e)===!1&&i.set(e,{name:e,behavior:t})}getExtensions(e){let t=[];if(e==="vertex"){let i=this.renderer.backend.extensions;this.object.isBatchedMesh&&i.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}let n=this.extensions[e];if(n!==void 0)for(let{name:i,behavior:s}of n.values())t.push(`#extension ${i} : ${s}`);return t.join(`
`)}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=CM[e];if(t===void 0){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance";break}if(n!==void 0){let i=this.renderer.backend.extensions;i.has(n)&&(i.get(n),t=!0)}CM[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){let e=this.transforms,t="";for(let n=0;n<e.length;n++){let i=e[n],s=this.getPropertyName(i.attributeNode);s&&(t+=`${i.varyingName} = ${s};
`)}return t}_getGLSLUniformStruct(e,t){return`
layout( std140 ) uniform ${e} {
${t}
};`}_getGLSLVertexCode(e){return`#version 300 es
${this.getSignature()}
// extensions
${e.extensions}
// precision
${DM}
// structs
${e.structs}
// uniforms
${e.uniforms}
// varyings
${e.varyings}
// attributes
${e.attributes}
// vars
${e.vars}
// codes
${e.codes}
void main() {
// transforms
${e.transforms}
// flow
${e.flow}
gl_PointSize = 1.0;
}
`}_getGLSLFragmentCode(e){return`#version 300 es
${this.getSignature()}
// extensions
${e.extensions}
// precision
${DM}
// structs
${e.structs}
// uniforms
${e.uniforms}
// varyings
${e.varyings}
// vars
${e.vars}
// codes
${e.codes}
void main() {
// flow
${e.flow}
}
`}buildCode(){let e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(let t in e){let n=`// code
`;n+=this.flowCode[t];let i=this.flowNodes[t],s=i[i.length-1];for(let o of i){let l=this.getFlowData(o),c=o.name;c&&(n.length>0&&(n+=`
`),n+=` // flow -> ${c}
`),n+=`${l.code}
`,o===s&&t!=="compute"&&(n+=`// result
`,t==="vertex"?(n+="gl_Position = ",n+=`${this.format(l.result,s.getNodeType(this),"vec4")};`):t==="fragment"&&(o.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${this.format(l.result,s.getNodeType(this),this.getOutputType())};`)))}let a=e[t];if(a.extensions=this.getExtensions(t),a.uniforms=this.getUniforms(t),a.attributes=this.getAttributes(t),a.varyings=this.getVaryings(t),a.vars=this.getVars(t,!0),a.structs=this.getStructs(t),a.codes=this.getCodes(t),a.transforms=this.getTransforms(t),a.flow=n,t==="vertex"){let o=this.renderer.backend.extensions;this.object.isBatchedMesh&&o.has("WEBGL_multi_draw")===!1&&(a.uniforms+=`
uniform uint nodeUniformDrawId;
`)}}this.material!==null?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,i=null){let s=super.getUniformFromNode(e,t,n,i),a=this.getDataFromNode(e,n,this.globalCache),o=a.uniformGPU;if(o===void 0){let l=e.groupNode,c=l.name,u=this.getBindGroupArray(c,n);if(t==="texture")o=new Su(s.name,s.node,l),u.push(o);else if(t==="cubeTexture"||t==="cubeDepthTexture")o=new tg(s.name,s.node,l),u.push(o);else if(t==="texture3D")o=new jh(s.name,s.node,l),u.push(o);else if(t==="buffer"){s.name=`buffer${e.id}`;let d=this.getSharedDataFromNode(e),h=d.buffer;h===void 0&&(e.name=`NodeBuffer_${e.id}`,h=new Jm(e,l),h.name=e.name,d.buffer=h),u.push(h),o=h}else{let d=this.uniformGroups[c];d===void 0?(d=new Qm(c,l),this.uniformGroups[c]=d,u.push(d)):u.indexOf(d)===-1&&u.push(d),o=this.getNodeUniform(s,t);let h=o.name;d.uniforms.some(f=>f.name===h)||d.addUniform(o)}a.uniformGPU=o}return s}},Wy=null,Kc=null,ng=class{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Ji.RENDER]:null,[Ji.COMPUTE]:null},this.trackTimestamp=e.trackTimestamp===!0}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}setXRTarget(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}createUniformBuffer(){}destroyUniformBuffer(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){let t=this.get(e),n=this.renderer.info.frame,i;e.isComputeNode===!0?i="c:"+this.renderer.info.compute.frameCalls:i="r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+e.id+":f"+n}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){let t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){let t=e.startsWith("c:")?Ji.COMPUTE:Ji.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}get hasTimestamp(){return!1}hasTimestampQuery(e){return this._getQueryPool(e).hasTimestampQuery(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp){Ce("WebGPURenderer: Timestamp tracking is disabled.");return}let t=this.timestampQueryPool[e];if(!t)return;let n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return Wy=Wy||new O,this.renderer.getDrawingBufferSize(Wy)}setScissorTest(){}getClearColor(){let e=this.renderer;return Kc=Kc||new Gh,e.getClearColor(Kc),Kc.getRGB(Kc),Kc}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas!==void 0?this.parameters.canvas:ly(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${"185"} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}},Jk=0,ev=class{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[this.activeBufferIndex^1]}switchBuffers(){this.activeBufferIndex^=1}},tv=class{constructor(e){this.backend=e}createAttribute(e,t){let n=this.backend,{gl:i}=n,s=e.array,a=e.usage||i.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,l=n.get(o),c=l.bufferGPU;c===void 0&&(c=this._createBuffer(i,t,s,a),l.bufferGPU=c,l.bufferType=t,l.version=o.version);let u;if(s instanceof Float32Array)u=i.FLOAT;else if(typeof Float16Array<"u"&&s instanceof Float16Array)u=i.HALF_FLOAT;else if(s instanceof Uint16Array)e.isFloat16BufferAttribute?u=i.HALF_FLOAT:u=i.UNSIGNED_SHORT;else if(s instanceof Int16Array)u=i.SHORT;else if(s instanceof Uint32Array)u=i.UNSIGNED_INT;else if(s instanceof Int32Array)u=i.INT;else if(s instanceof Int8Array)u=i.BYTE;else if(s instanceof Uint8Array)u=i.UNSIGNED_BYTE;else if(s instanceof Uint8ClampedArray)u=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+s);let d={bufferGPU:c,bufferType:t,type:u,byteLength:s.byteLength,bytesPerElement:s.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===i.INT||u===i.UNSIGNED_INT||e.gpuType===zt,id:Jk++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){let h=this._createBuffer(i,t,s,a);d=new ev(d,h)}n.set(e,d)}updateAttribute(e){let t=this.backend,{gl:n}=t,i=e.array,s=e.isInterleavedBufferAttribute?e.data:e,a=t.get(s),o=a.bufferType,l=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(o,a.bufferGPU),l.length===0)n.bufferSubData(o,0,i);else{for(let c=0,u=l.length;c<u;c++){let d=l[c];n.bufferSubData(o,d.start*i.BYTES_PER_ELEMENT,i,d.start,d.count)}s.clearUpdateRanges()}n.bindBuffer(o,null),a.version=s.version}destroyAttribute(e){let t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);let i=t.get(e);n.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,i=-1){let s=this.backend,{gl:a}=s,o=e.isInterleavedBufferAttribute?e.data:e,l=s.get(o),{bufferGPU:c}=l,u=i===-1?l.byteLength-n:i,d;if(t===null)d=new Uint8Array(new ArrayBuffer(u));else if(t.isReadbackBuffer){if(t._mapped===!0)throw new Error("THREE.WebGPURenderer: ReadbackBuffer must be released before being used again.");let h=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener("release",h),t.removeEventListener("dispose",h)};t.addEventListener("release",h),t.addEventListener("dispose",h),d=new Uint8Array(new ArrayBuffer(u)),t.buffer=d.buffer}else d=new Uint8Array(t);return a.bindBuffer(a.COPY_READ_BUFFER,c),a.getBufferSubData(a.COPY_READ_BUFFER,n,d),a.bindBuffer(a.COPY_READ_BUFFER,null),a.bindBuffer(a.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:d.buffer}_createBuffer(e,t,n,i){let s=e.createBuffer();return e.bindBuffer(t,s),e.bufferData(t,n,i),e.bindBuffer(t,null),s}},hh,Ur,nv=class{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){let e=this.gl;hh={[ci]:e.FUNC_ADD,[qp]:e.FUNC_SUBTRACT,[$p]:e.FUNC_REVERSE_SUBTRACT},Ur={[Ws]:e.ZERO,[Xp]:e.ONE,[Yp]:e.SRC_COLOR,[fo]:e.SRC_ALPHA,[ef]:e.SRC_ALPHA_SATURATE,[Jp]:e.DST_COLOR,[Kp]:e.DST_ALPHA,[jp]:e.ONE_MINUS_SRC_COLOR,[mo]:e.ONE_MINUS_SRC_ALPHA,[Qp]:e.ONE_MINUS_DST_COLOR,[Zp]:e.ONE_MINUS_DST_ALPHA};let t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=new Ge().fromArray(t),this.currentViewport=new Ge().fromArray(n),this._tempVec4=new Ge}enable(e){let{enabled:t}=this;t[e]!==!0&&(this.gl.enable(e),t[e]=!0)}disable(e){let{enabled:t}=this;t[e]!==!1&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){let{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){let{gl:t}=this;e!==O0?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===k0?t.cullFace(t.BACK):e===V0?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){let{currentLineWidth:t,gl:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,n){let i=this.gl,s=this.backend.drawBuffersIndexedExt;if(!s){Ce("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.");return}for(let a=0;a<e.length;a++){let o=e[a],l=null;if(t!==null){let c=t.getBlendMode(o.name);c.blending===Ld?l=n:c.blending!==_s&&(l=c)}else l=n;l!==null?this._setMRTBlendingIndex(a,l):s.blendFuncSeparateiOES(a,i.ONE,i.ZERO,i.ONE,i.ZERO)}}_setMRTBlendingIndex(e,t){let{gl:n}=this,i=this.backend.drawBuffersIndexedExt,s=t.blending,a=t.blendSrc,o=t.blendDst,l=t.blendEquation,c=t.premultipliedAlpha;if(s===Ra){let u=t.blendSrcAlpha!==null?t.blendSrcAlpha:a,d=t.blendDstAlpha!==null?t.blendDstAlpha:o,h=t.blendEquationAlpha!==null?t.blendEquationAlpha:l;i.blendEquationSeparateiOES(e,hh[l],hh[h]),i.blendFuncSeparateiOES(e,Ur[a],Ur[o],Ur[u],Ur[d])}else if(i.blendEquationSeparateiOES(e,n.FUNC_ADD,n.FUNC_ADD),c)switch(s){case li:i.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case Ma:i.blendFuncSeparateiOES(e,n.ONE,n.ONE,n.ONE,n.ONE);break;case wa:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case Ea:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:i.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break}else switch(s){case li:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case Ma:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case wa:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case Ea:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break}}setBlending(e,t,n,i,s,a,o,l){let{gl:c}=this;if(e===_s){this.currentBlendingEnabled===!0&&(this.disable(c.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(c.BLEND),this.currentBlendingEnabled=!0),e!==Ra){if(e!==this.currentBlending||l!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==ci||this.currentBlendEquationAlpha!==ci)&&(c.blendEquation(c.FUNC_ADD),this.currentBlendEquation=ci,this.currentBlendEquationAlpha=ci),l)switch(e){case li:c.blendFuncSeparate(c.ONE,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case Ma:c.blendFunc(c.ONE,c.ONE);break;case wa:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case Ea:c.blendFuncSeparate(c.DST_COLOR,c.ONE_MINUS_SRC_ALPHA,c.ZERO,c.ONE);break;default:G("WebGLState: Invalid blending: ",e);break}else switch(e){case li:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case Ma:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE,c.ONE,c.ONE);break;case wa:G("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Ea:G("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:G("WebGLState: Invalid blending: ",e);break}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=l}return}s=s||t,a=a||n,o=o||i,(t!==this.currentBlendEquation||s!==this.currentBlendEquationAlpha)&&(c.blendEquationSeparate(hh[t],hh[s]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=s),(n!==this.currentBlendSrc||i!==this.currentBlendDst||a!==this.currentBlendSrcAlpha||o!==this.currentBlendDstAlpha)&&(c.blendFuncSeparate(Ur[n],Ur[i],Ur[a],Ur[o]),this.currentBlendSrc=n,this.currentBlendDst=i,this.currentBlendSrcAlpha=a,this.currentBlendDstAlpha=o),this.currentBlending=e,this.currentPremultipledAlpha=!1}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){let{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){let t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=df[e]),this.currentDepthFunc!==e){let{gl:t}=this;switch(e){case Ll:t.depthFunc(t.NEVER);break;case Bl:t.depthFunc(t.ALWAYS);break;case Ul:t.depthFunc(t.LESS);break;case ua:t.depthFunc(t.LEQUAL);break;case Ol:t.depthFunc(t.EQUAL);break;case kl:t.depthFunc(t.GEQUAL);break;case Vl:t.depthFunc(t.GREATER);break;case Gl:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,i){let s=this._tempVec4.set(e,t,n,i);if(this.currentScissor.equals(s)===!1){let{gl:a}=this;a.scissor(s.x,s.y,s.z,s.w),this.currentScissor.copy(s)}}viewport(e,t,n,i){let s=this._tempVec4.set(e,t,n,i);if(this.currentViewport.equals(s)===!1){let{gl:a}=this;a.viewport(s.x,s.y,s.z,s.w),this.currentViewport.copy(s)}}setScissorTest(e){let t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){let{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,n){(this.currentStencilFunc!==e||this.currentStencilRef!==t||this.currentStencilFuncMask!==n)&&(this.gl.stencilFunc(e,t,n),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=n)}setStencilOp(e,t,n){(this.currentStencilFail!==e||this.currentStencilZFail!==t||this.currentStencilZPass!==n)&&(this.gl.stencilOp(e,t,n),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=n)}setMaterial(e,t,n){let{gl:i}=this;e.side===Ri?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let s=e.side===ln;t&&(s=!s),this.setFlipSided(s),e.blending===li&&e.transparent===!1?this.setBlending(_s):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);let a=e.stencilWrite;if(this.setStencilTest(a),a&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),e.alphaToCoverage===!0&&this.backend.renderer.currentSamples>0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),n>0&&this.currentClippingPlanes!==n)for(let l=0;l<8;l++)l<n?this.enable(12288+l):this.disable(12288+l)}setPolygonOffset(e,t,n){let{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),(this.currentPolygonOffsetFactor!==t||this.currentPolygonOffsetUnits!==n)&&(i.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e?(this.gl.useProgram(e),this.currentProgram=e,!0):!1}setVertexState(e,t=null){let n=this.gl;return this.currentVAO!==e||this.currentIndex!==t?(n.bindVertexArray(e),t!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0):!1}resetVertexState(){let e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){let{gl:n,currentBoundFramebuffers:i}=this;return i[e]!==t?(n.bindFramebuffer(e,t),i[e]=t,e===n.DRAW_FRAMEBUFFER&&(i[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(i[n.DRAW_FRAMEBUFFER]=t),!0):!1}drawBuffers(e,t){let{gl:n}=this,i=[],s=!1;if(e.textures!==null){i=this.currentDrawbuffers.get(t),i===void 0&&(i=[],this.currentDrawbuffers.set(t,i));let a=e.textures;if(i.length!==a.length||i[0]!==n.COLOR_ATTACHMENT0){for(let o=0,l=a.length;o<l;o++)i[o]=n.COLOR_ATTACHMENT0+o;i.length=a.length,s=!0}}else i[0]!==n.BACK&&(i[0]=n.BACK,s=!0);s&&n.drawBuffers(i)}activeTexture(e){let{gl:t,currentTextureSlot:n,maxTextures:i}=this;e===void 0&&(e=t.TEXTURE0+i-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){let{gl:i,currentTextureSlot:s,currentBoundTextures:a,maxTextures:o}=this;n===void 0&&(s===null?n=i.TEXTURE0+o-1:n=s);let l=a[n];l===void 0&&(l={type:void 0,texture:void 0},a[n]=l),(l.type!==e||l.texture!==t)&&(s!==n&&(i.activeTexture(n),this.currentTextureSlot=n),i.bindTexture(e,t),l.type=e,l.texture=t)}bindBufferBase(e,t,n){let{gl:i}=this,s=`${e}-${t}`;return this.currentBoundBufferBases[s]!==n?(i.bindBufferBase(e,t,n),this.currentBoundBufferBases[s]=n,!0):!1}unbindTexture(){let{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,i=n[t];i!==void 0&&i.type!==void 0&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}getParameter(e){let{gl:t,parameters:n}=this;return n[e]!==void 0?n[e]:t.getParameter(e)}pixelStorei(e,t){let{gl:n,parameters:i}=this;i[e]!==t&&(n.pixelStorei(e,t),i[e]=t)}},iv=class{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=cn){let{gl:n,extensions:i}=this,s,a=Fe.getTransfer(t);if(e===Gt)return n.UNSIGNED_BYTE;if(e===qd)return n.UNSIGNED_SHORT_4_4_4_4;if(e===$d)return n.UNSIGNED_SHORT_5_5_5_1;if(e===pc)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===fc)return n.UNSIGNED_INT_10F_11F_11F_REV;if(e===Dr)return n.BYTE;if(e===Ir)return n.SHORT;if(e===qs)return n.UNSIGNED_SHORT;if(e===zt)return n.INT;if(e===it)return n.UNSIGNED_INT;if(e===en)return n.FLOAT;if(e===xt)return n.HALF_FLOAT;if(e===Xd)return n.ALPHA;if(e===Pa)return n.RGB;if(e===bn)return n.RGBA;if(e===ui)return n.DEPTH_COMPONENT;if(e===Zi)return n.DEPTH_STENCIL;if(e===Da)return n.RED;if(e===Ia)return n.RED_INTEGER;if(e===mi)return n.RG;if(e===Fa)return n.RG_INTEGER;if(e===mc)return n.RGBA_INTEGER;if(e===Do||e===Io||e===Fo||e===Lo)if(a===be)if(s=i.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(e===Do)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===Io)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Fo)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Lo)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=i.get("WEBGL_compressed_texture_s3tc"),s!==null){if(e===Do)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===Io)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Fo)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Lo)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(e===jd||e===Kd||e===Zd||e===Jd)if(s=i.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(e===jd)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Kd)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Zd)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Jd)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(e===gc||e===yc||e===xc||e===_c||e===bc||e===Bo||e===vc)if(s=i.get("WEBGL_compressed_texture_etc"),s!==null){if(e===gc||e===yc)return a===be?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(e===xc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(e===_c)return s.COMPRESSED_R11_EAC;if(e===bc)return s.COMPRESSED_SIGNED_R11_EAC;if(e===Bo)return s.COMPRESSED_RG11_EAC;if(e===vc)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(e===Sc||e===Tc||e===Mc||e===wc||e===Ec||e===Rc||e===Ac||e===Cc||e===Nc||e===Pc||e===Dc||e===Ic||e===Fc||e===Lc)if(s=i.get("WEBGL_compressed_texture_astc"),s!==null){if(e===Sc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Tc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Mc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===wc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Ec)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===Rc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Ac)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Cc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Nc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Pc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Dc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Ic)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Fc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===Lc)return a===be?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(e===Bc||e===Uc||e===Oc)if(s=i.get("EXT_texture_compression_bptc"),s!==null){if(e===Bc)return a===be?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(e===Uc)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(e===Oc)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(e===kc||e===Vc||e===Uo||e===Gc)if(s=i.get("EXT_texture_compression_rgtc"),s!==null){if(e===kc)return s.COMPRESSED_RED_RGTC1_EXT;if(e===Vc)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===Uo)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===Gc)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return e===vs?n.UNSIGNED_INT_24_8:n[e]!==void 0?n[e]:null}_clientWaitAsync(){let{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((n,i)=>{function s(){let a=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(a===e.WAIT_FAILED){e.deleteSync(t),i();return}if(a===e.TIMEOUT_EXPIRED){requestAnimationFrame(s);return}e.deleteSync(t),n()}s()})}},IM=!1,Of,qy,FM,sv=class{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,IM===!1&&(this._init(),IM=!0)}_init(){let e=this.gl;Of={[Ei]:e.REPEAT,[ai]:e.CLAMP_TO_EDGE,[da]:e.MIRRORED_REPEAT},qy={[vt]:e.NEAREST,[rf]:e.NEAREST_MIPMAP_NEAREST,[Na]:e.NEAREST_MIPMAP_LINEAR,[St]:e.LINEAR,[Wd]:e.LINEAR_MIPMAP_NEAREST,[bs]:e.LINEAR_MIPMAP_LINEAR},FM={[of]:e.NEVER,[uf]:e.ALWAYS,[eh]:e.LESS,[Oo]:e.LEQUAL,[lf]:e.EQUAL,[La]:e.GEQUAL,[zc]:e.GREATER,[cf]:e.NOTEQUAL}}getGLTextureType(e){let{gl:t}=this,n;return e.isCubeTexture===!0?n=t.TEXTURE_CUBE_MAP:e.isArrayTexture===!0||e.isDataArrayTexture===!0||e.isCompressedArrayTexture===!0?n=t.TEXTURE_2D_ARRAY:e.isData3DTexture===!0?n=t.TEXTURE_3D:n=t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,s,a=!1){let{gl:o,extensions:l}=this;if(e!==null){if(o[e]!==void 0)return o[e];X("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let c=null;i&&(c=l.get("EXT_texture_norm16"),c||X("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let u=t;if(t===o.RED&&(n===o.FLOAT&&(u=o.R32F),n===o.HALF_FLOAT&&(u=o.R16F),n===o.UNSIGNED_BYTE&&(u=o.R8),n===o.BYTE&&(u=o.R8_SNORM),n===o.UNSIGNED_SHORT&&c&&(u=c.R16_EXT),n===o.SHORT&&c&&(u=c.R16_SNORM_EXT)),t===o.RED_INTEGER&&(n===o.UNSIGNED_BYTE&&(u=o.R8UI),n===o.UNSIGNED_SHORT&&(u=o.R16UI),n===o.UNSIGNED_INT&&(u=o.R32UI),n===o.BYTE&&(u=o.R8I),n===o.SHORT&&(u=o.R16I),n===o.INT&&(u=o.R32I)),t===o.RG&&(n===o.FLOAT&&(u=o.RG32F),n===o.HALF_FLOAT&&(u=o.RG16F),n===o.UNSIGNED_BYTE&&(u=o.RG8),n===o.BYTE&&(u=o.RG8_SNORM),n===o.UNSIGNED_SHORT&&c&&(u=c.RG16_EXT),n===o.SHORT&&c&&(u=c.RG16_SNORM_EXT)),t===o.RG_INTEGER&&(n===o.UNSIGNED_BYTE&&(u=o.RG8UI),n===o.UNSIGNED_SHORT&&(u=o.RG16UI),n===o.UNSIGNED_INT&&(u=o.RG32UI),n===o.BYTE&&(u=o.RG8I),n===o.SHORT&&(u=o.RG16I),n===o.INT&&(u=o.RG32I)),t===o.RGB){let d=a?Wl:Fe.getTransfer(s);n===o.FLOAT&&(u=o.RGB32F),n===o.HALF_FLOAT&&(u=o.RGB16F),n===o.UNSIGNED_BYTE&&(u=d===be?o.SRGB8:o.RGB8),n===o.BYTE&&(u=o.RGB8_SNORM),n===o.UNSIGNED_SHORT&&c&&(u=c.RGB16_EXT),n===o.SHORT&&c&&(u=c.RGB16_SNORM_EXT),n===o.UNSIGNED_SHORT_5_6_5&&(u=o.RGB565),n===o.UNSIGNED_SHORT_5_5_5_1&&(u=o.RGB5_A1),n===o.UNSIGNED_SHORT_4_4_4_4&&(u=o.RGB4),n===o.UNSIGNED_INT_5_9_9_9_REV&&(u=o.RGB9_E5),n===o.UNSIGNED_INT_10F_11F_11F_REV&&(u=o.R11F_G11F_B10F)}if(t===o.RGB_INTEGER&&(n===o.UNSIGNED_BYTE&&(u=o.RGB8UI),n===o.UNSIGNED_SHORT&&(u=o.RGB16UI),n===o.UNSIGNED_INT&&(u=o.RGB32UI),n===o.BYTE&&(u=o.RGB8I),n===o.SHORT&&(u=o.RGB16I),n===o.INT&&(u=o.RGB32I)),t===o.RGBA){let d=a?Wl:Fe.getTransfer(s);n===o.FLOAT&&(u=o.RGBA32F),n===o.HALF_FLOAT&&(u=o.RGBA16F),n===o.UNSIGNED_BYTE&&(u=d===be?o.SRGB8_ALPHA8:o.RGBA8),n===o.BYTE&&(u=o.RGBA8_SNORM),n===o.UNSIGNED_SHORT&&c&&(u=c.RGBA16_EXT),n===o.SHORT&&c&&(u=c.RGBA16_SNORM_EXT),n===o.UNSIGNED_SHORT_4_4_4_4&&(u=o.RGBA4),n===o.UNSIGNED_SHORT_5_5_5_1&&(u=o.RGB5_A1)}return t===o.RGBA_INTEGER&&(n===o.UNSIGNED_BYTE&&(u=o.RGBA8UI),n===o.UNSIGNED_SHORT&&(u=o.RGBA16UI),n===o.UNSIGNED_INT&&(u=o.RGBA32UI),n===o.BYTE&&(u=o.RGBA8I),n===o.SHORT&&(u=o.RGBA16I),n===o.INT&&(u=o.RGBA32I)),t===o.DEPTH_COMPONENT&&(n===o.UNSIGNED_SHORT&&(u=o.DEPTH_COMPONENT16),n===o.UNSIGNED_INT&&(u=o.DEPTH_COMPONENT24),n===o.FLOAT&&(u=o.DEPTH_COMPONENT32F)),t===o.DEPTH_STENCIL&&n===o.UNSIGNED_INT_24_8&&(u=o.DEPTH24_STENCIL8),(u===o.R16F||u===o.R32F||u===o.RG16F||u===o.RG32F||u===o.RGBA16F||u===o.RGBA32F)&&l.get("EXT_color_buffer_float"),u}setTextureParameters(e,t){let{gl:n,extensions:i,backend:s}=this,{state:a}=this.backend,o=Fe.getPrimaries(Fe.workingColorSpace),l=t.colorSpace===cn?null:Fe.getPrimaries(t.colorSpace),c=t.colorSpace===cn||o===l?n.NONE:n.BROWSER_DEFAULT_WEBGL;a.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),a.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,c),n.texParameteri(e,n.TEXTURE_WRAP_S,Of[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,Of[t.wrapT]),(e===n.TEXTURE_3D||e===n.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,Of[t.wrapR])),n.texParameteri(e,n.TEXTURE_MAG_FILTER,qy[t.magFilter]);let u=t.mipmaps!==void 0&&t.mipmaps.length>0,d=t.minFilter===St&&u?bs:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,qy[d]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,FM[t.compareFunction])),i.has("EXT_texture_filter_anisotropic")===!0){if(t.magFilter===vt||t.minFilter!==Na&&t.minFilter!==bs||t.type===en&&i.has("OES_texture_float_linear")===!1)return;if(t.anisotropy>1){let h=i.get("EXT_texture_filter_anisotropic");n.texParameterf(e,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,s.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){let{gl:t,backend:n,defaultTextures:i}=this,s=this.getGLTextureType(e),a=i[s];a===void 0&&(a=t.createTexture(),n.state.bindTexture(s,a),t.texParameteri(s,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(s,t.TEXTURE_MAG_FILTER,t.NEAREST),i[s]=a),n.set(e,{textureGPU:a,glTextureType:s})}createTexture(e,t){let{gl:n,backend:i}=this,s,a,o,l,c;if(e.isExternalTexture===!0)s=e.sourceTexture,a=this.getGLTextureType(e);else{let{levels:u,width:d,height:h,depth:p}=t;o=i.utils.convert(e.format,e.colorSpace),l=i.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,o,l,e.normalized,e.colorSpace,e.isVideoTexture),s=n.createTexture(),a=this.getGLTextureType(e),i.state.bindTexture(a,s),this.setTextureParameters(a,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,u,c,d,h,p):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,u,c,d,h,p):e.isVideoTexture||n.texStorage2D(a,u,c,d,h)}i.set(e,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:c})}copyBufferToTexture(e,t){let{gl:n,backend:i}=this,{state:s}=i,{textureGPU:a,glTextureType:o,glFormat:l,glType:c}=i.get(t),{width:u,height:d}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(o,a),s.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(o,0,0,0,u,d,l,c,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){let{gl:n}=this,{width:i,height:s}=t,{textureGPU:a,glTextureType:o,glFormat:l,glType:c,glInternalFormat:u}=this.backend.get(e);if(!(e.isRenderTargetTexture||a===void 0))if(this.backend.state.bindTexture(o,a),this.setTextureParameters(o,e),e.isCompressedTexture){let d=e.mipmaps,h=t.image;for(let p=0;p<d.length;p++){let f=d[p];e.isCompressedArrayTexture?e.format!==n.RGBA?l!==null?n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,h.depth,l,f.data):X("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texSubImage3D(n.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,h.depth,l,c,f.data):l!==null?n.compressedTexSubImage2D(n.TEXTURE_2D,p,0,0,f.width,f.height,l,f.data):X("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){let d=t.images,h=e.mipmaps;for(let p=0;p<6;p++){let f=kf(d[p]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+p,0,0,0,i,s,l,c,f);for(let m=0;m<h.length;m++){let y=h[m],x=kf(y.images[p]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+p,m+1,0,0,x.width,x.height,l,c,x)}}}else if(e.isDataArrayTexture||e.isArrayTexture){let d=t.image;if(e.layerUpdates.size>0){let h=my(d.width,d.height,e.format,e.type);for(let p of e.layerUpdates){let f=d.data.subarray(p*h/d.data.BYTES_PER_ELEMENT,(p+1)*h/d.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,p,d.width,d.height,1,l,c,f)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,d.width,d.height,d.depth,l,c,d.data)}else if(e.isData3DTexture){let d=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,d.width,d.height,d.depth,l,c,d.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(o,0,u,l,c,t.image);else if(e.isHTMLTexture)typeof n.texElementImage2D=="function"&&(n.texElementImage2D.length===3?n.texElementImage2D(n.TEXTURE_2D,n.RGBA8,t.image):n.texElementImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t.image));else{let d=e.mipmaps;if(d.length>0)for(let h=0,p=d.length;h<p;h++){let f=d[h],m=kf(f);n.texSubImage2D(o,h,0,0,f.width,f.height,l,c,m)}else{let h=kf(t.image);n.texSubImage2D(o,0,0,0,i,s,l,c,h)}}}generateMipmaps(e){let{gl:t,backend:n}=this,{textureGPU:i,glTextureType:s}=n.get(e);n.state.bindTexture(s,i),t.generateMipmap(s)}deallocateRenderBuffers(e){let{gl:t,backend:n}=this;if(e){let i=n.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(let s in i.framebuffers)t.deleteFramebuffer(i.framebuffers[s]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let s=0;s<i.msaaRenderbuffers.length;s++)t.deleteRenderbuffer(i.msaaRenderbuffers[s]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){let{gl:n,backend:i}=this,{textureGPU:s,renderTarget:a}=i.get(e);this.deallocateRenderBuffers(a),t===!1&&e.isExternalTexture!==!0&&n.deleteTexture(s),i.delete(e)}copyTextureToTexture(e,t,n=null,i=null,s=0,a=0){let{gl:o,backend:l}=this,{state:c}=this.backend,{textureGPU:u,glTextureType:d,glType:h,glFormat:p}=l.get(t);c.bindTexture(d,u);let f,m,y,x,b,_,S,M,w,T=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)f=n.max.x-n.min.x,m=n.max.y-n.min.y,y=n.isBox3?n.max.z-n.min.z:1,x=n.min.x,b=n.min.y,_=n.isBox3?n.min.z:0;else{let k=Math.pow(2,-s);f=Math.floor(T.width*k),m=Math.floor(T.height*k),e.isDataArrayTexture||e.isArrayTexture?y=T.depth:e.isData3DTexture?y=Math.floor(T.depth*k):y=1,x=0,b=0,_=0}i!==null?(S=i.x,M=i.y,w=i.z):(S=0,M=0,w=0),c.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,t.flipY),c.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),c.pixelStorei(o.UNPACK_ALIGNMENT,t.unpackAlignment);let R=c.getParameter(o.UNPACK_ROW_LENGTH),D=c.getParameter(o.UNPACK_IMAGE_HEIGHT),L=c.getParameter(o.UNPACK_SKIP_PIXELS),B=c.getParameter(o.UNPACK_SKIP_ROWS),W=c.getParameter(o.UNPACK_SKIP_IMAGES);c.pixelStorei(o.UNPACK_ROW_LENGTH,T.width),c.pixelStorei(o.UNPACK_IMAGE_HEIGHT,T.height),c.pixelStorei(o.UNPACK_SKIP_PIXELS,x),c.pixelStorei(o.UNPACK_SKIP_ROWS,b),c.pixelStorei(o.UNPACK_SKIP_IMAGES,_);let q=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,ce=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){let k=l.get(e),j=l.get(t),ee=l.get(k.renderTarget),ge=l.get(j.renderTarget),fe=ee.framebuffers[k.cacheKey],he=ge.framebuffers[j.cacheKey],ye=c.currentBoundFramebuffers[o.READ_FRAMEBUFFER]??null,ze=c.currentBoundFramebuffers[o.DRAW_FRAMEBUFFER]??null;c.bindFramebuffer(o.READ_FRAMEBUFFER,fe),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,he);for(let Pe=0;Pe<y;Pe++)q&&(o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,k.textureGPU,s,_+Pe),o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,u,a,w+Pe)),o.blitFramebuffer(x,b,f,m,S,M,f,m,o.DEPTH_BUFFER_BIT,o.NEAREST);c.bindFramebuffer(o.READ_FRAMEBUFFER,ye),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,ze)}else if(s!==0||e.isRenderTargetTexture||l.has(e)){let k=l.get(e);this._srcFramebuffer===null&&(this._srcFramebuffer=o.createFramebuffer()),this._dstFramebuffer===null&&(this._dstFramebuffer=o.createFramebuffer());let j=c.currentBoundFramebuffers[o.READ_FRAMEBUFFER]??null,ee=c.currentBoundFramebuffers[o.DRAW_FRAMEBUFFER]??null;c.bindFramebuffer(o.READ_FRAMEBUFFER,this._srcFramebuffer),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let ge=0;ge<y;ge++)q?o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,k.textureGPU,s,_+ge):o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,k.textureGPU,s),ce?o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,u,a,w+ge):o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,u,a),s!==0?o.blitFramebuffer(x,b,f,m,S,M,f,m,o.COLOR_BUFFER_BIT,o.NEAREST):ce?o.copyTexSubImage3D(d,a,S,M,w+ge,x,b,f,m):o.copyTexSubImage2D(d,a,S,M,x,b,f,m);c.bindFramebuffer(o.READ_FRAMEBUFFER,j),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,ee)}else ce?e.isDataTexture||e.isData3DTexture?o.texSubImage3D(d,a,S,M,w,f,m,y,p,h,T.data):t.isCompressedArrayTexture?o.compressedTexSubImage3D(d,a,S,M,w,f,m,y,p,T.data):o.texSubImage3D(d,a,S,M,w,f,m,y,p,h,T):e.isDataTexture?o.texSubImage2D(o.TEXTURE_2D,a,S,M,f,m,p,h,T.data):e.isCompressedTexture?o.compressedTexSubImage2D(o.TEXTURE_2D,a,S,M,T.width,T.height,p,T.data):o.texSubImage2D(o.TEXTURE_2D,a,S,M,f,m,p,h,T);c.pixelStorei(o.UNPACK_ROW_LENGTH,R),c.pixelStorei(o.UNPACK_IMAGE_HEIGHT,D),c.pixelStorei(o.UNPACK_SKIP_PIXELS,L),c.pixelStorei(o.UNPACK_SKIP_ROWS,B),c.pixelStorei(o.UNPACK_SKIP_IMAGES,W),a===0&&t.generateMipmaps&&o.generateMipmap(d),c.unbindTexture()}copyFramebufferToTexture(e,t,n){let{gl:i}=this,{state:s}=this.backend,{textureGPU:a}=this.backend.get(e),{x:o,y:l,z:c,w:u}=n,d=e.isDepthTexture===!0||t.renderTarget&&t.renderTarget.samples>0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(d){let p=o!==0||l!==0,f,m;if(e.isDepthTexture===!0?(f=i.DEPTH_BUFFER_BIT,m=i.DEPTH_ATTACHMENT,t.stencil&&(f|=i.STENCIL_BUFFER_BIT)):(f=i.COLOR_BUFFER_BIT,m=i.COLOR_ATTACHMENT0),p){let y=this.backend.get(t.renderTarget),x=y.framebuffers[t.getCacheKey()],b=y.msaaFrameBuffer;s.bindFramebuffer(i.DRAW_FRAMEBUFFER,x),s.bindFramebuffer(i.READ_FRAMEBUFFER,b);let _=h-l-u;i.blitFramebuffer(o,_,o+c,_+u,o,_,o+c,_+u,f,i.NEAREST),s.bindFramebuffer(i.READ_FRAMEBUFFER,x),s.bindTexture(i.TEXTURE_2D,a),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,_,c,u),s.unbindTexture()}else{let y=i.createFramebuffer();s.bindFramebuffer(i.DRAW_FRAMEBUFFER,y),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,m,i.TEXTURE_2D,a,0),i.blitFramebuffer(0,0,c,u,0,0,c,u,f,i.NEAREST),i.deleteFramebuffer(y)}}else s.bindTexture(i.TEXTURE_2D,a),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,h-u-l,c,u),s.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,i=!1){let{gl:s}=this,a=t.renderTarget,{depthTexture:o,depthBuffer:l,stencilBuffer:c,width:u,height:d}=a;if(s.bindRenderbuffer(s.RENDERBUFFER,e),l&&!c){let h=s.DEPTH_COMPONENT24;i===!0?this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(s.RENDERBUFFER,a.samples,h,u,d):n>0?(o&&o.isDepthTexture&&o.type===s.FLOAT&&(h=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,n,h,u,d)):s.renderbufferStorage(s.RENDERBUFFER,h,u,d),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else l&&c&&(n>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH24_STENCIL8,u,d):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,u,d),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e));s.bindRenderbuffer(s.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,i,s,a){let{backend:o,gl:l}=this,{textureGPU:c,glFormat:u,glType:d}=this.backend.get(e),h=l.createFramebuffer();o.state.bindFramebuffer(l.READ_FRAMEBUFFER,h);let p=e.isCubeTexture?l.TEXTURE_CUBE_MAP_POSITIVE_X+a:l.TEXTURE_2D;l.framebufferTexture2D(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,p,c,0);let f=this._getTypedArrayType(d),m=this._getBytesPerTexel(d,u),x=i*s*m,b=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,b),l.bufferData(l.PIXEL_PACK_BUFFER,x,l.STREAM_READ),l.readPixels(t,n,i,s,u,d,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();let _=new f(x/f.BYTES_PER_ELEMENT);return l.bindBuffer(l.PIXEL_PACK_BUFFER,b),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,_),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),o.state.bindFramebuffer(l.READ_FRAMEBUFFER,null),l.deleteFramebuffer(h),_}_getTypedArrayType(e){let{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`THREE.WebGLTextureUtils: Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){let{gl:n}=this,i=0;if(e===n.UNSIGNED_BYTE&&(i=1),(e===n.UNSIGNED_SHORT_4_4_4_4||e===n.UNSIGNED_SHORT_5_5_5_1||e===n.UNSIGNED_SHORT_5_6_5||e===n.UNSIGNED_SHORT||e===n.HALF_FLOAT)&&(i=2),(e===n.UNSIGNED_INT||e===n.FLOAT)&&(i=4),t===n.RGBA)return i*4;if(t===n.RGB)return i*3;if(t===n.ALPHA)return i}dispose(){let{gl:e}=this;this._srcFramebuffer!==null&&e.deleteFramebuffer(this._srcFramebuffer),this._dstFramebuffer!==null&&e.deleteFramebuffer(this._dstFramebuffer)}};function kf(r){return r.isDataTexture?r.image.data:typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas?r:r.data}var rv=class{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return t===void 0&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}},av=class{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=null}getMaxAnisotropy(){if(this.maxAnisotropy!==null)return this.maxAnisotropy;let e=this.backend.gl,t=this.backend.extensions;if(t.has("EXT_texture_filter_anisotropic")===!0){let n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}getUniformBufferLimit(){if(this.maxUniformBlockSize!==null)return this.maxUniformBlockSize;let e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}},LM={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"},ov=class{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){let{gl:n,mode:i,object:s,type:a,info:o,index:l}=this;l!==0?n.drawElements(i,t,a,e):n.drawArrays(i,e,t),o.update(s,t,1)}renderInstances(e,t,n){let{gl:i,mode:s,type:a,index:o,object:l,info:c}=this;n!==0&&(o!==0?i.drawElementsInstanced(s,t,a,e,n):i.drawArraysInstanced(s,e,t,n),c.update(l,t,n))}renderMultiDraw(e,t,n){let{extensions:i,mode:s,object:a,info:o}=this;if(n===0)return;let l=i.get("WEBGL_multi_draw");if(l===null)for(let c=0;c<n;c++)this.render(e[c],t[c]);else{this.index!==0?l.multiDrawElementsWEBGL(s,t,0,this.type,e,0,n):l.multiDrawArraysWEBGL(s,e,0,t,0,n);let c=0;for(let u=0;u<n;u++)c+=t[u];o.update(a,c,1)}}},ig=class{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return t===void 0&&(X(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestampQuery(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}},lv=class extends ig{constructor(e,t,n=2048){if(super(n),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext){X("EXT_disjoint_timer_query not supported; timestamps will be disabled."),this.trackTimestamp=!1;return}this.queries=[];for(let i=0;i<this.maxQueries;i++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return Ce(`WebGLTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;let t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;let t=this.queryOffsets.get(e);if(t==null||this.activeQuery!==null)return;let n=this.queries[t];if(n)try{this.queryStates.get(t)==="inactive"&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(i){G("Error in beginQuery:",i),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;let t=this.queryOffsets.get(e);if(t!=null&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(n){G("Error in endQuery:",n),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{let e=new Map;for(let[s,a]of this.queryOffsets)if(this.queryStates.get(a)==="ended"){let l=this.queries[a];e.set(s,this.resolveQuery(l))}if(e.size===0)return this.lastValue;let t={},n=[];for(let[s,a]of e){let o=s.match(/^(.*):f(d+)$/),l=parseInt(o[2]);n.includes(l)===!1&&n.push(l),t[l]===void 0&&(t[l]=0);let c=await a;this.timestamps.set(s,c),t[l]+=c}let i=t[n[n.length-1]];return this.lastValue=i,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return G("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed){t(this.lastValue);return}let n,i=!1,s=()=>{n&&(clearTimeout(n),n=null)},a=l=>{i||(i=!0,s(),t(l))},o=()=>{if(this.isDisposed){a(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){a(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){n=setTimeout(o,1);return}let u=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(u)/1e6)}catch(l){G("Error checking query:",l),t(this.lastValue)}};o()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,!!this.trackTimestamp)){for(let e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}},sg=class extends ng{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);let t=this.parameters,n={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=t.context!==void 0?t.context:e.domElement.getContext("webgl2",n);function s(a){a.preventDefault();let o={api:"WebGL",message:a.statusMessage||"Unknown reason",reason:null,originalEvent:a};e.onDeviceLost(o)}this._onContextLost=s,e.domElement.addEventListener("webglcontextlost",s,!1),this.gl=i,this.extensions=new rv(this),this.capabilities=new av(this),this.attributeUtils=new tv(this),this.textureUtils=new sv(this),this.bufferRenderer=new ov(this),this.state=new nv(this),this.utils=new iv(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(X("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return qn}get hasTimestamp(){return this.disjoint!==null}async getArrayBufferAsync(e,t=null,n=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,i)}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){let i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),n!==null){let s=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:s}),this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer===!0&&e.multiview===!1&&X("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new lv(this.gl,e,2048));let n=this.timestampQueryPool[e];n.allocateQueriesForContext(t)!==null&&n.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){let{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{let{width:s,height:a}=this.getDrawingBufferSize();t.viewport(0,0,s,a)}if(e.scissor)this.updateScissor(e);else{let{width:s,height:a}=this.getDrawingBufferSize();t.scissor(0,0,s,a)}this.initTimestampQuery(Ji.RENDER,this.getTimestampUID(e)),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);let i=e.occlusionQueryCount;i>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(i),n.occlusionQueryObjects=new Array(i),n.occlusionQueryIndex=0)}finishRender(e){let{gl:t,state:n}=this,i=this.get(e),s=i.previousContext;n.resetVertexState();let a=e.occlusionQueryCount;a>0&&(a>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));let o=e.textures;if(o!==null)for(let l=0;l<o.length;l++){let c=o[l];c.generateMipmaps&&this.generateMipmaps(c)}if(this._currentContext=s,this._resolveRenderTarget(e),s!==null){if(this._setFramebuffer(s),s.viewport)this.updateViewport(s);else{let{width:l,height:c}=this.getDrawingBufferSize();n.viewport(0,0,l,c)}if(s.scissor)this.updateScissor(s);else{let{width:l,height:c}=this.getDrawingBufferSize();n.scissor(0,0,l,c)}}this.prepareTimestampBuffer(Ji.RENDER,this.getTimestampUID(e))}resolveOccludedAsync(e){let t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:i}=t;if(n&&i){let s=new WeakSet,{gl:a}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;let o=()=>{let l=0;for(let c=0;c<n.length;c++){let u=n[c];u!==null&&a.getQueryParameter(u,a.QUERY_RESULT_AVAILABLE)&&(a.getQueryParameter(u,a.QUERY_RESULT)===0&&s.add(i[c]),n[c]=null,a.deleteQuery(u),l++)}l<n.length?requestAnimationFrame(o):t.occluded=s};o()}}isOccluded(e,t){let n=this.get(e);return n.occluded&&n.occluded.has(t)}updateViewport(e){let{state:t}=this,{x:n,y:i,width:s,height:a}=e.viewportValue;t.viewport(n,e.height-a-i,s,a)}updateScissor(e){let{state:t}=this,{x:n,y:i,width:s,height:a}=e.scissorValue;t.scissor(n,e.height-a-i,s,a)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){let e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,n,i=null,s=!0,a=!0){let{gl:o,renderer:l}=this;i===null&&(i={textures:null,clearColorValue:this.getClearColor()});let c=0;if(e&&(c|=o.COLOR_BUFFER_BIT),t&&(c|=o.DEPTH_BUFFER_BIT),n&&(c|=o.STENCIL_BUFFER_BIT),c!==0){let u;i.clearColorValue?u=i.clearColorValue:u=this.getClearColor();let d=l.getClearDepth(),h=l.getClearStencil();if(t&&this.state.setDepthMask(!0),i.textures===null)o.clearColor(u.r,u.g,u.b,u.a),o.clear(c);else{if(s&&this._setFramebuffer(i),e)for(let p=0;p<i.textures.length;p++)p===0?o.clearBufferfv(o.COLOR,p,[u.r,u.g,u.b,u.a]):o.clearBufferfv(o.COLOR,p,[0,0,0,1]);t&&n?o.clearBufferfi(o.DEPTH_STENCIL,0,d,h):t?o.clearBufferfv(o.DEPTH,0,[d]):n&&o.clearBufferiv(o.STENCIL,0,[h]),s&&a&&this._resolveRenderTarget(i),s&&this._currentContext!==null&&this._currentContext!==i&&this._setFramebuffer(this._currentContext)}}}beginCompute(e){let{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(Ji.COMPUTE,this.getTimestampUID(e))}compute(e,t,n,i,s=null){let{state:a,gl:o}=this;this.discard===!1&&(a.enable(o.RASTERIZER_DISCARD),this.discard=!0);let{programGPU:l,transformBuffers:c,attributes:u}=this.get(i),d=this._getVaoKey(u),h=this.vaoCache[d];h===void 0?this.vaoCache[d]=this._createVao(u):a.setVertexState(h),a.useProgram(l),this._bindUniforms(n);let p=this._getTransformFeedback(c);o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,p),o.beginTransformFeedback(o.POINTS),s=s!==null?s:t.count,Array.isArray(s)?(Ce("WebGLBackend.compute(): The count parameter must be a single number, not an array."),s=s[0]):s&&typeof s=="object"&&s.isIndirectStorageBufferAttribute&&(Ce("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),s=t.count),u[0].isStorageInstancedBufferAttribute?o.drawArraysInstanced(o.POINTS,0,1,s):o.drawArrays(o.POINTS,0,s),o.endTransformFeedback(),o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,null);for(let f=0;f<c.length;f++){let m=c[f];m.pbo&&this.has(m.pbo)&&this.textureUtils.copyBufferToTexture(m.transformBuffer,m.pbo),m.switchBuffers()}}finishCompute(e){let{state:t,gl:n}=this;this.discard=!1,t.disable(n.RASTERIZER_DISCARD),this.prepareTimestampBuffer(Ji.COMPUTE,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,n,i,s,a){if(e.isBatchedMesh)if(this.hasFeature("WEBGL_multi_draw")===!1){let{gl:o}=this,l=o.getUniformLocation(a,"nodeUniformDrawId"),c=e._multiDrawStarts,u=e._multiDrawCounts,d=e._multiDrawCount;for(let h=0;h<d;h++)o.uniform1ui(l,h),t.render(c[h],u[h])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else s>1?t.renderInstances(n,i,s):t.render(n,i)}draw(e){let{object:t,pipeline:n,material:i,context:s,hardwareClippingPlanes:a}=e,{programGPU:o}=this.get(n),{gl:l,state:c}=this,u=this.get(s),d=e.getDrawParameters();if(d===null)return;this._bindUniforms(e.getBindings());let h=t.isMesh&&t.matrixWorld.determinantAffine()<0;c.setMaterial(i,h,a),s.mrt!==null&&s.textures!==null&&c.setMRTBlending(s.textures,s.mrt,i),c.useProgram(o);let p=e.getAttributes(),f=this.get(p),m=f.vaoGPU;if(m===void 0){let T=this._getVaoKey(p);m=this.vaoCache[T],m===void 0&&(m=this._createVao(p),this.vaoCache[T]=m,f.vaoGPU=m)}let y=e.getIndex(),x=y!==null?this.get(y).bufferGPU:null;c.setVertexState(m,x);let b=u.lastOcclusionObject;if(b!==t&&b!==void 0){if(b!==null&&b.occlusionTest===!0&&(l.endQuery(l.ANY_SAMPLES_PASSED),u.occlusionQueryIndex++),t.occlusionTest===!0){let T=l.createQuery();l.beginQuery(l.ANY_SAMPLES_PASSED,T),u.occlusionQueries[u.occlusionQueryIndex]=T,u.occlusionQueryObjects[u.occlusionQueryIndex]=t}u.lastOcclusionObject=t}let _=this.bufferRenderer;t.isPoints?_.mode=l.POINTS:t.isLineSegments?_.mode=l.LINES:t.isLine?_.mode=l.LINE_STRIP:t.isLineLoop?_.mode=l.LINE_LOOP:i.wireframe===!0?(c.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),_.mode=l.LINES):_.mode=l.TRIANGLES;let{vertexCount:S,instanceCount:M}=d,{firstVertex:w}=d;if(_.object=t,y!==null){w*=y.array.BYTES_PER_ELEMENT;let T=this.get(y);_.index=y.count,_.type=T.type}else _.index=0;if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){let T=this.get(e.camera),R=e.camera.cameras,D=e.getBindingGroup("cameraIndex").bindings[0];if(T.indexesGPU===void 0||T.indexesGPU.length!==R.length){let k=new Uint32Array([0,0,0,0]),j=[];for(let ee=0,ge=R.length;ee<ge;ee++){let fe=l.createBuffer();k[0]=ee,l.bindBuffer(l.UNIFORM_BUFFER,fe),l.bufferData(l.UNIFORM_BUFFER,k,l.STATIC_DRAW),j.push(fe)}T.indexesGPU=j}let L=0;e:for(let k of e.getBindings())for(let j of k.bindings){if(j===D)break e;(j.isUniformsGroup||j.isUniformBuffer)&&L++}let B=this.renderer.getPixelRatio(),W=this._currentContext.renderTarget,q=this._isRenderCameraDepthArray(this._currentContext),ce=this._currentContext.activeCubeFace;if(q){let k=this.get(W.depthTexture);if(k.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){k.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;let{stencilBuffer:j}=W;for(let ee=0,ge=R.length;ee<ge;ee++)this.renderer._activeCubeFace=ee,this._currentContext.activeCubeFace=ee,this._setFramebuffer(this._currentContext),this.clear(!1,!0,j,this._currentContext,!1,!1);this.renderer._activeCubeFace=ce,this._currentContext.activeCubeFace=ce}}for(let k=0,j=R.length;k<j;k++){let ee=R[k];if(t.layers.test(ee.layers)){q&&(this.renderer._activeCubeFace=k,this._currentContext.activeCubeFace=k,this._setFramebuffer(this._currentContext));let ge=ee.viewport;if(ge!==void 0){let fe=ge.x*B,he=ge.y*B,ye=ge.width*B,ze=ge.height*B;c.viewport(Math.floor(fe),Math.floor(e.context.height-ze-he),Math.floor(ye),Math.floor(ze))}c.bindBufferBase(l.UNIFORM_BUFFER,L,T.indexesGPU[k]),this._draw(t,_,w,S,M,o)}this._currentContext.activeCubeFace=ce,this.renderer._activeCubeFace=ce}}else this._draw(t,_,w,S,M,o)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,s,a){return this.textureUtils.copyTextureToBuffer(e,t,n,i,s,a)}updateSampler(){return""}createNodeBuilder(e,t){return new Qb(e,t)}createProgram(e){let t=this.gl,{stage:n,code:i}=e,s=n==="fragment"?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(s,i),t.compileShader(s),this.set(e,{shaderGPU:s})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){let n=this.gl,i=e.pipeline,{fragmentProgram:s,vertexProgram:a}=i,o=n.createProgram(),l=this.get(s).shaderGPU,c=this.get(a).shaderGPU;if(n.attachShader(o,l),n.attachShader(o,c),n.linkProgram(o),this.set(i,{programGPU:o,fragmentShader:l,vertexShader:c}),t!==null&&this.parallel){let u=new Promise(d=>{let h=this.parallel,p=()=>{n.getProgramParameter(o,h.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),d()):requestAnimationFrame(p)};p()});t.push(u);return}this._completeCompile(e,i)}_handleSource(e,t){let n=e.split(`
`),i=[],s=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let o=s;o<a;o++){let l=o+1;i.push(`${l===t?">":" "} ${l}: ${n[o]}`)}return i.join(`
`)}_getShaderErrors(e,t,n){let i=e.getShaderParameter(t,e.COMPILE_STATUS),a=(e.getShaderInfoLog(t)||"").trim();if(i&&a==="")return"";let o=/ERROR: 0:(d+)/.exec(a);if(o){let l=parseInt(o[1]);return n.toUpperCase()+`
`+a+`
`+this._handleSource(e.getShaderSource(t),l)}else return a}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){let i=this.gl,a=(i.getProgramInfoLog(e)||"").trim();if(i.getProgramParameter(e,i.LINK_STATUS)===!1)if(typeof this.renderer.debug.onShaderError=="function")this.renderer.debug.onShaderError(i,e,n,t);else{let o=this._getShaderErrors(i,n,"vertex"),l=this._getShaderErrors(i,t,"fragment");G("WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+`
Program Info Log: `+a+`
`+o+`
`+l)}else a!==""&&X("WebGLProgram: Program Info Log:",a)}}_completeCompile(e,t){let{state:n,gl:i}=this,s=this.get(t),{programGPU:a,fragmentShader:o,vertexShader:l}=s;i.getProgramParameter(a,i.LINK_STATUS)===!1&&this._logProgramError(a,o,l),n.useProgram(a);let c=e.getBindings();this._setupBindings(c,a),this.set(t,{programGPU:a,pipeline:a})}createComputePipeline(e,t){let{state:n,gl:i}=this,s={stage:"fragment",code:`#version 300 es
precision highp float;
void main() {}`};this.createProgram(s);let{computeProgram:a}=e,o=i.createProgram(),l=this.get(s).shaderGPU,c=this.get(a).shaderGPU,u=a.transforms,d=[],h=[];for(let y=0;y<u.length;y++){let x=u[y];d.push(x.varyingName),h.push(x.attributeNode)}i.attachShader(o,l),i.attachShader(o,c),i.transformFeedbackVaryings(o,d,i.SEPARATE_ATTRIBS),i.linkProgram(o),i.getProgramParameter(o,i.LINK_STATUS)===!1&&this._logProgramError(o,l,c),n.useProgram(o),this._setupBindings(t,o);let p=a.attributes,f=[],m=[];for(let y=0;y<p.length;y++){let x=p[y].node.attribute;f.push(x),this.has(x)||this.attributeUtils.createAttribute(x,i.ARRAY_BUFFER)}for(let y=0;y<h.length;y++){let x=h[y].attribute;this.has(x)||this.attributeUtils.createAttribute(x,i.ARRAY_BUFFER);let b=this.get(x);m.push(b)}this.set(e,{programGPU:o,transformBuffers:m,attributes:f})}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let n=0,i=0;for(let s of t){this.set(s,{textures:i,uniformBuffers:n});for(let a of s.bindings)a.isUniformBuffer&&n++,a.isSampledTexture&&i++}}this.updateBindings(e,t)}updateBindings(e){let{gl:t}=this;for(let n of e.bindings){let i=this.get(n);if(n.isUniformsGroup||n.isUniformBuffer){let s=n.buffer,a=i.bufferGPU;t.bindBuffer(t.UNIFORM_BUFFER,a);let o=n.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,a),o.length===0)t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW);else{let l=Hc(s),c=l?1:s.BYTES_PER_ELEMENT;for(let u=0,d=o.length;u<d;u++){let h=o[u],p=h.start*c,f=h.count*c,m=p*(l?s.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,m,s,p,f)}}this.set(n,i)}else if(n.isSampledTexture){let{textureGPU:s,glTextureType:a}=this.get(n.texture);i.textureGPU=s,i.glTextureType=a,this.set(n,i)}}}updateBinding(e){let t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){let i=this.get(e).bufferGPU,s=e.buffer,a=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,i),a.length===0)t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW);else{let o=Hc(s),l=o?1:s.BYTES_PER_ELEMENT,c=a[0].start;for(let u=0,d=a.length;u<d;u++){let h=a[u],p=a[u+1],f=h.start+h.count;if(p!==void 0&&p.start===f)continue;let m=c*l,y=(f-c)*l,x=m*(o?s.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,x,s,m,y),p!==void 0&&(c=p.start)}}}}createUniformBuffer(e){let t=this.get(e);if(t.bufferGPU===void 0){let n=this.gl,i=e.buffer;t.bufferGPU=n.createBuffer(),n.bindBuffer(n.UNIFORM_BUFFER,t.bufferGPU),n.bufferData(n.UNIFORM_BUFFER,i.byteLength,n.DYNAMIC_DRAW)}}destroyUniformBuffer(e){let t=this.get(e);this.gl.deleteBuffer(t.bufferGPU),this.delete(e)}createIndexAttribute(e){let t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;let t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;let t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){let t=Object.keys(LM).filter(i=>LM[i]===e),n=this.extensions;for(let i=0;i<t.length;i++)if(n.has(t[i]))return!0;return!1}copyTextureToTexture(e,t,n=null,i=null,s=0,a=0){this.textureUtils.copyTextureToTexture(e,t,n,i,s,a)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}hasCompatibility(e){return e===Fr.TEXTURE_COMPARE?!0:super.hasCompatibility(e)}initRenderTarget(e){let{gl:t,state:n}=this;this._setFramebuffer(e),n.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){let{gl:t,state:n}=this,i=null;if(e.textures!==null){let s=e.renderTarget,a=this.get(s),{samples:o,depthBuffer:l,stencilBuffer:c}=s,u=s.isCubeRenderTarget===!0,d=s.isRenderTarget3D===!0,h=s.depth>1,p=s.isXRRenderTarget===!0,f=p===!0&&s._hasExternalTextures===!0,m=a.msaaFrameBuffer,y=a.depthRenderbuffer,x=this.extensions.get("WEBGL_multisampled_render_to_texture"),b=this.extensions.get("OVR_multiview2"),_=this._useMultisampledExtension(s),S=uA(e),M;if(u?(a.cubeFramebuffers||(a.cubeFramebuffers={}),M=a.cubeFramebuffers[S]):p&&f===!1?M=this._xrFramebuffer:(a.framebuffers||(a.framebuffers={}),M=a.framebuffers[S]),M===void 0){M=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,M);let w=e.textures,T=[];if(u){a.cubeFramebuffers[S]=M;let{textureGPU:D}=this.get(w[0]),L=this.renderer._activeCubeFace,B=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+L,D,B)}else{a.framebuffers[S]=M;for(let D=0;D<w.length;D++){let L=w[D],B=this.get(L);B.renderTarget=e.renderTarget,B.cacheKey=S;let W=t.COLOR_ATTACHMENT0+D;if(s.multiview)b.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,W,B.textureGPU,0,o,0,2);else if(d||h){let q=this.renderer._activeCubeFace,ce=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,W,B.textureGPU,ce,q)}else if(_)x.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,W,t.TEXTURE_2D,B.textureGPU,0,o);else{let q=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,W,t.TEXTURE_2D,B.textureGPU,q)}}}let R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(s._autoAllocateDepthBuffer===!0){let D=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(D,e,0,_),a.xrDepthRenderbuffer=D,T.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,D),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,D)}else if(e.depthTexture!==null){T.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);let D=this.get(e.depthTexture);if(D.renderTarget=e.renderTarget,D.cacheKey=S,s.multiview)b.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,D.textureGPU,0,o,0,2);else if(f&&_)x.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,D.textureGPU,0,o);else if(e.depthTexture.isArrayTexture){let L=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,R,D.textureGPU,0,L)}else if(e.depthTexture.isCubeTexture){let L=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_CUBE_MAP_POSITIVE_X+L,D.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,D.textureGPU,0)}a.depthInvalidationArray=T}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,M);let T=this.renderer._activeCubeFace,R=this.get(e.depthTexture),D=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,D,R.textureGPU,0,T)}if((p||_||s.multiview)&&s._isOpaqueFramebuffer!==!0){n.bindFramebuffer(t.FRAMEBUFFER,M);let T=this.get(e.textures[0]);s.multiview?b.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,T.textureGPU,0,o,0,2):_?x.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,T.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,T.textureGPU,0);let R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(s._autoAllocateDepthBuffer===!0){let D=a.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,D),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,D)}else{let D=this.get(e.depthTexture);s.multiview?b.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,D.textureGPU,0,o,0,2):_?x.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,D.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,D.textureGPU,0)}}}if(o>0&&_===!1&&!s.multiview){if(m===void 0){let w=[];m=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,m);let T=[],R=e.textures;for(let D=0;D<R.length;D++){T[D]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,T[D]),w.push(t.COLOR_ATTACHMENT0+D);let L=e.textures[D],B=this.get(L);t.renderbufferStorageMultisample(t.RENDERBUFFER,o,B.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+D,t.RENDERBUFFER,T[D])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),a.msaaFrameBuffer=m,a.msaaRenderbuffers=T,l&&y===void 0){y=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(y,e,o),a.depthRenderbuffer=y;let D=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;w.push(D)}a.invalidationArray=w}i=a.msaaFrameBuffer}else i=M;n.drawBuffers(e,M)}n.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let n=0;n<e.length;n++){let i=this.get(e[n]);t+=":"+i.id}return t}_createVao(e){let{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let i=0;i<e.length;i++){let s=e[i],a=this.get(s);t.bindBuffer(t.ARRAY_BUFFER,a.bufferGPU),t.enableVertexAttribArray(i);let o,l;s.isInterleavedBufferAttribute===!0?(o=s.data.stride*a.bytesPerElement,l=s.offset*a.bytesPerElement):(o=0,l=0),a.isInteger?t.vertexAttribIPointer(i,s.itemSize,a.type,o,l):t.vertexAttribPointer(i,s.itemSize,a.type,s.normalized,o,l),s.isInstancedBufferAttribute&&!s.isInterleavedBufferAttribute?t.vertexAttribDivisor(i,s.meshPerAttribute):s.isInterleavedBufferAttribute&&s.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(i,s.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t="";for(let s=0;s<e.length;s++)t+=":"+e[s].id;let n=this.transformFeedbackCache[t];if(n!==void 0)return n;let{gl:i}=this;n=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,n);for(let s=0;s<e.length;s++){let a=e[s];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,s,a.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){let n=this.gl,i=0,s=0;for(let a of e)for(let o of a.bindings)if(o.isUniformsGroup||o.isUniformBuffer){let l=i++,c=n.getUniformBlockIndex(t,o.name);n.uniformBlockBinding(t,c,l)}else if(o.isSampledTexture){let l=s++,c=n.getUniformLocation(t,o.name);n.uniform1i(c,l)}}_bindUniforms(e){let{gl:t,state:n}=this,i=0,s=0;for(let a of e)for(let o of a.bindings){let l=this.get(o);if(o.isUniformsGroup||o.isUniformBuffer){let c=i++;n.bindBufferBase(t.UNIFORM_BUFFER,c,l.bufferGPU)}else if(o.isSampledTexture){let c=s++;n.bindTexture(l.glTextureType,l.textureGPU,t.TEXTURE0+c)}}}_resolveRenderTarget(e){let{gl:t,state:n}=this,i=e.renderTarget;if(e.textures!==null&&i){let s=this.get(i);if(i.samples>0&&this._useMultisampledExtension(i)===!1){let a=s.framebuffers[e.getCacheKey()],o=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(o|=t.STENCIL_BUFFER_BIT));let l=s.msaaFrameBuffer,c=s.msaaRenderbuffers,u=e.textures,d=u.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,l),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,a),d)for(let h=0;h<u.length;h++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+h,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+h,t.TEXTURE_2D,null,0);for(let h=0;h<u.length;h++){if(d){let{textureGPU:p}=this.get(u[h]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,c[h]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,p,0)}if(e.scissor){let{x:p,y:f,width:m,height:y}=e.scissorValue,x=e.height-y-f;t.blitFramebuffer(p,x,p+m,x+y,p,x,p+m,x+y,o,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,o,t.NEAREST)}if(d)for(let h=0;h<u.length;h++){let{textureGPU:p}=this.get(u[h]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+h,t.RENDERBUFFER,c[h]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+h,t.TEXTURE_2D,p,0)}this._supportsInvalidateFramebuffer===!0&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,s.invalidationArray)}else if(i.resolveDepthBuffer===!1&&s.framebuffers){let a=s.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,a),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,s.depthInvalidationArray)}}}_useMultisampledExtension(e){return e.multiview===!0?!0:e.samples>0&&this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer!==!1}dispose(){this.textureUtils!==null&&this.textureUtils.dispose();let e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}},bh={PointList:"point-list",LineList:"line-list",LineStrip:"line-strip",TriangleList:"triangle-list"},lr=typeof self<"u"&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},vn={Never:"never",Less:"less",Equal:"equal",LessEqual:"less-equal",Greater:"greater",NotEqual:"not-equal",GreaterEqual:"greater-equal",Always:"always"},jn={Store:"store"},qe={Load:"load",Clear:"clear"},BM={CCW:"ccw",CW:"cw"},UM={None:"none",Back:"back"},rg={Uint16:"uint16",Uint32:"uint32"},A={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R16Unorm:"r16unorm",R16Snorm:"r16snorm",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RG16Unorm:"rg16unorm",RG16Snorm:"rg16snorm",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10UFloat:"rg11b10ufloat",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA16Unorm:"rgba16unorm",RGBA16Snorm:"rgba16snorm",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-unorm-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},$y={ClampToEdge:"clamp-to-edge",Repeat:"repeat",MirrorRepeat:"mirror-repeat"},ts={Linear:"linear",Nearest:"nearest"},Le={Zero:"zero",One:"one",Src:"src",OneMinusSrc:"one-minus-src",SrcAlpha:"src-alpha",OneMinusSrcAlpha:"one-minus-src-alpha",Dst:"dst",OneMinusDst:"one-minus-dst",DstAlpha:"dst-alpha",OneMinusDstAlpha:"one-minus-dst-alpha",SrcAlphaSaturated:"src-alpha-saturated",Constant:"constant",OneMinusConstant:"one-minus-constant"},Wo={Add:"add",Subtract:"subtract",ReverseSubtract:"reverse-subtract",Min:"min",Max:"max"},OM={None:0,All:15},Ua={Keep:"keep",Zero:"zero",Replace:"replace",Invert:"invert",IncrementClamp:"increment-clamp",DecrementClamp:"decrement-clamp",IncrementWrap:"increment-wrap",DecrementWrap:"decrement-wrap"},Xy={Storage:"storage",ReadOnlyStorage:"read-only-storage"},Yy={WriteOnly:"write-only",ReadOnly:"read-only",ReadWrite:"read-write"},kM={NonFiltering:"non-filtering",Comparison:"comparison"},qo={Float:"float",UnfilterableFloat:"unfilterable-float",Depth:"depth",SInt:"sint",UInt:"uint"},VM={TwoD:"2d",ThreeD:"3d"},Sn={TwoD:"2d",TwoDArray:"2d-array",Cube:"cube",ThreeD:"3d"},Qk={All:"all"},Vf={Vertex:"vertex",Instance:"instance"},ag={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},GM={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"},cv=class extends eg{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){let{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}},uv=class extends Km{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}},eV=0,dv=class extends uv{constructor(e,t){super("StorageBuffer_"+eV++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Mn.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}},jy=[null],hv=class{constructor(e){this.backend=e,this._preferredCanvasFormat=null}getCurrentDepthStencilFormat(e){let t;return e.depth&&(e.depthTexture!==null?t=this.getTextureFormatGPU(e.depthTexture):e.stencil?this.backend.renderer.reversedDepthBuffer===!0?t=A.Depth32FloatStencil8:t=A.Depth24PlusStencil8:this.backend.renderer.reversedDepthBuffer===!0?t=A.Depth32Float:t=A.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){let s=this.backend.renderer,a=s.getRenderTarget();t=a?a.samples:s.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=this.getSampleCount(t||1);let n=t>1&&e.renderTarget!==null&&e.isDepthTexture!==!0&&e.isFramebufferTexture!==!0;return{samples:t,primarySamples:n?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return e.textures!==null?t=this.getTextureFormatGPU(e.textures[0]):t=this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return e.textures!==null?e.textures.map(t=>this.getTextureFormatGPU(t)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return e.textures!==null?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return bh.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return bh.LineList;if(e.isLine)return bh.LineStrip;if(e.isMesh)return bh.TriangleList}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return e.textures!==null?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){let t=this.backend.parameters.outputType;if(t===void 0)return this._preferredCanvasFormat===null&&(this._preferredCanvasFormat=navigator.gpu.getPreferredCanvasFormat()),this._preferredCanvasFormat;if(t===Gt)return A.BGRA8Unorm;if(t===xt)return A.RGBA16Float;throw new Error("THREE.WebGPUUtils: Unsupported output buffer type.")}};function nr(r,e){jy[0]=e,r.queue.submit(jy),jy[0]=null}var og=class{constructor(){this.label="",this.layout=null,this.entries=[]}reset(){this.label="",this.layout=null,this.entries.length=0}},to=class{constructor(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}reset(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}},pl=class{constructor(){this.label=""}reset(){this.label=""}},lg=class{constructor(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}reset(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}},sl=class{constructor(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}reset(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}},rl=class{constructor(){this.label="",this.colorAttachments=[],this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}reset(){this.label="",this.colorAttachments.length=0,this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}},cg=class{constructor(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample=new pv,this.fragment=null}reset(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample.reset(),this.fragment=null}},pv=class{constructor(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}reset(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}},ug=class{constructor(){this.label="",this.code="",this.compilationHints=[]}reset(){this.label="",this.code="",this.compilationHints.length=0}},Kh=class{constructor(){this.label="",this.size={width:0,height:1,depthOrArrayLayers:1},this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats=[],this.textureBindingViewDimension=void 0}reset(){this.label="",this.size.width=0,this.size.height=1,this.size.depthOrArrayLayers=1,this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats.length=0,this.textureBindingViewDimension=void 0}},Zh=class{constructor(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}reset(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}},Oa=new og,ka=new to,Gf=new pl,Ky=new lg,Zy=new rl,Zc=new cg,ph=new sl,zf=new ug,Jc=new Kh,Bt=new Zh,fv=class extends hr{constructor(e){super(),this.device=e;let t=`
struct VarysStruct {
@builtin( position ) Position: vec4f,
@location( 0 ) vTex : vec2f,
@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
};
@group( 0 ) @binding ( 2 )
var<uniform> flipY: u32;
@vertex
fn mainVS(
@builtin( vertex_index ) vertexIndex : u32,
@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
var Varys : VarysStruct;
var pos = array(
vec2f( -1, -1 ),
vec2f( -1, 3 ),
vec2f( 3, -1 ),
);
let p = pos[ vertexIndex ];
let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
Varys.vTex = p * mult + vec2f( 0.5 );
Varys.Position = vec4f( p, 0, 1 );
Varys.vBaseArrayLayer = instanceIndex;
return Varys;
}
@group( 0 ) @binding( 0 )
var imgSampler : sampler;
@group( 0 ) @binding( 1 )
var img2d : texture_2d<f32>;
@fragment
fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
return textureSample( img2d, imgSampler, Varys.vTex );
}
@group( 0 ) @binding( 1 )
var img2dArray : texture_2d_array<f32>;
@fragment
fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
}
const faceMat = array(
mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
);
@group( 0 ) @binding( 1 )
var imgCube : texture_cube<f32>;
@fragment
fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
}
`;this.mipmapSampler=e.createSampler({minFilter:ts.Linear}),this.flipYSampler=e.createSampler({minFilter:ts.Nearest}),ka.size=4,ka.usage=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,this.flipUniformBuffer=e.createBuffer(ka),ka.reset(),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),ka.size=4,ka.usage=GPUBufferUsage.UNIFORM,this.noFlipUniformBuffer=e.createBuffer(ka),ka.reset(),this.transferPipelines={},zf.label="mipmap",zf.code=t,this.mipmapShaderModule=e.createShaderModule(zf),zf.reset()}getTransferPipeline(e,t){t=t||"2d-array";let n=`${e}-${t}`,i=this.transferPipelines[n];return i===void 0&&(Zc.label=`mipmap-${e}-${t}`,Zc.vertex={module:this.mipmapShaderModule},Zc.fragment={module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},Zc.layout="auto",i=this.device.createRenderPipeline(Zc),Zc.reset(),this.transferPipelines[n]=i),i}flipY(e,t,n=0){let i=t.format,{width:s,height:a}=t.size;Jc.size.width=s,Jc.size.height=a,Jc.format=i,Jc.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;let o=this.device.createTexture(Jc);Jc.reset();let l=this.getTransferPipeline(i,e.textureBindingViewDimension),c=this.getTransferPipeline(i,o.textureBindingViewDimension),u=this.device.createCommandEncoder(Gf),d=(h,p,f,m,y,x)=>{let b=h.getBindGroupLayout(0);Bt.dimension=p.textureBindingViewDimension||"2d-array",Bt.mipLevelCount=1;let _=p.createView(Bt);Bt.reset(),Oa.layout=b,Oa.entries.push({binding:0,resource:this.flipYSampler},{binding:1,resource:_},{binding:2,resource:{buffer:x?this.flipUniformBuffer:this.noFlipUniformBuffer}});let S=this.device.createBindGroup(Oa);Oa.reset(),Bt.dimension="2d",Bt.mipLevelCount=1,Bt.baseArrayLayer=y,Bt.arrayLayerCount=1;let M=m.createView(Bt);Bt.reset(),ph.view=M,ph.loadOp=qe.Clear,ph.storeOp=jn.Store,Zy.colorAttachments.push(ph);let w=u.beginRenderPass(Zy);Zy.reset(),ph.reset(),w.setPipeline(h),w.setBindGroup(0,S),w.draw(3,1,0,f),w.end()};d(l,e,n,o,0,!1),d(c,o,0,e,n,!0),nr(this.device,u.finish()),o.destroy()}generateMipmaps(e,t=null){let n=this.get(e),i=n.layers||this._mipmapCreateBundles(e),s=t;s===null&&(Gf.label="mipmapEncoder",s=this.device.createCommandEncoder(Gf),Gf.reset()),this._mipmapRunBundles(s,i),t===null&&nr(this.device,s.finish()),n.layers=i}_mipmapCreateBundles(e){let t=e.textureBindingViewDimension||"2d-array",n=this.getTransferPipeline(e.format,t),i=n.getBindGroupLayout(0),s=[];for(let a=1;a<e.mipLevelCount;a++)for(let o=0;o<e.depthOrArrayLayers;o++){Bt.dimension=t,Bt.baseMipLevel=a-1,Bt.mipLevelCount=1;let l=e.createView(Bt);Bt.reset(),Oa.layout=i,Oa.entries.push({binding:0,resource:this.mipmapSampler},{binding:1,resource:l},{binding:2,resource:{buffer:this.noFlipUniformBuffer}});let c=this.device.createBindGroup(Oa);Oa.reset(),Bt.dimension="2d",Bt.baseMipLevel=a,Bt.mipLevelCount=1,Bt.baseArrayLayer=o,Bt.arrayLayerCount=1;let u=e.createView(Bt);Bt.reset();let d=new sl;d.view=u,d.loadOp=qe.Clear,d.storeOp=jn.Store;let h=new rl;h.colorAttachments.push(d),Ky.colorFormats=[e.format];let p=this.device.createRenderBundleEncoder(Ky);Ky.reset(),p.setPipeline(n),p.setBindGroup(0,c),p.draw(3,1,0,o),s.push({renderBundles:[p.finish()],passDescriptor:h})}return s}_mipmapRunBundles(e,t){let n=t.length;for(let i=0;i<n;i++){let s=t[i],a=e.beginRenderPass(s.passDescriptor);a.executeBundles(s.renderBundles),a.end()}}},mv=class{constructor(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}reset(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}},Tu=class{constructor(){this.texture=null,this.mipLevel=0,this.origin={x:0,y:0,z:0},this.aspect="all"}reset(){this.texture=null,this.mipLevel=0,this.origin.x=0,this.origin.y=0,this.origin.z=0,this.aspect="all"}},gv=class{constructor(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},yv=class{constructor(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},xv=class{constructor(){this.source=null,this.origin={x:0,y:0},this.flipY=!1}reset(){this.source=null,this.origin.x=0,this.origin.y=0,this.flipY=!1}},_v=class extends Tu{constructor(){super(),this.colorSpace="srgb",this.premultipliedAlpha=!1}reset(){super.reset(),this.colorSpace="srgb",this.premultipliedAlpha=!1}},dg=class{constructor(){this.width=0,this.height=1,this.depthOrArrayLayers=1}reset(){this.width=0,this.height=1,this.depthOrArrayLayers=1}},Hf=new to,tV=new pl,In=new mv,Un=new Tu,Wf=new gv,Gr=new yv,qf=new xv,Qc=new _v,Va=new Kh,Ln=new dg,nV={[of]:"never",[eh]:"less",[lf]:"equal",[Oo]:"less-equal",[zc]:"greater",[La]:"greater-equal",[uf]:"always",[cf]:"not-equal"},iV=[0,1,3,2,4,5];function zM(r,e,t,n,i,s,a,o,l,c){Un.texture=e,Un.mipLevel=t,Un.origin.z=n,Gr.offset=n*s,Gr.bytesPerRow=a,Gr.rowsPerImage=o,Ln.width=l,Ln.height=c,r.queue.writeTexture(Un,i.data,Gr,Ln),Un.reset(),Gr.reset(),Ln.reset()}var bv=class{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){let t=this.backend,n=e.texture,i=e.textureNode,s=n.minFilter+"-"+n.magFilter+"-"+n.wrapS+"-"+n.wrapT+"-"+(n.wrapR||"0")+"-"+n.anisotropy+"-"+(n.isDepthTexture===!0?1:0)+"-"+(n.compareFunction!==null&&i.compareNode!==null?n.compareFunction:0),a=this._samplerCache.get(s);if(a===void 0){In.addressModeU=this._convertAddressMode(n.wrapS),In.addressModeV=this._convertAddressMode(n.wrapT),In.addressModeW=this._convertAddressMode(n.wrapR),In.magFilter=this._convertFilterMode(n.magFilter),In.minFilter=this._convertFilterMode(n.minFilter),In.mipmapFilter=this._convertMipmapFilterMode(n.minFilter),n.isDepthTexture&&(n.compareFunction===null||i.compareNode===null)&&(In.magFilter=ts.Nearest,In.minFilter=ts.Nearest,In.mipmapFilter=ts.Nearest),In.magFilter===ts.Linear&&In.minFilter===ts.Linear&&In.mipmapFilter===ts.Linear&&(In.maxAnisotropy=n.anisotropy),n.isDepthTexture&&n.compareFunction!==null&&i.compareNode!==null&&t.hasCompatibility(Fr.TEXTURE_COMPARE)&&(In.compare=nV[n.compareFunction]);let l=t.device.createSampler(In);In.reset(),a={sampler:l,usedTimes:0},this._samplerCache.set(s,a)}let o=t.get(e);return o.sampler!==a.sampler&&(this._releaseSampler(o),o.samplerKey=s,o.sampler=a.sampler,a.usedTimes++),s}destroySampler(e){this._releaseSampler(this.backend.get(e))}_releaseSampler(e){if(e.sampler!==void 0){let t=this._samplerCache.get(e.samplerKey);t.usedTimes--,t.usedTimes===0&&this._samplerCache.delete(e.samplerKey),e.sampler=void 0,e.samplerKey=void 0}}createDefaultTexture(e){let t,n=vv(e,this.backend.device);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(n):t=this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){let n=this.backend,i=n.get(e);if(i.initialized){if(i.externalTexture===!0)return;throw new Error("THREE.WebGPUTextureUtils: Texture already initialized.")}if(e.isExternalTexture){i.texture=e.sourceTexture,i.initialized=!0;return}t.needsMipmaps===void 0&&(t.needsMipmaps=!1),t.levels===void 0&&(t.levels=1),t.depth===void 0&&(t.depth=1);let{width:s,height:a,depth:o,levels:l}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());let c=this._getDimension(e),u=e.internalFormat||t.format||vv(e,n.device);i.format=u;let{samples:d,primarySamples:h,isMSAA:p}=n.utils.getTextureSampleData(e),f=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(f|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&u!==A.RGB9E5UFloat&&(f|=GPUTextureUsage.RENDER_ATTACHMENT);let m=new Kh;if(m.label=e.name,m.size.width=s,m.size.height=a,m.size.depthOrArrayLayers=o,m.mipLevelCount=l,m.sampleCount=h,m.dimension=c,m.format=u,m.usage=f,u===void 0){X("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);return}e.isCubeTexture&&(m.textureBindingViewDimension=Sn.Cube);try{i.texture=n.device.createTexture(m)}catch{X("WebGPURenderer: Failed to create texture with descriptor:",m),this.createDefaultTexture(e);return}if(p){let y=Object.assign({},m);y.label=y.label+"-msaa",y.sampleCount=d,y.mipLevelCount=1,i.msaaTexture=n.device.createTexture(y)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e,t=!1){let n=this.backend,i=n.get(e);i.texture!==void 0&&t===!1&&e.isExternalTexture!==!0&&i.texture.destroy(),i.msaaTexture!==void 0&&i.msaaTexture.destroy(),n.delete(e)}generateMipmaps(e,t=null){let n=this.backend.get(e);this._generateMipmaps(n.texture,t)}getColorBuffer(){let e=this.backend,t=e.renderer.getCanvasTarget(),{width:n,height:i}=e.getDrawingBufferSize(),s=e.renderer.currentSamples,a=t.colorTexture,o=e.get(a);if(a.width===n&&a.height===i&&a.samples===s)return o.texture;let l=o.texture;return l&&l.destroy(),Va.label="colorBuffer",Va.size.width=n,Va.size.height=i,Va.sampleCount=e.utils.getSampleCount(e.renderer.currentSamples),Va.format=e.utils.getPreferredCanvasFormat(),Va.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,l=e.device.createTexture(Va),Va.reset(),a.source.width=n,a.source.height=i,a.samples=s,o.texture=l,l}getDepthBuffer(e=!0,t=!1){let n=this.backend,i=n.renderer.getCanvasTarget(),{width:s,height:a}=n.getDrawingBufferSize(),o=n.renderer.currentSamples,l=i.depthTexture;if(l.width===s&&l.height===a&&l.samples===o&&l.depth===e&&l.stencil===t)return n.get(l).texture;let c=n.get(l).texture,u,d;if(t?(u=Zi,d=n.renderer.reversedDepthBuffer===!0?en:vs):e&&(u=ui,d=n.renderer.reversedDepthBuffer===!0?en:it),c!==void 0){if(l.image.width===s&&l.image.height===a&&l.format===u&&l.type===d&&l.samples===o)return c;this.destroyTexture(l)}return l.name="depthBuffer",l.format=u,l.type=d,l.image.width=s,l.image.height=a,l.samples=o,this.createTexture(l,{width:s,height:a}),n.get(l).texture}updateTexture(e,t){let n=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:s}=n;if(!(e.isRenderTargetTexture||s===void 0)){if(e.isDataTexture)if(i.length>0)for(let a=0,o=i.length;a<o;a++){let l=i[a];this._copyBufferToTexture(l,n.texture,s,0,e.flipY,0,a)}else this._copyBufferToTexture(t.image,n.texture,s,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)if(e.layerUpdates&&e.layerUpdates.size>0){for(let a of e.layerUpdates)this._copyBufferToTexture(t.image,n.texture,s,a,e.flipY,a);e.clearLayerUpdates()}else for(let a=0;a<t.image.depth;a++)this._copyBufferToTexture(t.image,n.texture,s,a,e.flipY,a);else if(e.isCompressedTexture||e.isCompressedArrayTexture)e.isCompressedArrayTexture&&e.layerUpdates.size>0?(this._copyCompressedBufferToTexture(e.mipmaps,n.texture,s,e.layerUpdates),e.clearLayerUpdates()):this._copyCompressedBufferToTexture(e.mipmaps,n.texture,s);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,n.texture,s);else if(e.isHTMLTexture){let a=this.backend.device,o=this.backend.renderer.domElement,l=e.image;if(typeof a.queue.copyElementImageToTexture!="function")return;if(!n.hasPaintCallback){n.hasPaintCallback=!0,o.requestPaint();return}let c=s.size.width,u=s.size.height;a.queue.copyElementImageToTexture.length===2?a.queue.copyElementImageToTexture({source:l},{destination:{texture:n.texture},width:c,height:u}):a.queue.copyElementImageToTexture(l,c,u,{texture:n.texture}),e.flipY&&this._flipY(n.texture,s)}else if(i.length>0)for(let a=0,o=i.length;a<o;a++){let l=i[a];this._copyImageToTexture(l,n.texture,s,0,e.flipY,e.premultiplyAlpha,a)}else this._copyImageToTexture(t.image,n.texture,s,0,e.flipY,e.premultiplyAlpha);n.version=e.version}}async copyTextureToBuffer(e,t,n,i,s,a){let o=this.backend.device,l=this.backend.get(e),c=l.texture,u=l.textureDescriptorGPU.format,d=this._getBytesPerTexel(u),h=i*d;h=Math.ceil(h/256)*256,Hf.size=(s-1)*h+i*d,Hf.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;let p=o.createBuffer(Hf);Hf.reset();let f=o.createCommandEncoder(tV);Un.texture=c,Un.origin.x=t,Un.origin.y=n,Un.origin.z=a,Wf.buffer=p,Wf.bytesPerRow=h,Ln.width=i,Ln.height=s,f.copyTextureToBuffer(Un,Wf,Ln),Un.reset(),Wf.reset(),Ln.reset();let m=this._getTypedArrayType(u);nr(o,f.finish()),await p.mapAsync(GPUMapMode.READ);let y=p.getMappedRange().slice();return p.destroy(),new m(y)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){let n=new mn;n.minFilter=vt,n.magFilter=vt,this.createTexture(n,{width:1,height:1,format:e}),this.defaultTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(t===void 0){let n=new xa;n.minFilter=vt,n.magFilter=vt,this.createTexture(n,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=n}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,n){let i=e.images,s=e.mipmaps;for(let a=0;a<6;a++){let o=i[a],l=e.flipY===!0?iV[a]:a;o.isDataTexture?this._copyBufferToTexture(o.image,t,n,l,e.flipY):this._copyImageToTexture(o,t,n,l,e.flipY,e.premultiplyAlpha);for(let c=0;c<s.length;c++){let d=s[c].images[a];d.isDataTexture?this._copyBufferToTexture(d.image,t,n,l,e.flipY,0,c+1):this._copyImageToTexture(d,t,n,l,e.flipY,e.premultiplyAlpha,c+1)}}}_copyImageToTexture(e,t,n,i,s,a,o=0){let l=this.backend.device,c=o>0?e.width:n.size.width,u=o>0?e.height:n.size.height;qf.source=e,qf.flipY=s,Qc.texture=t,Qc.mipLevel=o,Qc.origin.z=i,Qc.premultipliedAlpha=a,Ln.width=c,Ln.height=u;try{l.queue.copyExternalImageToTexture(qf,Qc,Ln)}catch{}finally{qf.reset(),Qc.reset(),Ln.reset()}}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new fv(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,i,s,a=0,o=0){let l=this.backend.device,c=e.data,u=this._getBytesPerTexel(n.format),d=e.width*u;Un.texture=t,Un.mipLevel=o,Un.origin.z=i,Gr.offset=e.width*e.height*u*a,Gr.bytesPerRow=d,Ln.width=e.width,Ln.height=e.height,l.queue.writeTexture(Un,c,Gr,Ln),Un.reset(),Gr.reset(),Ln.reset(),s===!0&&this._flipY(t,n,i)}_copyCompressedBufferToTexture(e,t,n,i=null){let s=this.backend.device,a=this._getBlockData(n.format),o=n.size.depthOrArrayLayers>1,l=i&&i.size>0?i:null;for(let c=0;c<e.length;c++){let u=e[c],d=u.width,h=u.height,p=o?n.size.depthOrArrayLayers:1,f=Math.ceil(d/a.width)*a.byteLength,m=Math.ceil(h/a.height),y=f*m,x=Math.ceil(d/a.width)*a.width,b=m*a.height;if(l!==null)for(let _ of l)zM(s,t,c,_,u,y,f,m,x,b);else for(let _=0;_<p;_++)zM(s,t,c,_,u,y,f,m,x,b)}}_getBlockData(e){if(e===A.BC1RGBAUnorm||e===A.BC1RGBAUnormSRGB)return{byteLength:8,width:4,height:4};if(e===A.BC2RGBAUnorm||e===A.BC2RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===A.BC3RGBAUnorm||e===A.BC3RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===A.BC4RUnorm||e===A.BC4RSnorm)return{byteLength:8,width:4,height:4};if(e===A.BC5RGUnorm||e===A.BC5RGSnorm)return{byteLength:16,width:4,height:4};if(e===A.BC6HRGBUFloat||e===A.BC6HRGBFloat)return{byteLength:16,width:4,height:4};if(e===A.BC7RGBAUnorm||e===A.BC7RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===A.ETC2RGB8Unorm||e===A.ETC2RGB8UnormSRGB)return{byteLength:8,width:4,height:4};if(e===A.ETC2RGB8A1Unorm||e===A.ETC2RGB8A1UnormSRGB)return{byteLength:8,width:4,height:4};if(e===A.ETC2RGBA8Unorm||e===A.ETC2RGBA8UnormSRGB)return{byteLength:16,width:4,height:4};if(e===A.EACR11Unorm)return{byteLength:8,width:4,height:4};if(e===A.EACR11Snorm)return{byteLength:8,width:4,height:4};if(e===A.EACRG11Unorm)return{byteLength:16,width:4,height:4};if(e===A.EACRG11Snorm)return{byteLength:16,width:4,height:4};if(e===A.ASTC4x4Unorm||e===A.ASTC4x4UnormSRGB)return{byteLength:16,width:4,height:4};if(e===A.ASTC5x4Unorm||e===A.ASTC5x4UnormSRGB)return{byteLength:16,width:5,height:4};if(e===A.ASTC5x5Unorm||e===A.ASTC5x5UnormSRGB)return{byteLength:16,width:5,height:5};if(e===A.ASTC6x5Unorm||e===A.ASTC6x5UnormSRGB)return{byteLength:16,width:6,height:5};if(e===A.ASTC6x6Unorm||e===A.ASTC6x6UnormSRGB)return{byteLength:16,width:6,height:6};if(e===A.ASTC8x5Unorm||e===A.ASTC8x5UnormSRGB)return{byteLength:16,width:8,height:5};if(e===A.ASTC8x6Unorm||e===A.ASTC8x6UnormSRGB)return{byteLength:16,width:8,height:6};if(e===A.ASTC8x8Unorm||e===A.ASTC8x8UnormSRGB)return{byteLength:16,width:8,height:8};if(e===A.ASTC10x5Unorm||e===A.ASTC10x5UnormSRGB)return{byteLength:16,width:10,height:5};if(e===A.ASTC10x6Unorm||e===A.ASTC10x6UnormSRGB)return{byteLength:16,width:10,height:6};if(e===A.ASTC10x8Unorm||e===A.ASTC10x8UnormSRGB)return{byteLength:16,width:10,height:8};if(e===A.ASTC10x10Unorm||e===A.ASTC10x10UnormSRGB)return{byteLength:16,width:10,height:10};if(e===A.ASTC12x10Unorm||e===A.ASTC12x10UnormSRGB)return{byteLength:16,width:12,height:10};if(e===A.ASTC12x12Unorm||e===A.ASTC12x12UnormSRGB)return{byteLength:16,width:12,height:12}}_convertAddressMode(e){let t=$y.ClampToEdge;return e===Ei?t=$y.Repeat:e===da&&(t=$y.MirrorRepeat),t}_convertFilterMode(e){let t=ts.Linear;return(e===vt||e===rf||e===Na)&&(t=ts.Nearest),t}_convertMipmapFilterMode(e){return e===Na||e===bs?ts.Linear:ts.Nearest}_getBytesPerTexel(e){if(e===A.R8Unorm||e===A.R8Snorm||e===A.R8Uint||e===A.R8Sint)return 1;if(e===A.R16Uint||e===A.R16Sint||e===A.R16Float||e===A.RG8Unorm||e===A.RG8Snorm||e===A.RG8Uint||e===A.RG8Sint||e===A.R16Unorm||e===A.R16Snorm)return 2;if(e===A.R32Uint||e===A.R32Sint||e===A.R32Float||e===A.RG16Uint||e===A.RG16Sint||e===A.RG16Float||e===A.RGBA8Unorm||e===A.RGBA8UnormSRGB||e===A.RGBA8Snorm||e===A.RGBA8Uint||e===A.RGBA8Sint||e===A.BGRA8Unorm||e===A.BGRA8UnormSRGB||e===A.RG16Unorm||e===A.RG16Snorm||e===A.RGB9E5UFloat||e===A.RGB10A2Unorm||e===A.RG11B10UFloat||e===A.Depth32Float||e===A.Depth24Plus||e===A.Depth24PlusStencil8||e===A.Depth32FloatStencil8)return 4;if(e===A.RG32Uint||e===A.RG32Sint||e===A.RG32Float||e===A.RGBA16Uint||e===A.RGBA16Sint||e===A.RGBA16Float||e===A.RGBA16Unorm||e===A.RGBA16Snorm)return 8;if(e===A.RGBA32Uint||e===A.RGBA32Sint||e===A.RGBA32Float)return 16}_getTypedArrayType(e){if(e===A.R8Uint)return Uint8Array;if(e===A.R8Sint)return Int8Array;if(e===A.R8Unorm)return Uint8Array;if(e===A.R8Snorm)return Int8Array;if(e===A.RG8Uint)return Uint8Array;if(e===A.RG8Sint)return Int8Array;if(e===A.RG8Unorm)return Uint8Array;if(e===A.RG8Snorm)return Int8Array;if(e===A.RGBA8Uint)return Uint8Array;if(e===A.RGBA8Sint)return Int8Array;if(e===A.RGBA8Unorm||e===A.RGBA8UnormSRGB)return Uint8Array;if(e===A.RGBA8Snorm)return Int8Array;if(e===A.R16Uint)return Uint16Array;if(e===A.R16Sint)return Int16Array;if(e===A.RG16Uint)return Uint16Array;if(e===A.RG16Sint)return Int16Array;if(e===A.RGBA16Uint)return Uint16Array;if(e===A.RGBA16Sint)return Int16Array;if(e===A.R16Float||e===A.RG16Float||e===A.RGBA16Float||e===A.R16Unorm)return Uint16Array;if(e===A.R16Snorm)return Int16Array;if(e===A.RG16Unorm)return Uint16Array;if(e===A.RG16Snorm)return Int16Array;if(e===A.RGBA16Unorm)return Uint16Array;if(e===A.RGBA16Snorm)return Int16Array;if(e===A.R32Uint)return Uint32Array;if(e===A.R32Sint)return Int32Array;if(e===A.R32Float)return Float32Array;if(e===A.RG32Uint)return Uint32Array;if(e===A.RG32Sint)return Int32Array;if(e===A.RG32Float)return Float32Array;if(e===A.RGBA32Uint)return Uint32Array;if(e===A.RGBA32Sint)return Int32Array;if(e===A.RGBA32Float)return Float32Array;if(e===A.BGRA8Unorm||e===A.BGRA8UnormSRGB)return Uint8Array;if(e===A.RGB10A2Unorm||e===A.RGB9E5UFloat||e===A.RG11B10UFloat)return Uint32Array;if(e===A.Depth32Float)return Float32Array;if(e===A.Depth24Plus||e===A.Depth24PlusStencil8)return Uint32Array;if(e===A.Depth32FloatStencil8)return Float32Array}_getDimension(e){let t;return e.is3DTexture||e.isData3DTexture?t=VM.ThreeD:t=VM.TwoD,t}};function vv(r,e){let t=r.format,n=r.type,i=r.normalized,s=r.colorSpace,a=Fe.getTransfer(s),o,l=!1;if(i&&(l=e.features.has(ag.TextureFormatsTier1),l===!1&&X("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),r.isCompressedTexture===!0||r.isCompressedArrayTexture===!0)switch(t){case Do:case Io:o=a===be?A.BC1RGBAUnormSRGB:A.BC1RGBAUnorm;break;case Fo:o=a===be?A.BC2RGBAUnormSRGB:A.BC2RGBAUnorm;break;case Lo:o=a===be?A.BC3RGBAUnormSRGB:A.BC3RGBAUnorm;break;case kc:o=A.BC4RUnorm;break;case Vc:o=A.BC4RSnorm;break;case Uo:o=A.BC5RGUnorm;break;case Gc:o=A.BC5RGSnorm;break;case Bc:o=a===be?A.BC7RGBAUnormSRGB:A.BC7RGBAUnorm;break;case Uc:o=A.BC6HRGBFloat;break;case Oc:o=A.BC6HRGBUFloat;break;case yc:case gc:o=a===be?A.ETC2RGB8UnormSRGB:A.ETC2RGB8Unorm;break;case xc:o=a===be?A.ETC2RGBA8UnormSRGB:A.ETC2RGBA8Unorm;break;case _c:o=A.EACR11Unorm;break;case bc:o=A.EACR11Snorm;break;case Bo:o=A.EACRG11Unorm;break;case vc:o=A.EACRG11Snorm;break;case Sc:o=a===be?A.ASTC4x4UnormSRGB:A.ASTC4x4Unorm;break;case Tc:o=a===be?A.ASTC5x4UnormSRGB:A.ASTC5x4Unorm;break;case Mc:o=a===be?A.ASTC5x5UnormSRGB:A.ASTC5x5Unorm;break;case wc:o=a===be?A.ASTC6x5UnormSRGB:A.ASTC6x5Unorm;break;case Ec:o=a===be?A.ASTC6x6UnormSRGB:A.ASTC6x6Unorm;break;case Rc:o=a===be?A.ASTC8x5UnormSRGB:A.ASTC8x5Unorm;break;case Ac:o=a===be?A.ASTC8x6UnormSRGB:A.ASTC8x6Unorm;break;case Cc:o=a===be?A.ASTC8x8UnormSRGB:A.ASTC8x8Unorm;break;case Nc:o=a===be?A.ASTC10x5UnormSRGB:A.ASTC10x5Unorm;break;case Pc:o=a===be?A.ASTC10x6UnormSRGB:A.ASTC10x6Unorm;break;case Dc:o=a===be?A.ASTC10x8UnormSRGB:A.ASTC10x8Unorm;break;case Ic:o=a===be?A.ASTC10x10UnormSRGB:A.ASTC10x10Unorm;break;case Fc:o=a===be?A.ASTC12x10UnormSRGB:A.ASTC12x10Unorm;break;case Lc:o=a===be?A.ASTC12x12UnormSRGB:A.ASTC12x12Unorm;break;case bn:o=a===be?A.RGBA8UnormSRGB:A.RGBA8Unorm;break;default:G("WebGPURenderer: Unsupported texture format.",t)}else switch(t){case bn:switch(n){case Dr:o=A.RGBA8Snorm;break;case Ir:o=l?A.RGBA16Snorm:A.RGBA16Sint;break;case qs:o=l?A.RGBA16Unorm:A.RGBA16Uint;break;case it:o=A.RGBA32Uint;break;case zt:o=A.RGBA32Sint;break;case Gt:o=a===be?A.RGBA8UnormSRGB:A.RGBA8Unorm;break;case xt:o=A.RGBA16Float;break;case en:o=A.RGBA32Float;break;default:G("WebGPURenderer: Unsupported texture type with RGBAFormat.",n)}break;case Pa:switch(n){case pc:o=A.RGB9E5UFloat;break;case fc:o=A.RG11B10UFloat;break;default:G("WebGPURenderer: Unsupported texture type with RGBFormat.",n)}break;case Da:switch(n){case Dr:o=A.R8Snorm;break;case Ir:o=l?A.R16Snorm:A.R16Sint;break;case qs:o=l?A.R16Unorm:A.R16Uint;break;case it:o=A.R32Uint;break;case zt:o=A.R32Sint;break;case Gt:o=A.R8Unorm;break;case xt:o=A.R16Float;break;case en:o=A.R32Float;break;default:G("WebGPURenderer: Unsupported texture type with RedFormat.",n)}break;case mi:switch(n){case Dr:o=A.RG8Snorm;break;case Ir:o=l?A.RG16Snorm:A.RG16Sint;break;case qs:o=l?A.RG16Unorm:A.RG16Uint;break;case it:o=A.RG32Uint;break;case zt:o=A.RG32Sint;break;case Gt:o=A.RG8Unorm;break;case xt:o=A.RG16Float;break;case en:o=A.RG32Float;break;default:G("WebGPURenderer: Unsupported texture type with RGFormat.",n)}break;case ui:switch(n){case qs:o=A.Depth16Unorm;break;case it:o=A.Depth24Plus;break;case en:o=A.Depth32Float;break;default:G("WebGPURenderer: Unsupported texture type with DepthFormat.",n)}break;case Zi:switch(n){case vs:o=A.Depth24PlusStencil8;break;case en:e&&e.features.has(ag.Depth32FloatStencil8)===!1&&G('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=A.Depth32FloatStencil8;break;default:G("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",n)}break;case Ia:switch(n){case zt:o=A.R32Sint;break;case it:o=A.R32Uint;break;default:G("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",n)}break;case Fa:switch(n){case zt:o=A.RG32Sint;break;case it:o=A.RG32Uint;break;default:G("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",n)}break;case mc:switch(n){case zt:o=A.RGBA32Sint;break;case it:o=A.RGBA32Uint;break;default:G("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",n)}break;default:G("WebGPURenderer: Unsupported texture format.",t)}return o}var sV=/^[fn]*s*([a-z_0-9]+)?s*(([sS]*?))s*[->]*s*([a-z_0-9]+(?:<[sS]+?>)?)/i,rV=/([a-z_0-9]+)s*:s*([a-z_0-9]+(?:<[sS]+?>)?)/ig,HM={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"},aV=r=>{r=r.trim();let e=r.match(sV);if(e!==null&&e.length===4){let t=e[2],n=[],i=null;for(;(i=rV.exec(t))!==null;)n.push({name:i[1],type:i[2]});let s=[];for(let u=0;u<n.length;u++){let{name:d,type:h}=n[u],p=h;p.startsWith("ptr")?p="pointer":(p.startsWith("texture")&&(p=h.split("<")[0]),p=HM[p]),s.push(new $h(p,d))}let a=r.substring(e[0].length),o=e[3]||"void",l=e[1]!==void 0?e[1]:"";return{type:HM[o]||o,inputs:s,name:l,inputsCode:t,blockCode:a,outputType:o}}else throw new Error("THREE.WGSLNodeFunction: Function is not a WGSL code.")},Sv=class extends Yh{constructor(e){let{type:t,inputs:n,name:i,inputsCode:s,blockCode:a,outputType:o}=aV(e);super(t,n,i),this.inputsCode=s,this.blockCode=a,this.outputType=o}getCode(e=this.name){let t=this.outputType!=="void"?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}},Tv=class extends $m{parseFunction(e){return new Sv(e)}},oV={[Mn.READ_ONLY]:"read",[Mn.WRITE_ONLY]:"write",[Mn.READ_WRITE]:"read_write"},WM={[Ei]:"repeat",[ai]:"clamp",[da]:"mirror"},Jy={vertex:lr.VERTEX,fragment:lr.FRAGMENT,compute:lr.COMPUTE},qM={instance:!0,swizzleAssign:!1,storageBuffer:!0},lV={"^^":"tsl_xor"},cV={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},$M={},fh={tsl_xor:new st("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new st("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new st("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new st("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new st("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new st("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new st("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new st("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new st("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new st("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new st("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new st("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),inverse_mat2:new st(`
fn tsl_inverse_mat2( m : mat2x2<f32> ) -> mat2x2<f32> {
let det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];
return mat2x2<f32>(
m[ 1 ][ 1 ], - m[ 0 ][ 1 ],
- m[ 1 ][ 0 ], m[ 0 ][ 0 ]
) * ( 1.0 / det );
}
`),inverse_mat3:new st(`
fn tsl_inverse_mat3( m : mat3x3<f32> ) -> mat3x3<f32> {
let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ];
let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ];
let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ];
let b01 = a22 * a11 - a12 * a21;
let b11 = - a22 * a10 + a12 * a20;
let b21 = a21 * a10 - a11 * a20;
let det = a00 * b01 + a01 * b11 + a02 * b21;
return mat3x3<f32>(
b01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ),
b11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ),
b21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 )
) * ( 1.0 / det );
}
`),inverse_mat4:new st(`
fn tsl_inverse_mat4( m : mat4x4<f32> ) -> mat4x4<f32> {
let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ];
let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ];
let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ];
let a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ];
let b00 = a00 * a11 - a01 * a10;
let b01 = a00 * a12 - a02 * a10;
let b02 = a00 * a13 - a03 * a10;
let b03 = a01 * a12 - a02 * a11;
let b04 = a01 * a13 - a03 * a11;
let b05 = a02 * a13 - a03 * a12;
let b06 = a20 * a31 - a21 * a30;
let b07 = a20 * a32 - a22 * a30;
let b08 = a20 * a33 - a23 * a30;
let b09 = a21 * a32 - a22 * a31;
let b10 = a21 * a33 - a23 * a31;
let b11 = a22 * a33 - a23 * a32;
let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
return mat4x4<f32>(
a11 * b11 - a12 * b10 + a13 * b09,
a02 * b10 - a01 * b11 - a03 * b09,
a31 * b05 - a32 * b04 + a33 * b03,
a22 * b04 - a21 * b05 - a23 * b03,
a12 * b08 - a10 * b11 - a13 * b07,
a00 * b11 - a02 * b08 + a03 * b07,
a32 * b02 - a30 * b05 - a33 * b01,
a20 * b05 - a22 * b02 + a23 * b01,
a10 * b10 - a11 * b08 + a13 * b06,
a01 * b08 - a00 * b10 - a03 * b06,
a30 * b04 - a31 * b02 + a33 * b00,
a21 * b02 - a20 * b04 - a23 * b00,
a11 * b07 - a10 * b09 - a12 * b06,
a00 * b09 - a01 * b07 + a02 * b06,
a31 * b01 - a30 * b03 - a32 * b00,
a20 * b03 - a21 * b01 + a22 * b00
) * ( 1.0 / det );
}
`),biquadraticTexture:new st(`
fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
let res = vec2f( iRes );
let uvScaled = coord * res;
let uvWrapping = ( ( uvScaled % res ) + res ) % res;
// https://www.shadertoy.com/view/WtyXRy
let uv = uvWrapping - 0.5;
let iuv = floor( uv );
let f = fract( uv );
let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
}
`),biquadraticTextureArray:new st(`
fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
let res = vec2f( iRes );
let uvScaled = coord * res;
let uvWrapping = ( ( uvScaled % res ) + res ) % res;
// https://www.shadertoy.com/view/WtyXRy
let uv = uvWrapping - 0.5;
let iuv = floor( uv );
let f = fract( uv );
let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
}
`)},uV={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inverse_mat2:"tsl_inverse_mat2",inverse_mat3:"tsl_inverse_mat3",inverse_mat4:"tsl_inverse_mat4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"},uC="";(typeof navigator<"u"&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(uC+=`diagnostic( off, derivative_uniformity );
`);var Mv=class extends Wm{constructor(e,t){super(e,t,new Tv),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,n,i,s,a=this.shaderStage){return a==="fragment"?i?s?`textureSample( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:s?`textureSample( ${t}, ${t}_sampler, ${n}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,"0",i)}generateTextureSampleLevel(e,t,n,i,s,a){return this.isUnfilterable(e)===!1?s?a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,a,i,s):this.generateTextureLod(e,t,n,s,a,i)}generateWrapFunction(e){let t=`tsl_coord_${WM[e.wrapS]}S_${WM[e.wrapT]}T_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}`,n=$M[t];if(n===void 0){let i=[],s=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f",a=`fn ${t}( coord : ${s} ) -> ${s} {
return ${s}(
`,o=(l,c)=>{l===Ei?(i.push(fh.repeatWrapping_float),a+=` tsl_repeatWrapping_float( coord.${c} )`):l===ai?(i.push(fh.clampWrapping_float),a+=` tsl_clampWrapping_float( coord.${c} )`):l===da?(i.push(fh.mirrorWrapping_float),a+=` tsl_mirrorWrapping_float( coord.${c} )`):(a+=` coord.${c}`,X(`WebGPURenderer: Unsupported texture wrap type "${l}" for vertex shader.`))};o(e.wrapS,"x"),a+=`,
`,o(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(a+=`,
`,o(e.wrapR,"z")),a+=`
);
}
`,$M[t]=n=new st(a,i)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){let i=this.getDataFromNode(e,this.shaderStage,this.cache);i.dimensionsSnippet===void 0&&(i.dimensionsSnippet={});let s=i.dimensionsSnippet[n];if(i.dimensionsSnippet[n]===void 0){let a,o,{primarySamples:l}=this.renderer.backend.utils.getTextureSampleData(e),c=l>1;e.is3DTexture||e.isData3DTexture?o="vec3<u32>":o="vec2<u32>",c||e.isStorageTexture?a=t:a=`${t}${n?`, u32( ${n} )`:""}`,s=new uu(new hu(`textureDimensions( ${a} )`,o)),i.dimensionsSnippet[n]=s,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new uu(new hu(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new uu(new hu("6u","u32")))}return s.build(this)}generateFilteredTexture(e,t,n,i,s="0u",a){let o=this.generateWrapFunction(e),l=this.generateTextureDimension(e,t,s);return i&&(n=`${n} + vec2<f32>(${i}) / ${l}`),a?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${o}( ${n} ), ${l}, u32( ${a} ), u32( ${s} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${o}( ${n} ), ${l}, u32( ${s} ) )`)}generateTextureLod(e,t,n,i,s,a="0u"){if(e.isCubeTexture===!0){s&&(n=`${n} + vec3<f32>(${s})`);let p=e.isDepthTexture?"u32":"f32";return`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${p}( ${a} ) )`}let o=this.generateWrapFunction(e),l=this.generateTextureDimension(e,t,a),c=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",u=c==="vec3"?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )";s&&(n=`${n} + ${c}<f32>(${s}) / ${c}<f32>( ${l} )`);let d=`${c}<f32>( 0 )`,h=`${c}<f32>( ${l} - ${u} )`;return n=`${c}<u32>( clamp( floor( ${o}( ${n} ) * ${c}<f32>( ${l} ) ), ${d}, ${h} ) )`,this.generateTextureLoad(e,t,n,a,i,null)}generateStorageTextureLoad(e,t,n,i,s,a){a&&(n=`${n} + ${a}`);let o;return s?o=`textureLoad( ${t}, ${n}, ${s} )`:o=`textureLoad( ${t}, ${n} )`,o}generateTextureLoad(e,t,n,i,s,a){i===null&&(i="0u"),a&&(n=`${n} + ${a}`);let o;return s?o=`textureLoad( ${t}, ${n}, ${s}, u32( ${i} ) )`:(o=`textureLoad( ${t}, ${n}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(o+=".x")),o}generateTextureStore(e,t,n,i,s){let a;return i?a=`textureStore( ${t}, ${n}, ${i}, ${s} )`:a=`textureStore( ${t}, ${n}, ${s} )`,a}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null&&this.renderer.hasCompatibility(Fr.TEXTURE_COMPARE)}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!=="float"||!this.isAvailable("float32Filterable")&&e.type===en||this.isSampleCompare(e)===!1&&e.minFilter===vt&&e.magFilter===vt||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,i,s,a=this.shaderStage){let o=null;return this.isUnfilterable(e)?o=this.generateTextureLod(e,t,n,i,s,"0",a):o=this._generateTextureSample(e,t,n,i,s,a),o}generateTextureGrad(e,t,n,i,s,a,o=this.shaderStage){if(o==="fragment")return s?a?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${s}, ${i[0]}, ${i[1]}, ${a} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${s}, ${i[0]}, ${i[1]} )`:a?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]}, ${a} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]} )`;G(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${o} shader.`)}generateTextureCompare(e,t,n,i,s,a,o=this.shaderStage){if(o==="fragment")return e.isDepthTexture===!0&&e.isArrayTexture===!0?a?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${a} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:a?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${a} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`;G(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}generateTextureGather(e,t,n,i,s,a){let o=e.isDepthTexture===!0?"":`${i}, `;return s?a?`textureGather( ${o}${t}, ${t}_sampler, ${n}, ${s}, ${a} )`:`textureGather( ${o}${t}, ${t}_sampler, ${n}, ${s} )`:a?`textureGather( ${o}${t}, ${t}_sampler, ${n}, ${a} )`:`textureGather( ${o}${t}, ${t}_sampler, ${n})`}generateTextureGatherCompare(e,t,n,i,s,a){return s?a?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${a} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i})`:a?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${a} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i})`}generateTextureLevel(e,t,n,i,s,a){return this.isUnfilterable(e)===!1?s?a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,a,i,s):this.generateTextureLod(e,t,n,s,a,i)}generateTextureBias(e,t,n,i,s,a,o=this.shaderStage){if(o==="fragment")return s?a?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${a} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:a?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${a} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i} )`;G(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${o} shader.`)}getPropertyName(e,t=this.shaderStage){if(e.isNodeVarying===!0&&e.needsInterpolation===!0){if(t==="vertex")return`varyings.${e.name}`}else if(e.isNodeUniform===!0){let n=e.name,i=e.type;return i==="texture"||i==="cubeTexture"||i==="cubeDepthTexture"||i==="storageTexture"||i==="texture3D"?n:i==="buffer"||i==="storageBuffer"||i==="indirectStorageBuffer"?this.isCustomStruct(e)?n:n+".value":e.groupNode.name+"."+n}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){let t=lV[e];return t!==void 0?(this._include(t),t):null}getNodeAccess(e,t){return t!=="compute"?e.isAtomic===!0?(X("WebGPURenderer: Atomic operations are only supported in compute shaders."),Mn.READ_WRITE):Mn.READ_ONLY:e.access}getStorageAccess(e,t){return oV[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,i=null){let s=super.getUniformFromNode(e,t,n,i),a=this.getDataFromNode(e,n,this.globalCache);if(a.uniformGPU===void 0){let o,l=e.groupNode,c=l.name,u=this.getBindGroupArray(c,n);if(t==="texture"||t==="cubeTexture"||t==="cubeDepthTexture"||t==="storageTexture"||t==="texture3D"){let d=null,h=this.getNodeAccess(e,n);if(t==="texture"||t==="storageTexture"?e.value.is3DTexture===!0?d=new jh(s.name,s.node,l,h):d=new Su(s.name,s.node,l,h):t==="cubeTexture"||t==="cubeDepthTexture"?d=new tg(s.name,s.node,l,h):t==="texture3D"&&(d=new jh(s.name,s.node,l,h)),d.store=e.isStorageTextureNode===!0,d.mipLevel=d.store?e.mipLevel:0,d.setVisibility(Jy[n]),e.value.isCubeTexture===!0||this.isUnfilterable(e.value)===!1&&d.store===!1||e.gatherNode!==null){let f=new cv(`${s.name}_sampler`,s.node,l);f.setVisibility(Jy[n]),u.push(f,d),o=[f,d]}else u.push(d),o=[d]}else if(t==="buffer"||t==="storageBuffer"||t==="indirectStorageBuffer"){let d=this.getSharedDataFromNode(e),h=d.buffer;if(h===void 0){let p=t==="buffer"?Jm:dv;h=new p(e,l),d.buffer=h}h.setVisibility(h.getVisibility()|Jy[n]),u.push(h),o=h,s.name=i||"NodeBuffer_"+s.id}else{let d=this.uniformGroups[c];d===void 0&&(d=new Qm(c,l),d.setVisibility(lr.VERTEX|lr.FRAGMENT|lr.COMPUTE),this.uniformGroups[c]=d),u.indexOf(d)===-1&&u.push(d),o=this.getNodeUniform(s,t);let h=o.name;d.uniforms.some(f=>f.name===h)||d.addUniform(o)}a.uniformGPU=o}return s}getBuiltin(e,t,n,i=this.shaderStage){let s=this.builtins[i]||(this.builtins[i]=new Map);return s.has(e)===!1&&s.set(e,{name:e,property:t,type:n}),t}hasBuiltin(e,t=this.shaderStage){return this.builtins[t]!==void 0&&this.builtins[t].has(e)}getVertexIndex(){return this.shaderStage==="vertex"?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){let t=e.layout,n=this.flowShaderNode(e),i=[];for(let a of t.inputs)i.push(a.name+" : "+this.getType(a.type));let s=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {
${n.vars}
${n.code}
`;return n.result&&(s+=` return ${n.result};
`),s+=`
}
`,s}getInstanceIndex(){return this.shaderStage==="vertex"?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){let t=[],n=this.directives[e];if(n!==void 0)for(let i of n)t.push(`enable ${i};`);return t.join(`
`)}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){let t=[],n=this.builtins[e];if(n!==void 0)for(let{name:i,property:s,type:a}of n.values())t.push(`@builtin( ${i} ) ${s} : ${a}`);return t.join(`,
`)}getScopedArray(e,t,n,i){return this.scopedArrays.has(e)===!1&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:i}),e}getScopedArrays(e){if(e!=="compute")return;let t=[];for(let{name:n,scope:i,bufferType:s,bufferCount:a}of this.scopedArrays.values()){let o=this.getType(s);t.push(`var<${i}> ${n}: array< ${o}, ${a} >;`)}return t.join(`
`)}getAttributes(e){let t=[];if(e==="compute"&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),e==="vertex"||e==="compute"){let n=this.getBuiltins("attribute");n&&t.push(n);let i=this.getAttributesArray();for(let s=0,a=i.length;s<a;s++){let o=i[s],l=o.name,c=this.getType(o.type);t.push(`@location( ${s} ) ${l} : ${c}`)}}return t.join(`,
`)}getStructMembers(e){let t=[];for(let n of e.members){let i=e.output?"@location( "+n.index+" ) ":"",s=this.getType(n.type);n.atomic&&(s="atomic< "+s+" >"),t.push(` ${i+n.name} : ${s}`)}return e.output&&t.push(` ${this.getBuiltins("output")}`),t.join(`,
`)}getStructs(e){let t="",n=this.structs[e];if(n.length>0){let i=[];for(let s of n){let a=`struct ${s.name} {
`;a+=this.getStructMembers(s),a+=`
};`,i.push(a)}t=`
`+i.join(`
`)+`
`}return t}getVar(e,t,n=null,i=""){let s=`var${i} ${t} : `;return n!==null?s+=this.generateArrayDeclaration(e,n):s+=this.getType(e),s}getVars(e,t=!1){let n="";t&&(n="<private>");let i=[],s=this.vars[e];if(s!==void 0)for(let a of s)i.push(`${this.getVar(a.type,a.name,a.count,n)};`);return t?i.join(`
`):`
${i.join(`
`)}
`}getVaryings(e){let t=[];if(e==="vertex"&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),e==="vertex"||e==="fragment"){let s=this.varyings,a=this.vars[e],o=0;for(let l=0;l<s.length;l++){let c=s[l];if(c.needsInterpolation){let u=`@location( ${o++} )`;if(c.interpolationType){let d=c.interpolationSampling!==null?`, ${c.interpolationSampling} )`:" )";u+=` @interpolate( ${c.interpolationType}${d}`}else/^(int|uint|ivec|uvec)/.test(c.type)&&(u+=" @interpolate(flat, either)");t.push(`${u} ${c.name} : ${this.getType(c.type)}`)}else e==="vertex"&&a.includes(c)===!1&&a.push(c)}}let n=this.getBuiltins(e);n&&t.push(n);let i=t.join(`,
`);return e==="vertex"?this._getWGSLStruct("VaryingsStruct"," "+i):i}isCustomStruct(e){let t=e.value,n=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&n.structTypeNode!==null,s=n.value&&n.value.array&&typeof n.value.itemSize=="number"&&n.value.array.length>n.value.itemSize;return i&&!s}getUniforms(e){let t=this.renderer.backend,n=this.uniforms[e],i=[],s=[],a=[],o={};for(let c of n){let u=c.groupNode.name,d=this.bindingsIndexes[u];if(c.type==="texture"||c.type==="cubeTexture"||c.type==="cubeDepthTexture"||c.type==="storageTexture"||c.type==="texture3D"){let h=c.node,p=h.value;(p.isCubeTexture===!0||this.isUnfilterable(p)===!1&&h.isStorageTextureNode!==!0||h.gatherNode!==null)&&(this.isSampleCompare(p)&&h.compareNode!==null?i.push(`@binding( ${d.binding++} ) @group( ${d.group} ) var ${c.name}_sampler : sampler_comparison;`):i.push(`@binding( ${d.binding++} ) @group( ${d.group} ) var ${c.name}_sampler : sampler;`));let m,y="",{primarySamples:x}=t.utils.getTextureSampleData(p);if(x>1&&(y="_multisampled"),p.isCubeTexture===!0&&p.isDepthTexture===!0)m="texture_depth_cube";else if(p.isCubeTexture===!0)m="texture_cube<f32>";else if(p.isDepthTexture===!0)t.compatibilityMode&&p.compareFunction===null?m=`texture${y}_2d<f32>`:m=`texture_depth${y}_2d${p.isArrayTexture===!0?"_array":""}`;else if(c.node.isStorageTextureNode===!0){let b=vv(p,t.device),_=this.getStorageAccess(c.node,e),S=c.node.value.is3DTexture,M=c.node.value.isArrayTexture;m=`texture_storage_${S?"3d":`2d${M?"_array":""}`}<${b}, ${_}>`}else if(p.isArrayTexture===!0||p.isDataArrayTexture===!0||p.isCompressedArrayTexture===!0)m="texture_2d_array<f32>";else if(p.is3DTexture===!0||p.isData3DTexture===!0)m="texture_3d<f32>";else{let b=this.getComponentTypeFromTexture(p).charAt(0);m=`texture${y}_2d<${b}32>`}i.push(`@binding( ${d.binding++} ) @group( ${d.group} ) var ${c.name} : ${m};`)}else if(c.type==="buffer"||c.type==="storageBuffer"||c.type==="indirectStorageBuffer"){let h=c.node,p=this.getType(h.getNodeType(this)),f=h.bufferCount,m=f>0&&c.type==="buffer"?", "+f:"",y=h.isStorageBufferNode?`storage, ${this.getStorageAccess(h,e)}`:"uniform";if(this.isCustomStruct(c))s.push(`@binding( ${d.binding++} ) @group( ${d.group} ) var<${y}> ${c.name} : ${p};`);else{let b=` value : array< ${h.isAtomic?`atomic<${p}>`:`${p}`}${m} >`;s.push(this._getWGSLStructBinding(c.name,b,y,d.binding++,d.group))}}else{let h=c.groupNode.name;if(o[h]===void 0){let p=this.uniformGroups[h];if(p!==void 0){let f=[];for(let y of p.uniforms){let x=y.getType(),b=this.getType(this.getVectorType(x));f.push(` ${y.name} : ${b}`)}let m=this.uniformGroupsBindings[h];m===void 0&&(m={index:d.binding++,id:d.group},this.uniformGroupsBindings[h]=m),o[h]={index:m.index,id:m.id,snippets:f}}}}}for(let c in o){let u=o[c];a.push(this._getWGSLStructBinding(c,u.snippets.join(`,
`),"uniform",u.index,u.id))}return[...i,...s,...a].join(`
`)}buildCode(){let e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(let t in e){this.shaderStage=t;let n=this.allowGlobalVariables,i=e[t];i.uniforms=this.getUniforms(t),i.attributes=this.getAttributes(t),i.varyings=this.getVaryings(t),i.structs=this.getStructs(t),i.vars=this.getVars(t,n),i.codes=this.getCodes(t),i.directives=this.getDirectives(t),i.scopedArrays=this.getScopedArrays(t);let s=`// code
`;s+=this.flowCode[t];let a=this.flowNodes[t],o=a[a.length-1],l=o.outputNode,c=l!==void 0&&l.isOutputStructNode===!0;for(let u of a){let d=this.getFlowData(u),h=u.name;if(h&&(s.length>0&&(s+=`
`),s+=` // flow -> ${h}
`),s+=`${d.code}
`,u===o&&t!=="compute"){if(s+=`// result
`,t==="vertex")s+=`varyings.builtinClipSpace = ${d.result};`;else if(t==="fragment")if(c)i.returnType=l.getNodeType(this),i.structs+="var<private> output : "+i.returnType+";",s+=`return ${d.result};`;else{let p=` @location( 0 ) color: ${this.getType(this.getOutputType())}`,f=this.getBuiltins("output");f&&(p+=`,
`+f),i.returnType="OutputStruct",i.structs+=this._getWGSLStruct("OutputStruct",p),i.structs+=`
var<private> output : OutputStruct;`,s+=`output.color = ${this.format(d.result,o.getNodeType(this),this.getOutputType())};
return output;`}}}i.flow=s}if(this.shaderStage=null,this.material!==null)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{let t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let n;return t!==null&&(n=this._getWGSLMethod(e+"_"+t)),n===void 0&&(n=this._getWGSLMethod(e)),n||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`select( ${n}, ${t}, ${e} )`}getType(e){return cV[e]||e}isAvailable(e){let t=qM[e];return t===void 0&&(e==="float32Filterable"?t=this.renderer.hasFeature("float32-filterable"):e==="clipDistance"&&(t=this.renderer.hasFeature("clip-distances")),qM[e]=t),t}_getWGSLMethod(e){return fh[e]!==void 0&&this._include(e),uV[e]}_include(e){let t=fh[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}
// directives
${e.directives}
// structs
${e.structs}
// uniforms
${e.uniforms}
// varyings
${e.varyings}
var<private> varyings : VaryingsStruct;
// vars
${e.vars}
// codes
${e.codes}
@vertex
fn main( ${e.attributes} ) -> VaryingsStruct {
// flow
${e.flow}
return varyings;
}
`}_getWGSLFragmentCode(e){return`${this.getSignature()}
// global
${uC}
// structs
${e.structs}
// uniforms
${e.uniforms}
// vars
${e.vars}
// codes
${e.codes}
@fragment
fn main( ${e.varyings} ) -> ${e.returnType} {
// flow
${e.flow}
}
`}_getWGSLComputeCode(e,t){let[n,i,s]=t;return`${this.getSignature()}
// directives
${e.directives}
// system
var<private> instanceIndex : u32;
// locals
${e.scopedArrays}
// structs
${e.structs}
// uniforms
${e.uniforms}
// vars
${this.allowGlobalVariables?e.vars:""}
// codes
${e.codes}
@compute @workgroup_size( ${n}, ${i}, ${s} )
fn main( ${e.attributes} ) {
// local vars
${this.allowGlobalVariables?"":e.vars}
// system
instanceIndex = globalId.x
+ globalId.y * ( ${n} * numWorkgroups.x )
+ globalId.z * ( ${n} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );
// flow
${e.flow}
}
`}_getWGSLStruct(e,t){return`
struct ${e} {
${t}
};`}_getWGSLStructBinding(e,t,n,i=0,s=0){let a=e+"Struct";return`${this._getWGSLStruct(a,t)}
@binding( ${i} ) @group( ${s} )
var<${n}> ${e} : ${a};`}},Fn=new to,Qy=new pl,dC=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);typeof Float16Array<"u"&&dC.set(Float16Array,["float16"]);var dV=new Map([[Yl,["float16"]]]),hV=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]),wv=class{constructor(e){this.backend=e}createAttribute(e,t){let n=this._getBufferAttribute(e),i=this.backend,s=i.get(n),a=s.buffer;if(a===void 0){let o=i.device,l=n.array;if(e.normalized===!1){if(l.constructor===Int16Array||l.constructor===Int8Array)l=new Int32Array(l);else if((l.constructor===Uint16Array||l.constructor===Uint8Array)&&(l=new Uint32Array(l),t&GPUBufferUsage.INDEX))for(let h=0;h<l.length;h++)l[h]===65535&&(l[h]=4294967295)}n.array=l;let c;if((n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&n.itemSize===3)c=4;else if(n.itemSize>1&&n.itemSize*l.BYTES_PER_ELEMENT%4!==0){let h=n.itemSize*l.BYTES_PER_ELEMENT;c=Math.floor((h+3)/4)*4/l.BYTES_PER_ELEMENT}if(c!==void 0){let h=n.itemSize,p=new l.constructor(n.count*c);for(let f=0;f<n.count;f++)p.set(l.subarray(f*h,f*h+h),f*c);(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&(n.itemSize=c,n.array=p),l=p,s._itemSize=h,s._paddedItemSize=c}let u=l.byteLength,d=u+(4-u%4)%4;Fn.label=n.name,Fn.size=d,Fn.usage=t,Fn.mappedAtCreation=!0,a=o.createBuffer(Fn),Fn.reset(),new l.constructor(a.getMappedRange()).set(l),a.unmap(),s.buffer=a}}updateAttribute(e){let t=this._getBufferAttribute(e),n=this.backend,i=n.device,s=n.get(t),a=n.get(t).buffer,o=t.array,l=s._itemSize,c=s._paddedItemSize;if(c!==void 0){o=new o.constructor(t.count*c);for(let d=0;d<t.count;d++)o.set(t.array.subarray(d*l,d*l+l),d*c);(t.isStorageBufferAttribute||t.isStorageInstancedBufferAttribute)&&(t.array=o)}let u=t.updateRanges;if(u.length===0)i.queue.writeBuffer(a,0,o,0);else{let d=Hc(o),h=d?1:o.BYTES_PER_ELEMENT;for(let p=0,f=u.length;p<f;p++){let m=u[p],y,x;if(c!==void 0){let _=Math.floor(m.start/l),S=Math.ceil((m.start+m.count)/l)-_;y=_*c*h,x=S*c*h}else y=m.start*h,x=m.count*h;let b=y*(d?o.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(a,b,o,y,x)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){let t=e.getAttributes(),n=new Map;for(let i=0;i<t.length;i++){let s=t[i],a=s.array.BYTES_PER_ELEMENT,o=this._getBufferAttribute(s),l=n.get(o);if(l===void 0){let d,h;s.isInterleavedBufferAttribute===!0?(d=s.data.stride*a,h=s.data.isInstancedInterleavedBuffer?Vf.Instance:Vf.Vertex):(d=s.itemSize*a,h=s.isInstancedBufferAttribute?Vf.Instance:Vf.Vertex,s.itemSize>1&&d%4!==0&&(d=Math.floor((d+3)/4)*4)),s.normalized===!1&&(s.array.constructor===Int16Array||s.array.constructor===Uint16Array)&&(d=4),l={arrayStride:d,attributes:[],stepMode:h},n.set(o,l)}let c=this._getVertexFormat(s),u=s.isInterleavedBufferAttribute===!0?s.offset*a:0;l.attributes.push({shaderLocation:i,offset:u,format:c})}return Array.from(n.values())}destroyAttribute(e){let t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,i=-1){let s=this.backend,a=s.device,l=s.get(this._getBufferAttribute(e)).buffer,c=i===-1?l.size-n:i,u;if(t!==null&&t.isReadbackBuffer){let p=s.get(t);if(t._mapped===!0)throw new Error("THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,p.readBufferGPU===void 0){Fn.label=`${t.name}_readback`,Fn.size=t.maxByteLength,Fn.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,u=a.createBuffer(Fn),Fn.reset();let f=()=>{t.buffer=null,t._mapped=!1,u.unmap()},m=()=>{t.buffer=null,t._mapped=!1,u.destroy(),s.delete(t),t.removeEventListener("release",f),t.removeEventListener("dispose",m)};t.addEventListener("release",f),t.addEventListener("dispose",m),p.readBufferGPU=u}else u=p.readBufferGPU}else Fn.label=`${e.name}_readback`,Fn.size=c,Fn.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,u=a.createBuffer(Fn),Fn.reset();Qy.label=`readback_encoder_${e.name}`;let d=a.createCommandEncoder(Qy);Qy.reset(),d.copyBufferToBuffer(l,n,u,0,c);let h=d.finish();if(nr(a,h),await u.mapAsync(GPUMapMode.READ,0,c),t===null){let f=u.getMappedRange(0,c).slice();return u.destroy(),f}else{if(t.isReadbackBuffer)return t.buffer=u.getMappedRange(0,c),t;{let p=u.getMappedRange(0,c);return new Uint8Array(t).set(new Uint8Array(p)),u.destroy(),t}}}_getVertexFormat(e){let{itemSize:t,normalized:n}=e,i=e.array.constructor,s=e.constructor,a;if(t===1)a=hV.get(i);else{let l=(dV.get(s)||dC.get(i))[n?1:0];if(l){let c=i.BYTES_PER_ELEMENT*t,d=Math.floor((c+3)/4)*4/i.BYTES_PER_ELEMENT;if(d%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");a=`${l}x${d}`}}return a||G("WebGPUAttributeUtils: Vertex format not supported yet."),a}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}},Ci=new og,mh=new to,eu=new Zh,Ev=class{constructor(e){this.layoutGPU=e,this.usedTimes=0}},Rv=class{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){let t=this.backend,n=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;let s=this._createLayoutEntries(e),a=Mu(JSON.stringify(s)),o=this._bindGroupLayoutCache.get(a);return o===void 0&&(o=new Ev(n.createBindGroupLayout({entries:s})),this._bindGroupLayoutCache.set(a,o)),o.usedTimes++,i.layout=o,i.layoutKey=a,o.layoutGPU}createBindings(e,t,n,i=0){let{backend:s}=this,a=s.get(e),o=this.createBindingsLayout(e),l;n>0&&(a.groups===void 0&&(a.groups=[],a.versions=[]),a.versions[n]===i&&(l=a.groups[n])),l===void 0&&(l=this.createBindGroup(e,o),n>0&&(a.groups[n]=l,a.versions[n]=i)),a.group=l}updateBinding(e){let t=this.backend,n=t.device,i=e.buffer,s=t.get(e).buffer,a=e.updateRanges;if(a.length===0)n.queue.writeBuffer(s,0,i,0);else{let o=Hc(i),l=o?1:i.BYTES_PER_ELEMENT,c=a[0].start;for(let u=0,d=a.length;u<d;u++){let h=a[u],p=a[u+1],f=h.start+h.count;if(p!==void 0&&p.start===f)continue;let m=c*l,y=(f-c)*l,x=m*(o?i.BYTES_PER_ELEMENT:1);n.queue.writeBuffer(s,x,i,m,y),p!==void 0&&(c=p.start)}}}createBindGroupIndex(e,t){let i=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,a=e[0];mh.label="bindingCameraIndex_"+a,mh.size=16,mh.usage=s;let o=i.createBuffer(mh);mh.reset(),i.queue.writeBuffer(o,0,e,0),Ci.label="bindGroupCameraIndex_"+a,Ci.layout=t,Ci.entries.push({binding:0,resource:{buffer:o}});let l=i.createBindGroup(Ci);return Ci.reset(),l}createBindGroup(e,t){let n=this.backend,i=n.device,s=0;Ci.label="bindGroup_"+e.name,Ci.layout=t;for(let o of e.bindings){if(o.isUniformBuffer){let l=n.get(o);Ci.entries.push({binding:s,resource:{buffer:l.buffer}})}else if(o.isStorageBuffer){let l=n.get(o.attribute).buffer;Ci.entries.push({binding:s,resource:{buffer:l}})}else if(o.isSampledTexture){let l=n.get(o.texture),c;if(l.externalTexture!==void 0)c=i.importExternalTexture({source:l.externalTexture});else{let u=o.store?1:l.texture.mipLevelCount,d=o.store?o.mipLevel:0,h=`view-${l.texture.width}-${l.texture.height}`;if(l.texture.depthOrArrayLayers>1&&(h+=`-${l.texture.depthOrArrayLayers}`),h+=`-${u}-${d}`,c=l[h],c===void 0){let p=Qk.All,f;o.isSampledCubeTexture?f=Sn.Cube:o.texture.isArrayTexture||o.texture.isDataArrayTexture||o.texture.isCompressedArrayTexture?f=Sn.TwoDArray:o.isSampledTexture3D?f=Sn.ThreeD:f=Sn.TwoD,eu.aspect=p,eu.dimension=f,eu.mipLevelCount=u,eu.baseMipLevel=d,c=l[h]=l.texture.createView(eu),eu.reset()}}Ci.entries.push({binding:s,resource:c})}else if(o.isSampler){let l=n.get(o);Ci.entries.push({binding:s,resource:l.sampler})}s++}let a=i.createBindGroup(Ci);return Ci.reset(),a}_createLayoutEntries(e){let t=[],n=0;for(let i of e.bindings){let s=this.backend,a={binding:n,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){let o={};i.isStorageBuffer&&(i.visibility&lr.COMPUTE&&(i.access===Mn.READ_WRITE||i.access===Mn.WRITE_ONLY)?o.type=Xy.Storage:o.type=Xy.ReadOnlyStorage),a.buffer=o}else if(i.isSampledTexture&&i.store){let o={};o.format=this.backend.get(i.texture).texture.format;let l=i.access;l===Mn.READ_WRITE?o.access=Yy.ReadWrite:l===Mn.WRITE_ONLY?o.access=Yy.WriteOnly:o.access=Yy.ReadOnly,i.texture.isArrayTexture?o.viewDimension=Sn.TwoDArray:i.texture.is3DTexture&&(o.viewDimension=Sn.ThreeD),a.storageTexture=o}else if(i.isSampledTexture){let o={},{primarySamples:l}=s.utils.getTextureSampleData(i.texture);if(l>1&&(o.multisampled=!0,i.texture.isDepthTexture||(o.sampleType=qo.UnfilterableFloat)),i.texture.isDepthTexture)s.compatibilityMode&&i.texture.compareFunction===null?o.sampleType=qo.UnfilterableFloat:o.sampleType=qo.Depth;else{let c=i.texture.type;c===zt?o.sampleType=qo.SInt:c===it?o.sampleType=qo.UInt:c===en&&(this.backend.hasFeature("float32-filterable")?o.sampleType=qo.Float:o.sampleType=qo.UnfilterableFloat)}i.isSampledCubeTexture?o.viewDimension=Sn.Cube:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?o.viewDimension=Sn.TwoDArray:i.isSampledTexture3D&&(o.viewDimension=Sn.ThreeD),a.texture=o}else if(i.isSampler){let o={};i.texture.isDepthTexture&&(i.texture.compareFunction!==null&&i.textureNode.compareNode!==null&&s.hasCompatibility(Fr.TEXTURE_COMPARE)?o.type=kM.Comparison:o.type=kM.NonFiltering),a.sampler=o}else G(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(a),n++}return t}deleteBindGroupData(e){let{backend:t}=this,n=t.get(e);n.layout&&(n.layout.usedTimes--,n.layout.usedTimes===0&&this._bindGroupLayoutCache.delete(n.layoutKey),n.layout=void 0,n.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}},Av=class{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}},Cv=class{constructor(){this.label="",this.layout=null,this.compute=null}reset(){this.label="",this.layout=null,this.compute=null}},Nv=class{constructor(){this.label="",this.bindGroupLayouts=null}reset(){this.label="",this.bindGroupLayouts=null}},gh=new Cv,tu=new Nv,nu=new lg,Ni=new cg,Pv=class{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){let{object:n,material:i,geometry:s,pipeline:a}=e,{vertexProgram:o,fragmentProgram:l}=a,c=this.backend,u=c.device,d=c.utils,h=c.get(a),p=[];for(let k of e.getBindings()){let j=c.get(k),{layoutGPU:ee}=j.layout;p.push(ee)}let f=c.attributeUtils.createShaderVertexBuffers(e),m;i.blending!==_s&&(i.blending!==li||i.transparent!==!1)&&(m=this._getBlending(i));let y={};i.stencilWrite===!0&&(y={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});let x=this._getColorWriteMask(i),b=[];if(e.context.textures!==null){let k=e.context.textures,j=e.context.mrt;for(let ee=0;ee<k.length;ee++){let ge=k[ee],fe=d.getTextureFormatGPU(ge),he;if(j!==null)if(this.backend.compatibilityMode!==!0){let ye=j.getBlendMode(ge.name);ye.blending===Ld?he=m:ye.blending!==_s&&(he=this._getBlending(ye))}else Ce("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),he=m;else he=m;b.push({format:fe,blend:he,writeMask:x})}}else{let k=d.getCurrentColorFormat(e.context);b.push({format:k,blend:m,writeMask:x})}let _=c.get(o).module,S=c.get(l).module,M=this._getPrimitiveState(n,s,i),w=this._getDepthCompare(i),T=d.getCurrentDepthStencilFormat(e.context),R=this._getSampleCount(e.context);tu.bindGroupLayouts=p;let D=u.createPipelineLayout(tu);tu.reset(),Ni.label=`renderPipeline_${i.name||i.type}_${i.id}`,Ni.vertex=Object.assign({},_,{buffers:f}),Ni.fragment=Object.assign({},S,{targets:b}),Ni.primitive=M,Ni.multisample.count=R,Ni.multisample.alphaToCoverageEnabled=i.alphaToCoverage&&R>1,Ni.layout=D;let L={},B=e.context.depth,W=e.context.stencil;(B===!0||W===!0)&&(B===!0&&(L.format=T,L.depthWriteEnabled=i.depthWrite,L.depthCompare=w),W===!0&&(L.stencilFront=y,L.stencilBack=y,L.stencilReadMask=i.stencilFuncMask,L.stencilWriteMask=i.stencilWriteMask),i.polygonOffset===!0&&M.topology===bh.TriangleList&&(L.depthBias=i.polygonOffsetUnits,L.depthBiasSlopeScale=i.polygonOffsetFactor,L.depthBiasClamp=0),Ni.depthStencil=L),u.pushErrorScope("validation");let q=[{program:o,module:_.module},{program:l,module:S.module}],ce=Ni.label;if(t===null)h.pipeline=u.createRenderPipeline(Ni),Ni.reset(),u.popErrorScope().then(k=>{k!==null&&(h.error=!0,G(`WebGPURenderer: Render pipeline creation failed (${ce}): ${k.message}`),this._reportShaderDiagnostics(q,ce))});else{let k=new Promise(async j=>{try{let ee=null,ge=null;try{ge=u.createRenderPipelineAsync(Ni)}catch(he){ee=he}if(Ni.reset(),ge!==null)try{h.pipeline=await ge}catch(he){ee=he}let fe=await u.popErrorScope();if(fe!==null||ee!==null){h.error=!0;let he=fe&&fe.message||ee&&ee.message||"unknown";G(`WebGPURenderer: Async render pipeline creation failed (${ce}): ${he}`),await this._reportShaderDiagnostics(q,ce)}}finally{j()}});t.push(k)}}createBundleEncoder(e,t="renderBundleEncoder"){let n=this.backend,{utils:i,device:s}=n,a=i.getCurrentDepthStencilFormat(e),o=i.getCurrentColorFormats(e),l=this._getSampleCount(e);nu.label=t,nu.colorFormats=o,nu.depthStencilFormat=a,nu.sampleCount=l;let c=s.createRenderBundleEncoder(nu);return nu.reset(),c}createComputePipeline(e,t){let n=this.backend,i=n.device,s=n.get(e.computeProgram).module,a=n.get(e),o=[];for(let d of t){let h=n.get(d),{layoutGPU:p}=h.layout;o.push(p)}let l=e.computeProgram,c=`computePipeline_${l.stage}${l.name?`_${l.name}`:""}`;i.pushErrorScope("validation"),tu.bindGroupLayouts=o;let u=i.createPipelineLayout(tu);tu.reset(),gh.label=c,gh.compute=s,gh.layout=u,a.pipeline=i.createComputePipeline(gh),gh.reset(),i.popErrorScope().then(d=>{d!==null&&(a.error=!0,G(`WebGPURenderer: Compute pipeline creation failed (${c}): ${d.message}`),this._reportShaderDiagnostics([{program:l,module:s.module}],c))})}async _reportShaderDiagnostics(e,t){for(let{program:n,module:i}of e){let s=await i.getCompilationInfo();if(s.messages.length===0)continue;let a=n.code.split(`
`);for(let o of s.messages){let l=o.lineNum>0?` at line ${o.lineNum}${o.linePos>0?`:${o.linePos}`:""}`:"",c=`WebGPURenderer [${t} / ${n.stage} ${o.type}]${l}: ${o.message}`,u="";o.lineNum>0&&o.lineNum<=a.length&&(u=`
${a[o.lineNum-1]}`,o.linePos>0&&(u+=`
${" ".repeat(o.linePos-1)}^`)),(o.type==="error"?G:X)(c+u)}}}_getBlending(e){let t,n,i=e.blending,s=e.blendSrc,a=e.blendDst,o=e.blendEquation;if(i===Ra){let l=e.blendSrcAlpha!==null?e.blendSrcAlpha:s,c=e.blendDstAlpha!==null?e.blendDstAlpha:a,u=e.blendEquationAlpha!==null?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(s),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(o)},n={srcFactor:this._getBlendFactor(l),dstFactor:this._getBlendFactor(c),operation:this._getBlendOperation(u)}}else{let l=e.premultipliedAlpha,c=(u,d,h,p)=>{t={srcFactor:u,dstFactor:d,operation:Wo.Add},n={srcFactor:h,dstFactor:p,operation:Wo.Add}};if(l)switch(i){case li:c(Le.One,Le.OneMinusSrcAlpha,Le.One,Le.OneMinusSrcAlpha);break;case Ma:c(Le.One,Le.One,Le.One,Le.One);break;case wa:c(Le.Zero,Le.OneMinusSrc,Le.Zero,Le.One);break;case Ea:c(Le.Dst,Le.OneMinusSrcAlpha,Le.Zero,Le.One);break}else switch(i){case li:c(Le.SrcAlpha,Le.OneMinusSrcAlpha,Le.One,Le.OneMinusSrcAlpha);break;case Ma:c(Le.SrcAlpha,Le.One,Le.One,Le.One);break;case wa:G(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case Ea:G(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break}}if(t!==void 0&&n!==void 0)return{color:t,alpha:n};G("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case Ws:t=Le.Zero;break;case Xp:t=Le.One;break;case Yp:t=Le.Src;break;case jp:t=Le.OneMinusSrc;break;case fo:t=Le.SrcAlpha;break;case mo:t=Le.OneMinusSrcAlpha;break;case Jp:t=Le.Dst;break;case Qp:t=Le.OneMinusDst;break;case Kp:t=Le.DstAlpha;break;case Zp:t=Le.OneMinusDstAlpha;break;case ef:t=Le.SrcAlphaSaturated;break;case sL:t=Le.Constant;break;case rL:t=Le.OneMinusConstant;break;default:G("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t,n=e.stencilFunc;switch(n){case ty:t=vn.Never;break;case Hu:t=vn.Always;break;case ny:t=vn.Less;break;case sy:t=vn.LessEqual;break;case iy:t=vn.Equal;break;case oy:t=vn.GreaterEqual;break;case ry:t=vn.Greater;break;case ay:t=vn.NotEqual;break;default:G("WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case Sr:t=Ua.Keep;break;case Y0:t=Ua.Zero;break;case j0:t=Ua.Replace;break;case ey:t=Ua.Invert;break;case K0:t=Ua.IncrementClamp;break;case Z0:t=Ua.DecrementClamp;break;case J0:t=Ua.IncrementWrap;break;case Q0:t=Ua.DecrementWrap;break;default:G("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case ci:t=Wo.Add;break;case qp:t=Wo.Subtract;break;case $p:t=Wo.ReverseSubtract;break;case H0:t=Wo.Min;break;case W0:t=Wo.Max;break;default:G("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){let i={},s=this.backend.utils;i.topology=s.getPrimitiveTopology(e,n),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?rg.Uint16:rg.Uint32);let a=n.side===ln;return e.isMesh&&e.matrixWorld.determinantAffine()<0&&(a=!a),i.frontFace=a===!0?BM.CW:BM.CCW,i.cullMode=n.side===Ri?UM.None:UM.Back,i}_getColorWriteMask(e){return e.colorWrite===!0?OM.All:OM.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=vn.Always;else{let n=this.backend.parameters.reversedDepthBuffer?df[e.depthFunc]:e.depthFunc;switch(n){case Ll:t=vn.Never;break;case Bl:t=vn.Always;break;case Ul:t=vn.Less;break;case ua:t=vn.LessEqual;break;case Ol:t=vn.Equal;break;case kl:t=vn.GreaterEqual;break;case Vl:t=vn.Greater;break;case Gl:t=vn.NotEqual;break;default:G("WebGPUPipelineUtils: Invalid depth function.",n)}}return t}},hg=class{constructor(){this.label="",this.type=void 0,this.count=0}reset(){this.label="",this.type=void 0,this.count=0}},Js=new to,pV=new pl,yh=new hg,Dv=class extends ig{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,yh.label=`queryset_global_timestamp_${t}`,yh.type="timestamp",yh.count=this.maxQueries,this.querySet=this.device.createQuerySet(yh),yh.reset();let i=this.maxQueries*8;Js.label=`buffer_timestamp_resolve_${t}`,Js.size=i,Js.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,this.resolveBuffer=this.device.createBuffer(Js),Js.reset(),Js.label=`buffer_timestamp_result_${t}`,Js.size=i,Js.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this.resultBuffer=this.device.createBuffer(Js),Js.reset()}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Ce(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;let t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||this.currentQueryIndex===0||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if(this.resultBuffer.mapState!=="unmapped")return this.lastValue;let e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=t*8;this.currentQueryIndex=0,this.queryOffsets.clear();let i=this.device.createCommandEncoder(pV);i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);let s=i.finish();if(nr(this.device,s),this.resultBuffer.mapState!=="unmapped")return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue;let a=new BigUint64Array(this.resultBuffer.getMappedRange(0,n)),o={},l=[];for(let[u,d]of e){let h=u.match(/^(.*):f(d+)$/),p=parseInt(h[2]);l.includes(p)===!1&&l.push(p),o[p]===void 0&&(o[p]=0);let f=a[d],m=a[d+1],y=Number(m-f)/1e6;this.timestamps.set(u,y),o[p]+=y}let c=o[l[l.length-1]];return this.resultBuffer.unmap(),this.lastValue=c,this.frames=l,c}catch(e){return G("Error resolving queries:",e),this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){G("Error waiting for pending resolve:",e)}if(this.resultBuffer&&this.resultBuffer.mapState==="mapped")try{this.resultBuffer.unmap()}catch(e){G("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}},Iv=class{constructor(){this.label="",this.timestampWrites=void 0}reset(){this.label="",this.timestampWrites=void 0}},ou=class{constructor(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}reset(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}},Fv=class{constructor(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}reset(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}},Ms={r:0,g:0,b:0,a:1},Pi=new to,Yn=new pl,$f=new Iv,xh=new hg,Xf=new ug,Yf=new Fv,es=new Tu,Qs=new Tu,Tt=new Zh,Or=new dg,Lv=class extends ng{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0?!0:e.alpha,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new hv(this),this.attributeUtils=new wv(this),this.bindingUtils=new Rv(this),this.capabilities=new Av(this),this.pipelineUtils=new Pv(this),this.textureUtils=new bv(this),this.occludedResolveCache=new Map;let t=typeof navigator>"u"?!0:/Android/.test(navigator.userAgent)===!1;this._compatibility={[Fr.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);let t=this.parameters,n;if(t.device===void 0){let i={powerPreference:t.powerPreference,featureLevel:"compatibility",xrCompatible:e.xr.enabled},s=typeof navigator<"u"?await navigator.gpu.requestAdapter(i):null;if(s===null)throw new Error("THREE.WebGPUBackend: Unable to create WebGPU adapter.");let a=Object.values(ag),o=[];for(let c of a)s.features.has(c)&&o.push(c);let l={requiredFeatures:o,requiredLimits:t.requiredLimits};n=await s.requestDevice(l)}else n=t.device;this.compatibilityMode=!n.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),n.lost.then(i=>{if(i.reason==="destroyed")return;let s={api:"WebGPU",message:i.message||"Unknown reason",reason:i.reason||null,originalEvent:i};e.onDeviceLost(s)}),n.onuncapturederror=i=>{let s=i.error,a=s&&s.constructor?s.constructor.name:"GPUError",o=s&&s.message||"Unknown uncaptured GPU error";e.onError({api:"WebGPU",type:a,message:o,originalEvent:i})},this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(ag.TimestampQuery),this.updateSize()}setXRRenderTargetTextures(e,t,n=null){this.set(e.texture,{texture:t,format:t.format,externalTexture:!0,xrViewDescriptors:n,initialized:!0})}get context(){let e=this.renderer.getCanvasTarget(),t=this.get(e),n=t.context;if(n===void 0){let i=this.parameters;e.isDefaultCanvasTarget===!0&&i.context!==void 0?n=i.context:n=e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${"185"} webgpu`);let s=i.alpha?"premultiplied":"opaque",a=i.outputType===xt?"extended":"standard";n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:s,toneMapping:{mode:a}}),t.context=n}return n}get coordinateSystem(){return di}get hasTimestamp(){return!0}async getArrayBufferAsync(e,t=null,n=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,i)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),i=e.currentSamples,s=n.descriptor;if(s===void 0||n.samples!==i){if(s=new rl,s.colorAttachments.push(new sl),e.depth===!0||e.stencil===!0){let l=new ou;l.view=this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView(),s.depthStencilAttachment=l}let o=s.colorAttachments[0];i>0?o.view=this.textureUtils.getColorBuffer().createView():o.resolveTarget=void 0,n.descriptor=s,n.samples=i}let a=s.colorAttachments[0];return i>0?a.resolveTarget=this.context.getCurrentTexture().createView():a.view=this.context.getCurrentTexture().createView(),s}_isRenderCameraDepthArray(e){let t=e.camera;return e.depthTexture&&e.depthTexture.isArrayTexture===!0&&t!==null&&t.isArrayCamera===!0}_hasExternalTexture(e){let t=e.textures;if(t===null)return!1;for(let n=0;n<t.length;n++)if(this.get(t[n]).externalTexture===!0)return!0;return!1}_createExternalTextureViews(e,t){let n=[],i=e.camera;if(t.xrViewDescriptors&&i!==null&&i.isArrayCamera===!0)for(let s=0;s<t.xrViewDescriptors.length;s++)n.push({view:t.texture.createView(t.xrViewDescriptors[s]),resolveTarget:void 0,depthSlice:void 0});else n.push({view:t.texture.createView({dimension:Sn.TwoD,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1}),resolveTarget:void 0,depthSlice:void 0});return n}_getRenderPassDescriptor(e,t={}){let n=e.renderTarget,i=this.get(n),s=this._hasExternalTexture(e),a=i.descriptors;(a===void 0||i.width!==n.width||i.height!==n.height||i.samples!==n.samples||s)&&(a={},i.descriptors=a);let o=e.getCacheKey(),l=a[o];if(l===void 0||s){let u=e.textures,d=[],h,p=this._isRenderCameraDepthArray(e);for(let m=0;m<u.length;m++){let y=this.get(u[m]);if(y.externalTexture===!0){d.push(...this._createExternalTextureViews(e,y));continue}if(Tt.label=`colorAttachment_${m}`,Tt.baseMipLevel=e.activeMipmapLevel,Tt.mipLevelCount=1,Tt.baseArrayLayer=e.activeCubeFace,Tt.arrayLayerCount=1,Tt.dimension=Sn.TwoD,n.isRenderTarget3D)h=e.activeCubeFace,Tt.baseArrayLayer=0,Tt.dimension=Sn.ThreeD;else if(n.isRenderTarget&&u[m].image.depth>1)if(p===!0){let x=e.camera.cameras;for(let b=0;b<x.length;b++){Tt.baseArrayLayer=b,Tt.arrayLayerCount=1,Tt.dimension=Sn.TwoD;let _=y.texture.createView(Tt);d.push({view:_,resolveTarget:void 0,depthSlice:void 0})}}else Tt.dimension=Sn.TwoDArray;if(p!==!0){let x=y.texture.createView(Tt),b,_;y.msaaTexture!==void 0?(b=y.msaaTexture.createView(),_=x):(b=x,_=void 0),d.push({view:b,resolveTarget:_,depthSlice:h})}Tt.reset()}let f=[];for(let m=0;m<d.length;m++){let y=d[m],x=new sl;x.view=y.view,x.depthSlice=y.depthSlice,x.resolveTarget=y.resolveTarget,f.push(x)}if(l={textureViews:d,colorAttachments:f,descriptor:new rl},e.depth){let m=this.get(e.depthTexture);(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(Tt.dimension=Sn.TwoD,Tt.arrayLayerCount=1,Tt.baseArrayLayer=e.activeCubeFace);let y=new ou;y.view=m.texture.createView(Tt),l.depthStencilAttachment=y,Tt.reset()}a[o]=l,i.width=n.width,i.height=n.height,i.samples=n.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}let c=l.descriptor;c.reset();for(let u=0;u<l.colorAttachments.length;u++){let d=l.colorAttachments[u],h={r:0,g:0,b:0,a:1};u===0&&t.clearValue&&(h=t.clearValue),d.loadOp=t.loadOp||qe.Load,d.storeOp=t.storeOp||jn.Store,d.clearValue=h,c.colorAttachments.push(d)}return l.depthStencilAttachment&&(c.depthStencilAttachment=l.depthStencilAttachment),c}beginRender(e){let t=this.get(e),n=this.device,i=e.occlusionQueryCount,s;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,xh.label=`occlusionQuerySet_${e.id}`,xh.type="occlusion",xh.count=i,s=n.createQuerySet(xh),xh.reset(),t.occlusionQuerySet=s,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null);let a;e.textures===null?a=this._getDefaultRenderPassDescriptor():a=this._getRenderPassDescriptor(e,{loadOp:qe.Load}),this.initTimestampQuery(Ji.RENDER,this.getTimestampUID(e),a),a.occlusionQuerySet=s;let o=a.depthStencilAttachment;if(e.textures!==null){let c=a.colorAttachments;for(let u=0;u<c.length;u++){let d=c[u];e.clearColor?(u===0?d.clearValue=e.clearColorValue:(Ms.r=0,Ms.g=0,Ms.b=0,Ms.a=1,d.clearValue=Ms),d.loadOp=qe.Clear):d.loadOp=qe.Load,d.storeOp=jn.Store}}else{let c=a.colorAttachments[0];e.clearColor?(c.clearValue=e.clearColorValue,c.loadOp=qe.Clear):c.loadOp=qe.Load,c.storeOp=jn.Store}e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=qe.Clear):o.depthLoadOp=qe.Load,o.depthStoreOp=jn.Store),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=qe.Clear):o.stencilLoadOp=qe.Load,o.stencilStoreOp=jn.Store),Yn.label="renderContext_"+e.id;let l=n.createCommandEncoder(Yn);if(Yn.reset(),this._isRenderCameraDepthArray(e)===!0){let c=e.camera.cameras;!t.layerDescriptors||t.layerDescriptors.length!==c.length?this._createArrayCameraLayerDescriptors(e,t,a,c):this._updateArrayCameraLayerDescriptors(e,t,c),t.bundleEncoders=[],t.bundleSets=[];for(let u=0;u<c.length;u++){let d=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+u),h={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(d),t.bundleSets.push(h)}t.currentPass=null}else{let c=l.beginRenderPass(a);t.currentPass=c,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=a,t.encoder=l,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createArrayCameraLayerDescriptors(e,t,n,i){let s=n.depthStencilAttachment;t.layerDescriptors=[];let a=this.get(e.depthTexture);a.viewCache||(a.viewCache=[]);for(let o=0;o<i.length;o++){let l=n.colorAttachments[0],c=new sl;c.view=n.colorAttachments[o].view,c.depthSlice=l.depthSlice,c.resolveTarget=l.resolveTarget,c.loadOp=l.loadOp,c.storeOp=l.storeOp,c.clearValue=l.clearValue;let u=new rl;if(u.label=n.label,u.occlusionQuerySet=n.occlusionQuerySet,u.timestampWrites=n.timestampWrites,u.colorAttachments.push(c),n.depthStencilAttachment){let d=o;a.viewCache[d]||(Tt.dimension=Sn.TwoD,Tt.baseArrayLayer=o,Tt.arrayLayerCount=1,a.viewCache[d]=a.texture.createView(Tt),Tt.reset());let h=new ou;h.view=a.viewCache[d],h.depthLoadOp=s.depthLoadOp||qe.Clear,h.depthStoreOp=s.depthStoreOp||jn.Store,h.depthClearValue=s.depthClearValue||1,e.stencil&&(h.stencilLoadOp=s.stencilLoadOp,h.stencilStoreOp=s.stencilStoreOp,h.stencilClearValue=s.stencilClearValue),u.depthStencilAttachment=h}else{let d=new ou;d.view=s.view,d.depthLoadOp=s.depthLoadOp,d.depthStoreOp=s.depthStoreOp,d.depthClearValue=s.depthClearValue,d.depthReadOnly=s.depthReadOnly,d.stencilLoadOp=s.stencilLoadOp,d.stencilStoreOp=s.stencilStoreOp,d.stencilClearValue=s.stencilClearValue,d.stencilReadOnly=s.stencilReadOnly,u.depthStencilAttachment=d}t.layerDescriptors.push(u)}}_updateArrayCameraLayerDescriptors(e,t,n){for(let i=0;i<n.length;i++){let s=t.layerDescriptors[i];if(s.depthStencilAttachment){let a=s.depthStencilAttachment;e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=qe.Clear):a.depthLoadOp=qe.Load),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=qe.Clear):a.stencilLoadOp=qe.Load)}}}finishRender(e){let t=this.get(e),n=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();let i=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){let s=[];for(let a=0;a<t.bundleEncoders.length;a++){let o=t.bundleEncoders[a];s.push(o.finish())}for(let a=0;a<t.layerDescriptors.length;a++)if(a<s.length){let o=t.layerDescriptors[a],l=i.beginRenderPass(o);if(e.viewport){let{x:c,y:u,width:d,height:h,minDepth:p,maxDepth:f}=e.viewportValue;l.setViewport(c,u,d,h,p,f)}if(e.scissor){let{x:c,y:u,width:d,height:h}=e.scissorValue;l.setScissorRect(c,u,d,h)}l.executeBundles([s[a]]),l.end()}}else t.currentPass&&t.currentPass.end();if(n>0){let s=n*8,a=this.occludedResolveCache.get(s);a===void 0&&(Pi.size=s,Pi.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,a=this.device.createBuffer(Pi),Pi.reset(),this.occludedResolveCache.set(s,a)),Pi.size=s,Pi.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;let o=this.device.createBuffer(Pi);Pi.reset(),t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,a,0),t.encoder.copyBufferToBuffer(a,0,o,0,s),t.occlusionQueryBuffer=o,this.resolveOccludedAsync(e)}if(nr(this.device,t.encoder.finish()),e.textures!==null){let s=e.textures;for(let a=0;a<s.length;a++){let o=s[a];o.generateMipmaps===!0&&this.textureUtils.generateMipmaps(o)}}}isOccluded(e,t){let n=this.get(e);return n.occluded&&n.occluded.has(t)}async resolveOccludedAsync(e){let t=this.get(e),{currentOcclusionQueryBuffer:n,currentOcclusionQueryObjects:i}=t;if(n&&i){let s=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await n.mapAsync(GPUMapMode.READ);let a=n.getMappedRange(),o=new BigUint64Array(a);for(let l=0;l<i.length;l++)o[l]===BigInt(0)&&s.add(i[l]);n.destroy(),t.occluded=s}}updateViewport(e){let{currentPass:t}=this.get(e),{x:n,y:i,width:s,height:a,minDepth:o,maxDepth:l}=e.viewportValue;t.setViewport(n,i,s,a,o,l)}updateScissor(e){let{currentPass:t}=this.get(e),{x:n,y:i,width:s,height:a}=e.scissorValue;t.setScissorRect(n,i,s,a)}getClearColor(){let e=super.getClearColor();return this.renderer.alpha===!0&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,n,i=null){let s=this.device,a=this.renderer,o=[],l,c,u;if(e){let p=this.getClearColor();Ms.r=p.r,Ms.g=p.g,Ms.b=p.b,Ms.a=p.a}if(i===null){c=a.depth,u=a.stencil;let p=this._getDefaultRenderPassDescriptor();if(e){o=p.colorAttachments;let f=o[0];f.clearValue=Ms,f.loadOp=qe.Clear,f.storeOp=jn.Store}(c||u)&&(l=p.depthStencilAttachment)}else{c=i.depth,u=i.stencil;let p={loadOp:e?qe.Clear:qe.Load,clearValue:e?Ms:void 0};c&&(p.depthLoadOp=t?qe.Clear:qe.Load,p.depthClearValue=t?a.getClearDepth():void 0,p.depthStoreOp=jn.Store),u&&(p.stencilLoadOp=n?qe.Clear:qe.Load,p.stencilClearValue=n?a.getClearStencil():void 0,p.stencilStoreOp=jn.Store);let f=this._getRenderPassDescriptor(i,p);o=f.colorAttachments,l=f.depthStencilAttachment}c&&l&&(t?(l.depthLoadOp=qe.Clear,l.depthClearValue=a.getClearDepth(),l.depthStoreOp=jn.Store):(l.depthLoadOp=qe.Load,l.depthStoreOp=jn.Store)),u&&l&&(n?(l.stencilLoadOp=qe.Clear,l.stencilClearValue=a.getClearStencil(),l.stencilStoreOp=jn.Store):(l.stencilLoadOp=qe.Load,l.stencilStoreOp=jn.Store)),Yn.label="clear";let d=s.createCommandEncoder(Yn);Yn.reset(),d.beginRenderPass({colorAttachments:o,depthStencilAttachment:l}).end(),nr(s,d.finish())}beginCompute(e){let t=this.get(e),n="computeGroup_"+e.id;$f.label=n,Yn.label=n,this.initTimestampQuery(Ji.COMPUTE,this.getTimestampUID(e),$f),t.cmdEncoderGPU=this.device.createCommandEncoder(Yn),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass($f),t.currentPipeline=null,Yn.reset(),$f.reset()}compute(e,t,n,i,s=null){let a=this.get(t),o=this.get(e),{passEncoderGPU:l}=o,c=this.get(i).pipeline;o.currentPipeline!==c&&(l.setPipeline(c),o.currentPipeline=c);for(let u=0,d=n.length;u<d;u++){let h=n[u],p=this.get(h);l.setBindGroup(u,p.group)}if(s===null&&(s=t.dispatchSize||t.count),s&&s.isIndirectStorageBufferAttribute){let u=this.get(s).buffer;l.dispatchWorkgroupsIndirect(u,0);return}if(typeof s=="number"){let u=s;if(a.dispatchSize===void 0||a.count!==u){a.dispatchSize=[0,1,1],a.count=u;let d=t.workgroupSize,h=d[0];for(let m=1;m<d.length;m++)h*=d[m];let p=Math.ceil(u/h),f=this.device.limits.maxComputeWorkgroupsPerDimension;s=[p,1,1],p>f&&(s[0]=Math.min(p,f),s[1]=Math.ceil(p/f)),a.dispatchSize=s}s=a.dispatchSize}l.dispatchWorkgroups(s[0],s[1]||1,s[2]||1)}finishCompute(e){let t=this.get(e);t.passEncoderGPU.end(),nr(this.device,t.cmdEncoderGPU.finish())}_draw(e,t,n,i,s,a,o,l,c){let{object:u,material:d,context:h}=e,p=e.getIndex(),f=p!==null;c.pipeline!==i&&(l.setPipeline(i),c.pipeline=i);let m=c.bindingGroups;for(let y=0,x=s.length;y<x;y++){let b=s[y];if(m[y]!==b.id){let _=this.get(b);l.setBindGroup(y,_.group),m[y]=b.id}}if(f===!0&&c.index!==p){let y=this.get(p).buffer,x=p.array instanceof Uint16Array?rg.Uint16:rg.Uint32;l.setIndexBuffer(y,x),c.index=p}for(let y=0,x=a.length;y<x;y++){let b=a[y];if(c.attributes[y]!==b){let _=this.get(b).buffer;l.setVertexBuffer(y,_),c.attributes[y]=b}}if(h.stencil===!0&&d.stencilWrite===!0&&n.currentStencilRef!==d.stencilRef&&(l.setStencilReference(d.stencilRef),n.currentStencilRef=d.stencilRef),u.isBatchedMesh===!0){let y=u._multiDrawStarts,x=u._multiDrawCounts,b=u._multiDrawCount,_=f===!0?p.array.BYTES_PER_ELEMENT:1;d.wireframe&&(_=u.geometry.attributes.position.count>65535?4:2);for(let S=0;S<b;S++)f===!0?l.drawIndexed(x[S],1,y[S]/_,0,S):l.draw(x[S],1,y[S],S),t.update(u,x[S],1)}else if(f===!0){let{vertexCount:y,instanceCount:x,firstVertex:b}=o,_=e.getIndirect();if(_!==null){let S=this.get(_).buffer,M=e.getIndirectOffset(),w=Array.isArray(M)?M:[M];for(let T=0;T<w.length;T++)l.drawIndexedIndirect(S,w[T])}else l.drawIndexed(y,x,b,0,0);t.update(u,y,x)}else{let{vertexCount:y,instanceCount:x,firstVertex:b}=o,_=e.getIndirect();if(_!==null){let S=this.get(_).buffer,M=e.getIndirectOffset(),w=Array.isArray(M)?M:[M];for(let T=0;T<w.length;T++)l.drawIndirect(S,w[T])}else l.draw(y,x,b,0);t.update(u,y,x)}}draw(e,t){let{object:n,context:i,pipeline:s}=e,a=this.get(i),o=this.get(s),l=o.pipeline;if(o.error===!0)return;let c=e.getDrawParameters();if(c===null)return;let u=e.getBindings(),d=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){let h=this.get(e.camera),p=e.camera.cameras,f=e.getBindingGroup("cameraIndex");if(h.indexesGPU===void 0||h.indexesGPU.length!==p.length){let y=this.get(f),x=[],b=new Uint32Array([0,0,0,0]);for(let _=0,S=p.length;_<S;_++){b[0]=_;let{layoutGPU:M}=y.layout,w=this.bindingUtils.createBindGroupIndex(b,M);x.push(w)}h.indexesGPU=x}let m=this.renderer.getPixelRatio();for(let y=0,x=p.length;y<x;y++){let b=p[y];if(n.layers.test(b.layers)){let _=b.viewport,S=a.currentPass,M=a.currentSets,w=a.bundleEncoders!==void 0;if(w){let T=a.bundleEncoders[y],R=a.bundleSets[y];S=T,M=R}if(_&&!w&&S.setViewport(Math.floor(_.x*m),Math.floor(_.y*m),Math.floor(_.width*m),Math.floor(_.height*m),i.viewportValue.minDepth,i.viewportValue.maxDepth),f&&h.indexesGPU){let T=u.indexOf(f);S.setBindGroup(T,h.indexesGPU[y]),M.bindingGroups[T]=f.id}this._draw(e,t,a,l,u,d,c,S,M)}}}else if(a.currentPass){if(a.occlusionQuerySet!==void 0){let h=a.lastOcclusionObject;h!==n&&(h!==null&&h.occlusionTest===!0&&(a.currentPass.endOcclusionQuery(),a.occlusionQueryIndex++),n.occlusionTest===!0&&(a.currentPass.beginOcclusionQuery(a.occlusionQueryIndex),a.occlusionQueryObjects[a.occlusionQueryIndex]=n),a.lastOcclusionObject=n)}this._draw(e,t,a,l,u,d,c,a.currentPass,a.currentSets)}}needsRenderUpdate(e){let t=this.get(e),{object:n,material:i}=e,s=this.utils,a=s.getSampleCountRenderContext(e.context),o=s.getCurrentColorSpace(e.context),l=s.getCurrentColorFormat(e.context),c=s.getCurrentDepthStencilFormat(e.context),u=s.getPrimitiveTopology(n,i),d=n.isMesh&&n.matrixWorld.determinantAffine()<0,h=!1;return(t.material!==i||t.materialVersion!==i.version||t.transparent!==i.transparent||t.blending!==i.blending||t.premultipliedAlpha!==i.premultipliedAlpha||t.blendSrc!==i.blendSrc||t.blendDst!==i.blendDst||t.blendEquation!==i.blendEquation||t.blendSrcAlpha!==i.blendSrcAlpha||t.blendDstAlpha!==i.blendDstAlpha||t.blendEquationAlpha!==i.blendEquationAlpha||t.colorWrite!==i.colorWrite||t.depthWrite!==i.depthWrite||t.depthTest!==i.depthTest||t.depthFunc!==i.depthFunc||t.stencilWrite!==i.stencilWrite||t.stencilFunc!==i.stencilFunc||t.stencilFail!==i.stencilFail||t.stencilZFail!==i.stencilZFail||t.stencilZPass!==i.stencilZPass||t.stencilFuncMask!==i.stencilFuncMask||t.stencilWriteMask!==i.stencilWriteMask||t.side!==i.side||t.alphaToCoverage!==i.alphaToCoverage||t.sampleCount!==a||t.colorSpace!==o||t.colorFormat!==l||t.depthStencilFormat!==c||t.primitiveTopology!==u||t.frontFaceCW!==d||t.clippingContextCacheKey!==e.clippingContextCacheKey)&&(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=a,t.colorSpace=o,t.colorFormat=l,t.depthStencilFormat=c,t.primitiveTopology=u,t.frontFaceCW=d,t.clippingContextCacheKey=e.clippingContextCacheKey,h=!0),h}getRenderCacheKey(e){let{object:t,material:n}=e,i=this.utils,s=e.context,a=t.isMesh&&t.matrixWorld.determinantAffine()<0;return[n.transparent,n.blending,n.premultipliedAlpha,n.blendSrc,n.blendDst,n.blendEquation,n.blendSrcAlpha,n.blendDstAlpha,n.blendEquationAlpha,n.colorWrite,n.depthWrite,n.depthTest,n.depthFunc,n.stencilWrite,n.stencilFunc,n.stencilFail,n.stencilZFail,n.stencilZPass,n.stencilFuncMask,n.stencilWriteMask,n.side,a,i.getSampleCountRenderContext(s),i.getCurrentColorSpace(s),i.getCurrentColorFormat(s),i.getCurrentDepthStencilFormat(s),i.getPrimitiveTopology(t,n),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,s,a){return this.textureUtils.copyTextureToBuffer(e,t,n,i,s,a)}initTimestampQuery(e,t,n){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new Dv(this.device,e,2048));let i=this.timestampQueryPool[e],s=i.allocateQueriesForContext(t);Yf.querySet=i.querySet,Yf.beginningOfPassWriteIndex=s,Yf.endOfPassWriteIndex=s+1,n.timestampWrites=Yf}createNodeBuilder(e,t){return new Mv(e,t)}createProgram(e){let t=this.get(e);Xf.label=e.stage+(e.name!==""?`_${e.name}`:""),Xf.code=e.code,t.module={module:this.device.createShaderModule(Xf),entryPoint:"main"},Xf.reset()}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){let t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){let n=this.get(e),s=n.currentPass.finish();this.get(t).bundleGPU=s,n.currentSets=n._currentSets,n.currentPass=n._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createUniformBuffer(e){let t=this.get(e);if(t.buffer===void 0){let n=e.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,s=[];e.visibility&lr.VERTEX&&s.push("vertex"),e.visibility&lr.FRAGMENT&&s.push("fragment"),e.visibility&lr.COMPUTE&&s.push("compute");let a=`(${s.join(",")})`;Pi.label=`bindingBuffer${e.id}_${e.name}_${a}`,Pi.size=n,Pi.usage=i;let o=this.device.createBuffer(Pi);Pi.reset(),t.buffer=o}}destroyUniformBuffer(e){this.get(e).buffer.destroy(),this.delete(e)}createBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}hasFeature(e){return GM[e]!==void 0&&(e=GM[e]),this.device.features.has(e)}copyTextureToTexture(e,t,n=null,i=null,s=0,a=0){let o=0,l=0,c=0,u=0,d=0,h=0,p=e.image.width,f=e.image.height,m=1;n!==null&&(n.isBox3===!0?(u=n.min.x,d=n.min.y,h=n.min.z,p=n.max.x-n.min.x,f=n.max.y-n.min.y,m=n.max.z-n.min.z):(u=n.min.x,d=n.min.y,p=n.max.x-n.min.x,f=n.max.y-n.min.y,m=1)),i!==null&&(o=i.x,l=i.y,c=i.z||0),Yn.label="copyTextureToTexture_"+e.id+"_"+t.id;let y=this.device.createCommandEncoder(Yn);Yn.reset();let x=this.get(e).texture,b=this.get(t).texture;es.texture=x,es.mipLevel=s,es.origin.x=u,es.origin.y=d,es.origin.z=h,Qs.texture=b,Qs.mipLevel=a,Qs.origin.x=o,Qs.origin.y=l,Qs.origin.z=c,Or.width=p,Or.height=f,Or.depthOrArrayLayers=m,y.copyTextureToTexture(es,Qs,Or),es.reset(),Qs.reset(),Or.reset(),nr(this.device,y.finish()),a===0&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){let i=this.get(t),s=null;t.renderTarget?e.isDepthTexture?s=this.get(t.depthTexture).texture:s=this.get(t.textures[0]).texture:e.isDepthTexture?s=this.textureUtils.getDepthBuffer(t.depth,t.stencil):s=this.context.getCurrentTexture();let a=this.get(e).texture;if(s.format!==a.format){G("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",s.format,a.format);return}let o;if(i.currentPass?(i.currentPass.end(),o=i.encoder):(Yn.label="copyFramebufferToTexture_"+e.id,o=this.device.createCommandEncoder(Yn),Yn.reset()),es.texture=s,es.origin.x=n.x,es.origin.y=n.y,Qs.texture=a,Or.width=n.z,Or.height=n.w,o.copyTextureToTexture(es,Qs,Or),es.reset(),Qs.reset(),Or.reset(),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,o),i.currentPass){let{descriptor:l}=i;for(let c=0;c<l.colorAttachments.length;c++)l.colorAttachments[c].loadOp=qe.Load;t.depth&&(l.depthStencilAttachment.depthLoadOp=qe.Load),t.stencil&&(l.depthStencilAttachment.stencilLoadOp=qe.Load),i.currentPass=o.beginRenderPass(l),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else nr(this.device,o.finish())}hasCompatibility(e){return this._compatibility[e]!==void 0?this._compatibility[e]:super.hasCompatibility(e)}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(let e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(let e of Object.values(this.timestampQueryPool))e!==null&&e.dispose();this.parameters.device===void 0&&this.device!==null&&this.device.destroy()}},Bv=class extends Eo{constructor(e,t,n,i,s,a){super(e,t,n,i,s,a),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}},Uv=class extends Eo{constructor(e,t,n,i,s,a){super(e,t,n,i,s,a),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}},Ov=class extends Ym{constructor(){super(),this.addMaterial(o_,"MeshPhongMaterial"),this.addMaterial(vu,"MeshStandardMaterial"),this.addMaterial(Vh,"MeshPhysicalMaterial"),this.addMaterial(g_,"MeshToonMaterial"),this.addMaterial(Uh,"MeshBasicMaterial"),this.addMaterial(a_,"MeshLambertMaterial"),this.addMaterial(n_,"MeshNormalMaterial"),this.addMaterial(y_,"MeshMatcapMaterial"),this.addMaterial(Qx,"LineBasicMaterial"),this.addMaterial(e_,"LineDashedMaterial"),this.addMaterial(__,"PointsMaterial"),this.addMaterial(Rm,"SpriteMaterial"),this.addMaterial(v_,"ShadowMaterial"),this.addLight(hb,Ro),this.addLight(Bb,Sa),this.addLight(Gb,Ad),this.addLight(Xh,Eo),this.addLight(Lb,Rd),this.addLight(Ub,va),this.addLight(kb,Nd),this.addLight(Ob,Bv),this.addLight(Vb,Uv),this.addToneMapping(MA,Bd),this.addToneMapping(wA,Ud),this.addToneMapping(EA,Od),this.addToneMapping(RA,Aa),this.addToneMapping(AA,kd),this.addToneMapping(CA,Vd)}},pg=class extends Kb{constructor(e={}){let t;e.forceWebGL?t=sg:(t=Lv,e.getFallback=()=>(X("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new sg(e)));let n=new t(e);super(n,e),this.library=new Ov,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}};var fg=class{constructor(e,t=J(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;let n=new We;n.name="RenderPipeline",this._quadMesh=new Is(n),this._quadMesh.name="Render Pipeline",this._context=null,this._toneMapping=e.toneMapping,this._outputColorSpace=e.outputColorSpace}render(){let e=this.renderer;this._update(),this._context.onBeforeRenderPipeline!==null&&this._context.onBeforeRenderPipeline();let t=e.toneMapping,n=e.outputColorSpace;e.toneMapping=Ki,e.outputColorSpace=Fe.workingColorSpace;let i=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=i,e.toneMapping=t,e.outputColorSpace=n,this._context.onAfterRenderPipeline!==null&&this._context.onAfterRenderPipeline()}get context(){return this._context}dispose(){this._quadMesh.material.dispose()}_update(){if(this._toneMapping!==this.renderer.toneMapping&&(this._toneMapping=this.renderer.toneMapping,this.needsUpdate=!0),this._outputColorSpace!==this.renderer.outputColorSpace&&(this._outputColorSpace=this.renderer.outputColorSpace,this.needsUpdate=!0),this.needsUpdate===!0){let e=this._toneMapping,t=this._outputColorSpace,n={renderPipeline:this,onBeforeRenderPipeline:null,onAfterRenderPipeline:null},i=this.outputNode;this.outputColorTransform===!0?(i=i.context(n),i=Pg(i,e,t)):(n.toneMapping=e,n.outputColorSpace=t,i=i.context(n)),this._context=n,this._quadMesh.material.fragmentNode=i,this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){Ce('RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.renderer.init(),this.render()}};var fz=g.BRDF_GGX,mz=g.BRDF_Lambert,gz=g.BasicPointShadowFilter,yz=g.BasicShadowFilter,xz=g.Break,_z=g.Const,bz=g.Continue,vz=g.DFGLUT,Sz=g.D_GGX,Tz=g.Discard,Mz=g.EPSILON,wz=g.F_Schlick,us=g.Fn,Ez=g.INFINITY,Rz=g.If,hC=g.Loop,Az=g.NodeAccess,Cz=g.NodeShaderStage,Nz=g.NodeType,Pz=g.NodeUpdateType,Dz=g.PCFShadowFilter,Iz=g.PCFSoftShadowFilter,Fz=g.PI,Lz=g.PI2,Bz=g.TWO_PI,Uz=g.HALF_PI,Oz=g.PointShadowFilter,kz=g.Return,Vz=g.Schlick_to_F0,Gz=g.ShaderNode,zz=g.Stack,Hz=g.Switch,Wz=g.TBNViewMatrix,qz=g.VSMShadowFilter,$z=g.V_GGX_SmithCorrelated,Xz=g.Var,Yz=g.VarIntent,pC=g.abs,jz=g.acesFilmicToneMapping,Kz=g.acos,Zz=g.acosh,fC=g.add,Jz=g.addMethodChaining,Qz=g.addNodeElement,e8=g.agxToneMapping,t8=g.all,n8=g.alphaT,i8=g.ambientOcclusion,s8=g.and,r8=g.anisotropy,a8=g.anisotropyB,o8=g.anisotropyT,l8=g.any,c8=g.append,u8=g.array,d8=g.asin,h8=g.asinh,p8=g.assign,f8=g.atan,m8=g.atanh,g8=g.atomicAdd,y8=g.atomicAnd,x8=g.atomicFunc,_8=g.atomicLoad,b8=g.atomicMax,v8=g.atomicMin,S8=g.atomicOr,T8=g.atomicStore,M8=g.atomicSub,w8=g.atomicXor,E8=g.attenuationColor,R8=g.attenuationDistance,A8=g.attribute,C8=g.attributeArray,N8=g.backgroundBlurriness,P8=g.backgroundIntensity,D8=g.backgroundRotation,I8=g.batch,F8=g.bentNormalView,L8=g.billboarding,B8=g.bitAnd,U8=g.bitNot,O8=g.bitOr,k8=g.bitXor,V8=g.bitangentGeometry,G8=g.bitangentLocal,z8=g.bitangentView,H8=g.bitangentWorld,W8=g.bitcast,q8=g.blendBurn,$8=g.blendColor,X8=g.blendDodge,Y8=g.blendOverlay,j8=g.blendScreen,K8=g.blur,Z8=g.bool,J8=g.buffer,Q8=g.bufferAttribute,e6=g.bumpMap,t6=g.builtin,n6=g.builtinAOContext,i6=g.builtinShadowContext,s6=g.bvec2,r6=g.bvec3,a6=g.bvec4,o6=g.bypass,l6=g.cache,c6=g.call,u6=g.cameraFar,d6=g.cameraIndex,h6=g.cameraNear,p6=g.cameraNormalMatrix,f6=g.cameraPosition,m6=g.cameraProjectionMatrix,g6=g.cameraProjectionMatrixInverse,y6=g.cameraViewMatrix,x6=g.cameraViewport,_6=g.cameraWorldMatrix,b6=g.cbrt,v6=g.cdl,S6=g.ceil,T6=g.checker,M6=g.cineonToneMapping,$g=g.clamp,w6=g.clearcoat,E6=g.clearcoatNormalView,R6=g.clearcoatRoughness,A6=g.clipSpace,C6=g.code,rp=g.color,N6=g.colorSpaceToWorking,P6=g.colorToDirection,D6=g.compute,I6=g.computeKernel,F6=g.computeSkinning,L6=g.context,B6=g.convert,U6=g.convertColorSpace,O6=g.convertToTexture,k6=g.countLeadingZeros,V6=g.countOneBits,G6=g.countTrailingZeros,z6=g.cos,H6=g.cosh,W6=g.cross,q6=g.cubeTexture,$6=g.cubeTextureBase,X6=g.dFdx,Y6=g.dFdy,j6=g.dashSize,K6=g.debug,Z6=g.decrement,J6=g.decrementBefore,Q6=g.defaultBuildStages,eH=g.defaultShaderStages,tH=g.defined,nH=g.degrees,iH=g.deltaTime,sH=g.densityFog,rH=g.densityFogFactor,aH=g.depth,oH=g.depthPass,lH=g.determinant,cH=g.difference,uH=g.diffuseColor,dH=g.directPointLight,hH=g.directionToColor,pH=g.directionToFaceDirection,fH=g.dispersion,mH=g.distance,gH=g.div,ap=g.dot,yH=g.drawIndex,xH=g.dynamicBufferAttribute,_H=g.element,bH=g.emissive,vH=g.equal,SH=g.equirectDirection,TH=g.equirectUV,op=g.exp,MH=g.exp2,wH=g.exponentialHeightFogFactor,EH=g.expression,RH=g.faceDirection,AH=g.faceForward,CH=g.faceforward,et=g.float,NH=g.floatBitsToInt,PH=g.floatBitsToUint,mC=g.floor,DH=g.fog,Xg=g.fract,IH=g.frameGroup,FH=g.frameId,LH=g.frontFacing,BH=g.fwidth,UH=g.gain,OH=g.gapSize,kH=g.getConstNodeType,VH=g.getCurrentStack,GH=g.getDirection,zH=g.getDistanceAttenuation,HH=g.getGeometryRoughness,WH=g.getNormalFromDepth,qH=g.interleavedGradientNoise,$H=g.vogelDiskSample,XH=g.getParallaxCorrectNormal,YH=g.getRoughness,jH=g.getScreenPosition,KH=g.getShIrradianceAt,ZH=g.getShadowMaterial,JH=g.getShadowRenderObjectFunction,QH=g.getTextureIndex,e9=g.getViewPosition,t9=g.globalId,n9=g.glsl,i9=g.glslFn,s9=g.grayscale,r9=g.greaterThan,a9=g.greaterThanEqual,o9=g.hash,l9=g.highpModelNormalViewMatrix,c9=g.highpModelViewMatrix,u9=g.hue,d9=g.increment,h9=g.incrementBefore,p9=g.instance,f9=g.instanceIndex,m9=g.instancedArray,g9=g.instancedBufferAttribute,y9=g.instancedDynamicBufferAttribute,x9=g.instancedMesh,gT=g.int,_9=g.intBitsToFloat,b9=g.inverse,v9=g.inverseSqrt,S9=g.inversesqrt,T9=g.invocationLocalIndex,M9=g.invocationSubgroupIndex,w9=g.ior,E9=g.iridescence,R9=g.iridescenceIOR,A9=g.iridescenceThickness,C9=g.ivec2,N9=g.ivec3,P9=g.ivec4,D9=g.js,I9=g.label,F9=g.length,L9=g.lengthSq,B9=g.lessThan,U9=g.lessThanEqual,O9=g.lightPosition,k9=g.lightProjectionUV,V9=g.lightShadowMatrix,G9=g.lightTargetDirection,z9=g.lightTargetPosition,H9=g.lightViewPosition,W9=g.lightingContext,q9=g.lights,$9=g.linearDepth,X9=g.linearToneMapping,Y9=g.localId,j9=g.log,K9=g.log2,Z9=g.logarithmicDepthToViewZ,gC=g.luminance,J9=g.mat2,Q9=g.mat3,eW=g.mat4,tW=g.matcapUV,nW=g.materialAO,iW=g.materialAlphaTest,sW=g.materialAnisotropy,rW=g.materialAnisotropyVector,aW=g.materialAttenuationColor,oW=g.materialAttenuationDistance,lW=g.materialClearcoat,cW=g.materialClearcoatNormal,uW=g.materialClearcoatRoughness,dW=g.materialColor,hW=g.materialDispersion,pW=g.materialEmissive,fW=g.materialEnvIntensity,mW=g.materialEnvRotation,gW=g.materialIOR,yW=g.materialIridescence,xW=g.materialIridescenceIOR,_W=g.materialIridescenceThickness,bW=g.materialLightMap,vW=g.materialLineDashOffset,SW=g.materialLineDashSize,TW=g.materialLineGapSize,MW=g.materialLineScale,wW=g.materialLineWidth,EW=g.materialMetalness,RW=g.materialNormal,AW=g.materialOpacity,CW=g.materialPointSize,NW=g.materialReference,PW=g.materialReflectivity,DW=g.materialRefractionRatio,IW=g.materialRotation,FW=g.materialRoughness,LW=g.materialSheen,BW=g.materialSheenRoughness,UW=g.materialShininess,OW=g.materialSpecular,kW=g.materialSpecularColor,VW=g.materialSpecularIntensity,GW=g.materialSpecularStrength,zW=g.materialThickness,HW=g.materialTransmission,lp=g.max,WW=g.maxMipLevel,qW=g.mediumpModelViewMatrix,$W=g.metalness,XW=g.min,zn=g.mix,YW=g.mixElement,jW=g.mod,KW=g.modelDirection,ZW=g.modelNormalMatrix,JW=g.modelPosition,QW=g.modelRadius,e7=g.modelScale,t7=g.modelViewMatrix,n7=g.modelViewPosition,i7=g.modelViewProjection,s7=g.modelWorldMatrix,r7=g.modelWorldMatrixInverse,a7=g.morphReference,o7=g.mrt,l7=g.mul,c7=g.mx_aastep,u7=g.mx_add,d7=g.mx_atan2,h7=g.mx_cell_noise_float,p7=g.mx_contrast,f7=g.mx_divide,Yg=g.mx_fractal_noise_float,m7=g.mx_fractal_noise_vec2,g7=g.mx_fractal_noise_vec3,y7=g.mx_fractal_noise_vec4,x7=g.mx_frame,_7=g.mx_heighttonormal,b7=g.mx_hsvtorgb,v7=g.mx_ifequal,S7=g.mx_ifgreater,T7=g.mx_ifgreatereq,M7=g.mx_invert,w7=g.mx_modulo,E7=g.mx_multiply,ds=g.mx_noise_float,R7=g.mx_noise_vec3,A7=g.mx_noise_vec4,C7=g.mx_place2d,N7=g.mx_power,P7=g.mx_ramp4,D7=g.mx_ramplr,I7=g.mx_ramptb,F7=g.mx_rgbtohsv,L7=g.mx_rotate2d,B7=g.mx_rotate3d,U7=g.mx_safepower,O7=g.mx_separate,k7=g.mx_splitlr,V7=g.mx_splittb,G7=g.mx_srgb_texture_to_lin_rec709,z7=g.mx_subtract,H7=g.mx_timer,W7=g.mx_transform_uv,q7=g.mx_unifiednoise2d,$7=g.mx_unifiednoise3d,X7=g.mx_worley_noise_float,Y7=g.mx_worley_noise_vec2,j7=g.mx_worley_noise_vec3,K7=g.negate,Z7=g.negateOnBackSide,J7=g.neutralToneMapping,Q7=g.nodeArray,eq=g.nodeImmutable,yC=g.nodeObject,tq=g.nodeObjectIntent,nq=g.nodeObjects,iq=g.nodeProxy,sq=g.nodeProxyIntent,rq=g.normalFlat,aq=g.normalGeometry,oq=g.normalLocal,lq=g.normalMap,xC=g.normalView,cq=g.normalViewGeometry,uq=g.normalWorld,dq=g.normalWorldGeometry,hq=g.normalize,pq=g.not,fq=g.notEqual,mq=g.numWorkgroups,gq=g.objectDirection,yq=g.objectGroup,xq=g.objectPosition,_q=g.objectRadius,bq=g.objectScale,vq=g.objectViewPosition,Sq=g.objectWorldMatrix,Tq=g.OnBeforeObjectUpdate,Mq=g.OnBeforeMaterialUpdate,wq=g.OnObjectUpdate,Eq=g.OnMaterialUpdate,Rq=g.oneMinus,Aq=g.or,Cq=g.orthographicDepthToViewZ,Nq=g.oscSawtooth,Pq=g.oscSine,Dq=g.oscSquare,Iq=g.oscTriangle,Fq=g.output,Lq=g.outputStruct,Bq=g.overloadingFn,Uq=g.overrideNode,Oq=g.overrideNodes,kq=g.packHalf2x16,Vq=g.packSnorm2x16,Gq=g.packUnorm2x16,zq=g.packNormalToRGB,Hq=g.parabola,Wq=g.parallaxDirection,qq=g.parallaxUV,$q=g.parameter,_C=g.pass,bC=g.passTexture,Xq=g.pcurve,Yq=g.perspectiveDepthToViewZ,jq=g.pmremTexture,Kq=g.pointShadow,Zq=g.pointUV,Jq=g.pointWidth,Qq=g.positionGeometry,vC=g.positionLocal,e$=g.positionPrevious,t$=g.positionView,SC=g.positionViewDirection,n$=g.positionWorld,i$=g.positionWorldDirection,s$=g.posterize,r$=g.pow,a$=g.pow2,o$=g.pow3,l$=g.pow4,c$=g.premultiplyAlpha,u$=g.property,d$=g.radians,h$=g.rand,p$=g.range,f$=g.rangeFog,m$=g.rangeFogFactor,g$=g.reciprocal,y$=g.reference,x$=g.referenceBuffer,_$=g.reflect,b$=g.reflectVector,v$=g.reflectView,S$=g.reflector,T$=g.refract,M$=g.refractVector,w$=g.refractView,E$=g.reinhardToneMapping,R$=g.remap,A$=g.remapClamp,C$=g.renderGroup,TC=g.renderOutput,N$=g.rendererReference,P$=g.replaceDefaultUV,D$=g.rotate,I$=g.rotateUV,F$=g.roughness,L$=g.round,B$=g.rtt,U$=g.sRGBTransferEOTF,O$=g.sRGBTransferOETF,k$=g.sample,V$=g.sampler,G$=g.samplerComparison,z$=g.saturate,H$=g.saturation,W$=g.screen,q$=g.screenCoordinate,$$=g.screenDPR,X$=g.screenSize,jg=g.screenUV,Y$=g.select,j$=g.setCurrentStack,K$=g.setName,Z$=g.shaderStages,J$=g.shadow,Q$=g.shadowPositionWorld,eX=g.shapeCircle,tX=g.sharedUniformGroup,nX=g.sheen,iX=g.sheenRoughness,sX=g.shiftLeft,rX=g.shiftRight,aX=g.shininess,oX=g.sign,Kg=g.sin,lX=g.sinh,cX=g.sinc,uX=g.skinning,Xt=g.smoothstep,dX=g.smoothstepElement,hX=g.specularColor,pX=g.specularF90,fX=g.spherizeUV,mX=g.split,gX=g.spritesheetUV,yX=g.sqrt,xX=g.stack,_l=g.step,_X=g.stepElement,bX=g.storage,vX=g.storageBarrier,SX=g.storageTexture,TX=g.storageTexture3D,MX=g.struct,wX=g.sub,EX=g.subgroupAdd,RX=g.subgroupAll,AX=g.subgroupAnd,CX=g.subgroupAny,NX=g.subgroupBallot,PX=g.subgroupBroadcast,DX=g.subgroupBroadcastFirst,IX=g.subBuild,FX=g.subgroupElect,LX=g.subgroupExclusiveAdd,BX=g.subgroupExclusiveMul,UX=g.subgroupInclusiveAdd,OX=g.subgroupInclusiveMul,kX=g.subgroupIndex,VX=g.subgroupMax,GX=g.subgroupMin,zX=g.subgroupMul,HX=g.subgroupOr,WX=g.subgroupShuffle,qX=g.subgroupShuffleDown,$X=g.subgroupShuffleUp,XX=g.subgroupShuffleXor,YX=g.subgroupSize,jX=g.subgroupXor,KX=g.tan,ZX=g.tanh,JX=g.tangentGeometry,QX=g.tangentLocal,eY=g.tangentView,tY=g.tangentWorld,ki=g.texture,nY=g.texture3D,iY=g.textureBarrier,sY=g.textureBicubic,rY=g.textureBicubicLevel,aY=g.textureCubeUV,oY=g.textureLoad,lY=g.textureSize,cY=g.textureLevel,uY=g.textureStore,dY=g.thickness,hY=g.time,pY=g.toneMapping,fY=g.toneMappingExposure,mY=g.toonOutlinePass,gY=g.transformDirection,yY=g.transformNormal,xY=g.transformNormalByInverseViewMatrix,_Y=g.transformNormalByViewMatrix,bY=g.transformNormalToView,vY=g.transformedClearcoatNormalView,SY=g.transformedNormalView,TY=g.transformedNormalWorld,MY=g.transmission,wY=g.transpose,EY=g.triNoise3D,RY=g.triplanarTexture,AY=g.triplanarTextures,CY=g.trunc,NY=g.uint,PY=g.uintBitsToFloat,pt=g.uniform,Zg=g.uniformArray,DY=g.uniformCubeTexture,IY=g.uniformGroup,FY=g.uniformFlow,LY=g.uniformTexture,BY=g.unpackHalf2x16,UY=g.unpackSnorm2x16,OY=g.unpackUnorm2x16,kY=g.unpackRGBToNormal,VY=g.unpremultiplyAlpha,GY=g.userData,sn=g.uv,zY=g.uvec2,HY=g.uvec3,WY=g.uvec4,qY=g.varying,$Y=g.varyingProperty,Ct=g.vec2,Ft=g.vec3,Vi=g.vec4,XY=g.vectorComponents,YY=g.velocity,jY=g.vertexColor,KY=g.vertexIndex,ZY=g.vertexStage,JY=g.vibrance,QY=g.viewZToLogarithmicDepth,ej=g.viewZToOrthographicDepth,tj=g.viewZToPerspectiveDepth,nj=g.viewZToReversedOrthographicDepth,ij=g.viewZToReversedPerspectiveDepth,sj=g.viewport,rj=g.viewportCoordinate,aj=g.viewportDepthTexture,oj=g.viewportLinearDepth,lj=g.viewportMipTexture,cj=g.viewportOpaqueMipTexture,uj=g.viewportResolution,dj=g.viewportSafeUV,hj=g.viewportSharedTexture,pj=g.viewportSize,fj=g.viewportTexture,mj=g.viewportUV,gj=g.wgsl,yj=g.wgslFn,xj=g.workgroupArray,_j=g.workgroupBarrier,bj=g.workgroupId,vj=g.workingToColorSpace,Sj=g.xor;var fV=`#ifdef USE_ALPHAHASH
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,mV=`#ifdef USE_ALPHAHASH
const float ALPHA_HASH_SCALE = 0.05;
float hash2D( vec2 value ) {
return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
}
float hash3D( vec3 value ) {
return hash2D( vec2( hash2D( value.xy ), value.z ) );
}
float getAlphaHashThreshold( vec3 position ) {
float maxDeriv = max(
length( dFdx( position.xyz ) ),
length( dFdy( position.xyz ) )
);
float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
vec2 pixScales = vec2(
exp2( floor( log2( pixScale ) ) ),
exp2( ceil( log2( pixScale ) ) )
);
vec2 alpha = vec2(
hash3D( floor( pixScales.x * position.xyz ) ),
hash3D( floor( pixScales.y * position.xyz ) )
);
float lerpFactor = fract( log2( pixScale ) );
float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
float a = min( lerpFactor, 1.0 - lerpFactor );
vec3 cases = vec3(
x * x / ( 2.0 * a * ( 1.0 - a ) ),
( x - 0.5 * a ) / ( 1.0 - a ),
1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
);
float threshold = ( x < ( 1.0 - a ) )
? ( ( x < a ) ? cases.x : cases.y )
: cases.z;
return clamp( threshold , 1.0e-6, 1.0 );
}
#endif`,gV=`#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,yV=`#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
#endif`,xV=`#ifdef USE_ALPHATEST
#ifdef ALPHA_TO_COVERAGE
diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
if ( diffuseColor.a == 0.0 ) discard;
#else
if ( diffuseColor.a < alphaTest ) discard;
#endif
#endif`,_V=`#ifdef USE_ALPHATEST
uniform float alphaTest;
#endif`,bV=`#ifdef USE_AOMAP
float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
reflectedLight.indirectDiffuse *= ambientOcclusion;
#if defined( USE_CLEARCOAT )
clearcoatSpecularIndirect *= ambientOcclusion;
#endif
#if defined( USE_SHEEN )
sheenSpecularIndirect *= ambientOcclusion;
#endif
#if defined( USE_ENVMAP ) && defined( STANDARD )
float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
#endif
#endif`,vV=`#ifdef USE_AOMAP
uniform sampler2D aoMap;
uniform float aoMapIntensity;
#endif`,SV=`#ifdef USE_BATCHING
#if ! defined( GL_ANGLE_multi_draw )
#define gl_DrawID _gl_DrawID
uniform int _gl_DrawID;
#endif
uniform highp sampler2D batchingTexture;
uniform highp usampler2D batchingIdTexture;
mat4 getBatchingMatrix( const in float i ) {
int size = textureSize( batchingTexture, 0 ).x;
int j = int( i ) * 4;
int x = j % size;
int y = j / size;
vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
return mat4( v1, v2, v3, v4 );
}
float getIndirectIndex( const in int i ) {
int size = textureSize( batchingIdTexture, 0 ).x;
int x = i % size;
int y = i / size;
return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
}
#endif
#ifdef USE_BATCHING_COLOR
uniform sampler2D batchingColorTexture;
vec4 getBatchingColor( const in float i ) {
int size = textureSize( batchingColorTexture, 0 ).x;
int j = int( i );
int x = j % size;
int y = j / size;
return texelFetch( batchingColorTexture, ivec2( x, y ), 0 );
}
#endif`,TV=`#ifdef USE_BATCHING
mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,MV=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
vPosition = vec3( position );
#endif`,wV=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
vec3 objectTangent = vec3( tangent.xyz );
#endif`,EV=`float G_BlinnPhong_Implicit( ) {
return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
vec3 halfDir = normalize( lightDir + viewDir );
float dotNH = saturate( dot( normal, halfDir ) );
float dotVH = saturate( dot( viewDir, halfDir ) );
vec3 F = F_Schlick( specularColor, 1.0, dotVH );
float G = G_BlinnPhong_Implicit( );
float D = D_BlinnPhong( shininess, dotNH );
return F * ( G * D );
} // validated`,RV=`#ifdef USE_IRIDESCENCE
const mat3 XYZ_TO_REC709 = mat3(
3.2404542, -0.9692660, 0.0556434,
-1.5371385, 1.8760108, -0.2040259,
-0.4985314, 0.0415560, 1.0572252
);
vec3 Fresnel0ToIor( vec3 fresnel0 ) {
vec3 sqrtF0 = sqrt( fresnel0 );
return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
}
vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
}
float IorToFresnel0( float transmittedIor, float incidentIor ) {
return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
}
vec3 evalSensitivity( float OPD, vec3 shift ) {
float phase = 2.0 * PI * OPD * 1.0e-9;
vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
xyz /= 1.0685e-7;
vec3 rgb = XYZ_TO_REC709 * xyz;
return rgb;
}
vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
vec3 I;
float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
float cosTheta2Sq = 1.0 - sinTheta2Sq;
if ( cosTheta2Sq < 0.0 ) {
return vec3( 1.0 );
}
float cosTheta2 = sqrt( cosTheta2Sq );
float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
float R12 = F_Schlick( R0, 1.0, cosTheta1 );
float T121 = 1.0 - R12;
float phi12 = 0.0;
if ( iridescenceIOR < outsideIOR ) phi12 = PI;
float phi21 = PI - phi12;
vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
vec3 phi23 = vec3( 0.0 );
if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
vec3 phi = vec3( phi21 ) + phi23;
vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
vec3 r123 = sqrt( R123 );
vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
vec3 C0 = R12 + Rs;
I = C0;
vec3 Cm = Rs - T121;
for ( int m = 1; m <= 2; ++ m ) {
Cm *= r123;
vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
I += Cm * Sm;
}
return max( I, vec3( 0.0 ) );
}
#endif`,AV=`#ifdef USE_BUMPMAP
uniform sampler2D bumpMap;
uniform float bumpScale;
vec2 dHdxy_fwd() {
vec2 dSTdx = dFdx( vBumpMapUv );
vec2 dSTdy = dFdy( vBumpMapUv );
float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
return vec2( dBx, dBy );
}
vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
vec3 vN = surf_norm;
vec3 R1 = cross( vSigmaY, vN );
vec3 R2 = cross( vN, vSigmaX );
float fDet = dot( vSigmaX, R1 ) * faceDirection;
vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
return normalize( abs( fDet ) * surf_norm - vGrad );
}
#endif`,CV=`#if NUM_CLIPPING_PLANES > 0
vec4 plane;
#ifdef ALPHA_TO_COVERAGE
float distanceToPlane, distanceGradient;
float clipOpacity = 1.0;
#pragma unroll_loop_start
for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
distanceGradient = fwidth( distanceToPlane ) / 2.0;
clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
if ( clipOpacity == 0.0 ) discard;
}
#pragma unroll_loop_end
#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
float unionClipOpacity = 1.0;
#pragma unroll_loop_start
for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
distanceGradient = fwidth( distanceToPlane ) / 2.0;
unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
}
#pragma unroll_loop_end
clipOpacity *= 1.0 - unionClipOpacity;
#endif
diffuseColor.a *= clipOpacity;
if ( diffuseColor.a == 0.0 ) discard;
#else
#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
#endif`,NV=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,PV=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
#endif`,DV=`#if NUM_CLIPPING_PLANES > 0
vClipPosition = - mvPosition.xyz;
#endif`,IV=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
diffuseColor *= vColor;
#endif`,FV=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#endif`,LV=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
varying vec4 vColor;
#endif`,BV=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
vColor = vec4( 1.0 );
#endif
#ifdef USE_COLOR_ALPHA
vColor *= color;
#elif defined( USE_COLOR )
vColor.rgb *= color;
#endif
#ifdef USE_INSTANCING_COLOR
vColor.rgb *= instanceColor.rgb;
#endif
#ifdef USE_BATCHING_COLOR
vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );
#endif`,UV=`#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 );
}
#define inverseTransformDirection transformDirectionByInverseViewMatrix
vec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) {
return normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz );
}
vec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) {
return normalize( ( vec4( dir, 0.0 ) * viewMatrix ).xyz );
}
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`,OV=`#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`,kV=`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;
#endif`,VV=`#ifdef USE_DISPLACEMENTMAP
uniform sampler2D displacementMap;
uniform float displacementScale;
uniform float displacementBias;
#endif`,GV=`#ifdef USE_DISPLACEMENTMAP
transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,zV=`#ifdef USE_EMISSIVEMAP
vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
emissiveColor = sRGBTransferEOTF( emissiveColor );
#endif
totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,HV=`#ifdef USE_EMISSIVEMAP
uniform sampler2D emissiveMap;
#endif`,WV="gl_FragColor = linearToOutputTexel( gl_FragColor );",qV=`vec4 LinearTransferOETF( in vec4 value ) {
return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
}
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 );
}`,$V=`#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 = transformNormalByInverseViewMatrix( 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, envMapRotation * reflectVec );
#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
#endif`,XV=`#ifdef USE_ENVMAP
uniform float envMapIntensity;
uniform mat3 envMapRotation;
#ifdef ENVMAP_TYPE_CUBE
uniform samplerCube envMap;
#else
uniform sampler2D envMap;
#endif
#endif`,YV=`#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`,jV=`#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`,KV=`#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 = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );
#ifdef ENVMAP_MODE_REFLECTION
vReflect = reflect( cameraToVertex, worldNormal );
#else
vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
#endif
#endif
#endif`,ZV=`#ifdef USE_FOG
vFogDepth = - mvPosition.z;
#endif`,JV=`#ifdef USE_FOG
varying float vFogDepth;
#endif`,QV=`#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`,eG=`#ifdef USE_FOG
uniform vec3 fogColor;
varying float vFogDepth;
#ifdef FOG_EXP2
uniform float fogDensity;
#else
uniform float fogNear;
uniform float fogFar;
#endif
#endif`,tG=`#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
}`,nG=`#ifdef USE_LIGHTMAP
uniform sampler2D lightMap;
uniform float lightMapIntensity;
#endif`,iG=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,sG=`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`,rG=`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 = transformNormalByInverseViewMatrix( 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 ) {
float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
if ( cutoffDistance > 0.0 ) {
distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
}
return distanceFalloff;
}
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
#include <lightprobes_pars_fragment>`,aG=`#ifdef USE_ENVMAP
vec3 getIBLIrradiance( const in vec3 normal ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );
vec4 envMapColor = textureCubeUV( envMap, envMapRotation * 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, pow4( roughness ) ) );
reflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );
vec4 envMapColor = textureCubeUV( envMap, envMapRotation * 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`,oG=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,lG=`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`,cG=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,uG=`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`,dG=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );
material.metalness = 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 = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;
material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );
#else
material.specularColor = vec3( 0.04 );
material.specularColorBlended = mix( material.specularColor, 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_DISPERSION
material.dispersion = dispersion;
#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.0001, 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`,hG=`uniform sampler2D dfgLUT;
struct PhysicalMaterial {
vec3 diffuseColor;
vec3 diffuseContribution;
vec3 specularColor;
vec3 specularColorBlended;
float roughness;
float metalness;
float specularF90;
float dispersion;
#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;
vec3 iridescenceFresnelDielectric;
vec3 iridescenceFresnelMetallic;
#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 ) );
return 0.5 / max( gv + gl, EPSILON );
}
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.specularColorBlended;
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 * transpose( 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 rInv = 1.0 / ( roughness + 0.1 );
float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;
float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;
float DG = exp( a * dotNV + b );
return saturate( DG );
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
float dotNV = saturate( dot( normal, viewDir ) );
vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;
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
float dotNV = saturate( dot( normal, viewDir ) );
vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;
#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;
}
vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
float dotNL = saturate( dot( normal, lightDir ) );
float dotNV = saturate( dot( normal, viewDir ) );
vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;
vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;
vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;
vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;
float Ess_V = dfgV.x + dfgV.y;
float Ess_L = dfgL.x + dfgL.y;
float Ems_V = 1.0 - Ess_V;
float Ems_L = 1.0 - Ess_L;
vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;
vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );
float compensationFactor = Ems_V * Ems_L;
vec3 multiScatter = Fms * compensationFactor;
return singleScatter + multiScatter;
}
#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.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );
reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
#ifdef USE_CLEARCOAT
vec3 Ncc = geometryClearcoatNormal;
vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );
vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );
vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );
mat3 mInvClearcoat = mat3(
vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
vec3( 0, 1, 0 ),
vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
);
vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;
clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );
#endif
}
#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 );
float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );
float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );
irradiance *= sheenEnergyComp;
#endif
reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );
}
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 ) {
vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );
#ifdef USE_SHEEN
float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;
diffuse *= sheenEnergyComp;
#endif
reflectedLight.indirectDiffuse += diffuse;
}
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 ) * RECIPROCAL_PI;
#endif
vec3 singleScatteringDielectric = vec3( 0.0 );
vec3 multiScatteringDielectric = vec3( 0.0 );
vec3 singleScatteringMetallic = vec3( 0.0 );
vec3 multiScatteringMetallic = vec3( 0.0 );
#ifdef USE_IRIDESCENCE
computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );
#else
computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );
#endif
vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );
vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );
vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;
vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );
vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
vec3 indirectSpecular = radiance * singleScattering;
indirectSpecular += multiScattering * cosineWeightedIrradiance;
vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;
#ifdef USE_SHEEN
float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;
indirectSpecular *= sheenEnergyComp;
indirectDiffuse *= sheenEnergyComp;
#endif
reflectedLight.indirectSpecular += indirectSpecular;
reflectedLight.indirectDiffuse += indirectDiffuse;
}
#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 );
}`,pG=`
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.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );
material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );
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 ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )
pointLightShadow = pointLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, 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.shadowIntensity, 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.shadowIntensity, 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
#ifdef USE_LIGHT_PROBES_GRID
vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;
vec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix );
irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );
#endif
#endif
#if defined( RE_IndirectSpecular )
vec3 radiance = vec3( 0.0 );
vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,fG=`#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( ENVMAP_TYPE_CUBE_UV )
#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )
iblIrradiance += getIBLIrradiance( geometryNormal );
#endif
#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`,mG=`#if defined( RE_IndirectDiffuse )
#if defined( LAMBERT ) || defined( PHONG )
irradiance += iblIrradiance;
#endif
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`,gG=`#ifdef USE_LIGHT_PROBES_GRID
uniform highp sampler3D probesSH;
uniform vec3 probesMin;
uniform vec3 probesMax;
uniform vec3 probesResolution;
vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {
vec3 res = probesResolution;
vec3 gridRange = probesMax - probesMin;
vec3 resMinusOne = res - 1.0;
vec3 probeSpacing = gridRange / resMinusOne;
vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5;
vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 );
uvw = uvw * resMinusOne / res + 0.5 / res;
float nz = res.z;
float paddedSlices = nz + 2.0;
float atlasDepth = 7.0 * paddedSlices;
float uvZBase = uvw.z * nz + 1.0;
vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) );
vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) );
vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) );
vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) );
vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) );
vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) );
vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) );
vec3 c0 = s0.xyz;
vec3 c1 = vec3( s0.w, s1.xy );
vec3 c2 = vec3( s1.zw, s2.x );
vec3 c3 = s2.yzw;
vec3 c4 = s3.xyz;
vec3 c5 = vec3( s3.w, s4.xy );
vec3 c6 = vec3( s4.zw, s5.x );
vec3 c7 = s5.yzw;
vec3 c8 = s6.xyz;
float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z;
vec3 result = c0 * 0.886227;
result += c1 * 2.0 * 0.511664 * y;
result += c2 * 2.0 * 0.511664 * z;
result += c3 * 2.0 * 0.511664 * x;
result += c4 * 2.0 * 0.429043 * x * y;
result += c5 * 2.0 * 0.429043 * y * z;
result += c6 * ( 0.743125 * z * z - 0.247708 );
result += c7 * 2.0 * 0.429043 * x * z;
result += c8 * 0.429043 * ( x * x - y * y );
return max( result, vec3( 0.0 ) );
}
#endif`,yG=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,xG=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
uniform float logDepthBufFC;
varying float vFragDepth;
varying float vIsPerspective;
#endif`,_G=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
varying float vFragDepth;
varying float vIsPerspective;
#endif`,bG=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
vFragDepth = 1.0 + gl_Position.w;
vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,vG=`#ifdef USE_MAP
vec4 sampledDiffuseColor = texture2D( map, vMapUv );
#ifdef DECODE_VIDEO_TEXTURE
sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
#endif
diffuseColor *= sampledDiffuseColor;
#endif`,SG=`#ifdef USE_MAP
uniform sampler2D map;
#endif`,TG=`#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`,MG=`#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`,wG=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
metalnessFactor *= texelMetalness.b;
#endif`,EG=`#ifdef USE_METALNESSMAP
uniform sampler2D metalnessMap;
#endif`,RG=`#ifdef USE_INSTANCING_MORPH
float morphTargetInfluences[ MORPHTARGETS_COUNT ];
float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
}
#endif`,AG=`#if defined( USE_MORPHCOLORS )
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`,CG=`#ifdef USE_MORPHNORMALS
objectNormal *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
}
#endif`,NG=`#ifdef USE_MORPHTARGETS
#ifndef USE_INSTANCING_MORPH
uniform float morphTargetBaseInfluence;
uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
#endif
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 );
}
#endif`,PG=`#ifdef USE_MORPHTARGETS
transformed *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
}
#endif`,DG=`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
#ifdef DOUBLE_SIDED
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
#ifdef DOUBLE_SIDED
tbn2[0] *= faceDirection;
tbn2[1] *= faceDirection;
#endif
#endif
vec3 nonPerturbedNormal = normal;`,IG=`#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;
#if defined( USE_PACKED_NORMALMAP )
mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) );
#endif
mapN.xy *= normalScale;
normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`,FG=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,LG=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,BG=`#ifndef FLAT_SHADED
vNormal = normalize( transformedNormal );
#ifdef USE_TANGENT
vTangent = normalize( transformedTangent );
vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
#ifdef FLIP_SIDED
vBitangent = - vBitangent;
#endif
#endif
#endif`,UG=`#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`,OG=`#ifdef USE_CLEARCOAT
vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,kG=`#ifdef USE_CLEARCOAT_NORMALMAP
vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
clearcoatMapN.xy *= clearcoatNormalScale;
clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,VG=`#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`,GG=`#ifdef USE_IRIDESCENCEMAP
uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
uniform sampler2D iridescenceThicknessMap;
#endif`,zG=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,HG=`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 float ShiftRight8 = 1. / 256.;
const float Inv255 = 1. / 255.;
const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
vec4 packDepthToRGBA( const in float v ) {
if( v <= 0.0 )
return vec4( 0., 0., 0., 0. );
if( v >= 1.0 )
return vec4( 1., 1., 1., 1. );
float vuf;
float af = modf( v * PackFactors.a, vuf );
float bf = modf( vuf * ShiftRight8, vuf );
float gf = modf( vuf * ShiftRight8, vuf );
return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
}
vec3 packDepthToRGB( const in float v ) {
if( v <= 0.0 )
return vec3( 0., 0., 0. );
if( v >= 1.0 )
return vec3( 1., 1., 1. );
float vuf;
float bf = modf( v * PackFactors.b, vuf );
float gf = modf( vuf * ShiftRight8, vuf );
return vec3( vuf * Inv255, gf * PackUpscale, bf );
}
vec2 packDepthToRG( const in float v ) {
if( v <= 0.0 )
return vec2( 0., 0. );
if( v >= 1.0 )
return vec2( 1., 1. );
float vuf;
float gf = modf( v * 256., vuf );
return vec2( vuf * Inv255, gf );
}
float unpackRGBAToDepth( const in vec4 v ) {
return dot( v, UnpackFactors4 );
}
float unpackRGBToDepth( const in vec3 v ) {
return dot( v, UnpackFactors3 );
}
float unpackRGToDepth( const in vec2 v ) {
return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
}
vec4 pack2HalfToRGBA( const in 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( const in 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 ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
return depth * ( far - near ) - far;
#else
return depth * ( near - far ) - near;
#endif
}
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 ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
return ( near * far ) / ( ( near - far ) * depth - near );
#else
return ( near * far ) / ( ( far - near ) * depth - far );
#endif
}`,WG=`#ifdef PREMULTIPLIED_ALPHA
gl_FragColor.rgb *= gl_FragColor.a;
#endif`,qG=`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;`,$G=`#ifdef DITHERING
gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,XG=`#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`,YG=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
roughnessFactor *= texelRoughness.g;
#endif`,jG=`#ifdef USE_ROUGHNESSMAP
uniform sampler2D roughnessMap;
#endif`,KG=`#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
#if defined( SHADOWMAP_TYPE_PCF )
uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
#else
uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
#endif
varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
struct DirectionalLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
#endif
#if NUM_SPOT_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
#else
uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
#endif
struct SpotLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
#elif defined( SHADOWMAP_TYPE_BASIC )
uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
#endif
varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
struct PointLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
float shadowCameraNear;
float shadowCameraFar;
};
uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
#endif
#if defined( SHADOWMAP_TYPE_PCF )
float interleavedGradientNoise( vec2 position ) {
return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );
}
vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {
const float goldenAngle = 2.399963229728653;
float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );
float theta = float( sampleIndex ) * goldenAngle + phi;
return vec2( cos( theta ), sin( theta ) ) * r;
}
#endif
#if defined( SHADOWMAP_TYPE_PCF )
float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, 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 ) {
vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
float radius = shadowRadius * texelSize.x;
float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;
shadow = (
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )
) * 0.2;
}
return mix( 1.0, shadow, shadowIntensity );
}
#elif defined( SHADOWMAP_TYPE_VSM )
float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
float shadow = 1.0;
shadowCoord.xyz /= shadowCoord.w;
#ifdef USE_REVERSED_DEPTH_BUFFER
shadowCoord.z -= shadowBias;
#else
shadowCoord.z += shadowBias;
#endif
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 ) {
vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;
float mean = distribution.x;
float variance = distribution.y * distribution.y;
#ifdef USE_REVERSED_DEPTH_BUFFER
float hard_shadow = step( mean, shadowCoord.z );
#else
float hard_shadow = step( shadowCoord.z, mean );
#endif
if ( hard_shadow == 1.0 ) {
shadow = 1.0;
} else {
variance = max( variance, 0.0000001 );
float d = shadowCoord.z - mean;
float p_max = variance / ( variance + d * d );
p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );
shadow = max( hard_shadow, p_max );
}
}
return mix( 1.0, shadow, shadowIntensity );
}
#else
float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
float shadow = 1.0;
shadowCoord.xyz /= shadowCoord.w;
#ifdef USE_REVERSED_DEPTH_BUFFER
shadowCoord.z -= shadowBias;
#else
shadowCoord.z += shadowBias;
#endif
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 ) {
float depth = texture2D( shadowMap, shadowCoord.xy ).r;
#ifdef USE_REVERSED_DEPTH_BUFFER
shadow = step( depth, shadowCoord.z );
#else
shadow = step( shadowCoord.z, depth );
#endif
}
return mix( 1.0, shadow, shadowIntensity );
}
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
float shadow = 1.0;
vec3 lightToPosition = shadowCoord.xyz;
vec3 bd3D = normalize( lightToPosition );
vec3 absVec = abs( lightToPosition );
float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );
if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
dp -= shadowBias;
#else
float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
dp += shadowBias;
#endif
float texelSize = shadowRadius / shadowMapSize.x;
vec3 absDir = abs( bd3D );
vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );
tangent = normalize( cross( bd3D, tangent ) );
vec3 bitangent = cross( bd3D, tangent );
float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;
vec2 sample0 = vogelDiskSample( 0, 5, phi );
vec2 sample1 = vogelDiskSample( 1, 5, phi );
vec2 sample2 = vogelDiskSample( 2, 5, phi );
vec2 sample3 = vogelDiskSample( 3, 5, phi );
vec2 sample4 = vogelDiskSample( 4, 5, phi );
shadow = (
texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )
) * 0.2;
}
return mix( 1.0, shadow, shadowIntensity );
}
#elif defined( SHADOWMAP_TYPE_BASIC )
float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
float shadow = 1.0;
vec3 lightToPosition = shadowCoord.xyz;
vec3 absVec = abs( lightToPosition );
float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );
if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {
float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
dp += shadowBias;
vec3 bd3D = normalize( lightToPosition );
float depth = textureCube( shadowMap, bd3D ).r;
#ifdef USE_REVERSED_DEPTH_BUFFER
depth = 1.0 - depth;
#endif
shadow = step( dp, depth );
}
return mix( 1.0, shadow, shadowIntensity );
}
#endif
#endif
#endif`,ZG=`#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 shadowIntensity;
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 shadowIntensity;
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 shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
float shadowCameraNear;
float shadowCameraFar;
};
uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
#endif
#endif`,JG=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
#ifdef HAS_NORMAL
vec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );
#else
vec3 shadowWorldNormal = vec3( 0.0 );
#endif
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`,QG=`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.shadowIntensity, 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.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
}
#pragma unroll_loop_end
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )
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.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
}
#pragma unroll_loop_end
#endif
#endif
return shadow;
}`,e5=`#ifdef USE_SKINNING
mat4 boneMatX = getBoneMatrix( skinIndex.x );
mat4 boneMatY = getBoneMatrix( skinIndex.y );
mat4 boneMatZ = getBoneMatrix( skinIndex.z );
mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,t5=`#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`,n5=`#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`,i5=`#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`,s5=`float specularStrength;
#ifdef USE_SPECULARMAP
vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
specularStrength = texelSpecular.r;
#else
specularStrength = 1.0;
#endif`,r5=`#ifdef USE_SPECULARMAP
uniform sampler2D specularMap;
#endif`,a5=`#if defined( TONE_MAPPING )
gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,o5=`#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 CineonToneMapping( 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 *= toneMappingExposure;
color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
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;
color = clamp( color, 0.0, 1.0 );
return color;
}
vec3 NeutralToneMapping( vec3 color ) {
const float StartCompression = 0.8 - 0.04;
const float Desaturation = 0.15;
color *= toneMappingExposure;
float x = min( color.r, min( color.g, color.b ) );
float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
color -= offset;
float peak = max( color.r, max( color.g, color.b ) );
if ( peak < StartCompression ) return color;
float d = 1. - StartCompression;
float newPeak = 1. - d * d / ( peak + d - StartCompression );
color *= newPeak / peak;
float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`,l5=`#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 = transformNormalByInverseViewMatrix( normal, viewMatrix );
vec4 transmitted = getIBLVolumeRefraction(
n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,
pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, 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`,c5=`#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 dispersion, const in float ior, const in float thickness,
const in vec3 attenuationColor, const in float attenuationDistance ) {
vec4 transmittedLight;
vec3 transmittance;
#ifdef USE_DISPERSION
float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
for ( int i = 0; i < 3; i ++ ) {
vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], 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 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
transmittedLight[ i ] = transmissionSample[ i ];
transmittedLight.a += transmissionSample.a;
transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
}
transmittedLight.a /= 3.0;
#else
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;
transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
#endif
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`,u5=`#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`,d5=`#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`,h5=`#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`,p5=`#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`,f5=`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,m5=`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 <tonemapping_fragment>
#include <colorspace_fragment>
}`,g5=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,y5=`#ifdef ENVMAP_TYPE_CUBE
uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
uniform sampler2D envMap;
#endif
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
#ifdef ENVMAP_TYPE_CUBE
vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection );
#elif defined( ENVMAP_TYPE_CUBE_UV )
vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
#else
vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
#endif
texColor.rgb *= backgroundIntensity;
gl_FragColor = texColor;
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,x5=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,_5=`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 <tonemapping_fragment>
#include <colorspace_fragment>
}`,b5=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
#include <uv_vertex>
#include <batching_vertex>
#include <skinbase_vertex>
#include <morphinstance_vertex>
#ifdef USE_DISPLACEMENTMAP
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinnormal_vertex>
#endif
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vHighPrecisionZW = gl_Position.zw;
}`,v5=`#if DEPTH_PACKING == 3200
uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
vec4 diffuseColor = vec4( 1.0 );
#include <clipping_planes_fragment>
#if DEPTH_PACKING == 3200
diffuseColor.a = opacity;
#endif
#include <map_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <logdepthbuf_fragment>
#ifdef USE_REVERSED_DEPTH_BUFFER
float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
#else
float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
#endif
#if DEPTH_PACKING == 3200
gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
#elif DEPTH_PACKING == 3201
gl_FragColor = packDepthToRGBA( fragCoordZ );
#elif DEPTH_PACKING == 3202
gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
#elif DEPTH_PACKING == 3203
gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
#endif
}`,S5=`#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <batching_vertex>
#include <skinbase_vertex>
#include <morphinstance_vertex>
#ifdef USE_DISPLACEMENTMAP
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinnormal_vertex>
#endif
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <worldpos_vertex>
#include <clipping_planes_vertex>
vWorldPosition = worldPosition.xyz;
}`,T5=`#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( 1.0 );
#include <clipping_planes_fragment>
#include <map_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
float dist = length( vWorldPosition - referencePosition );
dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
dist = saturate( dist );
gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );
}`,M5=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
}`,w5=`uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
vec3 direction = normalize( vWorldDirection );
vec2 sampleUV = equirectUv( direction );
gl_FragColor = texture2D( tEquirect, sampleUV );
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,E5=`uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
vLineDistance = scale * lineDistance;
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
}`,R5=`uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
if ( mod( vLineDistance, totalSize ) > dashSize ) {
discard;
}
vec3 outgoingLight = vec3( 0.0 );
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
outgoingLight = diffuseColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}`,A5=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#endif
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <worldpos_vertex>
#include <envmap_vertex>
#include <fog_vertex>
}`,C5=`uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <specularmap_fragment>
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 <aomap_fragment>
reflectedLight.indirectDiffuse *= diffuseColor.rgb;
vec3 outgoingLight = reflectedLight.indirectDiffuse;
#include <envmap_fragment>
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,N5=`#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <envmap_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,P5=`#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <specularmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_lambert_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
#include <envmap_fragment>
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,D5=`#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
vViewPosition = - mvPosition.xyz;
}`,I5=`#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
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 <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,F5=`#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphinstance_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
vViewPosition = - mvPosition.xyz;
#endif
}`,L5=`#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
varying vec3 vViewPosition;
#endif
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );
#ifdef OPAQUE
gl_FragColor.a = 1.0;
#endif
}`,B5=`#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphinstance_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <envmap_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,U5=`#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <specularmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_phong_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
#include <envmap_fragment>
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,O5=`#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
#ifdef USE_TRANSMISSION
vWorldPosition = worldPosition.xyz;
#endif
}`,k5=`#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_DISPERSION
uniform float dispersion;
#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 <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <roughnessmap_fragment>
#include <metalnessmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <clearcoat_normal_fragment_begin>
#include <clearcoat_normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_physical_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
#include <transmission_fragment>
vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
#ifdef USE_SHEEN
outgoingLight = outgoingLight + 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 <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,V5=`#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,G5=`#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_toon_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,z5=`uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#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 <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <project_vertex>
gl_PointSize = size;
#ifdef USE_SIZEATTENUATION
bool isPerspective = isPerspectiveMatrix( projectionMatrix );
if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
#endif
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <worldpos_vertex>
#include <fog_vertex>
}`,H5=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
vec3 outgoingLight = vec3( 0.0 );
#include <logdepthbuf_fragment>
#include <map_particle_fragment>
#include <color_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
outgoingLight = diffuseColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}`,W5=`#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphinstance_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,q5=`uniform vec3 color;
uniform float opacity;
#include <common>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
#include <logdepthbuf_fragment>
gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}`,$5=`uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
vec4 mvPosition = modelViewMatrix[ 3 ];
vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
#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 <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
}`,X5=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
vec3 outgoingLight = vec3( 0.0 );
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
outgoingLight = diffuseColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
}`,ke={alphahash_fragment:fV,alphahash_pars_fragment:mV,alphamap_fragment:gV,alphamap_pars_fragment:yV,alphatest_fragment:xV,alphatest_pars_fragment:_V,aomap_fragment:bV,aomap_pars_fragment:vV,batching_pars_vertex:SV,batching_vertex:TV,begin_vertex:MV,beginnormal_vertex:wV,bsdfs:EV,iridescence_fragment:RV,bumpmap_pars_fragment:AV,clipping_planes_fragment:CV,clipping_planes_pars_fragment:NV,clipping_planes_pars_vertex:PV,clipping_planes_vertex:DV,color_fragment:IV,color_pars_fragment:FV,color_pars_vertex:LV,color_vertex:BV,common:UV,cube_uv_reflection_fragment:OV,defaultnormal_vertex:kV,displacementmap_pars_vertex:VV,displacementmap_vertex:GV,emissivemap_fragment:zV,emissivemap_pars_fragment:HV,colorspace_fragment:WV,colorspace_pars_fragment:qV,envmap_fragment:$V,envmap_common_pars_fragment:XV,envmap_pars_fragment:YV,envmap_pars_vertex:jV,envmap_physical_pars_fragment:aG,envmap_vertex:KV,fog_vertex:ZV,fog_pars_vertex:JV,fog_fragment:QV,fog_pars_fragment:eG,gradientmap_pars_fragment:tG,lightmap_pars_fragment:nG,lights_lambert_fragment:iG,lights_lambert_pars_fragment:sG,lights_pars_begin:rG,lights_toon_fragment:oG,lights_toon_pars_fragment:lG,lights_phong_fragment:cG,lights_phong_pars_fragment:uG,lights_physical_fragment:dG,lights_physical_pars_fragment:hG,lights_fragment_begin:pG,lights_fragment_maps:fG,lights_fragment_end:mG,lightprobes_pars_fragment:gG,logdepthbuf_fragment:yG,logdepthbuf_pars_fragment:xG,logdepthbuf_pars_vertex:_G,logdepthbuf_vertex:bG,map_fragment:vG,map_pars_fragment:SG,map_particle_fragment:TG,map_particle_pars_fragment:MG,metalnessmap_fragment:wG,metalnessmap_pars_fragment:EG,morphinstance_vertex:RG,morphcolor_vertex:AG,morphnormal_vertex:CG,morphtarget_pars_vertex:NG,morphtarget_vertex:PG,normal_fragment_begin:DG,normal_fragment_maps:IG,normal_pars_fragment:FG,normal_pars_vertex:LG,normal_vertex:BG,normalmap_pars_fragment:UG,clearcoat_normal_fragment_begin:OG,clearcoat_normal_fragment_maps:kG,clearcoat_pars_fragment:VG,iridescence_pars_fragment:GG,opaque_fragment:zG,packing:HG,premultiplied_alpha_fragment:WG,project_vertex:qG,dithering_fragment:$G,dithering_pars_fragment:XG,roughnessmap_fragment:YG,roughnessmap_pars_fragment:jG,shadowmap_pars_fragment:KG,shadowmap_pars_vertex:ZG,shadowmap_vertex:JG,shadowmask_pars_fragment:QG,skinbase_vertex:e5,skinning_pars_vertex:t5,skinning_vertex:n5,skinnormal_vertex:i5,specularmap_fragment:s5,specularmap_pars_fragment:r5,tonemapping_fragment:a5,tonemapping_pars_fragment:o5,transmission_fragment:l5,transmission_pars_fragment:c5,uv_pars_fragment:u5,uv_pars_vertex:d5,uv_vertex:h5,worldpos_vertex:p5,background_vert:f5,background_frag:m5,backgroundCube_vert:g5,backgroundCube_frag:y5,cube_vert:x5,cube_frag:_5,depth_vert:b5,depth_frag:v5,distance_vert:S5,distance_frag:T5,equirect_vert:M5,equirect_frag:w5,linedashed_vert:E5,linedashed_frag:R5,meshbasic_vert:A5,meshbasic_frag:C5,meshlambert_vert:N5,meshlambert_frag:P5,meshmatcap_vert:D5,meshmatcap_frag:I5,meshnormal_vert:F5,meshnormal_frag:L5,meshphong_vert:B5,meshphong_frag:U5,meshphysical_vert:O5,meshphysical_frag:k5,meshtoon_vert:V5,meshtoon_frag:G5,points_vert:z5,points_frag:H5,shadow_vert:W5,shadow_frag:q5,sprite_vert:$5,sprite_frag:X5},se={common:{diffuse:{value:new me(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ve},alphaMap:{value:null},alphaMapTransform:{value:new ve},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ve}},envmap:{envMap:{value:null},envMapRotation:{value:new ve},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ve}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ve}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ve},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ve},normalScale:{value:new O(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ve},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ve}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ve}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ve}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new me(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new E},probesMax:{value:new E},probesResolution:{value:new E}},points:{diffuse:{value:new me(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ve},alphaTest:{value:0},uvTransform:{value:new ve}},sprite:{diffuse:{value:new me(16777215)},opacity:{value:1},center:{value:new O(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ve},alphaMap:{value:null},alphaMapTransform:{value:new ve},alphaTest:{value:0}}},MC={basic:{uniforms:Xn([se.common,se.specularmap,se.envmap,se.aomap,se.lightmap,se.fog]),vertexShader:ke.meshbasic_vert,fragmentShader:ke.meshbasic_frag},lambert:{uniforms:Xn([se.common,se.specularmap,se.envmap,se.aomap,se.lightmap,se.emissivemap,se.bumpmap,se.normalmap,se.displacementmap,se.fog,se.lights,{emissive:{value:new me(0)},envMapIntensity:{value:1}}]),vertexShader:ke.meshlambert_vert,fragmentShader:ke.meshlambert_frag},phong:{uniforms:Xn([se.common,se.specularmap,se.envmap,se.aomap,se.lightmap,se.emissivemap,se.bumpmap,se.normalmap,se.displacementmap,se.fog,se.lights,{emissive:{value:new me(0)},specular:{value:new me(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:ke.meshphong_vert,fragmentShader:ke.meshphong_frag},standard:{uniforms:Xn([se.common,se.envmap,se.aomap,se.lightmap,se.emissivemap,se.bumpmap,se.normalmap,se.displacementmap,se.roughnessmap,se.metalnessmap,se.fog,se.lights,{emissive:{value:new me(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ke.meshphysical_vert,fragmentShader:ke.meshphysical_frag},toon:{uniforms:Xn([se.common,se.aomap,se.lightmap,se.emissivemap,se.bumpmap,se.normalmap,se.displacementmap,se.gradientmap,se.fog,se.lights,{emissive:{value:new me(0)}}]),vertexShader:ke.meshtoon_vert,fragmentShader:ke.meshtoon_frag},matcap:{uniforms:Xn([se.common,se.bumpmap,se.normalmap,se.displacementmap,se.fog,{matcap:{value:null}}]),vertexShader:ke.meshmatcap_vert,fragmentShader:ke.meshmatcap_frag},points:{uniforms:Xn([se.points,se.fog]),vertexShader:ke.points_vert,fragmentShader:ke.points_frag},dashed:{uniforms:Xn([se.common,se.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ke.linedashed_vert,fragmentShader:ke.linedashed_frag},depth:{uniforms:Xn([se.common,se.displacementmap]),vertexShader:ke.depth_vert,fragmentShader:ke.depth_frag},normal:{uniforms:Xn([se.common,se.bumpmap,se.normalmap,se.displacementmap,{opacity:{value:1}}]),vertexShader:ke.meshnormal_vert,fragmentShader:ke.meshnormal_frag},sprite:{uniforms:Xn([se.sprite,se.fog]),vertexShader:ke.sprite_vert,fragmentShader:ke.sprite_frag},background:{uniforms:{uvTransform:{value:new ve},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ke.background_vert,fragmentShader:ke.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ve}},vertexShader:ke.backgroundCube_vert,fragmentShader:ke.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ke.cube_vert,fragmentShader:ke.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ke.equirect_vert,fragmentShader:ke.equirect_frag},distance:{uniforms:Xn([se.common,se.displacementmap,{referencePosition:{value:new E},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ke.distance_vert,fragmentShader:ke.distance_frag},shadow:{uniforms:Xn([se.lights,se.fog,{color:{value:new me(0)},opacity:{value:1}}]),vertexShader:ke.shadow_vert,fragmentShader:ke.shadow_frag}};MC.physical={uniforms:Xn([MC.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ve},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ve},clearcoatNormalScale:{value:new O(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ve},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ve},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ve},sheen:{value:0},sheenColor:{value:new me(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ve},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ve},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ve},transmissionSamplerSize:{value:new O},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ve},attenuationDistance:{value:0},attenuationColor:{value:new me(0)},specularColor:{value:new me(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ve},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ve},anisotropyVector:{value:new O},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ve}}]),vertexShader:ke.meshphysical_vert,fragmentShader:ke.meshphysical_frag};var Y5=new ve;Y5.set(-1,0,0,0,1,0,0,0,1);var Aj={[Bd]:"LINEAR_TONE_MAPPING",[Ud]:"REINHARD_TONE_MAPPING",[Od]:"CINEON_TONE_MAPPING",[Aa]:"ACES_FILMIC_TONE_MAPPING",[kd]:"AGX_TONE_MAPPING",[Vd]:"NEUTRAL_TONE_MAPPING",[sf]:"CUSTOM_TONE_MAPPING"};var Cj=new Float32Array(16),Nj=new Float32Array(9),Pj=new Float32Array(4);var Dj={[Bd]:"Linear",[Ud]:"Reinhard",[Od]:"Cineon",[Aa]:"ACESFilmic",[kd]:"AgX",[Vd]:"Neutral",[sf]:"Custom"};var Ij={[Fd]:"SHADOWMAP_TYPE_PCF",[Ta]:"SHADOWMAP_TYPE_VSM"};var Fj={[Pr]:"ENVMAP_TYPE_CUBE",[Ca]:"ENVMAP_TYPE_CUBE",[Po]:"ENVMAP_TYPE_CUBE_UV"};var Lj={[Ca]:"ENVMAP_MODE_REFRACTION"};var Bj={[No]:"ENVMAP_BLENDING_MULTIPLY",[tf]:"ENVMAP_BLENDING_MIX",[nf]:"ENVMAP_BLENDING_ADD"};var j5=new ve;j5.set(-1,0,0,0,1,0,0,0,1);var Uj=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);var wC={type:"change"},xT={type:"start"},RC={type:"end"},Jg=new xo,EC=new ri,Z5=Math.cos(70*Dn.DEG2RAD),un=new E,xi=2*Math.PI,at={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},yT=1e-6,Qg=class extends hc{constructor(e,t=null){super(e,t),this.state=at.NONE,this.target=new E,this.cursor=new E,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Cr.ROTATE,MIDDLE:Cr.DOLLY,RIGHT:Cr.PAN},this.touches={ONE:Nr.ROTATE,TWO:Nr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new E,this._lastQuaternion=new fn,this._lastTargetPosition=new E,this._quat=new fn().setFromUnitVectors(e.up,new E(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Co,this._sphericalDelta=new Co,this._scale=1,this._panOffset=new E,this._rotateStart=new O,this._rotateEnd=new O,this._rotateDelta=new O,this._panStart=new O,this._panEnd=new O,this._panDelta=new O,this._dollyStart=new O,this._dollyEnd=new O,this._dollyDelta=new O,this._dollyDirection=new E,this._mouse=new O,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Q5.bind(this),this._onPointerDown=J5.bind(this),this._onPointerUp=e4.bind(this),this._onContextMenu=o4.bind(this),this._onMouseWheel=i4.bind(this),this._onKeyDown=s4.bind(this),this._onTouchStart=r4.bind(this),this._onTouchMove=a4.bind(this),this._onMouseDown=t4.bind(this),this._onMouseMove=n4.bind(this),this._interceptControlDown=l4.bind(this),this._interceptControlUp=c4.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(wC),this.update(),this.state=at.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){let t=this.object.position;un.copy(t).sub(this.target),un.applyQuaternion(this._quat),this._spherical.setFromVector3(un),this.autoRotate&&this.state===at.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=xi:n>Math.PI&&(n-=xi),i<-Math.PI?i+=xi:i>Math.PI&&(i-=xi),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=a!=this._spherical.radius}if(un.setFromSpherical(this._spherical),un.applyQuaternion(this._quatInverse),t.copy(this.target).add(un),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let a=null;if(this.object.isPerspectiveCamera){let o=un.length();a=this._clampDistance(o*this._scale);let l=o-a;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),s=!!l}else if(this.object.isOrthographicCamera){let o=new E(this._mouse.x,this._mouse.y,0);o.unproject(this.object);let l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=l!==this.object.zoom;let c=new E(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),a=un.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;a!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position):(Jg.origin.copy(this.object.position),Jg.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Jg.direction))<Z5?this.object.lookAt(this.target):(EC.setFromNormalAndCoplanarPoint(this.object.up,this.target),Jg.intersectPlane(EC,this.target))))}else if(this.object.isOrthographicCamera){let a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),a!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>yT||8*(1-this._lastQuaternion.dot(this.object.quaternion))>yT||this._lastTargetPosition.distanceToSquared(this.target)>yT?(this.dispatchEvent(wC),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?xi/60*this.autoRotateSpeed*e:xi/60/60*this.autoRotateSpeed}_getZoomScale(e){let t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){un.setFromMatrixColumn(t,0),un.multiplyScalar(-e),this._panOffset.add(un)}_panUp(e,t){this.screenSpacePanning===!0?un.setFromMatrixColumn(t,1):(un.setFromMatrixColumn(t,0),un.crossVectors(this.object.up,un)),un.multiplyScalar(e),this._panOffset.add(un)}_pan(e,t){let n=this.domElement;if(this.object.isPerspectiveCamera){let i=this.object.position;un.copy(i).sub(this.target);let s=un.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/n.clientHeight,this.object.matrix),this._panUp(2*t*s/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let n=this.domElement.getBoundingClientRect(),i=e-n.left,s=t-n.top,a=n.width,o=n.height;this._mouse.x=i/a*2-1,this._mouse.y=-(s/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(xi*this._rotateDelta.x/t.clientHeight),this._rotateUp(xi*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(xi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-xi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(xi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-xi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let n=this._getSecondPointerPosition(e),i=.5*(e.pageX+n.x),s=.5*(e.pageY+n.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(xi*this._rotateDelta.x/t.clientHeight),this._rotateUp(xi*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(a,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new O,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){let t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){let t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}};function J5(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(r)&&(this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function Q5(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function e4(r){switch(this._removePointer(r),this._pointers.length){case 0:this.domElement.releasePointerCapture(r.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(RC),this.state=at.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:let e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function t4(r){let e;switch(r.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Cr.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(r),this.state=at.DOLLY;break;case Cr.ROTATE:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=at.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=at.ROTATE}break;case Cr.PAN:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=at.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=at.PAN}break;default:this.state=at.NONE}this.state!==at.NONE&&this.dispatchEvent(xT)}function n4(r){switch(this.state){case at.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(r);break;case at.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(r);break;case at.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(r);break}}function i4(r){this.enabled===!1||this.enableZoom===!1||this.state!==at.NONE||(r.preventDefault(),this.dispatchEvent(xT),this._handleMouseWheel(this._customWheelEvent(r)),this.dispatchEvent(RC))}function s4(r){this.enabled!==!1&&this._handleKeyDown(r)}function r4(r){switch(this._trackPointer(r),this._pointers.length){case 1:switch(this.touches.ONE){case Nr.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(r),this.state=at.TOUCH_ROTATE;break;case Nr.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(r),this.state=at.TOUCH_PAN;break;default:this.state=at.NONE}break;case 2:switch(this.touches.TWO){case Nr.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(r),this.state=at.TOUCH_DOLLY_PAN;break;case Nr.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(r),this.state=at.TOUCH_DOLLY_ROTATE;break;default:this.state=at.NONE}break;default:this.state=at.NONE}this.state!==at.NONE&&this.dispatchEvent(xT)}function a4(r){switch(this._trackPointer(r),this.state){case at.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(r),this.update();break;case at.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(r),this.update();break;case at.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(r),this.update();break;case at.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(r),this.update();break;default:this.state=at.NONE}}function o4(r){this.enabled!==!1&&r.preventDefault()}function l4(r){r.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function c4(r){r.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}var Fs=new Is,u4=new O,d4=new O(1,0),h4=new O(0,1),_T,p4=us(({input:r,threshold:e,smoothWidth:t})=>{let n=gC(r.rgb),i=Xt(e,e.add(t),n);return zn(Vi(0),r,i)}),bT=class extends ht{static get type(){return"BloomNode"}constructor(e,t=1,n=0,i=0){super("vec4"),this.inputNode=e,this.strength=t.isNode?t:pt(t),this.radius=n.isNode?n:pt(n),this.threshold=i.isNode?i:pt(i),this.smoothWidth=pt(.01),this._resolutionScale=.5,this.highPassFn=p4,this._renderTargetsHorizontal=[],this._renderTargetsVertical=[],this._nMips=5,this._renderTargetBright=new Jt(1,1,{depthBuffer:!1,type:xt}),this._renderTargetBright.texture.name="UnrealBloomPass.bright",this._renderTargetBright.texture.generateMipmaps=!1;for(let s=0;s<this._nMips;s++){let a=new Jt(1,1,{depthBuffer:!1,type:xt});a.texture.name="UnrealBloomPass.h"+s,a.texture.generateMipmaps=!1,this._renderTargetsHorizontal.push(a);let o=new Jt(1,1,{depthBuffer:!1,type:xt});o.texture.name="UnrealBloomPass.v"+s,o.texture.generateMipmaps=!1,this._renderTargetsVertical.push(o)}this._compositeMaterial=null,this._highPassFilterMaterial=null,this._separableBlurMaterials=[],this._textureNodeBright=ki(this._renderTargetBright.texture),this._textureNodeBlur0=ki(this._renderTargetsVertical[0].texture),this._textureNodeBlur1=ki(this._renderTargetsVertical[1].texture),this._textureNodeBlur2=ki(this._renderTargetsVertical[2].texture),this._textureNodeBlur3=ki(this._renderTargetsVertical[3].texture),this._textureNodeBlur4=ki(this._renderTargetsVertical[4].texture),this._textureOutput=bC(this,this._renderTargetsHorizontal[0].texture),this.updateBeforeType=pe.FRAME}getTextureNode(){return this._textureOutput}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setSize(e,t){let n=Math.floor(e*this._resolutionScale),i=Math.floor(t*this._resolutionScale);this._renderTargetBright.setSize(n,i);for(let s=0;s<this._nMips;s++)this._renderTargetsHorizontal[s].setSize(n,i),this._renderTargetsVertical[s].setSize(n,i),this._separableBlurMaterials[s].invSize.value.set(1/n,1/i),n=Math.floor(n/2),i=Math.floor(i/2)}updateBefore(e){let{renderer:t}=e;_T=dT.resetRendererState(t,_T);let n=t.getDrawingBufferSize(u4);this.setSize(n.width,n.height),t.setRenderTarget(this._renderTargetBright),Fs.material=this._highPassFilterMaterial,Fs.name="Bloom [ High Pass ]",Fs.render(t);let i=this._renderTargetBright;for(let s=0;s<this._nMips;s++)Fs.material=this._separableBlurMaterials[s],this._separableBlurMaterials[s].colorTexture.value=i.texture,this._separableBlurMaterials[s].direction.value=d4,t.setRenderTarget(this._renderTargetsHorizontal[s]),Fs.name=`Bloom [ Blur Horizontal - ${s} ]`,Fs.render(t),this._separableBlurMaterials[s].colorTexture.value=this._renderTargetsHorizontal[s].texture,this._separableBlurMaterials[s].direction.value=h4,t.setRenderTarget(this._renderTargetsVertical[s]),Fs.name=`Bloom [ Blur Vertical - ${s} ]`,Fs.render(t),i=this._renderTargetsVertical[s];t.setRenderTarget(this._renderTargetsHorizontal[0]),Fs.material=this._compositeMaterial,Fs.name="Bloom [ Composite ]",Fs.render(t),dT.restoreRendererState(t,_T)}setup(e){this._highPassFilterMaterial=this._highPassFilterMaterial||new We,this._highPassFilterMaterial.fragmentNode=this.highPassFn({input:this.inputNode,threshold:this.threshold,smoothWidth:this.smoothWidth}).context(e.getSharedContext()),this._highPassFilterMaterial.name="Bloom_highPass",this._highPassFilterMaterial.needsUpdate=!0;let t=[6,10,14,18,22];for(let o=0;o<this._nMips;o++)this._separableBlurMaterials.push(this._getSeparableBlurMaterial(e,t[o]));let n=Zg([1,.8,.6,.4,.2]),i=Zg([new E(1,1,1),new E(1,1,1),new E(1,1,1),new E(1,1,1),new E(1,1,1)]),s=us(([o,l])=>{let c=et(1.2).sub(o);return zn(o,c,l)}).setLayout({name:"lerpBloomFactor",type:"float",inputs:[{name:"factor",type:"float"},{name:"radius",type:"float"}]}),a=us(()=>{let o=s(n.element(0),this.radius).mul(Vi(i.element(0),1)).mul(this._textureNodeBlur0),l=s(n.element(1),this.radius).mul(Vi(i.element(1),1)).mul(this._textureNodeBlur1),c=s(n.element(2),this.radius).mul(Vi(i.element(2),1)).mul(this._textureNodeBlur2),u=s(n.element(3),this.radius).mul(Vi(i.element(3),1)).mul(this._textureNodeBlur3),d=s(n.element(4),this.radius).mul(Vi(i.element(4),1)).mul(this._textureNodeBlur4);return o.add(l).add(c).add(u).add(d).mul(this.strength)});return this._compositeMaterial=this._compositeMaterial||new We,this._compositeMaterial.fragmentNode=a().context(e.getSharedContext()),this._compositeMaterial.name="Bloom_comp",this._compositeMaterial.needsUpdate=!0,this._textureOutput}dispose(){for(let e=0;e<this._renderTargetsHorizontal.length;e++)this._renderTargetsHorizontal[e].dispose();for(let e=0;e<this._renderTargetsVertical.length;e++)this._renderTargetsVertical[e].dispose();this._renderTargetBright.dispose(),this._highPassFilterMaterial!==null&&this._highPassFilterMaterial.dispose(),this._compositeMaterial!==null&&this._compositeMaterial.dispose();for(let e=0;e<this._separableBlurMaterials.length;e++)this._separableBlurMaterials[e].dispose()}_getSeparableBlurMaterial(e,t){let n=[],i=t/3;for(let p=0;p<t;p++)n.push(.39894*Math.exp(-.5*p*p/(i*i))/i);let s=ki(null),a=Zg(n),o=pt(new O),l=pt(new O(.5,.5)),c=sn(),u=p=>s.sample(p),d=us(()=>{let p=u(c).rgb.mul(a.element(0)).toVar();return hC({start:gT(1),end:gT(t),type:"int",condition:"<"},({i:f})=>{let m=et(f),y=a.element(f),x=l.mul(o).mul(m),b=u(c.add(x)).rgb,_=u(c.sub(x)).rgb;p.addAssign(fC(b,_).mul(y))}),Vi(p,1)}),h=new We;return h.fragmentNode=d().context(e.getSharedContext()),h.name="Bloom_separable",h.needsUpdate=!0,h.colorTexture=s,h.direction=l,h.invSize=o,h}},AC=(r,e,t,n)=>new bT(yC(r),e,t,n);var hs={rise:.38,riseHot:.5,swirl:.18,swirlScale:4.2,cool:3.8,coolFloor:.5,hazeCool:1.6,edgeBand:.011,interiorFloor:.14,interiorPeak:.78,fireLight:.6,refract:.012,shimmer:.003,exposure:.5,bloom:.25,sparks:1},_i={burn:1,edge:.87,interior:.62,sparks:2.01,rise:.76,swirl:.57,cool:2.5,refract:.02,fireLight:.39,exposure:.5,bloom:.53,skinWarm:0,maskBody:0,rim:0},CC=.5,e0=us(([r])=>{let e=$g(r.sub(720).div(1900),0,1),t=Ft(1,.035,.002),n=Ft(1,.24,.008),i=Ft(1,.68,.12),s=Ft(1,.94,.72);return zn(zn(t,n,Xt(0,.32,e)),zn(i,s,Xt(.58,1,e)),Xt(.26,.72,e))}),vT=us(([r,e])=>Xg(Kg(ap(r,Ct(127.1,311.7)).add(e)).mul(43758.5453))),NC=us(([r,e,t])=>{let n=Ct(t,0),i=Ct(0,t),s=ds(Ft(r.add(n),e)).sub(ds(Ft(r.sub(n),e))),a=ds(Ft(r.add(i),e)).sub(ds(Ft(r.sub(i),e)));return Ct(a,s.negate()).div(t.mul(2))});function PC(r){let{renderer:e,scene:t,camera:n,subjectLayer:i,sceneLayers:s}=r,a=pt(1),o=pt(0),l=pt(0),c=pt(_i.burn),u=pt(_i.sparks),d=pt(_i.edge),h=pt(_i.interior),p=pt(_i.rise),f=pt(_i.swirl),m=pt(_i.cool),y=pt(_i.refract),x=pt(_i.fireLight),b=pt(_i.exposure),_=pt(_i.skinWarm),S=pt(_i.maskBody),M=pt(_i.rim),w=pt(0),T=pt(0),R=pt(new O(1/640,1/400),"vec2"),D=U=>new Jt(8,8,{type:U?xt:Gt,format:bn,minFilter:St,magFilter:St,generateMipmaps:!1,depthBuffer:!U,stencilBuffer:!1}),L=D(!1),B=[D(!0),D(!0)],W=D(!0),q=ki(L.texture),ce=new ga(new Uint8Array([0,0,0,0]),1,1);ce.needsUpdate=!0;let k=ki(ce),j=ki(B[0].texture),ee=ki(W.texture),ge=()=>Ct(sn().x.mul(a),sn().y).toVar(),fe=U=>Ct(U.x.div(a),U.y),he=(U,ae)=>{let Z=Ct(et(ae).div(a),0),we=Ct(0,ae),_e=q.sample(U.add(Z)).r.add(q.sample(U.sub(Z)).r).add(q.sample(U.add(we)).r).add(q.sample(U.sub(we)).r).mul(.25);return _e.mul(_e.oneMinus()).mul(4)},ye=()=>{let U=new We;return U.depthTest=!1,U.depthWrite=!1,U},ze=new Uh({color:16777215}),Pe=ye();Pe.fragmentNode=us(()=>{let U=ge(),ae=o,Z=l,we=j.sample(sn()).toVar(),_e=NC(U.mul(hs.swirlScale),ae.mul(.45),et(.02)).mul(f).add(NC(U.mul(hs.swirlScale*2.7).add(Ct(5.1,2.3)),ae.mul(1.1),et(.015)).mul(f.mul(.45))),Ae=ds(Ft(U.mul(1.4),ae.mul(.25))).mul(.16),ct=p.add($g(we.r,0,1).mul(hs.riseHot)),nt=Ct(_e.x.add(Ae),_e.y.sub(ct)),ft=U.sub(nt.mul(Z)),_t=j.sample(fe(ft)).toVar(),ut=lp(_t.r.mul(op(Z.mul(m.negate()))).sub(Z.mul(hs.coolFloor)),0),vi=_t.g.mul(op(Z.mul(-hs.hazeCool))),bt=_t.a.add(Z).min(6),ni=q.sample(sn()).r,mt=he(sn(),hs.edgeBand).mul(c).mul(d),gt=Yg(Ft(U.x.mul(11),U.y.mul(13).add(ae.mul(1.1)),ae.mul(.8)),2,2.2,.5),rn=ni.mul(c).mul(h).mul(et(hs.interiorFloor).add(Xt(-.05,.5,gt).mul(hs.interiorPeak-hs.interiorFloor))),dn=et(.78).add(ds(Ft(U.mul(18),ae.mul(6))).mul(.22)),ps=lp(rn,mt).mul(dn).toVar(),hn=lp(ut,ps),Kt=Xt(.15,.6,ps),gr=ds(Ft(U.mul(11),ae.mul(1.6)));return Vi(hn,lp(vi,ps.mul(.85).min(1)),zn(_t.b,gr,Kt),zn(bt,et(0),Kt))})();let ot=ye();ot.fragmentNode=us(()=>{let U=ge(),ae=o,Z=j.sample(sn()).toVar(),we=Z.r,_e=Z.a,Ae=Z.b.mul(.5).add(.5),ct=U.y.add(_e.mul(hs.rise+hs.riseHot*.5)),nt=ae.sub(_e),ft=Yg(Ft(U.x.mul(7.5),ct.mul(3.6),nt.mul(.55).add(2.7)),3,2,.55),_t=pC(ds(Ft(U.x.mul(20),ct.mul(13),nt.mul(.7).add(9)))),ut=ds(Ft(U.x.mul(30),U.y.add(ae.mul(1.6)).mul(22),ae.mul(1.1))),vi=et(1).add(Xt(0,1.2,_e).mul(.5)),bt=we.mul(et(1).add(ft.mul(vi)).sub(_t.mul(.5)).add(ut.mul(.15))).mul(et(.82).add(Ae.mul(.36))).toVar(),ni=Xt(.26,.4,bt),mt=Xt(.42,.62,bt),gt=Xt(.62,.88,bt),rn=Xt(.95,1.3,bt),dn=et(760).add(ni.mul(490)).add(mt.mul(500)).add(gt.mul(600)).add(rn.mul(550)),ps=e0(dn).mul(ni.mul(.7).add(mt.mul(1.15)).add(gt.mul(1.5)).add(rn.mul(1.3))),hn=ni.mul(.75).add(mt.mul(.2)).add(gt.mul(.05));return Vi(ps,hn)})();let Se=(U,ae)=>{let Z=Ft(0).toVar(),we=[[.055,.2,0,1],[.07,.26,.37,7],[.045,.16,.71,13]];for(let[_e,Ae,ct,nt]of we){let ft=Ct(_e,Ae),_t=U.div(ft).add(ct),ut=mC(_t),vi=Xg(_t),bt=vT(ut,nt),ni=vT(ut,nt+3.7),mt=vT(ut,nt+9.1),gt=et(1.1).add(mt.mul(.9)),rn=Xg(ae.div(gt).add(bt)),dn=Kg(ae.mul(2.4).add(bt.mul(25))).mul(.09).mul(rn),ps=et(.5).add(ni.sub(.5).mul(.7)).add(dn),hn=rn.oneMinus(),Kt=vi.sub(Ct(ps,hn)).mul(ft),gr=Ct(Kt.x,Kt.y.mul(.45)),Si=ap(gr,gr),fs=op(Si.mul(-1/(.0026*.0026))),ii=op(Si.mul(-1/(.006*.006))).mul(.06),An=Xt(0,.12,rn).mul(Xt(.55,1,rn).oneMinus()),gp=et(.7).add(Kg(ae.mul(17).add(ni.mul(50))).mul(.3)),Ls=ut.add(Ct(ps,1)).sub(ct).mul(ft),RT=j.sample(fe(Ls)).r,Gi=Xt(.25,.7,RT).mul(_l(.2,mt)),si=e0(et(1500).add(ni.mul(900)));Z.addAssign(si.mul(fs.add(ii)).mul(An.mul(gp).mul(Gi).mul(2.6)))}return Z},Je=_C(t,n);Je.setLayers(s);let lt=Je.getTextureNode("output"),kt=AC(ee,_i.bloom,.5,0),tt=us(()=>{let U=ge(),ae=o,Z=j.sample(sn()).toVar("flameField"),we=Z.r.add(Z.g),_e=j.sample(sn().add(Ct(R.x,0))).r.sub(j.sample(sn().sub(Ct(R.x,0))).r),Ae=j.sample(sn().add(Ct(0,R.y))).r.sub(j.sample(sn().sub(Ct(0,R.y))).r),ct=ds(Ft(U.x.mul(22),U.y.add(ae.mul(.9)).mul(16),ae.mul(1.7))),nt=Ct(_e,Ae).mul(y).add(Ct(ct,ct.mul(.6)).mul(Z.g).mul(hs.shimmer)).mul(Xt(0,.2,we)),ft=q.sample(sn()).r.toVar("flameSilhouetteRaw"),_t=lt.sample(sn().add(nt)).rgb,ut=k.sample(sn().add(nt)),vi=zn(_t,ut.rgb,ut.a.mul(w).mul(ft.oneMinus())).mul(et(1).sub(ft.mul(et(1).sub(S)))),bt=ft.mul(c).toVar("flameSilhouette"),ni=he(sn(),.007).mul(c).mul(et(.45).add(bt.mul(.55))),mt=ee.sample(sn()).toVar("flameSample"),gt=Vi(kt).rgb.toVar("flameGlow"),rn=vi.mul(et(1).add(gt.mul(x))).toVar("flameLit"),dn=Yg(Ft(U.x.mul(24),U.y.mul(24).add(ae.mul(1.1)),ae.mul(2)),2,2.1,.5).mul(.5).add(.5),ps=e0(et(1800).add(dn.mul(800))),hn=rn.mul(Ft(1.25,.72,.42)).mul(et(1.1).add(dn.mul(.5))).add(ps.mul(dn.mul(.3).add(.08)));rn.assign(zn(rn,hn,bt.mul(.8).mul(_)));let Kt=et(.55).add(ds(Ft(U.mul(44),ae.mul(8))).mul(.45));rn.addAssign(e0(et(2400)).mul(ni.mul(Kt).mul(M))),rn.mulAssign(Z.g.mul(.22).mul(bt.oneMinus()).oneMinus());let gr=mt.rgb.add(gt).add(Se(U,ae).mul(u)).mul(b),Si=$g(mt.a.mul(bt.mul(.45).oneMinus()),0,1),fs=rn.mul(Si.oneMinus()).add(gr).toVar("flameComposite"),ii=jg.sub(.5).length(),An=et(1).sub(Xt(.3,.74,ii).mul(.42));return fs.mulAssign(An),fs.assign(zn(fs,Ft(q.sample(sn()).r),_l(.5,T).mul(_l(T,1.5)))),fs.assign(zn(fs,Ft(Z.r,Z.g,Z.a.mul(.2)),_l(1.5,T).mul(_l(T,2.5)))),fs.assign(zn(fs,mt.rgb,_l(2.5,T))),Vi(fs,1)})(),ti=new fg(e);ti.outputColorTransform=!1,ti.outputNode=TC(tt,Aa);let Rn=new Is(Pe),jt=new Is(ot),Ke=0,K=0;function Q(){let U=e.getRenderTarget(),ae=t.backgroundNode,Z=t.overrideMaterial,we=n.layers.mask;t.backgroundNode=null,t.overrideMaterial=ze,n.layers.set(i);try{e.setRenderTarget(L),e.render(t,n)}finally{e.setRenderTarget(U),t.backgroundNode=ae,t.overrideMaterial=Z,n.layers.mask=we}}function re(U,ae){let Z=Math.max(8,Math.round(U*CC)),we=Math.max(8,Math.round(ae*CC));L.setSize(Z,we);for(let _e of B)_e.setSize(Z,we);W.setSize(U,ae),a.value=U/ae,R.value.set(1.5/Z,1.5/we)}function ue(U){K+=U,o.value=K,l.value=Math.min(.05,Math.max(0,U)),Q();let ae=B[Ke],Z=B[1-Ke];j.value=ae.texture,e.setRenderTarget(Z),Rn.render(e),Ke=1-Ke,j.value=Z.texture,e.setRenderTarget(W),jt.render(e),e.setRenderTarget(null),ti.render()}return{u:{burn:c,sparks:u,edge:d,interior:h,rise:p,swirl:f,cool:m,refract:y,fireLight:x,exposure:b,skinWarm:_,maskBody:S,rim:M,view:T},bloomNode:kt,setTitleTexture(U){k.value=U??ce,w.value=U?1:0},setSize:re,render:ue,dispose(){ce.dispose();for(let U of[L,...B,W])U.dispose();ti.dispose(),Pe.dispose(),ot.dispose(),ze.dispose()}}}function f4(r,e){return r.length()-e}function m4(r,e,t){let n=t*.5,i=Math.max(-n,Math.min(n,r.y));return r.distanceTo(new E(0,i,0))-e}function g4(r,e){let t=new E(Math.abs(r.x),Math.abs(r.y),Math.abs(r.z)).sub(new E(e[0]*.5,e[1]*.5,e[2]*.5));return t.clone().max(new E).length()+Math.min(Math.max(t.x,t.y,t.z),0)}function y4(r,e,t){let n=t*.5,i=e*(1-(r.y+n)/t);return Math.max(Math.hypot(r.x,r.z)-Math.max(0,i),Math.abs(r.y)-n)}function x4(r,e){return(new E(r.x/e[0],r.y/e[1],r.z/e[2]).length()-1)*Math.min(e[0],e[1],e[2])}function _4(r){let e=r.radius;return r.radii?r.radii:typeof e=="number"?[e,e,e]:e??[.5,.5,.5]}function b4(r,e,t){let n=Math.max(t-Math.abs(r-e),0)/t;return Math.min(r,e)-n*n*t*.25}function v4(r,e){let t=e.transform,n=t?.position??t?.translation??e.center??[0,0,0],i=t?.rotation??[0,0,0],s=t?.scale??[1,1,1],a=r.clone().sub(new E(n[0],n[1],n[2])),o=new fn().setFromEuler(new hi(i[0],i[1],i[2])).invert();return a.applyQuaternion(o),a.set(a.x/s[0],a.y/s[1],a.z/s[2]),{point:a,scale:Math.min(s[0],s[1],s[2])}}function S4(r,e){let t=v4(r,e),n;switch(e.type){case"sphere":n=f4(t.point,typeof e.radius=="number"?e.radius:.5);break;case"capsule":n=m4(t.point,typeof e.radius=="number"?e.radius:.25,e.height??1);break;case"box":n=g4(t.point,e.size??e.dimensions??[1,1,1]);break;case"cone":n=y4(t.point,typeof e.radius=="number"?e.radius:.5,e.height??1);break;case"ellipsoid":n=x4(t.point,_4(e));break}return n*t.scale}function T4(r){let e=new Map;for(let n of r.primitives)e.set(n.id,i=>S4(i,n));let t=r.primitives.length>0?e.get(r.primitives[0].id):void 0;for(let n=0;n<(r.operations?.length??0);n+=1){let i=r.operations?.[n];if(!i)continue;let s=e.get(i.left),a=e.get(i.right);if(!s||!a)continue;let o;switch(i.type){case"smooth-union":o=l=>b4(s(l),a(l),i.radius??.1);break;case"subtract":o=l=>Math.max(s(l),-a(l));break;case"intersect":o=l=>Math.max(s(l),a(l));break}e.set(i.id??i.output??`operation-${n}`,o),t=o}return t??(()=>1/0)}function Cu(r){let e=Math.max(4,Math.min(64,Math.floor(r.resolution))),t={min:[-2,-2,-2],max:[2,2,2]},n=r.bounds??t,i=new E(n.min[0],n.min[1],n.min[2]),s=new E((n.max[0]-n.min[0])/e,(n.max[1]-n.min[1])/e,(n.max[2]-n.min[2])/e),a=T4(r),o=new E,l=e+1,c=new Float32Array(l*l*l),u=(M,w,T)=>(T*l+w)*l+M;for(let M=0;M<l;M+=1)for(let w=0;w<l;w+=1)for(let T=0;T<l;T+=1)o.set(i.x+T*s.x,i.y+w*s.y,i.z+M*s.z),c[u(T,w,M)]=a(o);let d=[[0,0,0,1,0,0],[1,0,0,1,1,0],[0,1,0,1,1,0],[0,0,0,0,1,0],[0,0,1,1,0,1],[1,0,1,1,1,1],[0,1,1,1,1,1],[0,0,1,0,1,1],[0,0,0,0,0,1],[1,0,0,1,0,1],[1,1,0,1,1,1],[0,1,0,0,1,1]],h=[],p=[],f=[],m=new Int32Array(e*e*e).fill(-1),y=(M,w,T)=>(T*e+w)*e+M,x=Math.min(s.x,s.y,s.z)*.25,b=M=>{let w=a(o.set(M.x+x,M.y,M.z))-a(o.set(M.x-x,M.y,M.z)),T=a(o.set(M.x,M.y+x,M.z))-a(o.set(M.x,M.y-x,M.z)),R=a(o.set(M.x,M.y,M.z+x))-a(o.set(M.x,M.y,M.z-x)),D=new E(w,T,R);return D.lengthSq()<1e-20?new E(0,1,0):D.normalize()};for(let M=0;M<e;M+=1)for(let w=0;w<e;w+=1)for(let T=0;T<e;T+=1){let R=0,D=0,L=0,B=0;for(let[j,ee,ge,fe,he,ye]of d){let ze=c[u(T+j,w+ee,M+ge)],Pe=c[u(T+fe,w+he,M+ye)];if(ze<=0==Pe<=0)continue;let ot=ze/(ze-Pe);D+=j+(fe-j)*ot,L+=ee+(he-ee)*ot,B+=ge+(ye-ge)*ot,R+=1}if(R===0)continue;let W=i.x+(T+D/R)*s.x,q=i.y+(w+L/R)*s.y,ce=i.z+(M+B/R)*s.z;m[y(T,w,M)]=h.length/3,h.push(W,q,ce);let k=b(new E(W,q,ce));p.push(k.x,k.y,k.z)}let _=(M,w,T,R,D)=>{M<0||w<0||T<0||R<0||(D?f.push(M,T,w,M,R,T):f.push(M,w,T,M,T,R))};for(let M=0;M<l;M+=1)for(let w=0;w<l;w+=1)for(let T=0;T<l;T+=1){let R=c[u(T,w,M)]<=0;T+1<l&&w>0&&M>0&&w<l-1&&M<l-1&&R!==c[u(T+1,w,M)]<=0&&_(m[y(T,w-1,M-1)],m[y(T,w,M-1)],m[y(T,w,M)],m[y(T,w-1,M)],!R),w+1<l&&T>0&&M>0&&T<l-1&&M<l-1&&R!==c[u(T,w+1,M)]<=0&&_(m[y(T-1,w,M-1)],m[y(T-1,w,M)],m[y(T,w,M)],m[y(T,w,M-1)],!R),M+1<l&&T>0&&w>0&&T<l-1&&w<l-1&&R!==c[u(T,w,M+1)]<=0&&_(m[y(T-1,w-1,M)],m[y(T,w-1,M)],m[y(T,w,M)],m[y(T-1,w,M)],!R)}let S=new on;return S.setAttribute("position",new Ve(h,3)),S.setAttribute("normal",new Ve(p,3)),S.setIndex(f),S.computeBoundingSphere(),S}function M4(r,e){let t=new So;if(r.length>0){t.moveTo(r[0][0],r[0][1]);for(let n=1;n<r.length;n+=1)t.lineTo(r[n][0],r[n][1])}for(let n of e??[]){if(n.length<3)continue;let i=new ba;i.moveTo(n[0][0],n[0][1]);for(let s=1;s<n.length;s+=1)i.lineTo(n[s][0],n[s][1]);i.closePath(),t.holes.push(i)}return t}function w4(r,e,t,n,i=24){let s=[];for(let a=0;a<i;a+=1){let o=a/i*Math.PI*2;s.push([r+Math.cos(o)*t,e+Math.sin(o)*n])}return s}function t0(r){let e=[...r.holes??[],...(r.ovalHoles??[]).map(n=>w4(n.cx,n.cy,n.rx,n.ry))],t=M4(r.points,e);return new rc(t,{depth:r.depth,bevelEnabled:!1,steps:1})}function n0(r){let e=r.points.map(([t,n])=>new O(Math.max(1e-4,t),n));return new ac(e,r.segments??24)}function bl(r){let e=r.points.map(([i,s,a])=>new E(i,s,a)),t=new vo(e,r.closed??!1),n=Math.max(8,r.points.length*6);return new oc(t,n,r.radius??.05,r.radialSegments??8,r.closed??!1)}function DC(r){let e=r.stations;if(e.length<2)throw new Error("tapered-sweep needs at least two stations");let t=Math.max(3,r.radialSegments??10),n=e.map(m=>new E(...m.position)),i=n.map((m,y)=>{let x=n[Math.max(0,y-1)],_=n[Math.min(n.length-1,y+1)].clone().sub(x);return _.lengthSq()<1e-12?new E(0,1,0):_.normalize()}),s=new E(0,0,1);Math.abs(i[0].dot(s))>.9&&(s=new E(1,0,0));let a=[],o=[],l=s.clone().sub(i[0].clone().multiplyScalar(s.dot(i[0]))).normalize();for(let m=0;m<i.length;m+=1){let y=i[m],x=l.clone().sub(y.clone().multiplyScalar(l.dot(y)));if(x.lengthSq()<1e-12){let b=Math.abs(y.y)>.9?new E(1,0,0):new E(0,1,0);x.copy(b.sub(y.clone().multiplyScalar(b.dot(y))))}x.normalize(),a.push(x),o.push(new E().crossVectors(y,x).normalize()),l=x}let c=[],u=[],d=[],h=[],p=[];for(let m=0;m<e.length;m+=1){let y=e[m],x=m/(e.length-1);if(h.push(c.length/3),y.rx<=1e-6&&y.rz<=1e-6){p.push(!0),c.push(n[m].x,n[m].y,n[m].z),u.push(.5,x);continue}p.push(!1);let b=(y.twist??0)*Math.PI/180;for(let _=0;_<=t;_+=1){let S=_/t*Math.PI*2+b,M=a[m].clone().multiplyScalar(Math.cos(S)*y.rx).add(o[m].clone().multiplyScalar(Math.sin(S)*y.rz)),w=n[m].clone().add(M);c.push(w.x,w.y,w.z),u.push(_/t,x)}}for(let m=0;m<e.length-1;m+=1){let y=h[m],x=h[m+1];if(!(p[m]&&p[m+1]))for(let b=0;b<t;b+=1)p[m]?d.push(y,x+b+1,x+b):p[m+1]?d.push(y+b,y+b+1,x):d.push(y+b,y+b+1,x+b,y+b+1,x+b+1,x+b)}if(r.capEnds??!0)for(let m of[0,e.length-1]){if(p[m])continue;let y=c.length/3;c.push(n[m].x,n[m].y,n[m].z),u.push(.5,m===0?0:1);let x=h[m];for(let b=0;b<t;b+=1)m===0?d.push(y,x+b+1,x+b):d.push(y,x+b,x+b+1)}let f=new on;return f.setAttribute("position",new Ve(c,3)),f.setAttribute("uv",new Ve(u,2)),f.setIndex(d),f.computeVertexNormals(),f}function E4(r){let e=2166136261;for(let t=0;t<r.length;t+=1)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function je(r,e,t){if(typeof r=="number")return r;if(r&&typeof r=="object"){let n=r;for(let i of e)if(typeof n[i]=="number")return n[i]}return t}function R4(r){let e=/^#[0-9a-f]{3}$/i.test(r)?"#"+r.slice(1).split("").map(n=>n+n).join(""):r,t=/^#[0-9a-f]{6}$/i.test(e)?Number.parseInt(e.slice(1),16):9075295;return[Nu(t>>16&255),Nu(t>>8&255),Nu(t&255)]}function A4(r){let e=r.colorVariation?.palette;if(Array.isArray(e)&&e.length>0)return e.filter(i=>typeof i=="string");let t=r.albedo?.secondary;return[r.baseColor??r.color??r.albedo?.dominant,...Array.isArray(t)?t:[]].filter(i=>typeof i=="string"&&i.startsWith("#"))}function Yt(r){return Math.max(0,Math.min(1,r))}function Nu(r){return Math.max(30,Math.min(240,Math.round(r)))}function C4(r){return Math.max(.02,Math.min(1,r))}function IC(r){return Math.max(1,Math.min(2.5,r))}function N4(r){return r>=.5?1:0}function P4(r){let e=typeof r.baseColor=="string"?r.baseColor:"#8A7A5F";return new me().setStyle(e,Vt)}function FC(r){return r*r*(3-2*r)}function i0(r,e,t,n,i){let s=(r%n+n)%n,a=(e%i+i)%i,o=Math.imul(s+t*17,374761393)^Math.imul(a+t*31,668265263);return o=Math.imul(o^o>>>13,1274126177),((o^o>>>16)>>>0)/4294967295}function D4(r,e,t,n,i){let s=r*n,a=e*i,o=Math.floor(s),l=Math.floor(a),c=FC(s-o),u=FC(a-l),d=i0(o,l,t,n,i),h=i0(o+1,l,t,n,i),p=i0(o,l+1,t,n,i),f=i0(o+1,l+1,t,n,i);return Dn.lerp(Dn.lerp(d,h,c),Dn.lerp(p,f,c),u)}function I4(r){let t=(Array.isArray(r.surfaceFrequencyBands)?r.surfaceFrequencyBands:[]).flatMap(n=>{if(!n||typeof n!="object")return[];let i=n,s=typeof i.frequency=="number"?i.frequency:0,a=typeof i.amplitude=="number"?i.amplitude:0;if(s<=0||a<=0)return[];let o=Array.isArray(i.stretch)?i.stretch:[1,1],l=`${String(i.pattern??"")} ${String(i.role??"")}`.toLowerCase();return[{frequency:s,amplitude:a,stretchX:typeof o[0]=="number"?Math.max(.1,o[0]):1,stretchY:typeof o[1]=="number"?Math.max(.1,o[1]):1,ridge:/(ridge|groove|grain|fiber|striated|crack)/.test(l)}]});return t.length>0?t:[{frequency:2,amplitude:.42,stretchX:1,stretchY:1,ridge:!1},{frequency:12,amplitude:.22,stretchX:1,stretchY:1,ridge:!1},{frequency:56,amplitude:.08,stretchX:1,stretchY:1,ridge:!1}]}function ST(r,e,t,n){let i=0,s=0;for(let a=0;a<t.length;a+=1){let o=t[a],l=Math.max(1,Math.round(o.frequency*o.stretchX)),c=Math.max(1,Math.round(o.frequency*o.stretchY)),u=D4(r,e,n+a*1013,l,c);o.ridge&&(u=1-Math.abs(u*2-1)),i+=u*o.amplitude,s+=o.amplitude}return s>0?Yt(i/s):.5}function F4(r,e){if(r.length===1)return r[0];let t=Yt(e)*(r.length-1),n=Math.min(r.length-2,Math.floor(t)),i=t-n,s=r[n],a=r[n+1];return[Math.round(Dn.lerp(s[0],a[0],i)),Math.round(Dn.lerp(s[1],a[1],i)),Math.round(Dn.lerp(s[2],a[2],i))]}function LC(r){let e=/rgba?(s*(d+)s*,s*(d+)s*,s*(d+)/.exec(r);return e?[Nu(Number(e[1])),Nu(Number(e[2])),Nu(Number(e[3]))]:[138,122,95]}function L4(r,e,t){let n=r.stops.length>=2?r.stops:[{offset:0,color:"rgba(138,122,95,1)"},{offset:1,color:"rgba(138,122,95,1)"}],i;if(r.type==="radial"){let[u,d]=r.axis,h=e-u,p=t-d,f=Math.max(.001,Math.hypot(Math.max(u,1-u),Math.max(d,1-d)));i=Yt(Math.hypot(h,p)/f)}else{let[u,d]=r.axis,h=(e-.5)*u+(t-.5)*d,p=.5*(Math.abs(u)+Math.abs(d))||.5;i=Yt(h/p+.5)}let s=i*(n.length-1),a=Math.min(n.length-2,Math.max(0,Math.floor(s))),o=s-a,l=LC(n[a].color),c=LC(n[a+1].color);return[Dn.lerp(l[0],c[0],o),Dn.lerp(l[1],c[1],o),Dn.lerp(l[2],c[2],o)]}function cp(r,e,t,n,i){r[e]=Math.max(0,Math.min(255,Math.round(t))),r[e+1]=Math.max(0,Math.min(255,Math.round(n))),r[e+2]=Math.max(0,Math.min(255,Math.round(i))),r[e+3]=255}function up(r){let e=document.createElement("canvas");return e.width=r,e.height=r,e}function dp(r,e,t,n){let i=new _a(r),s=t.textureProjection&&typeof t.textureProjection=="object"?t.textureProjection:{},a=Array.isArray(s.repeat)?s.repeat:[2,2];return i.colorSpace=e,i.wrapS=Ei,i.wrapT=Ei,i.repeat.set(typeof a[0]=="number"?a[0]:2,typeof a[1]=="number"?a[1]:2),i.anisotropy=Math.max(1,Math.round(n.textureAnisotropy??s.anisotropy??8)),i.needsUpdate=!0,i}function hp(r,e){let t=r.referencePbr;if(!t||typeof t!="object"||t.usable===!1)return null;let n=typeof t.confidence=="number"?t.confidence:typeof t.estimatedFidelity=="number"?t.estimatedFidelity:0,i=typeof t.targetThreshold=="number"?t.targetThreshold:.7;if(n<i)return null;let s=t.maps;if(!s||typeof s!="object")return null;let a=s[e];if(!a||typeof a!="object")return null;let o=a,l=typeof o.url=="string"&&o.url.trim()?o.url:o.path;return typeof l=="string"&&l.trim()?l:null}function pp(r,e,t,n){let i=new cc().load(r),s=t.textureProjection&&typeof t.textureProjection=="object"?t.textureProjection:{},a=Array.isArray(s.repeat)?s.repeat:[1,1];return i.colorSpace=e,i.wrapS=Ei,i.wrapT=Ei,i.repeat.set(typeof a[0]=="number"?a[0]:1,typeof a[1]=="number"?a[1]:1),i.anisotropy=Math.max(1,Math.round(n.textureAnisotropy??s.anisotropy??8)),i.needsUpdate=!0,i}function B4(r,e){let t=hp(r,"albedo"),n=hp(r,"roughness"),i=hp(r,"height"),s=hp(r,"normal"),a=hp(r,"ao");return!t||!n||!i||!s||!a?null:{albedo:pp(t,Vt,r,e),roughness:pp(n,cn,r,e),height:pp(i,cn,r,e),normal:pp(s,cn,r,e),ao:pp(a,cn,r,e),source:"reference-pixel-extraction"}}function U4(r,e,t){if(typeof document>"u")return null;let n=(t.qualityPriority??"reference-fidelity")==="reference-fidelity",i=t.textureSize??e.textureResolution,s=typeof i=="number"&&Number.isFinite(i)?i:n?1024:512,a=Math.max(256,Math.min(2048,2**Math.round(Math.log2(s)))),o={albedo:up(a),roughness:up(a),height:up(a),normal:up(a),ao:up(a)},l={albedo:o.albedo.getContext("2d"),roughness:o.roughness.getContext("2d"),height:o.height.getContext("2d"),normal:o.normal.getContext("2d"),ao:o.ao.getContext("2d")};if(!l.albedo||!l.roughness||!l.height||!l.normal||!l.ao)return null;let c={albedo:l.albedo.createImageData(a,a),roughness:l.roughness.createImageData(a,a),height:l.height.createImageData(a,a),normal:l.normal.createImageData(a,a),ao:l.ao.createImageData(a,a)},u=E4(r),d=I4(e),h=new Float32Array(a*a),p=new Float32Array(a*a),f=A4(e),m=typeof e.baseColor=="string"?e.baseColor:"#8A7A5F",y=(f.length>=2?f:[m,"#6E614B","#A08F70"]).map(R4),x=Yt(je(e.roughness,["base"],.76)),b=Yt(je(e.roughness,["variation"],.18)),_=Yt(je(e.colorVariation,["amplitude","variation"],.18)),S=Yt(je(e.colorVariation,["heightCorrelation"],.3)),M=e.colorGradient;for(let R=0;R<a;R+=1){let D=R/a;for(let L=0;L<a;L+=1){let B=L/a,W=R*a+L,q=ST(B,D,d,u+101),ce=ST(B,D,d,u+7001),k=ST(B,D,d,u+15013);h[W]=q,p[W]=Yt(x+(ce-.5)*b*2);let j;if(M)j=L4(M,B,D);else{let ee=Yt(.5+(k-.5)*_*2+(q-.5)*S);j=F4(y,ee)}cp(c.albedo.data,W*4,j[0],j[1],j[2])}}let w=Math.max(.05,je(e.normal,["strength","amplitude"],.35)),T=Yt(je(e.ambientOcclusion,["cavityStrength","strength"],.35));for(let R=0;R<a;R+=1){let D=(R-1+a)%a*a,L=(R+1)%a*a;for(let B=0;B<a;B+=1){let W=(B-1+a)%a,q=(B+1)%a,ce=R*a+B,k=h[ce],j=(h[R*a+q]-h[R*a+W])*w*6,ee=(h[L+B]-h[D+B])*w*6,ge=1/Math.sqrt(j*j+ee*ee+1),fe=-j*ge,he=-ee*ge,ye=ge,ze=(h[R*a+W]+h[R*a+q]+h[D+B]+h[L+B])*.25,Pe=Math.max(0,ze-k),ot=Yt(1-T*(Pe*12+(1-k)*.16)),Se=ce*4,Je=k*255,lt=p[ce]*255;cp(c.height.data,Se,Je,Je,Je),cp(c.roughness.data,Se,lt,lt,lt),cp(c.normal.data,Se,(fe*.5+.5)*255,(he*.5+.5)*255,(ye*.5+.5)*255),cp(c.ao.data,Se,ot*255,ot*255,ot*255)}}return l.albedo.putImageData(c.albedo,0,0),l.roughness.putImageData(c.roughness,0,0),l.height.putImageData(c.height,0,0),l.normal.putImageData(c.normal,0,0),l.ao.putImageData(c.ao,0,0),{albedo:dp(o.albedo,Vt,e,t),roughness:dp(o.roughness,cn,e,t),height:dp(o.height,cn,e,t),normal:dp(o.normal,cn,e,t),ao:dp(o.ao,cn,e,t),source:"procedural"}}function ao(r,e,t,n=!1){let s=e.textureless?.declared===!0?null:B4(e,t)??U4(r,e,t),a=new Mo({color:s?16777215:P4(e),roughness:s?1:Yt(je(e.roughness,["base"],.76)),metalness:N4(je(e.metalness,["base"],0)),clearcoat:Yt(je(e.clearcoat,["base","amount"],0)),clearcoatRoughness:Yt(je(e.clearcoatRoughness,["base"],.25)),transmission:Yt(je(e.transmission,["base","amount"],0)),ior:IC(je(e.ior,["base","value"],1.5)),thickness:Math.max(0,je(e.thickness,["base","amount"],0)),attenuationDistance:Math.max(.001,je(e.attenuationDistance,["base","value"],1/0)),attenuationColor:new me(typeof e.attenuationColor=="string"?e.attenuationColor:"#ffffff"),sheen:Yt(je(e.sheen,["base","amount"],0)),sheenColor:new me(typeof e.sheenColor=="string"?e.sheenColor:"#ffffff"),sheenRoughness:Yt(je(e.sheenRoughness,["base"],1)),iridescence:Yt(je(e.iridescence,["base","amount"],0)),iridescenceIOR:IC(je(e.iridescenceIOR,["base","value"],1.3)),anisotropy:Yt(je(e.anisotropy,["base","amount"],0)),anisotropyRotation:je(e.anisotropy,["rotation"],0),specularIntensity:C4(je(e.specularF0??e.f0??e.specularIntensity,["base","value"],1)),specularColor:new me(typeof e.specularColor=="string"?e.specularColor:"#ffffff"),emissive:new me(typeof e.emissive=="string"?e.emissive:"#000000"),emissiveIntensity:Math.max(0,je(e.emissiveIntensity,["base"],1)),opacity:Yt(je(e.opacity,["base"],1)),transparent:je(e.transmission,["base","amount"],0)>0||je(e.opacity,["base"],1)<1,alphaTest:Math.max(0,je(e.alpha,["cutoff","alphaTest"],0)),wireframe:t.wireframe??!1,side:e.doubleSided===!0?Ri:oi,flatShading:e.flatShading===!0});if(s){a.map=s.albedo,a.roughnessMap=s.roughness,a.normalMap=s.normal,a.normalScale.setScalar(Math.max(.05,je(e.normal,["strength","amplitude"],.35))),a.aoMap=s.ao,a.aoMap.channel=0,a.aoMapIntensity=je(e.ambientOcclusion,["cavityStrength","strength"],.35);let o=n||e.denseMesh===!0||e.geometryDensity==="dense"||e.topologyClass==="dense",l=Math.max(0,je(e.bump,["amplitude","strength"],0)),c=o?Math.max(.05,l):l;c>0&&(a.bumpMap=s.height,a.bumpScale=c);let u=Math.max(0,je(e.displacement,["amplitude","strength"],0)),d=o?Math.max(.005,u):u;d>0&&(a.displacementMap=s.height,a.displacementScale=d,a.displacementBias=-d*.5)}return a.envMapIntensity=je(e,["envMapIntensity"],.8),a.userData.sculptMaterial=e,a.userData.proceduralMapsIndependent=!0,a.userData.pbrConstraints={albedoRange:[30,240],binaryMetalness:!0,f0Range:[.02,1],iorRange:[1,2.5]},a.userData.pbrTextureSource=s?.source??"flat-fallback",a.userData.referencePbr=e.referencePbr??null,a.userData.referenceMaterialId=e.referenceMaterialId??e.materialReference?.profileId??null,a.userData.materialEvidence=e.materialEvidence??null,a.userData.validationViews=e.materialReference?.validationViews??[],a.needsUpdate=!0,a}function BC(r,e){return Array.isArray(r)&&r.length===3&&r.every(t=>typeof t=="number")?new E(r[0],r[1],r[2]):new E(e[0],e[1],e[2])}function UC(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function Lt(r){if(!r||typeof r!="object")return null;let e=r,t=BC(e.localStart,[0,0,0]),i=BC(e.localEnd,[0,1,0]).clone().sub(t),s=i.length();if(s<=1e-4)return null;let a=i.clone().normalize(),o=new fn().setFromUnitVectors(new E(0,1,0),a),l=Math.max(.005,UC(e.baseRadius,.06)),c=Math.max(.003,UC(e.endRadius,l*.55));return{start:t,midpoint:i.multiplyScalar(.5),quaternion:o,length:s,baseRadius:l,endRadius:c}}function OC(r={}){let e=new He;e.name="Hannya Mask",e.userData.reconstructionEvidence={itemFamily:null,subtype:null,componentAdapter:null,route:null,exactnessTier:null,referenceCamera:{solved:!1,fovDegrees:40,aspect:1,orientation:{yaw:0,pitch:0,roll:0},positionHint:[0,0,3],note:"For likeness work, solve the reference camera (forge/stage1_intake/solve_camera_pose.py) so the review render aligns with the photo and the reference can be projected. Confirm by overlay review."},approximationNotes:[]},e.userData.materialPipeline={},e.userData.materialReferenceRegistry=null;let t={};t["clay-shell"]=ao("clay-shell",{id:"clay-shell",name:"Mask shell clay",type:"standard",shaderModel:"MeshStandardMaterial / PBR approximation",baseColor:"#B9B6B2",color:"#B9B6B2",albedo:{dominant:"#B9B6B2",secondary:["#A8A5A1","#C6C3BF"],samplingNotes:"Reference is an achromatic clay preview: single flat albedo; all tonal variation in the reference is lighting."},colorVariation:{palette:["#B9B6B2"],pattern:"none",amplitude:0,heightCorrelation:0},metalness:0,roughness:{base:.88,variation:.04,map:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_roughness.png (extracted; near-uniform matte, no specular lobe in the reference)"},textureResolution:1024,textureProjection:{mode:"uv",repeat:[1,1],anisotropy:4,texelDensityIntent:"flat albedo; no texture detail exists in the reference"},surfaceFrequencyBands:[{id:"macro",frequency:1,amplitude:.01,role:"none u2014 flat clay"},{id:"meso",frequency:4,amplitude:.01,role:"none"},{id:"micro",frequency:16,amplitude:.02,role:"faint matte breakup"}],localOverrides:[{id:"cavity-ao",region:"eye apertures' inner walls, mouth interior, nostril cavities, ear conchae, the shell interior seen through the rear opening",dirtAmount:0,cavityBias:!0,streak:!1,roughness:.92,aoDarken:.45,notes:"no dirt/wear exists on the pristine clay reference; the only regional response is cavity occlusion darkening"}],notes:"Geometry-only reconstruction: the consuming sandbox replaces materials wholesale.",ambientOcclusion:{source:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_ao.png",response:"cavity-only: concave regions (eye sockets, mouth, nostrils, concha) darken; convex crests stay open",intensity:.6},referencePbr:{version:"1",sourceImage:"/Users/dmitriy/new-10/.img2threejs/detail-inventory/zone-r1c1.png",extractor:"forge/stage1_intake/extract_pbr_evidence.py",method:"single-image statistical inversion on a reference crop",verdict:"usable",usable:!0,confidence:.742,estimatedFidelity:.742,targetThreshold:.7,hardLimit:"single-image inverse rendering is an estimate; the reference is an untextured clay preview, so this evidence proves the CLAY look the harness renders are compared against, not a production finish",maps:{albedo:{path:"/.img2threejs/pbr/clay-shell_albedo.png",channel:"albedo"},roughness:{path:"/.img2threejs/pbr/clay-shell_roughness.png",channel:"roughness"},height:{path:"/.img2threejs/pbr/clay-shell_height.png",channel:"height"},normal:{path:"/.img2threejs/pbr/clay-shell_normal.png",channel:"normal"},ao:{path:"/.img2threejs/pbr/clay-shell_ao.png",channel:"ao"}}}},r),t.dentition=ao("dentition",{id:"dentition",name:"Fangs and incisors",type:"standard",shaderModel:"MeshStandardMaterial / PBR approximation",baseColor:"#CBC8C3",color:"#CBC8C3",albedo:{dominant:"#CBC8C3",secondary:["#B9B6B2"],samplingNotes:"Teeth read one value step lighter than the shell in the front/below views."},colorVariation:{palette:["#CBC8C3"],pattern:"none",amplitude:0,heightCorrelation:0},metalness:0,roughness:{base:.78,variation:.03,map:"/Users/dmitriy/new-10/.img2threejs/pbr/dentition_roughness.png (extracted; near-uniform matte, no specular lobe in the reference)"},textureResolution:1024,textureProjection:{mode:"uv",repeat:[1,1],anisotropy:2,texelDensityIntent:"flat"},surfaceFrequencyBands:[{id:"macro",frequency:1,amplitude:.01,role:"none"},{id:"meso",frequency:4,amplitude:.01,role:"none"},{id:"micro",frequency:16,amplitude:.01,role:"none"}],localOverrides:[{id:"gumline-ao",region:"tooth roots where the incisor comb meets the gum bar and fang bases meet the lips",dirtAmount:0,cavityBias:!0,streak:!1,roughness:.82,aoDarken:.3,notes:"crevice darkening at the dentition roots, visible in the below view"}],notes:"Slightly lighter and less rough than the shell clay.",ambientOcclusion:{source:"/Users/dmitriy/new-10/.img2threejs/pbr/dentition_ao.png",response:"cavity-only: concave regions (eye sockets, mouth, nostrils, concha) darken; convex crests stay open",intensity:.6},referencePbr:{version:"1",sourceImage:"/Users/dmitriy/new-10/.img2threejs/detail-inventory/zone-r2c1.png",extractor:"forge/stage1_intake/extract_pbr_evidence.py",method:"single-image statistical inversion on a reference crop",verdict:"usable",usable:!0,confidence:.72,estimatedFidelity:.72,targetThreshold:.7,hardLimit:"single-image inverse rendering is an estimate; the reference is an untextured clay preview, so this evidence proves the CLAY look the harness renders are compared against, not a production finish",maps:{albedo:{path:"/.img2threejs/pbr/dentition_albedo.png",channel:"albedo"},roughness:{path:"/.img2threejs/pbr/dentition_roughness.png",channel:"roughness"},height:{path:"/.img2threejs/pbr/dentition_height.png",channel:"height"},normal:{path:"/.img2threejs/pbr/dentition_normal.png",channel:"normal"},ao:{path:"/.img2threejs/pbr/dentition_ao.png",channel:"ao"}}}},r);let n={root:e},i={},s={},a={},o={},l=Lt(null),c=new He;c.name="Hollow face shell__pivot",c.scale.set(1,1,1),l?(c.position.copy(l.start),c.rotation.set(0,0,0)):(c.position.set(0,0,0),c.rotation.set(0,0,0)),c.userData.sculptComponent={id:"mask-shell",name:"Hollow face shell",level:"macro",role:"body",importance:1,confidence:.9,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Hollow shell whose OUTER envelope is fitted to the reference silhouettes (front IoU 0.900, top 0.852) rather than authored by eye; inner offset gives the wall, eye and mouth apertures are subtracted through it at measured positions.",geometryDescriptor:{topologyIntent:"A thin conforming shell u2014 front half of a head, open posteriorly u2014 built as an implicit field: outer egg (cranium+jaw+brow bulk) minus an inset inner egg gives the wall; eye and mouth apertures are subtracted THROUGH the wall so daylight passes (rear view evidence).",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"cranium",type:"ellipsoid",center:[0,.1595,.105],radii:[.4307,.5531,.4706]},{id:"jaw",type:"ellipsoid",center:[0,-.3772,.081],radii:[.3906,.4803,.3375]},{id:"brow",type:"ellipsoid",center:[0,.12,.14],radii:[.4504,.3,.24]},{id:"inCran",type:"ellipsoid",center:[0,.1595,.0675],radii:[.3557,.4781,.3956]},{id:"inJaw",type:"ellipsoid",center:[0,-.3772,.0435],radii:[.3156,.4053,.2625]},{id:"eyeL",type:"ellipsoid",center:[.233,-.038,.42],radii:[.183,.102,.45],transform:{rotation:[0,0,.2]}},{id:"eyeR",type:"ellipsoid",center:[-.233,-.038,.42],radii:[.183,.102,.45],transform:{rotation:[0,0,-.2]}},{id:"mouth",type:"ellipsoid",center:[0,-.635,.34],radii:[.268,.096,.42]},{id:"mouthCL",type:"ellipsoid",center:[.2198,-.58,.32],radii:[.1,.075,.4]},{id:"mouthCR",type:"ellipsoid",center:[-.2198,-.58,.32],radii:[.1,.075,.4]}],operations:[{id:"o1",type:"smooth-union",left:"cranium",right:"jaw",radius:.18},{id:"outer",type:"smooth-union",left:"o1",right:"brow",radius:.14},{id:"inner",type:"smooth-union",left:"inCran",right:"inJaw",radius:.18},{id:"wall",type:"subtract",left:"outer",right:"inner"},{id:"m1",type:"smooth-union",left:"mouth",right:"mouthCL",radius:.05},{id:"m2",type:"smooth-union",left:"m1",right:"mouthCR",radius:.05},{id:"c1",type:"subtract",left:"wall",right:"eyeL"},{id:"c2",type:"subtract",left:"c1",right:"eyeR"},{id:"final",type:"subtract",left:"c2",right:"m2"}],resolution:64,bounds:{min:[-.7,-.92,-.42],max:[.7,.78,.62]}}},parent:null,attachment:null,dimensions:{width:.861,height:1.57,depth:1.04,units:"relative",confidence:.9},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"root",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"eye-aperture-l",kind:"hole",description:"Left almond through-cut, outer canthus raised (+0.22 rad cant)",evidenceRegion:"front"},{id:"eye-aperture-r",kind:"hole",description:"Right almond through-cut u2014 reflection of eye-aperture-l",evidenceRegion:"front"},{id:"mouth-aperture",kind:"hole",description:"Wide grimace through-cut, corners raised",evidenceRegion:"front"},{id:"glabella-facet",kind:"bevel",description:"Flat faceted plane between the brows, hard creases (carried by glabella-plate)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","rear","profile"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},c.userData.actionProfile={animationRole:"root",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n.root??e).add(c),n["mask-shell"]=c;let u=Cu({primitives:[{id:"cranium",type:"ellipsoid",center:[0,.1595,.105],radii:[.4307,.5531,.4706]},{id:"jaw",type:"ellipsoid",center:[0,-.3772,.081],radii:[.3906,.4803,.3375]},{id:"brow",type:"ellipsoid",center:[0,.12,.14],radii:[.4504,.3,.24]},{id:"inCran",type:"ellipsoid",center:[0,.1595,.0675],radii:[.3557,.4781,.3956]},{id:"inJaw",type:"ellipsoid",center:[0,-.3772,.0435],radii:[.3156,.4053,.2625]},{id:"eyeL",type:"ellipsoid",center:[.233,-.038,.42],radii:[.183,.102,.45],transform:{rotation:[0,0,.2]}},{id:"eyeR",type:"ellipsoid",center:[-.233,-.038,.42],radii:[.183,.102,.45],transform:{rotation:[0,0,-.2]}},{id:"mouth",type:"ellipsoid",center:[0,-.635,.34],radii:[.268,.096,.42]},{id:"mouthCL",type:"ellipsoid",center:[.2198,-.58,.32],radii:[.1,.075,.4]},{id:"mouthCR",type:"ellipsoid",center:[-.2198,-.58,.32],radii:[.1,.075,.4]}],operations:[{id:"o1",type:"smooth-union",left:"cranium",right:"jaw",radius:.18},{id:"outer",type:"smooth-union",left:"o1",right:"brow",radius:.14},{id:"inner",type:"smooth-union",left:"inCran",right:"inJaw",radius:.18},{id:"wall",type:"subtract",left:"outer",right:"inner"},{id:"m1",type:"smooth-union",left:"mouth",right:"mouthCL",radius:.05},{id:"m2",type:"smooth-union",left:"m1",right:"mouthCR",radius:.05},{id:"c1",type:"subtract",left:"wall",right:"eyeL"},{id:"c2",type:"subtract",left:"c1",right:"eyeR"},{id:"final",type:"subtract",left:"c2",right:"m2"}],resolution:64,bounds:{min:[-.7,-.92,-.42],max:[.7,.78,.62]}});l||u.scale(1,1,1);let d=new De(u,ao("clay-shell",{id:"clay-shell",name:"Mask shell clay",type:"standard",shaderModel:"MeshStandardMaterial / PBR approximation",baseColor:"#B9B6B2",color:"#B9B6B2",albedo:{dominant:"#B9B6B2",secondary:["#A8A5A1","#C6C3BF"],samplingNotes:"Reference is an achromatic clay preview: single flat albedo; all tonal variation in the reference is lighting."},colorVariation:{palette:["#B9B6B2"],pattern:"none",amplitude:0,heightCorrelation:0},metalness:0,roughness:{base:.88,variation:.04,map:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_roughness.png (extracted; near-uniform matte, no specular lobe in the reference)"},textureResolution:1024,textureProjection:{mode:"uv",repeat:[1,1],anisotropy:4,texelDensityIntent:"flat albedo; no texture detail exists in the reference"},surfaceFrequencyBands:[{id:"macro",frequency:1,amplitude:.01,role:"none u2014 flat clay"},{id:"meso",frequency:4,amplitude:.01,role:"none"},{id:"micro",frequency:16,amplitude:.02,role:"faint matte breakup"}],localOverrides:[{id:"cavity-ao",region:"eye apertures' inner walls, mouth interior, nostril cavities, ear conchae, the shell interior seen through the rear opening",dirtAmount:0,cavityBias:!0,streak:!1,roughness:.92,aoDarken:.45,notes:"no dirt/wear exists on the pristine clay reference; the only regional response is cavity occlusion darkening"}],notes:"Geometry-only reconstruction: the consuming sandbox replaces materials wholesale.",ambientOcclusion:{source:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_ao.png",response:"cavity-only: concave regions (eye sockets, mouth, nostrils, concha) darken; convex crests stay open",intensity:.6},referencePbr:{version:"1",sourceImage:"/Users/dmitriy/new-10/.img2threejs/detail-inventory/zone-r1c1.png",extractor:"forge/stage1_intake/extract_pbr_evidence.py",method:"single-image statistical inversion on a reference crop",verdict:"usable",usable:!0,confidence:.742,estimatedFidelity:.742,targetThreshold:.7,hardLimit:"single-image inverse rendering is an estimate; the reference is an untextured clay preview, so this evidence proves the CLAY look the harness renders are compared against, not a production finish",maps:{albedo:{path:"/.img2threejs/pbr/clay-shell_albedo.png",channel:"albedo"},roughness:{path:"/.img2threejs/pbr/clay-shell_roughness.png",channel:"roughness"},height:{path:"/.img2threejs/pbr/clay-shell_height.png",channel:"height"},normal:{path:"/.img2threejs/pbr/clay-shell_normal.png",channel:"normal"},ao:{path:"/.img2threejs/pbr/clay-shell_ao.png",channel:"ao"}}}},r,!0));d.name="Hollow face shell",l&&(d.position.copy(l.midpoint),d.quaternion.copy(l.quaternion)),d.castShadow=r.castShadow??!0,d.receiveShadow=r.receiveShadow??!0,d.userData.sculptComponent={id:"mask-shell",name:"Hollow face shell",level:"macro",role:"body",importance:1,confidence:.9,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Hollow shell whose OUTER envelope is fitted to the reference silhouettes (front IoU 0.900, top 0.852) rather than authored by eye; inner offset gives the wall, eye and mouth apertures are subtracted through it at measured positions.",geometryDescriptor:{topologyIntent:"A thin conforming shell u2014 front half of a head, open posteriorly u2014 built as an implicit field: outer egg (cranium+jaw+brow bulk) minus an inset inner egg gives the wall; eye and mouth apertures are subtracted THROUGH the wall so daylight passes (rear view evidence).",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"cranium",type:"ellipsoid",center:[0,.1595,.105],radii:[.4307,.5531,.4706]},{id:"jaw",type:"ellipsoid",center:[0,-.3772,.081],radii:[.3906,.4803,.3375]},{id:"brow",type:"ellipsoid",center:[0,.12,.14],radii:[.4504,.3,.24]},{id:"inCran",type:"ellipsoid",center:[0,.1595,.0675],radii:[.3557,.4781,.3956]},{id:"inJaw",type:"ellipsoid",center:[0,-.3772,.0435],radii:[.3156,.4053,.2625]},{id:"eyeL",type:"ellipsoid",center:[.233,-.038,.42],radii:[.183,.102,.45],transform:{rotation:[0,0,.2]}},{id:"eyeR",type:"ellipsoid",center:[-.233,-.038,.42],radii:[.183,.102,.45],transform:{rotation:[0,0,-.2]}},{id:"mouth",type:"ellipsoid",center:[0,-.635,.34],radii:[.268,.096,.42]},{id:"mouthCL",type:"ellipsoid",center:[.2198,-.58,.32],radii:[.1,.075,.4]},{id:"mouthCR",type:"ellipsoid",center:[-.2198,-.58,.32],radii:[.1,.075,.4]}],operations:[{id:"o1",type:"smooth-union",left:"cranium",right:"jaw",radius:.18},{id:"outer",type:"smooth-union",left:"o1",right:"brow",radius:.14},{id:"inner",type:"smooth-union",left:"inCran",right:"inJaw",radius:.18},{id:"wall",type:"subtract",left:"outer",right:"inner"},{id:"m1",type:"smooth-union",left:"mouth",right:"mouthCL",radius:.05},{id:"m2",type:"smooth-union",left:"m1",right:"mouthCR",radius:.05},{id:"c1",type:"subtract",left:"wall",right:"eyeL"},{id:"c2",type:"subtract",left:"c1",right:"eyeR"},{id:"final",type:"subtract",left:"c2",right:"m2"}],resolution:64,bounds:{min:[-.7,-.92,-.42],max:[.7,.78,.62]}}},parent:null,attachment:null,dimensions:{width:.861,height:1.57,depth:1.04,units:"relative",confidence:.9},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"root",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"eye-aperture-l",kind:"hole",description:"Left almond through-cut, outer canthus raised (+0.22 rad cant)",evidenceRegion:"front"},{id:"eye-aperture-r",kind:"hole",description:"Right almond through-cut u2014 reflection of eye-aperture-l",evidenceRegion:"front"},{id:"mouth-aperture",kind:"hole",description:"Wide grimace through-cut, corners raised",evidenceRegion:"front"},{id:"glabella-facet",kind:"bevel",description:"Flat faceted plane between the brows, hard creases (carried by glabella-plate)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","rear","profile"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},c.add(d),i["mask-shell"]=d,a["mask-shell"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(c);let h=Lt(null),p=new He;p.name="Horn (left)__pivot",p.scale.set(1,1,1),h?(p.position.copy(h.start),p.rotation.set(0,0,0)):(p.position.set(0,0,0),p.rotation.set(0,0,0)),p.userData.sculptComponent={id:"horn-l",name:"Horn (left)",level:"macro",role:"appendage",importance:.95,confidence:.9,primitive:"tapered-sweep",topologyClass:"continuous-sculpt",topologyRationale:"Swept blade, not a cone: base radius 0.196, taper 0.99, cross-section flattened to 0.50 of its width. Root, control and tip fitted against the horn-only band of the front reference (rows 0-20, where the skull is absent) plus the top view u2014 IoU 0.005 -> 0.855.",geometryDescriptor:{topologyIntent:"A swept 3D arc, not a cone: rises and splays laterally (front), leans posteriorly at mid-arc (profile, z dips to -0.10), tip recovers anteriorly (top view, z ends +0.10). Monotonic taper to a true point.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",taperedSweep:{stations:[{position:[.3781,.1602,.063],rx:.1958,rz:.0977,twist:0},{position:[.4676,.274,.0391],rx:.1743,rz:.0869,twist:0},{position:[.5493,.3822,.0155],rx:.1527,rz:.0761,twist:0},{position:[.6231,.4848,-.0078],rx:.131,rz:.0653,twist:0},{position:[.6891,.5818,-.0307],rx:.1094,rz:.0546,twist:0},{position:[.7471,.6732,-.0533],rx:.0877,rz:.0437,twist:0},{position:[.7973,.759,-.0756],rx:.0659,rz:.0329,twist:0},{position:[.8397,.8392,-.0976],rx:.0441,rz:.022,twist:0},{position:[.8742,.9138,-.1193],rx:.0222,rz:.0111,twist:0},{position:[.9008,.9827,-.1406],rx:0,rz:0,twist:0}],radialSegments:14,capEnds:!0}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"horn-socket-l",localStart:[.3781,.1602,.063],localEnd:[.9008,.9827,-.1406],contactType:"socket",embedDepth:.06,overlap:.06,gapTolerance:.01,contactNormal:[.45,.85,.1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"horn-collar-l",kind:"seam",description:"Raised collar ring where the horn seats into the cranium (socket seam, geometry carried by horn-collar-ring-l)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","profile","top"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},p.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(p),n["horn-l"]=p;let f=h?new Pt(h.endRadius,h.baseRadius,h.length,32,12):DC({stations:[{position:[.3781,.1602,.063],rx:.1958,rz:.0977,twist:0},{position:[.4676,.274,.0391],rx:.1743,rz:.0869,twist:0},{position:[.5493,.3822,.0155],rx:.1527,rz:.0761,twist:0},{position:[.6231,.4848,-.0078],rx:.131,rz:.0653,twist:0},{position:[.6891,.5818,-.0307],rx:.1094,rz:.0546,twist:0},{position:[.7471,.6732,-.0533],rx:.0877,rz:.0437,twist:0},{position:[.7973,.759,-.0756],rx:.0659,rz:.0329,twist:0},{position:[.8397,.8392,-.0976],rx:.0441,rz:.022,twist:0},{position:[.8742,.9138,-.1193],rx:.0222,rz:.0111,twist:0},{position:[.9008,.9827,-.1406],rx:0,rz:0,twist:0}],radialSegments:14,capEnds:!0});h||f.scale(1,1,1);let m=new De(f,t["clay-shell"]??new Et({color:8947848}));m.name="Horn (left)",h&&(m.position.copy(h.midpoint),m.quaternion.copy(h.quaternion)),m.castShadow=r.castShadow??!0,m.receiveShadow=r.receiveShadow??!0,m.userData.sculptComponent={id:"horn-l",name:"Horn (left)",level:"macro",role:"appendage",importance:.95,confidence:.9,primitive:"tapered-sweep",topologyClass:"continuous-sculpt",topologyRationale:"Swept blade, not a cone: base radius 0.196, taper 0.99, cross-section flattened to 0.50 of its width. Root, control and tip fitted against the horn-only band of the front reference (rows 0-20, where the skull is absent) plus the top view u2014 IoU 0.005 -> 0.855.",geometryDescriptor:{topologyIntent:"A swept 3D arc, not a cone: rises and splays laterally (front), leans posteriorly at mid-arc (profile, z dips to -0.10), tip recovers anteriorly (top view, z ends +0.10). Monotonic taper to a true point.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",taperedSweep:{stations:[{position:[.3781,.1602,.063],rx:.1958,rz:.0977,twist:0},{position:[.4676,.274,.0391],rx:.1743,rz:.0869,twist:0},{position:[.5493,.3822,.0155],rx:.1527,rz:.0761,twist:0},{position:[.6231,.4848,-.0078],rx:.131,rz:.0653,twist:0},{position:[.6891,.5818,-.0307],rx:.1094,rz:.0546,twist:0},{position:[.7471,.6732,-.0533],rx:.0877,rz:.0437,twist:0},{position:[.7973,.759,-.0756],rx:.0659,rz:.0329,twist:0},{position:[.8397,.8392,-.0976],rx:.0441,rz:.022,twist:0},{position:[.8742,.9138,-.1193],rx:.0222,rz:.0111,twist:0},{position:[.9008,.9827,-.1406],rx:0,rz:0,twist:0}],radialSegments:14,capEnds:!0}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"horn-socket-l",localStart:[.3781,.1602,.063],localEnd:[.9008,.9827,-.1406],contactType:"socket",embedDepth:.06,overlap:.06,gapTolerance:.01,contactNormal:[.45,.85,.1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"horn-collar-l",kind:"seam",description:"Raised collar ring where the horn seats into the cranium (socket seam, geometry carried by horn-collar-ring-l)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","profile","top"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},p.add(m),i["horn-l"]=m,a["horn-l"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(p);let y=Lt(null),x=new He;x.name="Horn (right)__pivot",x.scale.set(1,1,1),y?(x.position.copy(y.start),x.rotation.set(0,0,0)):(x.position.set(0,0,0),x.rotation.set(0,0,0)),x.userData.sculptComponent={id:"horn-r",name:"Horn (right)",level:"macro",role:"appendage",importance:.95,confidence:.9,primitive:"tapered-sweep",topologyClass:"continuous-sculpt",topologyRationale:"Swept blade, not a cone: base radius 0.196, taper 0.99, cross-section flattened to 0.50 of its width. Root, control and tip fitted against the horn-only band of the front reference (rows 0-20, where the skull is absent) plus the top view u2014 IoU 0.005 -> 0.855.",geometryDescriptor:{topologyIntent:"A swept 3D arc, not a cone: rises and splays laterally (front), leans posteriorly at mid-arc (profile, z dips to -0.10), tip recovers anteriorly (top view, z ends +0.10). Monotonic taper to a true point.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",taperedSweep:{stations:[{position:[-.3781,.1602,.063],rx:.1958,rz:.0977,twist:0},{position:[-.4676,.274,.0391],rx:.1743,rz:.0869,twist:0},{position:[-.5493,.3822,.0155],rx:.1527,rz:.0761,twist:0},{position:[-.6231,.4848,-.0078],rx:.131,rz:.0653,twist:0},{position:[-.6891,.5818,-.0307],rx:.1094,rz:.0546,twist:0},{position:[-.7471,.6732,-.0533],rx:.0877,rz:.0437,twist:0},{position:[-.7973,.759,-.0756],rx:.0659,rz:.0329,twist:0},{position:[-.8397,.8392,-.0976],rx:.0441,rz:.022,twist:0},{position:[-.8742,.9138,-.1193],rx:.0222,rz:.0111,twist:0},{position:[-.9008,.9827,-.1406],rx:0,rz:0,twist:0}],radialSegments:14,capEnds:!0}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"horn-socket-r",localStart:[-.3781,.1602,.063],localEnd:[-.9008,.9827,-.1406],contactType:"socket",embedDepth:.06,overlap:.06,gapTolerance:.01,contactNormal:[-.45,.85,.1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"horn-collar-r",kind:"seam",description:"Raised collar ring where the horn seats into the cranium (socket seam, geometry carried by horn-collar-ring-r)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","profile","top"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},x.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(x),n["horn-r"]=x;let b=y?new Pt(y.endRadius,y.baseRadius,y.length,32,12):DC({stations:[{position:[-.3781,.1602,.063],rx:.1958,rz:.0977,twist:0},{position:[-.4676,.274,.0391],rx:.1743,rz:.0869,twist:0},{position:[-.5493,.3822,.0155],rx:.1527,rz:.0761,twist:0},{position:[-.6231,.4848,-.0078],rx:.131,rz:.0653,twist:0},{position:[-.6891,.5818,-.0307],rx:.1094,rz:.0546,twist:0},{position:[-.7471,.6732,-.0533],rx:.0877,rz:.0437,twist:0},{position:[-.7973,.759,-.0756],rx:.0659,rz:.0329,twist:0},{position:[-.8397,.8392,-.0976],rx:.0441,rz:.022,twist:0},{position:[-.8742,.9138,-.1193],rx:.0222,rz:.0111,twist:0},{position:[-.9008,.9827,-.1406],rx:0,rz:0,twist:0}],radialSegments:14,capEnds:!0});y||b.scale(1,1,1);let _=new De(b,t["clay-shell"]??new Et({color:8947848}));_.name="Horn (right)",y&&(_.position.copy(y.midpoint),_.quaternion.copy(y.quaternion)),_.castShadow=r.castShadow??!0,_.receiveShadow=r.receiveShadow??!0,_.userData.sculptComponent={id:"horn-r",name:"Horn (right)",level:"macro",role:"appendage",importance:.95,confidence:.9,primitive:"tapered-sweep",topologyClass:"continuous-sculpt",topologyRationale:"Swept blade, not a cone: base radius 0.196, taper 0.99, cross-section flattened to 0.50 of its width. Root, control and tip fitted against the horn-only band of the front reference (rows 0-20, where the skull is absent) plus the top view u2014 IoU 0.005 -> 0.855.",geometryDescriptor:{topologyIntent:"A swept 3D arc, not a cone: rises and splays laterally (front), leans posteriorly at mid-arc (profile, z dips to -0.10), tip recovers anteriorly (top view, z ends +0.10). Monotonic taper to a true point.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",taperedSweep:{stations:[{position:[-.3781,.1602,.063],rx:.1958,rz:.0977,twist:0},{position:[-.4676,.274,.0391],rx:.1743,rz:.0869,twist:0},{position:[-.5493,.3822,.0155],rx:.1527,rz:.0761,twist:0},{position:[-.6231,.4848,-.0078],rx:.131,rz:.0653,twist:0},{position:[-.6891,.5818,-.0307],rx:.1094,rz:.0546,twist:0},{position:[-.7471,.6732,-.0533],rx:.0877,rz:.0437,twist:0},{position:[-.7973,.759,-.0756],rx:.0659,rz:.0329,twist:0},{position:[-.8397,.8392,-.0976],rx:.0441,rz:.022,twist:0},{position:[-.8742,.9138,-.1193],rx:.0222,rz:.0111,twist:0},{position:[-.9008,.9827,-.1406],rx:0,rz:0,twist:0}],radialSegments:14,capEnds:!0}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"horn-socket-r",localStart:[-.3781,.1602,.063],localEnd:[-.9008,.9827,-.1406],contactType:"socket",embedDepth:.06,overlap:.06,gapTolerance:.01,contactNormal:[-.45,.85,.1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"horn-collar-r",kind:"seam",description:"Raised collar ring where the horn seats into the cranium (socket seam, geometry carried by horn-collar-ring-r)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","profile","top"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},x.add(_),i["horn-r"]=_,a["horn-r"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(x);let S=Lt(null),M=new He;M.name="Pointed ear (l)__pivot",M.scale.set(1,1,1),S?(M.position.copy(S.start),M.rotation.set(.1,.28,.16)):(M.position.set(.4085,-.0711,-.125),M.rotation.set(.1,.28,.16)),M.userData.sculptComponent={id:"ear-l",name:"Pointed ear (l)",level:"macro",role:"appendage",importance:.75,confidence:.8,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Pointed elf-like ear embedded in the lateral wall, raked posteriorly; concha carved as a subtracted sphere so the relief is real geometry, not shading.",geometryDescriptor:{topologyIntent:"Pointed elf-like ear embedded in the lateral wall, raked posteriorly; concha carved as a subtracted sphere so the relief is real geometry, not shading.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"body",type:"ellipsoid",center:[0,0,0],radii:[.0952,.266,.22]},{id:"tip",type:"cone",center:[0,.28595000000000004,-.01],radius:.0904,height:.2826},{id:"concha",type:"sphere",center:[.0285,-.0599,.099],radius:.1144}],operations:[{id:"b",type:"smooth-union",left:"body",right:"tip",radius:.05},{id:"final",type:"subtract",left:"b",right:"concha"}],resolution:40,bounds:{min:[-.181,-.499,-.418],max:[.181,.632,.418]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"ear-socket-l",localStart:[0,0,0],localEnd:[.06,0,0],contactType:"embed",embedDepth:.07,overlap:.07,gapTolerance:.01,contactNormal:[1,0,0]},dimensions:{width:.2,height:.45,depth:.25,units:"relative",confidence:.85},transform:{position:[.4085,-.0711,-.125],rotation:[.1,.28,.16],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"helix-relief-l",kind:"ridge",description:"Helix/antihelix relief; concha carved as real negative volume",evidenceRegion:"profile"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["profile","front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},M.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(M),n["ear-l"]=M;let w=Cu({primitives:[{id:"body",type:"ellipsoid",center:[0,0,0],radii:[.0952,.266,.22]},{id:"tip",type:"cone",center:[0,.28595000000000004,-.01],radius:.0904,height:.2826},{id:"concha",type:"sphere",center:[.0285,-.0599,.099],radius:.1144}],operations:[{id:"b",type:"smooth-union",left:"body",right:"tip",radius:.05},{id:"final",type:"subtract",left:"b",right:"concha"}],resolution:40,bounds:{min:[-.181,-.499,-.418],max:[.181,.632,.418]}});S||w.scale(1,1,1);let T=new De(w,ao("clay-shell",{id:"clay-shell",name:"Mask shell clay",type:"standard",shaderModel:"MeshStandardMaterial / PBR approximation",baseColor:"#B9B6B2",color:"#B9B6B2",albedo:{dominant:"#B9B6B2",secondary:["#A8A5A1","#C6C3BF"],samplingNotes:"Reference is an achromatic clay preview: single flat albedo; all tonal variation in the reference is lighting."},colorVariation:{palette:["#B9B6B2"],pattern:"none",amplitude:0,heightCorrelation:0},metalness:0,roughness:{base:.88,variation:.04,map:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_roughness.png (extracted; near-uniform matte, no specular lobe in the reference)"},textureResolution:1024,textureProjection:{mode:"uv",repeat:[1,1],anisotropy:4,texelDensityIntent:"flat albedo; no texture detail exists in the reference"},surfaceFrequencyBands:[{id:"macro",frequency:1,amplitude:.01,role:"none u2014 flat clay"},{id:"meso",frequency:4,amplitude:.01,role:"none"},{id:"micro",frequency:16,amplitude:.02,role:"faint matte breakup"}],localOverrides:[{id:"cavity-ao",region:"eye apertures' inner walls, mouth interior, nostril cavities, ear conchae, the shell interior seen through the rear opening",dirtAmount:0,cavityBias:!0,streak:!1,roughness:.92,aoDarken:.45,notes:"no dirt/wear exists on the pristine clay reference; the only regional response is cavity occlusion darkening"}],notes:"Geometry-only reconstruction: the consuming sandbox replaces materials wholesale.",ambientOcclusion:{source:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_ao.png",response:"cavity-only: concave regions (eye sockets, mouth, nostrils, concha) darken; convex crests stay open",intensity:.6},referencePbr:{version:"1",sourceImage:"/Users/dmitriy/new-10/.img2threejs/detail-inventory/zone-r1c1.png",extractor:"forge/stage1_intake/extract_pbr_evidence.py",method:"single-image statistical inversion on a reference crop",verdict:"usable",usable:!0,confidence:.742,estimatedFidelity:.742,targetThreshold:.7,hardLimit:"single-image inverse rendering is an estimate; the reference is an untextured clay preview, so this evidence proves the CLAY look the harness renders are compared against, not a production finish",maps:{albedo:{path:"/.img2threejs/pbr/clay-shell_albedo.png",channel:"albedo"},roughness:{path:"/.img2threejs/pbr/clay-shell_roughness.png",channel:"roughness"},height:{path:"/.img2threejs/pbr/clay-shell_height.png",channel:"height"},normal:{path:"/.img2threejs/pbr/clay-shell_normal.png",channel:"normal"},ao:{path:"/.img2threejs/pbr/clay-shell_ao.png",channel:"ao"}}}},r,!0));T.name="Pointed ear (l)",S&&(T.position.copy(S.midpoint),T.quaternion.copy(S.quaternion)),T.castShadow=r.castShadow??!0,T.receiveShadow=r.receiveShadow??!0,T.userData.sculptComponent={id:"ear-l",name:"Pointed ear (l)",level:"macro",role:"appendage",importance:.75,confidence:.8,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Pointed elf-like ear embedded in the lateral wall, raked posteriorly; concha carved as a subtracted sphere so the relief is real geometry, not shading.",geometryDescriptor:{topologyIntent:"Pointed elf-like ear embedded in the lateral wall, raked posteriorly; concha carved as a subtracted sphere so the relief is real geometry, not shading.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"body",type:"ellipsoid",center:[0,0,0],radii:[.0952,.266,.22]},{id:"tip",type:"cone",center:[0,.28595000000000004,-.01],radius:.0904,height:.2826},{id:"concha",type:"sphere",center:[.0285,-.0599,.099],radius:.1144}],operations:[{id:"b",type:"smooth-union",left:"body",right:"tip",radius:.05},{id:"final",type:"subtract",left:"b",right:"concha"}],resolution:40,bounds:{min:[-.181,-.499,-.418],max:[.181,.632,.418]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"ear-socket-l",localStart:[0,0,0],localEnd:[.06,0,0],contactType:"embed",embedDepth:.07,overlap:.07,gapTolerance:.01,contactNormal:[1,0,0]},dimensions:{width:.2,height:.45,depth:.25,units:"relative",confidence:.85},transform:{position:[.4085,-.0711,-.125],rotation:[.1,.28,.16],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"helix-relief-l",kind:"ridge",description:"Helix/antihelix relief; concha carved as real negative volume",evidenceRegion:"profile"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["profile","front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},M.add(T),i["ear-l"]=T,a["ear-l"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(M);let R=Lt(null),D=new He;D.name="Pointed ear (r)__pivot",D.scale.set(1,1,1),R?(D.position.copy(R.start),D.rotation.set(.1,-.28,-.16)):(D.position.set(-.4085,-.0711,-.125),D.rotation.set(.1,-.28,-.16)),D.userData.sculptComponent={id:"ear-r",name:"Pointed ear (r)",level:"macro",role:"appendage",importance:.75,confidence:.8,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Pointed elf-like ear embedded in the lateral wall, raked posteriorly; concha carved as a subtracted sphere so the relief is real geometry, not shading.",geometryDescriptor:{topologyIntent:"Pointed elf-like ear embedded in the lateral wall, raked posteriorly; concha carved as a subtracted sphere so the relief is real geometry, not shading.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"body",type:"ellipsoid",center:[0,0,0],radii:[.0952,.266,.22]},{id:"tip",type:"cone",center:[0,.28595000000000004,-.01],radius:.0904,height:.2826},{id:"concha",type:"sphere",center:[-.0285,-.0599,.099],radius:.1144}],operations:[{id:"b",type:"smooth-union",left:"body",right:"tip",radius:.05},{id:"final",type:"subtract",left:"b",right:"concha"}],resolution:40,bounds:{min:[-.181,-.499,-.418],max:[.181,.632,.418]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"ear-socket-r",localStart:[0,0,0],localEnd:[-.06,0,0],contactType:"embed",embedDepth:.07,overlap:.07,gapTolerance:.01,contactNormal:[-1,0,0]},dimensions:{width:.2,height:.45,depth:.25,units:"relative",confidence:.85},transform:{position:[-.4085,-.0711,-.125],rotation:[.1,-.28,-.16],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"helix-relief-r",kind:"ridge",description:"Helix/antihelix relief; concha carved as real negative volume",evidenceRegion:"profile"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["profile","front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},D.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(D),n["ear-r"]=D;let L=Cu({primitives:[{id:"body",type:"ellipsoid",center:[0,0,0],radii:[.0952,.266,.22]},{id:"tip",type:"cone",center:[0,.28595000000000004,-.01],radius:.0904,height:.2826},{id:"concha",type:"sphere",center:[-.0285,-.0599,.099],radius:.1144}],operations:[{id:"b",type:"smooth-union",left:"body",right:"tip",radius:.05},{id:"final",type:"subtract",left:"b",right:"concha"}],resolution:40,bounds:{min:[-.181,-.499,-.418],max:[.181,.632,.418]}});R||L.scale(1,1,1);let B=new De(L,ao("clay-shell",{id:"clay-shell",name:"Mask shell clay",type:"standard",shaderModel:"MeshStandardMaterial / PBR approximation",baseColor:"#B9B6B2",color:"#B9B6B2",albedo:{dominant:"#B9B6B2",secondary:["#A8A5A1","#C6C3BF"],samplingNotes:"Reference is an achromatic clay preview: single flat albedo; all tonal variation in the reference is lighting."},colorVariation:{palette:["#B9B6B2"],pattern:"none",amplitude:0,heightCorrelation:0},metalness:0,roughness:{base:.88,variation:.04,map:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_roughness.png (extracted; near-uniform matte, no specular lobe in the reference)"},textureResolution:1024,textureProjection:{mode:"uv",repeat:[1,1],anisotropy:4,texelDensityIntent:"flat albedo; no texture detail exists in the reference"},surfaceFrequencyBands:[{id:"macro",frequency:1,amplitude:.01,role:"none u2014 flat clay"},{id:"meso",frequency:4,amplitude:.01,role:"none"},{id:"micro",frequency:16,amplitude:.02,role:"faint matte breakup"}],localOverrides:[{id:"cavity-ao",region:"eye apertures' inner walls, mouth interior, nostril cavities, ear conchae, the shell interior seen through the rear opening",dirtAmount:0,cavityBias:!0,streak:!1,roughness:.92,aoDarken:.45,notes:"no dirt/wear exists on the pristine clay reference; the only regional response is cavity occlusion darkening"}],notes:"Geometry-only reconstruction: the consuming sandbox replaces materials wholesale.",ambientOcclusion:{source:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_ao.png",response:"cavity-only: concave regions (eye sockets, mouth, nostrils, concha) darken; convex crests stay open",intensity:.6},referencePbr:{version:"1",sourceImage:"/Users/dmitriy/new-10/.img2threejs/detail-inventory/zone-r1c1.png",extractor:"forge/stage1_intake/extract_pbr_evidence.py",method:"single-image statistical inversion on a reference crop",verdict:"usable",usable:!0,confidence:.742,estimatedFidelity:.742,targetThreshold:.7,hardLimit:"single-image inverse rendering is an estimate; the reference is an untextured clay preview, so this evidence proves the CLAY look the harness renders are compared against, not a production finish",maps:{albedo:{path:"/.img2threejs/pbr/clay-shell_albedo.png",channel:"albedo"},roughness:{path:"/.img2threejs/pbr/clay-shell_roughness.png",channel:"roughness"},height:{path:"/.img2threejs/pbr/clay-shell_height.png",channel:"height"},normal:{path:"/.img2threejs/pbr/clay-shell_normal.png",channel:"normal"},ao:{path:"/.img2threejs/pbr/clay-shell_ao.png",channel:"ao"}}}},r,!0));B.name="Pointed ear (r)",R&&(B.position.copy(R.midpoint),B.quaternion.copy(R.quaternion)),B.castShadow=r.castShadow??!0,B.receiveShadow=r.receiveShadow??!0,B.userData.sculptComponent={id:"ear-r",name:"Pointed ear (r)",level:"macro",role:"appendage",importance:.75,confidence:.8,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Pointed elf-like ear embedded in the lateral wall, raked posteriorly; concha carved as a subtracted sphere so the relief is real geometry, not shading.",geometryDescriptor:{topologyIntent:"Pointed elf-like ear embedded in the lateral wall, raked posteriorly; concha carved as a subtracted sphere so the relief is real geometry, not shading.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"body",type:"ellipsoid",center:[0,0,0],radii:[.0952,.266,.22]},{id:"tip",type:"cone",center:[0,.28595000000000004,-.01],radius:.0904,height:.2826},{id:"concha",type:"sphere",center:[-.0285,-.0599,.099],radius:.1144}],operations:[{id:"b",type:"smooth-union",left:"body",right:"tip",radius:.05},{id:"final",type:"subtract",left:"b",right:"concha"}],resolution:40,bounds:{min:[-.181,-.499,-.418],max:[.181,.632,.418]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"ear-socket-r",localStart:[0,0,0],localEnd:[-.06,0,0],contactType:"embed",embedDepth:.07,overlap:.07,gapTolerance:.01,contactNormal:[-1,0,0]},dimensions:{width:.2,height:.45,depth:.25,units:"relative",confidence:.85},transform:{position:[-.4085,-.0711,-.125],rotation:[.1,-.28,-.16],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"helix-relief-r",kind:"ridge",description:"Helix/antihelix relief; concha carved as real negative volume",evidenceRegion:"profile"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["profile","front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},D.add(B),i["ear-r"]=B,a["ear-r"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(D);let W=Lt(null),q=new He;q.name="Brow ridge (l)__pivot",q.scale.set(1,1,1),W?(q.position.copy(W.start),q.rotation.set(-.16,-.34,.3)):(q.position.set(.2,.14,.4915),q.rotation.set(-.16,-.34,.3)),q.userData.sculptComponent={id:"brow-ridge-l",name:"Brow ridge (l)",level:"meso",role:"body",importance:.9,confidence:.85,primitive:"extrude",topologyClass:"assembled-solid",topologyRationale:"A hard-edged angular prism: the brow reads as distinct facet planes with countable faces, deliberately proud of the organic shell u2014 this faceting IS the expression.",geometryDescriptor:{topologyIntent:"A hard-edged angular prism: the brow reads as distinct facet planes with countable faces, deliberately proud of the organic shell u2014 this faceting IS the expression.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",profile2D:{points:[[-.2,-.055],[.2,-.025],[.2,.055],[-.2,.022]],depth:.13}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"brow-seat-l",localStart:[0,0,0],localEnd:[.17,.03,0],contactType:"overlap",embedDepth:.05,overlap:.05,gapTolerance:.01,contactNormal:[0,.3,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[.2,.14,.4915],rotation:[-.16,-.34,.3],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},q.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(q),n["brow-ridge-l"]=q;let ce=W?new Pt(W.endRadius,W.baseRadius,W.length,32,12):t0({points:[[-.2,-.055],[.2,-.025],[.2,.055],[-.2,.022]],depth:.13});W||ce.scale(1,1,1);let k=new De(ce,t["clay-shell"]??new Et({color:8947848}));k.name="Brow ridge (l)",W&&(k.position.copy(W.midpoint),k.quaternion.copy(W.quaternion)),k.castShadow=r.castShadow??!0,k.receiveShadow=r.receiveShadow??!0,k.userData.sculptComponent={id:"brow-ridge-l",name:"Brow ridge (l)",level:"meso",role:"body",importance:.9,confidence:.85,primitive:"extrude",topologyClass:"assembled-solid",topologyRationale:"A hard-edged angular prism: the brow reads as distinct facet planes with countable faces, deliberately proud of the organic shell u2014 this faceting IS the expression.",geometryDescriptor:{topologyIntent:"A hard-edged angular prism: the brow reads as distinct facet planes with countable faces, deliberately proud of the organic shell u2014 this faceting IS the expression.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",profile2D:{points:[[-.2,-.055],[.2,-.025],[.2,.055],[-.2,.022]],depth:.13}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"brow-seat-l",localStart:[0,0,0],localEnd:[.17,.03,0],contactType:"overlap",embedDepth:.05,overlap:.05,gapTolerance:.01,contactNormal:[0,.3,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[.2,.14,.4915],rotation:[-.16,-.34,.3],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},q.add(k),i["brow-ridge-l"]=k,a["brow-ridge-l"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(q);let j=Lt(null),ee=new He;ee.name="Brow ridge (r)__pivot",ee.scale.set(1,1,1),j?(ee.position.copy(j.start),ee.rotation.set(-.16,.34,-.3)):(ee.position.set(-.2,.14,.4915),ee.rotation.set(-.16,.34,-.3)),ee.userData.sculptComponent={id:"brow-ridge-r",name:"Brow ridge (r)",level:"meso",role:"body",importance:.9,confidence:.85,primitive:"extrude",topologyClass:"assembled-solid",topologyRationale:"A hard-edged angular prism: the brow reads as distinct facet planes with countable faces, deliberately proud of the organic shell u2014 this faceting IS the expression.",geometryDescriptor:{topologyIntent:"A hard-edged angular prism: the brow reads as distinct facet planes with countable faces, deliberately proud of the organic shell u2014 this faceting IS the expression.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",profile2D:{points:[[.2,.022],[-.2,.055],[-.2,-.025],[.2,-.055]],depth:.13}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"brow-seat-r",localStart:[0,0,0],localEnd:[-.17,.03,0],contactType:"overlap",embedDepth:.05,overlap:.05,gapTolerance:.01,contactNormal:[0,.3,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[-.2,.14,.4915],rotation:[-.16,.34,-.3],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},ee.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(ee),n["brow-ridge-r"]=ee;let ge=j?new Pt(j.endRadius,j.baseRadius,j.length,32,12):t0({points:[[.2,.022],[-.2,.055],[-.2,-.025],[.2,-.055]],depth:.13});j||ge.scale(1,1,1);let fe=new De(ge,t["clay-shell"]??new Et({color:8947848}));fe.name="Brow ridge (r)",j&&(fe.position.copy(j.midpoint),fe.quaternion.copy(j.quaternion)),fe.castShadow=r.castShadow??!0,fe.receiveShadow=r.receiveShadow??!0,fe.userData.sculptComponent={id:"brow-ridge-r",name:"Brow ridge (r)",level:"meso",role:"body",importance:.9,confidence:.85,primitive:"extrude",topologyClass:"assembled-solid",topologyRationale:"A hard-edged angular prism: the brow reads as distinct facet planes with countable faces, deliberately proud of the organic shell u2014 this faceting IS the expression.",geometryDescriptor:{topologyIntent:"A hard-edged angular prism: the brow reads as distinct facet planes with countable faces, deliberately proud of the organic shell u2014 this faceting IS the expression.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",profile2D:{points:[[.2,.022],[-.2,.055],[-.2,-.025],[.2,-.055]],depth:.13}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"brow-seat-r",localStart:[0,0,0],localEnd:[-.17,.03,0],contactType:"overlap",embedDepth:.05,overlap:.05,gapTolerance:.01,contactNormal:[0,.3,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[-.2,.14,.4915],rotation:[-.16,.34,-.3],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},ee.add(fe),i["brow-ridge-r"]=fe,a["brow-ridge-r"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(ee);let he=Lt(null),ye=new He;ye.name="Glabella facet plate__pivot",ye.scale.set(1,1,1),he?(ye.position.copy(he.start),ye.rotation.set(-.1,0,0)):(ye.position.set(0,.06,.5479),ye.rotation.set(-.1,0,0)),ye.userData.sculptComponent={id:"glabella-plate",name:"Glabella facet plate",level:"meso",role:"body",importance:.7,confidence:.85,primitive:"extrude",topologyClass:"assembled-solid",topologyRationale:"The flat faceted plane between the brows: a pentagonal plate whose hard edges catch light as real creases (detail glabella-facet-creases).",geometryDescriptor:{topologyIntent:"The flat faceted plane between the brows: a pentagonal plate whose hard edges catch light as real creases (detail glabella-facet-creases).",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",profile2D:{points:[[-.1,0],[-.05,.12],[.05,.12],[.1,0],[0,-.16]],depth:.05}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"glabella-seat",localStart:[0,0,0],localEnd:[0,-.15,0],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,.1,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,.06,.5479],rotation:[-.1,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},ye.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(ye),n["glabella-plate"]=ye;let ze=he?new Pt(he.endRadius,he.baseRadius,he.length,32,12):t0({points:[[-.1,0],[-.05,.12],[.05,.12],[.1,0],[0,-.16]],depth:.05});he||ze.scale(1,1,1);let Pe=new De(ze,t["clay-shell"]??new Et({color:8947848}));Pe.name="Glabella facet plate",he&&(Pe.position.copy(he.midpoint),Pe.quaternion.copy(he.quaternion)),Pe.castShadow=r.castShadow??!0,Pe.receiveShadow=r.receiveShadow??!0,Pe.userData.sculptComponent={id:"glabella-plate",name:"Glabella facet plate",level:"meso",role:"body",importance:.7,confidence:.85,primitive:"extrude",topologyClass:"assembled-solid",topologyRationale:"The flat faceted plane between the brows: a pentagonal plate whose hard edges catch light as real creases (detail glabella-facet-creases).",geometryDescriptor:{topologyIntent:"The flat faceted plane between the brows: a pentagonal plate whose hard edges catch light as real creases (detail glabella-facet-creases).",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",profile2D:{points:[[-.1,0],[-.05,.12],[.05,.12],[.1,0],[0,-.16]],depth:.05}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"glabella-seat",localStart:[0,0,0],localEnd:[0,-.15,0],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,.1,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,.06,.5479],rotation:[-.1,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},ye.add(Pe),i["glabella-plate"]=Pe,a["glabella-plate"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(ye);let ot=Lt(null),Se=new He;Se.name="Cheekbone facet (l)__pivot",Se.scale.set(1,1,1),ot?(Se.position.copy(ot.start),Se.rotation.set(0,0,0)):(Se.position.set(.26,-.3,.227),Se.rotation.set(0,0,0)),Se.userData.sculptComponent={id:"cheekbone-l",name:"Cheekbone facet (l)",level:"meso",role:"body",importance:.7,confidence:.8,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Raised cheek mass as an implicit flattened ellipsoid embedded in the shell u2014 an applied extrude plate cannot conform to the curved face and reads as a floating slab.",geometryDescriptor:{topologyIntent:"Faceted cheek plane wrapping the lateral face; hard creases against the shell.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"mass",type:"ellipsoid",center:[0,0,0],radii:[.15,.12,.09],transform:{rotation:[.05,.35,.1]}}],operations:[],resolution:26,bounds:{min:[-.22,-.18,-.14],max:[.22,.18,.14]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"cheek-seat-l",localStart:[0,0,0],localEnd:[.1,0,0],contactType:"overlap",embedDepth:.04,overlap:.04,gapTolerance:.01,contactNormal:[.4,0,.9]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[.26,-.3,.227],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"nasolabial-l",kind:"ridge",description:"Fold from the ala to the mouth corner (geometry: nasolabial-ridge-l)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","three-quarter"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Se.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(Se),n["cheekbone-l"]=Se;let Je=Cu({primitives:[{id:"mass",type:"ellipsoid",center:[0,0,0],radii:[.15,.12,.09],transform:{rotation:[.05,.35,.1]}}],operations:[],resolution:26,bounds:{min:[-.22,-.18,-.14],max:[.22,.18,.14]}});ot||Je.scale(1,1,1);let lt=new De(Je,ao("clay-shell",{id:"clay-shell",name:"Mask shell clay",type:"standard",shaderModel:"MeshStandardMaterial / PBR approximation",baseColor:"#B9B6B2",color:"#B9B6B2",albedo:{dominant:"#B9B6B2",secondary:["#A8A5A1","#C6C3BF"],samplingNotes:"Reference is an achromatic clay preview: single flat albedo; all tonal variation in the reference is lighting."},colorVariation:{palette:["#B9B6B2"],pattern:"none",amplitude:0,heightCorrelation:0},metalness:0,roughness:{base:.88,variation:.04,map:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_roughness.png (extracted; near-uniform matte, no specular lobe in the reference)"},textureResolution:1024,textureProjection:{mode:"uv",repeat:[1,1],anisotropy:4,texelDensityIntent:"flat albedo; no texture detail exists in the reference"},surfaceFrequencyBands:[{id:"macro",frequency:1,amplitude:.01,role:"none u2014 flat clay"},{id:"meso",frequency:4,amplitude:.01,role:"none"},{id:"micro",frequency:16,amplitude:.02,role:"faint matte breakup"}],localOverrides:[{id:"cavity-ao",region:"eye apertures' inner walls, mouth interior, nostril cavities, ear conchae, the shell interior seen through the rear opening",dirtAmount:0,cavityBias:!0,streak:!1,roughness:.92,aoDarken:.45,notes:"no dirt/wear exists on the pristine clay reference; the only regional response is cavity occlusion darkening"}],notes:"Geometry-only reconstruction: the consuming sandbox replaces materials wholesale.",ambientOcclusion:{source:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_ao.png",response:"cavity-only: concave regions (eye sockets, mouth, nostrils, concha) darken; convex crests stay open",intensity:.6},referencePbr:{version:"1",sourceImage:"/Users/dmitriy/new-10/.img2threejs/detail-inventory/zone-r1c1.png",extractor:"forge/stage1_intake/extract_pbr_evidence.py",method:"single-image statistical inversion on a reference crop",verdict:"usable",usable:!0,confidence:.742,estimatedFidelity:.742,targetThreshold:.7,hardLimit:"single-image inverse rendering is an estimate; the reference is an untextured clay preview, so this evidence proves the CLAY look the harness renders are compared against, not a production finish",maps:{albedo:{path:"/.img2threejs/pbr/clay-shell_albedo.png",channel:"albedo"},roughness:{path:"/.img2threejs/pbr/clay-shell_roughness.png",channel:"roughness"},height:{path:"/.img2threejs/pbr/clay-shell_height.png",channel:"height"},normal:{path:"/.img2threejs/pbr/clay-shell_normal.png",channel:"normal"},ao:{path:"/.img2threejs/pbr/clay-shell_ao.png",channel:"ao"}}}},r,!0));lt.name="Cheekbone facet (l)",ot&&(lt.position.copy(ot.midpoint),lt.quaternion.copy(ot.quaternion)),lt.castShadow=r.castShadow??!0,lt.receiveShadow=r.receiveShadow??!0,lt.userData.sculptComponent={id:"cheekbone-l",name:"Cheekbone facet (l)",level:"meso",role:"body",importance:.7,confidence:.8,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Raised cheek mass as an implicit flattened ellipsoid embedded in the shell u2014 an applied extrude plate cannot conform to the curved face and reads as a floating slab.",geometryDescriptor:{topologyIntent:"Faceted cheek plane wrapping the lateral face; hard creases against the shell.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"mass",type:"ellipsoid",center:[0,0,0],radii:[.15,.12,.09],transform:{rotation:[.05,.35,.1]}}],operations:[],resolution:26,bounds:{min:[-.22,-.18,-.14],max:[.22,.18,.14]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"cheek-seat-l",localStart:[0,0,0],localEnd:[.1,0,0],contactType:"overlap",embedDepth:.04,overlap:.04,gapTolerance:.01,contactNormal:[.4,0,.9]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[.26,-.3,.227],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"nasolabial-l",kind:"ridge",description:"Fold from the ala to the mouth corner (geometry: nasolabial-ridge-l)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","three-quarter"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Se.add(lt),i["cheekbone-l"]=lt,a["cheekbone-l"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(Se);let kt=Lt(null),tt=new He;tt.name="Cheekbone facet (r)__pivot",tt.scale.set(1,1,1),kt?(tt.position.copy(kt.start),tt.rotation.set(0,0,0)):(tt.position.set(-.26,-.3,.227),tt.rotation.set(0,0,0)),tt.userData.sculptComponent={id:"cheekbone-r",name:"Cheekbone facet (r)",level:"meso",role:"body",importance:.7,confidence:.8,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Raised cheek mass as an implicit flattened ellipsoid embedded in the shell u2014 an applied extrude plate cannot conform to the curved face and reads as a floating slab.",geometryDescriptor:{topologyIntent:"Faceted cheek plane wrapping the lateral face; hard creases against the shell.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"mass",type:"ellipsoid",center:[0,0,0],radii:[.15,.12,.09],transform:{rotation:[.05,-.35,-.1]}}],operations:[],resolution:26,bounds:{min:[-.22,-.18,-.14],max:[.22,.18,.14]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"cheek-seat-r",localStart:[0,0,0],localEnd:[-.1,0,0],contactType:"overlap",embedDepth:.04,overlap:.04,gapTolerance:.01,contactNormal:[-.4,0,.9]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[-.26,-.3,.227],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"nasolabial-r",kind:"ridge",description:"Fold from the ala to the mouth corner (geometry: nasolabial-ridge-r)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","three-quarter"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},tt.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(tt),n["cheekbone-r"]=tt;let ti=Cu({primitives:[{id:"mass",type:"ellipsoid",center:[0,0,0],radii:[.15,.12,.09],transform:{rotation:[.05,-.35,-.1]}}],operations:[],resolution:26,bounds:{min:[-.22,-.18,-.14],max:[.22,.18,.14]}});kt||ti.scale(1,1,1);let Rn=new De(ti,ao("clay-shell",{id:"clay-shell",name:"Mask shell clay",type:"standard",shaderModel:"MeshStandardMaterial / PBR approximation",baseColor:"#B9B6B2",color:"#B9B6B2",albedo:{dominant:"#B9B6B2",secondary:["#A8A5A1","#C6C3BF"],samplingNotes:"Reference is an achromatic clay preview: single flat albedo; all tonal variation in the reference is lighting."},colorVariation:{palette:["#B9B6B2"],pattern:"none",amplitude:0,heightCorrelation:0},metalness:0,roughness:{base:.88,variation:.04,map:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_roughness.png (extracted; near-uniform matte, no specular lobe in the reference)"},textureResolution:1024,textureProjection:{mode:"uv",repeat:[1,1],anisotropy:4,texelDensityIntent:"flat albedo; no texture detail exists in the reference"},surfaceFrequencyBands:[{id:"macro",frequency:1,amplitude:.01,role:"none u2014 flat clay"},{id:"meso",frequency:4,amplitude:.01,role:"none"},{id:"micro",frequency:16,amplitude:.02,role:"faint matte breakup"}],localOverrides:[{id:"cavity-ao",region:"eye apertures' inner walls, mouth interior, nostril cavities, ear conchae, the shell interior seen through the rear opening",dirtAmount:0,cavityBias:!0,streak:!1,roughness:.92,aoDarken:.45,notes:"no dirt/wear exists on the pristine clay reference; the only regional response is cavity occlusion darkening"}],notes:"Geometry-only reconstruction: the consuming sandbox replaces materials wholesale.",ambientOcclusion:{source:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_ao.png",response:"cavity-only: concave regions (eye sockets, mouth, nostrils, concha) darken; convex crests stay open",intensity:.6},referencePbr:{version:"1",sourceImage:"/Users/dmitriy/new-10/.img2threejs/detail-inventory/zone-r1c1.png",extractor:"forge/stage1_intake/extract_pbr_evidence.py",method:"single-image statistical inversion on a reference crop",verdict:"usable",usable:!0,confidence:.742,estimatedFidelity:.742,targetThreshold:.7,hardLimit:"single-image inverse rendering is an estimate; the reference is an untextured clay preview, so this evidence proves the CLAY look the harness renders are compared against, not a production finish",maps:{albedo:{path:"/.img2threejs/pbr/clay-shell_albedo.png",channel:"albedo"},roughness:{path:"/.img2threejs/pbr/clay-shell_roughness.png",channel:"roughness"},height:{path:"/.img2threejs/pbr/clay-shell_height.png",channel:"height"},normal:{path:"/.img2threejs/pbr/clay-shell_normal.png",channel:"normal"},ao:{path:"/.img2threejs/pbr/clay-shell_ao.png",channel:"ao"}}}},r,!0));Rn.name="Cheekbone facet (r)",kt&&(Rn.position.copy(kt.midpoint),Rn.quaternion.copy(kt.quaternion)),Rn.castShadow=r.castShadow??!0,Rn.receiveShadow=r.receiveShadow??!0,Rn.userData.sculptComponent={id:"cheekbone-r",name:"Cheekbone facet (r)",level:"meso",role:"body",importance:.7,confidence:.8,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Raised cheek mass as an implicit flattened ellipsoid embedded in the shell u2014 an applied extrude plate cannot conform to the curved face and reads as a floating slab.",geometryDescriptor:{topologyIntent:"Faceted cheek plane wrapping the lateral face; hard creases against the shell.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"mass",type:"ellipsoid",center:[0,0,0],radii:[.15,.12,.09],transform:{rotation:[.05,-.35,-.1]}}],operations:[],resolution:26,bounds:{min:[-.22,-.18,-.14],max:[.22,.18,.14]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"cheek-seat-r",localStart:[0,0,0],localEnd:[-.1,0,0],contactType:"overlap",embedDepth:.04,overlap:.04,gapTolerance:.01,contactNormal:[-.4,0,.9]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[-.26,-.3,.227],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"nasolabial-r",kind:"ridge",description:"Fold from the ala to the mouth corner (geometry: nasolabial-ridge-r)",evidenceRegion:"front"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","three-quarter"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},tt.add(Rn),i["cheekbone-r"]=Rn,a["cheekbone-r"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(tt);let jt=Lt(null),Ke=new He;Ke.name="Nose wedge__pivot",Ke.scale.set(1,1,1),jt?(Ke.position.copy(jt.start),Ke.rotation.set(0,0,0)):(Ke.position.set(0,0,0),Ke.rotation.set(0,0,0)),Ke.userData.sculptComponent={id:"nose-wedge",name:"Nose wedge",level:"meso",role:"body",importance:.85,confidence:.85,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Anterior wedge: rotated-box bridge continuing the brow crease line, ellipsoid tip, alae spheres; nostrils are SUBTRACTED cavities on the underside (below-view evidence), never dark paint.",geometryDescriptor:{topologyIntent:"Anterior wedge: rotated-box bridge continuing the brow crease line, ellipsoid tip, alae spheres; nostrils are SUBTRACTED cavities on the underside (below-view evidence), never dark paint.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"bridge",type:"box",center:[0,.02,.3759],size:[.11,.36,.16],transform:{rotation:[-.2,0,0]}},{id:"tip",type:"ellipsoid",center:[0,-.272,.4909],radii:[.095,.085,.095]},{id:"alaL",type:"sphere",center:[.092,-.322,.4409],radius:.062},{id:"alaR",type:"sphere",center:[-.092,-.322,.4409],radius:.062},{id:"nosL",type:"sphere",center:[.062,-.372,.4709],radius:.042},{id:"nosR",type:"sphere",center:[-.062,-.372,.4709],radius:.042}],operations:[{id:"n1",type:"smooth-union",left:"bridge",right:"tip",radius:.055},{id:"n2",type:"smooth-union",left:"n1",right:"alaL",radius:.035},{id:"n3",type:"smooth-union",left:"n2",right:"alaR",radius:.035},{id:"n4",type:"subtract",left:"n3",right:"nosL"},{id:"final",type:"subtract",left:"n4",right:"nosR"}],resolution:56,bounds:{min:[-.24,-.517,.136],max:[.24,.3,.636]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"nose-seat",localStart:[0,.18,.28],localEnd:[0,-.372,.4709],contactType:"overlap",embedDepth:.06,overlap:.06,gapTolerance:.01,contactNormal:[0,0,1]},dimensions:{width:.3,height:.55,depth:.35,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"nostril-l",kind:"hole",description:"Left nostril cavity, flared laterally",evidenceRegion:"below"},{id:"nostril-r",kind:"hole",description:"Right nostril cavity u2014 reflection",evidenceRegion:"below"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","profile","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Ke.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(Ke),n["nose-wedge"]=Ke;let K=Cu({primitives:[{id:"bridge",type:"box",center:[0,.02,.3759],size:[.11,.36,.16],transform:{rotation:[-.2,0,0]}},{id:"tip",type:"ellipsoid",center:[0,-.272,.4909],radii:[.095,.085,.095]},{id:"alaL",type:"sphere",center:[.092,-.322,.4409],radius:.062},{id:"alaR",type:"sphere",center:[-.092,-.322,.4409],radius:.062},{id:"nosL",type:"sphere",center:[.062,-.372,.4709],radius:.042},{id:"nosR",type:"sphere",center:[-.062,-.372,.4709],radius:.042}],operations:[{id:"n1",type:"smooth-union",left:"bridge",right:"tip",radius:.055},{id:"n2",type:"smooth-union",left:"n1",right:"alaL",radius:.035},{id:"n3",type:"smooth-union",left:"n2",right:"alaR",radius:.035},{id:"n4",type:"subtract",left:"n3",right:"nosL"},{id:"final",type:"subtract",left:"n4",right:"nosR"}],resolution:56,bounds:{min:[-.24,-.517,.136],max:[.24,.3,.636]}});jt||K.scale(1,1,1);let Q=new De(K,ao("clay-shell",{id:"clay-shell",name:"Mask shell clay",type:"standard",shaderModel:"MeshStandardMaterial / PBR approximation",baseColor:"#B9B6B2",color:"#B9B6B2",albedo:{dominant:"#B9B6B2",secondary:["#A8A5A1","#C6C3BF"],samplingNotes:"Reference is an achromatic clay preview: single flat albedo; all tonal variation in the reference is lighting."},colorVariation:{palette:["#B9B6B2"],pattern:"none",amplitude:0,heightCorrelation:0},metalness:0,roughness:{base:.88,variation:.04,map:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_roughness.png (extracted; near-uniform matte, no specular lobe in the reference)"},textureResolution:1024,textureProjection:{mode:"uv",repeat:[1,1],anisotropy:4,texelDensityIntent:"flat albedo; no texture detail exists in the reference"},surfaceFrequencyBands:[{id:"macro",frequency:1,amplitude:.01,role:"none u2014 flat clay"},{id:"meso",frequency:4,amplitude:.01,role:"none"},{id:"micro",frequency:16,amplitude:.02,role:"faint matte breakup"}],localOverrides:[{id:"cavity-ao",region:"eye apertures' inner walls, mouth interior, nostril cavities, ear conchae, the shell interior seen through the rear opening",dirtAmount:0,cavityBias:!0,streak:!1,roughness:.92,aoDarken:.45,notes:"no dirt/wear exists on the pristine clay reference; the only regional response is cavity occlusion darkening"}],notes:"Geometry-only reconstruction: the consuming sandbox replaces materials wholesale.",ambientOcclusion:{source:"/Users/dmitriy/new-10/.img2threejs/pbr/clay-shell_ao.png",response:"cavity-only: concave regions (eye sockets, mouth, nostrils, concha) darken; convex crests stay open",intensity:.6},referencePbr:{version:"1",sourceImage:"/Users/dmitriy/new-10/.img2threejs/detail-inventory/zone-r1c1.png",extractor:"forge/stage1_intake/extract_pbr_evidence.py",method:"single-image statistical inversion on a reference crop",verdict:"usable",usable:!0,confidence:.742,estimatedFidelity:.742,targetThreshold:.7,hardLimit:"single-image inverse rendering is an estimate; the reference is an untextured clay preview, so this evidence proves the CLAY look the harness renders are compared against, not a production finish",maps:{albedo:{path:"/.img2threejs/pbr/clay-shell_albedo.png",channel:"albedo"},roughness:{path:"/.img2threejs/pbr/clay-shell_roughness.png",channel:"roughness"},height:{path:"/.img2threejs/pbr/clay-shell_height.png",channel:"height"},normal:{path:"/.img2threejs/pbr/clay-shell_normal.png",channel:"normal"},ao:{path:"/.img2threejs/pbr/clay-shell_ao.png",channel:"ao"}}}},r,!0));Q.name="Nose wedge",jt&&(Q.position.copy(jt.midpoint),Q.quaternion.copy(jt.quaternion)),Q.castShadow=r.castShadow??!0,Q.receiveShadow=r.receiveShadow??!0,Q.userData.sculptComponent={id:"nose-wedge",name:"Nose wedge",level:"meso",role:"body",importance:.85,confidence:.85,primitive:"ellipsoid",topologyClass:"implicit",topologyRationale:"Anterior wedge: rotated-box bridge continuing the brow crease line, ellipsoid tip, alae spheres; nostrils are SUBTRACTED cavities on the underside (below-view evidence), never dark paint.",geometryDescriptor:{topologyIntent:"Anterior wedge: rotated-box bridge continuing the brow crease line, ellipsoid tip, alae spheres; nostrils are SUBTRACTED cavities on the underside (below-view evidence), never dark paint.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",sdf:{primitives:[{id:"bridge",type:"box",center:[0,.02,.3759],size:[.11,.36,.16],transform:{rotation:[-.2,0,0]}},{id:"tip",type:"ellipsoid",center:[0,-.272,.4909],radii:[.095,.085,.095]},{id:"alaL",type:"sphere",center:[.092,-.322,.4409],radius:.062},{id:"alaR",type:"sphere",center:[-.092,-.322,.4409],radius:.062},{id:"nosL",type:"sphere",center:[.062,-.372,.4709],radius:.042},{id:"nosR",type:"sphere",center:[-.062,-.372,.4709],radius:.042}],operations:[{id:"n1",type:"smooth-union",left:"bridge",right:"tip",radius:.055},{id:"n2",type:"smooth-union",left:"n1",right:"alaL",radius:.035},{id:"n3",type:"smooth-union",left:"n2",right:"alaR",radius:.035},{id:"n4",type:"subtract",left:"n3",right:"nosL"},{id:"final",type:"subtract",left:"n4",right:"nosR"}],resolution:56,bounds:{min:[-.24,-.517,.136],max:[.24,.3,.636]}}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"nose-seat",localStart:[0,.18,.28],localEnd:[0,-.372,.4709],contactType:"overlap",embedDepth:.06,overlap:.06,gapTolerance:.01,contactNormal:[0,0,1]},dimensions:{width:.3,height:.55,depth:.35,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"nostril-l",kind:"hole",description:"Left nostril cavity, flared laterally",evidenceRegion:"below"},{id:"nostril-r",kind:"hole",description:"Right nostril cavity u2014 reflection",evidenceRegion:"below"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","profile","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Ke.add(Q),i["nose-wedge"]=Q,a["nose-wedge"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(Ke);let ue=Lt({parentId:"mask-shell",parentSocket:"upper-lip-seat",localStart:[-.2573,-.5072,.288],localEnd:[.2573,-.5072,.288],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,0,1]}),U=new He;U.name="Upper lip__pivot",U.scale.set(1,1,1),ue?(U.position.copy(ue.start),U.rotation.set(0,0,0)):(U.position.set(0,0,0),U.rotation.set(0,0,0)),U.userData.sculptComponent={id:"upper-lip",name:"Upper lip",level:"meso",role:"body",importance:.8,confidence:.85,primitive:"tube",topologyClass:"continuous-sculpt",topologyRationale:"A tube swept along the grimace curve u2014 corners pulled up and wrapped posteriorly; frames the mouth aperture cut through the shell behind it.",geometryDescriptor:{topologyIntent:"A tube swept along the grimace curve u2014 corners pulled up and wrapped posteriorly; frames the mouth aperture cut through the shell behind it.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[-.2573,-.5072,.288],[-.1415,-.5602,.3381],[0,-.5822,.3562],[.1415,-.5602,.3381],[.2573,-.5072,.288]],radius:.048,closed:!1}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"upper-lip-seat",localStart:[-.2573,-.5072,.288],localEnd:[.2573,-.5072,.288],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,0,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},U.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(U),n["upper-lip"]=U;let ae=ue?new Pt(ue.endRadius,ue.baseRadius,ue.length,32,12):bl({points:[[-.2573,-.5072,.288],[-.1415,-.5602,.3381],[0,-.5822,.3562],[.1415,-.5602,.3381],[.2573,-.5072,.288]],radius:.048,closed:!1});ue||ae.scale(1,1,1);let Z=new De(ae,t["clay-shell"]??new Et({color:8947848}));Z.name="Upper lip",ue&&(Z.position.copy(ue.midpoint),Z.quaternion.copy(ue.quaternion)),Z.castShadow=r.castShadow??!0,Z.receiveShadow=r.receiveShadow??!0,Z.userData.sculptComponent={id:"upper-lip",name:"Upper lip",level:"meso",role:"body",importance:.8,confidence:.85,primitive:"tube",topologyClass:"continuous-sculpt",topologyRationale:"A tube swept along the grimace curve u2014 corners pulled up and wrapped posteriorly; frames the mouth aperture cut through the shell behind it.",geometryDescriptor:{topologyIntent:"A tube swept along the grimace curve u2014 corners pulled up and wrapped posteriorly; frames the mouth aperture cut through the shell behind it.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[-.2573,-.5072,.288],[-.1415,-.5602,.3381],[0,-.5822,.3562],[.1415,-.5602,.3381],[.2573,-.5072,.288]],radius:.048,closed:!1}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"upper-lip-seat",localStart:[-.2573,-.5072,.288],localEnd:[.2573,-.5072,.288],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,0,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},U.add(Z),i["upper-lip"]=Z,a["upper-lip"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(U);let _e=Lt({parentId:"mask-shell",parentSocket:"lower-lip-seat",localStart:[-.2573,-.632,.2311],localEnd:[.2573,-.632,.2311],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,0,1]}),Ae=new He;Ae.name="Lower lip__pivot",Ae.scale.set(1,1,1),_e?(Ae.position.copy(_e.start),Ae.rotation.set(0,0,0)):(Ae.position.set(0,0,0),Ae.rotation.set(0,0,0)),Ae.userData.sculptComponent={id:"lower-lip",name:"Lower lip",level:"meso",role:"body",importance:.8,confidence:.85,primitive:"tube",topologyClass:"continuous-sculpt",topologyRationale:"A tube swept along the grimace curve u2014 corners pulled up and wrapped posteriorly; frames the mouth aperture cut through the shell behind it.",geometryDescriptor:{topologyIntent:"A tube swept along the grimace curve u2014 corners pulled up and wrapped posteriorly; frames the mouth aperture cut through the shell behind it.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[-.2573,-.632,.2311],[-.1415,-.685,.2794],[0,-.707,.2964],[.1415,-.685,.2794],[.2573,-.632,.2311]],radius:.044,closed:!1}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"lower-lip-seat",localStart:[-.2573,-.632,.2311],localEnd:[.2573,-.632,.2311],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,0,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Ae.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(Ae),n["lower-lip"]=Ae;let ct=_e?new Pt(_e.endRadius,_e.baseRadius,_e.length,32,12):bl({points:[[-.2573,-.632,.2311],[-.1415,-.685,.2794],[0,-.707,.2964],[.1415,-.685,.2794],[.2573,-.632,.2311]],radius:.044,closed:!1});_e||ct.scale(1,1,1);let nt=new De(ct,t["clay-shell"]??new Et({color:8947848}));nt.name="Lower lip",_e&&(nt.position.copy(_e.midpoint),nt.quaternion.copy(_e.quaternion)),nt.castShadow=r.castShadow??!0,nt.receiveShadow=r.receiveShadow??!0,nt.userData.sculptComponent={id:"lower-lip",name:"Lower lip",level:"meso",role:"body",importance:.8,confidence:.85,primitive:"tube",topologyClass:"continuous-sculpt",topologyRationale:"A tube swept along the grimace curve u2014 corners pulled up and wrapped posteriorly; frames the mouth aperture cut through the shell behind it.",geometryDescriptor:{topologyIntent:"A tube swept along the grimace curve u2014 corners pulled up and wrapped posteriorly; frames the mouth aperture cut through the shell behind it.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[-.2573,-.632,.2311],[-.1415,-.685,.2794],[0,-.707,.2964],[.1415,-.685,.2794],[.2573,-.632,.2311]],radius:.044,closed:!1}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"lower-lip-seat",localStart:[-.2573,-.632,.2311],localEnd:[.2573,-.632,.2311],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,0,1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Ae.add(nt),i["lower-lip"]=nt,a["lower-lip"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(Ae);let _t=Lt({parentId:"mask-shell",parentSocket:"rim-seat",localStart:[.4264,.1595,-.162],localEnd:[-.4264,.1595,-.2338],contactType:"flush",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[0,0,-1]}),ut=new He;ut.name="Posterior rim__pivot",ut.scale.set(1,1,1),_t?(ut.position.copy(_t.start),ut.rotation.set(0,0,0)):(ut.position.set(0,0,0),ut.rotation.set(0,0,0)),ut.userData.sculptComponent={id:"posterior-rim",name:"Posterior rim",level:"meso",role:"body",importance:.7,confidence:.8,primitive:"tube",topologyClass:"conforming-shell",topologyRationale:"The wall-thickness rim terminating the shell u2014 a closed tube loop following the opening edge (cranium apex, behind the ear, around the jaw), matching the rear view's thickened lip.",geometryDescriptor:{topologyIntent:"The wall-thickness rim terminating the shell u2014 a closed tube loop following the opening edge (cranium apex, behind the ear, around the jaw), matching the rear view's thickened lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[.4264,.1595,-.162],[.3693,.4333,-.2338],[.2132,.6337,-.2338],[0,.7071,-.2338],[-.2132,.6337,-.2338],[-.3693,.4333,-.2338],[-.4264,.1595,-.2338],[-.3693,-.6149,-.162],[-.2132,-.789,-.162],[-0,-.8527,-.162],[.2132,-.789,-.162],[.3693,-.6149,-.162]],radius:.026,closed:!0}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"rim-seat",localStart:[.4264,.1595,-.162],localEnd:[-.4264,.1595,-.2338],contactType:"flush",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[0,0,-1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"rim-edge",kind:"seam",description:"Continuous closed rim edge; the shell terminates here",evidenceRegion:"rear"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["rear","profile"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},ut.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(ut),n["posterior-rim"]=ut;let vi=_t?new Pt(_t.endRadius,_t.baseRadius,_t.length,32,12):bl({points:[[.4264,.1595,-.162],[.3693,.4333,-.2338],[.2132,.6337,-.2338],[0,.7071,-.2338],[-.2132,.6337,-.2338],[-.3693,.4333,-.2338],[-.4264,.1595,-.2338],[-.3693,-.6149,-.162],[-.2132,-.789,-.162],[-0,-.8527,-.162],[.2132,-.789,-.162],[.3693,-.6149,-.162]],radius:.026,closed:!0});_t||vi.scale(1,1,1);let bt=new De(vi,t["clay-shell"]??new Et({color:8947848}));bt.name="Posterior rim",_t&&(bt.position.copy(_t.midpoint),bt.quaternion.copy(_t.quaternion)),bt.castShadow=r.castShadow??!0,bt.receiveShadow=r.receiveShadow??!0,bt.userData.sculptComponent={id:"posterior-rim",name:"Posterior rim",level:"meso",role:"body",importance:.7,confidence:.8,primitive:"tube",topologyClass:"conforming-shell",topologyRationale:"The wall-thickness rim terminating the shell u2014 a closed tube loop following the opening edge (cranium apex, behind the ear, around the jaw), matching the rear view's thickened lip.",geometryDescriptor:{topologyIntent:"The wall-thickness rim terminating the shell u2014 a closed tube loop following the opening edge (cranium apex, behind the ear, around the jaw), matching the rear view's thickened lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[.4264,.1595,-.162],[.3693,.4333,-.2338],[.2132,.6337,-.2338],[0,.7071,-.2338],[-.2132,.6337,-.2338],[-.3693,.4333,-.2338],[-.4264,.1595,-.2338],[-.3693,-.6149,-.162],[-.2132,-.789,-.162],[-0,-.8527,-.162],[.2132,-.789,-.162],[.3693,-.6149,-.162]],radius:.026,closed:!0}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"rim-seat",localStart:[.4264,.1595,-.162],localEnd:[-.4264,.1595,-.2338],contactType:"flush",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[0,0,-1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[{id:"rim-edge",kind:"seam",description:"Continuous closed rim edge; the shell terminates here",evidenceRegion:"rear"}],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["rear","profile"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},ut.add(bt),i["posterior-rim"]=bt,a["posterior-rim"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(ut);let mt=Lt({parentId:"mask-shell",parentSocket:"fold-seat-l",localStart:[.115,-.297,.3786],localEnd:[.235,-.56,.298],contactType:"overlap",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[.3,0,.95]}),gt=new He;gt.name="Nasolabial fold (l)__pivot",gt.scale.set(1,1,1),mt?(gt.position.copy(mt.start),gt.rotation.set(0,0,0)):(gt.position.set(0,0,0),gt.rotation.set(0,0,0)),gt.userData.sculptComponent={id:"nasolabial-ridge-l",name:"Nasolabial fold (l)",level:"micro",role:"body",importance:.5,confidence:.75,primitive:"tube",topologyClass:"surface-relief",topologyRationale:"The fold from the ala to the mouth corner u2014 positive relief as a thin swept ridge.",geometryDescriptor:{topologyIntent:"The fold from the ala to the mouth corner u2014 positive relief as a thin swept ridge.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[.115,-.297,.3786],[.175,-.437,.3598],[.235,-.56,.298]],radius:.018,closed:!1}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"fold-seat-l",localStart:[.115,-.297,.3786],localEnd:[.235,-.56,.298],contactType:"overlap",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[.3,0,.95]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},gt.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(gt),n["nasolabial-ridge-l"]=gt;let rn=mt?new Pt(mt.endRadius,mt.baseRadius,mt.length,32,12):bl({points:[[.115,-.297,.3786],[.175,-.437,.3598],[.235,-.56,.298]],radius:.018,closed:!1});mt||rn.scale(1,1,1);let dn=new De(rn,t["clay-shell"]??new Et({color:8947848}));dn.name="Nasolabial fold (l)",mt&&(dn.position.copy(mt.midpoint),dn.quaternion.copy(mt.quaternion)),dn.castShadow=r.castShadow??!0,dn.receiveShadow=r.receiveShadow??!0,dn.userData.sculptComponent={id:"nasolabial-ridge-l",name:"Nasolabial fold (l)",level:"micro",role:"body",importance:.5,confidence:.75,primitive:"tube",topologyClass:"surface-relief",topologyRationale:"The fold from the ala to the mouth corner u2014 positive relief as a thin swept ridge.",geometryDescriptor:{topologyIntent:"The fold from the ala to the mouth corner u2014 positive relief as a thin swept ridge.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[.115,-.297,.3786],[.175,-.437,.3598],[.235,-.56,.298]],radius:.018,closed:!1}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"fold-seat-l",localStart:[.115,-.297,.3786],localEnd:[.235,-.56,.298],contactType:"overlap",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[.3,0,.95]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},gt.add(dn),i["nasolabial-ridge-l"]=dn,a["nasolabial-ridge-l"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(gt);let hn=Lt({parentId:"mask-shell",parentSocket:"fold-seat-r",localStart:[-.115,-.297,.3786],localEnd:[-.235,-.56,.298],contactType:"overlap",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[-.3,0,.95]}),Kt=new He;Kt.name="Nasolabial fold (r)__pivot",Kt.scale.set(1,1,1),hn?(Kt.position.copy(hn.start),Kt.rotation.set(0,0,0)):(Kt.position.set(0,0,0),Kt.rotation.set(0,0,0)),Kt.userData.sculptComponent={id:"nasolabial-ridge-r",name:"Nasolabial fold (r)",level:"micro",role:"body",importance:.5,confidence:.75,primitive:"tube",topologyClass:"surface-relief",topologyRationale:"The fold from the ala to the mouth corner u2014 positive relief as a thin swept ridge.",geometryDescriptor:{topologyIntent:"The fold from the ala to the mouth corner u2014 positive relief as a thin swept ridge.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[-.115,-.297,.3786],[-.175,-.437,.3598],[-.235,-.56,.298]],radius:.018,closed:!1}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"fold-seat-r",localStart:[-.115,-.297,.3786],localEnd:[-.235,-.56,.298],contactType:"overlap",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[-.3,0,.95]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Kt.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(Kt),n["nasolabial-ridge-r"]=Kt;let gr=hn?new Pt(hn.endRadius,hn.baseRadius,hn.length,32,12):bl({points:[[-.115,-.297,.3786],[-.175,-.437,.3598],[-.235,-.56,.298]],radius:.018,closed:!1});hn||gr.scale(1,1,1);let Si=new De(gr,t["clay-shell"]??new Et({color:8947848}));Si.name="Nasolabial fold (r)",hn&&(Si.position.copy(hn.midpoint),Si.quaternion.copy(hn.quaternion)),Si.castShadow=r.castShadow??!0,Si.receiveShadow=r.receiveShadow??!0,Si.userData.sculptComponent={id:"nasolabial-ridge-r",name:"Nasolabial fold (r)",level:"micro",role:"body",importance:.5,confidence:.75,primitive:"tube",topologyClass:"surface-relief",topologyRationale:"The fold from the ala to the mouth corner u2014 positive relief as a thin swept ridge.",geometryDescriptor:{topologyIntent:"The fold from the ala to the mouth corner u2014 positive relief as a thin swept ridge.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[-.115,-.297,.3786],[-.175,-.437,.3598],[-.235,-.56,.298]],radius:.018,closed:!1}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"fold-seat-r",localStart:[-.115,-.297,.3786],localEnd:[-.235,-.56,.298],contactType:"overlap",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[-.3,0,.95]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Kt.add(Si),i["nasolabial-ridge-r"]=Si,a["nasolabial-ridge-r"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(Kt);let ii=Lt({parentId:"horn-l",parentSocket:"horn-socket-l",localStart:[0,0,0],localEnd:[0,0,.02],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[.45,.85,.1]}),An=new He;An.name="Horn base collar (l)__pivot",An.scale.set(1,1,1),ii?(An.position.copy(ii.start),An.rotation.set(0,0,0)):(An.position.set(0,0,0),An.rotation.set(0,0,0)),An.userData.sculptComponent={id:"horn-collar-ring-l",name:"Horn base collar (l)",level:"micro",role:"body",importance:.4,confidence:.75,primitive:"tube",topologyClass:"surface-relief",topologyRationale:"The raised ring where the horn seats into the skull u2014 a socket seam read as a torus lip.",geometryDescriptor:{topologyIntent:"The raised ring where the horn seats into the skull u2014 a socket seam read as a torus lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[.5431,.0279,.063],[.5105,.0325,-.0414],[.4424,.0713,-.1179],[.3571,.1339,-.1458],[.2774,.2036,-.1179],[.2247,.2616,-.0414],[.2131,.2924,.063],[.2457,.2878,.1674],[.3138,.249,.2438],[.3991,.1864,.2718],[.4788,.1167,.2438],[.5315,.0587,.1674]],radius:.0392,closed:!0}},parent:"horn-l",attachment:{parentId:"horn-l",parentSocket:"horn-socket-l",localStart:[0,0,0],localEnd:[0,0,.02],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[.45,.85,.1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.8},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","three-quarter"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},An.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["horn-l"]??e).add(An),n["horn-collar-ring-l"]=An;let gp=ii?new Pt(ii.endRadius,ii.baseRadius,ii.length,32,12):bl({points:[[.5431,.0279,.063],[.5105,.0325,-.0414],[.4424,.0713,-.1179],[.3571,.1339,-.1458],[.2774,.2036,-.1179],[.2247,.2616,-.0414],[.2131,.2924,.063],[.2457,.2878,.1674],[.3138,.249,.2438],[.3991,.1864,.2718],[.4788,.1167,.2438],[.5315,.0587,.1674]],radius:.0392,closed:!0});ii||gp.scale(1,1,1);let Ls=new De(gp,t["clay-shell"]??new Et({color:8947848}));Ls.name="Horn base collar (l)",ii&&(Ls.position.copy(ii.midpoint),Ls.quaternion.copy(ii.quaternion)),Ls.castShadow=r.castShadow??!0,Ls.receiveShadow=r.receiveShadow??!0,Ls.userData.sculptComponent={id:"horn-collar-ring-l",name:"Horn base collar (l)",level:"micro",role:"body",importance:.4,confidence:.75,primitive:"tube",topologyClass:"surface-relief",topologyRationale:"The raised ring where the horn seats into the skull u2014 a socket seam read as a torus lip.",geometryDescriptor:{topologyIntent:"The raised ring where the horn seats into the skull u2014 a socket seam read as a torus lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[.5431,.0279,.063],[.5105,.0325,-.0414],[.4424,.0713,-.1179],[.3571,.1339,-.1458],[.2774,.2036,-.1179],[.2247,.2616,-.0414],[.2131,.2924,.063],[.2457,.2878,.1674],[.3138,.249,.2438],[.3991,.1864,.2718],[.4788,.1167,.2438],[.5315,.0587,.1674]],radius:.0392,closed:!0}},parent:"horn-l",attachment:{parentId:"horn-l",parentSocket:"horn-socket-l",localStart:[0,0,0],localEnd:[0,0,.02],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[.45,.85,.1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.8},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","three-quarter"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},An.add(Ls),i["horn-collar-ring-l"]=Ls,a["horn-collar-ring-l"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(An);let Gi=Lt({parentId:"horn-r",parentSocket:"horn-socket-r",localStart:[0,0,0],localEnd:[0,0,.02],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[-.45,.85,.1]}),si=new He;si.name="Horn base collar (r)__pivot",si.scale.set(1,1,1),Gi?(si.position.copy(Gi.start),si.rotation.set(0,0,0)):(si.position.set(0,0,0),si.rotation.set(0,0,0)),si.userData.sculptComponent={id:"horn-collar-ring-r",name:"Horn base collar (r)",level:"micro",role:"body",importance:.4,confidence:.75,primitive:"tube",topologyClass:"surface-relief",topologyRationale:"The raised ring where the horn seats into the skull u2014 a socket seam read as a torus lip.",geometryDescriptor:{topologyIntent:"The raised ring where the horn seats into the skull u2014 a socket seam read as a torus lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[-.2131,.2924,.063],[-.2247,.2616,-.0414],[-.2774,.2036,-.1179],[-.3571,.1339,-.1458],[-.4424,.0713,-.1179],[-.5105,.0325,-.0414],[-.5431,.0279,.063],[-.5315,.0587,.1674],[-.4788,.1167,.2438],[-.3991,.1864,.2718],[-.3138,.249,.2438],[-.2457,.2878,.1674]],radius:.0392,closed:!0}},parent:"horn-r",attachment:{parentId:"horn-r",parentSocket:"horn-socket-r",localStart:[0,0,0],localEnd:[0,0,.02],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[-.45,.85,.1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.8},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","three-quarter"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},si.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["horn-r"]??e).add(si),n["horn-collar-ring-r"]=si;let AT=Gi?new Pt(Gi.endRadius,Gi.baseRadius,Gi.length,32,12):bl({points:[[-.2131,.2924,.063],[-.2247,.2616,-.0414],[-.2774,.2036,-.1179],[-.3571,.1339,-.1458],[-.4424,.0713,-.1179],[-.5105,.0325,-.0414],[-.5431,.0279,.063],[-.5315,.0587,.1674],[-.4788,.1167,.2438],[-.3991,.1864,.2718],[-.3138,.249,.2438],[-.2457,.2878,.1674]],radius:.0392,closed:!0});Gi||AT.scale(1,1,1);let Kr=new De(AT,t["clay-shell"]??new Et({color:8947848}));Kr.name="Horn base collar (r)",Gi&&(Kr.position.copy(Gi.midpoint),Kr.quaternion.copy(Gi.quaternion)),Kr.castShadow=r.castShadow??!0,Kr.receiveShadow=r.receiveShadow??!0,Kr.userData.sculptComponent={id:"horn-collar-ring-r",name:"Horn base collar (r)",level:"micro",role:"body",importance:.4,confidence:.75,primitive:"tube",topologyClass:"surface-relief",topologyRationale:"The raised ring where the horn seats into the skull u2014 a socket seam read as a torus lip.",geometryDescriptor:{topologyIntent:"The raised ring where the horn seats into the skull u2014 a socket seam read as a torus lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",tubePath:{points:[[-.2131,.2924,.063],[-.2247,.2616,-.0414],[-.2774,.2036,-.1179],[-.3571,.1339,-.1458],[-.4424,.0713,-.1179],[-.5105,.0325,-.0414],[-.5431,.0279,.063],[-.5315,.0587,.1674],[-.4788,.1167,.2438],[-.3991,.1864,.2718],[-.3138,.249,.2438],[-.2457,.2878,.1674]],radius:.0392,closed:!0}},parent:"horn-r",attachment:{parentId:"horn-r",parentSocket:"horn-socket-r",localStart:[0,0,0],localEnd:[0,0,.02],contactType:"overlap",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[-.45,.85,.1]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.8},transform:{position:[0,0,0],rotation:[0,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"clay-shell",materialLayers:["clay-shell"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","three-quarter"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(185, 182, 178, 1.0)",secondaryAlbedo:"rgba(168, 165, 161, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},si.add(Kr),i["horn-collar-ring-r"]=Kr,a["horn-collar-ring-r"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(si);let Bs=Lt(null),zi=new He;zi.name="upper fang l__pivot",zi.scale.set(1,1,1),Bs?(zi.position.copy(Bs.start),zi.rotation.set(3.141592653589793,0,.1)):(zi.position.set(.1662,-.615,.3167),zi.rotation.set(3.141592653589793,0,.1)),zi.userData.sculptComponent={id:"upper-fang-l",name:"upper fang l",level:"micro",role:"body",importance:.85,confidence:.9,primitive:"lathe",topologyClass:"continuous-sculpt",topologyRationale:"A fang: cone tapering to a point, projecting into the mouth aperture downward from the upper lip.",geometryDescriptor:{topologyIntent:"A fang: cone tapering to a point, projecting into the mouth aperture downward from the upper lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",latheProfile:{points:[[8e-4,-.0775],[.03,-.06665],[.020999999999999998,-.012400000000000008],[.008400000000000001,.0465],[8e-4,.0775]],segments:14}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"upper-lip-underside-l",localStart:[0,.05,0],localEnd:[0,-.08,0],contactType:"butt",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,-1,0]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[.1662,-.615,.3167],rotation:[3.141592653589793,0,.1],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},zi.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(zi),n["upper-fang-l"]=zi;let CT=Bs?new Pt(Bs.endRadius,Bs.baseRadius,Bs.length,32,12):n0({points:[[8e-4,-.0775],[.03,-.06665],[.020999999999999998,-.012400000000000008],[.008400000000000001,.0465],[8e-4,.0775]],segments:14});Bs||CT.scale(1,1,1);let Zr=new De(CT,t.dentition??new Et({color:8947848}));Zr.name="upper fang l",Bs&&(Zr.position.copy(Bs.midpoint),Zr.quaternion.copy(Bs.quaternion)),Zr.castShadow=r.castShadow??!0,Zr.receiveShadow=r.receiveShadow??!0,Zr.userData.sculptComponent={id:"upper-fang-l",name:"upper fang l",level:"micro",role:"body",importance:.85,confidence:.9,primitive:"lathe",topologyClass:"continuous-sculpt",topologyRationale:"A fang: cone tapering to a point, projecting into the mouth aperture downward from the upper lip.",geometryDescriptor:{topologyIntent:"A fang: cone tapering to a point, projecting into the mouth aperture downward from the upper lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",latheProfile:{points:[[8e-4,-.0775],[.03,-.06665],[.020999999999999998,-.012400000000000008],[.008400000000000001,.0465],[8e-4,.0775]],segments:14}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"upper-lip-underside-l",localStart:[0,.05,0],localEnd:[0,-.08,0],contactType:"butt",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,-1,0]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[.1662,-.615,.3167],rotation:[3.141592653589793,0,.1],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},zi.add(Zr),i["upper-fang-l"]=Zr,a["upper-fang-l"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(zi);let Us=Lt(null),Hi=new He;Hi.name="upper fang r__pivot",Hi.scale.set(1,1,1),Us?(Hi.position.copy(Us.start),Hi.rotation.set(3.141592653589793,0,-.1)):(Hi.position.set(-.1662,-.615,.3167),Hi.rotation.set(3.141592653589793,0,-.1)),Hi.userData.sculptComponent={id:"upper-fang-r",name:"upper fang r",level:"micro",role:"body",importance:.85,confidence:.9,primitive:"lathe",topologyClass:"continuous-sculpt",topologyRationale:"A fang: cone tapering to a point, projecting into the mouth aperture downward from the upper lip.",geometryDescriptor:{topologyIntent:"A fang: cone tapering to a point, projecting into the mouth aperture downward from the upper lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",latheProfile:{points:[[8e-4,-.0775],[.03,-.06665],[.020999999999999998,-.012400000000000008],[.008400000000000001,.0465],[8e-4,.0775]],segments:14}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"upper-lip-underside-r",localStart:[0,.05,0],localEnd:[0,-.08,0],contactType:"butt",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,-1,0]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[-.1662,-.615,.3167],rotation:[3.141592653589793,0,-.1],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Hi.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(Hi),n["upper-fang-r"]=Hi;let NT=Us?new Pt(Us.endRadius,Us.baseRadius,Us.length,32,12):n0({points:[[8e-4,-.0775],[.03,-.06665],[.020999999999999998,-.012400000000000008],[.008400000000000001,.0465],[8e-4,.0775]],segments:14});Us||NT.scale(1,1,1);let Jr=new De(NT,t.dentition??new Et({color:8947848}));Jr.name="upper fang r",Us&&(Jr.position.copy(Us.midpoint),Jr.quaternion.copy(Us.quaternion)),Jr.castShadow=r.castShadow??!0,Jr.receiveShadow=r.receiveShadow??!0,Jr.userData.sculptComponent={id:"upper-fang-r",name:"upper fang r",level:"micro",role:"body",importance:.85,confidence:.9,primitive:"lathe",topologyClass:"continuous-sculpt",topologyRationale:"A fang: cone tapering to a point, projecting into the mouth aperture downward from the upper lip.",geometryDescriptor:{topologyIntent:"A fang: cone tapering to a point, projecting into the mouth aperture downward from the upper lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",latheProfile:{points:[[8e-4,-.0775],[.03,-.06665],[.020999999999999998,-.012400000000000008],[.008400000000000001,.0465],[8e-4,.0775]],segments:14}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"upper-lip-underside-r",localStart:[0,.05,0],localEnd:[0,-.08,0],contactType:"butt",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,-1,0]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[-.1662,-.615,.3167],rotation:[3.141592653589793,0,-.1],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Hi.add(Jr),i["upper-fang-r"]=Jr,a["upper-fang-r"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(Hi);let Os=Lt(null),Wi=new He;Wi.name="lower fang l__pivot",Wi.scale.set(1,1,1),Os?(Wi.position.copy(Os.start),Wi.rotation.set(0,0,-.08)):(Wi.position.set(.2144,-.65,.268),Wi.rotation.set(0,0,-.08)),Wi.userData.sculptComponent={id:"lower-fang-l",name:"lower fang l",level:"micro",role:"body",importance:.85,confidence:.9,primitive:"lathe",topologyClass:"continuous-sculpt",topologyRationale:"A fang: cone tapering to a point, projecting into the mouth aperture upward from the lower lip.",geometryDescriptor:{topologyIntent:"A fang: cone tapering to a point, projecting into the mouth aperture upward from the lower lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",latheProfile:{points:[[8e-4,-.05],[.024,-.043000000000000003],[.0168,-.008],[.006720000000000001,.03],[8e-4,.05]],segments:14}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"lower-lip-crest-l",localStart:[0,-.05,0],localEnd:[0,.05,0],contactType:"butt",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,1,0]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[.2144,-.65,.268],rotation:[0,0,-.08],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Wi.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(Wi),n["lower-fang-l"]=Wi;let PT=Os?new Pt(Os.endRadius,Os.baseRadius,Os.length,32,12):n0({points:[[8e-4,-.05],[.024,-.043000000000000003],[.0168,-.008],[.006720000000000001,.03],[8e-4,.05]],segments:14});Os||PT.scale(1,1,1);let Qr=new De(PT,t.dentition??new Et({color:8947848}));Qr.name="lower fang l",Os&&(Qr.position.copy(Os.midpoint),Qr.quaternion.copy(Os.quaternion)),Qr.castShadow=r.castShadow??!0,Qr.receiveShadow=r.receiveShadow??!0,Qr.userData.sculptComponent={id:"lower-fang-l",name:"lower fang l",level:"micro",role:"body",importance:.85,confidence:.9,primitive:"lathe",topologyClass:"continuous-sculpt",topologyRationale:"A fang: cone tapering to a point, projecting into the mouth aperture upward from the lower lip.",geometryDescriptor:{topologyIntent:"A fang: cone tapering to a point, projecting into the mouth aperture upward from the lower lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",latheProfile:{points:[[8e-4,-.05],[.024,-.043000000000000003],[.0168,-.008],[.006720000000000001,.03],[8e-4,.05]],segments:14}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"lower-lip-crest-l",localStart:[0,-.05,0],localEnd:[0,.05,0],contactType:"butt",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,1,0]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[.2144,-.65,.268],rotation:[0,0,-.08],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},Wi.add(Qr),i["lower-fang-l"]=Qr,a["lower-fang-l"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(Wi);let ks=Lt(null),qi=new He;qi.name="lower fang r__pivot",qi.scale.set(1,1,1),ks?(qi.position.copy(ks.start),qi.rotation.set(0,0,.08)):(qi.position.set(-.2144,-.65,.268),qi.rotation.set(0,0,.08)),qi.userData.sculptComponent={id:"lower-fang-r",name:"lower fang r",level:"micro",role:"body",importance:.85,confidence:.9,primitive:"lathe",topologyClass:"continuous-sculpt",topologyRationale:"A fang: cone tapering to a point, projecting into the mouth aperture upward from the lower lip.",geometryDescriptor:{topologyIntent:"A fang: cone tapering to a point, projecting into the mouth aperture upward from the lower lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",latheProfile:{points:[[8e-4,-.05],[.024,-.043000000000000003],[.0168,-.008],[.006720000000000001,.03],[8e-4,.05]],segments:14}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"lower-lip-crest-r",localStart:[0,-.05,0],localEnd:[0,.05,0],contactType:"butt",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,1,0]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[-.2144,-.65,.268],rotation:[0,0,.08],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},qi.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add(qi),n["lower-fang-r"]=qi;let DT=ks?new Pt(ks.endRadius,ks.baseRadius,ks.length,32,12):n0({points:[[8e-4,-.05],[.024,-.043000000000000003],[.0168,-.008],[.006720000000000001,.03],[8e-4,.05]],segments:14});ks||DT.scale(1,1,1);let ea=new De(DT,t.dentition??new Et({color:8947848}));ea.name="lower fang r",ks&&(ea.position.copy(ks.midpoint),ea.quaternion.copy(ks.quaternion)),ea.castShadow=r.castShadow??!0,ea.receiveShadow=r.receiveShadow??!0,ea.userData.sculptComponent={id:"lower-fang-r",name:"lower fang r",level:"micro",role:"body",importance:.85,confidence:.9,primitive:"lathe",topologyClass:"continuous-sculpt",topologyRationale:"A fang: cone tapering to a point, projecting into the mouth aperture upward from the lower lip.",geometryDescriptor:{topologyIntent:"A fang: cone tapering to a point, projecting into the mouth aperture upward from the lower lip.",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",latheProfile:{points:[[8e-4,-.05],[.024,-.043000000000000003],[.0168,-.008],[.006720000000000001,.03],[8e-4,.05]],segments:14}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"lower-lip-crest-r",localStart:[0,-.05,0],localEnd:[0,.05,0],contactType:"butt",embedDepth:.03,overlap:.03,gapTolerance:.01,contactNormal:[0,1,0]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[-.2144,-.65,.268],rotation:[0,0,.08],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},qi.add(ea),i["lower-fang-r"]=ea,a["lower-fang-r"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push(qi);let Vs=Lt(null),$i=new He;$i.name="Incisor row__pivot",$i.scale.set(1,1,1),Vs?($i.position.copy(Vs.start),$i.rotation.set(-.4,0,0)):($i.position.set(0,-.593,.3275),$i.rotation.set(-.4,0,0)),$i.userData.sculptComponent={id:"incisor-row",name:"Incisor row",level:"micro",role:"body",importance:.8,confidence:.85,primitive:"extrude",topologyClass:"assembled-solid",topologyRationale:"Six rectangular incisors from a common gum bar u2014 one comb profile extruded thin. Declared as the repetition system 'incisor-row' (component-expanded).",geometryDescriptor:{topologyIntent:"Six rectangular incisors from a common gum bar u2014 one comb profile extruded thin. Declared as the repetition system 'incisor-row' (component-expanded).",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",profile2D:{points:[[-.14049999999999999,.028],[.14049999999999999,.028],[.1405,0],[.1351,-.055],[.1099,-.055],[.1045,0],[.0915,0],[.0861,-.055],[.0609,-.055],[.0555,0],[.0425,0],[.0371,-.055],[.0119,-.055],[.0065,0],[-.0065,0],[-.0119,-.055],[-.0371,-.055],[-.0425,0],[-.0555,0],[-.0609,-.055],[-.0861,-.055],[-.0915,0],[-.1045,0],[-.1099,-.055],[-.1351,-.055],[-.1405,0]],depth:.05}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"upper-lip-underside-center",localStart:[-.10725,0,0],localEnd:[.10725,0,0],contactType:"flush",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[0,-.4,.9]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,-.593,.3275],rotation:[-.4,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},$i.userData.actionProfile={animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},(n["mask-shell"]??e).add($i),n["incisor-row"]=$i;let IT=Vs?new Pt(Vs.endRadius,Vs.baseRadius,Vs.length,32,12):t0({points:[[-.14049999999999999,.028],[.14049999999999999,.028],[.1405,0],[.1351,-.055],[.1099,-.055],[.1045,0],[.0915,0],[.0861,-.055],[.0609,-.055],[.0555,0],[.0425,0],[.0371,-.055],[.0119,-.055],[.0065,0],[-.0065,0],[-.0119,-.055],[-.0371,-.055],[-.0425,0],[-.0555,0],[-.0609,-.055],[-.0861,-.055],[-.0915,0],[-.1045,0],[-.1099,-.055],[-.1351,-.055],[-.1405,0]],depth:.05});Vs||IT.scale(1,1,1);let ta=new De(IT,t.dentition??new Et({color:8947848}));return ta.name="Incisor row",Vs&&(ta.position.copy(Vs.midpoint),ta.quaternion.copy(Vs.quaternion)),ta.castShadow=r.castShadow??!0,ta.receiveShadow=r.receiveShadow??!0,ta.userData.sculptComponent={id:"incisor-row",name:"Incisor row",level:"micro",role:"body",importance:.8,confidence:.85,primitive:"extrude",topologyClass:"assembled-solid",topologyRationale:"Six rectangular incisors from a common gum bar u2014 one comb profile extruded thin. Declared as the repetition system 'incisor-row' (component-expanded).",geometryDescriptor:{topologyIntent:"Six rectangular incisors from a common gum bar u2014 one comb profile extruded thin. Declared as the repetition system 'incisor-row' (component-expanded).",edgeTreatment:{type:"none",bevelRadius:0,segments:1},deformationStack:[],uvStrategy:"generated procedural coordinates",normalStrategy:"vertex normals from generated geometry",profile2D:{points:[[-.14049999999999999,.028],[.14049999999999999,.028],[.1405,0],[.1351,-.055],[.1099,-.055],[.1045,0],[.0915,0],[.0861,-.055],[.0609,-.055],[.0555,0],[.0425,0],[.0371,-.055],[.0119,-.055],[.0065,0],[-.0065,0],[-.0119,-.055],[-.0371,-.055],[-.0425,0],[-.0555,0],[-.0609,-.055],[-.0861,-.055],[-.0915,0],[-.1045,0],[-.1099,-.055],[-.1351,-.055],[-.1405,0]],depth:.05}},parent:"mask-shell",attachment:{parentId:"mask-shell",parentSocket:"upper-lip-underside-center",localStart:[-.10725,0,0],localEnd:[.10725,0,0],contactType:"flush",embedDepth:.02,overlap:.02,gapTolerance:.01,contactNormal:[0,-.4,.9]},dimensions:{width:1,height:1,depth:1,units:"relative",confidence:.85},transform:{position:[0,-.593,.3275],rotation:[-.4,0,0],scale:[1,1,1]},actionProfile:{animationRole:"static-part",pivot:{mode:"custom",localPosition:[0,0,0],axis:[0,1,0],confidence:.8},transformChannels:{translate:!0,rotate:!0,scale:!0,bend:!1,twist:!1,detach:!0,visibility:!0,materialState:!0},sockets:[],constraints:[],collider:{type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},destruction:{breakable:!1,fractureGroup:"mask",seamRefs:[],detachableFragments:[],breakImpulse:0,debrisMaterial:"clay-shell"}},material:"dentition",materialLayers:["dentition"],deformations:[],joints:[],seams:[],localFeatures:[],surfaceDetail:{macroRoughness:.35,microRoughness:.12,bumpAmplitude:0,normalPattern:"smooth",displacementPattern:"",occlusionPattern:"cavity",edgeWearPattern:"",notes:""},evidenceRefs:["front","below"],details:[],fidelityTier:"blockout",colorMaterialRecipe:{dominantAlbedo:"rgba(203, 200, 195, 1.0)",secondaryAlbedo:"rgba(185, 182, 178, 1.0)",materialClass:"ceramic",materialClassConfidence:.5,notes:"Reference is an achromatic clay preview; class 'ceramic' is the nearest match for a matte rigid mask shell and is declared, not extracted."}},$i.add(ta),i["incisor-row"]=ta,a["incisor-row"]={type:"box",offset:[0,0,0],scale:[1,1,1],isTrigger:!1,notes:"box proxy is adequate for a static prop part"},o.mask??=[],o.mask.push($i),e.userData.sculptRuntime={nodes:n,meshes:i,sockets:s,colliders:a,destructionGroups:o},e.userData.lookDevTargets={qualityPriority:"reference-fidelity",materialPass:{albedoPaletteRequired:!0,roughnessVariationRequired:!0,normalOrBumpRequired:!0,localOverridesRequired:!0,minimumTextureResolution:1024,preferredTextureResolution:2048,independentMapChannels:["albedo","roughness","height","normal","ambient-occlusion"],requiredSurfaceFrequencyBands:["macro","meso","micro"],geometryReliefRequiredWhenSilhouetteAffected:!0,referencePbrExtraction:{requiredWhenSourceImagePresent:!0,targetThreshold:.7,stopOnLowConfidence:!0,script:"forge/stage1_intake/extract_pbr_evidence.py",acceptedLimitation:"single-image extraction is reference-derived inference, not exact photogrammetry"},mustAvoid:["single flat albedo per material","uniform roughness","albedo texture reused as roughness/height/normal/AO","single-frequency random noise","plastic-looking smooth bark, stone, cloth, foliage, or aged material","local color/detail described only in prose without material masks","claiming exact PBR recovery when confidence is below the target threshold"]},lightingPass:{requiredTerms:["key light","fill light","rim or environment light","exposure","tone mapping","background","contact shadow"],mustAvoid:["ambient-only lighting","flat value range","missing contact shadow","reference lighting copied without separating material readability"]},screenshotReview:["Compare albedo palette and local color zones.","Compare roughness/normal/bump response under light.","Compare cavity dirt, edge wear, stains, moss, scratches, or other local masks.","Compare key/fill/rim structure, exposure, tone mapping, background, and contact shadows.","Capture a neutral-light render to verify material readability without reference lighting.","Capture a grazing-light close-up to expose flat normals, uniform roughness, tiling, and plastic highlights.","Capture a reference-matched render from the same camera framing as the source."]},e.userData.actionReadiness={note:"Use root.userData.sculptRuntime.nodes for transforms, sockets for attachments, colliders for physics proxies, and destructionGroups for breakable sets."},e}var kC=2,GC=new yo;GC.set(0);var VC=4;function zC(){return typeof navigator<"u"&&!!navigator.gpu}async function HC(r,e={}){let t=e.verticalOffset??.02,n=e.distanceScale??1.55,i=()=>Math.max(1,innerWidth||0),s=()=>Math.max(1,innerHeight||0),a=new pg({antialias:!0});a.setPixelRatio(Math.min(devicePixelRatio,2)),a.setSize(i(),s()),a.toneMapping=Ki,a.domElement.setAttribute("role","img"),a.domElement.setAttribute("aria-label","A hannya mask wrapped in simulated fire."),r.appendChild(a.domElement),await a.init();let o=new fa,l=new an(40,i()/s(),.05,100),c=jg.sub(Ct(.5,.45)).mul(Ct(.9,1.2)).length();o.backgroundNode=zn(rp(262916),rp(1708300),Xt(.78,.05,c).pow(1.4).mul(.7));let u=new Sa(12175581,1.1);u.position.set(-2.2,4.5,2.6),o.add(u,new va(2830656,854794,.5));let d=new Ro(16747068,VC,0,2);d.position.set(0,.1,.35),o.add(d);let h=new vu({roughness:.92,metalness:.04});h.colorNode=rp(1710111).mul(Xt(5,1.2,vC.xy.length()));let p=new De(new Jl(6,64),h);p.rotation.x=-Math.PI*.5,p.position.y=-.75,o.add(p);let f=(Se,Je)=>et(1).sub(ap(xC,SC).abs()).pow(Se).mul(Je),m=OC();{let Se=new Yi().setFromObject(m),Je=new E,lt=new E;Se.getSize(Je),Se.getCenter(lt);let kt=1/Math.max(Je.y,1e-4);m.scale.setScalar(kt),m.position.set(-lt.x*kt,-lt.y*kt,-lt.z*kt)}let y=m.position.clone(),x=new Vh({color:1051659,metalness:.1,roughness:.58,clearcoat:.35,clearcoatRoughness:.5});x.emissiveNode=rp(16730644).mul(f(2.4,1.3).mul(.9).add(.03)),m.traverse(Se=>{let Je=Se;Je.isMesh&&(Je.material=x,Je.frustumCulled=!1,Je.layers.enable(kC))}),o.add(m);let b=new Qg(l,a.domElement);b.target.set(0,t,0),b.enableDamping=!0,b.dampingFactor=.06,b.enablePan=!1,b.minDistance=.7,b.maxDistance=5,l.position.set(0,t,1.5);let _=e.pinned??!1;_?(b.enabled=!1,b.autoRotate=!1):(b.autoRotate=e.autoRotate??!0,b.autoRotateSpeed=e.autoRotateSpeed??.6,a.domElement.addEventListener("pointerdown",()=>{b.autoRotate=!1})),b.update();let S={yaw:e.cursorYaw??.6,pitch:e.cursorPitch??.34,shift:e.cursorShift??.07,ease:e.cursorEase??.05},M=e.scrollRange??1,w=e.scrollZoom??.34,T=0,R=0,D=0,L=0,B=0,W=0,q=1.5,ce=Se=>{let Je=Se.clientX/i()*2-1,lt=Se.clientY/s()*2-1;T=Je*S.yaw,R=lt*S.pitch},k=Se=>{Se.relatedTarget||(T=0,R=0)},j=()=>{let Se=Math.max(1,M*s());B=Math.min(1,Math.max(0,scrollY/Se))};_&&(addEventListener("pointermove",ce,{passive:!0}),document.addEventListener("pointerout",k),addEventListener("scroll",j,{passive:!0}),j());let ee=PC({renderer:a,scene:o,camera:l,subjectLayer:kC,sceneLayers:GC}),ge=new O;function fe(){let Se=i(),Je=s();l.aspect=Se/Je,l.updateProjectionMatrix();let kt=1/(2*Math.tan(l.fov/2*(Math.PI/180)))/Math.min(1,l.aspect);q=Math.max(1.35,kt*n),_||l.position.setLength(q),l.lookAt(b.target),a.setSize(Se,Je),a.getDrawingBufferSize(ge),ee.setSize(ge.width,ge.height)}fe(),addEventListener("resize",fe);let he=performance.now(),ye=0,ze=0,Pe=0;function ot(Se){let Je=(Se-he)/1e3,lt=Math.min(Je,.05),kt=Math.min(Math.max(Je,0),.25);if(he=Se,ye++,ze+=lt,ze>=.5&&(Pe=ye/ze,ye=0,ze=0),_){let Rn=1-Math.pow(1-S.ease,kt*60);D+=(T-D)*Rn,L+=(R-L)*Rn,W+=(B-W)*Rn,m.rotation.set(L,D,0);let jt=W*W*(3-2*W),Ke=1+(w-1)*jt,K=S.shift*Ke,Q=S.yaw>0?D/S.yaw:0,re=S.pitch>0?L/S.pitch:0;m.position.set(y.x+Q*K,y.y-re*K,y.z),l.position.set(0,t,q*Ke),l.lookAt(b.target)}else b.update();let tt=Se/1e3,ti=.86+.14*(Math.sin(tt*17.3)*.5+Math.sin(tt*29.1+1.7)*.3+Math.sin(tt*7.7)*.2);return d.intensity=VC*ti*ee.u.burn.value,ee.render(lt),Pe}return{renderer:a,scene:o,camera:l,controls:b,model:m,flames:ee,motion:S,bufferSize:()=>ge.clone(),resize:fe,step:ot,dispose(){removeEventListener("resize",fe),removeEventListener("pointermove",ce),document.removeEventListener("pointerout",k),removeEventListener("scroll",j),a.setAnimationLoop(null),b.dispose(),ee.dispose(),a.dispose(),a.domElement.remove()}}}function WC(r){let{text:e,family:t="'Inter Tight', 'Inter', system-ui, sans-serif",weight:n=400,color:i="#F6EFDA",letterSpacing:s="-0.03em",margin:a=24,baseWidth:o=1470,bleed:l=27,maxHeightFraction:c=.42}=r,u=document.createElement("canvas");u.width=u.height=2;let d=u.getContext("2d"),h=new _a(u);h.colorSpace=Vt,h.flipY=!1,h.wrapS=h.wrapT=ai,h.generateMipmaps=!1,h.minFilter=St;function p(f,m){let y=Math.max(2,Math.floor(f)),x=Math.max(2,Math.floor(m));u.width=y,u.height=x,d.clearRect(0,0,y,x);let b=y/o,_=a*b,S=y-_*2;d.letterSpacing=s;let M=100;d.font=`${n} ${M}px ${t}`;let w=d.measureText(e).width/M;M=w>0?S/w:100,M=Math.min(M,x*c/.72),d.font=`${n} ${M}px ${t}`,d.letterSpacing=s,d.fillStyle=i,d.textAlign="left",d.textBaseline="alphabetic";let R=d.measureText(e).actualBoundingBoxDescent||0;return d.fillText(e,_,x+l*b-R),h.needsUpdate=!0,M}return{texture:h,resize:p,dispose(){h.dispose()}}}async function qC(r){if(!document.fonts)return!1;try{return await Promise.all(r.map(e=>document.fonts.load(e))),await document.fonts.ready,r.every(e=>document.fonts.check(e))}catch{return!1}}var r0=new Set,TT=0,s0=!1,$C=0,MT=0,XC=()=>window.scrollY;function YC(r){XC=r}var fp={y:0,H:0,time:0,dt:0};function jC(){let r=performance.now();fp.y=XC(),fp.H=window.innerHeight,fp.time=(r-$C)/1e3,fp.dt=Math.min((r-MT)/1e3,.1),MT=r;for(let e of r0)e(fp);TT=requestAnimationFrame(jC)}function oo(r){return r0.add(r),s0||(s0=!0,$C=MT=performance.now(),TT=requestAnimationFrame(jC)),()=>{r0.delete(r),r0.size===0&&s0&&(s0=!1,cancelAnimationFrame(TT))}}var KC=typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches,tK=typeof matchMedia<"u"&&matchMedia("(hover: hover) and (pointer: fine)").matches;var ZC="https://d8j0ntlcm91z4.cloudfront.net/user_3GJaYKPxdnQG0Q9O26lu6DPmcHu",lo=(r,e=1920)=>`https://images.higgs.ai/?default=1&output=webp&url=${encodeURIComponent(`${ZC}/${r}`)}&w=${e}&q=85`,O4=lo("hf_20260911_091755_d10337df-41a1-40eb-b426-ece300e6f5dd.png"),k4=lo("hf_20260911_091841_01f0c297-6fca-42d6-87fe-da2865d9c364.png"),V4=lo("hf_20260911_091846_72c99800-57a9-4d39-80c2-7768d8f4d556.png"),G4=lo("hf_20260911_091854_76cd1a76-8b9d-4003-b289-ed39974c5a1e.png"),z4=lo("hf_20260911_125735_c678d64c-22c1-4154-9500-412db0c453d8.png",720),H4=lo("hf_20260911_125838_cc288409-3b05-40ad-9466-3c207a38a9f7.png",720),W4=lo("hf_20260911_130330_8d67c81e-7527-494e-87fc-cc9b6cdaac3a.png",720),q4=lo("hf_20260911_130337_c65bbd62-a91b-4cbd-b9ea-1ab4a4ec969b.png",720),JC=`${ZC}/hf_20260911_125451_34d10d8e-e829-4dde-84bd-fd77156a4005.mp4`,jr=[{key:"fire",name:"Homura",epithet:"mask of fire",id:"131-234-2",description:"Black hinoki under red urushi. The burn lines are carved first, gilded, then lacquered over u2014 the glow sits under the skin, not on it. Danced once a year, at the closing of the summer fire rite.",background:"#910A0A",maskUrl:O4,textureUrl:z4},{key:"water",name:"u014Cnami",epithet:"mask of water",id:"131-234-3",description:"The Great Wave runs horn to jaw, brushed in gosu blue under a clear porcelain glaze. Gold marks where the crest breaks. Cold to the touch, even in July.",background:"#0B142D",maskUrl:k4,textureUrl:H4},{key:"earth",name:"Yamahada",epithet:"mask of earth",id:"131-234-4",description:"No lacquer. The grain stays open, mountain ridges cut into the brow, copper seams set the kintsugi way. Moss takes root where the horns meet the skull. Meant to age, not to shine.",background:"#403C1A",maskUrl:V4,textureUrl:W4},{key:"air",name:"Shirakumo",epithet:"mask of air",id:"131-234-5",description:"Bleached hinoki polished down to bone. Cloud spirals chased in silver, a breath of gold on lips and lids. The lightest mask in the set u2014 it moves before the dancer does.",background:"#070707",maskUrl:G4,textureUrl:q4}];var bi={HERO_VH:100,CUT_VH:60,COPY_VH:45,SLIDE_VH:150,FILM_START:0,FILM_ENTER:80,FILM_HOLD:140,RUNWAY:0,COVER_MARGIN:8};bi.FILM_START=bi.HERO_VH+4*bi.SLIDE_VH;bi.RUNWAY=bi.FILM_START+bi.FILM_ENTER+bi.FILM_HOLD+100;function QC(r){let e=document.getElementById("slides"),t=document.querySelector(".scroll-range");if(!e||!t)throw new Error("sections: #slides or .scroll-range missing");let{HERO_VH:n,CUT_VH:i,COPY_VH:s,SLIDE_VH:a,FILM_START:o,FILM_ENTER:l,COVER_MARGIN:c}=bi,u=bi.RUNWAY;t.style.height=`${u}vh`;let d=jr.map((x,b)=>{let _=document.createElement("section");_.className="slide",_.dataset.element=x.key,_.style.zIndex=String(10+b*10),_.style.setProperty("--slide-bg",x.background);let S=document.createElement("div");S.className="slide__inner";let M=document.createElement("h2");M.className="slide__head slide__item";let w=document.createElement("span");w.textContent=x.name;let T=document.createElement("span");T.textContent=x.epithet,M.append(w,document.createElement("br"),T);let R=document.createElement("p");R.className="slide__id slide__item",R.textContent=x.id;let D=document.createElement("p");D.className="slide__desc slide__item",D.textContent=x.description;let L=document.createElement("figure");L.className="slide__chip slide__item";let B=document.createElement("img");B.src=x.textureUrl,B.alt="",B.loading="eager",L.append(B);let W=document.createElement("img");return W.className="slide__mask",W.src=x.maskUrl,W.alt=`${x.name} u2014 hannya ${x.epithet}`,W.loading="eager",W.draggable=!1,S.append(M,R,D,L,W),_.append(S),_});e.append(...d);for(let x of jr){let b=new Image;b.src=x.maskUrl,b.decode().catch(()=>{})}let h=x=>x<0?0:x>1?1:x,p=!1,f=d.map(()=>["","","","",""]),m=(x,b,_,S)=>{f[x][b]!==S&&(f[x][b]=S,_==="visibility"?d[x].style.visibility=S:d[x].style.setProperty(_,S))},y=oo(({y:x,H:b})=>{let _=x/Math.max(1,b)*100;for(let w=0;w<jr.length;w++){let T=n+w*a,R=h((_-T)/i),D=h((_-T-i)/s),L=w<jr.length-1?a:o+l-(T+i),B=h((_-T-i)/L);m(w,0,"--reveal",R.toFixed(4)),m(w,1,"--copy",D.toFixed(4)),m(w,2,"--zoom",B.toFixed(4));let W=w<jr.length-1?n+(w+1)*a+i:o+l;m(w,3,"visibility",R>0&&_<W+c?"visible":"hidden")}let S=h((_-o)/l);m(jr.length-1,4,"--exit",S.toFixed(4));let M=_>=n+i+c;M!==p&&(p=M,r(p))});return{totalVh:u,dispose(){y();for(let x of d)x.remove()}}}var $4=bi.HERO_VH+2*bi.SLIDE_VH+bi.CUT_VH;function eN(){let r=document.getElementById("film");if(!r)throw new Error("film: #film missing");let{FILM_START:e,FILM_ENTER:t,FILM_HOLD:n,RUNWAY:i,COVER_MARGIN:s}=bi,a=document.createElement("video");a.className="film__video",a.muted=!0,a.loop=!0,a.playsInline=!0,a.preload="none",a.setAttribute("aria-hidden","true"),a.addEventListener("loadeddata",()=>{r.dataset.ready=""}),a.addEventListener("error",()=>{let x=a.error;console.info(`[film] media error${x?" code "+x.code:""}`)});let o=document.createElement("div");o.className="film__scrim";let l=document.createElement("h2");l.className="film__head film__item";let c=["Kurihara Su014Dgen","forty-one years","one bench"];for(let[x,b]of c.entries()){x&&l.append(document.createElement("br"));let _=document.createElement("span");_.textContent=b,l.append(_)}let u=document.createElement("p");u.className="film__desc film__item",u.textContent="Second-generation menuchi. He took the workshop from his father in 1998 and has cut every mask in the house since u2014 hinoki from Kiso, gofun he grinds himself. The wave faces are his alone; nobody else is allowed to paint them.",r.append(a,o,l,u);let d=x=>x<0?0:x>1?1:x,h=["","","",""],p=(x,b,_)=>{h[x]!==_&&(h[x]=_,b==="visibility"?r.style.visibility=_:r.style.setProperty(b,_))},f=!1,m=!1,y=oo(({y:x,H:b})=>{let _=x/Math.max(1,b)*100;!f&&_>=$4&&(f=!0,a.src=JC,a.preload="auto",a.load());let S=d((_-e)/t),M=e+t,w=d((_-M)/(n*.7));p(0,"--enter",S.toFixed(4)),p(2,"--fcopy",w.toFixed(4));let T=i+s;p(3,"visibility",_>e-20&&_<T?"visible":"hidden");let R=!KC&&f&&_>=e-20&&_<i-15;R!==m?(m=R,R?a.play().catch(()=>{}):a.pause()):R&&a.paused&&a.play().catch(()=>{})});return{dispose(){y(),a.pause(),a.removeAttribute("src"),r.replaceChildren()}}}function tN(){let r=document.getElementById("finale");if(!r)throw new Error("finale: #finale missing");let e=document.createElement("p");e.className="finale__micro finale__item",e.textContent="Four elements. Four faces. One bench.";let t=document.createElement("h2");t.className="finale__head finale__item";for(let[p,f]of["Commission","your own","omote"].entries())p&&t.append(document.createElement("br")),t.append(f);let i=[{key:"water",left:.6,top:39.3},{key:"fire",left:25.3,top:39.3},{key:"earth",left:50,top:52},{key:"air",left:74.7,top:52}].map((p,f)=>{let m=jr.find(x=>x.key===p.key),y=document.createElement("img");return y.className=`finale__mask finale__mask--${f+1} finale__item`,y.src=m.maskUrl,y.alt="",y.loading="lazy",y.draggable=!1,y.style.left=`${p.left}%`,y.style.top=`${p.top}%`,y}),s=document.createElement("p");s.className="finale__label finale__item",s.textContent="menuchi xA9 2026";let a=document.createElement("p");a.className="finale__note finale__item",a.textContent="Commissions open twice a year, spring and autumn. Write with the element you keep returning to u2014 letters are answered in order, by hand.",r.append(e,t,...i,s,a);let o=p=>p<0?0:p>1?1:p,l=[...r.querySelectorAll(".finale__item")],c=[],u=()=>{let p=scrollY;c=l.map(f=>f.getBoundingClientRect().top+p)};u(),addEventListener("resize",u),document.fonts?.ready&&document.fonts.ready.then(u).catch(()=>{});let d=l.map(()=>""),h=oo(({y:p,H:f})=>{for(let m=0;m<l.length;m++){let y=p+f*(.95-m*.012),x=o((y-c[m])/(f*.22)).toFixed(4);x!==d[m]&&(d[m]=x,l[m].style.setProperty("--nk",x))}});return{dispose(){h(),removeEventListener("resize",u),r.replaceChildren()}}}if(!zC()){let r=document.getElementById("unsupported");throw r&&(r.hidden=!1),new Error("WebGPU unavailable")}var X4="menuchi",sN="'Inter Tight', Inter, system-ui, sans-serif",mp=await HC(document.getElementById("stage"),{verticalOffset:.16,distanceScale:1.72,pinned:!0}),nN=WC({text:X4,family:sN});function ET(){let r=mp.bufferSize();nN.resize(r.width,r.height),mp.flames.setTitleTexture(nN.texture)}ET();qC([`400 320px ${sN}`,'500 96px "Noto Serif JP"']).then(()=>ET());var Y4=mp.resize;addEventListener("resize",()=>{Y4(),ET()});var wT=document.getElementById("menu");wT?.addEventListener("click",()=>{let r=wT.getAttribute("aria-expanded")==="true";wT.setAttribute("aria-expanded",String(!r))});var rN=new kT;YC(()=>rN.scroll);oo(r=>rN.raf(r.time*1e3));var j4=document.getElementById("stage"),K4=()=>{mp.step(performance.now())},iN=!1;function aN(r){r!==iN&&(iN=r,mp.renderer.setAnimationLoop(r?K4:null),j4.style.visibility=r?"visible":"hidden")}aN(!0);QC(r=>aN(!r));eN();tN();
</script>
</body>
</html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Particle Field</title>
<style>
/* ===================== lenis (minimal) ===================== */
html.lenis,
html.lenis body { height: auto; }
.lenis.lenis-smooth { scroll-behavior: auto !important; }
.lenis.lenis-smooth [data-lenis-prevent] { overscroll-behavior: contain; }
.lenis.lenis-stopped { overflow: hidden; }
.lenis.lenis-smooth iframe { pointer-events: none; }
/* ===================== page ===================== */
:root {
--bg: #050706;
--ink: #eef2f0;
--muted: #7c8a85;
--accent: #2ee6a0;
--ease-out: cubic-bezier(0.16, 1, 0.3, 1);
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html { background: var(--bg); }
body {
background: var(--bg);
color: var(--ink);
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
font-synthesis-weight: none;
-webkit-font-smoothing: antialiased;
overflow-x: hidden;
}
/* The canvas sits behind everything, pinned to the viewport. */
#field {
position: fixed;
inset: 0;
z-index: 0;
pointer-events: none;
}
#field canvas { display: block; }
#field .pf-fallback {
position: absolute;
top: 50%;
left: 50%;
width: min(60vw, 60vh);
transform: translate(-50%, -50%);
}
#smooth-wrapper { position: relative; z-index: 1; }
.panel {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
gap: 1.1rem;
max-width: 46rem;
padding: 8vh clamp(1.5rem, 6vw, 7rem);
pointer-events: none;
}
.panel.last { min-height: 130vh; }
/* Alternate sides so the field is never permanently hidden behind type. */
.panel:nth-child(even) { margin-left: auto; text-align: right; }
.eyebrow {
font-size: 0.72rem;
letter-spacing: 0.16em;
text-transform: uppercase;
color: var(--muted);
}
h1 {
font-size: clamp(2.6rem, 8vw, 5.5rem);
font-weight: 300;
letter-spacing: -0.035em;
line-height: 0.95;
}
h2 {
font-size: clamp(1.7rem, 4vw, 2.9rem);
font-weight: 300;
letter-spacing: -0.03em;
}
p {
font-size: clamp(0.95rem, 1.3vw, 1.08rem);
line-height: 1.65;
color: var(--muted);
max-width: 34rem;
text-wrap: pretty;
}
.panel:nth-child(even) p { margin-left: auto; }
.lede { color: #b6c4bf; }
code {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.9em;
color: var(--accent);
}
.hint {
font-size: 0.72rem;
letter-spacing: 0.18em;
text-transform: uppercase;
color: var(--muted);
margin-top: 2rem;
}
#stats {
position: fixed;
left: 1rem;
bottom: 1rem;
z-index: 3;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.68rem;
line-height: 1.7;
color: var(--muted);
white-space: pre;
pointer-events: none;
opacity: 0.75;
}
.lil-gui { --width: 300px; z-index: 4 !important; }
@media (prefers-reduced-motion: reduce) {
.hint { display: none; }
}
</style>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.185.1/build/three.module.min.js",
"lil-gui": "https://unpkg.com/lil-gui@0.19.2/dist/lil-gui.esm.js",
"lenis": "https://unpkg.com/lenis@1.1.18/dist/lenis.mjs"
}
}
</script>
</head>
<body>
<div id="field" aria-hidden="true"></div>
<div id="smooth-wrapper">
<div id="smooth-content">
<section class="panel hero" id="hero">
<p class="eyebrow">three.js · points · no post-processing</p>
<h1 id="title">Particle Field</h1>
<p class="lede" id="lede">
One <code>THREE.Points</code> cloud, a procedural sprite, and a CPU solver.
No bloom pass, no depth of field, no texture, no model.
</p>
<p class="hint">Scroll</p>
</section>
<section class="panel" id="arrival">
<h2>It arrives</h2>
<p>
The field dollies in from 106 world units to 16, interpolated in log space so the
approach reads as even rather than rushing at the end. Every particle starts as
identical fine dust and grows into its own size class on the way in.
</p>
</section>
<section class="panel" id="cursor">
<h2>It answers the cursor</h2>
<p>
Move across it. Particles inside the radius are not pushed away with a falloff —
they are relocated to sit exactly on the rim of a disc, measured perpendicular to
the view axis so the hole stays circular however far the field has rotated.
It snaps in four times faster than it relaxes out.
</p>
</section>
<section class="panel" id="shapes">
<h2>Any shape</h2>
<p>
The silhouette is a swappable sampler. The superellipse is one implementation;
an SVG path is another. Try the shape control, top right.
</p>
</section>
<section class="panel last" id="dissolve">
<h2>Then it goes</h2>
<p>
Each particle travels along a fixed random direction while growing and softening,
so the cloud evaporates instead of merely flying apart.
</p>
</section>
</div>
</div>
<div id="stats" aria-live="off"></div>
<script type="module">
import * as THREE from 'three'
import Lenis from 'lenis'
import GUI from 'lil-gui'
/* =========================================================================
* frameBus — a single requestAnimationFrame loop shared by the whole page.
* One rAF, one Set of subscribers, one scroll read per frame, so nothing
* can drift out of phase and there is not a single `scroll` listener.
* ========================================================================= */
const subscribers = new Set()
let rafId = 0
let running = false
let startedAt = 0
let previous = 0
let readScroll = () => window.scrollY
/** Point the bus at a smooth-scroll library instead of raw `window.scrollY`. */
function setScrollSource(source) {
readScroll = source
}
const frameState = { y: 0, H: 0, time: 0, dt: 0 }
function tick() {
const now = performance.now()
frameState.y = readScroll()
frameState.H = window.innerHeight
frameState.time = (now - startedAt) / 1000
frameState.dt = Math.min((now - previous) / 1000, 0.1)
previous = now
// Iterating the Set directly is safe: unsubscribing during a tick only
// affects entries not yet visited, which is the behaviour we want.
for (const fn of subscribers) fn(frameState)
rafId = requestAnimationFrame(tick)
}
function subscribe(fn) {
subscribers.add(fn)
if (!running) {
running = true
startedAt = previous = performance.now()
rafId = requestAnimationFrame(tick)
}
return () => {
subscribers.delete(fn)
if (subscribers.size === 0 && running) {
running = false
cancelAnimationFrame(rafId)
}
}
}
const prefersReducedMotion =
typeof matchMedia !== 'undefined' &&
matchMedia('(prefers-reduced-motion: reduce)').matches
const hasFinePointer =
typeof matchMedia !== 'undefined' &&
matchMedia('(hover: hover) and (pointer: fine)').matches
/* =========================================================================
* shapes/index — sampler contract
*
* A ShapeSampler turns *some* 2D silhouette into point clouds: `rim(n)`
* walks the outline spaced by arc length, `fill(n)` scatters the interior
* uniformly per unit area, both as 2 floats per point, y-up, origin-centred.
* A VolumeSampler owns its own depth instead: `edge(n)` (feature curves) and
* `surface(n)`, 3 floats per point.
* ========================================================================= */
const isVolume = (s) => s.is3D === true
/* =========================================================================
* shapes/parts3d — reusable 3D sampling primitives.
* Coordinate convention: y up, +z toward the viewer, origin at shape centre.
* ========================================================================= */
const TAU = Math.PI * 2
/** Cubic Bézier evaluated at t. */
function bezier3(p0, p1, p2, p3, t) {
const u = 1 - t
const a = u * u * u
const b = 3 * u * u * t
const c = 3 * u * t * t
const d = t * t * t
return [
a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0],
a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1],
a * p0[2] + b * p1[2] + c * p2[2] + d * p3[2],
]
}
/**
* Wrap any parametric curve in an arc-length parameterisation: a cumulative
* length table, binary-searched and lerped. Sampling uniformly in `s` then
* spaces points evenly no matter how unevenly `t` covers the curve.
*/
function arcLengthCurve(fn, steps = 256) {
const pts = []
const cum = new Float64Array(steps + 1)
let acc = 0
for (let i = 0; i <= steps; i++) {
const p = fn(i / steps)
if (i > 0) {
const q = pts[i - 1]
acc += Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2])
}
pts.push(p)
cum[i] = acc
}
const total = acc || 1e-9
function tAt(s) {
const target = Math.min(Math.max(s, 0), 1) * total
let lo = 0
let hi = steps
while (lo < hi) {
const mid = (lo + hi) >> 1
if (cum[mid] < target) lo = mid + 1
else hi = mid
}
const i = Math.max(1, lo)
const prev = cum[i - 1]
const next = cum[i]
const frac = next > prev ? (target - prev) / (next - prev) : 0
return (i - 1 + frac) / steps
}
return {
length: total,
at(s) {
return fn(tAt(s))
},
tangent(s) {
const t = tAt(s)
const e = 1 / steps
const a = fn(Math.max(0, t - e))
const b = fn(Math.min(1, t + e))
const d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]
const len = Math.hypot(d[0], d[1], d[2]) || 1
return [d[0] / len, d[1] / len, d[2] / len]
},
}
}
/** An orthonormal frame perpendicular to `t` (parallel-transport-lite). */
function frameFor(t) {
// Pick the world axis least aligned with the tangent to avoid degeneracy.
const ref = Math.abs(t[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0]
let ux = t[1] * ref[2] - t[2] * ref[1]
let uy = t[2] * ref[0] - t[0] * ref[2]
let uz = t[0] * ref[1] - t[1] * ref[0]
const ul = Math.hypot(ux, uy, uz) || 1
ux /= ul
uy /= ul
uz /= ul
return {
u: [ux, uy, uz],
v: [t[1] * uz - t[2] * uy, t[2] * ux - t[0] * uz, t[0] * uy - t[1] * ux],
}
}
/**
* Fill an unmet quota by duplicating already-written points, rather than
* leaving zeros that would stack a visible clump of particles at the origin.
*/
function padShortfall(out, offset, written, count) {
if (written >= count) return
const have = Math.max(written, 1)
for (let i = written; i < count; i++) {
const src = (offset + (i % have)) * 3
const dst = (offset + i) * 3
out[dst] = out[src]
out[dst + 1] = out[src + 1]
out[dst + 2] = out[src + 2]
}
}
/**
* Area-uniform sampling on an ellipsoid surface.
*
* Uniform-on-sphere scaled by (rx, ry, rz) is NOT area-uniform — scaling
* compresses area unevenly. Accepting with probability ∝ the local area
* element J restores uniformity:
* J = |(ry·rz·nx, rx·rz·ny, rx·ry·nz)|, n = unit-sphere normal
*/
function ellipsoid(opts) {
const [cx, cy, cz] = opts.center
const [rx, ry, rz] = opts.radii
const jMax = Math.max(ry * rz, rx * rz, rx * ry)
// Thomsen's approximation for ellipsoid area (±1%), scaled by the accepted
// patch fraction estimated with a quick Monte Carlo pass.
const p = 1.6075
const fullArea =
4 *
Math.PI *
Math.pow(
(Math.pow(rx * ry, p) + Math.pow(rx * rz, p) + Math.pow(ry * rz, p)) / 3,
1 / p,
)
function sphereNormal() {
const theta = Math.random() * TAU
const cosPhi = 2 * Math.random() - 1
const sinPhi = Math.sqrt(1 - cosPhi * cosPhi)
return [sinPhi * Math.cos(theta), cosPhi, sinPhi * Math.sin(theta)]
}
let patchFraction = 1
if (opts.patch) {
let kept = 0
const N = 2048
for (let i = 0; i < N; i++) {
if (opts.patch(sphereNormal())) kept++
}
patchFraction = kept / N
}
return {
area: fullArea * patchFraction,
sample(out, offset, count) {
let written = 0
let guard = count * 200
while (written < count && guard-- > 0) {
const n = sphereNormal()
if (opts.patch && !opts.patch(n)) continue
const j = Math.hypot(ry * rz * n[0], rx * rz * n[1], rx * ry * n[2])
if (Math.random() > j / jMax) continue
let p2 = [cx + rx * n[0], cy + ry * n[1], cz + rz * n[2]]
if (opts.warp) p2 = opts.warp(p2, n)
const o = (offset + written) * 3
out[o] = p2[0]
out[o + 1] = p2[1]
out[o + 2] = p2[2]
written++
}
padShortfall(out, offset, written, count)
},
}
}
/**
* A tube swept along a curve — horns. Area-uniform along the length because
* the curve is arc-length parameterised and the radius is importance-sampled:
* a section's area is proportional to its circumference.
*/
function sweptTube(opts) {
const { curve, radius } = opts
// Average radius for area estimate + the importance envelope.
const S = 64
let rSum = 0
let rMax = 1e-9
for (let i = 0; i <= S; i++) {
const r = radius(i / S)
rSum += r
rMax = Math.max(rMax, r)
}
const rMean = rSum / (S + 1)
return {
area: TAU * rMean * curve.length,
sample(out, offset, count) {
let written = 0
let guard = count * 100
while (written < count && guard-- > 0) {
const s = Math.random()
const r = radius(s)
// Importance-sample s by circumference so thick sections get more points.
if (Math.random() > r / rMax) continue
const c = curve.at(s)
const { u, v } = frameFor(curve.tangent(s))
const a = Math.random() * TAU
const ca = Math.cos(a) * r
const sa = Math.sin(a) * r
const o = (offset + written) * 3
out[o] = c[0] + u[0] * ca + v[0] * sa
out[o + 1] = c[1] + u[1] * ca + v[1] * sa
out[o + 2] = c[2] + u[2] * ca + v[2] * sa
written++
}
padShortfall(out, offset, written, count)
},
}
}
/** A flat band following a curve — lips, brow underside. */
function ribbon(opts) {
const { curve, halfWidth, across } = opts
const thick = opts.thickness ?? 0.12
const S = 64
let wSum = 0
let wMax = 1e-9
for (let i = 0; i <= S; i++) {
const w = halfWidth(i / S)
wSum += w
wMax = Math.max(wMax, w)
}
return {
area: 2 * (wSum / (S + 1)) * curve.length,
sample(out, offset, count) {
let written = 0
let guard = count * 100
while (written < count && guard-- > 0) {
const s = Math.random()
const w = halfWidth(s)
if (Math.random() > w / wMax) continue
const c = curve.at(s)
const d = across(s)
const dl = Math.hypot(d[0], d[1], d[2]) || 1
const t = (Math.random() * 2 - 1) * w
const n = (Math.random() * 2 - 1) * thick * 0.5
// Normal direction: perpendicular to both tangent and across.
const tg = curve.tangent(s)
const nx = tg[1] * d[2] - tg[2] * d[1]
const ny = tg[2] * d[0] - tg[0] * d[2]
const nz = tg[0] * d[1] - tg[1] * d[0]
const nl = Math.hypot(nx, ny, nz) || 1
const o = (offset + written) * 3
out[o] = c[0] + (d[0] / dl) * t + (nx / nl) * n
out[o + 1] = c[1] + (d[1] / dl) * t + (ny / nl) * n
out[o + 2] = c[2] + (d[2] / dl) * t + (nz / nl) * n
written++
}
padShortfall(out, offset, written, count)
},
}
}
/** Lateral surface of a cone — fangs. Points sampled ∝ local circumference. */
function cone(opts) {
const { tip, base, baseRadius } = opts
const axis = [tip[0] - base[0], tip[1] - base[1], tip[2] - base[2]]
const height = Math.hypot(axis[0], axis[1], axis[2]) || 1e-9
const dir = [axis[0] / height, axis[1] / height, axis[2] / height]
const { u, v } = frameFor(dir)
const slant = Math.hypot(height, baseRadius)
return {
area: Math.PI * baseRadius * slant,
sample(out, offset, count) {
for (let i = 0; i < count; i++) {
// Radius ∝ sqrt(u) gives area-uniform sampling on the unrolled disc.
const t = Math.sqrt(Math.random()) // 0 at tip, 1 at base
const r = baseRadius * t
const a = Math.random() * TAU
const ca = Math.cos(a) * r
const sa = Math.sin(a) * r
const o = (offset + i) * 3
out[o] = tip[0] - dir[0] * height * t + u[0] * ca + v[0] * sa
out[o + 1] = tip[1] - dir[1] * height * t + u[1] * ca + v[1] * sa
out[o + 2] = tip[2] - dir[2] * height * t + u[2] * ca + v[2] * sa
}
},
}
}
/** A tapered box volume — brow ridges. Volumetric fill, not just the shell. */
function wedge(opts) {
const { from, to, halfHeight, halfDepth } = opts
const axis = [to[0] - from[0], to[1] - from[1], to[2] - from[2]]
const len = Math.hypot(axis[0], axis[1], axis[2]) || 1e-9
const dir = [axis[0] / len, axis[1] / len, axis[2] / len]
const { u, v } = frameFor(dir)
return {
// Rough lateral area of the tapering box.
area: 2 * len * (halfHeight + halfDepth) * 0.6,
sample(out, offset, count) {
for (let i = 0; i < count; i++) {
const t = Math.random()
const taper = 1 - 0.8 * t
const h = (Math.random() * 2 - 1) * halfHeight * taper
const d = (Math.random() * 2 - 1) * halfDepth * taper
const o = (offset + i) * 3
out[o] = from[0] + dir[0] * len * t + u[0] * h + v[0] * d
out[o + 1] = from[1] + dir[1] * len * t + u[1] * h + v[1] * d
out[o + 2] = from[2] + dir[2] * len * t + u[2] * h + v[2] * d
}
},
}
}
/**
* Distribute a point budget across parts proportionally to area, sample each,
* and reject points falling inside that part's cut volumes. Cuts are per-part
* rather than global, because some parts deliberately live inside a cut — the
* fangs sit inside the mouth cavity that carves everything else.
*/
function samplePartsWithCuts(entries, count) {
const parts = entries.map((e) => e.part)
const totalArea = parts.reduce((s, p) => s + p.area, 0) || 1
const out = new Float32Array(count * 3)
const tmp = [0, 0, 0]
let written = 0
for (let pi = 0; pi < parts.length; pi++) {
const part = parts[pi]
const cuts = entries[pi].cuts ?? []
const quota =
pi === parts.length - 1
? count - written
: Math.round((part.area / totalArea) * count)
if (quota <= 0) continue
// Sample into a scratch block, then filter through the cuts, resampling
// the shortfall in progressively smaller blocks.
let need = quota
let guard = 40
while (need > 0 && guard-- > 0) {
const block = new Float32Array(need * 3)
part.sample(block, 0, need)
for (let i = 0; i < need; i++) {
tmp[0] = block[i * 3]
tmp[1] = block[i * 3 + 1]
tmp[2] = block[i * 3 + 2]
let cut = false
for (const c of cuts) {
if (c(tmp)) {
cut = true
break
}
}
if (!cut) {
const o = written * 3
out[o] = tmp[0]
out[o + 1] = tmp[1]
out[o + 2] = tmp[2]
written++
if (--need === 0) break
}
}
// If a part is entirely inside a cut, the guard expires and we move on.
}
// Any expired-guard shortfall is topped up from what we already have.
if (need > 0) {
padShortfall(out, 0, written, written + need)
written += need
}
}
return out
}
/**
* Sample a set of feature curves evenly: the point budget is split across
* curves ∝ length, and each curve is sampled uniformly in arc length with
* slot jitter (never a dotted line), with an optional radial scatter.
*/
function sampleCurves(curves, count, cuts = []) {
const total = curves.reduce((s, c) => s + c.curve.length, 0) || 1
const out = new Float32Array(count * 3)
let written = 0
for (let ci = 0; ci < curves.length; ci++) {
const { curve, scatter = 0 } = curves[ci]
const quota =
ci === curves.length - 1
? count - written
: Math.round((curve.length / total) * count)
let placed = 0
let attempt = 0
const maxAttempts = quota * 30
while (placed < quota && attempt++ < maxAttempts) {
const s = (placed + Math.random() * 0.7) / quota
const p = curve.at(s)
const px = p[0] + (Math.random() * 2 - 1) * scatter
const py = p[1] + (Math.random() * 2 - 1) * scatter
const pz = p[2] + (Math.random() * 2 - 1) * scatter
let cut = false
for (const c of cuts) {
if (c([px, py, pz])) {
cut = true
break
}
}
if (cut) continue
const o = written * 3
out[o] = px
out[o + 1] = py
out[o + 2] = pz
written++
placed++
}
if (placed < quota) {
padShortfall(out, 0, written, written + (quota - placed))
written += quota - placed
}
}
return out
}
/* =========================================================================
* shapes/superellipse
*
* The 4-pointed star is one function — no model, no texture, no asset.
* Polar form of the Lamé curve:
* r(θ) = [ (|cosθ|/a)^e + (|sinθ|/b)^e ]^(-1/e)
* The effective exponent is 2/n, so n > 2 pushes it below 1 and makes the
* curve *concave* — which is where the sparkle comes from.
* ========================================================================= */
function radiusAt(theta, a, b, e, invE) {
const c = Math.pow(Math.abs(Math.cos(theta)) / a, e)
const s = Math.pow(Math.abs(Math.sin(theta)) / b, e)
return Math.pow(c + s, invE)
}
function superellipse(options = {}) {
const n = options.n ?? 3.7
const aspect = options.aspect ?? 1.05
const a = options.radius ?? 5.3
const b = a * aspect
const lutSize = options.lut ?? 1440
const e = 2 / n
const invE = -n / 2
const r = (theta) => radiusAt(theta, a, b, e, invE)
// --- Cumulative arc-length table, walked once at build time -----------
// lut[i] is the distance travelled along the outline from θ=0 to θ=i/lutSize·2π.
const lut = new Float32Array(lutSize + 1)
{
let travelled = 0
let px = r(0)
let py = 0
for (let i = 0; i <= lutSize; i++) {
const theta = (i / lutSize) * TAU
const rad = r(theta)
const x = Math.cos(theta) * rad
const y = Math.sin(theta) * rad
if (i > 0) travelled += Math.hypot(x - px, y - py)
lut[i] = travelled
px = x
py = y
}
}
const perimeter = lut[lutSize]
/** Invert arc length → θ by binary-searching the table, then lerping. */
function thetaAtLength(target) {
let lo = 0
let hi = lutSize
while (lo < hi) {
const mid = (lo + hi) >> 1
if (lut[mid] < target) lo = mid + 1
else hi = mid
}
const i = Math.max(1, lo)
const prev = lut[i - 1]
const next = lut[i]
const frac = next > prev ? (target - prev) / (next - prev) : 0
return ((i - 1 + frac) / lutSize) * TAU
}
const rMax = Math.max(a, b)
return {
bounds: () => ({ halfW: a, halfH: b }),
rim(count) {
const out = new Float32Array(count * 2)
for (let i = 0; i < count; i++) {
// Jitter within the slot so the outline never looks like a dotted line.
const s = ((i + Math.random() * 0.7) / count) * perimeter
const theta = thetaAtLength(s)
const rad = r(theta) * (0.9 + Math.random() * 0.1)
out[i * 2] = Math.cos(theta) * rad
out[i * 2 + 1] = Math.sin(theta) * rad
}
return out
},
fill(count) {
const out = new Float32Array(count * 2)
let written = 0
let guard = count * 64 // pathological-shape backstop
while (written < count && guard-- > 0) {
const theta = Math.random() * TAU
const rad = r(theta)
// Rejection-sample the *angle* weighted by radius², so wide sectors of
// the star receive proportionally more points than the pinched ones.
if (Math.random() > (rad / rMax) ** 2) continue
// sqrt() of a uniform gives a radially uniform-in-area distribution;
// without it everything piles into the centre.
const t = Math.sqrt(Math.random()) * 0.93
out[written * 2] = Math.cos(theta) * rad * t
out[written * 2 + 1] = Math.sin(theta) * rad * t
written++
}
// Guard tripped (degenerate shape): pad rather than hand back zeros,
// which would stack a visible clump of particles at the origin.
for (let i = written; i < count; i++) {
const src = (i % Math.max(written, 1)) * 2
out[i * 2] = out[src]
out[i * 2 + 1] = out[src + 1]
}
return out
},
}
}
/* =========================================================================
* shapes/svgPath
*
* Samples any SVG path — a logo, an icon, a glyph outline — two ways, each
* the robust mechanism for its job:
* - Outline uses getPointAtLength(): the browser's own exact arc-length
* parameterisation, replacing the hand-built LUT above.
* - Interior rasterises the filled path once and samples opaque pixels,
* which handles holes and multiple subpaths for free.
* ========================================================================= */
function svgPath(d, options = {}) {
const radius = options.radius ?? 5.3
const resolution = options.resolution ?? 512
// --- Measure via a detached-but-rendered SVG -------------------------
// getBBox() needs a rendered element in some engines, so mount it hidden
// rather than measuring a fully detached node.
const NS = 'http://www.w3.org/2000/svg'
const svg = document.createElementNS(NS, 'svg')
svg.setAttribute('aria-hidden', 'true')
svg.style.cssText =
'position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;visibility:hidden'
const path = document.createElementNS(NS, 'path')
path.setAttribute('d', d)
svg.appendChild(path)
document.body.appendChild(svg)
let box
let totalLength = 0
try {
box = path.getBBox()
totalLength = path.getTotalLength()
} catch {
box = { x: 0, y: 0, width: 1, height: 1 }
}
if (!(box.width > 0) || !(box.height > 0)) {
document.body.removeChild(svg)
throw new Error('svgPath: path has an empty bounding box — check the `d` string')
}
const cx = box.x + box.width / 2
const cy = box.y + box.height / 2
// Normalise so the *longer* axis spans 2 × radius; proportions are kept.
const scale = (radius * 2) / Math.max(box.width, box.height)
const halfW = (box.width / 2) * scale
const halfH = (box.height / 2) * scale
// SVG's y axis points down, WebGL's points up.
const toWorldX = (px) => (px - cx) * scale
const toWorldY = (py) => -(py - cy) * scale
// --- Rasterise once for interior sampling ----------------------------
const rw = Math.max(2, Math.round((box.width / Math.max(box.width, box.height)) * resolution))
const rh = Math.max(2, Math.round((box.height / Math.max(box.width, box.height)) * resolution))
const canvas = document.createElement('canvas')
canvas.width = rw
canvas.height = rh
const ctx = canvas.getContext('2d', { willReadFrequently: true })
ctx.setTransform(
rw / box.width, 0, 0, rh / box.height,
(-box.x * rw) / box.width, (-box.y * rh) / box.height,
)
ctx.fillStyle = '#fff'
ctx.fill(new Path2D(d))
const pixels = ctx.getImageData(0, 0, rw, rh).data
const inside = []
for (let i = 0; i < rw * rh; i++) {
if (pixels[i * 4 + 3] > 127) inside.push(i)
}
document.body.removeChild(svg)
if (inside.length === 0) {
throw new Error('svgPath: path rasterised to nothing — is it stroke-only, with no fill area?')
}
return {
bounds: () => ({ halfW, halfH }),
rim(count) {
const out = new Float32Array(count * 2)
if (totalLength <= 0) return out
for (let i = 0; i < count; i++) {
const at = ((i + Math.random() * 0.7) / count) * totalLength
const p = path.getPointAtLength(at % totalLength)
out[i * 2] = toWorldX(p.x)
out[i * 2 + 1] = toWorldY(p.y)
}
return out
},
fill(count) {
const out = new Float32Array(count * 2)
for (let i = 0; i < count; i++) {
const idx = inside[(Math.random() * inside.length) | 0]
// Jitter inside the pixel so the cloud does not betray the raster grid.
const px = box.x + ((idx % rw) + Math.random()) * (box.width / rw)
const py = box.y + (((idx / rw) | 0) + Math.random()) * (box.height / rh)
out[i * 2] = toWorldX(px)
out[i * 2 + 1] = toWorldY(py)
}
return out
},
}
}
/* =========================================================================
* shapes/hannya
*
* A hannya mask composed from ~14 parametric primitives, proportioned
* against a 6-view reference sheet. Deliberately primitive: the identity
* lives in the feature curves — horns, brow crests, eye rims, nose ridge,
* the grimace — and in the cuts, not in surface detail.
*
* Source-space numbers below are measured off the front view (face
* half-height = 5.0) and the profile (depth). A final shift recentres the
* mask so it spins about its visual centre, then `scale` sizes it.
* ========================================================================= */
function hannya(options = {}) {
const SCALE = options.scale ?? 0.72
const hornLen = options.hornLength ?? 1
const open = options.mouthOpen ?? 1
// Centre of the unshifted build, computed from the extents measured below.
const YSHIFT = -1.68
const ZSHIFT = -1.19
// -------------------------------------------------------------------
// Shared curves
// -------------------------------------------------------------------
/** The grimace: wide, corners pulled hard up, wrapped back around the face. */
const mouthY = (x) => -2.35 + 0.75 * (x / 2.55) ** 2
const mouthZ = (x) => 2.25 - 0.55 * (x / 2.55) ** 2
const lipCurve = (offset) =>
arcLengthCurve((t) => {
const x = -2.55 + 5.1 * t
return [x, mouthY(x) + offset, mouthZ(x)]
})
/** Horn spine; `s` = ±1 mirrors it. Up, outward, raked back, tip recovering. */
const hornSpine = (s) => {
const base = [s * 1.85, 4.15, 0.15]
const stretch = (p) => [p[0], base[1] + (p[1] - base[1]) * hornLen, p[2]]
const c1 = stretch([s * 3.15, 5.7, -0.5])
const c2 = stretch([s * 3.5, 7.3, -1.0])
const tip = stretch([s * 2.7, 8.55, -0.55])
return arcLengthCurve((t) => bezier3(base, c1, c2, tip, t))
}
/** Front z of the face shell at (x, y) — used to seat curves ON the shell. */
const shellZ = (x, y) => {
const q = 1 - (x / 3.6) ** 2 - ((y - 0.2) / 5.0) ** 2
return -0.4 + 2.4 * Math.sqrt(Math.max(q, 0))
}
/** Chin taper: the face narrows toward the jaw. Applied to shell + border. */
const taperX = (y) => (y < 0.2 ? 1 - 0.42 * Math.pow((0.2 - y) / 5.2, 1.7) : 1)
// -------------------------------------------------------------------
// Cut volumes
// -------------------------------------------------------------------
/** Tilted eye sockets: outer corners raised — the angry almond. */
const eyeSocket = (s) => {
const cx = s * 1.75
const cy = 1.3
const cz = 1.95
const phi = (s * (16 * Math.PI)) / 180
const cos = Math.cos(-phi)
const sin = Math.sin(-phi)
return (p) => {
const dx0 = p[0] - cx
const dy0 = p[1] - cy
const dx = (dx0 * cos - dy0 * sin) / 1.08
const dy = (dx0 * sin + dy0 * cos) / 0.62
const dz = (p[2] - cz) / 1.3
return dx * dx + dy * dy + dz * dz < 1
}
}
const nostril = (s) => {
const c = [s * 0.45, -0.62, 2.7]
return (p) => {
const dx = p[0] - c[0]
const dy = p[1] - c[1]
const dz = p[2] - c[2]
return dx * dx + dy * dy + dz * dz < 0.3 * 0.3
}
}
/** The dark opening between the lips. */
const mouthCavity = (p) => {
if (Math.abs(p[0]) > 2.45 || p[2] < 0.6) return false
return Math.abs(p[1] - mouthY(p[0])) < 0.52 * open
}
const faceCuts = [eyeSocket(1), eyeSocket(-1), nostril(1), nostril(-1), mouthCavity]
// -------------------------------------------------------------------
// Parts
// -------------------------------------------------------------------
function hornTube(spine) {
return sweptTube({ curve: spine, radius: (s) => 0.06 + 0.55 * Math.pow(1 - s, 0.85) })
}
function browWedge(s) {
return wedge({
from: [s * 0.5, 2.1, 2.3],
to: [s * 2.9, 3.15, 0.95],
halfHeight: 0.62,
halfDepth: 0.5,
})
}
function cheek(s) {
const out = [s * 0.8, -0.1, 0.6]
const len = Math.hypot(out[0], out[1], out[2])
return ellipsoid({
center: [s * 2.15, -0.55, 0.9],
radii: [1.0, 1.15, 0.85],
patch: (n) => (n[0] * out[0] + n[1] * out[1] + n[2] * out[2]) / len > 0.15,
})
}
const lowerLipOffset = -0.62 - 0.5 * (open - 1)
const entries = [
{
// The shell: an egg patch, open at the back, narrowed toward the chin.
part: ellipsoid({
center: [0, 0.2, -0.4],
radii: [3.6, 5.0, 2.4],
patch: (n) => n[2] > -0.12,
warp: (p) => [p[0] * taperX(p[1]), p[1], p[2]],
}),
cuts: faceCuts,
},
{ part: hornTube(hornSpine(1)) },
{ part: hornTube(hornSpine(-1)) },
{ part: browWedge(1), cuts: [eyeSocket(1)] },
{ part: browWedge(-1), cuts: [eyeSocket(-1)] },
{ part: cheek(1), cuts: [mouthCavity, eyeSocket(1)] },
{ part: cheek(-1), cuts: [mouthCavity, eyeSocket(-1)] },
{
// Chin knob under the grimace.
part: ellipsoid({
center: [0, -4.35, 0.75],
radii: [1.05, 0.85, 0.75],
patch: (n) => n[2] > 0.1,
}),
cuts: [mouthCavity],
},
{
// Nose: a pyramid, wide at the nostrils, narrowing to the glabella.
part: wedge({
from: [0, -0.7, 2.85],
to: [0, 1.75, 2.1],
halfHeight: 0.55,
halfDepth: 0.85,
}),
cuts: [nostril(1), nostril(-1)],
},
{
part: ribbon({
curve: lipCurve(0.46),
halfWidth: (s) => 0.3 - 0.1 * Math.abs(2 * s - 1),
across: () => [0, 1, 0.25],
thickness: 0.45,
}),
cuts: [mouthCavity],
},
{
part: ribbon({
curve: lipCurve(lowerLipOffset),
halfWidth: (s) => 0.27 - 0.09 * Math.abs(2 * s - 1),
across: () => [0, 1, 0.25],
thickness: 0.45,
}),
cuts: [mouthCavity],
},
// Fangs live INSIDE the mouth cavity — no cuts on purpose.
{ part: cone({ tip: [1.64, -3.35, 2.26], base: [1.7, -2.05, 2.2], baseRadius: 0.3 }) },
{ part: cone({ tip: [-1.64, -3.35, 2.26], base: [-1.7, -2.05, 2.2], baseRadius: 0.3 }) },
{ part: cone({ tip: [0.95, -2.25, 2.24], base: [0.9, -3.05, 2.2], baseRadius: 0.22 }) },
{ part: cone({ tip: [-0.95, -2.25, 2.24], base: [-0.9, -3.05, 2.2], baseRadius: 0.22 }) },
]
// -------------------------------------------------------------------
// Feature curves — the identity
// -------------------------------------------------------------------
const deg = Math.PI / 180
/** Eye rim: the socket ellipse at 1.06×, seated on the shell surface. */
const eyeRim = (s) => {
const phi = s * 16 * deg
const cos = Math.cos(phi)
const sin = Math.sin(phi)
return arcLengthCurve((t) => {
const a = t * Math.PI * 2
const ex = 1.14 * Math.cos(a)
const ey = 0.68 * Math.sin(a)
const x = s * 1.75 + ex * cos - ey * sin
const y = 1.3 + ex * sin + ey * cos
return [x, y, shellZ(x, y) + 0.06]
})
}
/** Nose ridge with the under-hook at the tip. */
const noseRidge = arcLengthCurve((t) =>
bezier3([0, 1.75, 2.2], [0, 0.4, 2.75], [0, -0.5, 3.2], [0, -0.95, 2.95], t),
)
/** Ring around each nostril hole. */
const nostrilRing = (s) =>
arcLengthCurve((t) => {
const a = t * Math.PI * 2
return [
s * (0.45 + 0.4 * Math.cos(a)),
-0.62 + 0.3 * Math.sin(a),
2.62 + 0.18 * Math.sin(a),
]
})
/** Mask border: temple → jaw → chin → jaw → temple, with the chin taper. */
const faceBorder = arcLengthCurve((t) => {
const a = (30 - 240 * t) * deg
const y = 0.2 + 5.0 * Math.sin(a)
const x = 3.6 * Math.cos(a) * taperX(y)
return [x, y, -0.25]
})
/** Skull dome between the horns. */
const domeArc = arcLengthCurve((t) => {
const a = (55 + 70 * t) * deg
const y = 0.2 + 5.0 * Math.sin(a)
const x = 3.6 * Math.cos(a)
return [x, y, -0.25]
})
const browCrest = (s) =>
arcLengthCurve((t) => [s * (0.45 + 2.5 * t), 2.5 + 0.95 * t, 2.35 - 1.45 * t])
/** Straight helper line. */
const line = (a, b) =>
arcLengthCurve((t) => [
a[0] + (b[0] - a[0]) * t,
a[1] + (b[1] - a[1]) * t,
a[2] + (b[2] - a[2]) * t,
])
/** Closed triangle outline — used to draw fangs legibly. */
const tri = (a, b, c) =>
arcLengthCurve((t) => {
const u = t * 3
const seg = Math.min(2, Math.floor(u))
const f = u - seg
const [p0, p1] = seg === 0 ? [a, b] : seg === 1 ? [b, c] : [c, a]
return [
p0[0] + (p1[0] - p0[0]) * f,
p0[1] + (p1[1] - p0[1]) * f,
p0[2] + (p1[2] - p0[2]) * f,
]
})
const fangTri = (s, upper) =>
upper
? tri([s * 1.42, -2.1, 2.24], [s * 1.98, -2.1, 2.24], [s * 1.64, -3.35, 2.26])
: tri([s * 0.68, -3.0, 2.22], [s * 1.12, -3.0, 2.22], [s * 0.95, -2.25, 2.24])
const edgeCurves = [
// The one mouth line: the upper lip edge, just clear of the cavity cut.
{ curve: lipCurve(0.58), scatter: 0.04 },
{ curve: fangTri(1, true), scatter: 0.03 },
{ curve: fangTri(-1, true), scatter: 0.03 },
{ curve: fangTri(1, false), scatter: 0.03 },
{ curve: fangTri(-1, false), scatter: 0.03 },
// Nose side walls — turn the faint ridge into a readable wedge.
{ curve: line([0.3, 1.55, 2.3], [0.52, -0.35, 2.9]), scatter: 0.04 },
{ curve: line([-0.3, 1.55, 2.3], [-0.52, -0.35, 2.9]), scatter: 0.04 },
{ curve: hornSpine(1), scatter: 0.1 },
{ curve: hornSpine(-1), scatter: 0.1 },
{ curve: browCrest(1), scatter: 0.06 },
{ curve: browCrest(-1), scatter: 0.06 },
{ curve: eyeRim(1), scatter: 0.05 },
{ curve: eyeRim(-1), scatter: 0.05 },
{ curve: noseRidge, scatter: 0.05 },
{ curve: nostrilRing(1), scatter: 0.04 },
{ curve: nostrilRing(-1), scatter: 0.04 },
{ curve: faceBorder, scatter: 0.08 },
{ curve: domeArc, scatter: 0.08 },
]
// Edge points trace cut boundaries at a safe offset, but scatter can still
// push one inside — so edges are cut-checked too.
const edgeCuts = faceCuts
// -------------------------------------------------------------------
// Assembly
// -------------------------------------------------------------------
const place = (arr) => {
for (let i = 0; i < arr.length; i += 3) {
arr[i] = arr[i] * SCALE
arr[i + 1] = (arr[i + 1] + YSHIFT) * SCALE
arr[i + 2] = (arr[i + 2] + ZSHIFT) * SCALE
}
return arr
}
// Extents measured from the source-space numbers above (horn tips, chin,
// shell sides, nose tip, horn rake).
const halfW = 3.7 * SCALE
const halfH = 6.95 * SCALE
const halfD = 2.25 * SCALE
return {
is3D: true,
bounds: () => ({ halfW, halfH }),
bounds3: () => ({ halfW, halfH, halfD }),
edge: (n) => place(sampleCurves(edgeCurves, n, edgeCuts)),
surface: (n) => place(samplePartsWithCuts(entries, n)),
}
}
/* =========================================================================
* material — the shader. No texture, no post-processing pass.
*
* CALM_* are two rounded-box SDFs evaluated *after* projection, dimming
* particles that sit behind text. That is the trick that lets type stay
* legible on top of a live additive field without a scrim or backdrop blur.
* ========================================================================= */
const CALM_CHUNK = /* glsl */ `
uniform vec4 uCalmA;
uniform vec4 uCalmB;
uniform float uCalmOn;
uniform float uAspect;
`
const CALM_APPLY = /* glsl */ `
vec2 sp = gl_Position.xy / max(gl_Position.w, 1e-4);
sp.x *= uAspect;
float dCalm = min(
length(max(abs(sp - uCalmA.xy) - uCalmA.zw, vec2(0.0))),
length(max(abs(sp - uCalmB.xy) - uCalmB.zw, vec2(0.0)))
);
vA *= 1.0 - uCalmOn * 0.7 * (1.0 - smoothstep(0.0, 0.45, dCalm));
`
const VERTEX = /* glsl */ `
attribute vec3 aCol;
attribute float aSize;
attribute float aSoft;
attribute float aPhase;
attribute float aTw;
attribute float aDrift;
uniform float uScale; // renderer height * 0.5 — keeps sizes resolution-independent
uniform float uTime;
uniform float uMotion; // 0 kills all idle animation (reduced motion)
uniform float uSizeMul;
uniform float uMinPx;
uniform float uLife; // 0 = uniform dust, 1 = fully materialised
uniform float uSeedSize; // the size every particle starts at when uLife = 0
uniform float uBurst; // 0 = intact, 1 = fully dissolved
${CALM_CHUNK}
varying vec3 vCol;
varying float vSoft;
varying float vA;
void main() {
vCol = aCol;
// Turbulent wander. Three different frequencies keep it from looking like
// every particle is riding the same wave.
vec3 p = position;
float dr = aDrift * uLife * uMotion;
p.x += sin(uTime * 0.73 + aPhase) * dr;
p.y += sin(uTime * 0.61 + aPhase * 1.7) * dr;
p.z += sin(uTime * 0.51 + aPhase * 2.3) * dr;
vec4 mv = modelViewMatrix * vec4(p, 1.0);
float depth = max(-mv.z, 0.1);
// Materialise: every particle starts as identical fine dust and grows into
// its own size class. Dissolving grows and softens it further, so the cloud
// evaporates rather than merely flying apart.
float size = mix(uSeedSize, aSize, uLife) * (1.0 + uBurst * 0.6);
vSoft = clamp(mix(aSoft * uLife, 1.0, uBurst * 0.85), 0.0, 1.0);
// Manual perspective attenuation, clamped so particles never vanish and
// never blow up into screen-filling quads.
gl_PointSize = clamp(size * uSizeMul * uScale / depth, uMinPx, uScale * 0.05);
float tw = 1.0 - aTw * uMotion *
(0.5 + 0.5 * sin(uTime * (1.4 + fract(aPhase) * 1.3) + aPhase * 6.283));
float dAtt = clamp((depth - 16.0) / 8.0, 0.0, 1.0);
vA = tw * mix(1.0, 0.55, dAtt) * smoothstep(0.12, 1.1, depth);
gl_Position = projectionMatrix * mv;
${CALM_APPLY}
}
`
const FRAGMENT = /* glsl */ `
uniform float uOpacity;
varying vec3 vCol;
varying float vSoft;
varying float vA;
void main() {
// Procedural sprite — no texture is loaded anywhere in this component.
vec2 q = gl_PointCoord - vec2(0.5);
float d2 = dot(q, q) * 4.0;
if (d2 >= 1.0) discard;
float inv = 1.0 - d2;
float tight = min(1.0, inv * 1.9); // crisp disc with a soft edge
float soft = inv * inv; // wide quadratic glow
// The whole "blur / bloom" look is this mix, stacked additively. No post pass.
float a = mix(tight, soft * 0.55, vSoft) * vA * uOpacity;
if (a < 0.004) discard;
gl_FragColor = vec4(vCol, a);
}
`
function createMaterial(options = {}) {
return new THREE.ShaderMaterial({
transparent: true,
// Additive blending assumes a dark background. On a light background this
// needs NormalBlending and a re-thought palette.
blending: THREE.AdditiveBlending,
depthWrite: false,
vertexShader: VERTEX,
fragmentShader: FRAGMENT,
uniforms: {
uScale: { value: 1 },
uTime: { value: 0 },
uMotion: { value: options.motion === false ? 0 : 1 },
uSizeMul: { value: options.sizeMultiplier ?? 1 },
uMinPx: { value: 0 },
uLife: { value: 1 },
uSeedSize: { value: options.seedSize ?? 0.115 },
uBurst: { value: 0 },
uOpacity: { value: 1 },
uAspect: { value: 1 },
// Parked far off-screen so the SDF is inert until real rects arrive.
uCalmA: { value: new THREE.Vector4(99, 99, 0, 0) },
uCalmB: { value: new THREE.Vector4(99, 99, 0, 0) },
uCalmOn: { value: 0 },
},
})
}
/* =========================================================================
* geometry — turns a sampler into buffers.
*
* `soft` per size class is what produces the bokeh look: there is no blur
* pass anywhere, just a small share of large, very soft, additive points.
* ========================================================================= */
const DEFAULT_CLASSES = [
{ mix: 0.70, size: [0.08, 0.135], soft: 0.10 },
{ mix: 0.25, size: [0.16, 0.25], soft: 0.45 },
{ mix: 0.05, size: [0.32, 0.58], soft: 1.00 }, // the bokeh
]
const rand = (lo, hi) => lo + Math.random() * (hi - lo)
function buildGeometry(sampler, options = {}) {
const volume = isVolume(sampler)
const count = options.count ?? 6000
const rimFraction = options.rimFraction ?? 0.26
const cloudCount = Math.min(options.cloudCount ?? 260, count)
const cloudSpread = options.cloudSpread ?? [1.15, 1.9]
const cloudAmplitude = options.cloudAmplitude ?? 0.38
const thicknessRatio = options.thickness ?? 0.09
const rimSize = options.rimSize ?? [0.075, 0.13]
const rimSoft = options.rimSoft ?? 0.08
const classes = options.classes ?? DEFAULT_CLASSES
const twinkle = options.twinkle ?? 0.38
const driftBase = options.drift ?? 0.055
const pal = options.palette ?? {}
const pale = new THREE.Color(pal.pale ?? '#9FF5D4')
const accent = new THREE.Color(pal.accent ?? '#2EE6A0')
const deep = new THREE.Color(pal.deep ?? '#14805A')
const sparkle = new THREE.Color(pal.sparkle ?? '#FFFFFF')
const sparkleChance = pal.sparkleChance ?? 0.015
const { halfW, halfH } = sampler.bounds()
// 2D shapes fabricate depth as a thin slab; a volume sampler owns its own
// z and `thickness` is ignored (2D-only by design).
const halfD = volume ? sampler.bounds3().halfD : thicknessRatio * halfH
const rMax = Math.max(halfW, halfH)
const body = count - cloudCount
const rimCount = Math.round(body * rimFraction)
const fillCount = body - rimCount
const position = new Float32Array(count * 3)
const aCol = new Float32Array(count * 3)
const aSize = new Float32Array(count)
const aSoft = new Float32Array(count)
const aPhase = new Float32Array(count)
const aTw = new Float32Array(count)
const aDrift = new Float32Array(count)
const cloudAmp = new Float32Array(count)
const burstDir = new Float32Array(count * 3)
const burstDist = new Float32Array(count)
const holeJitter = new Float32Array(count)
const holeAngle = new Float32Array(count)
// Normalised cumulative mix, so `classes` need not sum to exactly 1.
const total = classes.reduce((s, c) => s + c.mix, 0) || 1
const cumulative = []
let acc = 0
for (const c of classes) {
acc += c.mix / total
cumulative.push(acc)
}
function pickClass() {
const r = Math.random()
for (let i = 0; i < cumulative.length; i++) if (r <= cumulative[i]) return classes[i]
return classes[classes.length - 1]
}
const tmp = new THREE.Color()
let w = 0
const writeCommon = (i, size, soft, tw, drift) => {
aSize[i] = size
aSoft[i] = soft
aPhase[i] = Math.random() * Math.PI * 2
aTw[i] = tw
aDrift[i] = drift
holeJitter[i] = 1 + (Math.random() * 2 - 1) * 0.08
holeAngle[i] = Math.random() * Math.PI * 2
}
// --- 1. Outline / feature edges --------------------------------------
const rimPts = volume ? sampler.edge(rimCount) : sampler.rim(rimCount)
const rimStride = volume ? 3 : 2
for (let i = 0; i < rimCount; i++, w++) {
const o = w * 3
position[o] = rimPts[i * rimStride]
position[o + 1] = rimPts[i * rimStride + 1]
position[o + 2] = volume
? rimPts[i * rimStride + 2]
: (Math.random() * 2 - 1) * halfD * 0.8
// The rim is what defines the silhouette, so it stays bright and crisp.
tmp.copy(Math.random() < 0.55 ? pale : accent)
aCol[o] = tmp.r
aCol[o + 1] = tmp.g
aCol[o + 2] = tmp.b
writeCommon(w, rand(rimSize[0], rimSize[1]), rimSoft, twinkle * 0.5, driftBase * 0.12)
}
// --- 2. Interior / surface -------------------------------------------
const fillPts = volume ? sampler.surface(fillCount) : sampler.fill(fillCount)
const fillStride = volume ? 3 : 2
for (let i = 0; i < fillCount; i++, w++) {
const o = w * 3
const x = fillPts[i * fillStride]
const y = fillPts[i * fillStride + 1]
const z = volume ? fillPts[i * fillStride + 2] : (Math.random() * 2 - 1) * halfD
position[o] = x
position[o + 1] = y
position[o + 2] = z
const q = Math.random()
if (Math.random() < sparkleChance) tmp.copy(sparkle)
else tmp.copy(q < 0.55 ? accent : q < 0.8 ? deep : pale)
// Depth cueing, and the reason the cloud reads as volumetric: particles
// are graded toward the pale shell colour. For the symmetric 2D slab the
// cue is |z|; a volume has a FRONT, so the cue is signed frontness —
// nose, brows and horn tips catch the light, the hollow back falls dark.
const radial = Math.min(Math.hypot(x, y) / rMax, 1)
let grade
if (volume) {
const front = Math.min(Math.max((z / halfD) * 0.5 + 0.5, 0), 1)
grade = Math.min(radial * radial * 0.4 + Math.pow(front, 1.8) * 0.55, 1) * 0.4
} else {
const zn = halfD > 0 ? Math.abs(z) / halfD : 0
grade = Math.min(radial * radial * 0.7 + zn * zn * zn * 0.45, 1) * 0.35
}
aCol[o] = tmp.r + (pale.r - tmp.r) * grade
aCol[o + 1] = tmp.g + (pale.g - tmp.g) * grade
aCol[o + 2] = tmp.b + (pale.b - tmp.b) * grade
const cls = pickClass()
writeCommon(
w,
rand(cls.size[0], cls.size[1]),
cls.soft,
twinkle * (0.6 + Math.random() * 0.8),
driftBase * (0.4 + Math.random() * 0.6),
)
}
// --- 3. Halo ---------------------------------------------------------
for (let i = 0; i < cloudCount; i++, w++) {
const o = w * 3
const theta = Math.random() * Math.PI * 2
const spread = rand(cloudSpread[0], cloudSpread[1])
position[o] = Math.cos(theta) * halfW * spread + (Math.random() - 0.5) * 1.4
position[o + 1] = Math.sin(theta) * halfH * spread + (Math.random() - 0.5) * 1.4
position[o + 2] = (Math.random() * 2 - 1) * halfD * (volume ? 0.9 : 2.6)
// Dimmed by baking brightness into the colour — with additive blending
// that is equivalent to a per-particle alpha, minus one attribute.
tmp.copy(Math.random() < 0.5 ? pale : accent).multiplyScalar(0.55 + Math.random() * 0.35)
aCol[o] = tmp.r
aCol[o + 1] = tmp.g
aCol[o + 2] = tmp.b
const cls = pickClass()
writeCommon(w, rand(cls.size[0], cls.size[1]), cls.soft, twinkle * (0.8 + Math.random() * 0.8), 0)
cloudAmp[w] = cloudAmplitude * (0.5 + Math.random())
}
// --- Dissolve targets -------------------------------------------------
for (let i = 0; i < count; i++) {
const theta = Math.random() * Math.PI * 2
const phi = Math.acos(2 * Math.random() - 1)
burstDir[i * 3] = Math.sin(phi) * Math.cos(theta)
burstDir[i * 3 + 1] = Math.sin(phi) * Math.sin(theta)
burstDir[i * 3 + 2] = Math.cos(phi)
burstDist[i] = rMax * (1.6 + Math.random() * 2.6)
aPhase[i] = aPhase[i] || Math.random() * Math.PI * 2
}
const live = new Float32Array(position)
const geometry = new THREE.BufferGeometry()
geometry.setAttribute('position', new THREE.BufferAttribute(live, 3))
geometry.setAttribute('aCol', new THREE.BufferAttribute(aCol, 3))
geometry.setAttribute('aSize', new THREE.BufferAttribute(aSize, 1))
geometry.setAttribute('aSoft', new THREE.BufferAttribute(aSoft, 1))
geometry.setAttribute('aPhase', new THREE.BufferAttribute(aPhase, 1))
geometry.setAttribute('aTw', new THREE.BufferAttribute(aTw, 1))
geometry.setAttribute('aDrift', new THREE.BufferAttribute(aDrift, 1))
// Points are displaced by the cursor and the dissolve, so the bounding
// sphere is never right. Frustum culling is disabled by the caller.
geometry.computeBoundingSphere()
return {
geometry,
count,
base: position,
live,
burstDir,
burstDist,
cloudAmp,
phase: aPhase,
holeJitter,
holeAngle,
bounds: { halfW, halfH, halfD },
}
}
/* =========================================================================
* interaction — the CPU position pass.
*
* The cursor effect is a hole PUNCH, not a repulsion field. Rather than
* pushing particles away with a falloff, every particle inside the radius is
* moved to sit exactly ON the rim of the disc, which is why it reads as a
* clean bite with a bright pile-up around it instead of a soft smear.
*
* Distance is measured perpendicular to the view axis, in local space, so
* the hole stays a circle on screen no matter how far the field has rotated.
* ========================================================================= */
class FieldSolver {
constructor(geo, options = {}) {
this.geo = geo
this.smoothed = new Float32Array(geo.base)
this.offsets = new Float32Array(geo.base.length)
const rMax = Math.max(geo.bounds.halfW, geo.bounds.halfH)
this.holeRadius = (options.holeRadius ?? 0.17) * rMax
this.springIn = options.springIn ?? 0.22
this.springOut = options.springOut ?? 0.055
this.restEnergy = options.restEnergy ?? 0.02
this.driftLerp = options.driftLerp ?? 0.08
/** True while offsets are non-zero, so we keep solving as it relaxes back. */
this.settling = false
/** Diagnostics, surfaced on the demo page. */
this.energy = 0
this.affected = 0
}
/** Advance one frame, writing into `geo.live`. */
update(params) {
const { time, burst, cursorLocal, viewAxisLocal, motion } = params
const {
base, live, burstDir, burstDist, cloudAmp, phase, holeJitter, holeAngle, count,
} = this.geo
const smoothed = this.smoothed
const offsets = this.offsets
const lerp = motion ? this.driftLerp : 1
const holeR = this.holeRadius
const holeR2 = holeR * holeR
// Orthonormal basis perpendicular to the view axis, for the degenerate
// case of a particle sitting exactly under the cursor.
const ax = viewAxisLocal.x
const ay = viewAxisLocal.y
const az = viewAxisLocal.z
const useYZ = Math.abs(ax) < 0.9
let t1x = useYZ ? 0 : -az
let t1y = useYZ ? -az : 0
let t1z = useYZ ? ay : ax
const t1len = Math.hypot(t1x, t1y, t1z) || 1
t1x /= t1len
t1y /= t1len
t1z /= t1len
const t2x = ay * t1z - az * t1y
const t2y = az * t1x - ax * t1z
const t2z = ax * t1y - ay * t1x
const interacting = cursorLocal !== null || this.settling
let energy = 0
let affected = 0
for (let i = 0; i < count; i++) {
const o = i * 3
let tx = base[o]
let ty = base[o + 1]
let tz = base[o + 2]
// Halo particles breathe slowly on their own.
const amp = cloudAmp[i]
if (amp > 0 && motion) {
const ph = phase[i]
tx += Math.sin(time * 0.13 + ph) * amp
ty += Math.sin(time * 0.11 + ph * 1.7) * amp
tz += Math.sin(time * 0.09 + ph * 2.3) * amp
}
// Dissolve: travel outward along a fixed random direction.
if (burst > 0) {
tx += burstDir[o] * burstDist[i] * burst
ty += burstDir[o + 1] * burstDist[i] * burst
tz += burstDir[o + 2] * burstDist[i] * burst
}
const sx = (smoothed[o] += (tx - smoothed[o]) * lerp)
const sy = (smoothed[o + 1] += (ty - smoothed[o + 1]) * lerp)
const sz = (smoothed[o + 2] += (tz - smoothed[o + 2]) * lerp)
if (!interacting) {
live[o] = sx
live[o + 1] = sy
live[o + 2] = sz
continue
}
let wantX = 0
let wantY = 0
let wantZ = 0
let inside = false
if (cursorLocal) {
const dx = sx - cursorLocal.x
const dy = sy - cursorLocal.y
const dz = sz - cursorLocal.z
// Drop the component along the view axis: what remains is the true
// on-screen distance, independent of depth.
const along = dx * ax + dy * ay + dz * az
const px = dx - along * ax
const py = dy - along * ay
const pz = dz - along * az
const d2 = px * px + py * py + pz * pz
if (d2 < holeR2) {
inside = true
affected++
const target = holeR * holeJitter[i]
if (d2 > 1e-6) {
// Push out to land exactly on the rim.
const k = target / Math.sqrt(d2) - 1
wantX = px * k
wantY = py * k
wantZ = pz * k
} else {
// Dead centre — no direction to push along, so pick one.
const a = holeAngle[i]
const c = Math.cos(a)
const s = Math.sin(a)
wantX = (t1x * c + t2x * s) * target
wantY = (t1y * c + t2y * s) * target
wantZ = (t1z * c + t2z * s) * target
}
}
}
// Asymmetric spring: snap in ~4x faster than it relaxes out. This is
// what gives the interaction its viscous, trailing feel.
const k = inside ? this.springIn : this.springOut
const ox = (offsets[o] += (wantX - offsets[o]) * k)
const oy = (offsets[o + 1] += (wantY - offsets[o + 1]) * k)
const oz = (offsets[o + 2] += (wantZ - offsets[o + 2]) * k)
energy += ox * ox + oy * oy + oz * oz
live[o] = sx + ox
live[o + 1] = sy + oy
live[o + 2] = sz + oz
}
this.energy = energy
this.affected = affected
if (interacting && !cursorLocal && energy < this.restEnergy) {
// Fully relaxed: zero the offsets and stop solving the interaction until
// the cursor comes back. A real idle path, not just a small number.
offsets.fill(0)
this.settling = false
} else {
this.settling = interacting
}
return true
}
}
/* =========================================================================
* scene — the component itself.
* ========================================================================= */
const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v)
const smoothstep = (t) => t * t * (3 - 2 * t)
/** Perceptually even dolly: interpolate distance in log space, not linearly. */
const dollyAt = (t, far, near) =>
far * Math.pow(near / far, 0.7 * t + 0.3 * smoothstep(t))
function radialSprite() {
const c = document.createElement('canvas')
c.width = c.height = 64
const ctx = c.getContext('2d')
const g = ctx.createRadialGradient(32, 32, 0, 32, 32, 32)
g.addColorStop(0, 'rgba(255,255,255,1)')
g.addColorStop(0.35, 'rgba(255,255,255,.8)')
g.addColorStop(1, 'rgba(255,255,255,0)')
ctx.fillStyle = g
ctx.fillRect(0, 0, 64, 64)
return new THREE.CanvasTexture(c)
}
function starLayer(count, rMin, rMax, size, accentChance, sprite) {
const pos = new Float32Array(count * 3)
const col = new Float32Array(count * 3)
const dim = new THREE.Color('#dddddd')
const accent = new THREE.Color('#2ee6a0')
const grey = new THREE.Color('#888888')
for (let i = 0; i < count; i++) {
const r = rMin + Math.random() * (rMax - rMin)
const theta = Math.random() * Math.PI * 2
const phi = Math.acos(2 * Math.random() - 1)
pos[i * 3] = r * Math.sin(phi) * Math.cos(theta)
pos[i * 3 + 1] = r * Math.sin(phi) * Math.sin(theta) * 0.7
// Pushed behind the field so it never intersects the star.
pos[i * 3 + 2] = -Math.abs(r * Math.cos(phi)) * 0.6 - 4
const c = Math.random() < accentChance ? accent : Math.random() < 0.5 ? dim : grey
col[i * 3] = c.r
col[i * 3 + 1] = c.g
col[i * 3 + 2] = c.b
}
const g = new THREE.BufferGeometry()
g.setAttribute('position', new THREE.BufferAttribute(pos, 3))
g.setAttribute('color', new THREE.BufferAttribute(col, 3))
return new THREE.Points(
g,
new THREE.PointsMaterial({
size,
map: sprite,
vertexColors: true,
transparent: true,
opacity: 0.85,
depthWrite: false,
blending: THREE.AdditiveBlending,
sizeAttenuation: true,
}),
)
}
/** Last-resort static silhouette when WebGL is unavailable. */
function svgFallback(shape) {
const NS = 'http://www.w3.org/2000/svg'
const svg = document.createElementNS(NS, 'svg')
const { halfW, halfH } = shape.bounds()
svg.setAttribute('viewBox', `${-halfW * 1.2} ${-halfH * 1.2} ${halfW * 2.4} ${halfH * 2.4}`)
svg.setAttribute('class', 'pf-fallback')
svg.setAttribute('aria-hidden', 'true')
const defs = document.createElementNS(NS, 'defs')
const grad = document.createElementNS(NS, 'radialGradient')
grad.setAttribute('id', 'pf-fb')
for (const [offset, color] of [
['0%', '#0c4632'],
['45%', '#14805a'],
['82%', '#2ee6a0'],
['100%', '#9ff5d4'],
]) {
const stop = document.createElementNS(NS, 'stop')
stop.setAttribute('offset', offset)
stop.setAttribute('stop-color', color)
grad.appendChild(stop)
}
defs.appendChild(grad)
svg.appendChild(defs)
// Trace the outline from the sampler itself, so any shape gets a fallback.
// A volume sampler has no single outline — flatten its feature curves to
// dots instead of pretending they form one closed path.
const stride = isVolume(shape) ? 3 : 2
const pts = isVolume(shape) ? shape.edge(240) : shape.rim(240)
const path = document.createElementNS(NS, 'path')
if (isVolume(shape)) {
let d = ''
for (let i = 0; i < 240; i++) {
const x = pts[i * stride].toFixed(2)
const y = (-pts[i * stride + 1]).toFixed(2)
d += `M${x} ${y}h0.06`
}
path.setAttribute('d', d)
path.setAttribute('stroke-linecap', 'round')
} else {
let d = ''
for (let i = 0; i < 240; i++) {
d += (i ? 'L' : 'M') + pts[i * 2].toFixed(2) + ' ' + (-pts[i * 2 + 1]).toFixed(2)
}
path.setAttribute('d', d + 'Z')
}
path.setAttribute('fill', 'url(#pf-fb)')
path.setAttribute('stroke', '#9ff5d4')
path.setAttribute('stroke-width', '0.06')
path.setAttribute('stroke-opacity', '0.8')
svg.appendChild(path)
return svg
}
function createParticleField(host, options = {}) {
const motionOn = !prefersReducedMotion
// Mutable and exposed on the returned field, so motion can be retuned live
// without rebuilding geometry or dropping the GL context.
const motion = {
autoSpin: 0,
sway: 0.6,
swaySpeed: 0.16,
parallaxReach: 0.9,
scrollSpin: Math.PI * 1.15,
tilt: 0.2,
wobble: 0.07,
dolly: [106, 16],
lifeRange: [0.05, 0.75],
driftFade: [0.1, 0.6],
wander: [0.8, 0.55],
oscillation: [0.08, 0.05],
driftLerp: 0.05,
...options.motion,
}
const fov = options.fov ?? 50
const cameraZ = options.cameraZ ?? 16
const maxDpr = options.maxDpr ?? 2
let shape = options.shape ?? superellipse()
// --- WebGL, with a real fallback -------------------------------------
let renderer = null
try {
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })
if (!renderer.getContext()) renderer = null
} catch {
renderer = null
}
if (!renderer) {
const fb = svgFallback(shape)
host.appendChild(fb)
const noop = () => {}
return {
scene: new THREE.Scene(),
camera: new THREE.PerspectiveCamera(),
renderer: null,
group: new THREE.Group(),
material: createMaterial(),
webgl: false,
motion,
step: noop,
setCalmTargets: noop,
setShape: noop,
stats: () => ({ count: 0, fps: 0, energy: 0, affected: 0, webgl: false }),
destroy: () => fb.remove(),
}
}
// A collapsed viewport is a real state — a hidden tab, a `display: none`
// ancestor, a panel animating from zero height. Left unclamped it divides
// by zero: the aspect becomes NaN, which poisons the projection matrix,
// and the drawing buffer height becomes 0, which pins every point to the
// minimum size permanently. Neither recovers, so clamp at the source.
const viewW = () => Math.max(1, innerWidth)
const viewH = () => Math.max(1, innerHeight)
renderer.outputColorSpace = THREE.SRGBColorSpace
renderer.setPixelRatio(Math.min(devicePixelRatio, maxDpr))
renderer.setSize(viewW(), viewH())
host.appendChild(renderer.domElement)
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(fov, viewW() / viewH(), 0.1, 300)
camera.position.z = cameraZ
const sprite = radialSprite()
let bgA = null
let bgB = null
if (options.starfield !== false) {
bgA = starLayer(900, 30, 90, 0.5, 0.06, sprite)
bgB = starLayer(700, 25, 80, 0.32, 0.1, sprite)
scene.add(bgA, bgB)
}
const group = new THREE.Group()
scene.add(group)
const material = createMaterial({ motion: motionOn, ...options.material })
let geometryDefaults = options.geometry
let solverDefaults = options.solver
// Phones are limited by fill rate and thermal budget long before the shader
// gets interesting. Spend less by drawing fewer particles rather than by
// degrading the effect — the look survives a smaller count, but not a
// cheaper sprite.
const isNarrow = () => innerWidth > 0 && innerWidth < (options.mobileBreakpoint ?? 768)
const withMobileBudget = (g) => {
if (!isNarrow()) return g
const base = g ?? {}
const k = options.mobileCountScale ?? 0.6
return {
...base,
count: Math.round((base.count ?? 6000) * k),
cloudCount: Math.round((base.cloudCount ?? 260) * k),
}
}
let geo = buildGeometry(shape, withMobileBudget(geometryDefaults))
let solver = new FieldSolver(geo, solverDefaults)
let points = new THREE.Points(geo.geometry, material)
points.frustumCulled = false // positions are displaced every frame
group.add(points)
// --- Pointer ----------------------------------------------------------
const ndc = new THREE.Vector2(99, 99)
let pointerLive = false
const onPointerMove = (e) => {
ndc.set((e.clientX / viewW()) * 2 - 1, -(e.clientY / viewH()) * 2 + 1)
pointerLive = motionOn
}
const onPointerOut = (e) => {
if (!e.relatedTarget) pointerLive = false
}
window.addEventListener('pointermove', onPointerMove, { passive: true })
document.addEventListener('pointerout', onPointerOut)
// --- Resize -----------------------------------------------------------
const syncScale = () => {
// Sizes are expressed against half the drawing-buffer height, so a point
// occupies the same fraction of the screen at any resolution or DPR.
material.uniforms.uScale.value = Math.max(1, renderer.domElement.height) * 0.5
material.uniforms.uAspect.value = camera.aspect
}
const onResize = () => {
camera.aspect = viewW() / viewH()
camera.updateProjectionMatrix()
renderer.setSize(viewW(), viewH())
syncScale()
measureCalm()
}
syncScale()
window.addEventListener('resize', onResize)
// --- Calm rects -------------------------------------------------------
let calmTargets = []
let calmBoxes = []
function measureCalm() {
// Measured on resize only — never inside the frame loop, so this can
// never cause a forced reflow mid-render.
calmBoxes = calmTargets.slice(0, 2).map((el) => {
const r = el.getBoundingClientRect()
return {
cx: r.left + r.width / 2,
cy: r.top + r.height / 2,
hw: r.width / 2,
hh: r.height / 2,
}
})
}
const drive =
options.drive ??
((s) => {
const max = document.documentElement.scrollHeight - s.H
return { progress: max > 0 ? clamp01(s.y / max) : 0, burst: 0 }
})
// --- Frame ------------------------------------------------------------
const viewAxis = new THREE.Vector3(0, 0, 1)
const invRot = new THREE.Matrix4()
const rayDir = new THREE.Vector3()
const hit = new THREE.Vector3()
const cursorLocal = new THREE.Vector3()
let driftX = 0
let driftY = 0
let fps = 0
let frames = 0
let fpsClock = 0
function step(state) {
const { time, dt } = state
const { progress, burst } = drive(state)
const p = clamp01(progress)
const b = clamp01(burst)
frames++
fpsClock += dt
if (fpsClock >= 0.5) {
fps = frames / fpsClock
frames = 0
fpsClock = 0
}
const [dollyFar, dollyNear] = motion.dolly
const [lifeFrom, lifeTo] = motion.lifeRange
const [fadeFrom, fadeTo] = motion.driftFade
// --- Dolly ---
const distance = dollyAt(p, dollyFar, dollyNear)
const groupZ = cameraZ - distance
// --- Rotation ---
group.rotation.y =
(motionOn ? time * motion.autoSpin + Math.sin(time * motion.swaySpeed) * motion.sway : 0) +
p * motion.scrollSpin
group.rotation.x = motion.tilt + (motionOn ? Math.sin(time * 0.09) * motion.wobble : 0)
// --- Parallax, clamped so the field can never leave the viewport ---
const halfHWorld = Math.tan((fov / 2) * (Math.PI / 180)) * distance
const halfWWorld = halfHWorld * camera.aspect
// Bounded twice: it must not leave the viewport, and it must not drift
// further than a fraction of its own size. Without the second bound a
// distant field roams across half the screen and reads as unmoored.
const spanX = Math.max(
0,
Math.min(halfWWorld - geo.bounds.halfW * 0.9, geo.bounds.halfW * motion.parallaxReach),
)
const spanY = Math.max(
0,
Math.min(halfHWorld - geo.bounds.halfH * 0.9, geo.bounds.halfH * motion.parallaxReach),
)
let wantX = 0
let wantY = 0
if (motionOn) {
if (hasFinePointer && pointerLive && Math.abs(ndc.x) <= 1) {
wantX = ndc.x * spanX
wantY = ndc.y * spanY
} else {
// Layered sines at unrelated frequencies, so the path never visibly loops.
wantX =
(Math.sin(time * 0.26 + 2.4) * 0.68 + Math.sin(time * 0.071) * 0.32) *
spanX * motion.wander[0]
wantY =
(Math.sin(time * 0.31 + 0.7) * 0.58 + Math.cos(time * 0.047) * 0.42) *
spanY * motion.wander[1]
}
wantX += Math.sin(time * 0.5) * spanX * motion.oscillation[0]
wantY += Math.cos(time * 0.37) * spanY * motion.oscillation[1]
wantX = Math.max(-spanX, Math.min(spanX, wantX))
wantY = Math.max(-spanY, Math.min(spanY, wantY))
}
driftX += (wantX - driftX) * motion.driftLerp
driftY += (wantY - driftY) * motion.driftLerp
const fade = 1 - smoothstep(clamp01((p - fadeFrom) / (fadeTo - fadeFrom || 1)))
group.position.set(driftX * fade, driftY * fade, groupZ)
group.updateMatrixWorld()
// --- Materialise / dissolve ---
const life = motionOn
? 0.18 + 0.82 * smoothstep(clamp01((p - lifeFrom) / (lifeTo - lifeFrom || 1)))
: 1
material.uniforms.uLife.value = life
material.uniforms.uBurst.value = b
material.uniforms.uTime.value = time
material.uniforms.uOpacity.value = 0.95 - b * 0.6
// A floor of ~1.4 device px keeps distant dust from flickering into nothing.
material.uniforms.uMinPx.value = 1.4 * Math.min(devicePixelRatio, maxDpr)
// --- Cursor into the field's local space ---
let cursor = null
if (motionOn && hasFinePointer && pointerLive && p >= 0.98 && b < 0.5 && Math.abs(ndc.x) <= 1) {
rayDir.set(ndc.x, ndc.y, 0.5).unproject(camera).sub(camera.position).normalize()
if (Math.abs(rayDir.z) > 1e-5) {
// Intersect the plane the field currently sits on.
const t = (groupZ - camera.position.z) / rayDir.z
if (t > 0) {
hit.copy(camera.position).addScaledVector(rayDir, t)
cursor = group.worldToLocal(cursorLocal.copy(hit))
}
}
}
invRot.makeRotationFromEuler(group.rotation).invert()
viewAxis.set(0, 0, 1).applyMatrix4(invRot).normalize()
solver.update({
time, burst: b, cursorLocal: cursor, viewAxisLocal: viewAxis, motion: motionOn,
})
geo.geometry.attributes.position.needsUpdate = true
// --- Calm rects → clip space ---
if (calmBoxes.length > 0) {
const w = viewW()
const h = viewH()
const k = 2 / h
const a = calmBoxes[0]
const bx = calmBoxes[1] ?? a
material.uniforms.uCalmA.value.set(
(a.cx - w / 2) * k, (h / 2 - a.cy) * k, a.hw * k, a.hh * k,
)
material.uniforms.uCalmB.value.set(
(bx.cx - w / 2) * k, (h / 2 - bx.cy) * k, bx.hw * k, bx.hh * k,
)
material.uniforms.uCalmOn.value = 1 - clamp01((p - 0.35) / 0.2)
} else {
material.uniforms.uCalmOn.value = 0
}
if (motionOn) {
if (bgA) bgA.rotation.y = time * 0.004
if (bgB) bgB.rotation.y = -time * 0.006
if (bgA) bgA.rotation.x = ndc.y * 0.02
if (bgB) bgB.rotation.x = ndc.y * 0.03
}
renderer.render(scene, camera)
}
const unsubscribe = subscribe(step)
function setShape(next, geometryOptions, solverOptions) {
shape = next
if (geometryOptions) geometryDefaults = geometryOptions
if (solverOptions) solverDefaults = solverOptions
group.remove(points)
geo.geometry.dispose()
geo = buildGeometry(shape, withMobileBudget(geometryDefaults))
solver = new FieldSolver(geo, solverDefaults)
points = new THREE.Points(geo.geometry, material)
points.frustumCulled = false
group.add(points)
}
return {
scene,
camera,
renderer,
group,
material,
motion,
webgl: true,
step,
setCalmTargets(elements) {
calmTargets = elements
measureCalm()
},
setShape,
stats: () => ({
count: geo.count,
fps,
energy: solver.energy,
affected: solver.affected,
webgl: true,
}),
destroy() {
unsubscribe()
window.removeEventListener('resize', onResize)
window.removeEventListener('pointermove', onPointerMove)
document.removeEventListener('pointerout', onPointerOut)
geo.geometry.dispose()
material.dispose()
sprite.dispose()
for (const bg of [bgA, bgB]) {
if (!bg) continue
bg.geometry.dispose()
bg.material.dispose()
}
renderer.domElement.remove()
renderer.dispose()
},
}
}
/* =========================================================================
* demo — the page itself.
* ========================================================================= */
// --- Smooth scroll ------------------------------------------------------
// Driven from the shared frame bus rather than its own rAF, so the whole
// page runs on exactly one loop and the WebGL motion reads the same eased
// scroll value the DOM is using.
if (!prefersReducedMotion) {
const lenis = new Lenis({ autoRaf: false, smoothWheel: true })
subscribe(() => lenis.raf(performance.now()))
setScrollSource(() => lenis.scroll)
}
// --- Shapes -------------------------------------------------------------
const BOLT = 'M12 2 L4 13 H10 L9 22 L20 9 H13 L14 2 Z'
// Opposite winding on the inner circle punches a hole under the nonzero fill
// rule — a good check that the rasterising sampler handles subpaths.
const RING =
'M10,50 a40,40 0 1,0 80,0 a40,40 0 1,0 -80,0 M25,50 a25,25 0 1,1 50,0 a25,25 0 1,1 -50,0'
const params = {
shape: 'Hannya mask (3D)',
hornLength: 1,
mouthOpen: 1,
n: 3.7,
aspect: 1.05,
radius: 5.3,
thickness: 0.09,
count: 6000,
rimFraction: 0.26,
sizeMultiplier: 1,
bigMix: 0.05,
sway: 0.15,
autoSpin: 0.18,
holeRadius: 0.17,
springIn: 0.22,
springOut: 0.055,
}
function makeShape() {
switch (params.shape) {
case 'Hannya mask (3D)':
return hannya({ hornLength: params.hornLength, mouthOpen: params.mouthOpen })
case 'Bolt (SVG)':
return svgPath(BOLT, { radius: params.radius })
case 'Ring (SVG, has a hole)':
return svgPath(RING, { radius: params.radius })
default:
return superellipse({ n: params.n, aspect: params.aspect, radius: params.radius })
}
}
function makeClasses() {
// Hold the medium share fixed and trade the crisp class against the bokeh
// class, so the slider reads as "more glow" rather than "more particles".
const big = params.bigMix
const med = 0.25
return [
{ mix: Math.max(0, 1 - med - big), size: [0.08, 0.135], soft: 0.1 },
{ mix: med, size: [0.16, 0.25], soft: 0.45 },
{ mix: big, size: [0.32, 0.58], soft: 1.0 },
]
}
const geometryOptions = () => ({
count: params.count,
rimFraction: params.rimFraction,
thickness: params.thickness,
classes: makeClasses(),
})
const solverOptions = () => ({
holeRadius: params.holeRadius,
springIn: params.springIn,
springOut: params.springOut,
})
// --- Field --------------------------------------------------------------
const host = document.getElementById('field')
const field = createParticleField(host, {
shape: makeShape(),
geometry: geometryOptions(),
solver: solverOptions(),
motion: { sway: params.sway, autoSpin: params.autoSpin },
drive: (state) => {
const max = document.documentElement.scrollHeight - state.H
const t = max > 0 ? clamp01(state.y / max) : 0
return {
// Arrival occupies the first third; the dissolve, the last quarter.
progress: clamp01(t / 0.34),
burst: clamp01((t - 0.76) / 0.24),
}
},
})
// Handy in the console, and lets a headless check drive frames directly.
window.field = field
const title = document.getElementById('title')
const lede = document.getElementById('lede')
if (title && lede) field.setCalmTargets([title, lede])
// --- Controls -----------------------------------------------------------
if (field.webgl) {
const gui = new GUI({ title: 'Particle Field' })
const rebuild = () => {
field.setShape(makeShape(), geometryOptions(), solverOptions())
// Continuous spin is safe only for shapes with real depth — a flat shape
// collapses to a line edge-on, so switching back also switches motion.
const volumetric = params.shape === 'Hannya mask (3D)'
params.autoSpin = volumetric ? 0.18 : 0
params.sway = volumetric ? 0.15 : 0.6
field.motion.autoSpin = params.autoSpin
field.motion.sway = params.sway
gui.controllersRecursive().forEach((c) => c.updateDisplay())
}
const shapeFolder = gui.addFolder('Shape')
shapeFolder
.add(params, 'shape', [
'Hannya mask (3D)',
'Superellipse star',
'Bolt (SVG)',
'Ring (SVG, has a hole)',
])
.name('silhouette')
.onChange(rebuild)
shapeFolder.add(params, 'hornLength', 0.5, 1.6, 0.05).name('horns (mask)').onFinishChange(rebuild)
shapeFolder.add(params, 'mouthOpen', 0.6, 1.8, 0.05).name('grimace (mask)').onFinishChange(rebuild)
shapeFolder.add(params, 'n', 2, 8, 0.05).name('exponent (star)').onFinishChange(rebuild)
shapeFolder.add(params, 'aspect', 0.6, 1.6, 0.01).onFinishChange(rebuild)
shapeFolder.add(params, 'thickness', 0, 0.6, 0.005).name('slab depth').onFinishChange(rebuild)
shapeFolder.add(params, 'count', 1000, 20000, 500).onFinishChange(rebuild)
shapeFolder.add(params, 'rimFraction', 0, 0.8, 0.01).name('outline share').onFinishChange(rebuild)
const lookFolder = gui.addFolder('Look')
lookFolder
.add(params, 'sizeMultiplier', 0.2, 3, 0.05)
.name('size')
.onChange((v) => (field.material.uniforms.uSizeMul.value = v))
lookFolder.add(params, 'bigMix', 0, 0.4, 0.005).name('bokeh share').onFinishChange(rebuild)
const motionFolder = gui.addFolder('Motion')
motionFolder
.add(params, 'sway', 0, 1.5, 0.01)
.name('yaw sway (rad)')
.onChange((v) => (field.motion.sway = v))
motionFolder
.add(params, 'autoSpin', 0, 0.4, 0.005)
.name('continuous spin')
.onChange((v) => (field.motion.autoSpin = v))
const cursorFolder = gui.addFolder('Cursor')
cursorFolder.add(params, 'holeRadius', 0.02, 0.5, 0.005).name('hole radius').onFinishChange(rebuild)
cursorFolder.add(params, 'springIn', 0.02, 1, 0.01).onFinishChange(rebuild)
cursorFolder.add(params, 'springOut', 0.005, 0.5, 0.005).onFinishChange(rebuild)
cursorFolder.close()
}
// --- Stats --------------------------------------------------------------
const statsEl = document.getElementById('stats')
let statClock = 0
subscribe((state) => {
statClock += state.dt
if (statClock < 0.25) return
statClock = 0
const s = field.stats()
if (!s.webgl) {
statsEl.textContent = 'WebGL unavailable — SVG fallback'
return
}
statsEl.textContent =
`${s.fps.toFixed(0).padStart(3)} fpsn` +
`${s.count.toLocaleString()} particlesn` +
`${s.affected.toString().padStart(4)} displacedn` +
`${s.energy.toFixed(2).padStart(6)} energy` +
(s.energy === 0 ? ' (idle)' : '')
})
</script>
</body>
</html>[/hidecontent]