three-live 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +4 -1
  2. package/dist/index.d.ts +190 -0
  3. package/dist/three-author-engine.js +171 -163
  4. package/dist/three-author.cjs +145 -163
  5. package/dist/three-author.d.ts +190 -0
  6. package/dist/three-author.js +145 -163
  7. package/dist/three-convert.cjs +142 -160
  8. package/dist/three-convert.d.ts +190 -0
  9. package/dist/three-convert.js +142 -160
  10. package/dist/three-live-ai.cjs +41 -0
  11. package/dist/three-live-ai.d.ts +759 -0
  12. package/dist/three-live-ai.js +41 -0
  13. package/dist/three-live-ai.min.js +41 -0
  14. package/dist/three-live-animation.cjs +6 -6
  15. package/dist/three-live-animation.d.ts +190 -0
  16. package/dist/three-live-animation.js +5 -5
  17. package/dist/three-live-animation.min.js +5 -5
  18. package/dist/three-live-cad.cjs +2 -2
  19. package/dist/three-live-cad.d.ts +190 -0
  20. package/dist/three-live-cad.js +2 -2
  21. package/dist/three-live-cad.min.js +2 -2
  22. package/dist/three-live-element.cjs +50 -85
  23. package/dist/three-live-element.d.ts +190 -0
  24. package/dist/three-live-element.js +50 -85
  25. package/dist/three-live-full.cjs +907 -189
  26. package/dist/three-live-full.js +907 -189
  27. package/dist/three-live-full.min.js +907 -189
  28. package/dist/three-live-procedural.cjs +16 -0
  29. package/dist/three-live-procedural.d.ts +759 -0
  30. package/dist/three-live-procedural.js +16 -0
  31. package/dist/three-live-procedural.min.js +16 -0
  32. package/dist/three-live-sandbox.html +11 -1
  33. package/dist/three-live-studio.cjs +72 -17
  34. package/dist/three-live-studio.d.ts +190 -0
  35. package/dist/three-live-studio.js +72 -17
  36. package/dist/three-live-studio.min.js +73 -18
  37. package/dist/three-live-tsl.cjs +103 -0
  38. package/dist/three-live-tsl.d.ts +759 -0
  39. package/dist/three-live-tsl.js +103 -0
  40. package/dist/three-live-tsl.min.js +103 -0
  41. package/dist/three-live-viewer.cjs +50 -85
  42. package/dist/three-live-viewer.d.ts +190 -0
  43. package/dist/three-live-viewer.js +50 -85
  44. package/dist/three-live-viewer.min.js +50 -85
  45. package/dist/three-live-webgpu.cjs +585 -0
  46. package/dist/three-live-webgpu.d.ts +759 -0
  47. package/dist/three-live-webgpu.js +585 -0
  48. package/dist/three-live-webgpu.min.js +585 -0
  49. package/dist/three-live.cjs +147 -165
  50. package/dist/three-live.js +147 -165
  51. package/dist/three-live.min.js +147 -165
  52. package/dist/three-view.cjs +49 -84
  53. package/dist/three-view.d.ts +190 -0
  54. package/dist/three-view.js +50 -85
  55. package/dist/three-xr.cjs +141 -159
  56. package/dist/three-xr.d.ts +190 -0
  57. package/dist/three-xr.js +140 -158
  58. package/package.json +21 -1
@@ -13,8 +13,8 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */var Vo=Object.defineProperty,Uo=(e,t)=>{for(var r in t)Vo(e,r,{get:t[r],enumerable:!0})},Ds={};Uo(Ds,{AmbientLight:()=>Kr,BoxGeometry:()=>Gr,BufferAttribute:()=>He,BufferGeometry:()=>Ue,Camera:()=>Zr,CapsuleGeometry:()=>Vn,CatmullRomCurve3:()=>cn,CircleGeometry:()=>Un,Clock:()=>Sn,Color:()=>ft,ConeGeometry:()=>sn,CubicBezierCurve3:()=>hn,Curve3:()=>St,CylinderGeometry:()=>Wr,DataTexture:()=>fn,DirectionalLight:()=>Mn,DodecahedronGeometry:()=>Fn,EdgesGeometry:()=>zn,Euler:()=>$r,Float32BufferAttribute:()=>Ji,Group:()=>vn,HemisphereLight:()=>hi,IKSolver:()=>Gs,IcosahedronGeometry:()=>kn,InstancedMesh:()=>qr,InteractivityVM:()=>ys,LOD:()=>Ks,LatheGeometry:()=>jr,Light:()=>er,Line:()=>Dt,LineBasicMaterial:()=>xr,LineCurve3:()=>ln,LineDashedMaterial:()=>Bn,LineLoop:()=>$n,LineSegments:()=>Hn,LodController:()=>zi,MAX_BSP_DEPTH:()=>Bs,MAX_CSG_TRIANGLES:()=>Us,MAX_INSTANCES_PER_MESH:()=>Jt,MAX_SHAPE_POINTS:()=>zs,MAX_TEXT_GEOMETRY_CHARS:()=>Os,Material:()=>tt,MathUtils:()=>Qi,Matrix3:()=>Zi,Matrix4:()=>_t,Mesh:()=>xt,MeshBasicMaterial:()=>gn,MeshLambertMaterial:()=>yn,MeshPhongMaterial:()=>bn,MeshPhysicalMaterial:()=>xn,MeshStandardMaterial:()=>Qt,Object3D:()=>pt,OctahedronGeometry:()=>Dn,PerspectiveCamera:()=>wn,PlaneGeometry:()=>rn,PointLight:()=>Yr,Points:()=>Gn,PointsMaterial:()=>ui,PolyhedronFallbackGeometry:()=>Da,PolyhedronGeometry:()=>Et,QuadraticBezierCurve3:()=>un,Quaternion:()=>dr,RawShaderMaterial:()=>_n,RectAreaLight:()=>jn,RingGeometry:()=>li,Scene:()=>Qr,SceneQuotaValidator:()=>vt,ShaderMaterial:()=>ai,SphereGeometry:()=>nn,SpotLight:()=>Wn,THREE:()=>kt,TetrahedronGeometry:()=>In,Texture:()=>gr,TextureLoader:()=>pn,ThreeLiveElement:()=>Ft,ThreeView:()=>Ze,TorusGeometry:()=>an,TorusKnotGeometry:()=>on,TubeGeometry:()=>mn,Uint16BufferAttribute:()=>en,Uint32BufferAttribute:()=>tn,Vector2:()=>lt,Vector3:()=>xe,Vector4:()=>Yi,WebGLRenderer:()=>Tn,WireframeGeometry:()=>On,activateAR:()=>os,applyMeshoptFilter:()=>Ms,authorScriptRunner:()=>br,buildSandboxWorkerSource:()=>ii,cadPlugin:()=>Ci,clearAuthorWarnings:()=>Ln,computeOutlineClipOffset:()=>vo,contactShadowPlugin:()=>pi,createUSDZBlob:()=>zr,crossFadeTo:()=>Yn,decimateGeometry:()=>qs,decodeMeshoptBuffer:()=>ws,decodeMeshoptGLB:()=>Ti,defineModelViewer:()=>Ba,encodeMeshoptBuffer:()=>yo,environmentMapPlugin:()=>cs,evaluateKawaseBloom:()=>xo,evaluateToneMapping:()=>ta,exportSceneToCanvas3D:()=>Jr,exportSceneToGLB:()=>ei,exportSceneToUSDZ:()=>An,extractMaterialVariants:()=>Rs,extractPrimitiveVariantMappings:()=>Ao,generateUSDZ:()=>Or,getARCapabilities:()=>di,getAllowClientScripts:()=>Cn,getAuthorWarnings:()=>Nn,getBestARMode:()=>Ga,getEnvironmentSH:()=>Xa,getInteractivityVM:()=>Mi,getLodController:()=>Ys,getSandboxEngineSrc:()=>ri,getSandboxIframeSrc:()=>En,glbToUSDZ:()=>Br,hotspotPlugin:()=>ps,ikPlugin:()=>Oi,installCadExtension:()=>Pr,installLodExtension:()=>ur,interactivityPlugin:()=>xs,isAllowedSandboxEngineUrl:()=>It,isQuickLookSupported:()=>ns,isSceneViewerSupported:()=>ss,isWebXRSupported:()=>as,keyframeAnimationPlugin:()=>Jn,lodPlugin:()=>$i,materialsPlugin:()=>vs,meshoptDecoder:()=>Si,meshoptPlugin:()=>As,morphPlugin:()=>es,noopProxy:()=>tr,parseAnimations:()=>Kn,parseHexRgb:()=>Ts,parseLod:()=>Ir,parseSafeGltfPointer:()=>Ar,postprocessingPlugin:()=>Ss,quatFromUnitVectors:()=>Nr,registerMaterialShader:()=>io,sampleChannel:()=>ir,sceneToCanvas3D:()=>Zt,sceneToGLB:()=>fr,sceneToUSDZ:()=>pr,selectLodLevelIndex:()=>_r,selectMaterialVariant:()=>To,sendInteractivityEvent:()=>bs,setAllowClientScripts:()=>Ra,setEnvironmentSH:()=>us,setMorphTargetWeight:()=>$a,setSandboxEngineSrc:()=>Ta,setSandboxIframeSrc:()=>Sa,skinningPlugin:()=>rs,solveFABRIK:()=>Di,solveTwoBoneIK:()=>Ii,threeAuthorPlugin:()=>rr,threeMicroPlugin:()=>Ua,toGLBData:()=>Yt,toTrustedWorkerScriptURL:()=>Rn,validateSandboxWorkerMessage:()=>ni,variantsPlugin:()=>Ps,warnUnsupported:()=>Pt,webxrPlugin:()=>Es});function Bo(e,t,r){let i=[],n=new Map,s=[],l=[],o=[],a=new Map,u=p=>{let y=n.get(p);return y===void 0&&(y=i.length,i.push({op:p}),n.set(p,y)),y},h=p=>{let y=a.get(p);return y===void 0&&(y=o.length,o.push({id:p}),a.set(p,y)),y},m=(p,y={})=>s.push({declaration:u(p),...y})-1,c=(p,y,M)=>l.push({id:p,type:y,value:M})-1,d=p=>({node:p,socket:"value"}),f=r?.interactivity??r?.gltfExtensions?.KHR_interactivity;if(f&&typeof f=="object"){let p=Array.isArray(f.graphs)?f.graphs[f.graph??0]:f;if(p&&Array.isArray(p.nodes)){let y=Array.isArray(p.declarations)?p.declarations:[];for(let M of y)M?.op&&u(M.op);Array.isArray(p.variables)&&l.push(...p.variables);for(let M of p.events||[])M?.id&&h(M.id);for(let M of p.nodes){if(!M||typeof M!="object")continue;let P=M.op||(typeof M.declaration=="number"?y[M.declaration]?.op:"");s.push(P?{...M,declaration:u(P)}:{...M})}}}let g=(p,y,M="translation")=>M==="baseColorFactor"||M==="metallicFactor"||M==="roughnessFactor"?`/materials/${Math.max(0,y)}/pbrMetallicRoughness/${M}`:M==="emissiveFactor"||M==="alphaCutoff"?`/materials/${Math.max(0,y)}/${M}`:M==="visible"?`/nodes/${p}/extensions/KHR_node_visibility/visible`:`/nodes/${p}/${M}`,x=new Map;e.forEach((p,y)=>{typeof p?.name=="string"&&!x.has(p.name)&&x.set(p.name,y)});let b=(p,y)=>typeof p.target=="string"&&x.has(p.target)?x.get(p.target):typeof p.targetNode=="number"?p.targetNode:y,v=p=>{let y=e[p];return(typeof y?.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0};for(let p=0;p<e.length;p++){let y=e[p],M=y?.extras?.interactivity;if(!M||typeof M!="object")continue;let P=(typeof y.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0,F=T=>{let E=Array.isArray(T)?T:[T],S=[];for(let k=0;k<E.length;k++){let w=E[k];if(!w||typeof w!="object")continue;let ie=w.action||"interpolate",oe=typeof w.duration=="number"?w.duration:.35;if(ie==="toggleTransform"){let I=w.property==="rotation"||w.property==="scale"?w.property:"translation",H=I==="rotation"?y.rotation||[0,0,0,1]:I==="scale"?y.scale||[1,1,1]:y.translation||[0,0,0],C=`/nodes/${p}/${I}`,z=c(`__toggle_${p}_${k}`,"bool",!1),ue=m("variable/get",{configuration:{variable:z}}),he=m("math/not",{values:{a:d(ue)}}),O=m("variable/set",{configuration:{variable:z},values:{value:d(he)}}),$=m("pointer/interpolate",{configuration:{pointer:C},values:{value:{value:Array.isArray(w.to)?w.to:H},duration:{value:oe}}}),_=m("pointer/interpolate",{configuration:{pointer:C},values:{value:{value:Array.isArray(w.from)?w.from:H},duration:{value:oe}}});s[O].flows={out:{node:m("flow/branch",{values:{condition:d(ue)},flows:{true:{node:$},false:{node:_}}})}},S.push(O)}else if(ie==="interpolate"){let I=w.to??w.value;if(I===void 0)continue;let H={value:{value:I},duration:{value:oe}};w.from!==void 0&&(H.from={value:w.from}),S.push(m("pointer/interpolate",{configuration:{pointer:typeof w.pointer=="string"?w.pointer:g(b(w,p),v(b(w,p)),w.property)},values:H}))}else if(ie==="setProperty"){if(w.value===void 0)continue;S.push(m("pointer/set",{configuration:{pointer:typeof w.pointer=="string"?w.pointer:g(b(w,p),v(b(w,p)),w.property)},values:{value:{value:w.value}}}))}else if(ie==="toggleVisibility"){let I=b(w,p),H=c(`__vis_${I}_${k}`,"bool",!0),C=m("variable/get",{configuration:{variable:H}}),z=m("math/not",{values:{a:d(C)}}),ue=m("variable/set",{configuration:{variable:H},values:{value:d(z)}});s[ue].flows={out:{node:m("pointer/set",{configuration:{pointer:`/nodes/${I}/extensions/KHR_node_visibility/visible`},values:{value:d(C)}})}},S.push(ue)}else if(ie==="cycleMaterialColor"&&Array.isArray(w.colors)&&w.colors.length>0){let I=typeof w.duration=="number"?w.duration:.25,H=`/materials/${Math.max(0,P)}/pbrMetallicRoughness/baseColorFactor`,C=c(`__color_idx_${p}_${k}`,"int",0),z=m("variable/get",{configuration:{variable:C}}),ue=m("math/add",{values:{a:d(z),b:{value:1}}}),he=m("math/rem",{values:{a:d(ue),b:{value:w.colors.length}}}),O=m("variable/set",{configuration:{variable:C},values:{value:d(he)}}),$={};for(let _=0;_<w.colors.length;_++){let W=w.colors[_],j=Array.isArray(W)&&W.length>=3?[W[0],W[1],W[2],W[3]??1]:[1,1,1,1];$[String(_)]={node:I>0?m("pointer/interpolate",{configuration:{pointer:H},values:{value:{value:j},duration:{value:I}}}):m("pointer/set",{configuration:{pointer:H},values:{value:{value:j}}})}}s[O].flows={out:{node:m("flow/switch",{values:{selection:d(z)},flows:$})}},S.push(O)}else if(ie==="playAnimation")S.push(m("animation/start",{configuration:{animation:w.animation??w.clip??0}}));else if(ie==="stopAnimation")S.push(m("animation/stop"));else if(ie==="sendEvent"){let I={};for(let[H,C]of Object.entries(w.values||{}))I[H]={value:C};S.push(m("event/send",{configuration:{event:h(String(w.event??w.id??"custom"))},values:I}))}}if(!S.length)return null;if(S.length===1)return S[0];let B={};return S.forEach((k,w)=>{B[String(w)]={node:k}}),m("flow/sequence",{flows:B})},G=(T,E,S)=>{let B=F(E);B!==null&&m(T,{...S?{configuration:S}:{},flows:{out:{node:B}}})};if(M.onSelect&&G("pointer/onSelect",M.onSelect,{nodeIndex:p}),M.onHoverIn&&G("pointer/onHoverIn",M.onHoverIn,{nodeIndex:p}),M.onHoverOut&&G("pointer/onHoverOut",M.onHoverOut,{nodeIndex:p}),M.onStart&&G("event/onStart",M.onStart),M.onReceive&&typeof M.onReceive=="object")for(let[T,E]of Object.entries(M.onReceive))G("event/receive",E,{event:h(T)})}return s.length?{graphs:[{declarations:i,nodes:s,variables:l,events:o}],graph:0}:null}var ks='SecurityError: Client-modified script compilation (Use Case 1) is disabled by default to satisfy strict CSP and Trusted Types requirements. Use script-src="..." or loadScriptFromSrc(url) for server-generated scripts (Use Case 2), or explicitly opt in via ThreeLiveElement.allowClientScripts = true (or the allow-client-scripts attribute).',Fs="Security Error: client-side scripts require allow-client-scripts opt-in.",Rr="__THREE_LIVE_REGISTRY__";function Ae(){let e=typeof globalThis<"u"?globalThis:{};if(!e[Rr]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,Rr,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[Rr]=t}}return e[Rr]}var Ve=Ae().plugins;function Ei(e){let t=Ae();t.workerExtensionInstallers||(t.workerExtensionInstallers=[]),t.workerExtensionInstallers.includes(e)||t.workerExtensionInstallers.push(e)}function je(e){let t=Ae().plugins;t.some(r=>r.name===e.name)||t.push(e),e.onRegister?.()}function Vs(){return Ae().plugins}var Us=8192,Bs=2048,Os=128,zs=4096;function Pr(e,t){if(!e||!e.BufferGeometry)return null;let r=e.Vector2,i=e.Vector3,n=e.Quaternion,s=e.Matrix4,l=e.Matrix3,o=e.Color,a=e.BufferAttribute,u=e.BufferGeometry,h=e.Material,m=e.MeshStandardMaterial,c=e.Mesh,d=8192,f=2048,g=128,x=4096,b=(R,A)=>{let L=R==null?NaN:Number(R);return Number.isFinite(L)?L:A};class v{constructor(A){this.currentPoint=new r(0,0),this.segments=[],Array.isArray(A)&&A.length>0&&this.fromPoints(A)}fromPoints(A){if(!A.length)return this;this.moveTo(A[0].x,A[0].y);for(let L=1;L<A.length;L++)this.lineTo(A[L].x,A[L].y);return this}moveTo(A,L){let N=Number(A)||0,U=Number(L)||0;return this.currentPoint.set(N,U),this.segments.push({type:"move",pts:[N,U]}),this}lineTo(A,L){let N=Number(A)||0,U=Number(L)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[this.currentPoint.x,this.currentPoint.y]}),this.currentPoint.set(N,U),this.segments.push({type:"line",pts:[N,U]}),this}quadraticCurveTo(A,L,N,U){let Q=this.currentPoint.x,q=this.currentPoint.y,Z=Number(A)||0,J=Number(L)||0,K=Number(N)||0,ae=Number(U)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[Q,q]}),this.currentPoint.set(K,ae),this.segments.push({type:"quad",pts:[Q,q,Z,J,K,ae]}),this}bezierCurveTo(A,L,N,U,Q,q){let Z=this.currentPoint.x,J=this.currentPoint.y,K=Number(A)||0,ae=Number(L)||0,ne=Number(N)||0,re=Number(U)||0,ce=Number(Q)||0,me=Number(q)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[Z,J]}),this.currentPoint.set(ce,me),this.segments.push({type:"cubic",pts:[Z,J,K,ae,ne,re,ce,me]}),this}absarc(A,L,N,U,Q,q=!1){return this.absellipse(A,L,N,N,U,Q,q,0)}arc(A,L,N,U,Q,q=!1){return this.absarc(this.currentPoint.x+(Number(A)||0),this.currentPoint.y+(Number(L)||0),N,U,Q,q)}absellipse(A,L,N,U,Q,q,Z=!1,J=0){let K=Number(A)||0,ae=Number(L)||0,ne=Math.max(0,Number(N)||0),re=Math.max(0,Number(U)||0),ce=Number(Q)||0,me=Number(q)||0,ge=Z?1:0,de=Number(J)||0;this.segments.push({type:"arc",pts:[K,ae,ne,re,ce,me,ge,de]});let pe=Math.cos(de),ye=Math.sin(de),ve=ne*Math.cos(me),be=re*Math.sin(me);return this.currentPoint.set(K+ve*pe-be*ye,ae+ve*ye+be*pe),this}ellipse(A,L,N,U,Q,q,Z=!1,J=0){return this.absellipse(this.currentPoint.x+(Number(A)||0),this.currentPoint.y+(Number(L)||0),N,U,Q,q,Z,J)}closePath(){if(this.segments.length>0){let A=this.segments[0],L=0,N=0;if(A.type==="arc"){let U=A.pts[0],Q=A.pts[1],q=A.pts[2],Z=A.pts[3],J=A.pts[4],K=A.pts[7],ae=Math.cos(K),ne=Math.sin(K),re=q*Math.cos(J),ce=Z*Math.sin(J);L=U+re*ae-ce*ne,N=Q+re*ne+ce*ae}else L=A.pts[0],N=A.pts[1];Math.hypot(this.currentPoint.x-L,this.currentPoint.y-N)>1e-6&&this.lineTo(L,N)}return this}getPoints(A=12){let L=Math.max(1,Math.min(128,Math.floor(Number(A)||12))),N=[],U=(Q,q)=>{if(N.length>0){let Z=N[N.length-1];if(Math.hypot(Z.x-Q,Z.y-q)<1e-6)return}N.push(new r(Q,q))};for(let Q of this.segments){let q=Q.pts;if(Q.type==="move"||Q.type==="line")U(q[0],q[1]);else if(Q.type==="quad"){let Z=q[0],J=q[1],K=q[2],ae=q[3],ne=q[4],re=q[5];U(Z,J);for(let ce=1;ce<=L;ce++){let me=ce/L,ge=1-me;U(ge*ge*Z+2*ge*me*K+me*me*ne,ge*ge*J+2*ge*me*ae+me*me*re)}}else if(Q.type==="cubic"){let Z=q[0],J=q[1],K=q[2],ae=q[3],ne=q[4],re=q[5],ce=q[6],me=q[7];U(Z,J);for(let ge=1;ge<=L;ge++){let de=ge/L,pe=1-de,ye=pe*pe,ve=de*de;U(ye*pe*Z+3*ye*de*K+3*pe*ve*ne+ve*de*ce,ye*pe*J+3*ye*de*ae+3*pe*ve*re+ve*de*me)}}else if(Q.type==="arc"){let Z=q[0],J=q[1],K=q[2],ae=q[3],ne=q[4],re=q[5],ce=q[6]!==0,me=q[7],ge=Math.PI*2,de=re-ne,pe=Math.abs(de)<1e-9;for(;de<0;)de+=ge;for(;de>ge;)de-=ge;de<1e-9&&(de=pe?0:ge),ce&&!pe&&(de=de===ge?-ge:de-ge);let ye=Math.cos(me),ve=Math.sin(me),be=Math.max(2,L);for(let Ee=0;Ee<=be;Ee++){let Te=Ee/be,Se=ne+Te*de,Ce=K*Math.cos(Se),Ie=ae*Math.sin(Se);U(Z+Ce*ye-Ie*ve,J+Ce*ve+Ie*ye)}}}if(N.length>2){let Q=N[0],q=N[N.length-1];Math.hypot(Q.x-q.x,Q.y-q.y)<1e-6&&N.pop()}return N}getSpacedPoints(A=12){return this.getPoints(A)}clone(){let A=new this.constructor;return A.currentPoint.copy(this.currentPoint),A.segments=this.segments.map(L=>({type:L.type,pts:[...L.pts]})),Array.isArray(this.holes)&&(A.holes=this.holes.map(L=>L.clone())),A}}class p extends v{constructor(A){super(A),this.holes=[]}extractPoints(A=12){return{shape:this.getPoints(A),holes:this.holes.map(L=>L.getPoints(A))}}}function y(R){let A=0,L=R.length;for(let N=0,U=L-1;N<L;U=N++)A+=R[U].x*R[N].y-R[N].x*R[U].y;return A*.5}function M(R,A,L,N,U,Q,q,Z){let J=q-L,K=Z-N,ae=U-L,ne=Q-N,re=R-L,ce=A-N,me=J*J+K*K,ge=J*ae+K*ne,de=J*re+K*ce,pe=ae*ae+ne*ne,ye=ae*re+ne*ce,ve=me*pe-ge*ge;if(Math.abs(ve)<1e-12)return!1;let be=1/ve,Ee=(pe*de-ge*ye)*be,Te=(me*ye-ge*de)*be;return Ee>=-1e-7&&Te>=-1e-7&&Ee+Te<=1+1e-7}function P(R,A){let L=R.slice();y(L)<0&&L.reverse();let N=L.map(J=>new r(J.x,J.y)),U=L.map((J,K)=>K),Q=[];for(let J of A){if(!J||J.length<3)continue;let K=J.slice();y(K)>0&&K.reverse();let ae=[],ne=-1/0,re=0;for(let ce=0;ce<K.length;ce++){let me=K[ce],ge=N.length;N.push(new r(me.x,me.y)),ae.push(ge),me.x>ne&&(ne=me.x,re=ce)}Q.push({pts:K,indices:ae,maxX:ne,maxIdx:re})}Q.sort((J,K)=>K.maxX-J.maxX);let q=(J,K,ae)=>(K.x-J.x)*(ae.y-J.y)-(K.y-J.y)*(ae.x-J.x),Z=(J,K,ae)=>{for(let ne=0;ne<ae.length;ne++){let re=ae[ne],ce=ae[(ne+1)%ae.length];if(q(J,K,re)*q(J,K,ce)<0&&q(re,ce,J)*q(re,ce,K)<0)return!0}return!1};for(let J of Q){let K=J.pts[J.maxIdx],ae=K.x,ne=U.length,re=U.map(pe=>N[pe]),ce=pe=>Math.hypot(re[pe].x-ae,re[pe].y-K.y),me=re.map((pe,ye)=>ye).sort((pe,ye)=>+(re[pe].x<ae)-+(re[ye].x<ae)||ce(pe)-ce(ye)),ge=me[0];for(let pe of me){let ye=re[pe],ve=re[(pe+ne-1)%ne],be=re[(pe+1)%ne],Ee=q(ye,be,K)>=0,Te=q(ve,ye,K)>=0;if((q(ve,ye,be)>=0?Ee&&Te:Ee||Te)&&!Z(K,ye,re)&&!Q.some(Se=>Z(K,ye,Se.pts))){ge=pe;break}}let de=[];for(let pe=0;pe<=ge;pe++)de.push(U[pe]);for(let pe=0;pe<=J.indices.length;pe++){let ye=J.indices[(J.maxIdx+pe)%J.indices.length];de.push(ye)}for(let pe=ge;pe<U.length;pe++)de.push(U[pe]);U=de}return{merged:U.map(J=>N[J]),mergedIndices:U,allVertices:N}}function F(R,A){let L=[],N=R.slice();if(N.length<3)return L;let U=N.length*N.length+64,Q=0;for(;N.length>2&&U-- >0;){let q=N.length,Z=N[(Q+q-1)%q],J=N[Q%q],K=N[(Q+1)%q],ae=A[Z],ne=A[J],re=A[K];if((ne.x-ae.x)*(re.y-ae.y)-(ne.y-ae.y)*(re.x-ae.x)>1e-9){let ce=!0,me=Math.min(ae.x,ne.x,re.x)-1e-7,ge=Math.max(ae.x,ne.x,re.x)+1e-7,de=Math.min(ae.y,ne.y,re.y)-1e-7,pe=Math.max(ae.y,ne.y,re.y)+1e-7;for(let ye=0;ye<q;ye++){let ve=N[ye];if(ve===Z||ve===J||ve===K)continue;let be=A[ve];if(be.x>=me&&be.x<=ge&&be.y>=de&&be.y<=pe&&M(be.x,be.y,ae.x,ae.y,ne.x,ne.y,re.x,re.y)&&(be.x-ae.x)*(be.x-ae.x)+(be.y-ae.y)*(be.y-ae.y)>=1e-12&&(be.x-ne.x)*(be.x-ne.x)+(be.y-ne.y)*(be.y-ne.y)>=1e-12&&(be.x-re.x)*(be.x-re.x)+(be.y-re.y)*(be.y-re.y)>=1e-12){ce=!1;break}}if(ce){L.push([Z,J,K]),N.splice(Q%q,1),Q=Math.max(0,Q%q-1);continue}}Q++,Q>=q*2&&(L.push([Z,J,K]),N.splice((Q-1)%q,1),Q=0)}return L}function G(R,A){let L=R instanceof p?R.extractPoints(A):{shape:R.getPoints(A),holes:[]},N=L.shape.length;for(let U of L.holes)N+=U.length;if(N>x)throw new RangeError(`SecurityError: shape point count (${N}) exceeds MAX_SHAPE_POINTS (${x})`);return L}function T(R){let A=1/0,L=1/0,N=-1/0,U=-1/0;for(let Q of R)Q.x<A&&(A=Q.x),Q.y<L&&(L=Q.y),Q.x>N&&(N=Q.x),Q.y>U&&(U=Q.y);return[A,L,Math.max(1e-6,N-A),Math.max(1e-6,U-L)]}class E extends u{constructor(A=new p,L=12){super();let N=Array.isArray(A)?A:[A],U=[],Q=[],q=[],Z=[];for(let J of N){if(!(J instanceof v))continue;let K=G(J,L);if(K.shape.length<3)continue;let{mergedIndices:ae,allVertices:ne}=P(K.shape,K.holes),re=F(ae,ne),ce=U.length/3,[me,ge,de,pe]=T(ne);for(let ye of ne)U.push(ye.x,ye.y,0),Q.push(0,0,1),q.push((ye.x-me)/de,(ye.y-ge)/pe);for(let[ye,ve,be]of re)Z.push(ce+ye,ce+ve,ce+be)}S(this,U,Q,q,Z)}}function S(R,A,L,N,U){return R.setAttribute("position",new a(A,3)),R.setAttribute("normal",new a(L,3)),R.setAttribute("uv",new a(N,2)),R.setIndex(U),R}function B(R){let A=R.length,L=[];for(let N=0;N<A;N++){let U=R[(N+A-1)%A],Q=R[N],q=R[(N+1)%A],Z=Q.x-U.x,J=Q.y-U.y,K=Math.hypot(Z,J)||1;Z/=K,J/=K;let ae=q.x-Q.x,ne=q.y-Q.y,re=Math.hypot(ae,ne)||1;ae/=re,ne/=re;let ce=J,me=-Z,ge=ne,de=-ae,pe=ce+ge,ye=me+de,ve=Math.hypot(pe,ye);if(ve>1e-6){pe/=ve,ye/=ve;let be=Math.max(.35,pe*ce+ye*me);L.push(new r(pe/be,ye/be))}else L.push(new r(ce,me))}return L}class k extends u{constructor(A=new p,L={}){super();let N=Array.isArray(A)?A:[A],U=Math.max(1,Math.min(64,Math.floor(b(L.curveSegments,12)))),Q=b(L.depth??L.amount,1),q=Math.max(1,Math.min(32,Math.floor(b(L.steps,1)))),Z=!!(L.bevelEnabled??!1),J=Z?Math.max(0,b(L.bevelThickness,.06)):0,K=Z?Math.max(0,b(L.bevelSize,J*.8)):0,ae=Z?b(L.bevelOffset,0):0,ne=Z?Math.max(1,Math.min(8,Math.floor(b(L.bevelSegments,2)))):0,re=[],ce=[],me=[],ge=[];for(let de of N){if(!(de instanceof v))continue;let pe=G(de,U);if(pe.shape.length<3)continue;let ye=pe.shape.slice();y(ye)<0&&ye.reverse();let ve=[];for(let Le of pe.holes){if(Le.length<3)continue;let Ne=Le.slice();y(Ne)>0&&Ne.reverse(),ve.push(Ne)}let{mergedIndices:be,allVertices:Ee}=P(ye,ve),Te=F(be,Ee),Se=[ye,...ve],Ce=[];for(let Le of Se){let Ne=B(Le);for(let We of Ne)Ce.push(We)}let[Ie,Je,Xe,ht]=T(Ee);for(let[Le,Ne]of[[-J,-1],[Q+J,1]]){let We=re.length/3;for(let ze=0;ze<Ee.length;ze++){let Be=Ee[ze],Oe=Ce[ze]??new r(0,0),et=Be.x+Oe.x*ae,Ke=Be.y+Oe.y*ae;re.push(et,Ke,Le),ce.push(0,0,Ne),me.push((et-Ie)/Xe,(Ke-Je)/ht)}for(let[ze,Be,Oe]of Te)ge.push(We+ze,We+(Ne<0?Oe:Be),We+(Ne<0?Be:Oe))}let Fe=[];if(Z&&ne>0)for(let Le=0;Le<ne;Le++){let Ne=Le/ne*Math.PI/2;Fe.push({z:-J*Math.cos(Ne),expand:ae+K*Math.sin(Ne)})}for(let Le=0;Le<=q;Le++){let Ne=Le/q;Fe.push({z:Ne*Q,expand:ae+K})}if(Z&&ne>0)for(let Le=1;Le<=ne;Le++){let Ne=Le/ne*Math.PI/2;Fe.push({z:Q+J*Math.sin(Ne),expand:ae+K*Math.cos(Ne)})}let nt=0;for(let Le of Se){let Ne=Le.length;for(let We=0;We<Fe.length-1;We++){let ze=Fe[We],Be=Fe[We+1];for(let Oe=0;Oe<Ne;Oe++){let et=(Oe+1)%Ne,Ke=Le[Oe],st=Le[et],at=Ce[nt+Oe],ot=Ce[nt+et],ct=Ke.x+at.x*ze.expand,mt=Ke.y+at.y*ze.expand,Bt=st.x+ot.x*ze.expand,Ot=st.y+ot.y*ze.expand,ar=st.x+ot.x*Be.expand,or=st.y+ot.y*Be.expand,Ct=Ke.x+at.x*Be.expand,Nt=Ke.y+at.y*Be.expand,Lt=Bt-ct,yt=Ot-mt,ko=Ct-ct,Fo=Nt-mt,Cs=Be.z-ze.z,zt=yt*Cs,$t=-Lt*Cs,Ht=Lt*Fo-yt*ko,Pi=Math.hypot(zt,$t,Ht)||1;zt/=Pi,$t/=Pi,Ht/=Pi;let Gt=re.length/3;re.push(ct,mt,ze.z,Bt,Ot,ze.z,ar,or,Be.z,Ct,Nt,Be.z),ce.push(zt,$t,Ht,zt,$t,Ht,zt,$t,Ht,zt,$t,Ht);let Ns=Oe/Ne,Ls=(Oe+1)/Ne,_s=We/(Fe.length-1),Is=(We+1)/(Fe.length-1);me.push(Ns,_s,Ls,_s,Ls,Is,Ns,Is),ge.push(Gt,Gt+1,Gt+2,Gt,Gt+2,Gt+3)}}nt+=Ne}}S(this,re,ce,me,ge)}}function w(R){return{x:R.x,y:R.y,z:R.z,nx:R.nx,ny:R.ny,nz:R.nz,u:R.u,v:R.v}}function ie(R){return{x:R.x,y:R.y,z:R.z,nx:-R.nx,ny:-R.ny,nz:-R.nz,u:R.u,v:R.v}}function oe(R,A,L){let N=R.nx+(A.nx-R.nx)*L,U=R.ny+(A.ny-R.ny)*L,Q=R.nz+(A.nz-R.nz)*L,q=Math.hypot(N,U,Q)||1;return{x:R.x+(A.x-R.x)*L,y:R.y+(A.y-R.y)*L,z:R.z+(A.z-R.z)*L,nx:N/q,ny:U/q,nz:Q/q,u:R.u+(A.u-R.u)*L,v:R.v+(A.v-R.v)*L}}function I(R){if(R.length<3)return null;let A=R[0],L=R[1],N=R[2],U=L.x-A.x,Q=L.y-A.y,q=L.z-A.z,Z=N.x-A.x,J=N.y-A.y,K=N.z-A.z,ae=Q*K-q*J,ne=q*Z-U*K,re=U*J-Q*Z,ce=Math.hypot(ae,ne,re);if(ce<1e-9)return null;ae/=ce,ne/=ce,re/=ce;let me=ae*A.x+ne*A.y+re*A.z;return{vertices:R,nx:ae,ny:ne,nz:re,w:me}}function H(R){R.vertices.reverse();for(let A=0;A<R.vertices.length;A++)R.vertices[A]=ie(R.vertices[A]);R.nx=-R.nx,R.ny=-R.ny,R.nz=-R.nz,R.w=-R.w}let C=1e-5,z=0,ue=1,he=2,O=3;function $(R,A,L,N,U,Q,q,Z,J){let K=0,ae=[];for(let ne=0;ne<U.vertices.length;ne++){let re=U.vertices[ne],ce=R*re.x+A*re.y+L*re.z-N,me=ce<-C?he:ce>C?ue:z;K|=me,ae.push(me)}switch(K){case z:{R*U.nx+A*U.ny+L*U.nz>0?Q.push(U):q.push(U);break}case ue:Z.push(U);break;case he:J.push(U);break;case O:{let ne=[],re=[],ce=U.vertices.length;for(let ye=0;ye<ce;ye++){let ve=(ye+1)%ce,be=ae[ye],Ee=ae[ve],Te=U.vertices[ye],Se=U.vertices[ve];if(be!==he&&ne.push(Te),be!==ue&&re.push(be!==he?w(Te):Te),(be|Ee)===O){let Ce=Se.x-Te.x,Ie=Se.y-Te.y,Je=Se.z-Te.z,Xe=R*Ce+A*Ie+L*Je,ht=Math.abs(Xe)>1e-12?(N-(R*Te.x+A*Te.y+L*Te.z))/Xe:.5,Fe=oe(Te,Se,Math.max(0,Math.min(1,ht)));ne.push(Fe),re.push(w(Fe))}}let{nx:me,ny:ge,nz:de,w:pe}=U;ne.length>=3&&Z.push({vertices:ne,nx:me,ny:ge,nz:de,w:pe}),re.length>=3&&J.push({vertices:re,nx:me,ny:ge,nz:de,w:pe});break}default:break}}class _{constructor(A,L=0){this.nx=0,this.ny=0,this.nz=0,this.w=0,this.hasPlane=!1,this.polygons=[],this.front=null,this.back=null,A&&A.length>0&&this.build(A,L)}invert(){for(let L=0;L<this.polygons.length;L++)H(this.polygons[L]);this.nx=-this.nx,this.ny=-this.ny,this.nz=-this.nz,this.w=-this.w,this.front&&this.front.invert(),this.back&&this.back.invert();let A=this.front;this.front=this.back,this.back=A}clipPolygons(A,L=0){if(!this.hasPlane||A.length===0)return A.slice();if(L>=f)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${f})`);let N=[],U=[];for(let Q=0;Q<A.length;Q++)$(this.nx,this.ny,this.nz,this.w,A[Q],N,U,N,U);return this.front&&N.length>0&&(N=this.front.clipPolygons(N,L+1)),this.back?U=U.length>0?this.back.clipPolygons(U,L+1):[]:U=[],N.concat(U)}clipTo(A,L=0){this.polygons.length>0&&(this.polygons=A.clipPolygons(this.polygons,0)),L<f&&(this.front&&this.front.clipTo(A,L+1),this.back&&this.back.clipTo(A,L+1))}allPolygons(A=[]){for(let L=0;L<this.polygons.length;L++)A.push(this.polygons[L]);return this.front&&this.front.allPolygons(A),this.back&&this.back.allPolygons(A),A}build(A,L=0){if(!A.length)return;if(!this.hasPlane){let Q=A[A.length>>1];this.nx=Q.nx,this.ny=Q.ny,this.nz=Q.nz,this.w=Q.w,this.hasPlane=!0}if(L>=f)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${f})`);let N=[],U=[];for(let Q=0;Q<A.length;Q++)$(this.nx,this.ny,this.nz,this.w,A[Q],this.polygons,this.polygons,N,U);N.length>0&&(this.front||(this.front=new _),this.front.build(N,L+1)),U.length>0&&(this.back||(this.back=new _),this.back.build(U,L+1))}}function W(R,A){if(!A&&R._csgPolygons)return R._csgPolygons;let L=R.attributes.position;if(!L||L.count===0)return[];let N=R.attributes.normal,U=R.attributes.uv,Q=R.index?R.index.array:null,q=Math.floor(Q?Q.length/3:L.count/3);if(q>d)throw new RangeError(`SecurityError: CSG input triangle count (${q}) exceeds MAX_CSG_TRIANGLES (${d})`);let Z=A?A.elements:null,J=Z?Z[0]*(Z[5]*Z[10]-Z[9]*Z[6])-Z[4]*(Z[1]*Z[10]-Z[9]*Z[2])+Z[8]*(Z[1]*Z[6]-Z[5]*Z[2])<0:!1,K=Z?new l().getNormalMatrix(A).elements:null,ae=re=>{let ce=L.getX(re),me=L.getY(re),ge=L.getZ(re),de=N?N.getX(re):NaN,pe=N?N.getY(re):NaN,ye=N?N.getZ(re):NaN;if(Z&&K){let Ee=Z[0]*ce+Z[4]*me+Z[8]*ge+Z[12],Te=Z[1]*ce+Z[5]*me+Z[9]*ge+Z[13],Se=Z[2]*ce+Z[6]*me+Z[10]*ge+Z[14];ce=Ee,me=Te,ge=Se;let Ce=K[0]*de+K[3]*pe+K[6]*ye,Ie=K[1]*de+K[4]*pe+K[7]*ye,Je=K[2]*de+K[5]*pe+K[8]*ye,Xe=Math.hypot(Ce,Ie,Je)||1;de=Ce/Xe,pe=Ie/Xe,ye=Je/Xe}let ve=U?U.getX(re):0,be=U?U.getY(re):0;return{x:ce,y:me,z:ge,nx:de,ny:pe,nz:ye,u:ve,v:be}},ne=[];for(let re=0;re<q;re++){let ce=Q?Q[re*3]:re*3,me=Q?Q[re*3+1]:re*3+1,ge=Q?Q[re*3+2]:re*3+2,de=I(J?[ae(ce),ae(ge),ae(me)]:[ae(ce),ae(me),ae(ge)]);de&&ne.push(de)}return ne}function j(R){let A=[],L=[],N=[],U=[];for(let q of R){let Z=q.vertices;if(Z.length<3)continue;let J=A.length/3;for(let K of Z)A.push(K.x,K.y,K.z),Number.isFinite(K.nx)&&K.nx*K.nx+K.ny*K.ny+K.nz*K.nz>.5?L.push(K.nx,K.ny,K.nz):L.push(q.nx,q.ny,q.nz),N.push(K.u,K.v);for(let K=1;K<Z.length-1;K++)U.push(J,J+K,J+K+1)}let Q=S(new u,A,L,N,U);return Q._csgPolygons=R,Q}function X(R,A,L){if(R.length+A.length>d)throw new RangeError(`SecurityError: Combined CSG triangle count (${R.length+A.length}) exceeds MAX_CSG_TRIANGLES (${d})`);if(R.length===0)return L==="union"?A:[];if(A.length===0)return L==="intersect"?[]:R;let N=1/0,U=1/0,Q=1/0,q=-1/0,Z=-1/0,J=-1/0;for(let ce=0;ce<A.length;ce++){let me=A[ce].vertices;for(let ge=0;ge<me.length;ge++){let de=me[ge];de.x<N&&(N=de.x),de.y<U&&(U=de.y),de.z<Q&&(Q=de.z),de.x>q&&(q=de.x),de.y>Z&&(Z=de.y),de.z>J&&(J=de.z)}}N-=1e-4,U-=1e-4,Q-=1e-4,q+=1e-4,Z+=1e-4,J+=1e-4;let K=[],ae=[];for(let ce=0;ce<R.length;ce++){let me=R[ce],ge=me.vertices,de=1/0,pe=1/0,ye=1/0,ve=-1/0,be=-1/0,Ee=-1/0;for(let Te=0;Te<ge.length;Te++){let Se=ge[Te];Se.x<de&&(de=Se.x),Se.y<pe&&(pe=Se.y),Se.z<ye&&(ye=Se.z),Se.x>ve&&(ve=Se.x),Se.y>be&&(be=Se.y),Se.z>Ee&&(Ee=Se.z)}ve<N||de>q||be<U||pe>Z||Ee<Q||ye>J?ae.push(me):K.push(me)}if(K.length===0)return L==="union"?R.concat(A):L==="subtract"?R:[];let ne=new _(K),re=new _(A);return L==="union"?(ne.clipTo(re),re.clipTo(ne),re.invert(),re.clipTo(ne),re.invert(),ne.build(re.allPolygons()),ae.concat(ne.allPolygons())):L==="subtract"?(ne.invert(),ne.clipTo(re),re.clipTo(ne),re.invert(),re.clipTo(ne),re.invert(),ne.build(re.allPolygons()),ne.invert(),ae.concat(ne.allPolygons())):(ne.invert(),re.clipTo(ne),re.invert(),ne.clipTo(re),re.clipTo(ne),ne.build(re.allPolygons()),ne.invert(),ne.allPolygons())}function D(R,A,L,N=null,U=null){let Q=W(R,N),q=W(A,U);return j(X(Q,q,L))}function Y(R,A,L){let N=R instanceof c||!!R?.isMesh,U=A instanceof c||!!A?.isMesh,Q=N?R.geometry:R,q=U?A.geometry:A,Z=null;if(U)if(A.updateMatrix(),N){R.updateMatrix();let ne=new s().makeScale(1/(R.scale.x||1),1/(R.scale.y||1),1/(R.scale.z||1)),re=Math.hypot(R.quaternion.x,R.quaternion.y,R.quaternion.z,R.quaternion.w)||1,ce=new s().compose(new i(0,0,0),new n(-R.quaternion.x/re,-R.quaternion.y/re,-R.quaternion.z/re,R.quaternion.w/re),new i(1,1,1)),me=new s().makeTranslation(-R.position.x,-R.position.y,-R.position.z);Z=ne.multiply(ce).multiply(me).multiply(A.matrix)}else Z=A.matrix;let J=D(Q,q,L,null,Z),K=N?R.material:new m,ae=new c(J,K);return N&&(ae.position.copy(R.position),ae.quaternion.copy(R.quaternion),ae.scale.copy(R.scale),ae.name=R.name),ae}let te={toGeometry:D,subtract(R,A){return Y(R,A,"subtract")},union(R,A){return Y(R,A,"union")},intersect(R,A){return Y(R,A,"intersect")}},se={0:[[[.15,0],[.85,0],[.85,1],[.15,1],[.15,0]]],1:[[[.3,.8],[.5,1],[.5,0]],[[.2,0],[.8,0]]],2:[[[.15,.8],[.3,1],[.7,1],[.85,.8],[.85,.55],[.15,0],[.85,0]]],3:[[[.15,.85],[.3,1],[.75,1],[.85,.75],[.5,.5],[.85,.25],[.75,0],[.3,0],[.15,.15]]],4:[[[.7,0],[.7,1],[.15,.35],[.9,.35]]],5:[[[.85,1],[.2,1],[.15,.55],[.75,.55],[.85,.3],[.75,0],[.2,0]]],6:[[[.8,.9],[.5,1],[.15,.7],[.15,.15],[.5,0],[.85,.2],[.85,.45],[.5,.55],[.15,.45]]],7:[[[.15,1],[.85,1],[.35,0]]],8:[[[.2,.5],[.15,.75],[.3,1],[.7,1],[.85,.75],[.8,.5],[.2,.5],[.15,.2],[.3,0],[.7,0],[.85,.2],[.8,.5]]],9:[[[.85,.55],[.5,.45],[.15,.55],[.15,.85],[.5,1],[.85,.85],[.85,.2],[.5,0],[.2,.1]]],A:[[[.1,0],[.5,1],[.9,0]],[[.25,.35],[.75,.35]]],B:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]],[[.7,.5],[.85,.25],[.7,0],[.15,0]]],C:[[[.85,.8],[.65,1],[.3,1],[.15,.75],[.15,.25],[.3,0],[.65,0],[.85,.2]]],D:[[[.15,0],[.15,1],[.65,1],[.85,.75],[.85,.25],[.65,0],[.15,0]]],E:[[[.85,1],[.15,1],[.15,0],[.85,0]],[[.15,.5],[.7,.5]]],F:[[[.85,1],[.15,1],[.15,0]],[[.15,.5],[.7,.5]]],G:[[[.85,.8],[.65,1],[.3,1],[.15,.75],[.15,.25],[.3,0],[.85,0],[.85,.45],[.55,.45]]],H:[[[.15,0],[.15,1]],[[.85,0],[.85,1]],[[.15,.5],[.85,.5]]],I:[[[.25,1],[.75,1]],[[.5,1],[.5,0]],[[.25,0],[.75,0]]],J:[[[.8,1],[.8,.25],[.6,0],[.3,0],[.15,.25]]],K:[[[.15,0],[.15,1]],[[.85,1],[.15,.45],[.85,0]]],L:[[[.15,1],[.15,0],[.85,0]]],M:[[[.1,0],[.1,1],[.5,.35],[.9,1],[.9,0]]],N:[[[.15,0],[.15,1],[.85,0],[.85,1]]],O:[[[.3,0],[.7,0],[.85,.25],[.85,.75],[.7,1],[.3,1],[.15,.75],[.15,.25],[.3,0]]],P:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]]],Q:[[[.3,0],[.7,0],[.85,.25],[.85,.75],[.7,1],[.3,1],[.15,.75],[.15,.25],[.3,0]],[[.55,.3],[.9,-.05]]],R:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]],[[.55,.5],[.85,0]]],S:[[[.85,.85],[.65,1],[.3,1],[.15,.75],[.85,.25],[.7,0],[.3,0],[.15,.15]]],T:[[[.1,1],[.9,1]],[[.5,1],[.5,0]]],U:[[[.15,1],[.15,.25],[.35,0],[.65,0],[.85,.25],[.85,1]]],V:[[[.1,1],[.5,0],[.9,1]]],W:[[[.05,1],[.25,0],[.5,.65],[.75,0],[.95,1]]],X:[[[.15,1],[.85,0]],[[.85,1],[.15,0]]],Y:[[[.15,1],[.5,.5],[.85,1]],[[.5,.5],[.5,0]]],Z:[[[.15,1],[.85,1],[.15,0],[.85,0]]],".":[[[.45,0],[.55,0],[.55,.12],[.45,.12],[.45,0]]],",":[[[.5,.15],[.4,-.1]]],":":[[[.45,.1],[.55,.1]],[[.45,.7],[.55,.7]]],"-":[[[.2,.5],[.8,.5]]],"+":[[[.2,.5],[.8,.5]],[[.5,.2],[.5,.8]]],"=":[[[.2,.35],[.8,.35]],[[.2,.65],[.8,.65]]],"/":[[[.2,0],[.8,1]]],"!":[[[.5,1],[.5,.28]],[[.5,.1],[.5,0]]],"?":[[[.2,.8],[.35,1],[.7,1],[.85,.75],[.5,.45],[.5,.28]],[[.5,.1],[.5,0]]],"(":[[[.65,1],[.35,.65],[.35,.35],[.65,0]]],")":[[[.35,1],[.65,.65],[.65,.35],[.35,0]]],"%":[[[.2,0],[.8,1]],[[.2,.8],[.35,.8],[.35,.95],[.2,.95],[.2,.8]],[[.65,.05],[.8,.05],[.8,.2],[.65,.2],[.65,.05]]],"#":[[[.32,0],[.32,1]],[[.68,0],[.68,1]],[[.12,.35],[.88,.35]],[[.12,.65],[.88,.65]]],$:[[[.8,.8],[.6,.92],[.3,.92],[.18,.72],[.82,.28],[.7,.08],[.4,.08],[.2,.2]],[[.5,1],[.5,0]]],_:[[[.1,0],[.9,0]]],"[":[[[.65,1],[.3,1],[.3,0],[.65,0]]],"]":[[[.35,1],[.7,1],[.7,0],[.35,0]]],"<":[[[.75,.85],[.25,.5],[.75,.15]]],">":[[[.25,.85],[.75,.5],[.25,.15]]],"*":[[[.5,.2],[.5,.8]],[[.2,.35],[.8,.65]],[[.2,.65],[.8,.35]]],"\\":[[[.2,1],[.8,0]]]};class le extends u{constructor(A="",L={}){super();let N=String(A??"").slice(0,g),U=Math.max(.005,Math.min(100,b(L.size,.2))),Q=!!(L.bevelEnabled??!1),q=Q?Math.max(0,Math.min(2,b(L.bevelThickness,U*.04))):0,Z=Q?Math.max(0,Math.min(2,b(L.bevelSize,U*.03))):0,J=Math.max(.001,Math.min(20,b(L.depth??L.height,U*.2)))+q*2,K=U*.085+Z,ae=U*.68,ne=U*.82,re=[],ce=[],me=[],ge=[],de=(ve,be,Ee,Te,Se,Ce,Ie)=>{let Je=Ee-ve,Xe=Te-be,ht=Math.hypot(Je,Xe),Fe=1,nt=0;ht>1e-6&&(Fe=Je/ht,nt=Xe/ht);let Le=-nt*Se,Ne=Fe*Se,We=Fe*Se*.6,ze=nt*Se*.6,Be=ve-We+Le,Oe=be-ze+Ne,et=ve-We-Le,Ke=be-ze-Ne,st=Ee+We-Le,at=Te+ze-Ne,ot=Ee+We+Le,ct=Te+ze+Ne,mt=(Bt,Ot,ar,or,Ct,Nt,Lt)=>{let yt=re.length/3;re.push(Bt[0],Bt[1],Bt[2],Ot[0],Ot[1],Ot[2],ar[0],ar[1],ar[2],or[0],or[1],or[2]),ce.push(Ct,Nt,Lt,Ct,Nt,Lt,Ct,Nt,Lt,Ct,Nt,Lt),me.push(0,0,1,0,1,1,0,1),ge.push(yt,yt+1,yt+2,yt,yt+2,yt+3)};mt([Be,Oe,Ie],[et,Ke,Ie],[st,at,Ie],[ot,ct,Ie],0,0,1),mt([et,Ke,Ce],[Be,Oe,Ce],[ot,ct,Ce],[st,at,Ce],0,0,-1),mt([Be,Oe,Ce],[et,Ke,Ce],[et,Ke,Ie],[Be,Oe,Ie],-Fe,-nt,0),mt([st,at,Ce],[ot,ct,Ce],[ot,ct,Ie],[st,at,Ie],Fe,nt,0),mt([et,Ke,Ce],[st,at,Ce],[st,at,Ie],[et,Ke,Ie],nt,-Fe,0),mt([ot,ct,Ce],[Be,Oe,Ce],[Be,Oe,Ie],[ot,ct,Ie],-nt,Fe,0)},pe=0,ye=0;for(let ve=0;ve<N.length;ve++){let be=N[ve];if(be===`
17
- `){pe=0,ye-=U*1.35;continue}if(be===" "||be===" "){pe+=ne*(be===" "?.75:3);continue}if(be==="\r")continue;let Ee=be.toUpperCase(),Te=be!==Ee&&be>="a"&&be<="z",Se=se[Ee]??se["?"],Ce=Te?U*.76:U,Ie=Te?ae*.88:ae;for(let Je of Se)for(let Xe=0;Xe<Je.length-1;Xe++){let ht=Je[Xe],Fe=Je[Xe+1];de(pe+ht[0]*Ie,ye+ht[1]*Ce,pe+Fe[0]*Ie,ye+Fe[1]*Ce,K,-J*.5,J*.5)}pe+=Te?ne*.88:ne}S(this,re,ce,me,ge),L.center!==!1?this.center():this.computeBoundingBox()}}function V(R){if(!R)return;let A=R,L=R.userData?.xr?.text??R.userData?.xr?.label??R.userData?.xr?.title??R.userData?.xr?.caption??R.userData?.xr?.spatialLabel;if(L!=null&&L!==!1){let U=A.geometry?.attributes?.position;if((!U||U.count===0)&&R.userData._textApplied!==!0){let Q="",q=.08,Z=.015,J;if(typeof L=="string"||typeof L=="number")Q=String(L);else if(typeof L=="object"){let K=L;Q=String(K.text??K.value??""),K.size!==void 0&&(q=Number(K.size)||.08),(K.depth!==void 0||K.height!==void 0)&&(Z=Number(K.depth??K.height)||q*.2),(typeof K.color=="string"||typeof K.color=="number")&&(J=K.color)}Q.trim().length>0&&(A.geometry=new le(Q,{size:q,depth:Z}),R.userData._textApplied=!0,A.material instanceof h?J!==void 0&&R.userData._autoTextColorApplied!==!0&&(A.material.color=new o(J),R.userData._autoTextColorApplied=!0):A.material=new m({color:J??16317180}))}}let N=R.userData?.csg;if(N&&typeof N=="object"&&R.userData._csgApplied!==!0&&A.geometry instanceof u&&A.geometry.attributes.position?.count>0){R.userData._csgApplied=!0;let U=Array.isArray(N)?N:[N],Q=A.geometry;for(let q of U){if(!q||typeof q!="object")continue;let Z=q,J=String(Z.op??Z.operation??"subtract"),K=J==="union"||J==="intersect"?J:"subtract",ae=Z.target??Z.mesh??Z.geometry;if(ae instanceof c||ae instanceof u)try{let ne=K==="union"?te.union(A,ae):K==="intersect"?te.intersect(A,ae):te.subtract(A,ae);A.geometry!==Q&&A.geometry.dispose?.(),A.geometry=ne.geometry}catch(ne){typeof console<"u"&&console.warn("[three-live] userData.csg skipped:",ne)}}}}let ee={Path:v,Shape:p,ShapeGeometry:E,ExtrudeGeometry:k,TextGeometry:le,CSG:te,MAX_CSG_TRIANGLES:d,MAX_BSP_DEPTH:f,MAX_TEXT_GEOMETRY_CHARS:g,MAX_SHAPE_POINTS:x,materializeDeclarativeGeometry:V};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,ee),t._cadMaterialize=V,t.materializeDeclarativeGeometry=R=>{t._cadMaterialize?.(R),t._lodMaterialize?.(R)}),ee}var Ci={name:"cad",onRegister(){Ei(Pr);let e=Ae(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&Pr(t,e)}};function Pe(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function Ni(e,t,r,i,n){let s=1/Math.tan(t/2);e.fill(0),e[0]=s/r,e[5]=s,e[11]=-1;let l=1/(i-n);return e[10]=(n+i)*l,e[14]=2*n*i*l,e}function Er(e,t,r,i){let[n,s,l]=t,[o,a,u]=i,[h,m,c]=r,d=n-h,f=s-m,g=l-c,x=Math.hypot(d,f,g);x<=1e-5?(d=0,f=0,g=1):(d/=x,f/=x,g/=x);let b=a*g-u*f,v=u*d-o*g,p=o*f-a*d;x=Math.hypot(b,v,p),x<=1e-5?(b=0,v=0,p=0):(b/=x,v/=x,p/=x);let y=f*p-g*v,M=g*b-d*p,P=d*v-f*b;return x=Math.hypot(y,M,P),x<=1e-5?(y=0,M=0,P=0):(y/=x,M/=x,P/=x),e[0]=b,e[1]=y,e[2]=d,e[3]=0,e[4]=v,e[5]=M,e[6]=f,e[7]=0,e[8]=p,e[9]=P,e[10]=g,e[11]=0,e[12]=-(b*n+v*s+p*l),e[13]=-(y*n+M*s+P*l),e[14]=-(d*n+f*s+g*l),e[15]=1,e}function ke(e,t,r){let i=t[0],n=t[1],s=t[2],l=t[3],o=t[4],a=t[5],u=t[6],h=t[7],m=t[8],c=t[9],d=t[10],f=t[11],g=t[12],x=t[13],b=t[14],v=t[15],p=r[0],y=r[1],M=r[2],P=r[3];return e[0]=p*i+y*o+M*m+P*g,e[1]=p*n+y*a+M*c+P*x,e[2]=p*s+y*u+M*d+P*b,e[3]=p*l+y*h+M*f+P*v,p=r[4],y=r[5],M=r[6],P=r[7],e[4]=p*i+y*o+M*m+P*g,e[5]=p*n+y*a+M*c+P*x,e[6]=p*s+y*u+M*d+P*b,e[7]=p*l+y*h+M*f+P*v,p=r[8],y=r[9],M=r[10],P=r[11],e[8]=p*i+y*o+M*m+P*g,e[9]=p*n+y*a+M*c+P*x,e[10]=p*s+y*u+M*d+P*b,e[11]=p*l+y*h+M*f+P*v,p=r[12],y=r[13],M=r[14],P=r[15],e[12]=p*i+y*o+M*m+P*g,e[13]=p*n+y*a+M*c+P*x,e[14]=p*s+y*u+M*d+P*b,e[15]=p*l+y*h+M*f+P*v,e}function lr(e,t,r,i){let n=t[0],s=t[1],l=t[2],o=t[3],a=n+n,u=s+s,h=l+l,m=n*a,c=n*u,d=n*h,f=s*u,g=s*h,x=l*h,b=o*a,v=o*u,p=o*h,y=i[0],M=i[1],P=i[2];return e[0]=(1-(f+x))*y,e[1]=(c+p)*y,e[2]=(d-v)*y,e[3]=0,e[4]=(c-p)*M,e[5]=(1-(m+x))*M,e[6]=(g+b)*M,e[7]=0,e[8]=(d+v)*P,e[9]=(g-b)*P,e[10]=(1-(m+f))*P,e[11]=0,e[12]=r[0],e[13]=r[1],e[14]=r[2],e[15]=1,e}function Ye(e,t,r=0){let i=t[0],n=t[1],s=t[2],l=t[4],o=t[5],a=t[6],u=t[8],h=t[9],m=t[10],c=m*o-a*h,d=-m*l+a*u,f=h*l-o*u,g=i*c+n*d+s*f;return!g||r>0&&(!Number.isFinite(g)||Math.abs(g)<=r)||(g=1/g,e[0]=c*g,e[1]=d*g,e[2]=f*g,e[3]=(-m*n+s*h)*g,e[4]=(m*i-s*u)*g,e[5]=(-h*i+n*u)*g,e[6]=(a*n-s*o)*g,e[7]=(-a*i+s*l)*g,e[8]=(o*i-n*l)*g),e}function Li(e,t){let r=t[0],i=t[1],n=t[2],s=t[3],l=t[4],o=t[5],a=t[6],u=t[7],h=t[8],m=t[9],c=t[10],d=t[11],f=t[12],g=t[13],x=t[14],b=t[15],v=r*o-i*l,p=r*a-n*l,y=r*u-s*l,M=i*a-n*o,P=i*u-s*o,F=n*u-s*a,G=h*g-m*f,T=h*x-c*f,E=h*b-d*f,S=m*x-c*g,B=m*b-d*g,k=c*b-d*x,w=v*k-p*B+y*S+M*E-P*T+F*G;return w?(w=1/w,e[0]=(o*k-a*B+u*S)*w,e[1]=(n*B-i*k-s*S)*w,e[2]=(g*F-x*P+b*M)*w,e[3]=(c*P-m*F-d*M)*w,e[4]=(a*E-l*k-u*T)*w,e[5]=(r*k-n*E+s*T)*w,e[6]=(x*y-f*F-b*p)*w,e[7]=(h*F-c*y+d*p)*w,e[8]=(l*B-o*E+u*G)*w,e[9]=(i*E-r*B-s*G)*w,e[10]=(f*P-g*y+b*v)*w,e[11]=(m*y-h*P-d*v)*w,e[12]=(o*T-l*S-a*G)*w,e[13]=(r*S-i*T+n*G)*w,e[14]=(g*p-f*M-x*v)*w,e[15]=(h*M-m*p+c*v)*w,e):null}function $s(e,t,r,i,n){let s=n[0]*t+n[4]*r+n[8]*i+n[12],l=n[1]*t+n[5]*r+n[9]*i+n[13],o=n[2]*t+n[6]*r+n[10]*i+n[14],a=n[3]*t+n[7]*r+n[11]*i+n[15],u=a!==0?1/a:1;e[0]=s*u,e[1]=l*u,e[2]=o*u}function Oo(e,t,r,i,n,s,l,o,a,u,h,m,c,d,f,g,x=0){let b=u-l,v=h-o,p=m-a,y=c-l,M=d-o,P=f-a,F=n*P-s*M,G=s*y-i*P,T=i*M-n*y,E=b*F+v*G+p*T;if(E>-1e-7&&E<1e-7)return!1;let S=1/E,B=e-l,k=t-o,w=r-a,ie=S*(B*F+k*G+w*T);if(ie<-x||ie>1+x)return!1;let oe=k*p-w*v,I=w*b-B*p,H=B*v-k*b,C=S*(i*oe+n*I+s*H);if(C<-x||ie+C>1+x)return!1;let z=S*(y*oe+M*I+P*H);if(z>1e-4&&z<g.distance){g.distance=z,g.point=[e+i*z,t+n*z,r+s*z];let ue=v*P-p*M,he=p*y-b*P,O=b*M-v*y,$=Math.hypot(ue,he,O)||1;return g.normal=[ue/$,he/$,O/$],!0}return!1}function Cr(e,t){let r=Array.isArray(e?.nodes)?e.nodes.length:0,i=[];for(let h=0;h<r;h++)i.push(Pe());if(r===0)return i;let n=new Set;for(let h of e.nodes)if(Array.isArray(h.children))for(let m of h.children)n.add(m);let s=new Set,l=128,o=(h,m,c=0)=>{if(c>l||h<0||h>=r||s.has(h))return;s.add(h);let d=e.nodes[h];if(!d)return;let f=Pe();if(t&&t[h])f.set(t[h]);else if(d.matrix&&d.matrix.length===16)f.set(d.matrix);else{let x=d.translation||[0,0,0],b=d.rotation||[0,0,0,1],v=d.scale||[1,1,1];lr(f,b,x,v)}let g=i[h];if(m?ke(g,m,f):g.set(f),Array.isArray(d.children))for(let x of d.children)typeof x=="number"&&o(x,g,c+1)},a=[],u=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(u&&Array.isArray(u.nodes))a.push(...u.nodes);else for(let h=0;h<r;h++)n.has(h)||a.push(h);for(let h of a)o(h,null);for(let h=0;h<r;h++)!n.has(h)&&!a.includes(h)&&o(h,null);return i}function _i(e,t){function r(a,u,h,m){let c=typeof a=="number"?a:Number(a);return Number.isFinite(c)?Math.max(u,Math.min(h,c)):m}function i(a,u){let h=a[0]*u[0]+a[1]*u[1]+a[2]*u[2]+1;if(h<1e-6){if(Math.abs(a[0])>Math.abs(a[2])){let x=Math.hypot(a[1],a[0])||1;return[-a[1]/x,a[0]/x,0,0]}let g=Math.hypot(a[2],a[1])||1;return[0,-a[2]/g,a[1]/g,0]}let m=a[1]*u[2]-a[2]*u[1],c=a[2]*u[0]-a[0]*u[2],d=a[0]*u[1]-a[1]*u[0],f=Math.hypot(m,c,d,h)||1;return[m/f,c/f,d/f,h/f]}function n(a,u,h,m,c){let d=u[0]-a[0],f=u[1]-a[1],g=u[2]-a[2],x=Math.hypot(d,f,g),b=h[0]-u[0],v=h[1]-u[1],p=h[2]-u[2],y=Math.hypot(b,v,p);if(x<1e-6||y<1e-6)return{rootPos:[a[0],a[1],a[2]],midPos:[u[0],u[1],u[2]],effectorPos:[h[0],h[1],h[2]],rootRotation:[0,0,0,1],midRotation:[0,0,0,1]};let M=[d/x,f/x,g/x],P=[b/y,v/y,p/y],F=m[0]-a[0],G=m[1]-a[1],T=m[2]-a[2],E=Math.hypot(F,G,T),S=E>1e-6?[F/E,G/E,T/E]:M,B=Math.abs(x-y)+1e-5,k=Math.max(B,x+y-1e-5),w=Math.max(B,Math.min(k,E>1e-6?E:B)),ie=r((x*x+w*w-y*y)/(2*x*w),-1,1,1),oe=Math.sqrt(Math.max(0,1-ie*ie)),I=c?c[0]-a[0]:d,H=c?c[1]-a[1]:f,C=c?c[2]-a[2]:g,z=I*S[0]+H*S[1]+C*S[2],ue=I-S[0]*z,he=H-S[1]*z,O=C-S[2]*z,$=Math.hypot(ue,he,O);if($<=1e-6){let ee=Math.abs(S[1])<.99?0:1,R=Math.abs(S[1])<.99?1:0,A=0;ue=S[1]*A-S[2]*R,he=S[2]*ee-S[0]*A,O=S[0]*R-S[1]*ee,$=Math.hypot(ue,he,O)||1}let _=[ue/$,he/$,O/$],W=[a[0]+S[0]*(x*ie)+_[0]*(x*oe),a[1]+S[1]*(x*ie)+_[1]*(x*oe),a[2]+S[2]*(x*ie)+_[2]*(x*oe)],j=[a[0]+S[0]*w,a[1]+S[1]*w,a[2]+S[2]*w],X=j[0]-W[0],D=j[1]-W[1],Y=j[2]-W[2],te=Math.hypot(X,D,Y),se=te>1e-6?[X/te,D/te,Y/te]:S,le=[W[0]+se[0]*y,W[1]+se[1]*y,W[2]+se[2]*y],V=[(W[0]-a[0])/x,(W[1]-a[1])/x,(W[2]-a[2])/x];return{rootPos:[a[0],a[1],a[2]],midPos:W,effectorPos:le,rootRotation:i(M,V),midRotation:i(P,se)}}function s(a,u,h=8,m=.001){let c=a.length;if(c<2)return{positions:a.map(E=>[E[0],E[1],E[2]]),rotations:[],iterations:0};let d=a.map(E=>[E[0],E[1],E[2]]),f=[],g=[],x=0;for(let E=0;E<c-1;E++){let S=d[E+1][0]-d[E][0],B=d[E+1][1]-d[E][1],k=d[E+1][2]-d[E][2],w=Math.hypot(S,B,k);f.push(w),x+=w,g.push(w>1e-6?[S/w,B/w,k/w]:[0,1,0])}let b=[d[0][0],d[0][1],d[0][2]],v=Math.round(r(h,1,32,8)),p=r(m,1e-5,.1,.001),y=u[0]-b[0],M=u[1]-b[1],P=u[2]-b[2],F=Math.hypot(y,M,P),G=0;if(F>=x&&x>1e-6){let E=F>1e-6?[y/F,M/F,P/F]:g[0];d[0]=[b[0],b[1],b[2]];for(let S=0;S<c-1;S++){let B=f[S];d[S+1]=[d[S][0]+E[0]*B,d[S][1]+E[1]*B,d[S][2]+E[2]*B]}G=1}else for(let E=1;E<=v;E++){let S=d[c-1];if(Math.hypot(S[0]-u[0],S[1]-u[1],S[2]-u[2])<=p)break;G=E;let B=(k,w,ie,oe,I)=>{let H=w[0]-k[0],C=w[1]-k[1],z=w[2]-k[2],ue=Math.hypot(H,C,z);if(ue>1e-6){let he=ie/ue;return[k[0]+H*he,k[1]+C*he,k[2]+z*he]}return[k[0]+oe[0]*ie*I,k[1]+oe[1]*ie*I,k[2]+oe[2]*ie*I]};d[c-1]=[u[0],u[1],u[2]];for(let k=c-2;k>=0;k--)d[k]=B(d[k+1],d[k],f[k],g[k],-1);d[0]=[b[0],b[1],b[2]];for(let k=0;k<c-1;k++)d[k+1]=B(d[k],d[k+1],f[k],g[k],1)}let T=[];for(let E=0;E<c-1;E++){let S=d[E+1][0]-d[E][0],B=d[E+1][1]-d[E][1],k=d[E+1][2]-d[E][2],w=Math.hypot(S,B,k),ie=w>1e-6?[S/w,B/w,k/w]:g[E];T.push(i(g[E],ie))}return{positions:d,rotations:T,iterations:G}}function l(a){if(!a||typeof a!="object"||Array.isArray(a))return null;let u=a;if(u.enabled===!1)return null;let h=p=>{if(typeof p!="string")return;let y=p.trim().slice(0,64);return/^[A-Za-z0-9_.:-]+$/.test(y)?y:void 0},m=p=>Array.isArray(p)&&p.length===3&&p.every(y=>typeof y=="number"&&Number.isFinite(y))?[r(p[0],-1e3,1e3,0),r(p[1],-1e3,1e3,0),r(p[2],-1e3,1e3,0)]:void 0,c=h(u.root),d=h(u.effector);if(!c||!d)return null;let f=h(u.mid),g=m(u.target)??h(u.target);if(!g)return null;let x=u.pole??u.poleTarget,b=m(x)??h(x),v=u.solver==="fabrik"?"fabrik":u.solver==="two-bone"||f?"two-bone":"fabrik";return{root:c,...f?{mid:f}:{},effector:d,target:g,...b?{pole:b}:{},solver:v,iterations:Math.round(r(u.iterations,1,32,8)),tolerance:r(u.tolerance,1e-5,.1,.001),weight:r(u.weight,0,1,1)}}let o=Object.freeze({solveTwoBone:n,solveFABRIK:s,parseIKTrait:l});return t&&typeof t=="object"&&(t.authorNamespace=t.authorNamespace||{},t.authorNamespace.IKSolver=o),{clampNum:r,parseIKTrait:l,quatFromUnitVectors:i,solveTwoBoneIK:n,solveFABRIK:s,IKSolver:o}}var Wt=_i(),Hs=Wt.clampNum,zo=Wt.parseIKTrait,Nr=Wt.quatFromUnitVectors,Ii=Wt.solveTwoBoneIK,Di=Wt.solveFABRIK,Gs=Wt.IKSolver;function ki(e){let t=e?.transform??e?.modelMatrix;return t&&t.length>=16?[t[12]||0,t[13]||0,t[14]||0]:[0,0,0]}function $o(e,t){let r=e?.transform??e?.modelMatrix;!r||r.length<16||(r[12]=t[0],r[13]=t[1],r[14]=t[2])}function Ho(e,t,r,i,n){let s=Hs(n,0,1,1),l=t[0]+(r[0]-t[0])*s,o=t[1]+(r[1]-t[1])*s,a=t[2]+(r[2]-t[2])*s,u=l-e[0],h=o-e[1],m=a-e[2],c=Math.hypot(u,h,m);if(c>1e-6&&i>1e-6){let b=i/c;return[e[0]+u*b,e[1]+h*b,e[2]+m*b]}let d=r[0]-e[0],f=r[1]-e[1],g=r[2]-e[2],x=Math.hypot(d,f,g);if(x>1e-6&&i>1e-6){let b=i/x;return[e[0]+d*b,e[1]+f*b,e[2]+g*b]}return[l,o,a]}function Go(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return Li(i,r instanceof Float32Array?r:Float32Array.from(r))?[i[0]*t[0]+i[4]*t[1]+i[8]*t[2]+i[12],i[1]*t[0]+i[5]*t[1]+i[9]*t[2]+i[13],i[2]*t[0]+i[6]*t[1]+i[10]*t[2]+i[14]]:t}function Fi(e,t){e.__ikWarned||(e.__ikWarned=new Set);let r=e.__ikWarned;r.has(t)||(r.add(t),console.warn(`[three-live] ik: joint '${t}' on '${e?.name??""}' not found among scene nodes or meshes.`))}function Vi(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return ki(i);let n;if(e==="head"?n=r?.headPose?.position??r?.headPose??r?.cameraPosition:e==="hand-left"?n=r?.handPoses?.left?.position??r?.handPoses?.left??r?.hands?.left?.position??r?.hands?.left:e==="hand-right"&&(n=r?.handPoses?.right?.position??r?.handPoses?.right??r?.hands?.right?.position??r?.hands?.right),(Array.isArray(n)||ArrayBuffer.isView(n))&&n.length>=3){let s=n;return Go(r,[s[0],s[1],s[2]])}return null}function Ui(e,t){return[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]-e[0]*t[2]+e[1]*t[3]+e[2]*t[0],e[3]*t[2]+e[0]*t[1]-e[1]*t[0]+e[2]*t[3],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]]}function Wo(e){return[-e[0],-e[1],-e[2],e[3]]}function Bi(e){let t=Math.hypot(e[0],e[1],e[2],e[3]);return t>1e-12?[e[0]/t,e[1]/t,e[2]/t,e[3]/t]:[0,0,0,1]}function jo(e,t){if(t>=1)return e;if(t<=0)return[0,0,0,1];let[r,i,n,s]=e;s<0&&(r=-r,i=-i,n=-n,s=-s);let l=Math.acos(Math.min(1,s)),o=Math.sin(l);if(o<1e-9)return[0,0,0,1];let a=Math.sin(l*t)/o;return Bi([r*a,i*a,n*a,Math.cos(l*t)])}function Xo(e){let t=Math.hypot(e[0],e[1],e[2])||1,r=Math.hypot(e[4],e[5],e[6])||1,i=Math.hypot(e[8],e[9],e[10])||1,n=e[0]/t,s=e[1]/t,l=e[2]/t,o=e[4]/r,a=e[5]/r,u=e[6]/r,h=e[8]/i,m=e[9]/i,c=e[10]/i,d=n+a+c,f;if(d>0){let g=Math.sqrt(d+1)*2;f=[(u-m)/g,(h-l)/g,(s-o)/g,.25*g]}else if(n>a&&n>c){let g=Math.sqrt(1+n-a-c)*2;f=[.25*g,(o+s)/g,(h+l)/g,(u-m)/g]}else if(a>c){let g=Math.sqrt(1+a-n-c)*2;f=[(o+s)/g,.25*g,(m+u)/g,(h-l)/g]}else{let g=Math.sqrt(1+c-n-a)*2;f=[(h+l)/g,(m+u)/g,.25*g,(s-o)/g]}return Bi(f)}function qo(e,t,r){let[i,n,s,l]=r,o=1-2*(n*n+s*s),a=2*(i*n-s*l),u=2*(i*s+n*l),h=2*(i*n+s*l),m=1-2*(i*i+s*s),c=2*(n*s-i*l),d=2*(i*s-n*l),f=2*(n*s+i*l),g=1-2*(i*i+n*n);for(let x=0;x<3;x++){let b=t[x*4],v=t[x*4+1],p=t[x*4+2];e[x*4]=o*b+a*v+u*p,e[x*4+1]=h*b+m*v+c*p,e[x*4+2]=d*b+f*v+g*p}}function Lr(e,t){let r=t[0]-e[0],i=t[1]-e[1],n=t[2]-e[2],s=Math.hypot(r,i,n);return s>1e-9?[r/s,i/s,n/s]:null}function Ws(e){e?.normalMatrix&&e?.transform&&Ye(e.normalMatrix,e.transform)}var js=new WeakMap;function Ko(e){let t=js.get(e);return t||(t=new Int32Array(e.nodes.length).fill(-1),e.nodes.forEach((r,i)=>{for(let n of Array.isArray(r?.children)?r.children:[])typeof n=="number"&&n>=0&&n<t.length&&(t[n]=i)}),js.set(e,t)),t}function Yo(e,t,r){let i=e?.gltf,n=i?.nodes;if(!Array.isArray(n)||n.length===0)return!1;let s=new Map;n.forEach((T,E)=>{typeof T?.name=="string"&&T.name&&!s.has(T.name)&&s.set(T.name,E)});let l=(t.mid?[t.root,t.mid,t.effector]:[t.root,t.effector]).map(T=>s.get(T));if(l.some(T=>T===void 0))return!1;let o=l,a=Ko(i);for(let T=1;T<o.length;T++){let E=a[o[T]],S=0;for(;E>=0&&E!==o[T-1]&&S++<256;)E=a[E];if(E!==o[T-1])return!1}let u=o[0],h=e.initialNodeTransforms,m=new Map,c=[],d=[u];for(;d.length&&c.length<4096;){let T=d.pop();if(m.has(T))continue;let E=h?.[T],S=n[T];m.set(T,{t:E?[E.t[0],E.t[1],E.t[2]]:S?.translation?[...S.translation]:[0,0,0],r:E?[E.r[0],E.r[1],E.r[2],E.r[3]]:S?.rotation?[...S.rotation]:[0,0,0,1],s:E?[E.s[0],E.s[1],E.s[2]]:S?.scale?[...S.scale]:[1,1,1]}),c.push(T);for(let B of Array.isArray(S?.children)?S.children:[])typeof B=="number"&&d.push(B)}let f=a[u],g=f>=0&&e.worldMatrices?.[f]?.length===16?Float32Array.from(e.worldMatrices[f]):Pe(),x=new Map,b=()=>{let T=(E,S)=>{let B=m.get(E);if(!B)return;let k=Pe();lr(k,B.r,B.t,B.s);let w=Pe();ke(w,S,k),x.set(E,w);for(let ie of Array.isArray(n[E]?.children)?n[E].children:[])typeof ie=="number"&&T(ie,w)};T(u,g)},v=T=>{let E=x.get(T);return[E[12],E[13],E[14]]};b();let p=o.map(v),y=T=>{if(typeof T=="string"&&!r.has(T)){let E=s.get(T),S=E!==void 0?x.get(E)??e.worldMatrices?.[E]:void 0;if(S&&S.length===16)return[S[12],S[13],S[14]]}return Vi(T,r,e)},M=y(t.target);if(!M)return!0;let P=t.pole?y(t.pole)??void 0:void 0,F=Xs(p,t,M,P),G=Hs(t.weight,0,1,1);for(let T=0;T<o.length-1;T++){let E=Lr(v(o[T]),v(o[T+1])),S=Lr(F[T],F[T+1]);if(!E||!S)continue;let B=jo(Nr(E,S),G),k=o[T],w=a[k],ie=w===f||w<0?g:x.get(w)??g,oe=Xo(ie),I=m.get(k);I.r=Bi(Ui(Wo(oe),Ui(B,Ui(oe,I.r)))),b()}if(Array.isArray(e.worldMatrices))for(let[T,E]of x)e.worldMatrices[T]?.set&&e.worldMatrices[T].set(E);for(let T of e.meshes??[]){let E=x.get(T?.nodeIndex);E&&T.transform?.set&&(T.transform.set(E),Ws(T))}return!0}function Xs(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let n=Ii(e[0],e[1],e[2],r,i);return[e[0],n.midPos,n.effectorPos]}return Di(e,r,t.iterations,t.tolerance).positions}function Zo(e,t,r){let i=e.__ikRestOffsets,n=e.__ikRestMats;if(!(!i||!n))for(let s=0;s<t.length-1;s++){let l=t[s]?.transform??t[s]?.modelMatrix,o=n[s],a=Lr([0,0,0],i[s]),u=Lr(r[s],r[s+1]);!l||l.length<16||!o||o.length<16||!a||!u||(qo(l,o,Nr(a,u)),Ws(t[s]))}}var Oi={name:"ik",onRegister(){let e=Ae();Ei(_i),_i(e.threeNamespace,e)},onUpdate(e){let t=e?.meshes;if(!Array.isArray(t)||t.length===0)return;let r=null;for(let i of t){let n=i?.userData?.xr?.ik??i?.extras?.xr?.ik??i?.extensions?.ANDROID_xr_scenecore?.ik;if(!n)continue;let s=zo(n);if(!s||s.weight<=0)continue;if(!r){r=new Map;for(let p of t)p&&typeof p.name=="string"&&p.name&&r.set(p.name,p)}if(Yo(e,s,r))continue;let l=r.get(s.root),o=r.get(s.effector),a=s.mid?r.get(s.mid):void 0;if(l||Fi(i,s.root),o||Fi(i,s.effector),s.mid&&!a&&Fi(i,s.mid),!l||!o)continue;let u=Vi(s.target,r,e);if(!u)continue;let h=s.pole?Vi(s.pole,r,e)??void 0:void 0,m=a?[l,a,o]:[l,o],c=m.map(p=>p.name||"").join(">");if(!i.__ikRestOffsets||i.__ikRestKey!==c){let p=m.map(ki),y=[];for(let M=0;M<p.length-1;M++)y.push([p[M+1][0]-p[M][0],p[M+1][1]-p[M][1],p[M+1][2]-p[M][2]]);i.__ikRestOffsets=y,i.__ikRestKey=c,i.__ikRestMats=m.map(M=>Array.from(M.transform??M.modelMatrix??[]))}let d=i.__ikRestOffsets,f=[ki(l)],g=[];for(let p=0;p<d.length;p++){let y=f[p],M=d[p];f.push([y[0]+M[0],y[1]+M[1],y[2]+M[2]]),g.push(Math.hypot(M[0],M[1],M[2]))}let x=Xs(f,s,u,h),b=f[0],v=[f[0]];for(let p=1;p<m.length;p++){let y=d[p-1],M=[b[0]+y[0],b[1]+y[1],b[2]+y[2]],P=[b[0]+(x[p][0]-x[p-1][0]),b[1]+(x[p][1]-x[p-1][1]),b[2]+(x[p][2]-x[p-1][2])],F=Ho(b,M,P,g[p-1],s.weight);$o(m[p],F),b=F,v.push(F)}Zo(i,m,v)}}};function ur(e,t){let r=(h,m,c,d)=>{let f=typeof h=="number"?h:Number(h);return Number.isFinite(f)?Math.max(m,Math.min(c,f)):d};function i(h,m,c=0,d=.05,f){if(!h||!h.length)return-1;let g=h[0]>0?[0,...h]:h,x=Number.isFinite(m)?Math.max(0,m):0,b=Number.isFinite(d)?Math.max(0,Math.min(.5,d)):.05;if(typeof f=="number"&&Number.isFinite(f)&&f>0){let y=c===-1?f*(1-b):f*(1+b);if(x>y)return-1}let v=0;for(let y=g.length-1;y>=1;y--)if(x>=g[y]){v=y;break}if(c<0||c>=g.length||c===v)return v;if(v>c){let y=c;for(let M=c+1;M<=v&&x>=g[M]*(1+b);M++)y=M;return y}let p=c;for(let y=c;y>v&&x<g[y]*(1-b);y--)p=y-1;return p}function n(h){if(!h)return null;let m=h===!0?{distances:[4,10],ratios:[.5,.25]}:Array.isArray(h)?{distances:h}:typeof h=="object"?h:null;if(!m||m.enabled===!1)return null;let c=r(m.hysteresis,0,.5,.05),d=[],f;if(Array.isArray(m.levels)&&m.levels.length>0){let v=m.levels.slice(0,8);for(let y=0;y<v.length;y++){let M=v[y];if(!M||typeof M!="object"||Array.isArray(M))continue;let P=M,F=r(P.distance,0,1e4,y===0?0:y*4),G=typeof P.hysteresis=="number"?r(P.hysteresis,0,.5,c):void 0,T=typeof P.ratio=="number"?r(P.ratio,.05,1,.5):void 0,E=typeof P.childIndex=="number"&&Number.isFinite(P.childIndex)?Math.max(0,Math.round(P.childIndex)):void 0,S=typeof P.node=="string"&&/^[A-Za-z0-9_.:-]+$/.test(P.node.trim())?P.node.trim().slice(0,64):void 0;d.push({distance:F,...G!==void 0?{hysteresis:G}:{},...T!==void 0?{ratio:T}:{},...E!==void 0?{childIndex:E}:{},...S?{node:S}:{}})}d.sort((y,M)=>y.distance-M.distance),d.length>0&&d[0].distance>0&&d.unshift({distance:0,childIndex:0});let p=0;d=d.slice(0,8).map((y,M)=>{let P=M===0?0:Math.max(p,y.distance);return p=P,{...y,distance:P,childIndex:y.childIndex??M}})}if(Array.isArray(m.ratios)&&m.ratios.length>0){let v=[];for(let p of m.ratios.slice(0,7))typeof p=="number"&&v.push(r(p,.05,1,.5));v.length>0&&(f=v)}if(d.length===0){let v=Array.isArray(m.distances)?m.distances:[],p=[];for(let M of v.slice(0,8))typeof M=="number"&&p.push(r(M,0,1e4,4));if(p.length===0&&f&&f.length>0)for(let M=0;M<f.length;M++)p.push((M+1)*4);if(p.length===0&&m.cullDistance===void 0)return null;p.length===0||p[0]>0?p.unshift(0):f&&f.length===p.length&&f[0]===1&&(f=f.slice(1));let y=0;for(let M=0;M<Math.min(8,p.length);M++){let P=M===0?0:Math.max(y,p[M]);y=P;let F=M>0&&f?f[M-1]:void 0;d.push({distance:P,childIndex:M,...F!==void 0?{ratio:F}:{}})}}else if(!f){let v=[];for(let p=1;p<d.length;p++)typeof d[p].ratio=="number"&&v.push(d[p].ratio);v.length>0&&(f=v)}let g=d.map(v=>v.distance),x=g[g.length-1]??0,b=m.cullDistance!==void 0&&m.cullDistance!==null&&m.cullDistance!==!1?r(m.cullDistance,Math.max(1,x),1e4,100):void 0;return{levels:d,distances:g,...f?{ratios:f}:{},hysteresis:c,...b!==void 0?{cullDistance:b}:{}}}function s(h,m){let c=h?.attributes?.position;if(!c||!c.array||c.count<3)return h;let d=r(m,.05,1,.5),f=c.array,g=c.count,x=h.attributes?.normal?.array,b=h.attributes?.uv?.array,v=h.index?.array,p=Math.floor((v?v.length:g)/3);if(p<1)return h;let y=Math.max(1,Math.min(p,Math.round(p*d))),M=1/0,P=1/0,F=1/0,G=-1/0,T=-1/0,E=-1/0;for(let $=0;$<g;$++){let _=f[$*3],W=f[$*3+1],j=f[$*3+2];_<M&&(M=_),W<P&&(P=W),j<F&&(F=j),_>G&&(G=_),W>T&&(T=W),j>E&&(E=j)}let S=Math.max(1e-5,G-M),B=Math.max(1e-5,T-P),k=Math.max(1e-5,E-F),w=Math.max(S,B,k),ie=$=>{let _=Math.max(1,Math.round(S/w*$)),W=Math.max(1,Math.round(B/w*$)),j=Math.max(1,Math.round(k/w*$)),X=new Map,D=new Int32Array(g),Y=[],te=[],se=[],le=[];for(let N=0;N<g;N++){let U=f[N*3],Q=f[N*3+1],q=f[N*3+2],Z=Math.min(_-1,Math.max(0,Math.floor((U-M)/S*_))),J=Math.min(W-1,Math.max(0,Math.floor((Q-P)/B*W))),K=Math.min(j-1,Math.max(0,Math.floor((q-F)/k*j))),ae=Z+J*_+K*_*W,ne=X.get(ae);ne===void 0?(ne=le.length,X.set(ae,ne),Y.push(U,Q,q),x&&te.push(x[N*3],x[N*3+1],x[N*3+2]),b&&se.push(b[N*2],b[N*2+1]),le.push(1)):(Y[ne*3]+=U,Y[ne*3+1]+=Q,Y[ne*3+2]+=q,x&&(te[ne*3]+=x[N*3],te[ne*3+1]+=x[N*3+1],te[ne*3+2]+=x[N*3+2]),le[ne]++),D[N]=ne}let V=[],ee=new Set;for(let N=0;N<p;N++){let U=v?v[N*3]:N*3,Q=v?v[N*3+1]:N*3+1,q=v?v[N*3+2]:N*3+2,Z=D[U],J=D[Q],K=D[q];if(Z===J||J===K||K===Z)continue;let ae=Math.min(Z,J,K),ne=Math.max(Z,J,K),re=Z+J+K-ae-ne,ce=`${ae}_${re}_${ne}`;ee.has(ce)||(ee.add(ce),V.push(Z,J,K))}let R=le.length,A=new Float32Array(R*3),L=x?new Float32Array(R*3):null;for(let N=0;N<R;N++){let U=1/le[N];if(A[N*3]=Y[N*3]*U,A[N*3+1]=Y[N*3+1]*U,A[N*3+2]=Y[N*3+2]*U,L){let Q=te[N*3],q=te[N*3+1],Z=te[N*3+2],J=Math.hypot(Q,q,Z)||1;L[N*3]=Q/J,L[N*3+1]=q/J,L[N*3+2]=Z/J}}return{pos:A,norm:L,uv:b?new Float32Array(se):null,tris:V,triCount:V.length/3,vertCount:R}},oe=Math.max(2,Math.round(Math.sqrt(y/4))),I=ie(oe);if(I.triCount>y*1.25&&oe>2){let $=Math.max(2,Math.round(oe*Math.sqrt(y/I.triCount)));if($!==oe){let _=ie($);_.triCount>=Math.min(4,y)&&(I=_)}}else if(I.triCount<Math.min(4,y)){let $=ie(Math.max(oe*2,8));$.triCount>I.triCount&&(I=$)}let H=I.tris;if(d<1&&I.triCount>y){let $=[],_=I.triCount/y;for(let W=0;W<y;W++){let j=Math.min(I.triCount-1,Math.floor(W*_));$.push(I.tris[j*3],I.tris[j*3+1],I.tris[j*3+2])}H=$}if(H.length<3){H=[];for(let $=0;$<y*3;$++)H.push(v?v[$]:$);I={pos:f.slice(),norm:x?x.slice():null,uv:b?b.slice():null,tris:H,triCount:y,vertCount:g}}let C=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),z=C?.BufferGeometry??h.constructor,ue=C?.BufferAttribute??c.constructor,he=new z;he.setAttribute("position",new ue(I.pos,3)),I.norm&&he.setAttribute("normal",new ue(I.norm,3)),I.uv&&he.setAttribute("uv",new ue(I.uv,2));let O=I.vertCount>65535?new Uint32Array(H):new Uint16Array(H);return typeof he.setIndex=="function"?he.setIndex(new ue(O,1)):he.index=new ue(O,1),he}let l=e?.Object3D??t?.threeNamespace?.Object3D??class{constructor(){this.name="",this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0},this.quaternion={x:0,y:0,z:0,w:1},this.scale={x:1,y:1,z:1},this.visible=!0,this.parent=null,this.children=[],this.userData={}}add(...h){for(let m of h)m&&(m.parent=this,this.children.push(m));return this}};class o extends l{constructor(){super(),this.isLOD=!0,this.type="LOD",this.autoUpdate=!0,this.levels=[],this._currentLevel=0}addLevel(m,c=0,d=.05){if(!m)return this;let f=Math.max(0,Number.isFinite(Number(c))?Number(c):0),g=r(d,0,.5,.05),x=this.levels.length;for(let p=0;p<this.levels.length;p++)if(f<this.levels[p].distance){x=p;break}this.levels.splice(x,0,{object:m,distance:f,hysteresis:g}),this.add(m);let b=this.levels.map(p=>p.object),v=this.children.filter(p=>!b.includes(p));this.children=[...b,...v];for(let p=0;p<this.levels.length;p++)this.levels[p].object.visible=p===this._currentLevel;return this.syncUserDataTrait(),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(m){if(!this.levels.length)return null;let c=i(this.levels.map(d=>d.distance),m,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);return c>=0&&c<this.levels.length?this.levels[c].object:null}update(m){if(this.levels.length===0||!m)return;let c=m.position??{x:0,y:0,z:0},d=this.position??{x:0,y:0,z:0},f=Math.hypot((Number(c.x)||0)-(Number(d.x)||0),(Number(c.y)||0)-(Number(d.y)||0),(Number(c.z)||0)-(Number(d.z)||0)),g=i(this.levels.map(x=>x.distance),f,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);this._currentLevel=g;for(let x=0;x<this.levels.length;x++)this.levels[x].object.visible=x===g}syncUserDataTrait(){this.userData=this.userData||{},this.userData.xr=this.userData.xr||{};let m=this.userData.xr.lod?.cullDistance;this.userData.xr.lod={levels:this.levels.map((c,d)=>({distance:c.distance,hysteresis:c.hysteresis,childIndex:d,...c.object?.name?{node:c.object.name}:{}})),distances:this.levels.map(c=>c.distance),hysteresis:this.levels[0]?.hysteresis??.05,...m!==void 0?{cullDistance:m}:{}}}}function a(h){if(!h||h._lodMaterialized||!h.userData?.xr?.lod||h.isLOD||Array.isArray(h.children)&&h.children.length>0)return;let m=h.geometry?.attributes?.position;if(!m||!m.array||m.count<3)return;let c=n(h.userData.xr.lod);if(!c||c.levels.length<2)return;h._lodMaterialized=!0;let d=h.geometry;h._lodOriginalGeometry=d;let f=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),g=f?.Mesh??h.constructor,x=f?.BufferGeometry??d.constructor,b=typeof h.name=="string"&&h.name.trim()?h.name.trim():"Mesh",v=new g(d,h.material);v.name=`${b}_LOD0`,v.visible=!0,v.castShadow=!!h.castShadow,v.receiveShadow=!!h.receiveShadow,h.add(v);for(let p=1;p<c.levels.length;p++){let y=c.levels[p].ratio??c.ratios?.[p-1]??Math.max(.05,Math.pow(.5,p)),M=s(d,y),P=new g(M,h.material);P.name=`${b}_LOD${p}`,P.visible=!1,P.castShadow=!!h.castShadow,P.receiveShadow=!!h.receiveShadow,h.add(P)}h.geometry=new x,h.userData.xr.lod={...c,levels:c.levels.map((p,y)=>({...p,childIndex:y,node:`${b}_LOD${y}`}))}}let u={LOD:o,decimateGeometry:s,selectLodLevelIndex:i,parseLod:n,materializeLodGeometry:a};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,{LOD:o,decimateGeometry:s}),t._lodMaterialize=a,t.materializeDeclarativeGeometry=h=>{t._cadMaterialize?.(h),t._lodMaterialize?.(h)}),u}var hr=ur(),qs=hr.decimateGeometry,_r=hr.selectLodLevelIndex,Ir=hr.parseLod,Au=hr.materializeLodGeometry,Ks=hr.LOD,cr=new WeakMap;function Ys(e){return e&&typeof e=="object"?cr.get(e):void 0}var zi=class{constructor(e,t){this.groups=[],this.viewer=e,this.gltf=t,this.rebuild()}rebuild(){this.groups.length=0;let e=this.gltf?.nodes;if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let i of this.viewer?.meshes??[])if(typeof i?.nodeIndex=="number"&&i.nodeIndex>=0){let n=t.get(i.nodeIndex);n||(n=[],t.set(i.nodeIndex,n)),n.push(i)}let r=i=>{let n=[],s=new Set,l=[i];for(;l.length>0;){let o=l.pop();if(s.has(o)||o<0||o>=e.length)continue;s.add(o);let a=t.get(o);a&&n.push(...a);let u=e[o]?.children;if(Array.isArray(u))for(let h=u.length-1;h>=0;h--)typeof u[h]=="number"&&l.push(u[h])}return n};for(let i=0;i<e.length;i++){let n=e[i];if(!n||typeof n!="object")continue;let s=n.extras?.xr?.lod??n.extensions?.ANDROID_xr_scenecore?.lod??n.extensions?.MOZ_hubs_components?.lod,l=Array.isArray(n.extensions?.MSFT_lod?.ids)?n.extensions.MSFT_lod.ids.filter(d=>typeof d=="number"&&Number.isInteger(d)&&d>=0&&d<e.length):[],o=Ir(s);if(!o&&l.length>0&&(o=Ir({distances:l.map((d,f)=>f*4)})),!o)continue;let a=l.length>0?l:Array.isArray(n.children)?n.children.filter(d=>typeof d=="number"&&Number.isInteger(d)&&d>=0&&d<e.length):[],u=[],h=[];if(a.length>0){let d=Math.min(a.length,o.levels.length);for(let f=0;f<d;f++){let g=a[f];u.push(g),h.push(r(g))}}else{let d=t.get(i)??[];if(d.length===0)continue;u.push(i),h.push(d)}let m=o.distances.slice(0,h.length);m.length===0&&m.push(0);let c={nodeIndex:i,name:typeof n.name=="string"?n.name:`LOD_${i}`,distances:m,hysteresis:o.hysteresis,...o.cullDistance!==void 0?{cullDistance:o.cullDistance}:{},childNodeIndices:u,levelMeshes:h,activeLevelIndex:0,lastDistance:0};this.applyGroupVisibility(c,0),this.groups.push(c)}}getGroups(){return this.groups}getActiveLevel(e){let t=this.findGroup(e);return t?t.activeLevelIndex:null}forceLodLevel(e,t){let r=this.findGroup(e);if(!r)return;if(t==null){r.forcedLevelIndex=null;let n=_r(r.distances,r.lastDistance,r.activeLevelIndex,r.hysteresis,r.cullDistance);r.activeLevelIndex=n,this.applyGroupVisibility(r,n);return}let i=t<0?-1:Math.min(Math.max(0,Math.trunc(t)),r.levelMeshes.length-1);r.forcedLevelIndex=i,r.activeLevelIndex=i,this.applyGroupVisibility(r,i)}findGroup(e){return typeof e=="number"?this.groups.find(t=>t.nodeIndex===e)??this.groups[e]:this.groups.find(t=>t.name===e)}update(e){if(this.groups.length===0)return;let t=this.viewer?.worldMatrices,r=this.viewer?.modelRootMatrix;for(let i of this.groups){let n=Array.isArray(t)&&i.nodeIndex<t.length?t[i.nodeIndex]:null,s=n&&n[12]||0,l=n&&n[13]||0,o=n&&n[14]||0,a=r?r[0]*s+r[4]*l+r[8]*o+r[12]:s,u=r?r[1]*s+r[5]*l+r[9]*o+r[13]:l,h=r?r[2]*s+r[6]*l+r[10]*o+r[14]:o,m=Math.hypot((e[0]||0)-a,(e[1]||0)-u,(e[2]||0)-h);if(i.lastDistance=m,i.forcedLevelIndex!==void 0&&i.forcedLevelIndex!==null){i.activeLevelIndex!==i.forcedLevelIndex&&(i.activeLevelIndex=i.forcedLevelIndex,this.applyGroupVisibility(i,i.forcedLevelIndex));continue}let c=_r(i.distances,m,i.activeLevelIndex,i.hysteresis,i.cullDistance);c!==i.activeLevelIndex&&(i.activeLevelIndex=c,this.applyGroupVisibility(i,c))}}applyGroupVisibility(e,t){let r=this.gltf?.nodes;for(let i=0;i<e.levelMeshes.length;i++){let n=i===t;for(let o of e.levelMeshes[i])o.visible=n;let s=e.childNodeIndices[i],l=Array.isArray(r)?r[s]:null;l&&typeof l=="object"&&(l.visible=n,l.extensions=l.extensions||{},l.extensions.KHR_node_visibility={visible:n})}}},$i={name:"lod",onRegister(){Ei(ur);let e=Ae(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);ur(t,e)},onLoadModel(e,t){!e||typeof e!="object"||cr.set(e,new zi(e,t))},onUpdate(e){let t=cr.get(e);if(!t||typeof e?.getCameraOrbit!="function")return;let r=e.getCameraOrbit(),i=typeof e.getCameraTarget=="function"?e.getCameraTarget():{x:0,y:0,z:0},n=r?.radius??3,s=r?.phi??0,l=r?.theta??0,o=Math.cos(s),a=(i.x||0)+n*o*Math.sin(l),u=(i.y||0)+n*Math.sin(s),h=(i.z||0)+n*o*Math.cos(l);t.update([a,u,h])},onBeforeDrawScene(e,t,r,i){let n=cr.get(e);n&&n.update(i)},onDestroy(e,t){t&&typeof t=="object"&&cr.delete(t)}},Qo={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function jt(e,t,r,i){if(!r||r.bufferView===void 0)return null;let n=e.bufferViews?.[r.bufferView];if(!n)return null;let s=Number(r.count??0);if(!Number.isInteger(s)||s<=0)return null;let l=r.componentType??5126,o=Qo[l];if(!o)throw new RangeError(`glTF accessor has unsupported componentType ${l}`);let a=o*i,u=n.byteStride&&n.byteStride>0?n.byteStride:a,h=(n.byteOffset||0)+(r.byteOffset||0);if(!Number.isInteger(h)||h<0||u<a||h+(s-1)*u+a>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(l===5126&&u===a&&h%4===0)return new Float32Array(t,h,s*i);let m=new DataView(t),c=r.normalized===!0,d=new Float32Array(s*i);for(let f=0;f<s;f++){let g=h+f*u;for(let x=0;x<i;x++){let b=g+x*o,v;switch(l){case 5126:v=m.getFloat32(b,!0);break;case 5120:v=m.getInt8(b),c&&(v=Math.max(v/127,-1));break;case 5121:v=m.getUint8(b),c&&(v/=255);break;case 5122:v=m.getInt16(b,!0),c&&(v=Math.max(v/32767,-1));break;case 5123:v=m.getUint16(b,!0),c&&(v/=65535);break;default:v=m.getUint32(b,!0),c&&(v/=4294967295)}d[f*i+x]=v}}return d}function Jo(e,t){let r=Number(t.offset?.[0]??0)||0,i=Number(t.offset?.[1]??0)||0,n=Number(t.scale?.[0]??1),s=Number(t.scale?.[1]??1),l=Number(t.rotation??0)||0,o=Math.cos(l),a=Math.sin(l),u=(Number.isFinite(n)?n:1)*o,h=(Number.isFinite(n)?n:1)*a,m=-(Number.isFinite(s)?s:1)*a,c=(Number.isFinite(s)?s:1)*o;for(let d=0;d+1<e.length;d+=2){let f=e[d],g=e[d+1];e[d]=u*f+h*g+r,e[d+1]=m*f+c*g+i}}function Xt(e,t,r,i=!0){let n=[],s=null;try{for(let[l,o]of[[35633,t],[35632,r]]){let a=e.createShader(l);if(!a){if(i)throw new Error("Shader allocation failed");return null}if(n.push(a),e.shaderSource(a,o),e.compileShader(a),e.getShaderParameter&&!e.getShaderParameter(a,35713)){if(i)throw new Error(`Shader compile error: ${e.getShaderInfoLog(a)}`);return null}}if(s=e.createProgram(),!s){if(i)throw new Error("Program allocation failed");return null}for(let l of n)e.attachShader(s,l);if(e.linkProgram(s),e.getProgramParameter&&!e.getProgramParameter(s,35714)){let l=i?e.getProgramInfoLog(s):null;if(e.deleteProgram?.(s),s=null,i)throw new Error(`Program link error: ${l}`);return null}return s}finally{for(let l of n)s&&e.detachShader?.(s,l),e.deleteShader?.(l)}}var Zs=["neutral","reinhard","none","aces","agx"];function qt(e){let t=String(e??"").trim().toLowerCase();return Zs.includes(t)?t:"neutral"}function el(e){return Zs.indexOf(qt(e))}function tl(e){return new TextDecoder().decode(e)}var Qs=Ae().decoders;function rl(e,t){Qs.set(e.toLowerCase(),t)}function Kt(e){return Qs.get(e.toLowerCase())}function Js(e){let t=ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e,r=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let i=r.getUint32(0,!0);if(i!==1179937895){let c=r.getUint8(0);throw c===123||c===32||c===10||c===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${i.toString(16)}`)}let n=r.getUint32(4,!0);if(n!==2)throw new Error(`Unsupported GLB version: ${n}`);let s=r.getUint32(8,!0),l=12,o=null,a=null;for(;l+8<=s&&l+8<=t.byteLength;){let c=r.getUint32(l,!0),d=r.getUint32(l+4,!0),f=l+8;if(f+c>t.byteLength)throw new Error(`Truncated GLB chunk: required ${f+c} bytes, buffer has ${t.byteLength}`);if(d===1313821514){let g=new Uint8Array(t,f,c),x=tl(g);o=JSON.parse(x,(b,v)=>b==="__proto__"||b==="constructor"||b==="prototype"?void 0:v)}else d===5130562&&(a=t.slice(f,f+c));l=f+c}if(!o)throw new Error("Missing JSON chunk in GLB");let u=o.extensionsRequired||[];if(u.includes("KHR_draco_mesh_compression")&&!Kt("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let c of["EXT_meshopt_compression","KHR_meshopt_compression"])if(u.includes(c)&&!Kt("meshopt"))throw new Error(`Model requires ${c}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(u.includes("KHR_texture_basisu")&&!Kt("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let h=a||new ArrayBuffer(0),m={gltf:o,bin:h,animations:[]};for(let c of Ve)c.onParseGLB?.(m);return m}function il(e){return typeof e=="object"&&e!==null&&"gltf"in e&&typeof e.gltf=="object"&&e.gltf!==null&&"bin"in e&&(e.bin instanceof ArrayBuffer||ArrayBuffer.isView(e.bin))}function Yt(e){if(il(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Js(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var ea=`#version 300 es
16
+ */var j0=Object.defineProperty,G0=(e,t)=>{for(var r in t)j0(e,r,{get:t[r],enumerable:!0})},Gc={};G0(Gc,{AIVoiceSession:()=>vu,AmbientLight:()=>Fa,BoxGeometry:()=>La,BufferAttribute:()=>zt,BufferGeometry:()=>$t,Camera:()=>za,CapsuleGeometry:()=>Tl,CatmullRomCurve3:()=>Jo,CircleGeometry:()=>Pl,Clock:()=>ml,Color:()=>Br,ConeGeometry:()=>Wo,CubicBezierCurve3:()=>Zo,Curve3:()=>hi,CylinderGeometry:()=>Ra,DataTexture:()=>tl,DirectionalLight:()=>ul,DodecahedronGeometry:()=>Al,EdgesGeometry:()=>El,Euler:()=>Ca,Float32BufferAttribute:()=>Oo,Group:()=>ll,HemisphereLight:()=>Za,IKSolver:()=>eh,IMAGE_SYSTEM_PROMPT:()=>eu,IcosahedronGeometry:()=>Sl,InstancedMesh:()=>Da,InteractivityVM:()=>Qu,LOD:()=>ah,LatheGeometry:()=>Ia,Light:()=>fi,LightShadow:()=>ka,Line:()=>Pi,LineBasicMaterial:()=>zn,LineCurve3:()=>Yo,LineDashedMaterial:()=>Nl,LineLoop:()=>Ll,LineSegments:()=>Rl,LodController:()=>wo,MAX_BSP_DEPTH:()=>Xc,MAX_CSG_TRIANGLES:()=>Kc,MAX_INSTANCES_PER_MESH:()=>Hi,MAX_SHADOW_LIGHTS:()=>Jn,MAX_SHAPE_POINTS:()=>Qc,MAX_TEXT_GEOMETRY_CHARS:()=>Yc,MAX_TSL_NODES:()=>Ah,MAX_TSL_UNIFORMS:()=>Th,Material:()=>_r,MathUtils:()=>Uo,Matrix3:()=>zo,Matrix4:()=>Ai,Mesh:()=>Yr,MeshBasicMaterial:()=>nl,MeshLambertMaterial:()=>al,MeshPhongMaterial:()=>sl,MeshPhysicalMaterial:()=>ol,MeshStandardMaterial:()=>Gi,Object3D:()=>zr,OctahedronGeometry:()=>_l,PART_STRIDE_BYTES:()=>Km,PART_STRIDE_WORDS:()=>Wm,PerspectiveCamera:()=>cl,PlaneGeometry:()=>Ho,PointLight:()=>Ba,Points:()=>Il,PointsMaterial:()=>Qa,PolyhedronFallbackGeometry:()=>Qh,PolyhedronGeometry:()=>pi,QuadraticBezierCurve3:()=>Qo,Quaternion:()=>Dn,RawShaderMaterial:()=>vl,RectAreaLight:()=>Dl,RingGeometry:()=>Ya,SCENE_PBR_WGSL:()=>Ws,SCENE_PICK_WGSL:()=>_c,SCENE_SHADOW_WGSL:()=>Mc,SCENE_UNIFORM_BYTES:()=>qm,SHADOW_MAP_TEXTURE_UNIT:()=>sc,Scene:()=>Va,SceneQuotaValidator:()=>Qr,ShaderMaterial:()=>Ka,SphereGeometry:()=>qo,SpotLight:()=>$l,TEXTURE_PROMPT_SUFFIX:()=>lu,THREE:()=>Ni,TSL_EXTENSION_NAME:()=>Ui,TSL_TIME_PERIOD_SEC:()=>Ph,TSL_WGSL_UNIFORM_BYTES:()=>Um,TetrahedronGeometry:()=>wl,Texture:()=>kn,TextureLoader:()=>rl,ThreeLiveElement:()=>di,ThreeView:()=>ir,TorusGeometry:()=>Ko,TorusKnotGeometry:()=>Xo,TubeGeometry:()=>el,Uint16BufferAttribute:()=>jo,Uint32BufferAttribute:()=>Go,VERTEX_STRIDE_BYTES:()=>Ym,VERTEX_STRIDE_FLOATS:()=>Xm,Vector2:()=>ar,Vector3:()=>Ze,Vector4:()=>Bo,WebGLRenderer:()=>fl,WebGPUSceneAccelerator:()=>Cc,WireframeGeometry:()=>Cl,acquireSceneWebGPUDevice:()=>Ri,activateAR:()=>Uu,aiPlugin:()=>Ts,applyMeshoptFilter:()=>tc,authorScriptRunner:()=>Bn,browserImageCodec:()=>On,buildImageMessages:()=>ru,buildImageUserText:()=>tu,buildSandboxWorkerSource:()=>Ha,buildSelectIndex:()=>ns,cadPlugin:()=>lo,clearAuthorWarnings:()=>xl,compileFromImage:()=>au,compileTslToGlsl:()=>$o,compileTslToWgsl:()=>bc,computeOutlineClipOffset:()=>Tm,computeWorldSceneBounds:()=>uc,connectVoice:()=>xs,contactShadowPlugin:()=>Ps,createAIChatProvider:()=>_u,createAIImageProvider:()=>uu,createUSDZBlob:()=>Aa,createWebSpeechRecognizer:()=>wu,crossFadeTo:()=>Eu,decimateGeometry:()=>nh,decodeMeshoptBuffer:()=>rc,decodeMeshoptGLB:()=>Fs,defineModelViewer:()=>rf,describeEditResult:()=>Ms,describeSelection:()=>ss,describeVoiceSelection:()=>Ji,detectImageMime:()=>nu,doesMeshCastShadow:()=>on,doesMeshReceiveShadow:()=>js,editScene:()=>Tu,encodeMeshoptBuffer:()=>_m,environmentMapPlugin:()=>Hu,evaluateKawaseBloom:()=>Am,evaluateToneMapping:()=>fh,exportSceneToCanvas3D:()=>Ua,exportSceneToGLB:()=>Oa,exportSceneToUSDZ:()=>hl,extractMaterialVariants:()=>pc,extractPrimitiveVariantMappings:()=>Bm,extractScript:()=>As,fitDirectionalShadowMatrix:()=>cc,fitSpotShadowMatrix:()=>Os,fmtShaderFloat:()=>Xr,formatSpatialPriors:()=>us,geminiLiveAdapter:()=>xu,generateUSDZ:()=>Sa,getARCapabilities:()=>Ns,getAllowClientScripts:()=>yl,getAuthorWarnings:()=>bl,getBestARMode:()=>Qf,getEnvironmentSH:()=>em,getInteractivityVM:()=>$s,getLodController:()=>sh,getSandboxEngineSrc:()=>Ga,getSandboxIframeSrc:()=>gl,getSelection:()=>yr,getShadowMapStats:()=>Im,getWebGPUSceneAccelerator:()=>hn,glbToUSDZ:()=>_a,hideSelectionChips:()=>Hn,hotspotPlugin:()=>Ku,ikPlugin:()=>vo,imageRepairMessage:()=>iu,indexedDbTextureCache:()=>mu,installCadExtension:()=>ha,installLodExtension:()=>Tn,installProceduralExtension:()=>ga,installTslExtension:()=>Ta,interactivityPlugin:()=>Ju,isAllowedImageUrl:()=>$r,isAllowedSandboxEngineUrl:()=>Ti,isQuickLookSupported:()=>Bu,isSceneViewerSupported:()=>zu,isWebXRSupported:()=>Vu,keyframeAnimationPlugin:()=>Iu,lodPlugin:()=>Mo,matchSelection:()=>Ol,materialsPlugin:()=>ec,meshoptDecoder:()=>Bs,meshoptPlugin:()=>ic,morphPlugin:()=>$u,noopProxy:()=>qi,normalizeImageInput:()=>hs,normalizeRendererPreference:()=>Tc,normalizeShadowMapsMode:()=>lc,packUniformVec4:()=>Pa,parseAnimations:()=>Cu,parseHexRgb:()=>nc,parseLod:()=>da,parseSafeGltfPointer:()=>Yn,parseSelectReply:()=>Zl,parseTexturePack:()=>hu,parseVoiceCommand:()=>Wl,postprocessingPlugin:()=>ac,prepareAlbedo:()=>cu,proceduralPlugin:()=>_o,quatFromUnitVectors:()=>fa,realtimeAdapter:()=>bu,registerMaterialShader:()=>cm,remapClipDepthToZeroOne:()=>aa,resetSceneWebGPUDevice:()=>n0,resolveActiveShadowLights:()=>Gs,resolveSceneRenderBackend:()=>Js,resolveSelection:()=>Yl,resolveSelectionWithModel:()=>Jl,sampleChannel:()=>en,sceneSelectEntries:()=>Vn,sceneToCanvas3D:()=>Vi,sceneToGLB:()=>En,sceneToUSDZ:()=>In,selectByVoice:()=>qn,selectCamera:()=>os,selectLodLevelIndex:()=>pa,selectMaterialVariant:()=>zm,selectMessages:()=>Ql,selectNamesByVoice:()=>Mu,sendInteractivityEvent:()=>Zu,serializeTexturePack:()=>fu,serializeTslToUsda:()=>Do,setAllowClientScripts:()=>jh,setEnvironmentSH:()=>ju,setMaterialUniform:()=>xc,setMorphTargetWeight:()=>Xf,setSandboxEngineSrc:()=>Uh,setSandboxIframeSrc:()=>Oh,setSceneWebGPUDeviceForTests:()=>i0,setSelectOnTap:()=>Ss,setSelection:()=>Ar,shadowMapsPlugin:()=>mc,showSelectionChips:()=>gu,skinningPlugin:()=>ku,solveFABRIK:()=>mo,solveTwoBoneIK:()=>fo,speakableName:()=>ws,startVoiceEdit:()=>_s,textureRequests:()=>ps,threeAuthorPlugin:()=>Wi,threeMicroPlugin:()=>tf,toGLBData:()=>zi,toTrustedWorkerScriptURL:()=>pl,tslPlugin:()=>vc,tslSafeMod:()=>Lo,tslTypeArity:()=>nr,tslTypeFromArity:()=>Ro,undoEdit:()=>Pu,validateSandboxWorkerMessage:()=>qa,validateTslGraph:()=>Oi,variantsPlugin:()=>dc,warnUnsupported:()=>Zr,webgpuScenePlugin:()=>Ec,webxrPlugin:()=>gc,writeSceneUniforms:()=>qs});function H0(e,t,r){let i=[],n=new Map,a=[],s=[],o=[],l=new Map,c=b=>{let w=n.get(b);return w===void 0&&(w=i.length,i.push({op:b}),n.set(b,w)),w},f=b=>{let w=l.get(b);return w===void 0&&(w=o.length,o.push({id:b}),l.set(b,w)),w},m=(b,w={})=>a.push({declaration:c(b),...w})-1,h=(b,w,S)=>s.push({id:b,type:w,value:S})-1,p=b=>({node:b,socket:"value"}),g=r?.interactivity??r?.gltfExtensions?.KHR_interactivity;if(g&&typeof g=="object"){let b=Array.isArray(g.graphs)?g.graphs[g.graph??0]:g;if(b&&Array.isArray(b.nodes)){let w=Array.isArray(b.declarations)?b.declarations:[];for(let S of w)S?.op&&c(S.op);Array.isArray(b.variables)&&s.push(...b.variables);for(let S of b.events||[])S?.id&&f(S.id);for(let S of b.nodes){if(!S||typeof S!="object")continue;let E=S.op||(typeof S.declaration=="number"?w[S.declaration]?.op:"");a.push(E?{...S,declaration:c(E)}:{...S})}}}let x=(b,w,S="translation")=>S==="baseColorFactor"||S==="metallicFactor"||S==="roughnessFactor"?`/materials/${Math.max(0,w)}/pbrMetallicRoughness/${S}`:S==="emissiveFactor"||S==="alphaCutoff"?`/materials/${Math.max(0,w)}/${S}`:S==="visible"?`/nodes/${b}/extensions/KHR_node_visibility/visible`:`/nodes/${b}/${S}`,v=new Map;e.forEach((b,w)=>{typeof b?.name=="string"&&!v.has(b.name)&&v.set(b.name,w)});let y=(b,w)=>typeof b.target=="string"&&v.has(b.target)?v.get(b.target):typeof b.targetNode=="number"?b.targetNode:w,A=b=>{let w=e[b];return(typeof w?.mesh=="number"?t[w.mesh]?.primitives?.[0]?.material:0)??0};for(let b=0;b<e.length;b++){let w=e[b],S=w?.extras?.interactivity;if(!S||typeof S!="object")continue;let E=(typeof w.mesh=="number"?t[w.mesh]?.primitives?.[0]?.material:0)??0,N=_=>{let P=Array.isArray(_)?_:[_],R=[];for(let F=0;F<P.length;F++){let V=P[F];if(!V||typeof V!="object")continue;let Y=V.action||"interpolate",J=typeof V.duration=="number"?V.duration:.35;if(Y==="toggleTransform"){let re=V.property==="rotation"||V.property==="scale"?V.property:"translation",Q=re==="rotation"?w.rotation||[0,0,0,1]:re==="scale"?w.scale||[1,1,1]:w.translation||[0,0,0],ee=`/nodes/${b}/${re}`,k=h(`__toggle_${b}_${F}`,"bool",!1),G=m("variable/get",{configuration:{variable:k}}),q=m("math/not",{values:{a:p(G)}}),H=m("variable/set",{configuration:{variable:k},values:{value:p(q)}}),te=m("pointer/interpolate",{configuration:{pointer:ee},values:{value:{value:Array.isArray(V.to)?V.to:Q},duration:{value:J}}}),Z=m("pointer/interpolate",{configuration:{pointer:ee},values:{value:{value:Array.isArray(V.from)?V.from:Q},duration:{value:J}}});a[H].flows={out:{node:m("flow/branch",{values:{condition:p(G)},flows:{true:{node:te},false:{node:Z}}})}},R.push(H)}else if(Y==="interpolate"){let re=V.to??V.value;if(re===void 0)continue;let Q={value:{value:re},duration:{value:J}};V.from!==void 0&&(Q.from={value:V.from}),R.push(m("pointer/interpolate",{configuration:{pointer:typeof V.pointer=="string"?V.pointer:x(y(V,b),A(y(V,b)),V.property)},values:Q}))}else if(Y==="setProperty"){if(V.value===void 0)continue;R.push(m("pointer/set",{configuration:{pointer:typeof V.pointer=="string"?V.pointer:x(y(V,b),A(y(V,b)),V.property)},values:{value:{value:V.value}}}))}else if(Y==="toggleVisibility"){let re=y(V,b),Q=h(`__vis_${re}_${F}`,"bool",!0),ee=m("variable/get",{configuration:{variable:Q}}),k=m("math/not",{values:{a:p(ee)}}),G=m("variable/set",{configuration:{variable:Q},values:{value:p(k)}});a[G].flows={out:{node:m("pointer/set",{configuration:{pointer:`/nodes/${re}/extensions/KHR_node_visibility/visible`},values:{value:p(ee)}})}},R.push(G)}else if(Y==="cycleMaterialColor"&&Array.isArray(V.colors)&&V.colors.length>0){let re=typeof V.duration=="number"?V.duration:.25,Q=`/materials/${Math.max(0,E)}/pbrMetallicRoughness/baseColorFactor`,ee=h(`__color_idx_${b}_${F}`,"int",0),k=m("variable/get",{configuration:{variable:ee}}),G=m("math/add",{values:{a:p(k),b:{value:1}}}),q=m("math/rem",{values:{a:p(G),b:{value:V.colors.length}}}),H=m("variable/set",{configuration:{variable:ee},values:{value:p(q)}}),te={};for(let Z=0;Z<V.colors.length;Z++){let ae=V.colors[Z],ie=Array.isArray(ae)&&ae.length>=3?[ae[0],ae[1],ae[2],ae[3]??1]:[1,1,1,1];te[String(Z)]={node:re>0?m("pointer/interpolate",{configuration:{pointer:Q},values:{value:{value:ie},duration:{value:re}}}):m("pointer/set",{configuration:{pointer:Q},values:{value:{value:ie}}})}}a[H].flows={out:{node:m("flow/switch",{values:{selection:p(k)},flows:te})}},R.push(H)}else if(Y==="playAnimation")R.push(m("animation/start",{configuration:{animation:V.animation??V.clip??0}}));else if(Y==="stopAnimation")R.push(m("animation/stop"));else if(Y==="sendEvent"){let re={};for(let[Q,ee]of Object.entries(V.values||{}))re[Q]={value:ee};R.push(m("event/send",{configuration:{event:f(String(V.event??V.id??"custom"))},values:re}))}}if(!R.length)return null;if(R.length===1)return R[0];let I={};return R.forEach((F,V)=>{I[String(V)]={node:F}}),m("flow/sequence",{flows:I})},C=(_,P,R)=>{let I=N(P);I!==null&&m(_,{...R?{configuration:R}:{},flows:{out:{node:I}}})};if(S.onSelect&&C("pointer/onSelect",S.onSelect,{nodeIndex:b}),S.onHoverIn&&C("pointer/onHoverIn",S.onHoverIn,{nodeIndex:b}),S.onHoverOut&&C("pointer/onHoverOut",S.onHoverOut,{nodeIndex:b}),S.onStart&&C("event/onStart",S.onStart),S.onReceive&&typeof S.onReceive=="object")for(let[_,P]of Object.entries(S.onReceive))C("event/receive",P,{event:f(_)})}return a.length?{graphs:[{declarations:i,nodes:a,variables:s,events:o}],graph:0}:null}var Hc='SecurityError: Client-modified script compilation (Use Case 1) is disabled by default to satisfy strict CSP and Trusted Types requirements. Use script-src="..." or loadScriptFromSrc(url) for server-generated scripts (Use Case 2), or explicitly opt in via ThreeLiveElement.allowClientScripts = true (or the allow-client-scripts attribute).',qc="Security Error: client-side scripts require allow-client-scripts opt-in.",ca="__THREE_LIVE_REGISTRY__";function We(){let e=typeof globalThis<"u"?globalThis:{};if(!e[ca]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,ca,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[ca]=t}}return e[ca]}var Lt=We().plugins;function Mn(e){let t=We();t.workerExtensionInstallers||(t.workerExtensionInstallers=[]),t.workerExtensionInstallers.includes(e)||t.workerExtensionInstallers.push(e)}function Rt(e){let t=We().plugins;t.some(r=>r.name===e.name)||t.push(e),e.onRegister?.()}function Wc(){return We().plugins}var Kc=8192,Xc=2048,Yc=128,Qc=4096;function ha(e,t){if(!e||!e.BufferGeometry)return null;let r=e.Vector2,i=e.Vector3,n=e.Quaternion,a=e.Matrix4,s=e.Matrix3,o=e.Color,l=e.BufferAttribute,c=e.BufferGeometry,f=e.Material,m=e.MeshStandardMaterial,h=e.Mesh,p=8192,g=2048,x=128,v=4096,y=(W,D)=>{let z=W==null?NaN:Number(W);return Number.isFinite(z)?z:D};class A{constructor(D){this.currentPoint=new r(0,0),this.segments=[],Array.isArray(D)&&D.length>0&&this.fromPoints(D)}fromPoints(D){if(!D.length)return this;this.moveTo(D[0].x,D[0].y);for(let z=1;z<D.length;z++)this.lineTo(D[z].x,D[z].y);return this}moveTo(D,z){let O=Number(D)||0,X=Number(z)||0;return this.currentPoint.set(O,X),this.segments.push({type:"move",pts:[O,X]}),this}lineTo(D,z){let O=Number(D)||0,X=Number(z)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[this.currentPoint.x,this.currentPoint.y]}),this.currentPoint.set(O,X),this.segments.push({type:"line",pts:[O,X]}),this}quadraticCurveTo(D,z,O,X){let se=this.currentPoint.x,ce=this.currentPoint.y,pe=Number(D)||0,xe=Number(z)||0,he=Number(O)||0,Ne=Number(X)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[se,ce]}),this.currentPoint.set(he,Ne),this.segments.push({type:"quad",pts:[se,ce,pe,xe,he,Ne]}),this}bezierCurveTo(D,z,O,X,se,ce){let pe=this.currentPoint.x,xe=this.currentPoint.y,he=Number(D)||0,Ne=Number(z)||0,ge=Number(O)||0,Ae=Number(X)||0,Ee=Number(se)||0,$e=Number(ce)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[pe,xe]}),this.currentPoint.set(Ee,$e),this.segments.push({type:"cubic",pts:[pe,xe,he,Ne,ge,Ae,Ee,$e]}),this}absarc(D,z,O,X,se,ce=!1){return this.absellipse(D,z,O,O,X,se,ce,0)}arc(D,z,O,X,se,ce=!1){return this.absarc(this.currentPoint.x+(Number(D)||0),this.currentPoint.y+(Number(z)||0),O,X,se,ce)}absellipse(D,z,O,X,se,ce,pe=!1,xe=0){let he=Number(D)||0,Ne=Number(z)||0,ge=Math.max(0,Number(O)||0),Ae=Math.max(0,Number(X)||0),Ee=Number(se)||0,$e=Number(ce)||0,De=pe?1:0,Be=Number(xe)||0;this.segments.push({type:"arc",pts:[he,Ne,ge,Ae,Ee,$e,De,Be]});let Fe=Math.cos(Be),Ve=Math.sin(Be),qe=ge*Math.cos($e),je=Ae*Math.sin($e);return this.currentPoint.set(he+qe*Fe-je*Ve,Ne+qe*Ve+je*Fe),this}ellipse(D,z,O,X,se,ce,pe=!1,xe=0){return this.absellipse(this.currentPoint.x+(Number(D)||0),this.currentPoint.y+(Number(z)||0),O,X,se,ce,pe,xe)}add(D){if(D&&typeof D.getPoints=="function"){this.segments.push({type:"curve",pts:[],curve:D});let z=D.getPoint?.(1);z&&this.currentPoint.set(Number(z.x)||0,Number(z.y)||0)}return this}splineThru(D){if(!Array.isArray(D)||D.length===0)return this;let z=e.SplineCurve||t?.authorNamespace?.SplineCurve;if(z)return this.add(new z([this.currentPoint.clone(),...D]));for(let O of D)O&&this.lineTo(Number(O.x)||0,Number(O.y)||0);return this}closePath(){if(this.segments.length>0){let D=this.segments[0],z=0,O=0;if(D.type==="curve"&&D.curve?.getPoint){let X=D.curve.getPoint(0);z=Number(X?.x)||0,O=Number(X?.y)||0}else if(D.type==="arc"){let X=D.pts[0],se=D.pts[1],ce=D.pts[2],pe=D.pts[3],xe=D.pts[4],he=D.pts[7],Ne=Math.cos(he),ge=Math.sin(he),Ae=ce*Math.cos(xe),Ee=pe*Math.sin(xe);z=X+Ae*Ne-Ee*ge,O=se+Ae*ge+Ee*Ne}else z=D.pts[0],O=D.pts[1];Math.hypot(this.currentPoint.x-z,this.currentPoint.y-O)>1e-6&&this.lineTo(z,O)}return this}getPoints(D=12){let z=Math.max(1,Math.min(128,Math.floor(Number(D)||12))),O=[],X=(se,ce)=>{if(O.length>0){let pe=O[O.length-1];if(Math.hypot(pe.x-se,pe.y-ce)<1e-6)return}O.push(new r(se,ce))};for(let se of this.segments){let ce=se.pts;if(se.type==="move"||se.type==="line")X(ce[0],ce[1]);else if(se.type==="quad"){let pe=ce[0],xe=ce[1],he=ce[2],Ne=ce[3],ge=ce[4],Ae=ce[5];X(pe,xe);for(let Ee=1;Ee<=z;Ee++){let $e=Ee/z,De=1-$e;X(De*De*pe+2*De*$e*he+$e*$e*ge,De*De*xe+2*De*$e*Ne+$e*$e*Ae)}}else if(se.type==="cubic"){let pe=ce[0],xe=ce[1],he=ce[2],Ne=ce[3],ge=ce[4],Ae=ce[5],Ee=ce[6],$e=ce[7];X(pe,xe);for(let De=1;De<=z;De++){let Be=De/z,Fe=1-Be,Ve=Fe*Fe,qe=Be*Be;X(Ve*Fe*pe+3*Ve*Be*he+3*Fe*qe*ge+qe*Be*Ee,Ve*Fe*xe+3*Ve*Be*Ne+3*Fe*qe*Ae+qe*Be*$e)}}else if(se.type==="arc"){let pe=ce[0],xe=ce[1],he=ce[2],Ne=ce[3],ge=ce[4],Ae=ce[5],Ee=ce[6]!==0,$e=ce[7],De=Math.PI*2,Be=Ae-ge,Fe=Math.abs(Be)<1e-9;for(;Be<0;)Be+=De;for(;Be>De;)Be-=De;Be<1e-9&&(Be=Fe?0:De),Ee&&!Fe&&(Be=Be===De?-De:Be-De);let Ve=Math.cos($e),qe=Math.sin($e),je=Math.max(2,z);for(let ut=0;ut<=je;ut++){let it=ut/je,nt=ge+it*Be,ct=he*Math.cos(nt),Je=Ne*Math.sin(nt);X(pe+ct*Ve-Je*qe,xe+ct*qe+Je*Ve)}}else if(se.type==="curve"&&se.curve?.getPoints)for(let pe of se.curve.getPoints(z))pe&&X(Number(pe.x)||0,Number(pe.y)||0)}if(O.length>2){let se=O[0],ce=O[O.length-1];Math.hypot(se.x-ce.x,se.y-ce.y)<1e-6&&O.pop()}return O}getSpacedPoints(D=12){return this.getPoints(D)}clone(){let D=new this.constructor;return D.currentPoint.copy(this.currentPoint),D.segments=this.segments.map(z=>({type:z.type,pts:[...z.pts],...z.curve?{curve:z.curve.clone?z.curve.clone():z.curve}:{}})),Array.isArray(this.holes)&&(D.holes=this.holes.map(z=>z.clone())),D}}class b extends A{constructor(D){super(D),this.holes=[]}extractPoints(D=12){return{shape:this.getPoints(D),holes:this.holes.map(z=>z.getPoints(D))}}}function w(W){let D=0,z=W.length;for(let O=0,X=z-1;O<z;X=O++)D+=W[X].x*W[O].y-W[O].x*W[X].y;return D*.5}function S(W,D,z,O,X,se,ce,pe){let xe=ce-z,he=pe-O,Ne=X-z,ge=se-O,Ae=W-z,Ee=D-O,$e=xe*xe+he*he,De=xe*Ne+he*ge,Be=xe*Ae+he*Ee,Fe=Ne*Ne+ge*ge,Ve=Ne*Ae+ge*Ee,qe=$e*Fe-De*De;if(Math.abs(qe)<1e-12)return!1;let je=1/qe,ut=(Fe*Be-De*Ve)*je,it=($e*Ve-De*Be)*je;return ut>=-1e-7&&it>=-1e-7&&ut+it<=1+1e-7}function E(W,D){let z=W.slice();w(z)<0&&z.reverse();let O=z.map(xe=>new r(xe.x,xe.y)),X=z.map((xe,he)=>he),se=[];for(let xe of D){if(!xe||xe.length<3)continue;let he=xe.slice();w(he)>0&&he.reverse();let Ne=[],ge=-1/0,Ae=0;for(let Ee=0;Ee<he.length;Ee++){let $e=he[Ee],De=O.length;O.push(new r($e.x,$e.y)),Ne.push(De),$e.x>ge&&(ge=$e.x,Ae=Ee)}se.push({pts:he,indices:Ne,maxX:ge,maxIdx:Ae})}se.sort((xe,he)=>he.maxX-xe.maxX);let ce=(xe,he,Ne)=>(he.x-xe.x)*(Ne.y-xe.y)-(he.y-xe.y)*(Ne.x-xe.x),pe=(xe,he,Ne)=>{for(let ge=0;ge<Ne.length;ge++){let Ae=Ne[ge],Ee=Ne[(ge+1)%Ne.length];if(ce(xe,he,Ae)*ce(xe,he,Ee)<0&&ce(Ae,Ee,xe)*ce(Ae,Ee,he)<0)return!0}return!1};for(let xe of se){let he=xe.pts[xe.maxIdx],Ne=he.x,ge=X.length,Ae=X.map(Fe=>O[Fe]),Ee=Fe=>Math.hypot(Ae[Fe].x-Ne,Ae[Fe].y-he.y),$e=Ae.map((Fe,Ve)=>Ve).sort((Fe,Ve)=>+(Ae[Fe].x<Ne)-+(Ae[Ve].x<Ne)||Ee(Fe)-Ee(Ve)),De=$e[0];for(let Fe of $e){let Ve=Ae[Fe],qe=Ae[(Fe+ge-1)%ge],je=Ae[(Fe+1)%ge],ut=ce(Ve,je,he)>=0,it=ce(qe,Ve,he)>=0;if((ce(qe,Ve,je)>=0?ut&&it:ut||it)&&!pe(he,Ve,Ae)&&!se.some(nt=>pe(he,Ve,nt.pts))){De=Fe;break}}let Be=[];for(let Fe=0;Fe<=De;Fe++)Be.push(X[Fe]);for(let Fe=0;Fe<=xe.indices.length;Fe++){let Ve=xe.indices[(xe.maxIdx+Fe)%xe.indices.length];Be.push(Ve)}for(let Fe=De;Fe<X.length;Fe++)Be.push(X[Fe]);X=Be}return{merged:X.map(xe=>O[xe]),mergedIndices:X,allVertices:O}}function N(W,D){let z=[],O=W.slice();if(O.length<3)return z;let X=O.length*O.length+64,se=0;for(;O.length>2&&X-- >0;){let ce=O.length,pe=O[(se+ce-1)%ce],xe=O[se%ce],he=O[(se+1)%ce],Ne=D[pe],ge=D[xe],Ae=D[he];if((ge.x-Ne.x)*(Ae.y-Ne.y)-(ge.y-Ne.y)*(Ae.x-Ne.x)>1e-9){let Ee=!0,$e=Math.min(Ne.x,ge.x,Ae.x)-1e-7,De=Math.max(Ne.x,ge.x,Ae.x)+1e-7,Be=Math.min(Ne.y,ge.y,Ae.y)-1e-7,Fe=Math.max(Ne.y,ge.y,Ae.y)+1e-7;for(let Ve=0;Ve<ce;Ve++){let qe=O[Ve];if(qe===pe||qe===xe||qe===he)continue;let je=D[qe];if(je.x>=$e&&je.x<=De&&je.y>=Be&&je.y<=Fe&&S(je.x,je.y,Ne.x,Ne.y,ge.x,ge.y,Ae.x,Ae.y)&&(je.x-Ne.x)*(je.x-Ne.x)+(je.y-Ne.y)*(je.y-Ne.y)>=1e-12&&(je.x-ge.x)*(je.x-ge.x)+(je.y-ge.y)*(je.y-ge.y)>=1e-12&&(je.x-Ae.x)*(je.x-Ae.x)+(je.y-Ae.y)*(je.y-Ae.y)>=1e-12){Ee=!1;break}}if(Ee){z.push([pe,xe,he]),O.splice(se%ce,1),se=Math.max(0,se%ce-1);continue}}se++,se>=ce*2&&(z.push([pe,xe,he]),O.splice((se-1)%ce,1),se=0)}return z}function C(W,D){let z=W instanceof b?W.extractPoints(D):{shape:W.getPoints(D),holes:[]},O=z.shape.length;for(let X of z.holes)O+=X.length;if(O>v)throw new RangeError(`SecurityError: shape point count (${O}) exceeds MAX_SHAPE_POINTS (${v})`);return z}function _(W){let D=1/0,z=1/0,O=-1/0,X=-1/0;for(let se of W)se.x<D&&(D=se.x),se.y<z&&(z=se.y),se.x>O&&(O=se.x),se.y>X&&(X=se.y);return[D,z,Math.max(1e-6,O-D),Math.max(1e-6,X-z)]}class P extends c{constructor(D=new b,z=12){super();let O=Array.isArray(D)?D:[D],X=[],se=[],ce=[],pe=[];for(let xe of O){if(!(xe instanceof A))continue;let he=C(xe,z);if(he.shape.length<3)continue;let{mergedIndices:Ne,allVertices:ge}=E(he.shape,he.holes),Ae=N(Ne,ge),Ee=X.length/3,[$e,De,Be,Fe]=_(ge);for(let Ve of ge)X.push(Ve.x,Ve.y,0),se.push(0,0,1),ce.push((Ve.x-$e)/Be,(Ve.y-De)/Fe);for(let[Ve,qe,je]of Ae)pe.push(Ee+Ve,Ee+qe,Ee+je)}R(this,X,se,ce,pe)}}function R(W,D,z,O,X){return W.setAttribute("position",new l(D,3)),W.setAttribute("normal",new l(z,3)),W.setAttribute("uv",new l(O,2)),W.setIndex(X),W}function I(W){let D=W.length,z=[];for(let O=0;O<D;O++){let X=W[(O+D-1)%D],se=W[O],ce=W[(O+1)%D],pe=se.x-X.x,xe=se.y-X.y,he=Math.hypot(pe,xe)||1;pe/=he,xe/=he;let Ne=ce.x-se.x,ge=ce.y-se.y,Ae=Math.hypot(Ne,ge)||1;Ne/=Ae,ge/=Ae;let Ee=xe,$e=-pe,De=ge,Be=-Ne,Fe=Ee+De,Ve=$e+Be,qe=Math.hypot(Fe,Ve);if(qe>1e-6){Fe/=qe,Ve/=qe;let je=Math.max(.35,Fe*Ee+Ve*$e);z.push(new r(Fe/je,Ve/je))}else z.push(new r(Ee,$e))}return z}class F extends c{constructor(D=new b,z={}){super();let O=Array.isArray(D)?D:[D],X=Math.max(1,Math.min(64,Math.floor(y(z.curveSegments,12)))),se=y(z.depth??z.amount,1),ce=Math.max(1,Math.min(32,Math.floor(y(z.steps,1)))),pe=!!(z.bevelEnabled??!1),xe=pe?Math.max(0,y(z.bevelThickness,.06)):0,he=pe?Math.max(0,y(z.bevelSize,xe*.8)):0,Ne=pe?y(z.bevelOffset,0):0,ge=pe?Math.max(1,Math.min(8,Math.floor(y(z.bevelSegments,2)))):0,Ae=[],Ee=[],$e=[],De=[];for(let Be of O){if(!(Be instanceof A))continue;let Fe=C(Be,X);if(Fe.shape.length<3)continue;let Ve=Fe.shape.slice();w(Ve)<0&&Ve.reverse();let qe=[];for(let Pe of Fe.holes){if(Pe.length<3)continue;let at=Pe.slice();w(at)>0&&at.reverse(),qe.push(at)}let{mergedIndices:je,allVertices:ut}=E(Ve,qe),it=N(je,ut),nt=[Ve,...qe],ct=[];for(let Pe of nt){let at=I(Pe);for(let vt of at)ct.push(vt)}let[Je,Dt,Ft,lr]=_(ut);for(let[Pe,at]of[[-xe,-1],[se+xe,1]]){let vt=Ae.length/3;for(let Mt=0;Mt<ut.length;Mt++){let Pt=ut[Mt],Ct=ct[Mt]??new r(0,0),Xt=Pt.x+Ct.x*Ne,Ot=Pt.y+Ct.y*Ne;Ae.push(Xt,Ot,Pe),Ee.push(0,0,at),$e.push((Xt-Je)/Ft,(Ot-Dt)/lr)}for(let[Mt,Pt,Ct]of it)De.push(vt+Mt,vt+(at<0?Ct:Pt),vt+(at<0?Pt:Ct))}let wt=[];if(pe&&ge>0)for(let Pe=0;Pe<ge;Pe++){let at=Pe/ge*Math.PI/2;wt.push({z:-xe*Math.cos(at),expand:Ne+he*Math.sin(at)})}for(let Pe=0;Pe<=ce;Pe++){let at=Pe/ce;wt.push({z:at*se,expand:Ne+he})}if(pe&&ge>0)for(let Pe=1;Pe<=ge;Pe++){let at=Pe/ge*Math.PI/2;wt.push({z:se+xe*Math.sin(at),expand:Ne+he*Math.cos(at)})}let Gt=0;for(let Pe of nt){let at=Pe.length;for(let vt=0;vt<wt.length-1;vt++){let Mt=wt[vt],Pt=wt[vt+1];for(let Ct=0;Ct<at;Ct++){let Xt=(Ct+1)%at,Ot=Pe[Ct],Yt=Pe[Xt],Qt=ct[Gt+Ct],Zt=ct[Gt+Xt],ur=Ot.x+Qt.x*Mt.expand,br=Ot.y+Qt.y*Mt.expand,oi=Yt.x+Zt.x*Mt.expand,Jt=Yt.y+Zt.y*Mt.expand,er=Yt.x+Zt.x*Pt.expand,vi=Yt.y+Zt.y*Pt.expand,Hr=Ot.x+Qt.x*Pt.expand,xr=Ot.y+Qt.y*Pt.expand,cr=oi-ur,Ht=Jt-br,ro=Hr-ur,fn=xr-br,wi=Pt.z-Mt.z,Nr=Ht*wi,Cr=-cr*wi,Er=cr*fn-Ht*ro,li=Math.hypot(Nr,Cr,Er)||1;Nr/=li,Cr/=li,Er/=li;let hr=Ae.length/3;Ae.push(ur,br,Mt.z,oi,Jt,Mt.z,er,vi,Pt.z,Hr,xr,Pt.z),Ee.push(Nr,Cr,Er,Nr,Cr,Er,Nr,Cr,Er,Nr,Cr,Er);let mn=Ct/at,oa=(Ct+1)/at,vr=vt/(wt.length-1),fr=(vt+1)/(wt.length-1);$e.push(mn,vr,oa,vr,oa,fr,mn,fr),De.push(hr,hr+1,hr+2,hr,hr+2,hr+3)}}Gt+=at}}R(this,Ae,Ee,$e,De)}}function V(W){return{x:W.x,y:W.y,z:W.z,nx:W.nx,ny:W.ny,nz:W.nz,u:W.u,v:W.v}}function Y(W){return{x:W.x,y:W.y,z:W.z,nx:-W.nx,ny:-W.ny,nz:-W.nz,u:W.u,v:W.v}}function J(W,D,z){let O=W.nx+(D.nx-W.nx)*z,X=W.ny+(D.ny-W.ny)*z,se=W.nz+(D.nz-W.nz)*z,ce=Math.hypot(O,X,se)||1;return{x:W.x+(D.x-W.x)*z,y:W.y+(D.y-W.y)*z,z:W.z+(D.z-W.z)*z,nx:O/ce,ny:X/ce,nz:se/ce,u:W.u+(D.u-W.u)*z,v:W.v+(D.v-W.v)*z}}function re(W){if(W.length<3)return null;let D=W[0],z=W[1],O=W[2],X=z.x-D.x,se=z.y-D.y,ce=z.z-D.z,pe=O.x-D.x,xe=O.y-D.y,he=O.z-D.z,Ne=se*he-ce*xe,ge=ce*pe-X*he,Ae=X*xe-se*pe,Ee=Math.hypot(Ne,ge,Ae);if(Ee<1e-9)return null;Ne/=Ee,ge/=Ee,Ae/=Ee;let $e=Ne*D.x+ge*D.y+Ae*D.z;return{vertices:W,nx:Ne,ny:ge,nz:Ae,w:$e}}function Q(W){W.vertices.reverse();for(let D=0;D<W.vertices.length;D++)W.vertices[D]=Y(W.vertices[D]);W.nx=-W.nx,W.ny=-W.ny,W.nz=-W.nz,W.w=-W.w}let ee=1e-5,k=0,G=1,q=2,H=3;function te(W,D,z,O,X,se,ce,pe,xe){let he=0,Ne=[];for(let ge=0;ge<X.vertices.length;ge++){let Ae=X.vertices[ge],Ee=W*Ae.x+D*Ae.y+z*Ae.z-O,$e=Ee<-ee?q:Ee>ee?G:k;he|=$e,Ne.push($e)}switch(he){case k:{W*X.nx+D*X.ny+z*X.nz>0?se.push(X):ce.push(X);break}case G:pe.push(X);break;case q:xe.push(X);break;case H:{let ge=[],Ae=[],Ee=X.vertices.length;for(let Ve=0;Ve<Ee;Ve++){let qe=(Ve+1)%Ee,je=Ne[Ve],ut=Ne[qe],it=X.vertices[Ve],nt=X.vertices[qe];if(je!==q&&ge.push(it),je!==G&&Ae.push(je!==q?V(it):it),(je|ut)===H){let ct=nt.x-it.x,Je=nt.y-it.y,Dt=nt.z-it.z,Ft=W*ct+D*Je+z*Dt,lr=Math.abs(Ft)>1e-12?(O-(W*it.x+D*it.y+z*it.z))/Ft:.5,wt=J(it,nt,Math.max(0,Math.min(1,lr)));ge.push(wt),Ae.push(V(wt))}}let{nx:$e,ny:De,nz:Be,w:Fe}=X;ge.length>=3&&pe.push({vertices:ge,nx:$e,ny:De,nz:Be,w:Fe}),Ae.length>=3&&xe.push({vertices:Ae,nx:$e,ny:De,nz:Be,w:Fe});break}default:break}}class Z{constructor(D,z=0){this.nx=0,this.ny=0,this.nz=0,this.w=0,this.hasPlane=!1,this.polygons=[],this.front=null,this.back=null,D&&D.length>0&&this.build(D,z)}invert(){for(let z=0;z<this.polygons.length;z++)Q(this.polygons[z]);this.nx=-this.nx,this.ny=-this.ny,this.nz=-this.nz,this.w=-this.w,this.front&&this.front.invert(),this.back&&this.back.invert();let D=this.front;this.front=this.back,this.back=D}clipPolygons(D,z=0){if(!this.hasPlane||D.length===0)return D.slice();if(z>=g)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${g})`);let O=[],X=[];for(let se=0;se<D.length;se++)te(this.nx,this.ny,this.nz,this.w,D[se],O,X,O,X);return this.front&&O.length>0&&(O=this.front.clipPolygons(O,z+1)),this.back?X=X.length>0?this.back.clipPolygons(X,z+1):[]:X=[],O.concat(X)}clipTo(D,z=0){this.polygons.length>0&&(this.polygons=D.clipPolygons(this.polygons,0)),z<g&&(this.front&&this.front.clipTo(D,z+1),this.back&&this.back.clipTo(D,z+1))}allPolygons(D=[]){for(let z=0;z<this.polygons.length;z++)D.push(this.polygons[z]);return this.front&&this.front.allPolygons(D),this.back&&this.back.allPolygons(D),D}build(D,z=0){if(!D.length)return;if(!this.hasPlane){let se=D[D.length>>1];this.nx=se.nx,this.ny=se.ny,this.nz=se.nz,this.w=se.w,this.hasPlane=!0}if(z>=g)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${g})`);let O=[],X=[];for(let se=0;se<D.length;se++)te(this.nx,this.ny,this.nz,this.w,D[se],this.polygons,this.polygons,O,X);O.length>0&&(this.front||(this.front=new Z),this.front.build(O,z+1)),X.length>0&&(this.back||(this.back=new Z),this.back.build(X,z+1))}}function ae(W,D){if(!D&&W._csgPolygons)return W._csgPolygons;let z=W.attributes.position;if(!z||z.count===0)return[];let O=W.attributes.normal,X=W.attributes.uv,se=W.index?W.index.array:null,ce=Math.floor(se?se.length/3:z.count/3);if(ce>p)throw new RangeError(`SecurityError: CSG input triangle count (${ce}) exceeds MAX_CSG_TRIANGLES (${p})`);let pe=D?D.elements:null,xe=pe?pe[0]*(pe[5]*pe[10]-pe[9]*pe[6])-pe[4]*(pe[1]*pe[10]-pe[9]*pe[2])+pe[8]*(pe[1]*pe[6]-pe[5]*pe[2])<0:!1,he=pe?new s().getNormalMatrix(D).elements:null,Ne=Ae=>{let Ee=z.getX(Ae),$e=z.getY(Ae),De=z.getZ(Ae),Be=O?O.getX(Ae):NaN,Fe=O?O.getY(Ae):NaN,Ve=O?O.getZ(Ae):NaN;if(pe&&he){let ut=pe[0]*Ee+pe[4]*$e+pe[8]*De+pe[12],it=pe[1]*Ee+pe[5]*$e+pe[9]*De+pe[13],nt=pe[2]*Ee+pe[6]*$e+pe[10]*De+pe[14];Ee=ut,$e=it,De=nt;let ct=he[0]*Be+he[3]*Fe+he[6]*Ve,Je=he[1]*Be+he[4]*Fe+he[7]*Ve,Dt=he[2]*Be+he[5]*Fe+he[8]*Ve,Ft=Math.hypot(ct,Je,Dt)||1;Be=ct/Ft,Fe=Je/Ft,Ve=Dt/Ft}let qe=X?X.getX(Ae):0,je=X?X.getY(Ae):0;return{x:Ee,y:$e,z:De,nx:Be,ny:Fe,nz:Ve,u:qe,v:je}},ge=[];for(let Ae=0;Ae<ce;Ae++){let Ee=se?se[Ae*3]:Ae*3,$e=se?se[Ae*3+1]:Ae*3+1,De=se?se[Ae*3+2]:Ae*3+2,Be=re(xe?[Ne(Ee),Ne(De),Ne($e)]:[Ne(Ee),Ne($e),Ne(De)]);Be&&ge.push(Be)}return ge}function ie(W){let D=[],z=[],O=[],X=[];for(let ce of W){let pe=ce.vertices;if(pe.length<3)continue;let xe=D.length/3;for(let he of pe)D.push(he.x,he.y,he.z),Number.isFinite(he.nx)&&he.nx*he.nx+he.ny*he.ny+he.nz*he.nz>.5?z.push(he.nx,he.ny,he.nz):z.push(ce.nx,ce.ny,ce.nz),O.push(he.u,he.v);for(let he=1;he<pe.length-1;he++)X.push(xe,xe+he,xe+he+1)}let se=R(new c,D,z,O,X);return se._csgPolygons=W,se}function de(W,D,z){if(W.length+D.length>p)throw new RangeError(`SecurityError: Combined CSG triangle count (${W.length+D.length}) exceeds MAX_CSG_TRIANGLES (${p})`);if(W.length===0)return z==="union"?D:[];if(D.length===0)return z==="intersect"?[]:W;let O=1/0,X=1/0,se=1/0,ce=-1/0,pe=-1/0,xe=-1/0;for(let Ee=0;Ee<D.length;Ee++){let $e=D[Ee].vertices;for(let De=0;De<$e.length;De++){let Be=$e[De];Be.x<O&&(O=Be.x),Be.y<X&&(X=Be.y),Be.z<se&&(se=Be.z),Be.x>ce&&(ce=Be.x),Be.y>pe&&(pe=Be.y),Be.z>xe&&(xe=Be.z)}}O-=1e-4,X-=1e-4,se-=1e-4,ce+=1e-4,pe+=1e-4,xe+=1e-4;let he=[],Ne=[];for(let Ee=0;Ee<W.length;Ee++){let $e=W[Ee],De=$e.vertices,Be=1/0,Fe=1/0,Ve=1/0,qe=-1/0,je=-1/0,ut=-1/0;for(let it=0;it<De.length;it++){let nt=De[it];nt.x<Be&&(Be=nt.x),nt.y<Fe&&(Fe=nt.y),nt.z<Ve&&(Ve=nt.z),nt.x>qe&&(qe=nt.x),nt.y>je&&(je=nt.y),nt.z>ut&&(ut=nt.z)}qe<O||Be>ce||je<X||Fe>pe||ut<se||Ve>xe?Ne.push($e):he.push($e)}if(he.length===0)return z==="union"?W.concat(D):z==="subtract"?W:[];let ge=new Z(he),Ae=new Z(D);return z==="union"?(ge.clipTo(Ae),Ae.clipTo(ge),Ae.invert(),Ae.clipTo(ge),Ae.invert(),ge.build(Ae.allPolygons()),Ne.concat(ge.allPolygons())):z==="subtract"?(ge.invert(),ge.clipTo(Ae),Ae.clipTo(ge),Ae.invert(),Ae.clipTo(ge),Ae.invert(),ge.build(Ae.allPolygons()),ge.invert(),Ne.concat(ge.allPolygons())):(ge.invert(),Ae.clipTo(ge),Ae.invert(),ge.clipTo(Ae),Ae.clipTo(ge),ge.build(Ae.allPolygons()),ge.invert(),ge.allPolygons())}function me(W,D,z,O=null,X=null){let se=ae(W,O),ce=ae(D,X);return ie(de(se,ce,z))}function Se(W,D,z){let O=W instanceof h||!!W?.isMesh,X=D instanceof h||!!D?.isMesh,se=O?W.geometry:W,ce=X?D.geometry:D,pe=null;if(X)if(D.updateMatrix(),O){W.updateMatrix();let ge=new a().makeScale(1/(W.scale.x||1),1/(W.scale.y||1),1/(W.scale.z||1)),Ae=Math.hypot(W.quaternion.x,W.quaternion.y,W.quaternion.z,W.quaternion.w)||1,Ee=new a().compose(new i(0,0,0),new n(-W.quaternion.x/Ae,-W.quaternion.y/Ae,-W.quaternion.z/Ae,W.quaternion.w/Ae),new i(1,1,1)),$e=new a().makeTranslation(-W.position.x,-W.position.y,-W.position.z);pe=ge.multiply(Ee).multiply($e).multiply(D.matrix)}else pe=D.matrix;let xe=me(se,ce,z,null,pe),he=O?W.material:new m,Ne=new h(xe,he);return O&&(Ne.position.copy(W.position),Ne.quaternion.copy(W.quaternion),Ne.scale.copy(W.scale),Ne.name=W.name),Ne}let ke={toGeometry:me,subtract(W,D){return Se(W,D,"subtract")},union(W,D){return Se(W,D,"union")},intersect(W,D){return Se(W,D,"intersect")}},_e={0:[[[.15,0],[.85,0],[.85,1],[.15,1],[.15,0]]],1:[[[.3,.8],[.5,1],[.5,0]],[[.2,0],[.8,0]]],2:[[[.15,.8],[.3,1],[.7,1],[.85,.8],[.85,.55],[.15,0],[.85,0]]],3:[[[.15,.85],[.3,1],[.75,1],[.85,.75],[.5,.5],[.85,.25],[.75,0],[.3,0],[.15,.15]]],4:[[[.7,0],[.7,1],[.15,.35],[.9,.35]]],5:[[[.85,1],[.2,1],[.15,.55],[.75,.55],[.85,.3],[.75,0],[.2,0]]],6:[[[.8,.9],[.5,1],[.15,.7],[.15,.15],[.5,0],[.85,.2],[.85,.45],[.5,.55],[.15,.45]]],7:[[[.15,1],[.85,1],[.35,0]]],8:[[[.2,.5],[.15,.75],[.3,1],[.7,1],[.85,.75],[.8,.5],[.2,.5],[.15,.2],[.3,0],[.7,0],[.85,.2],[.8,.5]]],9:[[[.85,.55],[.5,.45],[.15,.55],[.15,.85],[.5,1],[.85,.85],[.85,.2],[.5,0],[.2,.1]]],A:[[[.1,0],[.5,1],[.9,0]],[[.25,.35],[.75,.35]]],B:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]],[[.7,.5],[.85,.25],[.7,0],[.15,0]]],C:[[[.85,.8],[.65,1],[.3,1],[.15,.75],[.15,.25],[.3,0],[.65,0],[.85,.2]]],D:[[[.15,0],[.15,1],[.65,1],[.85,.75],[.85,.25],[.65,0],[.15,0]]],E:[[[.85,1],[.15,1],[.15,0],[.85,0]],[[.15,.5],[.7,.5]]],F:[[[.85,1],[.15,1],[.15,0]],[[.15,.5],[.7,.5]]],G:[[[.85,.8],[.65,1],[.3,1],[.15,.75],[.15,.25],[.3,0],[.85,0],[.85,.45],[.55,.45]]],H:[[[.15,0],[.15,1]],[[.85,0],[.85,1]],[[.15,.5],[.85,.5]]],I:[[[.25,1],[.75,1]],[[.5,1],[.5,0]],[[.25,0],[.75,0]]],J:[[[.8,1],[.8,.25],[.6,0],[.3,0],[.15,.25]]],K:[[[.15,0],[.15,1]],[[.85,1],[.15,.45],[.85,0]]],L:[[[.15,1],[.15,0],[.85,0]]],M:[[[.1,0],[.1,1],[.5,.35],[.9,1],[.9,0]]],N:[[[.15,0],[.15,1],[.85,0],[.85,1]]],O:[[[.3,0],[.7,0],[.85,.25],[.85,.75],[.7,1],[.3,1],[.15,.75],[.15,.25],[.3,0]]],P:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]]],Q:[[[.3,0],[.7,0],[.85,.25],[.85,.75],[.7,1],[.3,1],[.15,.75],[.15,.25],[.3,0]],[[.55,.3],[.9,-.05]]],R:[[[.15,0],[.15,1],[.7,1],[.85,.75],[.7,.5],[.15,.5]],[[.55,.5],[.85,0]]],S:[[[.85,.85],[.65,1],[.3,1],[.15,.75],[.85,.25],[.7,0],[.3,0],[.15,.15]]],T:[[[.1,1],[.9,1]],[[.5,1],[.5,0]]],U:[[[.15,1],[.15,.25],[.35,0],[.65,0],[.85,.25],[.85,1]]],V:[[[.1,1],[.5,0],[.9,1]]],W:[[[.05,1],[.25,0],[.5,.65],[.75,0],[.95,1]]],X:[[[.15,1],[.85,0]],[[.85,1],[.15,0]]],Y:[[[.15,1],[.5,.5],[.85,1]],[[.5,.5],[.5,0]]],Z:[[[.15,1],[.85,1],[.15,0],[.85,0]]],".":[[[.45,0],[.55,0],[.55,.12],[.45,.12],[.45,0]]],",":[[[.5,.15],[.4,-.1]]],":":[[[.45,.1],[.55,.1]],[[.45,.7],[.55,.7]]],"-":[[[.2,.5],[.8,.5]]],"+":[[[.2,.5],[.8,.5]],[[.5,.2],[.5,.8]]],"=":[[[.2,.35],[.8,.35]],[[.2,.65],[.8,.65]]],"/":[[[.2,0],[.8,1]]],"!":[[[.5,1],[.5,.28]],[[.5,.1],[.5,0]]],"?":[[[.2,.8],[.35,1],[.7,1],[.85,.75],[.5,.45],[.5,.28]],[[.5,.1],[.5,0]]],"(":[[[.65,1],[.35,.65],[.35,.35],[.65,0]]],")":[[[.35,1],[.65,.65],[.65,.35],[.35,0]]],"%":[[[.2,0],[.8,1]],[[.2,.8],[.35,.8],[.35,.95],[.2,.95],[.2,.8]],[[.65,.05],[.8,.05],[.8,.2],[.65,.2],[.65,.05]]],"#":[[[.32,0],[.32,1]],[[.68,0],[.68,1]],[[.12,.35],[.88,.35]],[[.12,.65],[.88,.65]]],$:[[[.8,.8],[.6,.92],[.3,.92],[.18,.72],[.82,.28],[.7,.08],[.4,.08],[.2,.2]],[[.5,1],[.5,0]]],_:[[[.1,0],[.9,0]]],"[":[[[.65,1],[.3,1],[.3,0],[.65,0]]],"]":[[[.35,1],[.7,1],[.7,0],[.35,0]]],"<":[[[.75,.85],[.25,.5],[.75,.15]]],">":[[[.25,.85],[.75,.5],[.25,.15]]],"*":[[[.5,.2],[.5,.8]],[[.2,.35],[.8,.65]],[[.2,.65],[.8,.35]]],"\\":[[[.2,1],[.8,0]]]};class Le extends c{constructor(D="",z={}){super();let O=String(D??"").slice(0,x),X=Math.max(.005,Math.min(100,y(z.size,.2))),se=!!(z.bevelEnabled??!1),ce=se?Math.max(0,Math.min(2,y(z.bevelThickness,X*.04))):0,pe=se?Math.max(0,Math.min(2,y(z.bevelSize,X*.03))):0,xe=Math.max(.001,Math.min(20,y(z.depth??z.height,X*.2)))+ce*2,he=X*.085+pe,Ne=X*.68,ge=X*.82,Ae=[],Ee=[],$e=[],De=[],Be=(qe,je,ut,it,nt,ct,Je)=>{let Dt=ut-qe,Ft=it-je,lr=Math.hypot(Dt,Ft),wt=1,Gt=0;lr>1e-6&&(wt=Dt/lr,Gt=Ft/lr);let Pe=-Gt*nt,at=wt*nt,vt=wt*nt*.6,Mt=Gt*nt*.6,Pt=qe-vt+Pe,Ct=je-Mt+at,Xt=qe-vt-Pe,Ot=je-Mt-at,Yt=ut+vt-Pe,Qt=it+Mt-at,Zt=ut+vt+Pe,ur=it+Mt+at,br=(oi,Jt,er,vi,Hr,xr,cr)=>{let Ht=Ae.length/3;Ae.push(oi[0],oi[1],oi[2],Jt[0],Jt[1],Jt[2],er[0],er[1],er[2],vi[0],vi[1],vi[2]),Ee.push(Hr,xr,cr,Hr,xr,cr,Hr,xr,cr,Hr,xr,cr),$e.push(0,0,1,0,1,1,0,1),De.push(Ht,Ht+1,Ht+2,Ht,Ht+2,Ht+3)};br([Pt,Ct,Je],[Xt,Ot,Je],[Yt,Qt,Je],[Zt,ur,Je],0,0,1),br([Xt,Ot,ct],[Pt,Ct,ct],[Zt,ur,ct],[Yt,Qt,ct],0,0,-1),br([Pt,Ct,ct],[Xt,Ot,ct],[Xt,Ot,Je],[Pt,Ct,Je],-wt,-Gt,0),br([Yt,Qt,ct],[Zt,ur,ct],[Zt,ur,Je],[Yt,Qt,Je],wt,Gt,0),br([Xt,Ot,ct],[Yt,Qt,ct],[Yt,Qt,Je],[Xt,Ot,Je],Gt,-wt,0),br([Zt,ur,ct],[Pt,Ct,ct],[Pt,Ct,Je],[Zt,ur,Je],-Gt,wt,0)},Fe=0,Ve=0;for(let qe=0;qe<O.length;qe++){let je=O[qe];if(je===`
17
+ `){Fe=0,Ve-=X*1.35;continue}if(je===" "||je===" "){Fe+=ge*(je===" "?.75:3);continue}if(je==="\r")continue;let ut=je.toUpperCase(),it=je!==ut&&je>="a"&&je<="z",nt=_e[ut]??_e["?"],ct=it?X*.76:X,Je=it?Ne*.88:Ne;for(let Dt of nt)for(let Ft=0;Ft<Dt.length-1;Ft++){let lr=Dt[Ft],wt=Dt[Ft+1];Be(Fe+lr[0]*Je,Ve+lr[1]*ct,Fe+wt[0]*Je,Ve+wt[1]*ct,he,-xe*.5,xe*.5)}Fe+=it?ge*.88:ge}R(this,Ae,Ee,$e,De),z.center!==!1?this.center():this.computeBoundingBox()}}function ne(W){if(!W)return;let D=W,z=W.userData?.xr?.text??W.userData?.xr?.label??W.userData?.xr?.title??W.userData?.xr?.caption??W.userData?.xr?.spatialLabel;if(z!=null&&z!==!1){let X=D.geometry?.attributes?.position;if((!X||X.count===0)&&W.userData._textApplied!==!0){let se="",ce=.08,pe=.015,xe;if(typeof z=="string"||typeof z=="number")se=String(z);else if(typeof z=="object"){let he=z;se=String(he.text??he.value??""),he.size!==void 0&&(ce=Number(he.size)||.08),(he.depth!==void 0||he.height!==void 0)&&(pe=Number(he.depth??he.height)||ce*.2),(typeof he.color=="string"||typeof he.color=="number")&&(xe=he.color)}se.trim().length>0&&(D.geometry=new Le(se,{size:ce,depth:pe}),W.userData._textApplied=!0,D.material instanceof f?xe!==void 0&&W.userData._autoTextColorApplied!==!0&&(D.material.color=new o(xe),W.userData._autoTextColorApplied=!0):D.material=new m({color:xe??16317180}))}}let O=W.userData?.csg;if(O&&typeof O=="object"&&W.userData._csgApplied!==!0&&D.geometry instanceof c&&D.geometry.attributes.position?.count>0){W.userData._csgApplied=!0;let X=Array.isArray(O)?O:[O],se=D.geometry;for(let ce of X){if(!ce||typeof ce!="object")continue;let pe=ce,xe=String(pe.op??pe.operation??"subtract"),he=xe==="union"||xe==="intersect"?xe:"subtract",Ne=pe.target??pe.mesh??pe.geometry;if(Ne instanceof h||Ne instanceof c)try{let ge=he==="union"?ke.union(D,Ne):he==="intersect"?ke.intersect(D,Ne):ke.subtract(D,Ne);D.geometry!==se&&D.geometry.dispose?.(),D.geometry=ge.geometry}catch(ge){typeof console<"u"&&console.warn("[three-live] userData.csg skipped:",ge)}}}}let Re={Path:A,Shape:b,ShapeGeometry:P,ExtrudeGeometry:F,TextGeometry:Le,CSG:ke,MAX_CSG_TRIANGLES:p,MAX_BSP_DEPTH:g,MAX_TEXT_GEOMETRY_CHARS:x,MAX_SHAPE_POINTS:v,materializeDeclarativeGeometry:ne};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,Re),t._cadMaterialize=ne,t.materializeDeclarativeGeometry=W=>{t._cadMaterialize?.(W),t._lodMaterialize?.(W),t._procMaterialize?.(W)}),Re}var lo={name:"cad",onRegister(){Mn(ha);let e=We(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&ha(t,e)}};function lt(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function uo(e,t,r,i,n){let a=1/Math.tan(t/2);e.fill(0),e[0]=a/r,e[5]=a,e[11]=-1;let s=1/(i-n);return e[10]=(n+i)*s,e[14]=2*n*i*s,e}function q0(e,t,r,i,n,a,s){let o=1/(t-r),l=1/(i-n),c=1/(a-s);return e.fill(0),e[0]=-2*o,e[5]=-2*l,e[10]=2*c,e[12]=(t+r)*o,e[13]=(n+i)*l,e[14]=(s+a)*c,e[15]=1,e}function _n(e,t,r,i){let[n,a,s]=t,[o,l,c]=i,[f,m,h]=r,p=n-f,g=a-m,x=s-h,v=Math.hypot(p,g,x);v<=1e-5?(p=0,g=0,x=1):(p/=v,g/=v,x/=v);let y=l*x-c*g,A=c*p-o*x,b=o*g-l*p;v=Math.hypot(y,A,b),v<=1e-5?(y=0,A=0,b=0):(y/=v,A/=v,b/=v);let w=g*b-x*A,S=x*y-p*b,E=p*A-g*y;return v=Math.hypot(w,S,E),v<=1e-5?(w=0,S=0,E=0):(w/=v,S/=v,E/=v),e[0]=y,e[1]=w,e[2]=p,e[3]=0,e[4]=A,e[5]=S,e[6]=g,e[7]=0,e[8]=b,e[9]=E,e[10]=x,e[11]=0,e[12]=-(y*n+A*a+b*s),e[13]=-(w*n+S*a+E*s),e[14]=-(p*n+g*a+x*s),e[15]=1,e}function ft(e,t,r){let i=t[0],n=t[1],a=t[2],s=t[3],o=t[4],l=t[5],c=t[6],f=t[7],m=t[8],h=t[9],p=t[10],g=t[11],x=t[12],v=t[13],y=t[14],A=t[15],b=r[0],w=r[1],S=r[2],E=r[3];return e[0]=b*i+w*o+S*m+E*x,e[1]=b*n+w*l+S*h+E*v,e[2]=b*a+w*c+S*p+E*y,e[3]=b*s+w*f+S*g+E*A,b=r[4],w=r[5],S=r[6],E=r[7],e[4]=b*i+w*o+S*m+E*x,e[5]=b*n+w*l+S*h+E*v,e[6]=b*a+w*c+S*p+E*y,e[7]=b*s+w*f+S*g+E*A,b=r[8],w=r[9],S=r[10],E=r[11],e[8]=b*i+w*o+S*m+E*x,e[9]=b*n+w*l+S*h+E*v,e[10]=b*a+w*c+S*p+E*y,e[11]=b*s+w*f+S*g+E*A,b=r[12],w=r[13],S=r[14],E=r[15],e[12]=b*i+w*o+S*m+E*x,e[13]=b*n+w*l+S*h+E*v,e[14]=b*a+w*c+S*p+E*y,e[15]=b*s+w*f+S*g+E*A,e}function Sn(e,t,r,i){let n=t[0],a=t[1],s=t[2],o=t[3],l=n+n,c=a+a,f=s+s,m=n*l,h=n*c,p=n*f,g=a*c,x=a*f,v=s*f,y=o*l,A=o*c,b=o*f,w=i[0],S=i[1],E=i[2];return e[0]=(1-(g+v))*w,e[1]=(h+b)*w,e[2]=(p-A)*w,e[3]=0,e[4]=(h-b)*S,e[5]=(1-(m+v))*S,e[6]=(x+y)*S,e[7]=0,e[8]=(p+A)*E,e[9]=(x-y)*E,e[10]=(1-(m+g))*E,e[11]=0,e[12]=r[0],e[13]=r[1],e[14]=r[2],e[15]=1,e}function rr(e,t,r=0){let i=t[0],n=t[1],a=t[2],s=t[4],o=t[5],l=t[6],c=t[8],f=t[9],m=t[10],h=m*o-l*f,p=-m*s+l*c,g=f*s-o*c,x=i*h+n*p+a*g;return!x||r>0&&(!Number.isFinite(x)||Math.abs(x)<=r)||(x=1/x,e[0]=h*x,e[1]=p*x,e[2]=g*x,e[3]=(-m*n+a*f)*x,e[4]=(m*i-a*c)*x,e[5]=(-f*i+n*c)*x,e[6]=(l*n-a*o)*x,e[7]=(-l*i+a*s)*x,e[8]=(o*i-n*s)*x),e}function co(e,t){let r=t[0],i=t[1],n=t[2],a=t[3],s=t[4],o=t[5],l=t[6],c=t[7],f=t[8],m=t[9],h=t[10],p=t[11],g=t[12],x=t[13],v=t[14],y=t[15],A=r*o-i*s,b=r*l-n*s,w=r*c-a*s,S=i*l-n*o,E=i*c-a*o,N=n*c-a*l,C=f*x-m*g,_=f*v-h*g,P=f*y-p*g,R=m*v-h*x,I=m*y-p*x,F=h*y-p*v,V=A*F-b*I+w*R+S*P-E*_+N*C;return V?(V=1/V,e[0]=(o*F-l*I+c*R)*V,e[1]=(n*I-i*F-a*R)*V,e[2]=(x*N-v*E+y*S)*V,e[3]=(h*E-m*N-p*S)*V,e[4]=(l*P-s*F-c*_)*V,e[5]=(r*F-n*P+a*_)*V,e[6]=(v*w-g*N-y*b)*V,e[7]=(f*N-h*w+p*b)*V,e[8]=(s*I-o*P+c*C)*V,e[9]=(i*P-r*I-a*C)*V,e[10]=(g*E-x*w+y*A)*V,e[11]=(m*w-f*E-p*A)*V,e[12]=(o*_-s*R-l*C)*V,e[13]=(r*R-i*_+n*C)*V,e[14]=(x*b-g*S-v*A)*V,e[15]=(f*S-m*b+h*A)*V,e):null}function Zc(e,t,r,i,n){let a=n[0]*t+n[4]*r+n[8]*i+n[12],s=n[1]*t+n[5]*r+n[9]*i+n[13],o=n[2]*t+n[6]*r+n[10]*i+n[14],l=n[3]*t+n[7]*r+n[11]*i+n[15],c=l!==0?1/l:1;e[0]=a*c,e[1]=s*c,e[2]=o*c}function W0(e,t,r,i,n,a,s,o,l,c,f,m,h,p,g,x,v=0){let y=c-s,A=f-o,b=m-l,w=h-s,S=p-o,E=g-l,N=n*E-a*S,C=a*w-i*E,_=i*S-n*w,P=y*N+A*C+b*_;if(P>-1e-7&&P<1e-7)return!1;let R=1/P,I=e-s,F=t-o,V=r-l,Y=R*(I*N+F*C+V*_);if(Y<-v||Y>1+v)return!1;let J=F*b-V*A,re=V*y-I*b,Q=I*A-F*y,ee=R*(i*J+n*re+a*Q);if(ee<-v||Y+ee>1+v)return!1;let k=R*(w*J+S*re+E*Q);if(k>1e-4&&k<x.distance){x.distance=k,x.point=[e+i*k,t+n*k,r+a*k];let G=A*E-b*S,q=b*w-y*E,H=y*S-A*w,te=Math.hypot(G,q,H)||1;return x.normal=[G/te,q/te,H/te],!0}return!1}function An(e,t){let r=Array.isArray(e?.nodes)?e.nodes.length:0,i=[];for(let f=0;f<r;f++)i.push(lt());if(r===0)return i;let n=new Set;for(let f of e.nodes)if(Array.isArray(f.children))for(let m of f.children)n.add(m);let a=new Set,s=128,o=(f,m,h=0)=>{if(h>s||f<0||f>=r||a.has(f))return;a.add(f);let p=e.nodes[f];if(!p)return;let g=lt();if(t&&t[f])g.set(t[f]);else if(p.matrix&&p.matrix.length===16)g.set(p.matrix);else{let v=p.translation||[0,0,0],y=p.rotation||[0,0,0,1],A=p.scale||[1,1,1];Sn(g,y,v,A)}let x=i[f];if(m?ft(x,m,g):x.set(g),Array.isArray(p.children))for(let v of p.children)typeof v=="number"&&o(v,x,h+1)},l=[],c=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(c&&Array.isArray(c.nodes))l.push(...c.nodes);else for(let f=0;f<r;f++)n.has(f)||l.push(f);for(let f of l)o(f,null);for(let f=0;f<r;f++)!n.has(f)&&!l.includes(f)&&o(f,null);return i}function ho(e,t){function r(l,c,f,m){let h=typeof l=="number"?l:Number(l);return Number.isFinite(h)?Math.max(c,Math.min(f,h)):m}function i(l,c){let f=l[0]*c[0]+l[1]*c[1]+l[2]*c[2]+1;if(f<1e-6){if(Math.abs(l[0])>Math.abs(l[2])){let v=Math.hypot(l[1],l[0])||1;return[-l[1]/v,l[0]/v,0,0]}let x=Math.hypot(l[2],l[1])||1;return[0,-l[2]/x,l[1]/x,0]}let m=l[1]*c[2]-l[2]*c[1],h=l[2]*c[0]-l[0]*c[2],p=l[0]*c[1]-l[1]*c[0],g=Math.hypot(m,h,p,f)||1;return[m/g,h/g,p/g,f/g]}function n(l,c,f,m,h){let p=c[0]-l[0],g=c[1]-l[1],x=c[2]-l[2],v=Math.hypot(p,g,x),y=f[0]-c[0],A=f[1]-c[1],b=f[2]-c[2],w=Math.hypot(y,A,b);if(v<1e-6||w<1e-6)return{rootPos:[l[0],l[1],l[2]],midPos:[c[0],c[1],c[2]],effectorPos:[f[0],f[1],f[2]],rootRotation:[0,0,0,1],midRotation:[0,0,0,1]};let S=[p/v,g/v,x/v],E=[y/w,A/w,b/w],N=m[0]-l[0],C=m[1]-l[1],_=m[2]-l[2],P=Math.hypot(N,C,_),R=P>1e-6?[N/P,C/P,_/P]:S,I=Math.abs(v-w)+1e-5,F=Math.max(I,v+w-1e-5),V=Math.max(I,Math.min(F,P>1e-6?P:I)),Y=r((v*v+V*V-w*w)/(2*v*V),-1,1,1),J=Math.sqrt(Math.max(0,1-Y*Y)),re=h?h[0]-l[0]:p,Q=h?h[1]-l[1]:g,ee=h?h[2]-l[2]:x,k=re*R[0]+Q*R[1]+ee*R[2],G=re-R[0]*k,q=Q-R[1]*k,H=ee-R[2]*k,te=Math.hypot(G,q,H);if(te<=1e-6){let Re=Math.abs(R[1])<.99?0:1,W=Math.abs(R[1])<.99?1:0,D=0;G=R[1]*D-R[2]*W,q=R[2]*Re-R[0]*D,H=R[0]*W-R[1]*Re,te=Math.hypot(G,q,H)||1}let Z=[G/te,q/te,H/te],ae=[l[0]+R[0]*(v*Y)+Z[0]*(v*J),l[1]+R[1]*(v*Y)+Z[1]*(v*J),l[2]+R[2]*(v*Y)+Z[2]*(v*J)],ie=[l[0]+R[0]*V,l[1]+R[1]*V,l[2]+R[2]*V],de=ie[0]-ae[0],me=ie[1]-ae[1],Se=ie[2]-ae[2],ke=Math.hypot(de,me,Se),_e=ke>1e-6?[de/ke,me/ke,Se/ke]:R,Le=[ae[0]+_e[0]*w,ae[1]+_e[1]*w,ae[2]+_e[2]*w],ne=[(ae[0]-l[0])/v,(ae[1]-l[1])/v,(ae[2]-l[2])/v];return{rootPos:[l[0],l[1],l[2]],midPos:ae,effectorPos:Le,rootRotation:i(S,ne),midRotation:i(E,_e)}}function a(l,c,f=8,m=.001){let h=l.length;if(h<2)return{positions:l.map(P=>[P[0],P[1],P[2]]),rotations:[],iterations:0};let p=l.map(P=>[P[0],P[1],P[2]]),g=[],x=[],v=0;for(let P=0;P<h-1;P++){let R=p[P+1][0]-p[P][0],I=p[P+1][1]-p[P][1],F=p[P+1][2]-p[P][2],V=Math.hypot(R,I,F);g.push(V),v+=V,x.push(V>1e-6?[R/V,I/V,F/V]:[0,1,0])}let y=[p[0][0],p[0][1],p[0][2]],A=Math.round(r(f,1,32,8)),b=r(m,1e-5,.1,.001),w=c[0]-y[0],S=c[1]-y[1],E=c[2]-y[2],N=Math.hypot(w,S,E),C=0;if(N>=v&&v>1e-6){let P=N>1e-6?[w/N,S/N,E/N]:x[0];p[0]=[y[0],y[1],y[2]];for(let R=0;R<h-1;R++){let I=g[R];p[R+1]=[p[R][0]+P[0]*I,p[R][1]+P[1]*I,p[R][2]+P[2]*I]}C=1}else for(let P=1;P<=A;P++){let R=p[h-1];if(Math.hypot(R[0]-c[0],R[1]-c[1],R[2]-c[2])<=b)break;C=P;let I=(F,V,Y,J,re)=>{let Q=V[0]-F[0],ee=V[1]-F[1],k=V[2]-F[2],G=Math.hypot(Q,ee,k);if(G>1e-6){let q=Y/G;return[F[0]+Q*q,F[1]+ee*q,F[2]+k*q]}return[F[0]+J[0]*Y*re,F[1]+J[1]*Y*re,F[2]+J[2]*Y*re]};p[h-1]=[c[0],c[1],c[2]];for(let F=h-2;F>=0;F--)p[F]=I(p[F+1],p[F],g[F],x[F],-1);p[0]=[y[0],y[1],y[2]];for(let F=0;F<h-1;F++)p[F+1]=I(p[F],p[F+1],g[F],x[F],1)}let _=[];for(let P=0;P<h-1;P++){let R=p[P+1][0]-p[P][0],I=p[P+1][1]-p[P][1],F=p[P+1][2]-p[P][2],V=Math.hypot(R,I,F),Y=V>1e-6?[R/V,I/V,F/V]:x[P];_.push(i(x[P],Y))}return{positions:p,rotations:_,iterations:C}}function s(l){if(!l||typeof l!="object"||Array.isArray(l))return null;let c=l;if(c.enabled===!1)return null;let f=b=>{if(typeof b!="string")return;let w=b.trim().slice(0,64);return/^[A-Za-z0-9_.:-]+$/.test(w)?w:void 0},m=b=>Array.isArray(b)&&b.length===3&&b.every(w=>typeof w=="number"&&Number.isFinite(w))?[r(b[0],-1e3,1e3,0),r(b[1],-1e3,1e3,0),r(b[2],-1e3,1e3,0)]:void 0,h=f(c.root),p=f(c.effector);if(!h||!p)return null;let g=f(c.mid),x=m(c.target)??f(c.target);if(!x)return null;let v=c.pole??c.poleTarget,y=m(v)??f(v),A=c.solver==="fabrik"?"fabrik":c.solver==="two-bone"||g?"two-bone":"fabrik";return{root:h,...g?{mid:g}:{},effector:p,target:x,...y?{pole:y}:{},solver:A,iterations:Math.round(r(c.iterations,1,32,8)),tolerance:r(c.tolerance,1e-5,.1,.001),weight:r(c.weight,0,1,1)}}let o=Object.freeze({solveTwoBone:n,solveFABRIK:a,parseIKTrait:s});return t&&typeof t=="object"&&(t.authorNamespace=t.authorNamespace||{},t.authorNamespace.IKSolver=o),{clampNum:r,parseIKTrait:s,quatFromUnitVectors:i,solveTwoBoneIK:n,solveFABRIK:a,IKSolver:o}}var ki=ho(),Jc=ki.clampNum,K0=ki.parseIKTrait,fa=ki.quatFromUnitVectors,fo=ki.solveTwoBoneIK,mo=ki.solveFABRIK,eh=ki.IKSolver;function po(e){let t=e?.transform??e?.modelMatrix;return t&&t.length>=16?[t[12]||0,t[13]||0,t[14]||0]:[0,0,0]}function X0(e,t){let r=e?.transform??e?.modelMatrix;!r||r.length<16||(r[12]=t[0],r[13]=t[1],r[14]=t[2])}function Y0(e,t,r,i,n){let a=Jc(n,0,1,1),s=t[0]+(r[0]-t[0])*a,o=t[1]+(r[1]-t[1])*a,l=t[2]+(r[2]-t[2])*a,c=s-e[0],f=o-e[1],m=l-e[2],h=Math.hypot(c,f,m);if(h>1e-6&&i>1e-6){let y=i/h;return[e[0]+c*y,e[1]+f*y,e[2]+m*y]}let p=r[0]-e[0],g=r[1]-e[1],x=r[2]-e[2],v=Math.hypot(p,g,x);if(v>1e-6&&i>1e-6){let y=i/v;return[e[0]+p*y,e[1]+g*y,e[2]+x*y]}return[s,o,l]}function Q0(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return co(i,r instanceof Float32Array?r:Float32Array.from(r))?[i[0]*t[0]+i[4]*t[1]+i[8]*t[2]+i[12],i[1]*t[0]+i[5]*t[1]+i[9]*t[2]+i[13],i[2]*t[0]+i[6]*t[1]+i[10]*t[2]+i[14]]:t}function go(e,t){e.__ikWarned||(e.__ikWarned=new Set);let r=e.__ikWarned;r.has(t)||(r.add(t),console.warn(`[three-live] ik: joint '${t}' on '${e?.name??""}' not found among scene nodes or meshes.`))}function yo(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return po(i);let n;if(e==="head"?n=r?.headPose?.position??r?.headPose??r?.cameraPosition:e==="hand-left"?n=r?.handPoses?.left?.position??r?.handPoses?.left??r?.hands?.left?.position??r?.hands?.left:e==="hand-right"&&(n=r?.handPoses?.right?.position??r?.handPoses?.right??r?.hands?.right?.position??r?.hands?.right),(Array.isArray(n)||ArrayBuffer.isView(n))&&n.length>=3){let a=n;return Q0(r,[a[0],a[1],a[2]])}return null}function bo(e,t){return[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]-e[0]*t[2]+e[1]*t[3]+e[2]*t[0],e[3]*t[2]+e[0]*t[1]-e[1]*t[0]+e[2]*t[3],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]]}function Z0(e){return[-e[0],-e[1],-e[2],e[3]]}function xo(e){let t=Math.hypot(e[0],e[1],e[2],e[3]);return t>1e-12?[e[0]/t,e[1]/t,e[2]/t,e[3]/t]:[0,0,0,1]}function J0(e,t){if(t>=1)return e;if(t<=0)return[0,0,0,1];let[r,i,n,a]=e;a<0&&(r=-r,i=-i,n=-n,a=-a);let s=Math.acos(Math.min(1,a)),o=Math.sin(s);if(o<1e-9)return[0,0,0,1];let l=Math.sin(s*t)/o;return xo([r*l,i*l,n*l,Math.cos(s*t)])}function ep(e){let t=Math.hypot(e[0],e[1],e[2])||1,r=Math.hypot(e[4],e[5],e[6])||1,i=Math.hypot(e[8],e[9],e[10])||1,n=e[0]/t,a=e[1]/t,s=e[2]/t,o=e[4]/r,l=e[5]/r,c=e[6]/r,f=e[8]/i,m=e[9]/i,h=e[10]/i,p=n+l+h,g;if(p>0){let x=Math.sqrt(p+1)*2;g=[(c-m)/x,(f-s)/x,(a-o)/x,.25*x]}else if(n>l&&n>h){let x=Math.sqrt(1+n-l-h)*2;g=[.25*x,(o+a)/x,(f+s)/x,(c-m)/x]}else if(l>h){let x=Math.sqrt(1+l-n-h)*2;g=[(o+a)/x,.25*x,(m+c)/x,(f-s)/x]}else{let x=Math.sqrt(1+h-n-l)*2;g=[(f+s)/x,(m+c)/x,.25*x,(a-o)/x]}return xo(g)}function tp(e,t,r){let[i,n,a,s]=r,o=1-2*(n*n+a*a),l=2*(i*n-a*s),c=2*(i*a+n*s),f=2*(i*n+a*s),m=1-2*(i*i+a*a),h=2*(n*a-i*s),p=2*(i*a-n*s),g=2*(n*a+i*s),x=1-2*(i*i+n*n);for(let v=0;v<3;v++){let y=t[v*4],A=t[v*4+1],b=t[v*4+2];e[v*4]=o*y+l*A+c*b,e[v*4+1]=f*y+m*A+h*b,e[v*4+2]=p*y+g*A+x*b}}function ma(e,t){let r=t[0]-e[0],i=t[1]-e[1],n=t[2]-e[2],a=Math.hypot(r,i,n);return a>1e-9?[r/a,i/a,n/a]:null}function th(e){e?.normalMatrix&&e?.transform&&rr(e.normalMatrix,e.transform)}var rh=new WeakMap;function rp(e){let t=rh.get(e);return t||(t=new Int32Array(e.nodes.length).fill(-1),e.nodes.forEach((r,i)=>{for(let n of Array.isArray(r?.children)?r.children:[])typeof n=="number"&&n>=0&&n<t.length&&(t[n]=i)}),rh.set(e,t)),t}function ip(e,t,r){let i=e?.gltf,n=i?.nodes;if(!Array.isArray(n)||n.length===0)return!1;let a=new Map;n.forEach((_,P)=>{typeof _?.name=="string"&&_.name&&!a.has(_.name)&&a.set(_.name,P)});let s=(t.mid?[t.root,t.mid,t.effector]:[t.root,t.effector]).map(_=>a.get(_));if(s.some(_=>_===void 0))return!1;let o=s,l=rp(i);for(let _=1;_<o.length;_++){let P=l[o[_]],R=0;for(;P>=0&&P!==o[_-1]&&R++<256;)P=l[P];if(P!==o[_-1])return!1}let c=o[0],f=e.initialNodeTransforms,m=new Map,h=[],p=[c];for(;p.length&&h.length<4096;){let _=p.pop();if(m.has(_))continue;let P=f?.[_],R=n[_];m.set(_,{t:P?[P.t[0],P.t[1],P.t[2]]:R?.translation?[...R.translation]:[0,0,0],r:P?[P.r[0],P.r[1],P.r[2],P.r[3]]:R?.rotation?[...R.rotation]:[0,0,0,1],s:P?[P.s[0],P.s[1],P.s[2]]:R?.scale?[...R.scale]:[1,1,1]}),h.push(_);for(let I of Array.isArray(R?.children)?R.children:[])typeof I=="number"&&p.push(I)}let g=l[c],x=g>=0&&e.worldMatrices?.[g]?.length===16?Float32Array.from(e.worldMatrices[g]):lt(),v=new Map,y=()=>{let _=(P,R)=>{let I=m.get(P);if(!I)return;let F=lt();Sn(F,I.r,I.t,I.s);let V=lt();ft(V,R,F),v.set(P,V);for(let Y of Array.isArray(n[P]?.children)?n[P].children:[])typeof Y=="number"&&_(Y,V)};_(c,x)},A=_=>{let P=v.get(_);return[P[12],P[13],P[14]]};y();let b=o.map(A),w=_=>{if(typeof _=="string"&&!r.has(_)){let P=a.get(_),R=P!==void 0?v.get(P)??e.worldMatrices?.[P]:void 0;if(R&&R.length===16)return[R[12],R[13],R[14]]}return yo(_,r,e)},S=w(t.target);if(!S)return!0;let E=t.pole?w(t.pole)??void 0:void 0,N=ih(b,t,S,E),C=Jc(t.weight,0,1,1);for(let _=0;_<o.length-1;_++){let P=ma(A(o[_]),A(o[_+1])),R=ma(N[_],N[_+1]);if(!P||!R)continue;let I=J0(fa(P,R),C),F=o[_],V=l[F],Y=V===g||V<0?x:v.get(V)??x,J=ep(Y),re=m.get(F);re.r=xo(bo(Z0(J),bo(I,bo(J,re.r)))),y()}if(Array.isArray(e.worldMatrices))for(let[_,P]of v)e.worldMatrices[_]?.set&&e.worldMatrices[_].set(P);for(let _ of e.meshes??[]){let P=v.get(_?.nodeIndex);P&&_.transform?.set&&(_.transform.set(P),th(_))}return!0}function ih(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let n=fo(e[0],e[1],e[2],r,i);return[e[0],n.midPos,n.effectorPos]}return mo(e,r,t.iterations,t.tolerance).positions}function np(e,t,r){let i=e.__ikRestOffsets,n=e.__ikRestMats;if(!(!i||!n))for(let a=0;a<t.length-1;a++){let s=t[a]?.transform??t[a]?.modelMatrix,o=n[a],l=ma([0,0,0],i[a]),c=ma(r[a],r[a+1]);!s||s.length<16||!o||o.length<16||!l||!c||(tp(s,o,fa(l,c)),th(t[a]))}}var vo={name:"ik",onRegister(){let e=We();Mn(ho),ho(e.threeNamespace,e)},onUpdate(e){let t=e?.meshes;if(!Array.isArray(t)||t.length===0)return;let r=null;for(let i of t){let n=i?.userData?.xr?.ik??i?.extras?.xr?.ik??i?.extensions?.ANDROID_xr_scenecore?.ik;if(!n)continue;let a=K0(n);if(!a||a.weight<=0)continue;if(!r){r=new Map;for(let b of t)b&&typeof b.name=="string"&&b.name&&r.set(b.name,b)}if(ip(e,a,r))continue;let s=r.get(a.root),o=r.get(a.effector),l=a.mid?r.get(a.mid):void 0;if(s||go(i,a.root),o||go(i,a.effector),a.mid&&!l&&go(i,a.mid),!s||!o)continue;let c=yo(a.target,r,e);if(!c)continue;let f=a.pole?yo(a.pole,r,e)??void 0:void 0,m=l?[s,l,o]:[s,o],h=m.map(b=>b.name||"").join(">");if(!i.__ikRestOffsets||i.__ikRestKey!==h){let b=m.map(po),w=[];for(let S=0;S<b.length-1;S++)w.push([b[S+1][0]-b[S][0],b[S+1][1]-b[S][1],b[S+1][2]-b[S][2]]);i.__ikRestOffsets=w,i.__ikRestKey=h,i.__ikRestMats=m.map(S=>Array.from(S.transform??S.modelMatrix??[]))}let p=i.__ikRestOffsets,g=[po(s)],x=[];for(let b=0;b<p.length;b++){let w=g[b],S=p[b];g.push([w[0]+S[0],w[1]+S[1],w[2]+S[2]]),x.push(Math.hypot(S[0],S[1],S[2]))}let v=ih(g,a,c,f),y=g[0],A=[g[0]];for(let b=1;b<m.length;b++){let w=p[b-1],S=[y[0]+w[0],y[1]+w[1],y[2]+w[2]],E=[y[0]+(v[b][0]-v[b-1][0]),y[1]+(v[b][1]-v[b-1][1]),y[2]+(v[b][2]-v[b-1][2])],N=Y0(y,S,E,x[b-1],a.weight);X0(m[b],N),y=N,A.push(N)}np(i,m,A)}}};function Tn(e,t){let r=(f,m,h,p)=>{let g=typeof f=="number"?f:Number(f);return Number.isFinite(g)?Math.max(m,Math.min(h,g)):p};function i(f,m,h=0,p=.05,g){if(!f||!f.length)return-1;let x=f[0]>0?[0,...f]:f,v=Number.isFinite(m)?Math.max(0,m):0,y=Number.isFinite(p)?Math.max(0,Math.min(.5,p)):.05;if(typeof g=="number"&&Number.isFinite(g)&&g>0){let w=h===-1?g*(1-y):g*(1+y);if(v>w)return-1}let A=0;for(let w=x.length-1;w>=1;w--)if(v>=x[w]){A=w;break}if(h<0||h>=x.length||h===A)return A;if(A>h){let w=h;for(let S=h+1;S<=A&&v>=x[S]*(1+y);S++)w=S;return w}let b=h;for(let w=h;w>A&&v<x[w]*(1-y);w--)b=w-1;return b}function n(f){if(!f)return null;let m=f===!0?{distances:[4,10],ratios:[.5,.25]}:Array.isArray(f)?{distances:f}:typeof f=="object"?f:null;if(!m||m.enabled===!1)return null;let h=r(m.hysteresis,0,.5,.05),p=[],g;if(Array.isArray(m.levels)&&m.levels.length>0){let A=m.levels.slice(0,8);for(let w=0;w<A.length;w++){let S=A[w];if(!S||typeof S!="object"||Array.isArray(S))continue;let E=S,N=r(E.distance,0,1e4,w===0?0:w*4),C=typeof E.hysteresis=="number"?r(E.hysteresis,0,.5,h):void 0,_=typeof E.ratio=="number"?r(E.ratio,.05,1,.5):void 0,P=typeof E.childIndex=="number"&&Number.isFinite(E.childIndex)?Math.max(0,Math.round(E.childIndex)):void 0,R=typeof E.node=="string"&&/^[A-Za-z0-9_.:-]+$/.test(E.node.trim())?E.node.trim().slice(0,64):void 0;p.push({distance:N,...C!==void 0?{hysteresis:C}:{},..._!==void 0?{ratio:_}:{},...P!==void 0?{childIndex:P}:{},...R?{node:R}:{}})}p.sort((w,S)=>w.distance-S.distance),p.length>0&&p[0].distance>0&&p.unshift({distance:0,childIndex:0});let b=0;p=p.slice(0,8).map((w,S)=>{let E=S===0?0:Math.max(b,w.distance);return b=E,{...w,distance:E,childIndex:w.childIndex??S}})}if(Array.isArray(m.ratios)&&m.ratios.length>0){let A=[];for(let b of m.ratios.slice(0,7))typeof b=="number"&&A.push(r(b,.05,1,.5));A.length>0&&(g=A)}if(p.length===0){let A=Array.isArray(m.distances)?m.distances:[],b=[];for(let S of A.slice(0,8))typeof S=="number"&&b.push(r(S,0,1e4,4));if(b.length===0&&g&&g.length>0)for(let S=0;S<g.length;S++)b.push((S+1)*4);if(b.length===0&&m.cullDistance===void 0)return null;b.length===0||b[0]>0?b.unshift(0):g&&g.length===b.length&&g[0]===1&&(g=g.slice(1));let w=0;for(let S=0;S<Math.min(8,b.length);S++){let E=S===0?0:Math.max(w,b[S]);w=E;let N=S>0&&g?g[S-1]:void 0;p.push({distance:E,childIndex:S,...N!==void 0?{ratio:N}:{}})}}else if(!g){let A=[];for(let b=1;b<p.length;b++)typeof p[b].ratio=="number"&&A.push(p[b].ratio);A.length>0&&(g=A)}let x=p.map(A=>A.distance),v=x[x.length-1]??0,y=m.cullDistance!==void 0&&m.cullDistance!==null&&m.cullDistance!==!1?r(m.cullDistance,Math.max(1,v),1e4,100):void 0;return{levels:p,distances:x,...g?{ratios:g}:{},hysteresis:h,...y!==void 0?{cullDistance:y}:{}}}function a(f,m){let h=f?.attributes?.position;if(!h||!h.array||h.count<3)return f;let p=r(m,.05,1,.5),g=h.array,x=h.count,v=f.attributes?.normal?.array,y=f.attributes?.uv?.array,A=f.index?.array,b=Math.floor((A?A.length:x)/3);if(b<1)return f;let w=Math.max(1,Math.min(b,Math.round(b*p))),S=1/0,E=1/0,N=1/0,C=-1/0,_=-1/0,P=-1/0;for(let te=0;te<x;te++){let Z=g[te*3],ae=g[te*3+1],ie=g[te*3+2];Z<S&&(S=Z),ae<E&&(E=ae),ie<N&&(N=ie),Z>C&&(C=Z),ae>_&&(_=ae),ie>P&&(P=ie)}let R=Math.max(1e-5,C-S),I=Math.max(1e-5,_-E),F=Math.max(1e-5,P-N),V=Math.max(R,I,F),Y=te=>{let Z=Math.max(1,Math.round(R/V*te)),ae=Math.max(1,Math.round(I/V*te)),ie=Math.max(1,Math.round(F/V*te)),de=new Map,me=new Int32Array(x),Se=[],ke=[],_e=[],Le=[];for(let O=0;O<x;O++){let X=g[O*3],se=g[O*3+1],ce=g[O*3+2],pe=Math.min(Z-1,Math.max(0,Math.floor((X-S)/R*Z))),xe=Math.min(ae-1,Math.max(0,Math.floor((se-E)/I*ae))),he=Math.min(ie-1,Math.max(0,Math.floor((ce-N)/F*ie))),Ne=pe+xe*Z+he*Z*ae,ge=de.get(Ne);ge===void 0?(ge=Le.length,de.set(Ne,ge),Se.push(X,se,ce),v&&ke.push(v[O*3],v[O*3+1],v[O*3+2]),y&&_e.push(y[O*2],y[O*2+1]),Le.push(1)):(Se[ge*3]+=X,Se[ge*3+1]+=se,Se[ge*3+2]+=ce,v&&(ke[ge*3]+=v[O*3],ke[ge*3+1]+=v[O*3+1],ke[ge*3+2]+=v[O*3+2]),Le[ge]++),me[O]=ge}let ne=[],Re=new Set;for(let O=0;O<b;O++){let X=A?A[O*3]:O*3,se=A?A[O*3+1]:O*3+1,ce=A?A[O*3+2]:O*3+2,pe=me[X],xe=me[se],he=me[ce];if(pe===xe||xe===he||he===pe)continue;let Ne=Math.min(pe,xe,he),ge=Math.max(pe,xe,he),Ae=pe+xe+he-Ne-ge,Ee=`${Ne}_${Ae}_${ge}`;Re.has(Ee)||(Re.add(Ee),ne.push(pe,xe,he))}let W=Le.length,D=new Float32Array(W*3),z=v?new Float32Array(W*3):null;for(let O=0;O<W;O++){let X=1/Le[O];if(D[O*3]=Se[O*3]*X,D[O*3+1]=Se[O*3+1]*X,D[O*3+2]=Se[O*3+2]*X,z){let se=ke[O*3],ce=ke[O*3+1],pe=ke[O*3+2],xe=Math.hypot(se,ce,pe)||1;z[O*3]=se/xe,z[O*3+1]=ce/xe,z[O*3+2]=pe/xe}}return{pos:D,norm:z,uv:y?new Float32Array(_e):null,tris:ne,triCount:ne.length/3,vertCount:W}},J=Math.max(2,Math.round(Math.sqrt(w/4))),re=Y(J);if(re.triCount>w*1.25&&J>2){let te=Math.max(2,Math.round(J*Math.sqrt(w/re.triCount)));if(te!==J){let Z=Y(te);Z.triCount>=Math.min(4,w)&&(re=Z)}}else if(re.triCount<Math.min(4,w)){let te=Y(Math.max(J*2,8));te.triCount>re.triCount&&(re=te)}let Q=re.tris;if(p<1&&re.triCount>w){let te=[],Z=re.triCount/w;for(let ae=0;ae<w;ae++){let ie=Math.min(re.triCount-1,Math.floor(ae*Z));te.push(re.tris[ie*3],re.tris[ie*3+1],re.tris[ie*3+2])}Q=te}if(Q.length<3){Q=[];for(let te=0;te<w*3;te++)Q.push(A?A[te]:te);re={pos:g.slice(),norm:v?v.slice():null,uv:y?y.slice():null,tris:Q,triCount:w,vertCount:x}}let ee=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),k=ee?.BufferGeometry??f.constructor,G=ee?.BufferAttribute??h.constructor,q=new k;q.setAttribute("position",new G(re.pos,3)),re.norm&&q.setAttribute("normal",new G(re.norm,3)),re.uv&&q.setAttribute("uv",new G(re.uv,2));let H=re.vertCount>65535?new Uint32Array(Q):new Uint16Array(Q);return typeof q.setIndex=="function"?q.setIndex(new G(H,1)):q.index=new G(H,1),q}let s=e?.Object3D??t?.threeNamespace?.Object3D??class{constructor(){this.name="",this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0},this.quaternion={x:0,y:0,z:0,w:1},this.scale={x:1,y:1,z:1},this.visible=!0,this.parent=null,this.children=[],this.userData={}}add(...f){for(let m of f)m&&(m.parent=this,this.children.push(m));return this}};class o extends s{constructor(){super(),this.isLOD=!0,this.type="LOD",this.autoUpdate=!0,this.levels=[],this._currentLevel=0}addLevel(m,h=0,p=.05){if(!m)return this;let g=Math.max(0,Number.isFinite(Number(h))?Number(h):0),x=r(p,0,.5,.05),v=this.levels.length;for(let b=0;b<this.levels.length;b++)if(g<this.levels[b].distance){v=b;break}this.levels.splice(v,0,{object:m,distance:g,hysteresis:x}),this.add(m);let y=this.levels.map(b=>b.object),A=this.children.filter(b=>!y.includes(b));this.children=[...y,...A];for(let b=0;b<this.levels.length;b++)this.levels[b].object.visible=b===this._currentLevel;return this.syncUserDataTrait(),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(m){if(!this.levels.length)return null;let h=i(this.levels.map(p=>p.distance),m,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);return h>=0&&h<this.levels.length?this.levels[h].object:null}update(m){if(this.levels.length===0||!m)return;let h=m.position??{x:0,y:0,z:0},p=this.position??{x:0,y:0,z:0},g=Math.hypot((Number(h.x)||0)-(Number(p.x)||0),(Number(h.y)||0)-(Number(p.y)||0),(Number(h.z)||0)-(Number(p.z)||0)),x=i(this.levels.map(v=>v.distance),g,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);this._currentLevel=x;for(let v=0;v<this.levels.length;v++)this.levels[v].object.visible=v===x}syncUserDataTrait(){this.userData=this.userData||{},this.userData.xr=this.userData.xr||{};let m=this.userData.xr.lod?.cullDistance;this.userData.xr.lod={levels:this.levels.map((h,p)=>({distance:h.distance,hysteresis:h.hysteresis,childIndex:p,...h.object?.name?{node:h.object.name}:{}})),distances:this.levels.map(h=>h.distance),hysteresis:this.levels[0]?.hysteresis??.05,...m!==void 0?{cullDistance:m}:{}}}}function l(f){if(!f||f._lodMaterialized||!f.userData?.xr?.lod||f.isLOD||Array.isArray(f.children)&&f.children.length>0)return;let m=f.geometry?.attributes?.position;if(!m||!m.array||m.count<3)return;let h=n(f.userData.xr.lod);if(!h||h.levels.length<2)return;f._lodMaterialized=!0;let p=f.geometry;f._lodOriginalGeometry=p;let g=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),x=g?.Mesh??f.constructor,v=g?.BufferGeometry??p.constructor,y=typeof f.name=="string"&&f.name.trim()?f.name.trim():"Mesh",A=new x(p,f.material);A.name=`${y}_LOD0`,A.visible=!0,A.castShadow=!!f.castShadow,A.receiveShadow=!!f.receiveShadow,f.add(A);for(let b=1;b<h.levels.length;b++){let w=h.levels[b].ratio??h.ratios?.[b-1]??Math.max(.05,Math.pow(.5,b)),S=a(p,w),E=new x(S,f.material);E.name=`${y}_LOD${b}`,E.visible=!1,E.castShadow=!!f.castShadow,E.receiveShadow=!!f.receiveShadow,f.add(E)}f.geometry=new v,f.userData.xr.lod={...h,levels:h.levels.map((b,w)=>({...b,childIndex:w,node:`${y}_LOD${w}`}))}}let c={LOD:o,decimateGeometry:a,selectLodLevelIndex:i,parseLod:n,materializeLodGeometry:l};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,{LOD:o,decimateGeometry:a}),t._lodMaterialize=l,t.materializeDeclarativeGeometry=f=>{t._cadMaterialize?.(f),t._lodMaterialize?.(f),t._procMaterialize?.(f)}),c}var Pn=Tn(),nh=Pn.decimateGeometry,pa=Pn.selectLodLevelIndex,da=Pn.parseLod,Eg=Pn.materializeLodGeometry,ah=Pn.LOD,Nn=new WeakMap;function sh(e){return e&&typeof e=="object"?Nn.get(e):void 0}var wo=class{constructor(e,t){this.groups=[],this.viewer=e,this.gltf=t,this.rebuild()}rebuild(){this.groups.length=0;let e=this.gltf?.nodes;if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let i of this.viewer?.meshes??[])if(typeof i?.nodeIndex=="number"&&i.nodeIndex>=0){let n=t.get(i.nodeIndex);n||(n=[],t.set(i.nodeIndex,n)),n.push(i)}let r=i=>{let n=[],a=new Set,s=[i];for(;s.length>0;){let o=s.pop();if(a.has(o)||o<0||o>=e.length)continue;a.add(o);let l=t.get(o);l&&n.push(...l);let c=e[o]?.children;if(Array.isArray(c))for(let f=c.length-1;f>=0;f--)typeof c[f]=="number"&&s.push(c[f])}return n};for(let i=0;i<e.length;i++){let n=e[i];if(!n||typeof n!="object")continue;let a=n.extras?.xr?.lod??n.extensions?.ANDROID_xr_scenecore?.lod??n.extensions?.MOZ_hubs_components?.lod,s=Array.isArray(n.extensions?.MSFT_lod?.ids)?n.extensions.MSFT_lod.ids.filter(p=>typeof p=="number"&&Number.isInteger(p)&&p>=0&&p<e.length):[],o=da(a);if(!o&&s.length>0&&(o=da({distances:s.map((p,g)=>g*4)})),!o)continue;let l=s.length>0?s:Array.isArray(n.children)?n.children.filter(p=>typeof p=="number"&&Number.isInteger(p)&&p>=0&&p<e.length):[],c=[],f=[];if(l.length>0){let p=Math.min(l.length,o.levels.length);for(let g=0;g<p;g++){let x=l[g];c.push(x),f.push(r(x))}}else{let p=t.get(i)??[];if(p.length===0)continue;c.push(i),f.push(p)}let m=o.distances.slice(0,f.length);m.length===0&&m.push(0);let h={nodeIndex:i,name:typeof n.name=="string"?n.name:`LOD_${i}`,distances:m,hysteresis:o.hysteresis,...o.cullDistance!==void 0?{cullDistance:o.cullDistance}:{},childNodeIndices:c,levelMeshes:f,activeLevelIndex:0,lastDistance:0};this.applyGroupVisibility(h,0),this.groups.push(h)}}getGroups(){return this.groups}getActiveLevel(e){let t=this.findGroup(e);return t?t.activeLevelIndex:null}forceLodLevel(e,t){let r=this.findGroup(e);if(!r)return;if(t==null){r.forcedLevelIndex=null;let n=pa(r.distances,r.lastDistance,r.activeLevelIndex,r.hysteresis,r.cullDistance);r.activeLevelIndex=n,this.applyGroupVisibility(r,n);return}let i=t<0?-1:Math.min(Math.max(0,Math.trunc(t)),r.levelMeshes.length-1);r.forcedLevelIndex=i,r.activeLevelIndex=i,this.applyGroupVisibility(r,i)}findGroup(e){return typeof e=="number"?this.groups.find(t=>t.nodeIndex===e)??this.groups[e]:this.groups.find(t=>t.name===e)}update(e){if(this.groups.length===0)return;let t=this.viewer?.worldMatrices,r=this.viewer?.modelRootMatrix;for(let i of this.groups){let n=Array.isArray(t)&&i.nodeIndex<t.length?t[i.nodeIndex]:null,a=n&&n[12]||0,s=n&&n[13]||0,o=n&&n[14]||0,l=r?r[0]*a+r[4]*s+r[8]*o+r[12]:a,c=r?r[1]*a+r[5]*s+r[9]*o+r[13]:s,f=r?r[2]*a+r[6]*s+r[10]*o+r[14]:o,m=Math.hypot((e[0]||0)-l,(e[1]||0)-c,(e[2]||0)-f);if(i.lastDistance=m,i.forcedLevelIndex!==void 0&&i.forcedLevelIndex!==null){i.activeLevelIndex!==i.forcedLevelIndex&&(i.activeLevelIndex=i.forcedLevelIndex,this.applyGroupVisibility(i,i.forcedLevelIndex));continue}let h=pa(i.distances,m,i.activeLevelIndex,i.hysteresis,i.cullDistance);h!==i.activeLevelIndex&&(i.activeLevelIndex=h,this.applyGroupVisibility(i,h))}}applyGroupVisibility(e,t){let r=this.gltf?.nodes;for(let i=0;i<e.levelMeshes.length;i++){let n=i===t;for(let o of e.levelMeshes[i])o.visible=n;let a=e.childNodeIndices[i],s=Array.isArray(r)?r[a]:null;s&&typeof s=="object"&&(s.visible=n,s.extensions=s.extensions||{},s.extensions.KHR_node_visibility={visible:n})}}},Mo={name:"lod",onRegister(){Mn(Tn);let e=We(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);Tn(t,e)},onLoadModel(e,t){!e||typeof e!="object"||Nn.set(e,new wo(e,t))},onUpdate(e){let t=Nn.get(e);if(!t||typeof e?.getCameraOrbit!="function")return;let r=e.getCameraOrbit(),i=typeof e.getCameraTarget=="function"?e.getCameraTarget():{x:0,y:0,z:0},n=r?.radius??3,a=r?.phi??0,s=r?.theta??0,o=Math.cos(a),l=(i.x||0)+n*o*Math.sin(s),c=(i.y||0)+n*Math.sin(a),f=(i.z||0)+n*o*Math.cos(s);t.update([l,c,f])},onBeforeDrawScene(e,t,r,i){let n=Nn.get(e);n&&n.update(i)},onDestroy(e,t){t&&typeof t=="object"&&Nn.delete(t)}};function ga(e,t){if(!e||!e.Vector3||!e.BufferGeometry)return null;let r=e.Vector3,i=e.Matrix4,n=e.BufferGeometry;if(typeof r.prototype.distanceToSquared!="function"&&(r.prototype.distanceToSquared=function(T){let u=this.x-Number(T?.x??0),d=this.y-Number(T?.y??0),M=this.z-Number(T?.z??0);return u*u+d*d+M*M}),typeof r.prototype.addScalar!="function"&&(r.prototype.addScalar=function(T){let u=Number(T)||0;return this.set(this.x+u,this.y+u,this.z+u)}),typeof r.prototype.applyQuaternion!="function"&&(r.prototype.applyQuaternion=function(T){let u=this.x,d=this.y,M=this.z,L=Number(T?.x)||0,$=Number(T?.y)||0,B=Number(T?.z)||0,U=T?.w===void 0?1:Number(T.w)||0,j=2*($*M-B*d),K=2*(B*u-L*M),ue=2*(L*d-$*u);return this.set(u+U*j+($*ue-B*K),d+U*K+(B*j-L*ue),M+U*ue+(L*K-$*j))}),typeof r.prototype.min!="function"&&(r.prototype.min=function(T){return this.set(Math.min(this.x,T.x),Math.min(this.y,T.y),Math.min(this.z,T.z))}),typeof r.prototype.max!="function"&&(r.prototype.max=function(T){return this.set(Math.max(this.x,T.x),Math.max(this.y,T.y),Math.max(this.z,T.z))}),typeof r.prototype.clamp!="function"&&(r.prototype.clamp=function(T,u){return this.set(Math.max(T.x,Math.min(u.x,this.x)),Math.max(T.y,Math.min(u.y,this.y)),Math.max(T.z,Math.min(u.z,this.z)))}),typeof r.prototype.clampScalar!="function"&&(r.prototype.clampScalar=function(T,u){return this.set(Math.max(T,Math.min(u,this.x)),Math.max(T,Math.min(u,this.y)),Math.max(T,Math.min(u,this.z)))}),typeof r.prototype.negate!="function"&&(r.prototype.negate=function(){return this.multiplyScalar(-1)}),typeof r.prototype.equals!="function"&&(r.prototype.equals=function(T){return!!T&&T.x===this.x&&T.y===this.y&&T.z===this.z}),i&&typeof i.prototype.getMaxScaleOnAxis!="function"&&(i.prototype.getMaxScaleOnAxis=function(){let T=this.elements;return Math.sqrt(Math.max(T[0]*T[0]+T[1]*T[1]+T[2]*T[2],T[4]*T[4]+T[5]*T[5]+T[6]*T[6],T[8]*T[8]+T[9]*T[9]+T[10]*T[10]))}),e.MathUtils&&typeof e.MathUtils=="object"){let T=1234567;try{typeof e.MathUtils.seededRandom!="function"&&(e.MathUtils.seededRandom=u=>{u!==void 0&&(T=Number.isFinite(u)?u|0:0);let d=T=T+1831565813|0;return d=Math.imul(d^d>>>15,d|1),d^=d+Math.imul(d^d>>>7,d|61),((d^d>>>14)>>>0)/4294967296}),typeof e.MathUtils.randInt!="function"&&(e.MathUtils.randInt=(u,d)=>u+Math.floor(Math.random()*(d-u+1))),typeof e.MathUtils.randFloatSpread!="function"&&(e.MathUtils.randFloatSpread=u=>u*(.5-Math.random()))}catch{}}class a{constructor(u,d){this.isBox3=!0,this.min=u!=null?new r(u.x,u.y,u.z):new r(1/0,1/0,1/0),this.max=d!=null?new r(d.x,d.y,d.z):new r(-1/0,-1/0,-1/0)}set(u,d){return this.min.copy(u),this.max.copy(d),this}makeEmpty(){return this.min.set(1/0,1/0,1/0),this.max.set(-1/0,-1/0,-1/0),this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}clone(){return new a(this.min,this.max)}copy(u){return u?(this.min.copy(u.min),this.max.copy(u.max),this):this}expandByPoint(u){if(!u)return this;let d=Number(u.x),M=Number(u.y),L=u.z===void 0?0:Number(u.z);return!Number.isFinite(d)||!Number.isFinite(M)||!Number.isFinite(L)?this:(d<this.min.x&&(this.min.x=d),M<this.min.y&&(this.min.y=M),L<this.min.z&&(this.min.z=L),d>this.max.x&&(this.max.x=d),M>this.max.y&&(this.max.y=M),L>this.max.z&&(this.max.z=L),this)}expandByVector(u){if(this.isEmpty()||!u)return this;let d=Number(u.x),M=Number(u.y),L=Number(u.z);return!Number.isFinite(d)||!Number.isFinite(M)||!Number.isFinite(L)?this:(this.min.set(this.min.x-d,this.min.y-M,this.min.z-L),this.max.set(this.max.x+d,this.max.y+M,this.max.z+L),this.isEmpty()&&this.makeEmpty(),this)}expandByScalar(u){let d=Number(u);return this.isEmpty()||!Number.isFinite(d)?this:(this.min.set(this.min.x-d,this.min.y-d,this.min.z-d),this.max.set(this.max.x+d,this.max.y+d,this.max.z+d),this.isEmpty()&&this.makeEmpty(),this)}setFromArray(u){if(this.makeEmpty(),!u)return this;for(let d=0,M=u.length-2;d<M;d+=3)this.expandByPoint({x:u[d],y:u[d+1],z:u[d+2]});return this}setFromBufferAttribute(u){if(this.makeEmpty(),!u||typeof u.count!="number")return this;for(let d=0;d<u.count;d++)this.expandByPoint({x:u.getX(d),y:u.getY(d),z:u.getZ(d)});return this}setFromPoints(u){if(this.makeEmpty(),Array.isArray(u))for(let d of u)this.expandByPoint(d);return this}setFromCenterAndSize(u,d){if(!u||!d)return this;let M=Math.abs(Number(d.x)||0)*.5,L=Math.abs(Number(d.y)||0)*.5,$=Math.abs(Number(d.z)||0)*.5,B=Number(u.x)||0,U=Number(u.y)||0,j=Number(u.z)||0;return this.min.set(B-M,U-L,j-$),this.max.set(B+M,U+L,j+$),this}setFromObject(u,d){return this.makeEmpty().expandByObject(u,!!d)}expandByObject(u,d){return s(this,u,!!d),this}getCenter(u=new r){return this.isEmpty()?u.set(0,0,0):u.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(u=new r){return this.isEmpty()?u.set(0,0,0):u.subVectors(this.max,this.min)}getParameter(u,d=new r){let M=this.max.x-this.min.x,L=this.max.y-this.min.y,$=this.max.z-this.min.z;return d.set(M!==0?(u.x-this.min.x)/M:0,L!==0?(u.y-this.min.y)/L:0,$!==0?(u.z-this.min.z)/$:0)}containsPoint(u){return!!u&&!this.isEmpty()&&u.x>=this.min.x&&u.x<=this.max.x&&u.y>=this.min.y&&u.y<=this.max.y&&u.z>=this.min.z&&u.z<=this.max.z}containsBox(u){return!!u&&this.min.x<=u.min.x&&u.max.x<=this.max.x&&this.min.y<=u.min.y&&u.max.y<=this.max.y&&this.min.z<=u.min.z&&u.max.z<=this.max.z}intersectsBox(u){return!!u&&u.max.x>=this.min.x&&u.min.x<=this.max.x&&u.max.y>=this.min.y&&u.min.y<=this.max.y&&u.max.z>=this.min.z&&u.min.z<=this.max.z}intersectsSphere(u){return!u||this.isEmpty()||u.isEmpty()?!1:this.clampPoint(u.center,new r).distanceToSquared(u.center)<=u.radius*u.radius}intersectsPlane(u){if(!u?.normal||this.isEmpty())return!1;let d=u.normal.x,M=u.normal.y,L=u.normal.z,$=Number(u.constant)||0,B=(d>0?d*this.min.x:d*this.max.x)+(M>0?M*this.min.y:M*this.max.y)+(L>0?L*this.min.z:L*this.max.z),U=(d>0?d*this.max.x:d*this.min.x)+(M>0?M*this.max.y:M*this.min.y)+(L>0?L*this.max.z:L*this.min.z);return B<=-$&&U>=-$}clampPoint(u,d=new r){return this.isEmpty()?d.copy(u):d.copy(u).clamp(this.min,this.max)}distanceToPoint(u){return this.isEmpty()?1/0:this.clampPoint(u,new r).distanceTo(u)}getBoundingSphere(u=new o){return this.isEmpty()?u.makeEmpty():(this.getCenter(u.center),u.radius=this.getSize(new r).length()*.5,u)}intersect(u){return u?(this.min.max(u.min),this.max.min(u.max),this.isEmpty()&&this.makeEmpty(),this):this}union(u){return!u||u.isEmpty()?this:this.isEmpty()?this.copy(u):(this.min.min(u.min),this.max.max(u.max),this)}applyMatrix4(u){if(this.isEmpty()||!u)return this;let d=this.min.x,M=this.min.y,L=this.min.z,$=this.max.x,B=this.max.y,U=this.max.z,j=new r;this.makeEmpty();for(let K=0;K<8;K++)j.set(K&1?$:d,K&2?B:M,K&4?U:L).applyMatrix4(u),this.expandByPoint(j);return this}translate(u){return this.isEmpty()||!u?this:(this.min.add(u),this.max.add(u),this)}equals(u){return!!u&&u.min.equals(this.min)&&u.max.equals(this.max)}}function s(T,u,d){if(!u)return;u.updateMatrixWorld?.(!0);let M=new r,L=new a,$=new i,B=new i,U=new Set,j=new Map,K=(le,oe)=>{let fe=le?.attributes?.position;if(!(!fe||!(fe.count>0)))if(d)for(let ye=0;ye<fe.count;ye++)M.set(fe.getX(ye),fe.getY(ye),fe.getZ(ye)).applyMatrix4(oe),T.expandByPoint(M);else{let ye=j.get(le);ye||(ye=new a().setFromBufferAttribute(fe),j.set(le,ye)),ye.isEmpty()||T.union(L.copy(ye).applyMatrix4(oe))}},ue=le=>{if(!le||typeof le!="object"||U.has(le)||(U.add(le),t?.materializeDeclarativeGeometry?.(le),le.isBoxHelper&&le!==u))return;(le.isSprite||le.isBox3Helper)&&le._bakeAuthorGeometry?.();let oe=le._sourceGeo||le.geometry;if(oe&&oe.attributes?.position&&le.matrixWorld)if(le.isInstancedMesh&&typeof le.getMatrixAt=="function"){let fe=Math.floor((le.instanceMatrix?.array?.length??0)/16),ye=Math.min(Math.max(0,Math.floor(Number(le.count)||0)),fe);for(let ve=0;ve<ye;ve++)le.getMatrixAt(ve,$),B.multiplyMatrices(le.matrixWorld,$),K(oe,B)}else K(oe,le.matrixWorld);if(Array.isArray(le.children))for(let fe of le.children)ue(fe)};ue(u)}class o{constructor(u,d=-1){this.isSphere=!0,this.center=u!=null?new r(u.x,u.y,u.z):new r;let M=Number(d);this.radius=Number.isFinite(M)?M:-1}set(u,d){u&&this.center.copy(u);let M=Number(d);return this.radius=Number.isFinite(M)?M:-1,this}setFromPoints(u,d){if(!Array.isArray(u)||u.length===0)return this.makeEmpty();if(d)this.center.copy(d);else{let B=new a().setFromPoints(u);if(B.isEmpty())return this.makeEmpty();B.getCenter(this.center)}let M=0,L=!1,$=new r;for(let B of u){let U=Number(B?.x),j=Number(B?.y),K=B?.z===void 0?0:Number(B.z);Number.isFinite(U)&&Number.isFinite(j)&&Number.isFinite(K)&&(L=!0,M=Math.max(M,this.center.distanceToSquared($.set(U,j,K))))}return L?(this.radius=Math.sqrt(M),this):this.makeEmpty()}copy(u){return u?(this.center.copy(u.center),this.radius=u.radius,this):this}clone(){return new o(this.center,this.radius)}isEmpty(){return!(this.radius>=0)||!Number.isFinite(this.radius)}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(u){return!!u&&!this.isEmpty()&&u.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(u){return this.isEmpty()?1/0:u.distanceTo(this.center)-this.radius}intersectsSphere(u){if(!u||this.isEmpty()||u.isEmpty())return!1;let d=this.radius+u.radius;return u.center.distanceToSquared(this.center)<=d*d}intersectsBox(u){return!!u&&u.intersectsSphere(this)}intersectsPlane(u){if(!u?.normal||this.isEmpty())return!1;let d=u.normal.dot(this.center)+(Number(u.constant)||0);return Math.abs(d)<=this.radius}clampPoint(u,d=new r){return d.copy(u),this.isEmpty()||this.center.distanceToSquared(u)>this.radius*this.radius&&d.sub(this.center).normalize().multiplyScalar(this.radius).add(this.center),d}getBoundingBox(u=new a){return this.isEmpty()?u.makeEmpty():(u.set(this.center,this.center),u.expandByScalar(this.radius),u)}applyMatrix4(u){if(this.isEmpty()||!u)return this;let d=u.getMaxScaleOnAxis();return Number.isFinite(d)?(this.center.applyMatrix4(u),this.radius*=d,this):this.makeEmpty()}translate(u){return!this.isEmpty()&&u&&this.center.add(u),this}expandByPoint(u){if(!u||!Number.isFinite(u.x)||!Number.isFinite(u.y)||!Number.isFinite(u.z))return this;if(this.isEmpty())return this.center.copy(u),this.radius=0,this;let d=this.center.distanceToSquared(u);if(d>this.radius*this.radius){let M=Math.sqrt(d),L=(this.radius+M)*.5;this.center.addScaledVector(new r().subVectors(u,this.center),(M-this.radius)/(2*M)),this.radius=L}return this}union(u){if(!u||u.isEmpty())return this;if(this.isEmpty())return this.copy(u);if(this.center.equals(u.center))return this.radius=Math.max(this.radius,u.radius),this;let d=new r().subVectors(u.center,this.center),M=d.length();if(M+u.radius<=this.radius)return this;if(M+this.radius<=u.radius)return this.copy(u);let L=(this.radius+M+u.radius)*.5;return this.center.addScaledVector(d,(L-this.radius)/M),this.radius=L,this}equals(u){return!!u&&u.center.equals(this.center)&&u.radius===this.radius}}n.prototype.computeBoundingSphere=function(){(!this.boundingSphere||!this.boundingSphere.isSphere)&&(this.boundingSphere=new o);let T=this.attributes?.position;if(!T||!(T.count>0))return this.boundingSphere.makeEmpty();let u=new a().setFromBufferAttribute(T);if(u.isEmpty())return this.boundingSphere.makeEmpty();let d=u.getCenter(this.boundingSphere.center),M=0,L=new r;for(let $=0;$<T.count;$++){let B=T.getX($),U=T.getY($),j=T.getZ($);Number.isFinite(B)&&Number.isFinite(U)&&Number.isFinite(j)&&(M=Math.max(M,d.distanceToSquared(L.set(B,U,j))))}return this.boundingSphere.radius=Math.sqrt(M),this.boundingSphere},n.prototype.computeBoundingBox=function(){(!this.boundingBox||!this.boundingBox.isBox3)&&(this.boundingBox=new a);let T=this.attributes?.position;return T&&T.count>0?this.boundingBox.setFromBufferAttribute(T):this.boundingBox.makeEmpty(),this.boundingSphere&&this.computeBoundingSphere(),this.boundingBox};let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=512,f=2048,m=16384,h=256,p="AAAAAAAAAF8AAAAHAAcAFH8UfxQkKn8qEiMTCGRiNklVIlAABQMAAAAcIkEAAEEiHAAUCD4IFAgIPggIAFAwAAAICAgICABgYAAAIBAIBAI+UUlFPgBCf0AAQmFRSUYhQUVLMRgUEn8QJ0VFRTk8SklJMAFxCQUDNklJSTYGSUkpHgA2NgAAAFY2AAAIFCJBABQUFBQUAEEiFAgCAVEJBjJJeUE+fhEREX5/SUlJNj5BQUEif0FBIhx/SUlJQX8JCQkBPkFJSXp/CAgIfwBBf0EAIEBBPwF/CBQiQX9AQEBAfwIMAn9/BAgQfz5BQUE+fwkJCQY+QVEhXn8JGSlGRklJSTEBAX8BAT9AQEA/HyBAIB8/QDhAP2MUCBRjBwhwCAdhUUlFQwB/QUEAAgQIECAAQUF/AAQCAQIEQEBAQEAAAQIEACBUVFR4f0hERDg4REREIDhEREh/OFRUVBgIfgkBAgxSUlI+fwgEBHgARH1AACBARD0AfxAoRAAAQX9AAHwEGAR4fAgEBHg4REREOHwUFBQICBQUGHx8CAQECEhUVFQgBD9EQCA8QEAgfBwgQCAcPEAwQDxEKBAoRAxQUFA8RGRUTEQACDZBAAAAfwAAAEE2CAAIBAgQCA==",g=new Int16Array(128).fill(-1);for(let T=0;T<64;T++)g[l.charCodeAt(T)]=T;let x=(()=>{let T=new Uint8Array(475),u=0,d=0,M=0;for(let L=0;L<p.length&&M<475;L++){let $=p.charCodeAt(L);if($===61)break;let B=$<128?g[$]:-1;B<0||(u=u<<6|B,d+=6,d>=8&&(d-=8,T[M++]=u>>d&255))}return T})(),v=(()=>{let T=new Uint32Array(256);for(let u=0;u<256;u++){let d=u;for(let M=0;M<8;M++)d=d&1?3988292384^d>>>1:d>>>1;T[u]=d>>>0}return T})(),y=T=>{let u=4294967295;for(let d=0;d<T.length;d++)u=v[(u^T[d])&255]^u>>>8;return(u^4294967295)>>>0},A=(()=>{let T=new Float32Array(256);for(let u=0;u<256;u++){let d=u/255;T[u]=d<=.04045?d/12.92:Math.pow((d+.055)/1.055,2.4)}return T})(),b=typeof globalThis<"u"?globalThis.__three_live_native_encode_rgba_png__:void 0,w={};for(let T of"black:000000,white:ffffff,red:ff0000,lime:00ff00,green:008000,blue:0000ff,yellow:ffff00,cyan:00ffff,aqua:00ffff,magenta:ff00ff,fuchsia:ff00ff,silver:c0c0c0,gray:808080,grey:808080,darkgray:a9a9a9,darkgrey:a9a9a9,dimgray:696969,dimgrey:696969,lightgray:d3d3d3,lightgrey:d3d3d3,slategray:708090,slategrey:708090,darkslategray:2f4f4f,darkslategrey:2f4f4f,maroon:800000,olive:808000,purple:800080,teal:008080,navy:000080,orange:ffa500,orangered:ff4500,gold:ffd700,coral:ff7f50,salmon:fa8072,tomato:ff6347,crimson:dc143c,pink:ffc0cb,hotpink:ff69b4,deeppink:ff1493,indigo:4b0082,violet:ee82ee,plum:dda0dd,orchid:da70d6,brown:a52a2a,saddlebrown:8b4513,sienna:a0522d,chocolate:d2691e,peru:cd853f,tan:d2b48c,wheat:f5deb3,beige:f5f5dc,ivory:fffff0,linen:faf0e6,snow:fffafa,khaki:f0e68c,skyblue:87ceeb,deepskyblue:00bfff,dodgerblue:1e90ff,royalblue:4169e1,steelblue:4682b4,turquoise:40e0d0,aquamarine:7fffd4,chartreuse:7fff00,forestgreen:228b22,seagreen:2e8b57".split(",")){let[u,d]=T.split(":");w[u]=parseInt(d,16)}let S=T=>T>0?T<255?T+.5|0:255:0,E=T=>{let u=T.trim();return u.endsWith("%")?S(parseFloat(u)*255/100):S(parseFloat(u))},N=T=>{if(!T)return 255;let u=T.trim();if(!u)return 255;let d=u.endsWith("%")?parseFloat(u)/100:parseFloat(u);return Number.isFinite(d)?S(Math.max(0,Math.min(1,d))*255):255},C=(T,u=[0,0,0,255])=>{if(typeof T!="string")return u;let d=T.trim().toLowerCase();if(!d)return u;if(d==="transparent")return[0,0,0,0];if(d.charCodeAt(0)===35){let ve=d.slice(1);if(ve.length===3||ve.length===4){let we=parseInt(ve[0]+ve[0],16),Te=parseInt(ve[1]+ve[1],16),Me=parseInt(ve[2]+ve[2],16),be=ve.length===4?parseInt(ve[3]+ve[3],16):255;if(Number.isFinite(we+Te+Me+be))return[we,Te,Me,be]}else if(ve.length===6||ve.length===8){let we=parseInt(ve.slice(0,2),16),Te=parseInt(ve.slice(2,4),16),Me=parseInt(ve.slice(4,6),16),be=ve.length===8?parseInt(ve.slice(6,8),16):255;if(Number.isFinite(we+Te+Me+be))return[we,Te,Me,be]}return u}let M=w[d];if(M!==void 0)return[M>>16&255,M>>8&255,M&255,255];let L=/^(rgba?|hsla?)\(([^)]+)\)$/.exec(d);if(!L)return u;let $=L[1],B=L[2].replace(/\//g," ").split(/[\s,]+/).filter(Boolean);if(B.length<3)return u;if($.startsWith("rgb"))return[E(B[0]),E(B[1]),E(B[2]),N(B[3])];let U=parseFloat(B[0]);if(!Number.isFinite(U))return u;B[0].endsWith("turn")?U*=360:B[0].endsWith("rad")&&(U=U*180/Math.PI);let j=(U%360+360)%360/360,K=Math.max(0,Math.min(1,(parseFloat(B[1])||0)/100)),ue=Math.max(0,Math.min(1,(parseFloat(B[2])||0)/100)),le=N(B[3]);if(K===0){let ve=S(ue*255);return[ve,ve,ve,le]}let oe=ue<.5?ue*(1+K):ue+K-ue*K,fe=2*ue-oe,ye=ve=>{let we=ve;return we<0&&(we+=1),we>1&&(we-=1),we<1/6?fe+(oe-fe)*6*we:we<1/2?oe:we<2/3?fe+(oe-fe)*(2/3-we)*6:fe};return[S(ye(j+1/3)*255),S(ye(j)*255),S(ye(j-1/3)*255),le]},_=(T,u,d,M,L,$=c)=>{if(!T||u<=0||d<=0||T.length<u*d*4)return{uri:"",avgColor:[1,1,1,1]};if(typeof b=="function"){let Oe=b(T,u,d,M,L,$);if(Array.isArray(Oe)&&typeof Oe[0]=="string")return{uri:Oe[0],avgColor:[Oe[1],Oe[2],Oe[3],Oe[4]]}}let B=u>$||d>$?$/Math.max(u,d):1,U=Math.max(1,Math.round(u*B)),j=Math.max(1,Math.round(d*B)),K=1+U*4,ue=j*K,le=2+Math.max(1,Math.ceil(ue/65535))*5+ue+4,oe=new Uint8Array(57+le),fe=new DataView(oe.buffer);fe.setUint32(0,2303741511),fe.setUint32(4,218765834),fe.setUint32(8,13),fe.setUint32(12,1229472850),fe.setUint32(16,U),fe.setUint32(20,j),oe[24]=8,oe[25]=6,fe.setUint32(29,y(oe.subarray(12,29))),fe.setUint32(33,le),fe.setUint32(37,1229209940),oe[41]=120,oe[42]=1;let ye=new Uint8Array(ue),ve=0,we=1,Te=0,Me=0,be=0,Ce=0,Ie=0,ze=U===u&&j===d;for(let Oe=0;Oe<j;Oe++){ye[ve++]=0,Te=(Te+we)%65521;let Xe=M?j-1-Oe:Oe,rt=ze?Xe:Math.floor(Xe*d/j),yt=ze?Xe+1:Math.max(rt+1,Math.floor((Xe+1)*d/j));for(let pt=0;pt<U;pt++){let ot=0,bt=0,St=0,dt=0;if(ze){let gt=(rt*u+pt)*4;ot=T[gt]|0,bt=T[gt+1]|0,St=T[gt+2]|0,dt=T[gt+3]|0}else{let gt=Math.floor(pt*u/U),Bt=Math.max(gt+1,Math.floor((pt+1)*u/U)),Nt=0;for(let Vt=rt;Vt<yt&&Vt<d;Vt++)for(let Et=gt;Et<Bt&&Et<u;Et++){let qt=(Vt*u+Et)*4;ot+=T[qt]|0,bt+=T[qt+1]|0,St+=T[qt+2]|0,dt+=T[qt+3]|0,Nt++}Nt>1&&(ot=ot/Nt+.5|0,bt=bt/Nt+.5|0,St=St/Nt+.5|0,dt=dt/Nt+.5|0)}ye[ve++]=ot,we+=ot,Te+=we,ye[ve++]=bt,we+=bt,Te+=we,ye[ve++]=St,we+=St,Te+=we,ye[ve++]=dt,we+=dt,Te+=we,Me+=L?ot/255:A[ot],be+=L?bt/255:A[bt],Ce+=L?St/255:A[St],Ie+=dt/255}we%=65521,Te%=65521}let Ue=43,He=ue,Ke=0;for(;He>0||Ke===0;){let Oe=Math.min(65535,He),Xe=He-Oe===0?1:0;if(oe[Ue++]=Xe,fe.setUint16(Ue,Oe,!0),fe.setUint16(Ue+2,~Oe&65535,!0),Ue+=4,Oe>0&&(oe.set(ye.subarray(Ke,Ke+Oe),Ue),Ue+=Oe,Ke+=Oe,He-=Oe),Xe)break}fe.setUint32(Ue,(Te<<16|we)>>>0),Ue+=4,fe.setUint32(Ue,y(oe.subarray(37,Ue))),Ue+=4,fe.setUint32(Ue,0),fe.setUint32(Ue+4,1229278788),fe.setUint32(Ue+8,2923585666);let et=Math.max(1,U*j),Qe=[Me/et,be/et,Ce/et,Ie/et],tt=["data:image/png;base64,"];for(let Oe=0;Oe<oe.length;Oe+=3){let Xe=oe[Oe]<<16|(oe[Oe+1]??0)<<8|(oe[Oe+2]??0);tt.push(l[Xe>>18&63]+l[Xe>>12&63]+(Oe+1<oe.length?l[Xe>>6&63]:"=")+(Oe+2<oe.length?l[Xe&63]:"="))}return{uri:tt.join(""),avgColor:Qe}},P=(T,u,d,M)=>(T&255|(u&255)<<8|(d&255)<<16|(M&255)<<24)>>>0,R=T=>{if(T._lut)return T._lut;let u=new Uint32Array(256),d=T.s;if(d.length===1){let M=d[0].c;u.fill(P(M[0],M[1],M[2],M[3]))}else if(d.length>1){let M=0;for(let L=0;L<256;L++){let $=L/255;if($<=d[0].o){let B=d[0].c;u[L]=P(B[0],B[1],B[2],B[3])}else if($>=d[d.length-1].o){let B=d[d.length-1].c;u[L]=P(B[0],B[1],B[2],B[3])}else{for(;M<d.length-2&&$>d[M+1].o;)M++;let B=d[M],U=d[M+1],j=U.o-B.o,K=j>1e-9?($-B.o)/j:0;u[L]=P(B.c[0]+(U.c[0]-B.c[0])*K+.5|0,B.c[1]+(U.c[1]-B.c[1])*K+.5|0,B.c[2]+(U.c[2]-B.c[2])*K+.5|0,B.c[3]+(U.c[3]-B.c[3])*K+.5|0)}}}return T._lut=u,u},I=(T,u,d)=>{if(T.s.length===0)return 0;let M=R(T),L=0;if(T.rad){let B=T.x1-T.x0,U=T.y1-T.y0,j=T.r1-T.r0,K=u-T.x0,ue=d-T.y0,le=B*B+U*U-j*j,oe=-2*(K*B+ue*U+T.r0*j),fe=K*K+ue*ue-T.r0*T.r0;if(Math.abs(le)<1e-9)L=Math.abs(oe)>1e-9?-fe/oe:0;else{let ye=Math.sqrt(Math.max(0,oe*oe-4*le*fe)),ve=(-oe+ye)/(2*le),we=(-oe-ye)/(2*le);L=T.r0+ve*j>=0?ve:T.r0+we*j>=0?we:Math.max(ve,we)}}else{let B=T.x1-T.x0,U=T.y1-T.y0,j=B*B+U*U;if(j<=1e-12)return M[255];L=((u-T.x0)*B+(d-T.y0)*U)/j}let $=L<=0?0:L>=1?255:L*255+.5|0;return M[$]};class F{constructor(u,d,M,L,$,B,U){this._g=1,this.rad=u,this.x0=Number(d)||0,this.y0=Number(M)||0,this.r0=Math.max(0,Number(L)||0),this.x1=Number($)||0,this.y1=Number(B)||0,this.r1=Math.max(0,Number(U)||0),this.s=[],this._lut=null}addColorStop(u,d){let M=Math.max(0,Math.min(1,Number(u)||0));this.s.push({o:M,c:C(d,[0,0,0,255]),i:this.s.length}),this.s.sort((L,$)=>L.o-$.o||L.i-$.i),this._lut=null}}class V{constructor(u,d,M,L){this._g=2,this.d=u,this.w=Math.max(1,d|0),this.h=Math.max(1,M|0);let $=(L||"repeat").toLowerCase();this.rx=$==="repeat"||$==="repeat-x",this.ry=$==="repeat"||$==="repeat-y"}}let Y=(T,u,d)=>{let M=Math.floor(u),L=Math.floor(d);if(T.rx)M=(M%T.w+T.w)%T.w;else if(M<0||M>=T.w)return 0;if(T.ry)L=(L%T.h+T.h)%T.h;else if(L<0||L>=T.h)return 0;let $=(L*T.w+M)*4;return P(T.d[$],T.d[$+1],T.d[$+2],T.d[$+3])},J=T=>T>=32&&T<=126?T:T===176?39:T===8226||T===183?42:T===8211||T===8212||T===8722?45:T===215?120:T===8216||T===8217?39:T===8220||T===8221?34:63,re=new Array(190),Q=(T,u)=>{let d=(T-32)*2+(u?1:0),M=re[d];if(M)return M;let L=new Uint8Array(63),$=(T-32)*5;for(let U=0;U<5;U++){let j=x[$+U]??0;for(let K=0;K<7;K++)j>>K&1&&(L[(K+1)*7+(U+1)]=1)}let B=new Uint8Array(140);for(let U=0;U<7;U++)for(let j=0;j<5;j++){let K=(U+1)*7+(j+1),ue=L[K],le=L[K-7],oe=L[K+1],fe=L[K-1],ye=L[K+7],ve=U*2,we=j*2;B[ve*10+we]=fe===le&&fe!==ye&&le!==oe?le:ue,B[ve*10+we+1]=le===oe&&le!==fe&&oe!==ye?oe:ue,B[(ve+1)*10+we]=ye===fe&&ye!==oe&&fe!==le?fe:ue,B[(ve+1)*10+we+1]=oe===ye&&oe!==le&&ye!==fe?ye:ue}if(u)for(let U=0;U<14;U++)for(let j=9;j>=1;j--)B[U*10+j-1]&&(B[U*10+j]=1);return re[d]=B,B},ee=T=>{let u=String(T||"10px sans-serif"),d=/\b(bold|bolder|[6-9]00)\b/i.test(u),M=/(\d+(?:\.\d+)?)\s*(px|pt|em|rem)\b/i.exec(u);if(!M)return{sizePx:10,bold:d};let L=parseFloat(M[1]),$=M[2].toLowerCase();return $==="pt"?L*=4/3:($==="em"||$==="rem")&&(L*=16),{sizePx:Number.isFinite(L)&&L>0?Math.min(1024,L):10,bold:d}},k=T=>{T.fillStyle="#000000",T.strokeStyle="#000000",T.globalAlpha=1,T.globalCompositeOperation="source-over",T.lineWidth=1,T.lineCap="butt",T.lineJoin="miter",T.lineDashOffset=0,T.font="10px sans-serif",T.textAlign="start",T.textBaseline="alphabetic",T.shadowColor="rgba(0, 0, 0, 0)",T.shadowBlur=0,T.shadowOffsetX=0,T.shadowOffsetY=0,T._m=[1,0,0,1,0,0],T._dash=[],T._clip=null,T._stack=[],T._subs=[],T._cur=null,T._pts=0},G=(T,u,d)=>{let M=T._m;return[(M[0]*u+M[2]*d+M[4])*T.canvas._sx,(M[1]*u+M[3]*d+M[5])*T.canvas._sy]},q=T=>{let u=T.canvas._sx>0?1/T.canvas._sx:1,d=T.canvas._sy>0?1/T.canvas._sy:1,M=T._m,L=M[0]*M[3]-M[1]*M[2];if(Math.abs(L)<1e-12)return[0,0,0,0,0,0];let $=1/L;return[M[3]*u*$,-M[2]*d*$,(-M[3]*M[4]+M[2]*M[5])*$,-M[1]*u*$,M[0]*d*$,(M[1]*M[4]-M[0]*M[5])*$]},H=(T,u,d)=>{let[M,L,$,B,U,j]=q(T);return[M*u+L*d+$,B*u+U*d+j]},te=T=>{let u=String(T.globalCompositeOperation||"source-over").toLowerCase();return u==="source-over"?0:u==="copy"?1:u==="destination-out"?2:u==="lighter"||u==="add"?3:u==="multiply"?4:u==="screen"?5:0},Z=(T,u,d)=>{T._pts>=m||!T._cur||(T._cur.pts.push([u,d]),T._pts++)},ae=(T,u)=>{let d=Number(T.globalAlpha),M=Number.isFinite(d)?Math.max(0,Math.min(1,d)):1,L=Math.round(M*256);if(typeof u=="string"){let U=C(u,[0,0,0,255]),j=P(U[0],U[1],U[2],U[3]*L+128>>8);return()=>j}let $=u?u._g:0;if($===1||$===2){let[U,j,K,ue,le,oe]=q(T);return(fe,ye)=>{let ve=U*fe+j*ye+K,we=ue*fe+le*ye+oe,Te=$===1?I(u,ve,we):Y(u,ve,we);if(L>=256)return Te;let Me=(Te>>>24)*L+128>>8&255;return(Te&16777215|Me<<24)>>>0}}let B=P(0,0,0,255*L+128>>8);return()=>B},ie=(T,u,d,M,L)=>{let $=T.canvas._bw,B=T.canvas._bh;if(d<0||d>=$||M<0||M>=B)return;let U=M*$+d;if(T._clip&&!T._clip[U])return;let j=T.canvas._data,K=U*4,ue=L&255,le=L>>>8&255,oe=L>>>16&255,fe=L>>>24;if(u===1){j[K]=ue,j[K+1]=le,j[K+2]=oe,j[K+3]=fe;return}if(fe<=0)return;if(fe>=255&&u===0){j[K]=ue,j[K+1]=le,j[K+2]=oe,j[K+3]=255;return}if(u===2){j[K+3]=(j[K+3]*(255-fe)+127)/255|0,j[K+3]===0&&(j[K]=j[K+1]=j[K+2]=0);return}if(u===3){j[K]=Math.min(255,j[K]+((ue*fe+127)/255|0)),j[K+1]=Math.min(255,j[K+1]+((le*fe+127)/255|0)),j[K+2]=Math.min(255,j[K+2]+((oe*fe+127)/255|0)),j[K+3]=Math.min(255,j[K+3]+fe);return}let ye=j[K+3],ve=fe/255,we=ye/255,Te=ve+we*(1-ve);if(Te<=1e-6){j[K]=j[K+1]=j[K+2]=j[K+3]=0;return}let Me=ue,be=le,Ce=oe;u===4&&ye>0?(Me=(Me*j[K]+127)/255,be=(be*j[K+1]+127)/255,Ce=(Ce*j[K+2]+127)/255):u===5&&ye>0&&(Me=255-(255-Me)*(255-j[K])/255,be=255-(255-be)*(255-j[K+1])/255,Ce=255-(255-Ce)*(255-j[K+2])/255),j[K]=S((Me*ve+j[K]*we*(1-ve))/Te),j[K+1]=S((be*ve+j[K+1]*we*(1-ve))/Te),j[K+2]=S((Ce*ve+j[K+2]*we*(1-ve))/Te),j[K+3]=S(Te*255)},de=(T,u,d,M)=>{if(T.canvas.width<=0||T.canvas.height<=0)return;let L=T.canvas._bw,$=T.canvas._bh,B=[],U=$,j=-1;for(let ye of u){let ve=ye.pts,we=ve.length;if(!(we<2))for(let Te=0;Te<we;Te++){let[Me,be]=ve[Te],[Ce,Ie]=ve[(Te+1)%we];if(be===Ie)continue;let ze=Math.min(be,Ie),Ue=Math.max(be,Ie);B.push([ze,Ue,Ie>be?Me:Ce,(Ie>be?Ce-Me:Me-Ce)/(Ue-ze),Ie>be?1:-1]),ze<U&&(U=ze),Ue>j&&(j=Ue)}}if(B.length===0)return;let K=Math.max(0,Math.floor(U)),ue=Math.min($-1,Math.ceil(j)),le=d==="evenodd",oe=(ye,ve,we)=>{for(let Te=ve;Te<=we;Te++)M(Te,ye)},fe=[];for(let ye=K;ye<=ue;ye++){let ve=ye+.5;fe.length=0;for(let we=0;we<B.length;we++){let Te=B[we];Te[0]<=ve&&Te[1]>ve&&fe.push([Te[2]+(ve-Te[0])*Te[3],Te[4]])}if(!(fe.length<2))if(fe.sort((we,Te)=>we[0]-Te[0]),le)for(let we=0;we+1<fe.length;we+=2)oe(ye,Math.max(0,Math.ceil(fe[we][0]-.5)),Math.min(L-1,Math.floor(fe[we+1][0]-.5)));else{let we=0,Te=0;for(let Me=0;Me<fe.length;Me++){let be=we;we+=fe[Me][1],be===0&&we!==0?Te=fe[Me][0]:be!==0&&we===0&&oe(ye,Math.max(0,Math.ceil(Te-.5)),Math.min(L-1,Math.floor(fe[Me][0]-.5)))}}}},me=(T,u,d,M,L,$)=>{if(!Number.isFinite(d+M)||T.canvas.width<=0||T.canvas.height<=0)return;let B=String(u??"").slice(0,1024);if(!B)return;let U=Array.from(B),{sizePx:j,bold:K}=ee(T.font),ue=j,le=j*(K?.54:.5),oe=j*(K?.64:.6),fe=U.length*oe-j*.1,ye=1;if(L!==void 0&&Number.isFinite(L)){if(L<=0)return;fe>L&&fe>0&&(ye=L/fe)}let ve=fe*ye,we=d;T.textAlign==="center"?we-=ve*.5:(T.textAlign==="right"||T.textAlign==="end")&&(we-=ve);let Te=M,Me=T.textBaseline;Me==="middle"?Te-=ue*.5:Me==="bottom"||Me==="ideographic"?Te-=ue:Me==="alphabetic"?Te-=ue*.82:Me==="hanging"&&(Te-=ue*.08);let be=ae(T,$?T.strokeStyle:T.fillStyle),Ce=te(T),[Ie,ze,Ue,He,Ke,et]=q(T),Qe=T.canvas._bw,tt=T.canvas._bh,Oe=new Uint8Array(Qe*tt),Xe=le*ye;if(Xe<=1e-6||ue<=1e-6)return;let rt=1/Xe,yt=1/ue;for(let pt=0;pt<U.length;pt++){let ot=J(U[pt].codePointAt(0)??32);if(ot===32)continue;let bt=we+pt*oe*ye,St=Q(ot,K),dt=G(T,bt,Te),gt=G(T,bt+Xe,Te),Bt=G(T,bt+Xe,Te+ue),Nt=G(T,bt,Te+ue),Vt=Math.max(0,Math.floor(Math.min(dt[0],gt[0],Bt[0],Nt[0]))),Et=Math.min(Qe-1,Math.ceil(Math.max(dt[0],gt[0],Bt[0],Nt[0]))),qt=Math.max(0,Math.floor(Math.min(dt[1],gt[1],Bt[1],Nt[1]))),tr=Math.min(tt-1,Math.ceil(Math.max(dt[1],gt[1],Bt[1],Nt[1])));for(let Mr=qt;Mr<=tr;Mr++){let mr=Mr+.5;for(let qr=Vt;qr<=Et;qr++){let Di=Mr*Qe+qr;if(Oe[Di])continue;let Mi=qr+.5,dn=Ie*Mi+ze*mr+Ue,gn=He*Mi+Ke*mr+et,Wr=(dn-bt)*rt,Kr=(gn-Te)*yt;if(Wr<0||Wr>=1||Kr<0||Kr>=1)continue;let pr=Math.min(9,Wr*10|0),dr=Math.min(13,Kr*14|0);St[dr*10+pr]===1&&($&&pr>0&&pr<9&&dr>0&&dr<13&&St[dr*10+pr-1]&&St[dr*10+pr+1]&&St[(dr-1)*10+pr]&&St[(dr+1)*10+pr]||(Oe[Di]=1,ie(T,Ce,qr,Mr,be(Mi,mr))))}}}T.canvas._ver++};class Se{constructor(u){this.canvas=u,k(this)}save(){this._stack.length>=h||this._stack.push([this._m.slice(),this.fillStyle,this.strokeStyle,this.globalAlpha,this.globalCompositeOperation,this.lineWidth,this.lineCap,this.lineJoin,this._dash.slice(),this.lineDashOffset,this.font,this.textAlign,this.textBaseline,this.shadowColor,this.shadowBlur,this.shadowOffsetX,this.shadowOffsetY,this._clip?new Uint8Array(this._clip):null])}restore(){let u=this._stack.pop();u&&([this._m,this.fillStyle,this.strokeStyle,this.globalAlpha,this.globalCompositeOperation,this.lineWidth,this.lineCap,this.lineJoin,this._dash,this.lineDashOffset,this.font,this.textAlign,this.textBaseline,this.shadowColor,this.shadowBlur,this.shadowOffsetX,this.shadowOffsetY,this._clip]=u)}setLineDash(u){if(!Array.isArray(u))return;let d=[];for(let M=0;M<Math.min(64,u.length);M++){let L=Number(u[M]);if(!Number.isFinite(L)||L<0)return;d.push(L)}this._dash=d.length%2===1?[...d,...d]:d}getLineDash(){return[...this._dash]}resetTransform(){this._m=[1,0,0,1,0,0]}setTransform(u,d,M,L,$,B){if(u&&typeof u=="object"){this.setTransform(u.a??1,u.b??0,u.c??0,u.d??1,u.e??0,u.f??0);return}let U=Number(u??1),j=Number(d??0),K=Number(M??0),ue=Number(L??1),le=Number($??0),oe=Number(B??0);Number.isFinite(U+j+K+ue+le+oe)&&(this._m=[U,j,K,ue,le,oe])}getTransform(){let u=this._m;return{a:u[0],b:u[1],c:u[2],d:u[3],e:u[4],f:u[5]}}transform(u,d,M,L,$,B){if(!Number.isFinite(u+d+M+L+$+B))return;let U=this._m;this._m=[U[0]*u+U[2]*d,U[1]*u+U[3]*d,U[0]*M+U[2]*L,U[1]*M+U[3]*L,U[0]*$+U[2]*B+U[4],U[1]*$+U[3]*B+U[5]]}translate(u,d){this.transform(1,0,0,1,u,d)}rotate(u){if(!Number.isFinite(u))return;let d=Math.cos(u),M=Math.sin(u);this.transform(d,M,-M,d,0,0)}scale(u,d){this.transform(u,0,0,d,0,0)}createLinearGradient(u,d,M,L){return new F(!1,u,d,0,M,L,0)}createRadialGradient(u,d,M,L,$,B){return new F(!0,u,d,M,L,$,B)}createPattern(u,d="repeat"){let M=Le(u);return M?new V(M.data,M.width,M.height,d):null}beginPath(){this._subs.length=0,this._cur=null,this._pts=0}closePath(){if(this._cur&&this._cur.pts.length>0){this._cur.closed=!0;let u=this._cur.pts[0];this._cur={pts:[[u[0],u[1]]],closed:!1},this._subs.push(this._cur)}}moveTo(u,d){Number.isFinite(u+d)&&(this._cur={pts:[G(this,u,d)],closed:!1},this._subs.push(this._cur),this._pts++)}lineTo(u,d){if(!Number.isFinite(u+d))return;if(!this._cur||this._cur.pts.length===0){this.moveTo(u,d);return}let M=G(this,u,d);Z(this,M[0],M[1])}rect(u,d,M,L){Number.isFinite(u+d+M+L)&&(this.moveTo(u,d),this.lineTo(u+M,d),this.lineTo(u+M,d+L),this.lineTo(u,d+L),this.closePath())}roundRect(u,d,M,L,$){if(!Number.isFinite(u+d+M+L))return;M<0&&(u+=M,M=-M),L<0&&(d+=L,L=-L);let B=Array.isArray($)?$:$!==void 0?[$]:[0],U=fe=>{let ye=Number(fe&&typeof fe=="object"?fe.x??0:fe??0);return Number.isFinite(ye)?Math.max(0,ye):0},j=U(B[0]),K=U(B[1]??B[0]),ue=U(B[2]??B[0]),le=U(B[3]??B[1]??B[0]),oe=Math.min(1,M/Math.max(1e-6,j+K),M/Math.max(1e-6,le+ue),L/Math.max(1e-6,j+le),L/Math.max(1e-6,K+ue));if(j*=oe,K*=oe,ue*=oe,le*=oe,j+K+ue+le<=1e-4){this.rect(u,d,M,L);return}this.moveTo(u+j,d),this.lineTo(u+M-K,d),K>0&&this.arc(u+M-K,d+K,K,-Math.PI/2,0),this.lineTo(u+M,d+L-ue),ue>0&&this.arc(u+M-ue,d+L-ue,ue,0,Math.PI/2),this.lineTo(u+le,d+L),le>0&&this.arc(u+le,d+L-le,le,Math.PI/2,Math.PI),this.lineTo(u,d+j),j>0&&this.arc(u+j,d+j,j,Math.PI,Math.PI*3/2),this.closePath()}quadraticCurveTo(u,d,M,L){if(!Number.isFinite(u+d+M+L))return;(!this._cur||this._cur.pts.length===0)&&this.moveTo(u,d);let $=this._cur.pts,[B,U]=$[$.length-1],[j,K]=G(this,u,d),[ue,le]=G(this,M,L),oe=Math.max(4,Math.min(64,Math.ceil((Math.hypot(j-B,K-U)+Math.hypot(ue-j,le-K))*.5)));for(let fe=1;fe<=oe;fe++){let ye=fe/oe,ve=1-ye;Z(this,ve*ve*B+2*ve*ye*j+ye*ye*ue,ve*ve*U+2*ve*ye*K+ye*ye*le)}}bezierCurveTo(u,d,M,L,$,B){if(!Number.isFinite(u+d+M+L+$+B))return;(!this._cur||this._cur.pts.length===0)&&this.moveTo(u,d);let U=this._cur.pts,[j,K]=U[U.length-1],[ue,le]=G(this,u,d),[oe,fe]=G(this,M,L),[ye,ve]=G(this,$,B),we=Math.max(6,Math.min(64,Math.ceil((Math.hypot(ue-j,le-K)+Math.hypot(oe-ue,fe-le)+Math.hypot(ye-oe,ve-fe))*.4)));for(let Te=1;Te<=we;Te++){let Me=Te/we,be=1-Me,Ce=be*be,Ie=Me*Me;Z(this,Ce*be*j+3*Ce*Me*ue+3*be*Ie*oe+Ie*Me*ye,Ce*be*K+3*Ce*Me*le+3*be*Ie*fe+Ie*Me*ve)}}ellipse(u,d,M,L,$=0,B=0,U=Math.PI*2,j=!1){if(!Number.isFinite(u+d+M+L+$+B+U))return;let K=Math.max(0,M),ue=Math.max(0,L),le=Math.PI*2,oe=U-B;if(!j)oe>=le?oe=le:oe<0&&(oe=(oe%le+le)%le);else if(oe<=-le)oe=-le;else if(oe>0){let Te=oe%le;oe=Te===0?0:Te-le}let fe=Math.cos($),ye=Math.sin($),ve=Math.hypot(this._m[0]*this.canvas._sx,this._m[1]*this.canvas._sy,this._m[2]*this.canvas._sx,this._m[3]*this.canvas._sy),we=Math.max(8,Math.min(96,Math.ceil(Math.abs(oe)*Math.max(1,K,ue)*ve/3)));for(let Te=0;Te<=we;Te++){let Me=B+oe*Te/we,be=K*Math.cos(Me),Ce=ue*Math.sin(Me),Ie=u+be*fe-Ce*ye,ze=d+be*ye+Ce*fe;Te===0&&(!this._cur||this._cur.pts.length===0)?this.moveTo(Ie,ze):this.lineTo(Ie,ze)}}arc(u,d,M,L,$,B=!1){this.ellipse(u,d,M,M,0,L,$,B)}arcTo(u,d,M,L,$){if(!Number.isFinite(u+d+M+L+$))return;let B=Math.max(0,$);if(!this._cur||this._cur.pts.length===0){this.moveTo(u,d);return}if(B<=1e-6){this.lineTo(u,d);return}let U=this._cur.pts,[j,K]=U[U.length-1],[ue,le]=H(this,j,K),oe=ue-u,fe=le-d,ye=M-u,ve=L-d,we=Math.hypot(oe,fe),Te=Math.hypot(ye,ve);if(we<1e-6||Te<1e-6){this.lineTo(u,d);return}let Me=oe/we,be=fe/we,Ce=ye/Te,Ie=ve/Te,ze=Me*Ie-be*Ce;if(Math.abs(ze)<1e-6){this.lineTo(u,d);return}let Ue=Math.acos(Math.max(-1,Math.min(1,Me*Ce+be*Ie)))*.5,He=B/Math.tan(Ue),Ke=Me+Ce,et=be+Ie,Qe=Math.hypot(Ke,et)||1,tt=B/Math.sin(Ue),Oe=u+Ke/Qe*tt,Xe=d+et/Qe*tt;this.arc(Oe,Xe,B,Math.atan2(d+be*He-Xe,u+Me*He-Oe),Math.atan2(d+Ie*He-Xe,u+Ce*He-Oe),ze>0)}fill(u){if(this.canvas.width<=0||this.canvas.height<=0)return;let d=ae(this,this.fillStyle),M=te(this);de(this,this._subs,typeof u=="string"?u:"nonzero",(L,$)=>ie(this,M,L,$,d(L+.5,$+.5))),this.canvas._ver++}clip(u){let d=this.canvas._bw,M=this.canvas._bh,L=new Uint8Array(d*M);if(de(this,this._subs,typeof u=="string"?u:"nonzero",($,B)=>{L[B*d+$]=1}),this._clip)for(let $=0;$<L.length;$++)L[$]&=this._clip[$];this._clip=L}stroke(){if(this.canvas.width<=0||this.canvas.height<=0)return;let u=this._m,d=(Math.hypot(u[0]*this.canvas._sx,u[1]*this.canvas._sy)+Math.hypot(u[2]*this.canvas._sx,u[3]*this.canvas._sy))*.5,M=Number(this.lineWidth),L=Number.isFinite(M)&&M>0?M:1,$=Math.max(.5,L*d*.5),B=$*$,U=this.lineCap,j=this.canvas._bw,K=this.canvas._bh,ue=ae(this,this.strokeStyle),le=te(this),oe=new Uint8Array(j*K),fe=0,ye=[];for(let Me=0;Me<this._dash.length;Me++){let be=this._dash[Me]*d;ye.push(be),fe+=be}let ve=(Me,be,Ce,Ie,ze,Ue)=>{let He=Me,Ke=be,et=Ce,Qe=Ie,tt=et-He,Oe=Qe-Ke,Xe=Math.hypot(tt,Oe);if(U==="square"&&Xe>1e-6){let dt=tt/Xe*$,gt=Oe/Xe*$;ze&&(He-=dt,Ke-=gt),Ue&&(et+=dt,Qe+=gt),tt=et-He,Oe=Qe-Ke}let rt=tt*tt+Oe*Oe,yt=$+.5,pt=Math.max(0,Math.floor(Math.min(He,et)-yt)),ot=Math.min(j-1,Math.ceil(Math.max(He,et)+yt)),bt=Math.max(0,Math.floor(Math.min(Ke,Qe)-yt)),St=Math.min(K-1,Math.ceil(Math.max(Ke,Qe)+yt));for(let dt=bt;dt<=St;dt++){let gt=dt+.5;for(let Bt=pt;Bt<=ot;Bt++){let Nt=dt*j+Bt;if(oe[Nt])continue;let Vt=Bt+.5,Et=rt>1e-9?((Vt-He)*tt+(gt-Ke)*Oe)/rt:0;if(U==="butt"&&(Et<0&&ze||Et>1&&Ue))continue;Et=Math.max(0,Math.min(1,Et));let qt=He+Et*tt,tr=Ke+Et*Oe;(Vt-qt)*(Vt-qt)+(gt-tr)*(gt-tr)<=B&&(oe[Nt]=1,ie(this,le,Bt,dt,ue(Vt,gt)))}}},we=Number(this.lineDashOffset),Te=Number.isFinite(we)?we:0;for(let Me of this._subs){let be=Me.pts,Ce=be.length;if(Ce<2)continue;let Ie=Me.closed?Ce:Ce-1,ze=fe>1e-6?(Te*d%fe+fe)%fe:0;for(let Ue=0;Ue<Ie;Ue++){let[He,Ke]=be[Ue],[et,Qe]=be[(Ue+1)%Ce];if(fe<=1e-6)ve(He,Ke,et,Qe,!Me.closed&&Ue===0,!Me.closed&&Ue===Ie-1);else{let tt=Math.hypot(et-He,Qe-Ke);if(tt<=1e-6)continue;let Oe=0;for(;Oe<tt;){let Xe=ze,rt=0;for(;rt<ye.length&&Xe>=ye[rt];)Xe-=ye[rt],rt++;let yt=Math.min(tt-Oe,rt<ye.length?Math.max(.25,ye[rt]-Xe):tt-Oe);if(rt%2===0){let pt=Oe/tt,ot=(Oe+yt)/tt;ve(He+(et-He)*pt,Ke+(Qe-Ke)*pt,He+(et-He)*ot,Ke+(Qe-Ke)*ot,!0,!0)}Oe+=yt,ze=(ze+yt)%fe}}}}this.canvas._ver++}clearRect(u,d,M,L){if(!Number.isFinite(u+d+M+L)||this.canvas.width<=0||this.canvas.height<=0)return;let $=this._m;if($[0]===1&&$[1]===0&&$[2]===0&&$[3]===1&&$[4]===0&&$[5]===0&&!this._clip&&u<=0&&d<=0&&u+M>=this.canvas.width&&d+L>=this.canvas.height){this.canvas._data.fill(0),this.canvas._ver++;return}let B=this.canvas._data,U=this.canvas._bw,j=this._clip;de(this,[{pts:[G(this,u,d),G(this,u+M,d),G(this,u+M,d+L),G(this,u,d+L)],closed:!0}],"nonzero",(K,ue)=>{let le=ue*U+K;if(j&&!j[le])return;let oe=le*4;B[oe]=B[oe+1]=B[oe+2]=B[oe+3]=0}),this.canvas._ver++}fillRect(u,d,M,L){if(!Number.isFinite(u+d+M+L)||M===0||L===0||this.canvas.width<=0||this.canvas.height<=0)return;let $=ae(this,this.fillStyle),B=te(this),U=this._m;if(U[1]===0&&U[2]===0){let j=this.canvas._bw,K=this.canvas._bh,ue=(U[0]*u+U[4])*this.canvas._sx,le=(U[0]*(u+M)+U[4])*this.canvas._sx,oe=(U[3]*d+U[5])*this.canvas._sy,fe=(U[3]*(d+L)+U[5])*this.canvas._sy,ye=Math.max(0,Math.ceil(Math.min(ue,le)-.5)),ve=Math.min(j-1,Math.ceil(Math.max(ue,le)-.5)-1),we=Math.max(0,Math.ceil(Math.min(oe,fe)-.5)),Te=Math.min(K-1,Math.ceil(Math.max(oe,fe)-.5)-1);if(ye<=ve&&we<=Te){if(!this._clip&&typeof this.fillStyle=="string"){let be=$(0,0),Ce=be>>>24;if(B===0&&Ce>=255||B===1){let Ie=new Uint32Array(new Uint8Array([be&255,be>>>8&255,be>>>16&255,Ce]).buffer)[0],ze=this.canvas._data,Ue=new Uint32Array(ze.buffer,ze.byteOffset,j*K);if(ye===0&&ve===j-1)Ue.fill(Ie,we*j,(Te+1)*j);else for(let He=we;He<=Te;He++)Ue.fill(Ie,He*j+ye,He*j+ve+1);this.canvas._ver++;return}}let Me=be=>{let Ce=be+.5;for(let Ie=ye;Ie<=ve;Ie++)ie(this,B,Ie,be,$(Ie+.5,Ce))};for(let be=we;be<=Te;be++)Me(be)}this.canvas._ver++;return}de(this,[{pts:[G(this,u,d),G(this,u+M,d),G(this,u+M,d+L),G(this,u,d+L)],closed:!0}],"nonzero",(j,K)=>ie(this,B,j,K,$(j+.5,K+.5))),this.canvas._ver++}strokeRect(u,d,M,L){if(!Number.isFinite(u+d+M+L)||M===0&&L===0)return;let $=this._subs,B=this._cur,U=this._pts;this._subs=[],this._cur=null,this._pts=0,this.rect(u,d,M,L),this.stroke(),this._subs=$,this._cur=B,this._pts=U}measureText(u){let{sizePx:d,bold:M}=ee(this.font),L=Array.from(String(u??"")).length;return{width:L>0?L*d*(M?.64:.6)-d*.1:0,actualBoundingBoxAscent:d*.8,actualBoundingBoxDescent:d*.2,fontBoundingBoxAscent:d*.85,fontBoundingBoxDescent:d*.2}}fillText(u,d,M,L){me(this,u,d,M,L,!1)}strokeText(u,d,M,L){me(this,u,d,M,L,!0)}createImageData(u,d){let M=u&&typeof u=="object",L=Math.max(1,Math.min(f,Math.floor(Math.abs(Number(M?u.width:u))||1))),$=Math.max(1,Math.min(f,Math.floor(Math.abs(Number(M?u.height:d))||1)));return{data:new Uint8ClampedArray(L*$*4),width:L,height:$}}getImageData(u,d,M,L){let $=Math.floor(Number(u)||0),B=Math.floor(Number(d)||0),U=Math.floor(Number(M)||0),j=Math.floor(Number(L)||0);U<0&&($+=U,U=-U),j<0&&(B+=j,j=-j),U=Math.max(1,Math.min(f,U)),j=Math.max(1,Math.min(f,j));let K=new Uint8ClampedArray(U*j*4);if(this.canvas.width<=0||this.canvas.height<=0)return{data:K,width:U,height:j};let ue=this.canvas._bw,le=this.canvas._bh,oe=this.canvas._sx,fe=this.canvas._sy,ye=this.canvas._data;for(let ve=0;ve<j;ve++){let we=B+ve;if(we<0||we>=this.canvas.height)continue;let Te=Math.min(le-1,Math.floor((we+.5)*fe));for(let Me=0;Me<U;Me++){let be=$+Me;if(be<0||be>=this.canvas.width)continue;let Ce=(Te*ue+Math.min(ue-1,Math.floor((be+.5)*oe)))*4,Ie=(ve*U+Me)*4;K[Ie]=ye[Ce],K[Ie+1]=ye[Ce+1],K[Ie+2]=ye[Ce+2],K[Ie+3]=ye[Ce+3]}}return{data:K,width:U,height:j}}putImageData(u,d,M,L=0,$=0,B,U){if(!u?.data||this.canvas.width<=0||this.canvas.height<=0)return;let j=Math.floor(Number(u.width)||0),K=Math.floor(Number(u.height)||0);if(j<=0||K<=0)return;let ue=Math.floor(Number(L)||0),le=Math.floor(Number($)||0),oe=B!==void 0?Math.floor(Number(B)):j,fe=U!==void 0?Math.floor(Number(U)):K;oe<0&&(ue+=oe,oe=-oe),fe<0&&(le+=fe,fe=-fe);let ye=Math.max(0,ue),ve=Math.max(0,le),we=Math.min(j,ue+oe),Te=Math.min(K,le+fe);if(ye>=we||ve>=Te)return;let Me=Math.floor(Number(d)||0),be=Math.floor(Number(M)||0),Ce=this.canvas._bw,Ie=this.canvas._bh,ze=1/this.canvas._sx,Ue=1/this.canvas._sy,He=this.canvas._data,Ke=u.data,et=Math.max(0,Math.floor((Me+ye)*this.canvas._sx)),Qe=Math.min(Ce-1,Math.ceil((Me+we)*this.canvas._sx)-1),tt=Math.max(0,Math.floor((be+ve)*this.canvas._sy)),Oe=Math.min(Ie-1,Math.ceil((be+Te)*this.canvas._sy)-1);for(let Xe=tt;Xe<=Oe;Xe++){let rt=Math.floor((Xe+.5)*Ue)-be;if(!(rt<ve||rt>=Te))for(let yt=et;yt<=Qe;yt++){let pt=Math.floor((yt+.5)*ze)-Me;if(pt<ye||pt>=we)continue;let ot=(rt*j+pt)*4,bt=(Xe*Ce+yt)*4;He[bt]=Ke[ot]|0,He[bt+1]=Ke[ot+1]|0,He[bt+2]=Ke[ot+2]|0,He[bt+3]=Ke[ot+3]|0}}this.canvas._ver++}drawImage(u,...d){let M=Le(u);if(!M||M.width<=0||M.height<=0||this.canvas.width<=0||this.canvas.height<=0)return;let L=Number(u?.width)>0?Number(u.width):M.width,$=Number(u?.height)>0?Number(u.height):M.height,B=0,U=0,j=L,K=$,ue=0,le=0,oe=L,fe=$;if(d.length>=8)[B,U,j,K,ue,le,oe,fe]=d;else if(d.length>=4)[ue,le,oe,fe]=d;else if(d.length>=2)[ue,le]=d;else return;if(!Number.isFinite(B+U+j+K+ue+le+oe+fe)||j===0||K===0||oe===0||fe===0)return;let ye=Number(this.globalAlpha),ve=Number.isFinite(ye)?Math.max(0,Math.min(1,ye)):1,we=Math.round(ve*256),Te=te(this),[Me,be,Ce,Ie,ze,Ue]=q(this),He=1/oe,Ke=1/fe,et=M.width/L,Qe=M.height/$;de(this,[{pts:[G(this,ue,le),G(this,ue+oe,le),G(this,ue+oe,le+fe),G(this,ue,le+fe)],closed:!0}],"nonzero",(tt,Oe)=>{let Xe=tt+.5,rt=Oe+.5,yt=Me*Xe+be*rt+Ce,pt=Ie*Xe+ze*rt+Ue,ot=(yt-ue)*He,bt=(pt-le)*Ke;if(ot<0||ot>=1||bt<0||bt>=1)return;let St=Math.floor((B+ot*j)*et),dt=Math.floor((U+bt*K)*Qe);if(St<0||St>=M.width||dt<0||dt>=M.height)return;let gt=(dt*M.width+St)*4;ie(this,Te,tt,Oe,P(M.data[gt],M.data[gt+1],M.data[gt+2],M.data[gt+3]*we+128>>8))}),this.canvas._ver++}}let ke=(T,u,d)=>{let M=Math.floor(Number(u)),L=Math.floor(Number(d));T._w=Number.isFinite(M)&&M>=0?M:0,T._h=Number.isFinite(L)&&L>=0?L:0,T._bw=T._w>0?Math.min(c,T._w):1,T._bh=T._h>0?Math.min(c,T._h):1,T._sx=T._w>0?T._bw/T._w:1,T._sy=T._h>0?T._bh/T._h:1,T._data=new Uint8ClampedArray(T._bw*T._bh*4),T._ctx2d&&k(T._ctx2d),T._ver++};class _e{constructor(u=300,d=150){this._vc=!0,this._ver=1,this._ctx2d=null,this.style={},ke(this,u,d)}get width(){return this._w}set width(u){ke(this,u,this._h)}get height(){return this._h}set height(u){ke(this,this._w,u)}getContext(u){return String(u).toLowerCase()!=="2d"?null:this._ctx2d??(this._ctx2d=new Se(this))}toDataURL(){return this._w<=0||this._h<=0||this._w>f||this._h>f?"":_(this._data,this._bw,this._bh,!1,!1).uri}addEventListener(){}removeEventListener(){}getBoundingClientRect(){return{left:0,top:0,width:this._w,height:this._h,right:this._w,bottom:this._h}}}function Le(T){if(!T||typeof T!="object")return null;let u=T._vc?T:T.canvas?._vc?T.canvas:T.image?._vc?T.image:null;if(u)return{data:u._data,width:u._bw,height:u._bh,logicalW:u._w,logicalH:u._h,ver:u._ver};let d=T.image&&typeof T.image=="object"?T.image:T;if(d.data&&typeof d.data.length=="number"&&Number(d.width)>0&&Number(d.height)>0){let M=Math.floor(Number(d.width)),L=Math.floor(Number(d.height));return{data:d.data instanceof Uint8ClampedArray?d.data:new Uint8ClampedArray(d.data),width:M,height:L,logicalW:M,logicalH:L,ver:-1}}if(typeof d.getContext=="function"){let M=Math.floor(Number(d.width)||0),L=Math.floor(Number(d.height)||0);if(M>0&&L>0&&M<=f&&L<=f)try{let $=d.getContext("2d")?.getImageData?.(0,0,M,L);if($?.data)return{data:$.data instanceof Uint8ClampedArray?$.data:new Uint8ClampedArray($.data),width:M,height:L,logicalW:M,logicalH:L,ver:-1}}catch{}}return null}let ne=e.Texture??class{constructor(T=""){this.source=T,this.isTexture=!0,this.image=null,this.width=0,this.height=0}dispose(){}},Re=T=>{let u=Le(T.image);if(!u){T.width=Number(T.image?.width??0)||0,T.height=Number(T.image?.height??0)||0,T._cs="";return}if(T.width=u.logicalW,T.height=u.logicalH,u.logicalW<=0||u.logicalH<=0||u.logicalW>f||u.logicalH>f){T._cs="";return}let d=`${u.ver>=0?u.ver:T._fs}|${u.logicalW}x${u.logicalH}|${T.flipY?1:0}|${T.colorSpace}`;if(d===T._bk&&T._cs)return;T._bk=d;let M=_(u.data,u.width,u.height,T.flipY,T.colorSpace==="srgb-linear",Math.min(f,Number(T._pngDim)||c));T._cs=M.uri,T._ca=M.avgColor};class W extends ne{constructor(u=null,d,M=1001,L=1001,$=1006,B=1008,U=1023,j=1009,K=1,ue="srgb"){super(""),delete this.source,this.isCanvasTexture=!0,this.isDataTexture=!0,this.image=u,this.width=Number(u?.width??0)||0,this.height=Number(u?.height??0)||0,this.wrapS=Number(M)||1001,this.wrapT=Number(L)||1001,this.magFilter=Number($)||1006,this.minFilter=Number(B)||1008,this.format=Number(U)||1023,this.type=Number(j)||1009,this.flipY=!0,this.generateMipmaps=!0,this.unpackAlignment=4,this.colorSpace=ue||"srgb",this._bk="",this._cs="",this._ca=[1,1,1,1],this._ms="",this._fs=1}get needsUpdate(){return!1}set needsUpdate(u){u&&(this._ms="",this._fs++,this.width=Number(this.image?.width??0)||0,this.height=Number(this.image?.height??0)||0)}get source(){return this._ms?this._ms:(Re(this),this._cs)}set source(u){this._ms=typeof u=="string"?u:""}get avgColor(){return this._ms||Re(this),this._ca}set avgColor(u){Array.isArray(u)&&u.length===4&&(this._ca=[u[0],u[1],u[2],u[3]])}}try{Object.freeze(F.prototype),Object.freeze(V.prototype),Object.freeze(Se.prototype),Object.freeze(_e.prototype)}catch{}let D=(T=300,u=150)=>new _e(T,u);try{let T=typeof globalThis<"u"?globalThis:typeof self<"u"?self:void 0;if(T&&typeof T.HTMLCanvasElement>"u"){let u=d=>String(d).toLowerCase()==="canvas"?new _e(300,150):{style:{},getContext:()=>null,addEventListener:()=>{},removeEventListener:()=>{},appendChild:()=>{},removeChild:()=>{},setAttribute:()=>{}};if(typeof T.document>"u"||T.document===null){let d=Object.freeze({appendChild:()=>{},removeChild:()=>{},style:{}}),M=Object.freeze({style:{}});T.document=Object.freeze({__threeLiveVirtualCanvas:!0,createElement:u,createTextNode:()=>({}),querySelectorAll:()=>[],querySelector:()=>null,getElementById:()=>null,head:d,body:d,documentElement:M,addEventListener:()=>{},removeEventListener:()=>{}})}else if(typeof T.document=="object"&&!T.document.__threeLiveVirtualCanvas){let d=typeof T.document.createElement=="function"?T.document.createElement.bind(T.document):null;try{T.document.__threeLiveVirtualCanvas=!0,T.document.createElement=M=>String(M).toLowerCase()==="canvas"?new _e(300,150):d?d(M):u(M)}catch{}}}}catch{}let z=new Uint8Array([151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]),O=new Uint8Array(512);for(let T=0;T<256;T++)O[T]=z[T],O[T+256]=z[T];let X=T=>T*T*T*(T*(T*6-15)+10),se=(T,u,d)=>u+T*(d-u),ce=(T,u,d,M)=>{let L=T&15,$=L<8?u:d,B=L<4?d:L===12||L===14?u:M;return((L&1)===0?$:-$)+((L&2)===0?B:-B)};class pe{noise(u,d,M=0){let L=Number(u),$=Number(d),B=Number(M);if(!Number.isFinite(L)||!Number.isFinite($)||!Number.isFinite(B))return 0;let U=Math.floor(L),j=Math.floor($),K=Math.floor(B),ue=U&255,le=j&255,oe=K&255;L-=U,$-=j,B-=K;let fe=L-1,ye=$-1,ve=B-1,we=X(L),Te=X($),Me=X(B),be=O[ue]+le,Ce=O[be]+oe,Ie=O[be+1]+oe,ze=O[ue+1]+le,Ue=O[ze]+oe,He=O[ze+1]+oe;return se(Me,se(Te,se(we,ce(O[Ce],L,$,B),ce(O[Ue],fe,$,B)),se(we,ce(O[Ie],L,ye,B),ce(O[He],fe,ye,B))),se(Te,se(we,ce(O[Ce+1],L,$,ve),ce(O[Ue+1],fe,$,ve)),se(we,ce(O[Ie+1],L,ye,ve),ce(O[He+1],fe,ye,ve))))}}Object.freeze(pe.prototype);let xe=new Int8Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),he=new Int8Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]),Ne=.5*(Math.sqrt(3)-1),ge=(3-Math.sqrt(3))/6,Ae=1/3,Ee=1/6,$e=(Math.sqrt(5)-1)/4,De=(5-Math.sqrt(5))/20,Be=(T,u,d)=>xe[T]*u+xe[T+1]*d,Fe=(T,u,d,M)=>xe[T]*u+xe[T+1]*d+xe[T+2]*M,Ve=(T,u,d,M,L)=>he[T]*u+he[T+1]*d+he[T+2]*M+he[T+3]*L;function qe(T){let u=T===void 0?Math:T;if(typeof u=="function")return u;if(typeof u=="number"){let d=Number.isFinite(u)?u|0:0;return()=>{let M=d=d+1831565813|0;return M=Math.imul(M^M>>>15,M|1),M^=M+Math.imul(M^M>>>7,M|61),((M^M>>>14)>>>0)/4294967296}}return u&&typeof u=="object"&&typeof u.random=="function"?()=>u.random():Math.random}class je{constructor(u){let d=qe(u),M=new Uint8Array(256);for(let B=0;B<256;B++){let U=Number(d()),j=Number.isFinite(U)?(U%1+1)%1:0;M[B]=Math.floor(j*256)&255}let L=new Uint8Array(512),$=new Uint8Array(512);for(let B=0;B<512;B++){let U=M[B&255];L[B]=U,$[B]=U%12}this.p=M,this.perm=L,this.permMod12=$}noise(u,d){let M=Number(u),L=Number(d);if(!Number.isFinite(M)||!Number.isFinite(L))return 0;let $=this.perm,B=this.permMod12,U=(M+L)*Ne,j=Math.floor(M+U),K=Math.floor(L+U),ue=(j+K)*ge,le=j-ue,oe=K-ue,fe=M-le,ye=L-oe,ve=fe>ye?1:0,we=fe>ye?0:1,Te=fe-ve+ge,Me=ye-we+ge,be=fe-1+2*ge,Ce=ye-1+2*ge,Ie=j&255,ze=K&255,Ue=B[Ie+$[ze]]*3,He=B[Ie+ve+$[ze+we]]*3,Ke=B[Ie+1+$[ze+1]]*3,et=0,Qe=.5-fe*fe-ye*ye;Qe>=0&&(Qe*=Qe,et=Qe*Qe*Be(Ue,fe,ye));let tt=0,Oe=.5-Te*Te-Me*Me;Oe>=0&&(Oe*=Oe,tt=Oe*Oe*Be(He,Te,Me));let Xe=0,rt=.5-be*be-Ce*Ce;return rt>=0&&(rt*=rt,Xe=rt*rt*Be(Ke,be,Ce)),70*(et+tt+Xe)}noise3d(u,d,M){let L=Number(u),$=Number(d),B=Number(M);if(!Number.isFinite(L)||!Number.isFinite($)||!Number.isFinite(B))return 0;let U=this.perm,j=this.permMod12,K=(L+$+B)*Ae,ue=Math.floor(L+K),le=Math.floor($+K),oe=Math.floor(B+K),fe=(ue+le+oe)*Ee,ye=L-(ue-fe),ve=$-(le-fe),we=B-(oe-fe),Te,Me,be,Ce,Ie,ze;ye>=ve?ve>=we?(Te=1,Me=0,be=0,Ce=1,Ie=1,ze=0):ye>=we?(Te=1,Me=0,be=0,Ce=1,Ie=0,ze=1):(Te=0,Me=0,be=1,Ce=1,Ie=0,ze=1):ve<we?(Te=0,Me=0,be=1,Ce=0,Ie=1,ze=1):ye<we?(Te=0,Me=1,be=0,Ce=0,Ie=1,ze=1):(Te=0,Me=1,be=0,Ce=1,Ie=1,ze=0);let Ue=ye-Te+Ee,He=ve-Me+Ee,Ke=we-be+Ee,et=ye-Ce+2*Ee,Qe=ve-Ie+2*Ee,tt=we-ze+2*Ee,Oe=ye-1+3*Ee,Xe=ve-1+3*Ee,rt=we-1+3*Ee,yt=ue&255,pt=le&255,ot=oe&255,bt=j[yt+U[pt+U[ot]]]*3,St=j[yt+Te+U[pt+Me+U[ot+be]]]*3,dt=j[yt+Ce+U[pt+Ie+U[ot+ze]]]*3,gt=j[yt+1+U[pt+1+U[ot+1]]]*3,Bt=0,Nt=.6-ye*ye-ve*ve-we*we;Nt>=0&&(Nt*=Nt,Bt=Nt*Nt*Fe(bt,ye,ve,we));let Vt=0,Et=.6-Ue*Ue-He*He-Ke*Ke;Et>=0&&(Et*=Et,Vt=Et*Et*Fe(St,Ue,He,Ke));let qt=0,tr=.6-et*et-Qe*Qe-tt*tt;tr>=0&&(tr*=tr,qt=tr*tr*Fe(dt,et,Qe,tt));let Mr=0,mr=.6-Oe*Oe-Xe*Xe-rt*rt;return mr>=0&&(mr*=mr,Mr=mr*mr*Fe(gt,Oe,Xe,rt)),32*(Bt+Vt+qt+Mr)}noise4d(u,d,M,L){let $=Number(u),B=Number(d),U=Number(M),j=Number(L);if(!Number.isFinite($)||!Number.isFinite(B)||!Number.isFinite(U)||!Number.isFinite(j))return 0;let K=this.perm,ue=($+B+U+j)*$e,le=Math.floor($+ue),oe=Math.floor(B+ue),fe=Math.floor(U+ue),ye=Math.floor(j+ue),ve=(le+oe+fe+ye)*De,we=$-(le-ve),Te=B-(oe-ve),Me=U-(fe-ve),be=j-(ye-ve),Ce=(we>Te?1:0)+(we>Me?1:0)+(we>be?1:0),Ie=(we<=Te?1:0)+(Te>Me?1:0)+(Te>be?1:0),ze=(we<=Me?1:0)+(Te<=Me?1:0)+(Me>be?1:0),Ue=(we<=be?1:0)+(Te<=be?1:0)+(Me<=be?1:0),He=Ce>=3?1:0,Ke=Ie>=3?1:0,et=ze>=3?1:0,Qe=Ue>=3?1:0,tt=Ce>=2?1:0,Oe=Ie>=2?1:0,Xe=ze>=2?1:0,rt=Ue>=2?1:0,yt=Ce>=1?1:0,pt=Ie>=1?1:0,ot=ze>=1?1:0,bt=Ue>=1?1:0,St=we-He+De,dt=Te-Ke+De,gt=Me-et+De,Bt=be-Qe+De,Nt=we-tt+2*De,Vt=Te-Oe+2*De,Et=Me-Xe+2*De,qt=be-rt+2*De,tr=we-yt+3*De,Mr=Te-pt+3*De,mr=Me-ot+3*De,qr=be-bt+3*De,Di=we-1+4*De,Mi=Te-1+4*De,dn=Me-1+4*De,gn=be-1+4*De,Wr=le&255,Kr=oe&255,pr=fe&255,dr=ye&255,B0=(K[Wr+K[Kr+K[pr+K[dr]]]]&31)*4,z0=(K[Wr+He+K[Kr+Ke+K[pr+et+K[dr+Qe]]]]&31)*4,V0=(K[Wr+tt+K[Kr+Oe+K[pr+Xe+K[dr+rt]]]]&31)*4,U0=(K[Wr+yt+K[Kr+pt+K[pr+ot+K[dr+bt]]]]&31)*4,O0=(K[Wr+1+K[Kr+1+K[pr+1+K[dr+1]]]]&31)*4,zc=0,yn=.6-we*we-Te*Te-Me*Me-be*be;yn>=0&&(yn*=yn,zc=yn*yn*Ve(B0,we,Te,Me,be));let Vc=0,bn=.6-St*St-dt*dt-gt*gt-Bt*Bt;bn>=0&&(bn*=bn,Vc=bn*bn*Ve(z0,St,dt,gt,Bt));let Uc=0,xn=.6-Nt*Nt-Vt*Vt-Et*Et-qt*qt;xn>=0&&(xn*=xn,Uc=xn*xn*Ve(V0,Nt,Vt,Et,qt));let Oc=0,vn=.6-tr*tr-Mr*Mr-mr*mr-qr*qr;vn>=0&&(vn*=vn,Oc=vn*vn*Ve(U0,tr,Mr,mr,qr));let jc=0,wn=.6-Di*Di-Mi*Mi-dn*dn-gn*gn;return wn>=0&&(wn*=wn,jc=wn*wn*Ve(O0,Di,Mi,dn,gn)),27*(zc+Vc+Uc+Oc+jc)}noise2D(u,d){return this.noise(u,d)}noise3D(u,d,M){return this.noise3d(u,d,M)}noise4D(u,d,M,L){return this.noise4d(u,d,M,L)}}Object.freeze(je.prototype);let ut=T=>{if(!T||typeof T!="object")return null;let u=T,d=u.image,M=Le(d??u);if(M&&d?._vc)return{buf:M.data,w:M.width,h:M.height,ch:4,isFloat:!1,flipY:!!u.flipY};let L=d?.data,$=Number(d?.width??u.width)|0,B=Number(d?.height??u.height)|0;if(!L||!($>0&&B>0)||!L.length)return null;let U=$*B,j=u.format,K=j===1021||j===1024||j===1028||L.length===U?1:j===1025||j===1030||L.length===U*2?2:j===1022||L.length===U*3?3:4;return{buf:L,w:$,h:B,ch:K,isFloat:u.type===1015||u.type===1016||L instanceof Float32Array||L instanceof Float64Array,flipY:!!u.flipY}},it=(T,u,d,M)=>{let L=Math.min(T.w-1,Math.max(0,u*T.w|0)),$=Math.min(T.h-1,Math.max(0,d*T.h|0)),B=T.flipY?T.h-1-$:$,U=Number(T.buf[(B*T.w+L)*T.ch+Math.min(M,T.ch-1)]??0);if(!Number.isFinite(U))return 0;let j=T.isFloat&&U<=1?U*255:U;return j>0?j<255?j+.5|0:255:0},nt=e.MeshStandardMaterial?.prototype&&(Object.getPrototypeOf(e.MeshStandardMaterial.prototype)||e.MeshStandardMaterial.prototype);nt&&typeof nt._packPbr!="function"&&(nt._packPbr=function(){let T;if((this.roughnessMap||this.metalnessMap)&&this.roughnessMap!==this.metalnessMap){let M=ut(this.roughnessMap),L=ut(this.metalnessMap);if(M||L){let $=Math.min(128,Math.max(M?.w??1,L?.w??1)),B=Math.min(128,Math.max(M?.h??1,L?.h??1)),U=new Uint8ClampedArray($*B*4);for(let j=0;j<B;j++){let K=(j+.5)/B;for(let ue=0;ue<$;ue++){let le=(ue+.5)/$,oe=(j*$+ue)*4;U[oe]=255,U[oe+1]=M?it(M,le,K,1):255,U[oe+2]=L?it(L,le,K,2):255,U[oe+3]=255}}T=_(U,$,B,!1,!0,128).uri}}let u,d;if(!this.normalMap&&this.bumpMap){let M=ut(this.bumpMap);if(M){let L=Number.isFinite(this.bumpScale)?this.bumpScale:1,$=Math.min(128,M.w),B=Math.min(128,M.h),U=new Uint8ClampedArray($*B*4),j=(K,ue)=>it(M,((K%$+$)%$+.5)/$,((ue%B+B)%B+.5)/B,0)/255;for(let K=0;K<B;K++)for(let ue=0;ue<$;ue++){let le=(j(ue+1,K)-j(ue-1,K))*L*2,oe=(j(ue,K+1)-j(ue,K-1))*L*2,fe=1/Math.hypot(le,oe,1),ye=(K*$+ue)*4;U[ye]=(-le*fe*.5+.5)*255+.5|0,U[ye+1]=(oe*fe*.5+.5)*255+.5|0,U[ye+2]=(fe*.5+.5)*255+.5|0,U[ye+3]=255}u=_(U,$,B,!1,!0,128).uri,d=1}}return{mrUri:T,normUri:u,normScale:d}});let ct=0,Je=e.Vector2,Dt=e.PlaneGeometry,Ft=e.Mesh,lr=e.Material;class wt extends lr{constructor(u={}){super({roughness:.85,metalness:0,side:2,transparent:u.transparent??!0,...u}),this.isSpriteMaterial=!0;let d=Number(u.rotation);this.rotation=Number.isFinite(d)?d:0,this.sizeAttenuation=u.sizeAttenuation!==!1,u.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35,this.map&&!this.emissiveMap&&(this.emissiveMap=this.map))}clone(){return new wt({...this,emissive:this._em?this.emissive:void 0})}}class Gt extends Ft{constructor(u){super(new Dt(1,1),u instanceof lr?u:new wt(u||{})),this.isSprite=!0,this.center=new Je(.5,.5),this.userData={xr:{billboard:"spherical"}}}_cloneCustom(){let u=new Gt(this.material);return u.center.copy(this.center),u._autoNamed=!!this._autoNamed,u._noBillboard=!!this._noBillboard,u}_bakeAuthorGeometry(){this._bakedOwner!==this?((!this.name||this._autoNamed)&&(this.name=`Sprite_${++ct}`,this._autoNamed=!0),this._bakedOwner=this):this.name||(this.name=`Sprite_${++ct}`,this._autoNamed=!0);let u=this.userData?.xr?.billboard;u===!1||u===null?(this._noBillboard=!0,delete this.userData.xr.billboard,Object.keys(this.userData.xr).length===0&&delete this.userData.xr):((typeof u=="string"||u===!0)&&(this._noBillboard=!1),this._noBillboard||(!this.userData||typeof this.userData!="object"?this.userData={xr:{billboard:"spherical"}}:!this.userData.xr||typeof this.userData.xr!="object"?this.userData.xr={billboard:"spherical"}:this.userData.xr.billboard===void 0&&(this.userData.xr.billboard="spherical")));let d=Number.isFinite(this.center?.x)?this.center.x:.5,M=Number.isFinite(this.center?.y)?this.center.y:.5,L=Number(this.material?.rotation),$=Number.isFinite(L)?L:0,B=`${d},${M},${$}`;if(this._bakedKey!==B&&(this._bakedKey!==void 0||d!==.5||M!==.5||$!==0)){let U=new Dt(1,1),j=U.attributes.position?.array,K=.5-d,ue=.5-M,le=Math.cos($),oe=Math.sin($);if(j){for(let fe=0;fe<j.length;fe+=3){let ye=j[fe]+K,ve=j[fe+1]+ue;j[fe]=ye*le-ve*oe,j[fe+1]=ye*oe+ve*le}U.boundingBox=null,U.boundingSphere=null}U.__baked=!0,this._bakedKey=B,this.geometry=U}}}if(Object.freeze(wt.prototype),Object.freeze(Gt.prototype),Je?.prototype){let T=Je.prototype,u=(d,M)=>{typeof T[d]!="function"&&(T[d]=M)};u("length",function(){return Math.hypot(this.x,this.y)}),u("normalize",function(){return this.divideScalar(Math.hypot(this.x,this.y)||1)}),u("distanceTo",function(d){return Math.hypot(this.x-(d?.x||0),this.y-(d?.y||0))}),u("dot",function(d){return this.x*(d?.x||0)+this.y*(d?.y||0)}),u("lerp",function(d,M){let L=Number(M)||0;return this.set(this.x+((d?.x||0)-this.x)*L,this.y+((d?.y||0)-this.y)*L)}),u("lerpVectors",function(d,M,L){let $=Number(L)||0,B=d?.x||0,U=d?.y||0;return this.set(B+((M?.x||0)-B)*$,U+((M?.y||0)-U)*$)}),u("equals",function(d){return!!d&&d.x===this.x&&d.y===this.y})}let Pe=(T,u=0)=>{let d=Number(T);return Number.isFinite(d)?d:u},at=T=>Math.max(0,Math.min(1,Pe(T,0))),vt=T=>new Je(Pe(T?.x),Pe(T?.y));class Mt{constructor(u="Curve"){this.type=u,this.arcLengthDivisions=200,this._lenCache=null}getPoint(u,d=new Je){return d.set(0,0)}getPointAt(u,d){return this.getPoint(this.getUtoTMapping(u),d)}getPoints(u=5){let d=Math.max(1,Math.min(1024,Math.floor(Pe(u,5)))),M=[];for(let L=0;L<=d;L++)M.push(this.getPoint(L/d));return M}getSpacedPoints(u=5){let d=Math.max(1,Math.min(1024,Math.floor(Pe(u,5)))),M=[];for(let L=0;L<=d;L++)M.push(this.getPointAt(L/d));return M}getLength(){let u=this.getLengths();return u[u.length-1]||0}getLengths(u=this.arcLengthDivisions){let d=Math.max(1,Math.min(2048,Math.floor(Pe(u,200))));if(this._lenCache&&this._lenCache.length===d+1)return this._lenCache;let M=[0],L=0,$=this.getPoint(0);for(let B=1;B<=d;B++){let U=this.getPoint(B/d);L+=Math.hypot(Pe(U.x)-Pe($.x),Pe(U.y)-Pe($.y),Pe(U.z)-Pe($.z)),M.push(L),$=U}return d===this.arcLengthDivisions&&(this._lenCache=M),M}updateArcLengths(){this._lenCache=null,this.getLengths()}getUtoTMapping(u,d){let M=this.getLengths(),L=M.length,$=M[L-1]||0;if($<=0||L<2)return at(u);let B=d!==void 0&&Number.isFinite(Number(d))?Math.max(0,Math.min($,Number(d))):at(u)*$,U=0,j=L-1;for(;U<=j;){let oe=U+j>>1,fe=M[oe]-B;if(fe<0)U=oe+1;else if(fe>0)j=oe-1;else return oe/(L-1)}let K=Math.max(0,U-1),ue=M[K],le=(M[K+1]??$)-ue;return(K+(le>1e-12?(B-ue)/le:0))/(L-1)}getTangent(u,d){let M=at(u),L=this.getPoint(Math.max(0,M-1e-4)),$=this.getPoint(Math.min(1,M+1e-4)),B=Pe($.x)-Pe(L.x),U=Pe($.y)-Pe(L.y);if("z"in L||d?.isVector3){let K=Pe($.z)-Pe(L.z),ue=Math.hypot(B,U,K)||1;return(d||new r).set(B/ue,U/ue,K/ue)}let j=Math.hypot(B,U)||1;return(d||new Je).set(B/j,U/j)}getTangentAt(u,d){return this.getTangent(this.getUtoTMapping(u),d)}clone(){return new this.constructor().copy(this)}copy(u){if(!u||typeof u!="object")return this;let d=u,M=this;for(let L of Object.keys(d)){if(L==="type"||L.startsWith("is"))continue;if(L.startsWith("_")){M[L]=null;continue}let $=d[L];Array.isArray($)?M[L]=$.map(B=>B?.clone?B.clone():B&&typeof B=="object"&&"x"in B?vt(B):B):$?.clone?M[L]=$.clone():$&&typeof $=="object"&&"x"in $?M[L]=vt($):M[L]=$}return this}}class Pt extends Mt{constructor(u,d){super("LineCurve"),this.isLineCurve=!0,this.v1=vt(u),this.v2=vt(d)}getPoint(u,d=new Je){let M=Pe(u,0),L=Pe(this.v1.x),$=Pe(this.v1.y);return M===1?d.set(Pe(this.v2.x),Pe(this.v2.y)):d.set(L+(Pe(this.v2.x)-L)*M,$+(Pe(this.v2.y)-$)*M)}getPointAt(u,d=new Je){return this.getPoint(at(u),d)}}class Ct extends Mt{constructor(u,d,M){super("QuadraticBezierCurve"),this.isQuadraticBezierCurve=!0,this.v0=vt(u),this.v1=vt(d),this.v2=vt(M)}getPoint(u,d=new Je){let M=at(u),L=1-M;return d.set(L*L*Pe(this.v0.x)+2*L*M*Pe(this.v1.x)+M*M*Pe(this.v2.x),L*L*Pe(this.v0.y)+2*L*M*Pe(this.v1.y)+M*M*Pe(this.v2.y))}}class Xt extends Mt{constructor(u,d,M,L){super("CubicBezierCurve"),this.isCubicBezierCurve=!0,this.v0=vt(u),this.v1=vt(d),this.v2=vt(M),this.v3=vt(L)}getPoint(u,d=new Je){let M=at(u),L=1-M,$=L*L,B=M*M;return d.set($*L*Pe(this.v0.x)+3*$*M*Pe(this.v1.x)+3*L*B*Pe(this.v2.x)+B*M*Pe(this.v3.x),$*L*Pe(this.v0.y)+3*$*M*Pe(this.v1.y)+3*L*B*Pe(this.v2.y)+B*M*Pe(this.v3.y))}}class Ot extends Mt{constructor(u=[]){super("SplineCurve"),this.isSplineCurve=!0,this.points=Array.isArray(u)?u:[]}getPoint(u,d=new Je){let M=this.points,L=Array.isArray(M)?M.length:0;if(L===0)return d.set(0,0);if(L===1)return d.set(Pe(M[0]?.x),Pe(M[0]?.y));let $=(L-1)*at(u),B=Math.floor($),U=$-B;B>=L-1&&(B=L-2,U=1);let j=M[B===0?0:B-1],K=M[B],ue=M[B+1],le=M[B>L-3?L-1:B+2],oe=U*U,fe=oe*U,ye=(ve,we,Te,Me)=>.5*(2*we+(Te-ve)*U+(2*ve-5*we+4*Te-Me)*oe+(3*we-ve-3*Te+Me)*fe);return d.set(ye(Pe(j?.x),Pe(K?.x),Pe(ue?.x),Pe(le?.x)),ye(Pe(j?.y),Pe(K?.y),Pe(ue?.y),Pe(le?.y)))}}class Yt extends Mt{constructor(u=0,d=0,M=1,L=1,$=0,B=Math.PI*2,U=!1,j=0){super("EllipseCurve"),this.isEllipseCurve=!0,this.aX=Pe(u,0),this.aY=Pe(d,0),this.xRadius=Pe(M,1),this.yRadius=Pe(L,1),this.aStartAngle=Pe($,0),this.aEndAngle=Pe(B,Math.PI*2),this.aClockwise=!!U,this.aRotation=Pe(j,0)}getPoint(u,d=new Je){let M=Math.PI*2,L=Pe(this.aStartAngle,0),$=Pe(this.aEndAngle,M)-L;Math.abs($)>=1e-9?($=($%M+M)%M,$<1e-9&&($=M),this.aClockwise&&($=$===M?-M:$-M)):$=0;let B=L+at(u)*$,U=Pe(this.xRadius,1)*Math.cos(B),j=Pe(this.yRadius,1)*Math.sin(B),K=Pe(this.aRotation,0),ue=Math.cos(K),le=Math.sin(K);return d.set(this.aX+U*ue-j*le,this.aY+U*le+j*ue)}}class Qt extends Yt{constructor(u=0,d=0,M=1,L=0,$=Math.PI*2,B=!1){super(u,d,M,M,L,$,B,0),this.type="ArcCurve",this.isArcCurve=!0}}class Zt extends Mt{constructor(){super("CurvePath"),this.isCurvePath=!0,this.curves=[],this.autoClose=!1,this._curveLens=null}add(u){return u&&typeof u.getPoint=="function"&&(this.curves.push(u),this._curveLens=null,this._lenCache=null),this}closePath(){if(this.curves.length===0)return this;let u=this.curves[0].getPoint(0),d=this.curves[this.curves.length-1].getPoint(1),M=!!(u&&("z"in u||u.isVector3));if(Math.hypot(Pe(u?.x)-Pe(d?.x),Pe(u?.y)-Pe(d?.y),M?Pe(u?.z)-Pe(d?.z):0)>1e-6){let L=e.LineCurve3;this.add(M&&L?new L(d,u):new Pt(d,u))}return this}getCurveLengths(){if(this._curveLens&&this._curveLens.length===this.curves.length)return this._curveLens;let u=[],d=0;for(let M of this.curves){let L=0;if(typeof M?.getLength=="function")L=Pe(M.getLength(),0);else if(typeof M?.getPoints=="function"){let $=M.getPoints(32);for(let B=1;B<$.length;B++)L+=Math.hypot(Pe($[B]?.x)-Pe($[B-1]?.x),Pe($[B]?.y)-Pe($[B-1]?.y),Pe($[B]?.z)-Pe($[B-1]?.z))}d+=L,u.push(d)}return this._curveLens=u,u}getLength(){let u=this.getCurveLengths();return u[u.length-1]||0}updateArcLengths(){this._curveLens=null,this._lenCache=null;for(let u of this.curves)u?.updateArcLengths?.();this.getCurveLengths()}getPoint(u,d){if(this.curves.length===0)return(d||new Je).set(0,0);let M=this.getCurveLengths(),L=M[M.length-1]||0;if(L<=1e-12)return this.curves[0].getPoint(0,d);let $=at(u)*L;for(let B=0;B<M.length;B++)if($<=M[B]||B===M.length-1){let U=B>0?M[B-1]:0,j=M[B]-U,K=j>1e-12?($-U)/j:0,ue=this.curves[B];return typeof ue.getPointAt=="function"?ue.getPointAt(K,d):ue.getPoint(K,d)}return this.curves[this.curves.length-1].getPoint(1,d)}getPoints(u=12){let d=Math.max(1,Math.min(1024,Math.floor(Pe(u,12)))),M=[],L=null;for(let $ of this.curves){let B=$?.isEllipseCurve?d*2:$?.isLineCurve||$ instanceof(e.LineCurve3||Function)?1:$?.isSplineCurve&&Array.isArray($.points)?d*Math.max(1,$.points.length):d;for(let U of $.getPoints(Math.min(1024,B)))L&&Math.hypot(Pe(L.x)-Pe(U.x),Pe(L.y)-Pe(U.y),Pe(L.z)-Pe(U.z))<1e-6||(M.push(U),L=U)}if(this.autoClose&&M.length>1){let $=M[0];Math.hypot(Pe(L.x)-Pe($.x),Pe(L.y)-Pe($.y),Pe(L.z)-Pe($.z))>1e-6&&M.push($.clone?$.clone():$)}return M}getSpacedPoints(u=40){let d=Math.max(1,Math.min(1024,Math.floor(Pe(u,40)))),M=[];for(let L=0;L<=d;L++)M.push(this.getPoint(L/d));return this.autoClose&&M.length>0&&M.push(M[0].clone?M[0].clone():M[0]),M}}let ur=e.BufferAttribute,br=e.Object3D,oi=e.Line,Jt=e.LineSegments,er=e.LineBasicMaterial,vi=e.MeshBasicMaterial,Hr=e.ConeGeometry,xr=e.Color,cr=(T,u,d,M)=>{T.name=u.name,T.position.copy(u.position),T.quaternion.copy(u.quaternion),T.scale.copy(u.scale),T.visible=u.visible,T.castShadow=u.castShadow,T.receiveShadow=u.receiveShadow;try{T.userData=JSON.parse(JSON.stringify(u.userData||{}))}catch{T.userData={...u.userData||{}}}if(M&&Array.isArray(u.children))for(let L=d;L<u.children.length;L++)T.add(u.children[L].clone(!0));return T},Ht=T=>{let u=new n;return u.setAttribute("position",new ur(new Float32Array(T),3)),u.__isSegmentPairs=!0,u},ro=[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,3,7,2,6],fn=(T,u,d,M,L,$)=>{if(!Number.isFinite(T+u+d+M+L+$)||M<T||L<u||$<d)return new n;let B=[];for(let U of ro)B.push(U&1?M:T,U&2?L:u,U&4?$:d);return Ht(B)};class wi extends Jt{constructor(u=10,d=10,M=4473924,L=8947848){let $=Math.max(1e-4,Math.abs(Pe(u,10))),B=Math.max(1,Math.min(256,Math.floor(Pe(d,10)))),U=new xr(M??4473924),j=new xr(L??8947848),K=$*.5,ue=$/B,le=B%2===0&&U.getHex()!==j.getHex()?B>>1:-1,oe=[],fe=[];for(let ye=0,ve=-K;ye<=B;ye++,ve+=ue)(ye===le?fe:oe).push(-K,0,ve,K,0,ve,ve,0,-K,ve,0,K);if(super(Ht(oe.length?oe:fe),new er({color:oe.length?j:U})),this.type="GridHelper",this.isGridHelper=!0,this._size=$,this._divisions=B,this._internalKids=0,fe.length&&oe.length){let ye=new Jt(Ht(fe),new er({color:U}));this._centerLines=ye,this._internalKids=1,this.add(ye)}}_bakeAuthorGeometry(){this._centerLines?.material&&this.material&&(this._centerLines.material.transparent=this.material.transparent,this._centerLines.material.opacity=this.material.opacity),super._bakeAuthorGeometry()}clone(u=!0){let d=new wi(this._size,this._divisions,this._centerLines?this._centerLines.material.color:this.material.color,this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,cr(d,this,this._internalKids,u)}dispose(){}}class Nr extends Jt{constructor(u=1){let d=Math.max(1e-4,Math.abs(Pe(u,1)));super(Ht([0,0,0,d,0,0]),new er({color:16724736})),this.type="AxesHelper",this.isAxesHelper=!0,this._size=d,this._yAxis=new Jt(Ht([0,0,0,0,d,0]),new er({color:3407616})),this._zAxis=new Jt(Ht([0,0,0,0,0,d]),new er({color:35071})),this.add(this._yAxis),this.add(this._zAxis)}setColors(u,d,M){return this.material.color.set(u),this._yAxis.material.color.set(d),this._zAxis.material.color.set(M),this}_bakeAuthorGeometry(){for(let u of[this._yAxis,this._zAxis])u?.material&&this.material&&(u.material.transparent=this.material.transparent,u.material.opacity=this.material.opacity);super._bakeAuthorGeometry()}clone(u=!0){let d=new Nr(this._size).setColors(this.material.color,this._yAxis.material.color,this._zAxis.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,cr(d,this,2,u)}dispose(){}}class Cr extends br{constructor(u=new r(0,0,1),d=new r(0,0,0),M=1,L=16776960,$,B){super(),this.type="ArrowHelper",this.isArrowHelper=!0,this.position.set(Pe(d?.x),Pe(d?.y),Pe(d?.z));let U=new n;U.setAttribute("position",new ur(new Float32Array([0,0,0,0,1,0]),3)),this.line=new oi(U,new er({color:L})),this.cone=new Ft(new Hr(.5,1,8).translate(0,-.5,0),new vi({color:L})),this.add(this.line),this.add(this.cone),this.setDirection(u).setLength(M,$,B)}setDirection(u){let d=Pe(u?.x,0),M=Pe(u?.y,0),L=Pe(u?.z,1),$=Math.hypot(d,M,L),B=$>1e-9?d/$:0,U=$>1e-9?M/$:1,j=$>1e-9?L/$:0;return U>.99999?this.quaternion.set(0,0,0,1):U<-.99999?this.quaternion.set(1,0,0,0):this.quaternion.setFromAxisAngle(new r(j,0,-B).normalize(),Math.acos(Math.max(-1,Math.min(1,U)))),this}setLength(u,d,M){let L=Math.max(1e-4,Math.abs(Pe(u,1))),$=d!==void 0&&Number.isFinite(Number(d))?Math.max(1e-4,Math.abs(Number(d))):.2*L,B=M!==void 0&&Number.isFinite(Number(M))?Math.max(1e-4,Math.abs(Number(M))):.2*$;return this.line.scale.set(1,Math.max(1e-4,L-$),1),this.line.updateMatrix?.(),this.cone.scale.set(B,$,B),this.cone.position.set(0,L,0),this.cone.updateMatrix?.(),this}setColor(u){return this.line.material.color.set(u),this.cone.material.color.set(u),this}clone(u=!0){let d=new Cr;return d.line.scale.copy(this.line.scale),d.cone.scale.copy(this.cone.scale),d.cone.position.copy(this.cone.position),d.setColor(this.cone.material.color),d.line.material.transparent=this.line.material.transparent,d.line.material.opacity=this.line.material.opacity,d.cone.material.transparent=this.cone.material.transparent,d.cone.material.opacity=this.cone.material.opacity,cr(d,this,2,u)}dispose(){}}class Er extends Jt{constructor(u=new a,d=16776960){let M=u instanceof a?u:new a(u?.min,u?.max);super(M.isEmpty()?new n:fn(M.min.x,M.min.y,M.min.z,M.max.x,M.max.y,M.max.z),new er({color:d})),this.type="Box3Helper",this.isBox3Helper=!0,this.box=M}_bakeAuthorGeometry(){let u=this.box,d=!u||u.isEmpty()?new n:fn(u.min.x,u.min.y,u.min.z,u.max.x,u.max.y,u.max.z);this._sourceGeo=d,this.geometry=d,super._bakeAuthorGeometry()}clone(u=!0){let d=new Er(this.box.clone(),this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,cr(d,this,0,u)}dispose(){}}class li extends Jt{constructor(u,d=16776960){super(new n,new er({color:d})),this.type="BoxHelper",this.isBoxHelper=!0,this.object=u,u&&this.update()}update(u){u!==void 0&&(this.object=u);let d=new a;this.object&&this.object!==this&&d.setFromObject(this.object);let M=d.isEmpty()?new n:fn(d.min.x,d.min.y,d.min.z,d.max.x,d.max.y,d.max.z);return this.position.set(0,0,0),this.quaternion.set(0,0,0,1),this.scale.set(1,1,1),this._sourceGeo=M,this.geometry=M,this}setFromObject(u){return this.update(u)}_bakeAuthorGeometry(){this.update(),super._bakeAuthorGeometry()}clone(u=!0){let d=new li(this.object,this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,cr(d,this,0,u)}dispose(){}}for(let T of[Mt,Pt,Ct,Xt,Ot,Yt,Qt,Zt,wi,Nr,Cr,Er,li])Object.freeze(T.prototype);let hr=["checkerboard","grid","wood","marble","brushedMetal","carbonFiber","concrete","brick","fabric","leather","rust"],mn=[[8,3359061,14870768,.6],[8,16317180,6583435,.7],[10,9132587,0,.6],[3,15857145,4674921,.25],[1,12106946,0,.32],[8,2040616,0,.35],[4,10265519,0,.9],[8,10107694,13157048,.85],[32,3890060,0,.9],[12,5913128,0,.6],[4,9124378,9080985,.9]],oa=(T,u,d)=>{let M=Math.imul(T,668265261)^Math.imul(u,374761393)^Math.imul(d,2654435769);return M^=M>>>15,M=Math.imul(M,2246822507),M^=M>>>13,M=Math.imul(M,3266489909),M^=M>>>16,M>>>0},vr=(T,u,d)=>oa(T,u,d)/4294967296,fr=(T,u)=>(T%u+u)%u,Lc=(T,u,d,M,L)=>{let $=Math.floor(T),B=Math.floor(u),U=T-$,j=u-B,K=fr($,d),ue=fr(B,M),le=(K+1)%d,oe=(ue+1)%M,fe=U*U*(3-2*U),ye=j*j*(3-2*j),ve=vr(K,ue,L),we=vr(le,ue,L),Te=vr(K,oe,L),Me=vr(le,oe,L);return ve+(we-ve)*fe+(Te-ve)*ye+(ve-we-Te+Me)*fe*ye},kr=(T,u,d,M,L,$)=>{let B=0,U=.5,j=0,K=1;for(let ue=0;ue<L;ue++){let le=d*K,oe=M*K;B+=U*Lc(T*le,u*oe,le,oe,$+ue>>>0),j+=U,U*=.5,K*=2}return B/j},io=T=>T-Math.floor(T),no=T=>Math.abs(io(T)*2-1),pn=(T,u,d)=>{let M=(d-T)/(u-T);return M<0?M=0:M>1&&(M=1),M*M*(3-2*M)},wr=(T,u,d)=>T+(u-T)*d,Fr=T=>T<=0?0:T>=1?255:Math.floor(T*255+.5),T0=(T,u,d,M,L,$,B,U,j,K,ue)=>{let le=Me=>[L[0]*Me,L[1]*Me,L[2]*Me],oe=(Me,be,Ce)=>[wr(Me[0],be[0],Ce),wr(Me[1],be[1],Ce),wr(Me[2],be[2],Ce)];if(T===0){let Me=fr(Math.floor(U*d)+Math.floor(j*d),2)===1?$:L;return[Me[0],Me[1],Me[2],.5,B,0]}if(T===1){let Me=io(U*d),be=io(j*d),Ce=Math.max(.035,d/u),Ie=1-pn(Ce*.5,Ce,Math.min(Me,1-Me,be,1-be));return[...oe(L,$,Ie),.3+.4*Ie,B,0]}if(T===2){let Me=kr(U,j,4,4,4,M),be=no(j*d+Me*1.5),Ce=kr(U,j,2,96,2,M+7>>>0),Ie=be*.7+Ce*.3;return[...le(wr(.55,1,Ie)),Ie,B+(1-Ie)*.15,0]}if(T===3){let Me=kr(U,j,3,3,5,M),be=no((U+j)*d+Me*2.5),Ce=be*be,Ie=Ce*Ce,ze=Ie*Ie,Ue=.92+.08*Me,He=oe(L,$,ze*.85);return[He[0]*Ue,He[1]*Ue,He[2]*Ue,.5-ze*.2,B+ze*.1,0]}if(T===4){let Me=kr(U,j,2,192*d,2,M),be=vr(K,ue,M+3>>>0);return[...le(.85+.12*Me+.03*be),.35+Me*.3,B+(Me-.5)*.12,1]}if(T===5){let Me=d*2,be=U*Me,Ce=j*Me,Ie=be-Math.floor(be),ze=Ce-Math.floor(Ce),Ue=fr(Math.floor(be)+Math.floor(Ce),2)===0,He=Ue?ze*2-1:Ie*2-1,Ke=1-He*He,et=.08*no(Ue?ze*8:Ie*8),Qe=.6+.4*Ke;return[L[0]*Qe+et,L[1]*Qe+et,L[2]*Qe+et,Ke*.8,B+.1*(1-Ke),0]}if(T===6){let Me=kr(U,j,d,d,5,M),be=vr(K,ue,M+31>>>0),Ce=d*16,Ie=pn(.82,.9,Lc(U*Ce,j*Ce,Ce,Ce,M+17>>>0));return[...le((.82+.25*Me+.06*(be-.5))*(1-.35*Ie)),.5+.25*(Me-.5)-.3*Ie,B-.05*Me,0]}if(T===7){let Me=Math.floor(d/2),be=j*d,Ce=Math.floor(be),Ie=be-Ce,ze=U*Me+(fr(Ce,2)===1?.5:0),Ue=Math.floor(ze),He=ze-Ue,Ke=Math.min(Math.min(He,1-He)*2,Math.min(Ie,1-Ie)),et=Math.max(.06,1.5*d/u),Qe=1-pn(et*.5,et,Ke),tt=vr(fr(Ue,Me),fr(Ce,d),M),Oe=kr(U,j,d,d,3,M+5>>>0),Xe=.8+.25*tt+.15*(Oe-.5),rt=.9+.1*Oe;return[wr(L[0]*Xe,$[0]*rt,Qe),wr(L[1]*Xe,$[1]*rt,Qe),wr(L[2]*Xe,$[2]*rt,Qe),(1-Qe)*(.75+.1*Oe)+Qe*.2,wr(B,.95,Qe),0]}if(T===8){let Me=U*d,be=j*d,Ce=(Me-Math.floor(Me))*2-1,Ie=(be-Math.floor(be))*2-1,ze=fr(Math.floor(Me)+Math.floor(be),2)===0?1-Ce*Ce:1-Ie*Ie,Ue=kr(U,j,4,4,2,M);return[...le((.75+.25*ze)*(.95+.1*(Ue-.5))),ze,B,0]}if(T===9){let Me=U*d,be=j*d,Ce=Math.floor(Me),Ie=Math.floor(be),ze=1e9,Ue=1e9;for(let et=-1;et<=1;et++)for(let Qe=-1;Qe<=1;Qe++){let tt=Ce+Qe,Oe=Ie+et,Xe=fr(tt,d),rt=fr(Oe,d),yt=tt+vr(Xe,rt,M)-Me,pt=Oe+vr(Xe,rt,M+1>>>0)-be,ot=yt*yt+pt*pt;ot<ze?(Ue=ze,ze=ot):ot<Ue&&(Ue=ot)}let He=1-pn(0,.12,Math.sqrt(Ue)-Math.sqrt(ze)),Ke=kr(U,j,4,4,3,M+3>>>0);return[...le((.85+.2*(Ke-.5))*(1-.3*He)),.6-.4*He+.1*(Ke-.5),B+.15*He,0]}let fe=kr(U,j,d,d,5,M),ye=pn(.45,.6,fe),ve=kr(U,j,d*8,d*8,3,M+9>>>0),we=.9+.1*ve,Te=.7+.5*ve;return[wr($[0]*we,L[0]*Te,ye),wr($[1]*we,L[1]*Te,ye),wr($[2]*we,L[2]*Te,ye),.4+.4*ye*ve+.1*ye,wr(.35,B,ye),1-ye]},P0=(T,u,d,M,L,$,B,U)=>{let j=globalThis.__three_live_native_material_preset__;if(typeof j=="function"){let oe=j(T,u,d,M,...L,...$,B,U);if(Array.isArray(oe)&&oe.length===3)return oe}let K=new Uint8Array(u*u*4),ue=new Uint8Array(u*u*4),le=new Float64Array(u*u);for(let oe=0;oe<u;oe++){let fe=(oe+.5)/u;for(let ye=0;ye<u;ye++){let ve=T0(T,u,d,M,L,$,B,(ye+.5)/u,fe,ye,oe),we=(oe*u+ye)*4;K[we]=Fr(ve[0]),K[we+1]=Fr(ve[1]),K[we+2]=Fr(ve[2]),K[we+3]=255,ue[we]=255,ue[we+1]=Fr(ve[4]),ue[we+2]=Fr(ve[5]),ue[we+3]=255,le[oe*u+ye]=ve[3]}}return[K,Rc(le,u,U),ue]},Rc=(T,u,d)=>{let M=new Uint8Array(u*u*4),L=d*u*.0625;for(let $=0;$<u;$++){let B=($+u-1)%u,U=($+1)%u;for(let j=0;j<u;j++){let K=-(T[$*u+(j+1)%u]-T[$*u+(j+u-1)%u])*L,ue=(T[U*u+j]-T[B*u+j])*L,le=1/Math.sqrt(K*K+ue*ue+1),oe=($*u+j)*4;M[oe]=Fr(K*le*.5+.5),M[oe+1]=Fr(ue*le*.5+.5),M[oe+2]=Fr(le*.5+.5),M[oe+3]=255}}return M},Ic=(T,u)=>{let d=u;try{T!=null&&(d=new xr(T).getHex())}catch{}return[(d>>16&255)/255,(d>>8&255)/255,(d&255)/255]},la=new Map,ao=(T,u={})=>{let d=hr.indexOf(T);if(d<0)throw new TypeError(`THREE.ProceduralTexture: unknown preset '${T}' (use ${hr.join(", ")})`);let M=u&&typeof u=="object"?u:{},L=mn[d],$=Math.max(1,Math.min(256,Math.round(Pe(M.scale,L[0]))));(d===0||d===7||d===8)&&$%2===1&&$++;let B=Math.max(16,Math.min(512,Math.round(Pe(M.size,256)))),U=Math.round(Math.abs(Pe(M.seed,1)))>>>0,j=Ic(M.color,L[1]),K=Ic(M.color2,L[2]||L[1]),ue=at(Pe(M.roughness,L[3])),le=Math.max(0,Math.min(8,Pe(M.normalStrength,1))),oe=[d,B,$,U,...j,...K,ue,le].join(","),fe=la.get(oe);if(fe)return{...fe};let[ye,ve,we]=P0(d,B,$,U,j,K,ue,le),Te=(Ce,Ie)=>{let ze=new _e(B,B);ze._data.set(Ce),ze._ver++;let Ue=new W(ze);return Ue.flipY=!1,Ue.colorSpace=Ie,Ue.name=`${T}_${Ie==="srgb"?"albedo":Ce===ve?"normal":"orm"}`,Ue},Me=Te(we,"srgb-linear"),be={map:Te(ye,"srgb")};return le>0&&(be.normalMap=Te(ve,"srgb-linear")),be.roughnessMap=Me,be.metalnessMap=Me,la.size>=64&&la.clear(),la.set(oe,be),{...be}},so={presets:Object.freeze(hr.slice()),create:(T,u)=>ao(String(T),u)};for(let T of hr)so[T]=u=>ao(T,u);Object.freeze(so);let N0=500,C0=T=>{if(typeof T!="string")return null;let u="",d=!1;for(let M=0;M<T.length;M++){let L=T.charCodeAt(M);if(L<=32||L===127){d=u.length>0;continue}d&&(u+=" ",d=!1),u+=T[M]}return u.length===0||u.length>N0?null:u},E0=T=>{let u=typeof T=="number"?T:NaN;return Number.isFinite(u)?u<=384?256:u<=768?512:1024:512},$c=T=>T>512&&T%2===0?T/2:T,L0=(T,u)=>{let d=u/2,M=new Uint8Array(d*d*4);for(let L=0;L<d;L++)for(let $=0;$<d;$++){let B=(2*L*u+2*$)*4,U=B+u*4,j=(L*d+$)*4;for(let K=0;K<4;K++)M[j+K]=T[B+K]+T[B+4+K]+T[U+K]+T[U+4+K]+2>>2}return M},R0=T=>{let u=typeof T=="number"?T:NaN,d=Number.isFinite(u)?Math.abs(u):1;return Math.floor(d+.5)%4294967296},I0=T=>{let u=[];for(let d=0;d<T.length;d++){let M=T.charCodeAt(d);if(M>=55296&&M<=56319&&d+1<T.length){let L=T.charCodeAt(d+1);L>=56320&&L<=57343?(M=65536+(M-55296<<10)+(L-56320),d++):M=65533}else M>=55296&&M<=57343&&(M=65533);M<128?u.push(M):M<2048?u.push(192|M>>6,128|M&63):M<65536?u.push(224|M>>12,128|M>>6&63,128|M&63):u.push(240|M>>18,128|M>>12&63,128|M>>6&63,128|M&63)}return u},$0=(T,u,d)=>{let M=I0(`three-live-texture1${T}${u}${d}`),L=3421674724,$=2216829733;for(let B of M){$=($^B)>>>0;let U=$&65535,j=$>>>16,K=U*435,ue=j*435+(K>>>16),le=(ue&65535)<<16|K&65535,oe=Math.floor(ue/65536);L=Math.imul(L,435)+oe+($<<8>>>0)>>>0,$=le>>>0}return L.toString(16).padStart(8,"0")+$.toString(16).padStart(8,"0")},Dc=T=>{let u=C0(T?.prompt);if(u===null)return null;let d=E0(T?.size),M=R0(T?.seed);return{prompt:u,size:d,seed:M,key:$0(u,d,M)}},oo=(T,u,d,M,L)=>{if($c(u)!==u)return oo(L0(T,u),u/2,d,M,L);let $=new Float64Array(u*u);for(let be=0;be<u*u;be++){let Ce=be*4;$[be]=2126*T[Ce]+7152*T[Ce+1]+722*T[Ce+2]}let B=Math.min(4,Math.floor((u-1)/2)),U=new Float64Array(u*u);for(let be=0;be<u;be++)for(let Ce=0;Ce<u;Ce++){let Ie=0;for(let ze=0;ze<=2*B;ze++)Ie+=$[be*u+(Ce+u+ze-B)%u];U[be*u+Ce]=Ie}let j=(2*B+1)*(2*B+1),K=new Float64Array(u*u),ue=1/0,le=-1/0;for(let be=0;be<u;be++)for(let Ce=0;Ce<u;Ce++){let Ie=0;for(let Ue=0;Ue<=2*B;Ue++)Ie+=U[(be+u+Ue-B)%u*u+Ce];let ze=j*$[be*u+Ce]-Ie;K[be*u+Ce]=ze,ze<ue&&(ue=ze),ze>le&&(le=ze)}let oe=le-ue,fe=new Float64Array(u*u);for(let be=0;be<u*u;be++)fe[be]=oe===0?.5:(K[be]-ue)/oe;let ye=Number.isFinite(d)?Math.max(0,Math.min(8,d)):1,ve=Rc(fe,u,ye),we=Number.isFinite(M)?Math.max(0,Math.min(1,M)):0,Te=Fr(Number.isFinite(L)?Math.max(0,Math.min(1,L)):0),Me=new Uint8Array(u*u*4);for(let be=0;be<u*u;be++){let Ce=be*4;Me[Ce]=255,Me[Ce+1]=Fr(we+.35*(.5-fe[be])),Me[Ce+2]=Te,Me[Ce+3]=255}return[ve,Me]},ua=new Map,kc=new WeakMap,D0=0,k0=(T,u)=>{let d=Dc(T);if(!d)return null;let{prompt:M,size:L,seed:$,key:B}=d,U=at(Pe(T.roughness,u>=0?mn[u][3]:.8)),j=at(Pe(T.metalness,0)),K=Math.max(0,Math.min(8,Pe(T.normalStrength,1))),ue=globalThis,le=ue.__three_live_native_texture_pack__,oe=ue.__three_live_texture_pack__,fe=0;if(typeof le=="function"){let Ie=ue.__three_live_native_texture_pack_token__;fe=typeof Ie=="function"&&Number(Ie())||0}else oe&&typeof oe=="object"&&(fe=kc.get(oe)??0,fe||kc.set(oe,fe=++D0));let ye=[fe,B,K,U,j].join(","),ve=fe?ua.get(ye):void 0;if(ve)return{...ve};let we=null;if(typeof le=="function"){let Ie=le(M,L,$,K,U,j);Array.isArray(Ie)&&Ie.length===3&&(we=Ie)}else{let Ie=oe&&typeof oe=="object"&&Object.prototype.hasOwnProperty.call(oe,B)?oe[B]:null;Ie&&Ie.size===L&&Ie.rgba instanceof Uint8Array&&Ie.rgba.length===L*L*4&&(we=[Ie.rgba,...oo(Ie.rgba,L,K,U,j)])}if(!we)return null;let Te=(Ie,ze,Ue,He)=>{let Ke=new W({data:new Uint8ClampedArray(Ie.buffer,Ie.byteOffset,ze*ze*4),width:ze,height:ze});return Ke.flipY=!1,Ke.colorSpace=Ue,Ke.name=`ai_${B}_${He}`,Ke._pngDim=ze,Ke},Me=$c(L),be=Te(we[2],Me,"srgb-linear","orm"),Ce={map:Te(we[0],L,"srgb","albedo")};return K>0&&(Ce.normalMap=Te(we[1],Me,"srgb-linear","normal")),Ce.roughnessMap=be,Ce.metalnessMap=be,fe&&(ua.size>=32&&ua.clear(),ua.set(ye,Ce)),{...Ce}},Fc=new Set,F0=T=>{let u=T?.userData?.xr?.material,d=T?.material;if(u==null||!d||typeof d!="object"||Array.isArray(d))return;let M=typeof u=="string"?{preset:u}:typeof u=="object"?u:null,L=String(M?.preset??M?.type??""),$=hr.indexOf(L),B=!!M&&M.prompt!==void 0&&M.prompt!==null,U=B?k0(M,$):null;if(!M||$<0&&!U){!(B&&L==="")&&!Fc.has(L)&&(Fc.add(L),console.warn(`[three-live] userData.xr.material: unknown preset '${L}' (use ${hr.join(", ")}).`));return}d._presetTint===void 0&&(d._presetTint=d.color?.getHex?.()??16777215);let j="";try{j=JSON.stringify([M,d._presetTint])}catch{j=L}if(d._presetKey===j)return;if(d._presetOwner&&d._presetOwner!==T){let le=Object.assign(Object.create(Object.getPrototypeOf(d)),d);le.color=new xr(d._presetTint);for(let oe of["_presetKey","_presetMaps","_presetOwner"])le[oe]=void 0;for(let oe of["map","normalMap","roughnessMap","metalnessMap"])d._presetMaps?.[oe]&&le[oe]===d._presetMaps[oe]&&(le[oe]=null);T.material=d=le}let K=U??ao(L,{...M,color:M.color??(d._presetTint===16777215?void 0:d._presetTint)}),ue=d._presetMaps||{};for(let le of["map","normalMap","roughnessMap","metalnessMap"])(!d[le]||d[le]===ue[le])&&(d[le]=K[le]??null,ue[le]=K[le]??null);ue.map===d.map&&d.color?.set?.(16777215),ue.roughnessMap===d.roughnessMap&&(d.roughness=1),ue.metalnessMap===d.metalnessMap&&(d.metalness=1),d._presetMaps=ue,d._presetKey=j,d._presetOwner=T},Bc={Box3:a,Sphere:o,CanvasTexture:W,ImprovedNoise:pe,SimplexNoise:je,SpriteMaterial:wt,Sprite:Gt,LineCurve:Pt,QuadraticBezierCurve:Ct,CubicBezierCurve:Xt,SplineCurve:Ot,EllipseCurve:Yt,ArcCurve:Qt,CurvePath:Zt,GridHelper:wi,AxesHelper:Nr,ArrowHelper:Cr,Box3Helper:Er,BoxHelper:li,ProceduralTexture:so};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,Bc),t.createCanvas=D,t._procMaterialize=F0,t.canonicalTextureSpec=Dc,t.deriveTextureMaps=oo,t.encodeRgbaPngDataUri=(T,u,d)=>_(T,u,d,!1,!1,f).uri,t.materializeDeclarativeGeometry=T=>{t._cadMaterialize?.(T),t._lodMaterialize?.(T),t._procMaterialize?.(T)}),Bc}var _o={name:"procedural",onRegister(){Mn(ga);let e=We(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&ga(t,e)}};function oh(e){if(typeof e!="function")return null;let t=new Uint32Array(256);for(let h=0;h<256;h++){let p=h;for(let g=0;g<8;g++)p=p&1?3988292384^p>>>1:p>>>1;t[h]=p>>>0}let r=(h,p,g)=>{let x=4294967295;for(let v=p;v<g;v++)x=t[(x^h[v])&255]^x>>>8;return(x^4294967295)>>>0},i=(h,p)=>(h[p]<<24|h[p+1]<<16|h[p+2]<<8|h[p+3])>>>0,n=(h,p,g)=>{h[p]=g>>>24,h[p+1]=g>>>16&255,h[p+2]=g>>>8&255,h[p+3]=g&255},a=h=>{let p=new e("deflate"),g=p.writable.getWriter();g.write(h).catch(()=>{}),g.close().catch(()=>{});let x=p.readable.getReader(),v=[],y=0,A=()=>x.read().then(b=>{if(b.done){let w=new Uint8Array(y),S=0;for(let E=0;E<v.length;E++)w.set(v[E],S),S+=v[E].length;return w}return b.value&&(v.push(b.value),y+=b.value.length),A()});return A()},s=h=>{if(h.length<45||i(h,0)!==2303741511||i(h,12)!==1229472850)return null;let p=i(h,16),g=i(h,20);if(h[24]!==8||h[25]!==6||h[28]!==0||!p||!g||p>4096||g>4096)return null;let x=1+p*4,v=new Uint8Array(x*g),y=0,A=33,b=-2,w=0,S=[],E=!1;for(;A+8<=h.length&&!E;){let N=i(h,A),C=i(h,A+4),_=A+8,P=_+N;if(P+4>h.length)return null;if(C===1229209940)for(let R=_;R<P&&!E;){if(b<0)b++,R++;else if(w>0){let I=Math.min(w,P-R);if(y+I>v.length)return null;v.set(h.subarray(R,R+I),y),y+=I,R+=I,w-=I,w===0&&S[0]&1&&(E=!0)}else{if(S.push(h[R++]),S.length===1&&S[0]>>1&3)return null;if(S.length===5){let I=S[1]|S[2]<<8;if((I^(S[3]|S[4]<<8))!==65535)return null;w=I,I===0&&(S[0]&1&&(E=!0),S=[])}}w===0&&S.length===5&&(S=[])}else if(C===1229278788)break;A=P+4}if(y!==v.length)return null;for(let N=0;N<g;N++)if(v[N*x]!==0)return null;return{w:p,h:g,raw:v}},o=(h,p,g)=>{let x=p*4,v=x+1,y=new Uint8Array(h.length),A=new Uint8Array(x),b=new Uint8Array(x);for(let w=0;w<g;w++){let S=w*v+1,E=S-v,N=0,C=1/0;for(let _=0;_<5;_++){if(_===3||(_===2||_===4)&&w===0)continue;let P=0;for(let R=0;R<x;R++){let I=R>=4?h[S+R-4]:0,F=w>0?h[E+R]:0,V=0;if(_===1)V=I;else if(_===2)V=F;else if(_===4){let J=R>=4&&w>0?h[E+R-4]:0,re=I+F-J,Q=Math.abs(re-I),ee=Math.abs(re-F),k=Math.abs(re-J);V=Q<=ee&&Q<=k?I:ee<=k?F:J}let Y=h[S+R]-V&255;A[R]=Y,P+=Y<128?Y:256-Y}P<C&&(C=P,N=_,b.set(A))}y[w*v]=N,y.set(b,S)}return y},l=h=>{let p=null;try{p=s(h)}catch{p=null}if(!p)return Promise.resolve(h);let{w:g,h:x,raw:v}=p;return a(o(v,g,x)).then(y=>{let A=45+y.length+12;if(A>=h.length)return h;let b=new Uint8Array(A);b.set(h.subarray(0,33),0),n(b,33,y.length),n(b,37,1229209940),b.set(y,41),n(b,41+y.length,r(b,37,41+y.length));let w=45+y.length;return n(b,w,0),n(b,w+4,1229278788),n(b,w+8,2923585666),b},()=>h)},c=new Int16Array(128).fill(-1),f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let h=0;h<64;h++)c[f.charCodeAt(h)]=h;let m=h=>{let p=h.length;for(;p>0&&h.charCodeAt(p-1)===61;)p--;let g=new Uint8Array(Math.floor(p*3/4)),x=0,v=0,y=0;for(let A=0;A<p;A++){let b=h.charCodeAt(A),w=b<128?c[b]:-1;if(w<0)return null;x=(x<<6|w)&16777215,v+=6,v>=8&&(v-=8,g[y++]=x>>v&255)}return y===g.length?g:null};return{png:l,glb:h=>{let p=(R,I)=>(R[I]|R[I+1]<<8|R[I+2]<<16|R[I+3]<<24)>>>0,g=(R,I,F)=>{R[I]=F&255,R[I+1]=F>>>8&255,R[I+2]=F>>>16&255,R[I+3]=F>>>24},x,v=new Uint8Array(0);try{if(h.length<20||p(h,0)!==1179937895)return Promise.resolve(h);let R=Math.min(h.length,p(h,8)),I=p(h,12);if(p(h,16)!==1313821514||20+I>R)return Promise.resolve(h);x=JSON.parse(new TextDecoder().decode(h.subarray(20,20+I)));let F=20+I;if(F+8<=R){let V=p(h,F);if(p(h,F+4)!==5130562||F+8+V>R)return Promise.resolve(h);v=h.subarray(F+8,F+8+V)}}catch{return Promise.resolve(h)}if(!x||typeof x!="object")return Promise.resolve(h);let y=Array.isArray(x.bufferViews)?x.bufferViews:[],A=Array.isArray(x.images)?x.images:[],b=[],w=[],S=[],E="data:image/png;base64,";for(let R=0;R<A.length;R++){let I=A[R];if(!I||typeof I!="object")continue;let F=y[I.bufferView];if(typeof I.uri=="string"&&I.uri.indexOf(E)===0){let V=m(I.uri.slice(E.length));V&&(w.push(R),S.push(V))}else I.mimeType==="image/png"&&F&&(F.buffer||0)===0&&b.indexOf(I.bufferView)<0&&b.push(I.bufferView)}if(!b.length&&!w.length)return Promise.resolve(h);let N=[];for(let R=0;R<y.length;R++)N.push(R);N.sort((R,I)=>(y[R].byteOffset||0)-(y[I].byteOffset||0));let C=0;for(let R=0;R<N.length;R++){let I=y[N[R]],F=I.byteOffset||0;if(typeof I.byteLength!="number"||(I.buffer||0)!==0||F<C||F+I.byteLength>v.length)return Promise.resolve(h);C=F+I.byteLength}let _=R=>{let I=y[R].byteOffset||0;return v.subarray(I,I+y[R].byteLength)},P=[];for(let R=0;R<b.length;R++)P.push(l(_(b[R])));for(let R=0;R<S.length;R++)P.push(l(S[R]));return Promise.all(P).then(R=>{let I=[];for(let k=0;k<y.length;k++){let G=b.indexOf(k);I.push(G>=0?R[G]:_(k))}let F=0;for(let k=0;k<N.length;k++)F=(F+3&-4)+I[N[k]].length;for(let k=0;k<w.length;k++)F=(F+3&-4)+R[b.length+k].length;let V=F+3&-4,Y=new Uint8Array(V),J=0;for(let k=0;k<N.length;k++){let G=N[k];J=J+3&-4,Y.set(I[G],J),y[G].byteOffset=J,y[G].byteLength=I[G].length,J+=I[G].length}for(let k=0;k<w.length;k++){let G=R[b.length+k];J=J+3&-4,Y.set(G,J);let q=A[w[k]];delete q.uri,q.mimeType="image/png",q.bufferView=y.length,y.push({buffer:0,byteOffset:J,byteLength:G.length}),J+=G.length}x.bufferViews=y,!Array.isArray(x.buffers)||!x.buffers.length?x.buffers=[{byteLength:V}]:x.buffers[0].byteLength=V;let re=new TextEncoder().encode(JSON.stringify(x)),Q=re.length+3&-4;if(Q!==re.length){let k=new Uint8Array(Q).fill(32);k.set(re),re=k}let ee=new Uint8Array(20+Q+8+V);return g(ee,0,1179937895),g(ee,4,2),g(ee,8,ee.length),g(ee,12,Q),g(ee,16,1313821514),ee.set(re,20),g(ee,20+Q,V),g(ee,24+Q,5130562),ee.set(Y,28+Q),ee.length<h.length?ee:h})}}}var ap={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Fi(e,t,r,i){if(!r||r.bufferView===void 0)return null;let n=e.bufferViews?.[r.bufferView];if(!n)return null;let a=Number(r.count??0);if(!Number.isInteger(a)||a<=0)return null;let s=r.componentType??5126,o=ap[s];if(!o)throw new RangeError(`glTF accessor has unsupported componentType ${s}`);let l=o*i,c=n.byteStride&&n.byteStride>0?n.byteStride:l,f=(n.byteOffset||0)+(r.byteOffset||0);if(!Number.isInteger(f)||f<0||c<l||f+(a-1)*c+l>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(s===5126&&c===l&&f%4===0)return new Float32Array(t,f,a*i);let m=new DataView(t),h=r.normalized===!0,p=new Float32Array(a*i);for(let g=0;g<a;g++){let x=f+g*c;for(let v=0;v<i;v++){let y=x+v*o,A;switch(s){case 5126:A=m.getFloat32(y,!0);break;case 5120:A=m.getInt8(y),h&&(A=Math.max(A/127,-1));break;case 5121:A=m.getUint8(y),h&&(A/=255);break;case 5122:A=m.getInt16(y,!0),h&&(A=Math.max(A/32767,-1));break;case 5123:A=m.getUint16(y,!0),h&&(A/=65535);break;default:A=m.getUint32(y,!0),h&&(A/=4294967295)}p[g*i+v]=A}}return p}function sp(e,t){let r=Number(t.offset?.[0]??0)||0,i=Number(t.offset?.[1]??0)||0,n=Number(t.scale?.[0]??1),a=Number(t.scale?.[1]??1),s=Number(t.rotation??0)||0,o=Math.cos(s),l=Math.sin(s),c=(Number.isFinite(n)?n:1)*o,f=(Number.isFinite(n)?n:1)*l,m=-(Number.isFinite(a)?a:1)*l,h=(Number.isFinite(a)?a:1)*o;for(let p=0;p+1<e.length;p+=2){let g=e[p],x=e[p+1];e[p]=c*g+f*x+r,e[p+1]=m*g+h*x+i}}function _i(e,t,r,i=!0){let n=[],a=null;try{for(let[s,o]of[[35633,t],[35632,r]]){let l=e.createShader(s);if(!l){if(i)throw new Error("Shader allocation failed");return null}if(n.push(l),e.shaderSource(l,o),e.compileShader(l),e.getShaderParameter&&!e.getShaderParameter(l,35713)){if(i)throw new Error(`Shader compile error: ${e.getShaderInfoLog(l)}`);return null}}if(a=e.createProgram(),!a){if(i)throw new Error("Program allocation failed");return null}for(let s of n)e.attachShader(a,s);if(e.linkProgram(a),e.getProgramParameter&&!e.getProgramParameter(a,35714)){let s=i?e.getProgramInfoLog(a):null;if(e.deleteProgram?.(a),a=null,i)throw new Error(`Program link error: ${s}`);return null}return a}finally{for(let s of n)a&&e.detachShader?.(a,s),e.deleteShader?.(s)}}var lh=["neutral","reinhard","none","aces","agx"];function Bi(e){let t=String(e??"").trim().toLowerCase();return lh.includes(t)?t:"neutral"}function op(e){return lh.indexOf(Bi(e))}function lp(e){return new TextDecoder().decode(e)}var uh=We().decoders;function up(e,t){uh.set(e.toLowerCase(),t)}function ya(e){return uh.get(e.toLowerCase())}function ch(e){let t=ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e,r=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let i=r.getUint32(0,!0);if(i!==1179937895){let h=r.getUint8(0);throw h===123||h===32||h===10||h===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${i.toString(16)}`)}let n=r.getUint32(4,!0);if(n!==2)throw new Error(`Unsupported GLB version: ${n}`);let a=r.getUint32(8,!0),s=12,o=null,l=null;for(;s+8<=a&&s+8<=t.byteLength;){let h=r.getUint32(s,!0),p=r.getUint32(s+4,!0),g=s+8;if(g+h>t.byteLength)throw new Error(`Truncated GLB chunk: required ${g+h} bytes, buffer has ${t.byteLength}`);if(p===1313821514){let x=new Uint8Array(t,g,h),v=lp(x);o=JSON.parse(v,(y,A)=>y==="__proto__"||y==="constructor"||y==="prototype"?void 0:A)}else p===5130562&&(l=t.slice(g,g+h));s=g+h}if(!o)throw new Error("Missing JSON chunk in GLB");let c=o.extensionsRequired||[];for(let[h,p]of[["KHR_draco_mesh_compression","draco"],["EXT_meshopt_compression","meshopt"],["KHR_meshopt_compression","meshopt"],["KHR_texture_basisu","ktx2"]])if(c.includes(h)&&!ya(p))throw new Error(`Model requires ${h}. Register a decoder via ThreeLiveElement.registerDecoder('${p}', decoder).`);let f=l||new ArrayBuffer(0),m={gltf:o,bin:f,animations:[],animationsParsed:!1};for(let h of Lt)h.onParseGLB?.(m);return m}function hh(e,t=An(e)){let r=e?.extensions?.KHR_lights_punctual?.lights;if(!Array.isArray(r))return[];let i=[],n=new Set,a=(s,o,l,c)=>{let f=s.type,m=f==="directional"||f==="point"||f==="spot"?f:"ambient",h=o?o[8]:-.5,p=o?o[9]:-1,g=o?o[10]:-.8,x=Math.hypot(h,p,g)||1,v=s.extras?.shadow??l,y=s.name||c,A={type:m,color:s.color||[1,1,1],intensity:s.intensity??1};y&&(A.name=y),o&&(A.position=[o[12],o[13],o[14]]),m==="directional"&&o?A.direction=[h/x,p/x,g/x]:(m==="spot"&&(A.direction=o?[-h/x,-p/x,-g/x]:[0,-1,0],A.innerConeAngle=s.spot?.innerConeAngle??0,A.outerConeAngle=s.spot?.outerConeAngle??Math.PI/4),A.range=s.range),v&&(A.shadow=v),i.push(A)};return(e.nodes||[]).forEach((s,o)=>{let l=s?.extensions?.KHR_lights_punctual?.light;typeof l=="number"&&r[l]&&(n.add(l),a(r[l],t[o],s.extras?.shadow,s.name))}),r.forEach((s,o)=>{n.has(o)||a(s)}),i}function cp(e){return typeof e=="object"&&e!==null&&"gltf"in e&&typeof e.gltf=="object"&&e.gltf!==null&&"bin"in e&&(e.bin instanceof ArrayBuffer||ArrayBuffer.isView(e.bin))}function zi(e){if(cp(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return ch(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var So=`#version 300 es
18
18
  layout(location=0) in vec3 aPos;
19
19
  layout(location=3) in vec3 aOff;
20
20
  layout(location=1) in vec3 aNormal;
@@ -49,7 +49,7 @@ vec2 scaleUV=uUvTransform.zw;
49
49
  if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
50
50
  vUV=aUV*scaleUV+uUvTransform.xy;
51
51
  gl_Position=uMVP*vec4(aPosition,1.0);
52
- }`,nl=`#version 300 es
52
+ }`,hp=`#version 300 es
53
53
  precision highp float;
54
54
  in vec3 vNormal,vWorldPos;
55
55
  in vec2 vUV;
@@ -58,117 +58,81 @@ in vec4 vInstTint;
58
58
  #define uBaseColor (uBaseColor*vInstTint)
59
59
  uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity,uExposure;
60
60
  uniform vec2 uClearcoat;
61
- uniform vec3 uCameraPos,uAmbientColor;
62
- uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap;
63
- uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap;
61
+ uniform vec3 uCameraPos,uAmbientColor,uEmissiveFactor;
62
+ uniform mat3 uHemi;
63
+ uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap,uEmissiveTexture;
64
+ uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap,uHasEmissiveTexture;
64
65
  uniform float uNormalScale,uOcclusionStrength;
65
- /*XRD_U*/
66
+ /*XRD_U*//*SHD_U*/
66
67
  uniform vec2 uViewportSize;
67
68
  uniform vec4 uSectionPlane;
68
69
  uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
69
70
  uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2],uPointLightSpotDir[2];
70
71
  uniform vec2 uPointLightSpotCone[2];
71
72
  out vec4 fragColor;
72
-
73
73
  vec2 envBRDF(float r,float n){
74
- vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04);
75
- vec4 rv=r*c0+c1;
74
+ vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04),rv=r*c0+c1;
76
75
  float a=min(rv.x*rv.x,exp2(-9.28*n))*rv.x+rv.y;
77
76
  return vec2(-1.04,1.04)*a+rv.zw;
78
77
  }
79
-
80
78
  vec3 F_SchlickRoughness(vec3 F0,float r,float n){
81
79
  return F0+(max(vec3(1.0-r),F0)-F0)*pow(clamp(1.0-n,0.0,1.0),5.0);
82
80
  }
83
-
84
81
  vec3 getStudioRadiance(vec3 R,float r){
85
- vec3 kd=normalize(vec3(0.0,1.0,0.35));
82
+ vec3 kd=normalize(vec3(0.0,1.0,0.35)),fd=normalize(vec3(-0.85,0.45,-0.35));
86
83
  float ki=pow(max(dot(R,kd),0.0),mix(96.0,1.5,r))*mix(2.4,0.5,r);
87
- vec3 fd=normalize(vec3(-0.85,0.45,-0.35));
88
84
  float fi=pow(max(dot(R,fd),0.0),mix(36.0,1.2,r))*mix(1.3,0.35,r);
89
85
  float ri=pow(clamp(1.0-abs(R.y),0.0,1.0),3.5)*mix(0.55,0.22,r);
90
- vec3 ag=mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5);
91
- return ag+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
86
+ return mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5)+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
92
87
  }
93
-
94
- vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D normalMap,float scale){
95
- vec3 mapNormal=texture(normalMap,uv).xyz*2.0-1.0;
96
- mapNormal.xy*=scale;
97
- vec3 dp1=dFdx(vWorldPos);
98
- vec3 dp2=dFdy(vWorldPos);
99
- vec2 duv1=dFdx(uv);
100
- vec2 duv2=dFdy(uv);
101
- vec3 dp2perp=cross(dp2,N);
102
- vec3 dp1perp=cross(N,dp1);
103
- vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;
104
- vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;
105
- float invmax=inversesqrt(max(dot(T,T),dot(B,B)));
106
- return normalize(mat3(T*invmax,B*invmax,N)*normalize(mapNormal));
88
+ vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D m,float s){
89
+ vec3 q=texture(m,uv).xyz*2.0-1.0;q.xy*=s;
90
+ vec3 p1=dFdx(vWorldPos),p2=dFdy(vWorldPos),c2=cross(p2,N),c1=cross(N,p1);
91
+ vec2 u1=dFdx(uv),u2=dFdy(uv);
92
+ vec3 T=c2*u1.x+c1*u2.x,B=c2*u1.y+c1*u2.y;
93
+ float k=inversesqrt(max(dot(T,T),dot(B,B)));
94
+ return normalize(mat3(T*k,B*k,N)*normalize(q));
107
95
  }
108
-
109
96
  vec2 equirectangularUV(vec3 dir){
110
97
  vec3 d=normalize(dir);
111
- float u=atan(d.z,d.x)*0.15915494309+0.5;
112
- float v=asin(clamp(d.y,-1.0,1.0))*0.31830988618+0.5;
113
- return vec2(u,1.0-v);
114
- }
115
-
116
- vec3 neutralToneMapping(vec3 color){
117
- const float startCompression=0.76;
118
- const float desaturation=0.15;
119
- float x=min(color.r,min(color.g,color.b));
120
- float offset=x<0.08?x-6.25*x*x:0.04;
121
- color-=offset;
122
- float peak=max(color.r,max(color.g,color.b));
123
- if(peak<startCompression)return color;
124
- const float d=1.0-startCompression;
125
- float newPeak=1.0-d*d/(peak+d-startCompression);
126
- color*=newPeak/peak;
127
- float g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);
128
- return mix(color,newPeak*vec3(1.0),g);
129
- }
130
-
131
- vec3 acesToneMapping(vec3 color){
132
- color*=0.6;
133
- return clamp((color*(2.51*color+0.03))/(color*(2.43*color+0.59)+0.14),0.0,1.0);
134
- }
135
-
136
- vec3 agxToneMapping(vec3 color){
137
- color=max(color,vec3(0.0));
138
- vec3 inset=vec3(
139
- 0.84247906*color.r+0.0784336*color.g+0.07922375*color.b,
140
- 0.04232824*color.r+0.87846864*color.g+0.07916613*color.b,
141
- 0.04237565*color.r+0.0784336*color.g+0.87914297*color.b);
142
- vec3 ev=clamp((log2(max(inset,vec3(1e-6)))+12.47393)/16.5,0.0,1.0);
143
- vec3 x2=ev*ev;
144
- vec3 x4=x2*x2;
145
- vec3 s=15.5*x4*x2-40.14*x4*ev+31.96*x4-6.868*x2*ev+0.4298*x2+0.1191*ev-0.00232;
146
- vec3 outset=vec3(
147
- 1.196879*s.r-0.09802088*s.g-0.09902974*s.b,
148
- -0.05289685*s.r+1.15190313*s.g-0.09896118*s.b,
149
- -0.05297164*s.r-0.09804345*s.g+1.15107367*s.b);
150
- return clamp(pow(max(outset,vec3(0.0)),vec3(2.2)),0.0,1.0);
151
- }
152
-
153
- vec3 applyToneMapping(vec3 color,int mode){
154
- if(mode==0)return neutralToneMapping(color);
155
- if(mode==1)return color/(color+vec3(1.0));
156
- if(mode==3)return acesToneMapping(color);
157
- if(mode==4)return agxToneMapping(color);
158
- return color;
159
- }
160
-
161
- vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 base,float specExp,float specWeight){
162
- float NoH=max(dot(N,normalize(L+V)),0.0);
163
- return base*max(dot(N,L),0.0)*0.75+vec3(pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
98
+ return vec2(atan(d.z,d.x)*0.15915494309+0.5,0.5-asin(clamp(d.y,-1.0,1.0))*0.31830988618);
99
+ }
100
+ vec3 neutralToneMapping(vec3 c){
101
+ float x=min(c.r,min(c.g,c.b));
102
+ c-=x<0.08?x-6.25*x*x:0.04;
103
+ float p=max(c.r,max(c.g,c.b));
104
+ if(p<0.76)return c;
105
+ float n=1.0-0.0576/(p-0.52);
106
+ c*=n/p;
107
+ return mix(c,vec3(n),1.0-1.0/(0.15*(p-n)+1.0));
108
+ }
109
+ vec3 acesToneMapping(vec3 c){
110
+ c*=0.6;return clamp((c*(2.51*c+0.03))/(c*(2.43*c+0.59)+0.14),0.0,1.0);
111
+ }
112
+ vec3 agxToneMapping(vec3 c){
113
+ c=max(c,vec3(0.0));
114
+ vec3 i=mat3(0.84247906,0.04232824,0.04237565,0.0784336,0.87846864,0.0784336,0.07922375,0.07916613,0.87914297)*c;
115
+ vec3 e=clamp((log2(max(i,vec3(1e-6)))+12.47393)/16.5,0.0,1.0),x2=e*e,x4=x2*x2;
116
+ vec3 s=15.5*x4*x2-40.14*x4*e+31.96*x4-6.868*x2*e+0.4298*x2+0.1191*e-0.00232;
117
+ vec3 o=mat3(1.196879,-0.05289685,-0.05297164,-0.09802088,1.15190313,-0.09804345,-0.09902974,-0.09896118,1.15107367)*s;
118
+ return clamp(pow(max(o,vec3(0.0)),vec3(2.2)),0.0,1.0);
119
+ }
120
+ vec3 applyToneMapping(vec3 c,int m){
121
+ return m==0?neutralToneMapping(c):m==1?c/(c+vec3(1.0)):m==3?acesToneMapping(c):m==4?agxToneMapping(c):c;
122
+ }
123
+ vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 b,float e,float w){
124
+ float h=max(dot(N,normalize(L+V)),0.0);
125
+ return b*max(dot(N,L),0.0)*0.75+vec3(pow(h,e)*w+uClearcoat.x*pow(h,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
164
126
  }
165
127
 
166
128
  void main(){
167
129
  if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
168
130
  vec4 base=uBaseColor;
169
131
  if(uHasTexture==1)base*=texture(uBaseColorTexture,vUV);
132
+ if(base.a<0.004)discard;
133
+ vec3 em=uHasEmissiveTexture==1?uEmissiveFactor*texture(uEmissiveTexture,vUV).rgb:uEmissiveFactor;
170
134
  if(length(vNormal)<1e-4&&uHasTexture==1){
171
- vec3 unlit=base.rgb+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
135
+ vec3 unlit=base.rgb+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
172
136
  fragColor=vec4(unlit,base.a);
173
137
  return;
174
138
  }
@@ -200,7 +164,7 @@ float specWeight=mix(0.22*gloss,1.0,metallic);
200
164
  vec3 directLight=vec3(0.0);
201
165
  for(int i=0;i<2;i++){
202
166
  if(i>=uNumDirLights)break;
203
- directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i];
167
+ directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i]/*SHD_D*/;
204
168
  }
205
169
  for(int i=0;i<2;i++){
206
170
  if(i>=uNumPointLights)break;
@@ -209,7 +173,7 @@ float dist=length(toLight);
209
173
  vec3 L=toLight/max(dist,0.0001);
210
174
  float spotAtt=clamp((dot(-L,uPointLightSpotDir[i])-uPointLightSpotCone[i].y)/max(uPointLightSpotCone[i].x-uPointLightSpotCone[i].y,0.0001),0.0,1.0);
211
175
  spotAtt*=spotAtt;
212
- directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist);
176
+ directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist)/*SHD_P*/;
213
177
  }
214
178
 
215
179
  vec3 R=reflect(-V,N);
@@ -229,8 +193,9 @@ envDiffuse=mix(vec3(0.10,0.10,0.12),vec3(0.52,0.54,0.58),N.y*0.5+0.5);
229
193
  }
230
194
 
231
195
  vec3 kD=(vec3(1.0)-F)*(1.0-metallic);
196
+ directLight+=kD*base.rgb*mix(uHemi[1],uHemi[0],dot(N,uHemi[2])*0.5+0.5)*occ;
232
197
  vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
233
- vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
198
+ vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
234
199
  if(uClearcoat.x>0.0){
235
200
  vec3 ccF=F_SchlickRoughness(vec3(0.04),uClearcoat.y,NoV)*uClearcoat.x;
236
201
  color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
@@ -240,24 +205,24 @@ color=applyToneMapping(color,uToneMapping);
240
205
  float outAlpha=base.a;
241
206
  /*XRD_O*/
242
207
  fragColor=vec4(color,outAlpha);
243
- }`;function ta(e,t,r=1){t=qt(t);let i=Number.isFinite(r)?Math.max(0,r):1,[n,s,l]=[0,1,2].map(g=>Math.max(0,(Number(e[g])||0)*i)),o=g=>Math.max(0,Math.min(1,g)),a=g=>[g(n),g(s),g(l)];if(t==="none")return a(o);if(t==="reinhard")return a(g=>g/(g+1));if(t==="aces")return a(g=>{let x=g*.6;return o(x*(2.51*x+.03)/(x*(2.43*x+.59)+.14))});if(t==="agx"){let[g,x,b]=[.84247906*n+.0784336*s+.07922375*l,.04232824*n+.87846864*s+.07916613*l,.04237565*n+.0784336*s+.87914297*l].map(v=>{let p=o((Math.log2(Math.max(v,1e-6))+12.47393)/16.5),y=p*p,M=y*y;return 15.5*M*y-40.14*M*p+31.96*M-6.868*y*p+.4298*y+.1191*p-.00232});return[1.196879*g-.09802088*x-.09902974*b,-.05289685*g+1.15190313*x-.09896118*b,-.05297164*g-.09804345*x+1.15107367*b].map(v=>o(Math.pow(Math.max(v,0),2.2)))}let u=Math.min(n,s,l),h=u<.08?u-6.25*u*u:.04;[n,s,l]=a(g=>g-h);let m=Math.max(n,s,l);if(m<.76)return a(o);let c=1-.0576/(m-.52),d=c/m,f=1-1/(.15*(m-c)+1);return a(g=>o(g*d+(c-g*d)*f))}var sl=`#version 300 es
208
+ }`;function fh(e,t,r=1){t=Bi(t);let i=Number.isFinite(r)?Math.max(0,r):1,[n,a,s]=[0,1,2].map(x=>Math.max(0,(Number(e[x])||0)*i)),o=x=>Math.max(0,Math.min(1,x)),l=x=>[x(n),x(a),x(s)];if(t==="none")return l(o);if(t==="reinhard")return l(x=>x/(x+1));if(t==="aces")return l(x=>{let v=x*.6;return o(v*(2.51*v+.03)/(v*(2.43*v+.59)+.14))});if(t==="agx"){let[x,v,y]=[.84247906*n+.0784336*a+.07922375*s,.04232824*n+.87846864*a+.07916613*s,.04237565*n+.0784336*a+.87914297*s].map(A=>{let b=o((Math.log2(Math.max(A,1e-6))+12.47393)/16.5),w=b*b,S=w*w;return 15.5*S*w-40.14*S*b+31.96*S-6.868*w*b+.4298*w+.1191*b-.00232});return[1.196879*x-.09802088*v-.09902974*y,-.05289685*x+1.15190313*v-.09896118*y,-.05297164*x-.09804345*v+1.15107367*y].map(A=>o(Math.pow(Math.max(A,0),2.2)))}let c=Math.min(n,a,s),f=c<.08?c-6.25*c*c:.04;[n,a,s]=l(x=>x-f);let m=Math.max(n,a,s);if(m<.76)return l(o);let h=1-.0576/(m-.52),p=h/m,g=1-1/(.15*(m-h)+1);return l(x=>o(x*p+(h-x*p)*g))}var fp=`#version 300 es
244
209
  layout(location=0) in vec3 aPosition;
245
210
  uniform mat4 uMVP;
246
- void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,al=`#version 300 es
211
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,mp=`#version 300 es
247
212
  precision highp float;
248
213
  uniform vec4 uColorId;
249
214
  out vec4 fragColor;
250
- void main(){fragColor=uColorId;}`;function Hi(e,t,r){let i={};for(let n of r)i[n]=e.getUniformLocation(t,n);return i}var ra=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uPointLightSpotDir","uPointLightSpotCone","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function ia(){let e=Ae().xrDepthShader;return{fs:nl.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...ra,...e.uniformNames]:ra}}function ol(e){if(typeof e!="string")return null;let t=e.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let r=t.toLowerCase();return r.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:r.startsWith("https://")||r.startsWith("blob:")?t:r.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function Gi(e,t,r,i,n,s,l,o){if(i===void 0||!t.accessors?.[i])return null;let a=jt(t,r,t.accessors[i],s);if(!a)return null;o&&(a=a.slice(),Jo(a,o));let u=e.createBuffer();return l.push(u),e.bindBuffer(34962,u),e.bufferData(34962,a,35044),e.enableVertexAttribArray(n),e.vertexAttribPointer(n,s,5126,!1,0,0),a}function Wi(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function na(e,t,r){let i=ia(),n=ea,s=i.fs,l=!1;for(let a of Ve)if(a.onResolveShader){let u=a.onResolveShader(t,r,n,s);u&&(n=u.vs,s=u.fs,l=!0)}let o=l?Xt(e,n,s):null;return{program:o,uniforms:o?Hi(e,o,i.uniforms):null}}function ll(e,t,r){let i=t.instanceMatrices;if(!i||i.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let n=i.length>>4,s=t.instanceColors,l=new Float32Array(n*20);for(let a=0;a<n;a++)l.set(i.subarray(a*16,a*16+16),a*20),l[a*20+16]=s?s[a*3]:1,l[a*20+17]=s?s[a*3+1]:1,l[a*20+18]=s?s[a*3+2]:1,l[a*20+19]=1;let o=e.createBuffer();r.push(o),e.bindBuffer(34962,o),e.bufferData(34962,l,35044);for(let a=0;a<5;a++)e.enableVertexAttribArray(8+a),e.vertexAttribPointer(8+a,4,5126,!1,80,a*16),e.vertexAttribDivisor(8+a,1);return!0}function ul(e,t){let r=e.materials?.[t?.material];if(!r)return null;let i=[r.pbrMetallicRoughness?.baseColorTexture,r.pbrMetallicRoughness?.metallicRoughnessTexture,r.normalTexture,r.occlusionTexture,r.emissiveTexture];for(let n of i){let s=n?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var hl=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),sa=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Dr(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function aa(e,t){let r=e?.pbrMetallicRoughness,i=r?.baseColorFactor,n=e?.extensions?.KHR_materials_clearcoat,s=l=>l!==void 0&&t[l.index]?t[l.index]:null;return{baseColor:i?[i[0],i[1],i[2],i[3]??1]:[.8,.8,.8,1],metallic:r?.metallicFactor??.1,roughness:r?.roughnessFactor??.5,clearcoat:n?n.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,n?.clearcoatRoughnessFactor??.04),texture:s(r?.baseColorTexture),metallicRoughnessTexture:s(r?.metallicRoughnessTexture),normalTexture:s(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:s(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function oa(e,t,r){let i=new Set,n=s=>{s&&!i.has(s)&&(i.add(s),e.deleteTexture(s))};for(let s of t)for(let l of s.primitives){if(l.vao&&e.deleteVertexArray(l.vao),l.buffers)for(let a of l.buffers)e.deleteBuffer(a);n(l.texture),n(l.metallicRoughnessTexture),n(l.normalTexture),n(l.occlusionTexture);let o=new Set;l.customProgram&&o.add(l.customProgram);for(let a of l.programCache?.values()??[])a.program&&o.add(a.program);for(let a of o)e.deleteProgram(a)}if(r)for(let s of r)n(s)}function la(e,t,r=sa,i){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return cl(e,t,r,i,n)}catch(s){let l=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;oa(e,l,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let o of n.buffers)e.deleteBuffer(o);throw s}}function cl(e,t,r,i,n){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=t,l=Kt("meshopt");l?.decodeBufferViews&&l.decodeBufferViews(s,t);let o=t.bin,a=[];n.meshes=a;let u=[],h=s.extensions?.KHR_materials_variants;h&&Array.isArray(h.variants)&&h.variants.forEach((k,w)=>{u.push(typeof k?.name=="string"&&k.name?k.name:`Variant_${w}`)});let m=Cr(s),c=[];if(Array.isArray(s.nodes))for(let k=0;k<s.nodes.length;k++){let w=s.nodes[k];w.mesh!==void 0&&s.meshes&&s.meshes[w.mesh]&&c.push({node:w,nodeIdx:k,meshIdx:w.mesh})}let d=c.length>0?c:(s.meshes||[]).map((k,w)=>({node:k,nodeIdx:-1,meshIdx:w})),f=[],g=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(s.asset?.extras?.lights)&&s.asset.extras.lights.length>0?s.asset.extras.lights:null;if(g)for(let k of g)f.push({...k,type:k.type||k.light_type||"point",innerConeAngle:k.innerConeAngle??k.inner_cone_angle,outerConeAngle:k.outerConeAngle??k.outer_cone_angle});else if(s.extensions?.KHR_lights_punctual?.lights){let k=s.extensions.KHR_lights_punctual.lights;for(let w of k){let ie=w.type==="directional"?"directional":w.type==="point"?"point":w.type==="spot"?"spot":"ambient";f.push({type:ie,color:w.color||[1,1,1],intensity:w.intensity!==void 0?w.intensity:1})}}if(f.length===0&&(f.push({type:"ambient",color:[1,1,1],intensity:.35}),f.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),d.length>r.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${r.maxMeshes}). Found: ${d.length}`);let x=[];if(n.gpuTextures=x,s.textures&&s.images){if(s.textures.length>r.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${r.maxTextures}). Found: ${s.textures.length}`);for(let k=0;k<s.textures.length;k++){let w=s.textures[k],ie=s.images[w.source];if(ie){let oe=e.createTexture();e.bindTexture(3553,oe),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),e.texParameteri(3553,10242,10497),e.texParameteri(3553,10243,10497),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729);let I=H=>{e.bindTexture(3553,oe),e.texImage2D(3553,0,6408,6408,5121,H),e.generateMipmap(3553),i?.()};if(ie.bufferView!==void 0){let H=s.bufferViews[ie.bufferView],C=H.byteOffset||0,z=new Blob([o.slice(C,C+H.byteLength)],{type:ie.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(z).then(I).catch(()=>{})}else if(ie.uri){let H=ol(ie.uri);if(H){let C=new Image;C.crossOrigin="anonymous",C.referrerPolicy="no-referrer",C.onload=()=>I(C),C.src=H}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",ie.uri)}x.push(oe)}else x.push(null)}}let b=[1/0,1/0,1/0],v=[-1/0,-1/0,-1/0],p=0,y=0;for(let k=0;k<d.length;k++){let w=d[k],ie=s.meshes[w.meshIdx],oe=w.nodeIdx>=0?m[w.nodeIdx]:Pe(),I=new Float32Array(9);Ye(I,oe);let H={name:w.node.name||ie.name||`Mesh_${w.meshIdx}`,nodeIndex:w.nodeIdx,transform:oe,normalMatrix:I,primitives:[],extras:w.node.extras||ie.extras,...w.node?.visible===!1||w.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};n.mesh=H;let C=w.node?.extensions?.EXT_mesh_gpu_instancing;if(C&&C.attributes&&typeof C.attributes=="object"){let z=C.attributes,ue=z.TRANSLATION!==void 0?s.accessors?.[z.TRANSLATION]:null,he=z.ROTATION!==void 0?s.accessors?.[z.ROTATION]:null,O=z.SCALE!==void 0?s.accessors?.[z.SCALE]:null,$=z._COLOR_0!==void 0?s.accessors?.[z._COLOR_0]:null,_=Number(ue?.count??he?.count??O?.count??0);if(!Number.isFinite(_)||_<0||_>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${_}`);if(_>0){let W=(V,ee)=>{if(!V||V.bufferView===void 0||!s.bufferViews?.[V.bufferView])return null;let R=V.componentType??5126,A=N=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${N})`),null);if(R!==5120&&R!==5121&&R!==5122&&R!==5123&&R!==5126)return A(`componentType ${R}`);if(!(Number(V.count)>=_))return A(`count ${V.count} < ${_}`);let L=null;try{L=jt(s,o,{...V,count:_},ee)}catch{return A("out of bounds")}return!L||!L.every(Number.isFinite)?A("non-finite value"):L},j=W(ue,3),X=W(he,4),D=W(O,3),Y=$?.type==="VEC4"?4:3,te=W($,Y),se=new Float32Array(_*16),le=Pe();for(let V=0;V<_;V++){let ee=j?[j[V*3],j[V*3+1],j[V*3+2]]:[0,0,0],R=X?[X[V*4],X[V*4+1],X[V*4+2],X[V*4+3]]:[0,0,0,1],A=D?[D[V*3],D[V*3+1],D[V*3+2]]:[1,1,1];lr(le,R,ee,A),se.set(le,V*16)}if(H.instanceMatrices=se,te){let V=new Float32Array(_*3);for(let ee=0;ee<_;ee++)V[ee*3]=te[ee*Y],V[ee*3+1]=te[ee*Y+1],V[ee*3+2]=te[ee*Y+2];H.instanceColors=V}}}for(let z of ie.primitives||[]){if(z.extensions?.KHR_draco_mesh_compression){let L=Kt("draco");L&&L.decodePrimitive(s,z,o)}let ue=[],he=e.createVertexArray();n.vao=he,n.buffers=ue,e.bindVertexArray(he);let O=ll(e,H,ue),$=s.accessors[z.attributes.POSITION],_=Number($?.count??0);if(!Number.isFinite(_)||_<0||p+_>r.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${r.maxVertices}).`);if(p+=_,$?.min&&$?.max){let L=N=>{for(let U=0;U<3;U++){let Q=N[12+U],q=N[12+U];for(let Z=0;Z<3;Z++){let J=N[Z*4+U]*$.min[Z],K=N[Z*4+U]*$.max[Z];Q+=J<K?J:K,q+=J>K?J:K}Q<b[U]&&(b[U]=Q),q>v[U]&&(v[U]=q)}};if(H.instanceMatrices&&H.instanceMatrices.length>=16){let N=H.instanceMatrices.length>>4,U=Pe();for(let Q=0;Q<N;Q++){let q=H.instanceMatrices.subarray(Q*16,Q*16+16);ke(U,oe,q),L(U)}}else L(oe)}let W=Gi(e,s,o,z.attributes.POSITION,0,3,ue);Gi(e,s,o,z.attributes.NORMAL,1,3,ue),Gi(e,s,o,z.attributes.TEXCOORD_0,2,2,ue,ul(s,z));let j=0,X=5123,D=null;if(z.indices!==void 0){let L=s.accessors[z.indices],N=(s.bufferViews[L.bufferView].byteOffset||0)+(L.byteOffset||0);if(j=Number(L.count??0),!Number.isFinite(j)||j<0||y+j>r.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${r.maxIndices}).`);y+=j,X=L.componentType===5125?5125:5123;let U=e.createBuffer();ue.push(U),e.bindBuffer(34963,U),L.componentType===5125?D=new Uint32Array(o,N,L.count):L.componentType===5121?D=Uint16Array.from(new Uint8Array(o,N,L.count)):D=N%2===0?new Uint16Array(o,N,L.count):new Uint16Array(o.slice(N,N+L.count*2)),e.bufferData(34963,D,35044)}else j=$.count;let Y={};for(let L of Ve)if(L.onBuildPrimitiveVAO){let N=L.onBuildPrimitiveVAO(e,he,z,s,o);N&&(Y[L.name]=N)}e.bindVertexArray(null);let te=s.materials&&z.material!==void 0?s.materials[z.material]:null,{program:se,uniforms:le}=na(e,z,te),V=aa(te,x),ee=!!(te?.extensions?.KHR_materials_transmission||Y.materials?.isTransmissive),R=z.extensions?.KHR_materials_variants?.mappings,A=Array.isArray(R)?R.filter(L=>L&&typeof L.material=="number"&&Array.isArray(L.variants)).map(L=>({material:L.material|0,variants:L.variants.map(N=>Number(N)|0)})):void 0;H.primitives.push({vao:he,instanced:O,indexCount:j,indexType:X,...V,positions:W,indices:D,buffers:ue,materialIndex:z.material,defaultMaterialIndex:z.material,variantMappings:A,primitiveDef:z,programCache:new Map([[z.material??-1,{program:se,uniforms:le}]]),pluginData:Y,customProgram:se,customUniforms:le,isTransmissive:ee})}a.push(H)}isFinite(b[0])||(b=[-1,-1,-1]),isFinite(v[0])||(v=[1,1,1]);let M=[(b[0]+v[0])/2,(b[1]+v[1])/2,(b[2]+v[2])/2],P=v[0]-b[0],F=v[1]-b[1],G=v[2]-b[2],T=Math.max(Math.hypot(P,F,G)/2,.5),E=[b[0],b[1],b[2]],S=[v[0],v[1],v[2]],B=t.animations;if(!B){for(let k of Ve)if(k.onParseGLB?.(t),t.animations){B=t.animations;break}}return B||(B=[]),{meshes:a,bounds:{center:M,radius:T,min:E,max:S},lights:f,animations:B,worldMatrices:m,gpuTextures:x,availableVariants:u}}function mr(e){let t=e.customTarget||e.bounds.center,r=e.currDistance*Math.cos(e.currPhi);return[t[0]+r*Math.sin(e.currTheta),t[1]+e.currDistance*Math.sin(e.currPhi),t[2]+r*Math.cos(e.currTheta)]}var Ze=class{constructor(e,t,r){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=Pe(),this.clearColor=[0,0,0,0],this.envIntensity=1,this.exposure=1,this.shadowIntensity=0,this.shadowSoftness=.5,this.toneMapping="neutral",this.environmentTexture=null,this.animations=[],this.currentClip=null,this.animationTime=0,this.isPlayingAnimation=!1,this.autoplay=!1,this.animationName="",this.gpuTextures=[],this.availableVariants=[],this.activeVariantName=null,this.gltf=null,this.worldMatrices=[],this.initialNodeTransforms=[],this.projMatrix=Pe(),this.viewMatrix=Pe(),this.activeViewMatrix=null,this.modelMatrix=Pe(),this.mvpMatrix=Pe(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshName="",this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:Pe(),rawValueToMeters:.001,format:0},this.container=e;let i,n;if(t&&typeof t.getContext=="function"?(i=t,n=r):(n=t,i=n?.canvas),!i){let o=e.querySelector("canvas");o||(o=document.createElement("canvas"),o.style.width="100%",o.style.height="100%",o.style.display="block",o.style.touchAction="none",e.prepend(o)),i=o}this.canvas=i,this.opts=n||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!s:s&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=Wi(this.opts.exposure)),this.opts.camera&&this.setInitialCamera(this.opts.camera.theta,this.opts.camera.phi,this.opts.camera.distance,this.opts.camera.zoom),this.opts.shadowIntensity!==void 0&&(this.shadowIntensity=Math.max(0,Math.min(1,Number(this.opts.shadowIntensity)||0))),this.opts.shadowSoftness!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(this.opts.shadowSoftness)||0))),this.opts.toneMapping!==void 0&&(this.toneMapping=qt(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let l=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!l)throw new Error("WebGL2 not supported");this.gl=l,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){rl(e,t)}static getDecoder(e){return Kt(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=ia();this.renderProg=Xt(e,ea,t.fs),this.pickProg=Xt(e,sl,al),this.uRender=Hi(e,this.renderProg,t.uniforms),this.uPick=Hi(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of Ve)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=r,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,r,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,r),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),n=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=n,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,n,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,n)}loadGLBData(e,t){let{meshes:r,bounds:i,lights:n,animations:s,worldMatrices:l,gpuTextures:o,availableVariants:a}=la(this.gl,e,t,()=>this.render());if(this.lastGlbData=e,this.lastLimits=t,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=n,this.animations=s||[],this.worldMatrices=l||[],this.gpuTextures=o||[],this.availableVariants=a||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let m of e.gltf.nodes)this.initialNodeTransforms.push({t:m.translation?[m.translation[0],m.translation[1],m.translation[2]]:[0,0,0],r:m.rotation?[m.rotation[0],m.rotation[1],m.rotation[2],m.rotation[3]]:[0,0,0,1],s:m.scale?[m.scale[0],m.scale[1],m.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let m of Ve)m.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let u=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;u!==void 0&&(this.exposure=Wi(u));let h=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;h!==void 0&&(this.envIntensity=Math.max(0,Number(h)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(Js(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of Ve)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Yt(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Yt(e),{meshes:i}=la(this.gl,r,sa,()=>this.render());if(t)for(let n of i)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],Ye(n.normalMatrix,n.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(e,t,r,i=1){this.clearColor=[e,t,r,i]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let r=this.meshes[t],i;e instanceof Map?i=e.get(r.name)??e.get(t):Array.isArray(e)?i=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,r.name)?i=e[r.name]:Object.prototype.hasOwnProperty.call(e,t)&&(i=e[t])),i&&i.length===16&&(r.transform.set(i),Ye(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],n=[],s=[],l=[],o=[],a=[];for(let u of this.lights){let h=u.color||[1,1,1],m=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")r=[h[0]*m,h[1]*m,h[2]*m];else if(u.type==="directional"&&i.length<6){let c=u.direction||[.5,1,.8];i.push(c[0],c[1],c[2]),n.push(h[0]*m,h[1]*m,h[2]*m)}else if((u.type==="point"||u.type==="spot")&&s.length<6){let c=u.position||[0,0,0];if(s.push(c[0],c[1],c[2]),l.push(h[0]*m,h[1]*m,h[2]*m),u.type==="spot"){let d=u.direction||[0,-1,0],f=Math.max(.01,Math.min(Math.PI/2,u.outerConeAngle??Math.PI/3)),g=Math.max(0,Math.min(f-1e-4,u.innerConeAngle??0));o.push(d[0],d[1],d[2]),a.push(Math.cos(g),Math.cos(f))}else o.push(0,-1,0),a.push(-2,-3)}}i.length===0&&(i.push(.5,1,.8),n.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),t.uniform1i(e.uNumDirLights,i.length/3),i.length>0&&(t.uniform3fv(e.uDirLightDir,i),t.uniform3fv(e.uDirLightColor,n)),t.uniform1i(e.uNumPointLights,s.length/3),s.length>0&&(t.uniform3fv(e.uPointLightPos,s),t.uniform3fv(e.uPointLightColor,l),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,o),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,a)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Wi(e)}getExposure(){return this.exposure}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=qt(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of Ve)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of Ve)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(u=>u.primitives.filter(h=>h.materialIndex===r||e.length===1&&h.materialIndex===void 0)),n=i[0],s=n?[...n.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=n?n.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,o=n?n.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,a={baseColorFactor:s,metallicFactor:l,roughnessFactor:o,setBaseColorFactor:u=>{let h=[u[0],u[1],u[2],u[3]??1];a.baseColorFactor=h,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=h);for(let m of i)m.baseColor=h;this.render()},setMetallicFactor:u=>{a.metallicFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=u);for(let h of i)h.metallic=u;this.render()},setRoughnessFactor:u=>{a.roughnessFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=u);for(let h of i)h.roughness=u;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:a}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let n of this.meshes)for(let s of n.primitives){let l=s.defaultMaterialIndex;if(!t&&Array.isArray(s.variantMappings)){for(let a of s.variantMappings)if(Array.isArray(a.variants)&&a.variants.includes(r)){l=a.material;break}}let o=l!==void 0?i[l]:void 0;s.materialIndex=o?l:void 0,Object.assign(s,aa(o,this.gpuTextures)),this.applyPrimitiveProgram(s,s.materialIndex,o??null)}return!0}applyPrimitiveProgram(e,t,r){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let i=t??-1,n=e.programCache.get(i);n||(n=na(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,n)),e.customProgram=n.program,e.customUniforms=n.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of Ve)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,r){this.customTarget=[e,t,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(r,e))}setCamera(e,t,r,i){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(e,t,r,i){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),r!==void 0&&r>0){let n=this.clampDistance(r);this.initialDistance=n,this.customDistance=!0,this.targetDistance=n,this.currDistance=n}else if(i!==void 0&&i>0){let n=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=n,this.customDistance=!0,this.targetDistance=n,this.currDistance=n}else{this.customDistance=!1;let n=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=n,this.targetDistance=n,this.currDistance=n}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let r=Pe();ke(r,this.projMatrix,this.viewMatrix);let[i,n,s]=e,l=t?t[0]:0,o=t?t[1]:0,a=t?t[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*e[0]+u[4]*e[1]+u[8]*e[2]+u[12],n=u[1]*e[0]+u[5]*e[1]+u[9]*e[2]+u[13],s=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]+u[14],t&&(l=u[0]*t[0]+u[4]*t[1]+u[8]*t[2],o=u[1]*t[0]+u[5]*t[1]+u[9]*t[2],a=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]));let h=r[0]*i+r[4]*n+r[8]*s+r[12],m=r[1]*i+r[5]*n+r[9]*s+r[13],c=r[2]*i+r[6]*n+r[10]*s+r[14],d=r[3]*i+r[7]*n+r[11]*s+r[15];if(d<=1e-4)return{x:0,y:0,z:1,visible:!1};let f=h/d,g=m/d,x=c/d,b=this.canvas.getBoundingClientRect(),v=b.width||this.canvas.clientWidth||this.canvas.width||300,p=b.height||this.canvas.clientHeight||this.canvas.height||150,y=(f*.5+.5)*v,M=(-g*.5+.5)*p,P=f>=-1.1&&f<=1.1&&g>=-1.1&&g<=1.1&&x>=-1&&x<=1;if(P&&t){let[F,G,T]=mr(this),E=[i-F,n-G,s-T];l*E[0]+o*E[1]+a*E[2]>.05&&(P=!1)}return{x:y,y:M,z:x,visible:P}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas,t=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=r=>{r.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=r=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=t(),this.lastPointerX=r.clientX,this.lastPointerY=r.clientY,this.totalDragDist=0,this.activePointers.set(r.pointerId,{x:r.clientX,y:r.clientY}),this.isPanning=r.button===2||r.shiftKey||this.activePointers.size===2,e.setPointerCapture(r.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=r=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=t();let i=this.activePointers.get(r.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},n=r.clientX-i.x,s=r.clientY-i.y;if(this.activePointers.set(r.pointerId,{x:r.clientX,y:r.clientY}),this.lastPointerX=r.clientX,this.lastPointerY=r.clientY,this.totalDragDist+=Math.hypot(n,s),this.isPanning||r.button===2||r.shiftKey||this.activePointers.size===2){let l=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],o=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],a=this.customTarget?[...this.customTarget]:[...this.bounds.center],u=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;a[0]+=(-n*l[0]+s*o[0])*u,a[1]+=(-n*l[1]+s*o[1])*u,a[2]+=(-n*l[2]+s*o[2])*u,this.customTarget=a}else this.targetTheta=this.clampTheta(this.targetTheta-n*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=r=>{this.lastInteractionTime=t(),this.activePointers.delete(r.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(r.pointerId)}catch{}if(this.totalDragDist<5&&r.button===0){let i=e.getBoundingClientRect(),n=Math.floor((r.clientX-i.left)*(e.width/Math.max(i.width,1))),s=Math.floor((r.clientY-i.top)*(e.height/Math.max(i.height,1)));this.performMeshPick(n,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=r=>{if(!this.interactive)return;r.preventDefault(),this.lastInteractionTime=t();let i=Math.exp(r.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*i)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=r=>{let i=r.detail||{};i.reset?this.resetCamera():this.setCamera(i.theta,i.phi,i.distance,i.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=r=>{if(this.interactive){switch(r.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=t(),r.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(r,i,n)=>{this[n]&&(r.removeEventListener(i,this[n]),this[n]=null)},t=this.canvas;e(t,"webglcontextlost","boundContextLost"),e(t,"webglcontextrestored","boundContextRestored"),e(t,"contextmenu","boundContextMenu"),e(t,"pointerdown","boundPointerDown"),e(t,"pointermove","boundPointerMove"),e(t,"pointerup","boundPointerUp"),e(t,"wheel","boundWheel"),e(t,"keydown","boundKeyDown"),e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),n=r.width||300,s=r.height||300,l=i.width>0?Math.floor((e-i.left)*(n/i.width)):Math.floor(e),o=i.height>0?Math.floor((t-i.top)*(s/i.height)):Math.floor(t);return this.performMeshPick(l,o,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,n=Math.max(1,this.canvas.width||300),s=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,n);let l=Pe();ke(l,this.projMatrix,this.viewMatrix);let o=[],a=Math.max(0,Math.min(n-1,e)),u=Math.max(0,Math.min(s-1,s-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==n||this.pickFboHeight!==s)&&this.resizePickingFbo(n,s),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,n,s),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16640),i.useProgram(this.pickProg);for(let M=0;M<this.meshes.length;M++){let P=this.meshes[M];if(P.visible===!1||P.isPluginMesh)continue;let F=M+1,G=(F&255)/255,T=(F>>8&255)/255,E=(F>>16&255)/255;i.uniform4f(this.uPick.uColorId,G,T,E,1),ke(this.modelMatrix,this.modelRootMatrix,P.transform);let S=P.instanceMatrices;if(S&&S.length>=16){let B=S.length>>4,k=Pe();for(let w of P.primitives){i.bindVertexArray(w.vao);for(let ie=0;ie<B;ie++)ke(k,this.modelMatrix,S.subarray(ie*16,ie*16+16)),ke(this.mvpMatrix,l,k),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Dr(i,w)}}else{ke(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let B of P.primitives)i.bindVertexArray(B.vao),Dr(i,B)}}let p=new Uint8Array(4);i.readPixels(a,u,1,1,6408,5121,p),i.bindFramebuffer(36160,null);let y=p[0]+(p[1]<<8)+(p[2]<<16);y>0&&y<=this.meshes.length&&(o=[this.meshes[y-1]])}o.length===0&&(o=this.meshes.filter(p=>p.visible!==!1));let h=null,m=1/0,c=[0,0,0],d=[0,1,0],[f,g,x]=mr(this),b=Pe();for(let p of o){ke(b,this.modelRootMatrix,p.transform);let y=p.instanceMatrices,M=y&&y.length>=16?y.length>>4:1;for(let P=0;P<M;P++){y&&y.length>=16?ke(this.modelMatrix,b,y.subarray(P*16,P*16+16)):this.modelMatrix.set(b),ke(this.mvpMatrix,l,this.modelMatrix);let F=Pe();if(!Li(F,this.mvpMatrix))continue;let G=(a+.5)/n*2-1,T=(u+.5)/s*2-1,E=[0,0,0],S=[0,0,0];$s(E,G,T,-1,F),$s(S,G,T,1,F);let B=S[0]-E[0],k=S[1]-E[1],w=S[2]-E[2],ie=Math.hypot(B,k,w)||1,oe=B/ie,I=k/ie,H=w/ie,C={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((z=>{for(let ue of p.primitives){if(!ue.positions)continue;let he=ue.positions,O=ue.indices,$=Math.floor(O?O.length/3:he.length/9);for(let _=0;_<$;_++){let W=O?O[_*3]:_*3,j=O?O[_*3+1]:_*3+1,X=O?O[_*3+2]:_*3+2;Oo(E[0],E[1],E[2],oe,I,H,he[W*3],he[W*3+1],he[W*3+2],he[j*3],he[j*3+1],he[j*3+2],he[X*3],he[X*3+1],he[X*3+2],C,z)}}})(1e-4),isFinite(C.distance)){let z=C.point[0],ue=C.point[1],he=C.point[2],O=this.modelMatrix,$=O[0]*z+O[4]*ue+O[8]*he+O[12],_=O[1]*z+O[5]*ue+O[9]*he+O[13],W=O[2]*z+O[6]*ue+O[10]*he+O[14],j=$-f,X=_-g,D=W-x,Y=Math.hypot(j,X,D);if(Y<m){Ye(this.normalMatrix,this.modelMatrix);let te=this.normalMatrix,se=C.normal[0],le=C.normal[1],V=C.normal[2],ee=te[0]*se+te[3]*le+te[6]*V,R=te[1]*se+te[4]*le+te[7]*V,A=te[2]*se+te[5]*le+te[8]*V,L=Math.hypot(ee,R,A)||1;ee/=L,R/=L,A/=L,ee*j+R*X+A*D>0&&(ee=-ee,R=-R,A=-A),h=p,m=Math.round(Y*1e3)/1e3,c=[Math.round($*1e3)/1e3,Math.round(_*1e3)/1e3,Math.round(W*1e3)/1e3],d=[Math.round(ee*1e3)/1e3,Math.round(R*1e3)/1e3,Math.round(A*1e3)/1e3]}}}}if(!h)return null;let v={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:m,hitPoint:c,normal:d,screenX:e,screenY:t};if(r){for(let p of Ve)p.onMeshSelect?.(this,v);this.opts.onMeshClick&&this.opts.onMeshClick(v),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:v}))}return v}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,n=i?e-r:e,s=i?Math.max(1,t-r):r,l=(n+.5)/s*2-1;return Math.floor((l*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);Ni(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;Er(this.viewMatrix,mr(this),r,[0,1,0]),ke(this.mvpMatrix,this.projMatrix,this.viewMatrix),Ye(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let r of Ve)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of Ve)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],n=this.modelRootMatrix;n[0]=e,n[1]=0,n[2]=-t,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=t,n[9]=0,n[10]=e,n[11]=0,n[12]=r-(e*r+t*i),n[13]=0,n[14]=i-(-t*r+e*i),n[15]=1}setVisible(e){this.isVisible=e}update(e){for(let s of Ve)s.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let s of Ve)s.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),n=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(n-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=n;let s={theta:r,phi:i,zoom:n,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(s),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:s}))}}renderXRView(e,t,r,i,n=!0,s=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let l=e?.transform?.inverse?.matrix||this.viewMatrix,o=e?.projectionMatrix||this.projMatrix,a=e?.transform?.position,u=a?[a.x,a.y,a.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:l,projMatrix:o,eyePos:u,viewport:i,eye:e?.eye||"none",clear:s>0?!1:e?.eye!=="right",isAR:n})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),p=Math.max(1,this.canvas.height||1),y=Math.max(1,Math.floor(v*.5)),M=Math.max(1,v-y),P=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),F=this.customTarget||this.bounds.center,[G,T,E]=mr(this),S=Math.cos(this.currTheta),B=-Math.sin(this.currTheta),k=.032,w=Pe(),ie=Pe(),oe=[G-S*k,T,E-B*k],I=[F[0]-S*k*.25,F[1],F[2]-B*k*.25];Ni(w,this.fov,y/p,.1,P),Er(ie,oe,I,[0,1,0]);let H=Pe(),C=Pe(),z=[G+S*k,T,E+B*k],ue=[F[0]+S*k*.25,F[1],F[2]+B*k*.25];Ni(H,this.fov,M/p,.1,P),Er(C,z,ue,[0,1,0]),this.render({viewMatrix:ie,projMatrix:w,eyePos:oe,viewport:[0,0,y,p],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:C,projMatrix:H,eyePos:z,viewport:[y,0,M,p],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,p);return}let t=this.gl,r=0,i=0,n=this.canvas.width,s=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],n=e.viewport[2],s=e.viewport[3],t.viewport(r,i,n,s)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16640));let l=Pe(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o,ke(l,e?.projMatrix??this.projMatrix,o);let a=Ae().xrDepthShader,u=el(this.toneMapping),[h,m,c]=e?e.eyePos:mr(this);for(let v of Ve)v.onBeforeDrawScene?.(this,t,l,[h,m,c],u);let d=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&d===0)return;let f=e?.eye||"none",g=!1,x=d>0?[...this.backdropMeshes,...this.meshes]:this.meshes,b=v=>{for(let p=0;p<x.length;p++){let y=x[p];if(y.visible===!1)continue;let M=this.selectedMeshName!==""&&y.name===this.selectedMeshName;p<d||y.worldSpace===!0||y.name==="__xr_reticle__"?this.modelMatrix.set(y.transform):ke(this.modelMatrix,this.modelRootMatrix,y.transform),ke(this.mvpMatrix,l,this.modelMatrix),Ye(y.normalMatrix,this.modelMatrix);let P=y.extras?.xr?.stereo||y.userData?.xr?.stereo,F=0,G=0,T=1,E=1;P==="sbs"?(T=.5,F=f==="right"?.5:0):P==="ou"&&(E=.5,G=f==="right"?.5:0);for(let S of y.primitives){let B=!!S.isTransmissive;if(!v&&B){g=!0;continue}if(v&&!B)continue;let k=S.customProgram||this.renderProg,w=S.customUniforms||this.uRender;t.useProgram(k),t.vertexAttrib3f(3,0,0,0),w.uInstanced&&t.uniform1i(w.uInstanced,0),t.uniform1i(w.uToneMapping,u),t.uniform1f(w.uEnvIntensity,this.envIntensity),w.uExposure&&t.uniform1f(w.uExposure,this.exposure),t.uniform3f(w.uCameraPos,h,m,c),t.uniform1f(w.uEmissive,M?1:0),t.uniformMatrix4fv(w.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(w.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(w.uNormalMatrix,!1,y.normalMatrix),w.uUvTransform&&t.uniform4f(w.uUvTransform,F,G,T,E),w.uViewportSize&&t.uniform2f(w.uViewportSize,Math.max(1,n),Math.max(1,s)),a?.bind(t,w,this.xrDepthState,o,[r,i,Math.max(1,n),Math.max(1,s)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(w.uEnvironmentMap,4),t.uniform1i(w.uHasEnvironmentMap,1)):t.uniform1i(w.uHasEnvironmentMap,0),this.bindLights(w),w.uSectionEnabled&&t.uniform1i(w.uSectionEnabled,0);for(let oe of Ve)oe.onBeforeDrawPrimitive?.(t,k,S,y,this.worldMatrices||[],this.gltf);t.uniform4fv(w.uBaseColor,S.baseColor),t.uniform1f(w.uMetallic,S.metallic),t.uniform1f(w.uRoughness,S.roughness),w.uClearcoat&&t.uniform2f(w.uClearcoat,S.clearcoat??0,S.clearcoatRoughness??.04),S.texture?(t.activeTexture(33984),t.bindTexture(3553,S.texture),t.uniform1i(w.uBaseColorTexture,0),t.uniform1i(w.uHasTexture,1)):t.uniform1i(w.uHasTexture,0),S.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,S.metallicRoughnessTexture),t.uniform1i(w.uMetallicRoughnessTexture,1),t.uniform1i(w.uHasMetallicRoughnessTexture,1)):t.uniform1i(w.uHasMetallicRoughnessTexture,0),S.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,S.normalTexture),t.uniform1i(w.uNormalTexture,2),t.uniform1i(w.uHasNormalTexture,1),t.uniform1f(w.uNormalScale,S.normalScale)):t.uniform1i(w.uHasNormalTexture,0),S.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,S.occlusionTexture),t.uniform1i(w.uOcclusionTexture,3),t.uniform1i(w.uHasOcclusionTexture,1),t.uniform1f(w.uOcclusionStrength,S.occlusionStrength)):t.uniform1i(w.uHasOcclusionTexture,0),t.bindVertexArray(S.vao);let ie=y.instanceMatrices;if(S.instanceCount!==void 0)t.drawElementsInstanced(4,S.indexCount,S.indexType,0,S.instanceCount);else if(ie&&ie.length>=16&&S.instanced&&w.uInstanced&&w.uViewProj){let oe=ie.length>>4;t.uniform1i(w.uInstanced,1),t.uniformMatrix4fv(w.uViewProj,!1,l),S.indices?t.drawElementsInstanced(4,S.indexCount,S.indexType,0,oe):t.drawArraysInstanced(4,0,S.indexCount,oe),t.uniform1i(w.uInstanced,0)}else if(ie&&ie.length>=16){let oe=ie.length>>4,I=y.instanceColors,H=Pe(),C=new Float32Array(9),z=[S.baseColor[0],S.baseColor[1],S.baseColor[2],S.baseColor[3]];for(let ue=0;ue<oe;ue++)ke(H,this.modelMatrix,ie.subarray(ue*16,ue*16+16)),ke(this.mvpMatrix,l,H),Ye(C,H),t.uniformMatrix4fv(w.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(w.uModel,!1,H),t.uniformMatrix3fv(w.uNormalMatrix,!1,C),I&&(z[0]=S.baseColor[0]*I[ue*3],z[1]=S.baseColor[1]*I[ue*3+1],z[2]=S.baseColor[2]*I[ue*3+2],z[3]=S.baseColor[3],t.uniform4fv(w.uBaseColor,z)),Dr(t,S)}else Dr(t,S)}}};if(b(!1),g){for(let v of Ve)v.onBeforeTransmissivePass?.(t,this);b(!0)}for(let v of Ve)v.onAfterRender?.(t,this,l,e?.eye??"none",[r,i,n,s],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){oa(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of Ve)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};Ze.registerPlugin=je,Ze.getRegisteredPlugins=Vs;function ml(e){return e+3&-4}var Me=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function ua(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function ha(e,t=0){let[r,i,n,,s,l,o,,a,u,h,,m,c,d]=Array.from({length:15},(C,z)=>Me(e[t+z],z%5===0?1:0)),f=Math.hypot(r,i,n),g=Math.hypot(s,l,o),x=Math.hypot(a,u,h);r*(l*h-u*o)-s*(i*h-u*n)+a*(i*o-l*n)<0&&(f=-f);let b=Math.abs(f)>1e-8?1/f:0,v=Math.abs(g)>1e-8?1/g:0,p=Math.abs(x)>1e-8?1/x:0,y=r*b,M=i*b,P=n*b,F=s*v,G=l*v,T=o*v,E=a*p,S=u*p,B=h*p,k=y+G+B,w=0,ie=0,oe=0,I=1;if(k>0){let C=.5/Math.sqrt(k+1);I=.25/C,w=(T-S)*C,ie=(E-P)*C,oe=(M-F)*C}else if(y>G&&y>B){let C=2*Math.sqrt(Math.max(0,1+y-G-B));C>1e-8&&(I=(T-S)/C,w=.25*C,ie=(F+M)/C,oe=(E+P)/C)}else if(G>B){let C=2*Math.sqrt(Math.max(0,1+G-y-B));C>1e-8&&(I=(E-P)/C,w=(F+M)/C,ie=.25*C,oe=(T+S)/C)}else{let C=2*Math.sqrt(Math.max(0,1+B-y-G));C>1e-8&&(I=(M-F)/C,w=(E+P)/C,ie=(T+S)/C,oe=.25*C)}let H=Math.hypot(w,ie,oe,I);return H>1e-8&&Number.isFinite(H)?(w/=H,ie/=H,oe/=H,I/=H):(w=0,ie=0,oe=0,I=1),{t:[m,c,d],r:[w,ie,oe,I],s:[f,g,x]}}function fl(e){let t={};return e.grab&&(t.interactable={mode:typeof e.grab=="string"?e.grab:"2-hand"},t.movable={scaleInZ:!!e.scale,minScale:typeof e.scale=="object"?e.scale.min??.1:.1,maxScale:typeof e.scale=="object"?e.scale.max??10:10}),e.billboard&&(t.billboard={mode:typeof e.billboard=="string"?e.billboard:"capsule"}),e.follow&&(t.follow={target:typeof e.follow=="object"?e.follow.mode??"head":e.follow}),e.anchor&&(t.anchor={plane:e.anchor}),e.physics&&e.physics!=="none"&&(t.rigidbody={type:e.physics}),t}var At=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function ca(e){let t=e?.audioEmitter??e?.spatialAudio??(typeof e?.audio=="object"&&e.audio&&("preset"in e.audio||"distanceModel"in e.audio||"coneInnerAngle"in e.audio||"maxDistance"in e.audio||"volume"in e.audio)?e.audio:typeof e?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(e.audio)?{preset:e.audio}:void 0);if(!t||typeof t=="object"&&t.enabled===!1)return null;let r=typeof t=="string"?{preset:t}:t,i=typeof r.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(r.src)?r.src:void 0,n=typeof r.preset=="string"?r.preset:void 0;return!i&&!n?null:{ae:r,src:i,preset:n,volume:At(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function Zt(e,t){return ma(e,t)[0]}function ma(e,t){e.updateMatrixWorld(!0);let r=[],i=0,n=[],s=[],l=[],o=[],a=new Set,u=[],h=[],m=new Map,c=[],d=[],f=[],g=new Map,x=[],b=[];function v(I){let H=m.get(I);if(H!==void 0)return H;H=h.length,m.set(I,H);let C=I,z=C.color?.r??1,ue=C.color?.g??1,he=C.color?.b??1,O=C.opacity??1,$={baseColorFactor:[z,ue,he,O],metallicFactor:C.metalness??0,roughnessFactor:C.roughness??.5},_={},W=ee=>{if(!ee)return;let R=(typeof ee=="string"?ee:typeof ee.source=="string"?ee.source:typeof ee.image=="string"?ee.image:"").trim();if(!R||/[\x00-\x1f\x7f\\]|\.\./.test(R)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(R)||!R.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(R)))return;let A=g.get(R);if(A===void 0){let L=c.length;c.push({uri:R}),d.length===0&&d.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),A=f.length,f.push({sampler:0,source:L}),g.set(R,A)}return{index:A}},j=W(C.map);j&&($.baseColorTexture=j);let X=W(C.roughnessMap||C.metalnessMap);X&&($.metallicRoughnessTexture=X);let D=C.map?.avgColor;Array.isArray(D)&&D.length>=3&&(_.avgColor=[D[0],D[1],D[2]]);let Y=W(C.normalMap),te=W(C.emissiveMap),se=W(C.aoMap),le={name:C.name||"",pbrMetallicRoughness:$,doubleSided:C.side===2||!!C.doubleSided,...Y?{normalTexture:Y}:{},...te?{emissiveTexture:te}:{},...se?{occlusionTexture:se}:{},...Object.keys(_).length>0?{extras:_}:{}};if(C.emissive&&(C.emissive.r>0||C.emissive.g>0||C.emissive.b>0)){let ee=C.emissiveIntensity??1;le.emissiveFactor=[C.emissive.r*ee,C.emissive.g*ee,C.emissive.b*ee]}let V={};return C.clearcoat&&C.clearcoat>0&&(V.KHR_materials_clearcoat={clearcoatFactor:C.clearcoat,clearcoatRoughnessFactor:C.clearcoatRoughness||0}),C.sheen&&C.sheen>0&&(V.KHR_materials_sheen={sheenColorFactor:C.sheenColor?[C.sheenColor.r,C.sheenColor.g,C.sheenColor.b]:[1,1,1],sheenRoughnessFactor:C.sheenRoughness||0}),C.transmission&&C.transmission>0&&(V.KHR_materials_transmission={transmissionFactor:C.transmission}),C.thickness&&C.thickness>0&&(V.KHR_materials_volume={thicknessFactor:C.thickness,attenuationDistance:C.attenuationDistance??1/0,attenuationColor:C.attenuationColor?[C.attenuationColor.r,C.attenuationColor.g,C.attenuationColor.b]:[1,1,1]}),C.ior!==void 0&&C.ior!==1.5&&(V.KHR_materials_ior={ior:C.ior}),C.dispersion&&C.dispersion>0&&(V.KHR_materials_dispersion={dispersion:C.dispersion}),C.iridescence&&C.iridescence>0&&(V.KHR_materials_iridescence={iridescenceFactor:C.iridescence,iridescenceIor:C.iridescenceIOR??1.3}),Object.keys(V).length>0&&(le.extensions=V),h.push(le),H}function p(I,H){let C=new Uint8Array(I.buffer,I.byteOffset,I.byteLength),z=ml(C.byteLength),ue=new Uint8Array(z);ue.set(C),r.push(ue);let he=n.length;return n.push({buffer:0,byteOffset:i,byteLength:C.byteLength,target:H}),i+=z,he}function y(I,H,C,z,ue,he,O){let $=p(I,C),_=s.length,W={bufferView:$,byteOffset:0,componentType:z,count:ue,type:H};return he&&(W.min=he),O&&(W.max=O),s.push(W),_}e.traverse(I=>{if(I.isLight||I.color&&I.intensity!==void 0){let H=I.matrixWorld?.elements,C=Me(H?H[12]:I.position?.x,0),z=Me(H?H[13]:I.position?.y,0),ue=Me(H?H[14]:I.position?.z,0),he=I.target,O=he?.parent?he?.matrixWorld?.elements:void 0,$=Me(O?O[12]:he?.position?.x,0),_=Me(O?O[13]:he?.position?.y,0),W=Me(O?O[14]:he?.position?.z,0),j=$-C,X=_-z,D=W-ue,Y=Math.hypot(j,X,D),te=Math.max(.01,Math.min(Math.PI/2,Me(I.angle,Math.PI/3))),se=Math.max(0,Math.min(1,Me(I.penumbra,0)));b.push({type:I.type,color:[I.color.r,I.color.g,I.color.b],intensity:I.intensity,position:[C,z,ue],...I.type==="spot"?{direction:Y>1e-6?[j/Y,X/Y,D/Y]:[0,-1,0],outerConeAngle:te,innerConeAngle:Math.max(0,te*(1-se)),range:Math.max(0,Me(I.distance,0))}:I.type==="point"?{range:Math.max(0,Me(I.distance,0))}:{}})}});let M=[],P=new Set([e]),F=[];if(Array.isArray(e.children))for(let I=e.children.length-1;I>=0;I--)F.push({obj:e.children[I],parentKids:M});for(;F.length>0;){let{obj:I,parentKids:H}=F.pop();if(!I||typeof I!="object"||P.has(I))continue;P.add(I),I._bakeAuthorGeometry?.(),Ae().materializeDeclarativeGeometry?.(I);let C=!!(I.userData&&(I.userData.xr&&typeof I.userData.xr=="object"&&Object.keys(I.userData.xr).length>0||I.userData.interactivity&&typeof I.userData.interactivity=="object"&&Object.keys(I.userData.interactivity).length>0)),z={name:I.name||(C?`Node_${o.length}`:"")},ue=Me(I.position?.x,0),he=Me(I.position?.y,0),O=Me(I.position?.z,0),$=Me(I.quaternion?.x,0),_=Me(I.quaternion?.y,0),W=Me(I.quaternion?.z,0),j=Me(I.quaternion?.w,1),X=Me(I.scale?.x,1),D=Me(I.scale?.y,1),Y=Me(I.scale?.z,1);if((ue||he||O)&&(z.translation=[ue,he,O]),($||_||W||j!==1)&&(z.rotation=[$,_,W,j]),(X!==1||D!==1||Y!==1)&&(z.scale=[X,D,Y]),I.visible===!1&&(z.extensions={...z.extensions||{},KHR_node_visibility:{visible:!1}},a.add("KHR_node_visibility")),I.userData&&Object.keys(I.userData).length>0&&(z.extras=JSON.parse(JSON.stringify(I.userData,(le,V)=>{if(!(le==="__proto__"||le==="prototype"||le==="constructor"))return typeof V=="function"?void 0:V})),I.userData.xr)){let le=fl(I.userData.xr);z.extensions={...z.extensions||{},MOZ_hubs_components:le,ANDROID_xr_scenecore:le},Ae().xrTraitSerializer?.gltfNode(z,I.userData.xr),a.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(I.geometry){let le=I.geometry,V=le.attributes.position;if(V&&V.count>0){let ee=[1/0,1/0,1/0],R=[-1/0,-1/0,-1/0];for(let q=0;q<V.count;q++){let Z=V.getX(q),J=V.getY(q),K=V.getZ(q);Z<ee[0]&&(ee[0]=Z),Z>R[0]&&(R[0]=Z),J<ee[1]&&(ee[1]=J),J>R[1]&&(R[1]=J),K<ee[2]&&(ee[2]=K),K>R[2]&&(R[2]=K)}let A={attributes:{POSITION:y(V.array,"VEC3",34962,5126,V.count,ee,R)}};if(le.attributes.normal&&(A.attributes.NORMAL=y(le.attributes.normal.array,"VEC3",34962,5126,le.attributes.normal.count)),le.attributes.uv&&(A.attributes.TEXCOORD_0=y(le.attributes.uv.array,"VEC2",34962,5126,le.attributes.uv.count)),le.index){let q=le.index.array instanceof Uint32Array;A.indices=y(le.index.array,"SCALAR",34963,q?5125:5123,le.index.count)}let L=Array.isArray(I.material)?I.material[0]:I.material;L&&(A.material=v(L));let N=I.userData?.variants;if(N&&typeof N=="object"){let q=new Map;for(let Z of Object.keys(N)){if(!Z||Z==="__proto__"||Z==="constructor"||Z==="prototype")continue;let J=N[Z];if(!J||typeof J!="object")continue;let K=x.indexOf(Z);if(K===-1&&x.length<256&&(K=x.length,x.push(Z)),K===-1)continue;let ae=v(J),ne=q.get(ae);ne||(ne=[],q.set(ae,ne)),ne.push(K)}if(q.size>0){let Z=[];for(let[J,K]of q.entries())Z.push({material:J,variants:K});A.extensions={...A.extensions||{},KHR_materials_variants:{mappings:Z}},a.add("KHR_materials_variants")}}let U=I;if(U.isInstancedMesh&&typeof U.count=="number"&&U.count>0&&U.instanceMatrix?.array){let q=Math.min(1e4,Math.floor(U.count)),Z=U.instanceMatrix.array,J=new Float32Array(q*3),K=new Float32Array(q*4),ae=new Float32Array(q*3);for(let re=0;re<q;re++){let{t:ce,r:me,s:ge}=ha(Z,re*16);J[re*3]=ce[0],J[re*3+1]=ce[1],J[re*3+2]=ce[2],K[re*4]=me[0],K[re*4+1]=me[1],K[re*4+2]=me[2],K[re*4+3]=me[3],ae[re*3]=ge[0],ae[re*3+1]=ge[1],ae[re*3+2]=ge[2]}let ne={TRANSLATION:y(J,"VEC3",0,5126,q),ROTATION:y(K,"VEC4",0,5126,q),SCALE:y(ae,"VEC3",0,5126,q)};if(U.instanceColor?.array&&U.instanceColor.array.length>=q*3){let re=new Float32Array(U.instanceColor.array.subarray(0,q*3));ne._COLOR_0=y(re,"VEC3",0,5126,q)}z.extensions={...z.extensions||{},EXT_mesh_gpu_instancing:{attributes:ne}},a.add("EXT_mesh_gpu_instancing")}let Q=l.length;l.push({primitives:[A],name:I.name,...z.extras?{extras:z.extras}:{}}),z.mesh=Q}}let te=o.length;o.push(z),u.push(I),H.push(te);let se=I.children;if(Array.isArray(se)&&se.length>0){let le=[];z.children=le;for(let V=se.length-1;V>=0;V--)F.push({obj:se[V],parentKids:le})}}for(let I=0;I<o.length;I++){let H=o[I];H.children&&H.children.length===0?delete H.children:H.children&&H.children.length>0&&(H.extras?.xr?.lod||H.extensions?.ANDROID_xr_scenecore?.lod||u[I]?.isLOD)&&(H.extensions={...H.extensions||{},MSFT_lod:{ids:[...H.children]}},a.add("MSFT_lod"))}let G=t?.animateCallback||t?.animateFn||(typeof e.userData?.animate=="function"?e.userData.animate:typeof e.__animateFn=="function"?e.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),T=[];if(typeof G=="function"&&u.length>0){let I=t?.duration??4,H=t?.fps??15,C=Math.max(2,Math.round(I*H)+1),z=new Float32Array(C),ue=u.map(D=>[Me(D.position?.x,0),Me(D.position?.y,0),Me(D.position?.z,0),Me(D.quaternion?.x,0),Me(D.quaternion?.y,0),Me(D.quaternion?.z,0),Me(D.quaternion?.w,1),Me(D.scale?.x,1),Me(D.scale?.y,1),Me(D.scale?.z,1)]),he=u.map(()=>new Float32Array(C*3)),O=u.map(()=>new Float32Array(C*4)),$=u.map(()=>new Float32Array(C*3));for(let D=0;D<C;D++){let Y=D/(C-1)*I;z[D]=Y;try{G(Y)}catch{}for(let te=0;te<u.length;te++){let se=u[te];he[te][D*3]=Me(se.position?.x,0),he[te][D*3+1]=Me(se.position?.y,0),he[te][D*3+2]=Me(se.position?.z,0);let le=Me(se.quaternion?.x,0),V=Me(se.quaternion?.y,0),ee=Me(se.quaternion?.z,0),R=Me(se.quaternion?.w,1),A=Math.hypot(le,V,ee,R)||1;if(le/=A,V/=A,ee/=A,R/=A,D>0){let L=(D-1)*4,N=O[te];N[L]*le+N[L+1]*V+N[L+2]*ee+N[L+3]*R<0&&(le=-le,V=-V,ee=-ee,R=-R)}O[te][D*4]=le,O[te][D*4+1]=V,O[te][D*4+2]=ee,O[te][D*4+3]=R,$[te][D*3]=Me(se.scale?.x,1),$[te][D*3+1]=Me(se.scale?.y,1),$[te][D*3+2]=Me(se.scale?.z,1)}}for(let D=0;D<u.length;D++){let Y=u[D],te=ue[D];Y.position?.set(te[0],te[1],te[2]),Y.quaternion?.set(te[3],te[4],te[5],te[6]),Y.scale?.set(te[7],te[8],te[9])}e.updateMatrixWorld(!0);let _=null,W=()=>(_===null&&(_=y(z,"SCALAR",0,5126,C,[0],[I])),_),j=[],X=[];for(let D=0;D<u.length;D++){let Y=ue[D],te=(le,V,ee)=>le.some((R,A)=>Math.abs(R-Y[ee+A%V])>1e-4),se=(le,V,ee,R)=>{le&&X.push({sampler:j.push({input:W(),interpolation:"LINEAR",output:y(V,ee,0,5126,C)})-1,target:{node:D,path:R}})};se(te(he[D],3,0),he[D],"VEC3","translation"),se(te(O[D],4,3),O[D],"VEC4","rotation"),se(te($[D],3,7),$[D],"VEC3","scale")}X.length>0&&T.push({name:"ProceduralLoop",samplers:j,channels:X})}let E=Bo(o,l,e.userData),S=[],B=[],k=[];for(let I=0;I<o.length;I++){let H=o[I],C=ca(H.extras?.xr);if(!C)continue;let{ae:z,src:ue,preset:he,volume:O,loop:$,isGlobal:_}=C,W=H.name||`Node_${I}`,j=B.length;B.push({name:`${W}_source`,gain:O,loop:$,autoPlay:typeof z.autoplay=="boolean"?z.autoplay:!0,...ue!==void 0?{audio:S.push({uri:ue})-1}:{},...he?{extras:{preset:he,pitch:At(z.pitch,.25,4,1)}}:{}});let X=k.length,D=At(z.refDistance,.05,100,1),Y=At(z.coneInnerAngle,0,360,360),te=At(z.coneOuterAngle,Y,360,360);k.push({name:`${W}_emitter`,type:_?"global":"positional",gain:O,sources:[j],..._?{}:{positional:{distanceModel:z.distanceModel==="linear"||z.distanceModel==="exponential"?z.distanceModel:"inverse",refDistance:D,maxDistance:At(z.maxDistance,D,500,Math.max(D,25)),rolloffFactor:At(z.rolloffFactor,0,10,1),coneInnerAngle:+(Y*Math.PI/180).toFixed(6),coneOuterAngle:+(te*Math.PI/180).toFixed(6),coneOuterGain:At(z.coneOuterGain,0,1,0)}}}),H.extensions={...H.extensions||{},KHR_audio_emitter:{emitter:X}},a.add("KHR_audio_emitter")}let w={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity}},scenes:[{nodes:M}],scene:0,nodes:o,meshes:l,materials:h,...c.length>0?{images:c}:{},...d.length>0?{samplers:d}:{},...f.length>0?{textures:f}:{},accessors:s,bufferViews:n,buffers:[{byteLength:i}],...T.length>0?{animations:T}:{},...E||a.size>0?{extensionsUsed:[...E?["KHR_interactivity"]:[],...a]}:{},...E||x.length>0||k.length>0?{extensions:{...E?{KHR_interactivity:E}:{},...x.length>0?{KHR_materials_variants:{variants:x.map(I=>({name:I}))}}:{},...k.length>0?{KHR_audio_emitter:{...S.length>0?{audio:S}:{},sources:B,emitters:k}}:{}}}:{}},ie=new Uint8Array(i),oe=0;for(let I of r)ie.set(I,oe),oe+=I.byteLength;return[{gltf:w,bin:ie.buffer,lights:b,environmentIntensity:e.environmentIntensity},u]}function ji(e){return new TextEncoder().encode(e)}function fr(e,t){let{gltf:r,bin:i}=Zt(e,t),n=JSON.stringify(r),s=ji(n),l=(4-s.byteLength%4)%4,o=s.byteLength+l,a=20+o+8+i.byteLength,u=new Uint8Array(a),h=new DataView(u.buffer);h.setUint32(0,1179937895,!0),h.setUint32(4,2,!0),h.setUint32(8,a,!0),h.setUint32(12,o,!0),h.setUint32(16,1313821514,!0),u.set(s,20);for(let c=0;c<l;c++)u[20+s.byteLength+c]=32;let m=20+o;return h.setUint32(m,i.byteLength,!0),h.setUint32(m+4,5130562,!0),u.set(new Uint8Array(i),m+8),u}function pl(e,t){let[r,i]=ma(e,t);return fa(r,i)}function fa(e,t){let r=[],i=e.gltf,n=Ae().decoders.get("meshopt");n&&typeof n.decodeBufferViews=="function"&&n.decodeBufferViews(i,e);let s=e.bin,l=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),o=i.accessors||[],a=i.bufferViews||[],u=i.materials||[],h=i.meshes||[],m=i.nodes||[],c=i.textures||[],d=i.images||[],f=i.samplers||[],g=new Set,x=u.map((P,F)=>ua(g,kr(P?.name,`Material_${F}`))),b=new Map;function v(P){let F=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(P);if(!F)return null;let G=F[2].replace(/\s+/g,""),T=G.endsWith("==")?2:G.endsWith("=")?1:0,E=new Uint8Array((G.length*3>>2)-T),S=k=>{let w=G.charCodeAt(k);return w>96?w-71:w>64?w-65:w>47?w+4:w===43?62:w===47?63:0},B=0;for(let k=0;k<G.length;k+=4){let w=S(k)<<18|S(k+1)<<12|S(k+2)<<6|S(k+3);E[B++]=w>>16&255,B<E.length&&(E[B++]=w>>8&255),B<E.length&&(E[B++]=w&255)}return E}function p(P,F,G){let T=P?.index;if(typeof T!="number")return;let E=c[T],S=E?.source;if(typeof S!="number"||!d[S])return;let B=b.get(S);if(B===void 0){B=null;let ie=d[S],oe=null;if(typeof ie.bufferView=="number"){let I=a[ie.bufferView],H=I?.byteOffset||0,C=I?.byteLength||0;I&&C>0&&H>=0&&H+C<=l.byteLength&&(oe=new Uint8Array(l,H,C))}else typeof ie.uri=="string"&&(oe=v(ie.uri));if(oe&&oe.byteLength>0){let I=oe[0]===255&&oe[1]===216&&oe[2]===255||!(oe[0]===137&&oe[1]===80)&&/jpe?g/i.test(ie.mimeType||ie.uri||"");B={file:`texture_${S}.${I?"jpg":"png"}`,data:oe}}b.set(S,B)}if(!B)return;let k=typeof E.sampler=="number"?f[E.sampler]:void 0,w=ie=>ie===33071?"clamp":ie===33648?"mirror":"repeat";return{file:B.file,data:B.data,wrapS:w(k?.wrapS),wrapT:w(k?.wrapT),...F?{scale:F}:{},...G?{bias:G}:{}}}function y(P){let F=o[P];if(!F)throw new Error(`Accessor ${P} not found`);let G=a[F.bufferView||0],T=(G.byteOffset||0)+(F.byteOffset||0),E=G.byteLength||0;return{acc:F,buffer:l.slice(T,T+E)}}function M(P,F,G,T){let E=[],S=h[P];if(!S)return E;let B=S.primitives||[];for(let k=0;k<B.length;k++){let w=B[k],ie=w.attributes?.POSITION;if(ie===void 0)continue;let{acc:oe,buffer:I}=y(ie),H=new Float32Array(I,0,oe.count*3),C,z=w.attributes?.NORMAL;if(z!==void 0){let{acc:V,buffer:ee}=y(z),R=new Float32Array(ee,0,V.count*3);C=new Float32Array(R.length);for(let A=0;A<V.count;A++){let L=R[A*3],N=R[A*3+1],U=R[A*3+2],Q=Math.hypot(L,N,U)||1;C[A*3]=L/Q,C[A*3+1]=N/Q,C[A*3+2]=U/Q}}let ue,he=w.attributes?.TEXCOORD_0;if(he!==void 0){let{acc:V,buffer:ee}=y(he);ue=new Float32Array(ee,0,V.count*2)}let O;if(w.indices!==void 0){let{acc:V,buffer:ee}=y(w.indices);O=V.componentType===5125?new Uint32Array(ee,0,V.count):new Uint16Array(ee,0,V.count);let R=oe.count;for(let A of O)if(A>=R)throw new Error(`SecurityError: Index buffer value (${A}) out of vertex bounds [0, ${R}).`)}else{let V=oe.count;O=V>65535?new Uint32Array(V):new Uint16Array(V);for(let ee=0;ee<V;ee++)O[ee]=ee}let $="DefaultMaterial",_=[1,1,1],W=.5,j=0,X=0,D=0,Y=1.5,te=1,se=[0,0,0],le;if(w.material!==void 0&&u[w.material]){let V=u[w.material];$=x[w.material]||`Material_${w.material}`;let ee=V.pbrMetallicRoughness||{},R=(ce,me)=>Array.isArray(ce)&&ce.length>=3?[ce[0],ce[1],ce[2]]:me;_=R(ee.baseColorFactor,[1,1,1]);let A=Array.isArray(ee.baseColorFactor)&&typeof ee.baseColorFactor[3]=="number"?ee.baseColorFactor[3]:1,L=_[0]!==1||_[1]!==1||_[2]!==1||A!==1,N=p(ee.baseColorTexture,L?[_[0],_[1],_[2],A]:void 0),U=V.extras?.avgColor;!N&&Array.isArray(U)&&U.length>=3&&(_=[_[0]*U[0],_[1]*U[1],_[2]*U[2]]),typeof ee.roughnessFactor=="number"&&(W=ee.roughnessFactor),typeof ee.metallicFactor=="number"&&(j=ee.metallicFactor);let Q=typeof ee.roughnessFactor=="number"?ee.roughnessFactor:1,q=typeof ee.metallicFactor=="number"?ee.metallicFactor:1,Z=p(ee.metallicRoughnessTexture,Q!==1||q!==1?[1,Q,q,1]:void 0);se=R(V.emissiveFactor,[0,0,0]);let J=(se[0]>0||se[1]>0||se[2]>0)&&(se[0]!==1||se[1]!==1||se[2]!==1)?[se[0],se[1],se[2],1]:void 0,K=p(V.emissiveTexture,J),ae=p(V.normalTexture,[2,2,2,1],[-1,-1,-1,0]),ne=p(V.occlusionTexture);(N||Z||ae||K||ne)&&(le=[N,Z,ae,K,ne]);let re=V.extensions||{};re.KHR_materials_clearcoat&&(X=re.KHR_materials_clearcoat.clearcoatFactor??0,D=re.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof re.KHR_materials_ior?.ior=="number"&&(Y=re.KHR_materials_ior.ior),te=A*(1-(re.KHR_materials_transmission?.transmissionFactor??0))}E.push({name:B.length>1?`${F}_p${k}`:F,positions:H,indices:O,normals:C,uvs:ue,materialName:$,color:_,roughness:W,metallic:j,clearcoat:X,clearcoatRoughness:D,ior:Y,opacity:te,emissiveColor:se,...le?{textures:le}:{},xrTraits:G||S.extras?.xr,...T?{invisible:!0}:{}})}return E}if(m.length>0){let P=new Float32Array(0),F=new Uint16Array(0),G=(H,C)=>{if(H===void 0)return null;let{acc:z,buffer:ue}=y(H);return new Float32Array(ue,0,z.count*C)},T=(H,C)=>Array.isArray(H)&&H.length>=3?[Me(H[0],C),Me(H[1],C),Me(H[2],C)]:[C,C,C],E=(H,C,z)=>H&&H.length>=(C+1)*3?[H[C*3],H[C*3+1],H[C*3+2]]:z,S=(H,C,z)=>H&&H.length>=(C+1)*4?[H[C*4],H[C*4+1],H[C*4+2],H[C*4+3]]:z,B=new Map,k=i.animations?.[0];if(k&&Array.isArray(k.channels)&&Array.isArray(k.samplers))for(let H of k.channels){let C=k.samplers[H?.sampler],z=H?.target?.node,ue=H?.target?.path;if(!C||typeof z!="number"||C.input===void 0)continue;let he=B.get(z);he||(he={input:C.input},B.set(z,he)),ue==="translation"?he.t=C.output:ue==="rotation"?he.r=C.output:ue==="scale"&&(he.s=C.output)}let w=i.scenes?.[i.scene??0]?.nodes??[];if(!Array.isArray(w)||w.length===0){let H=new Set;for(let C of m)if(Array.isArray(C?.children))for(let z of C.children)H.add(z);w=[];for(let C=0;C<m.length;C++)H.has(C)||w.push(C);w.length===0&&(w=[0])}let ie=new Set,oe=[],I=(H,C)=>{if(Array.isArray(H))for(let z=H.length-1;z>=0;z--)oe.push({idx:H[z],out:C})};for(I(w,r);oe.length>0;){let{idx:H,out:C}=oe.pop();if(typeof H!="number"||H<0||H>=m.length||ie.has(H))continue;ie.add(H);let z=m[H];if(!z)continue;let ue=[0,0,0],he=[0,0,0,1],O=[1,1,1];if(Array.isArray(z.matrix)&&z.matrix.length===16){let te=ha(z.matrix);ue=te.t,he=te.r,O=te.s}else ue=T(z.translation,0),Array.isArray(z.rotation)&&z.rotation.length>=4&&(he=[Me(z.rotation[0],0),Me(z.rotation[1],0),Me(z.rotation[2],0),Me(z.rotation[3],1)]),O=T(z.scale,1);let $,_=B.get(H);if(_){let te=G(_.input,1);if(te&&te.length>0){let se=G(_.t,3),le=G(_.r,4),V=G(_.s,3),ee=Array.from(te),R=[],A=[],L=[];for(let N=0;N<te.length;N++)R.push(E(se,N,ue)),A.push(S(le,N,he)),L.push(E(V,N,O));$={times:ee,translations:R,rotations:A,scales:L}}}let W=Array.isArray(z.children)?z.children:[],j=typeof z.mesh=="number"&&z.mesh>=0&&z.mesh<h.length,X=t?.[H]?.userData?.xr??z.extras?.xr;if(!j&&W.length===0&&(z.camera!==void 0||z.extensions?.KHR_lights_punctual||!z.name&&!z.extras&&!X&&!$))continue;let D=(te,se,le)=>({name:te,positions:P,indices:F,isXform:!0,xrTraits:X,timeSamples:$,translation:ue,rotation:he,scale:O,children:se,...le?{invisible:!0}:{}}),Y=z.visible===!1||z.extensions?.KHR_node_visibility?.visible===!1||t?.[H]?.visible===!1;if(j){let te=z.name||h[z.mesh]?.name||`Mesh_${H}`,se=M(z.mesh,te,X,Y),le=z.extensions?.EXT_mesh_gpu_instancing?.attributes;if(le&&typeof le=="object"&&se.length>0){let V=G(le.TRANSLATION,3),ee=G(le.ROTATION,4),R=G(le.SCALE,3),A=G(le._COLOR_0,3),L=Math.min(1e3,V?V.length/3:ee?ee.length/4:R?R.length/3:0);if(L>0){let N=[];for(let U=0;U<L;U++){let Q=E(V,U,[0,0,0]),q=S(ee,U,[0,0,0,1]),Z=E(R,U,[1,1,1]);for(let J of se){let K=J.color||[.8,.8,.8],ae=A&&A.length>=(U+1)*3;N.push({...J,name:`${J.name}_${U}`,materialName:ae?`${J.materialName}_inst_${U}`:J.materialName,color:ae?[K[0]*A[U*3],K[1]*A[U*3+1],K[2]*A[U*3+2]]:J.color,translation:Q,rotation:q,scale:Z})}}I(W,N),C.push(D(te,N,Y));continue}}if(se.length===1)se[0].translation=ue,se[0].rotation=he,se[0].scale=O,se[0].timeSamples=$,W.length>0&&(se[0].children=[],I(W,se[0].children)),C.push(se[0]);else{let V=[...se];I(W,V),C.push(D(te,V,Y))}}else{let te=[];I(W,te),C.push(D(z.name||`Group_${H}`,te,Y))}}}else for(let P=0;P<h.length;P++){let F=h[P].name||`Mesh_${P}`;r.push(...M(P,F,h[P].extras?.xr))}return r}function kr(e,t){if(!e||typeof e!="string")return t;let r=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(r)&&(r="_"+r),r||t}function Fr(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function $e(e){if(!Number.isFinite(e)||Math.abs(e)<1e-7)return"0";let t=Number(e.toFixed(5)).toString();return t.indexOf(".")===-1?`${t}.0`:t}var bt=(e,t,r)=>`(${$e(e)}, ${$e(t)}, ${$e(r)})`,Vr=(e,t,r,i)=>`(${$e(e)}, ${$e(t)}, ${$e(r)}, ${$e(i)})`;function pa(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=bt(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function dl(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${$e(e[i*2])}, ${$e(1-e[i*2+1])})`;return r.join(", ")}function gl(e){return Array.from(e).join(", ")}function yl(e){let t=new Map,r=0,i=null,n=[...e];for(;n.length>0;){let f=n.pop();if(!f.isXform&&f.positions&&f.positions.length>0){let g=kr(f.materialName,"DefaultMaterial");t.has(g)||t.set(g,{color:f.color||[1,1,1],roughness:f.roughness??.5,metallic:f.metallic??0,clearcoat:f.clearcoat??0,clearcoatRoughness:f.clearcoatRoughness??0,ior:f.ior??1.5,opacity:f.opacity??1,emissiveColor:f.emissiveColor||[0,0,0],textures:f.textures})}if(f.timeSamples&&f.timeSamples.times.length>0){let g=f.timeSamples.times[f.timeSamples.times.length-1];g>r&&(r=g)}if(f.xrTraits?.anchor&&!i&&(i=f.xrTraits.anchor==="vertical"||f.xrTraits.anchor==="wall"?"vertical":"horizontal"),f.children)for(let g=f.children.length-1;g>=0;g--)n.push(f.children[g])}let s="";r>0&&(s=`startTimeCode = 0
251
- endTimeCode = ${$e(r)}
215
+ void main(){fragColor=uColorId;}`;function ba(e,t,r){let i={};for(let n of r)i[n]=e.getUniformLocation(t,n);return i}var pp="uMVP uModel uInstanced uViewProj uNormalMatrix uUvTransform uBaseColor uMetallic uRoughness uClearcoat uEmissive uCameraPos uBaseColorTexture uHasTexture uMetallicRoughnessTexture uHasMetallicRoughnessTexture uNormalTexture uHasNormalTexture uNormalScale uOcclusionTexture uHasOcclusionTexture uOcclusionStrength uEmissiveFactor uEmissiveTexture uHasEmissiveTexture uToneMapping uEnvironmentMap uHasEnvironmentMap uAmbientColor uHemi uNumDirLights uDirLightDir uDirLightColor uNumPointLights uPointLightPos uPointLightColor uPointLightSpotDir uPointLightSpotCone uEnvIntensity uExposure uViewportSize uSectionPlane uSectionEnabled".split(" ");function Ao(){let e=We(),t=e.xrDepthShader,r=e.shadowMapShader;return{fs:hp.replace("/*XRD_U*/",t?.uniformsGLSL||"").replace("/*XRD_O*/",t?.occlusionGLSL||"").replace("/*SHD_U*/",r?.uniformsGLSL||"").replace("/*SHD_D*/",r?.dirGLSL||"").replace("/*SHD_P*/",r?.ptGLSL||""),uniforms:[...pp,...t?.uniformNames||[],...r?.uniformNames||[]]}}function dp(e){if(typeof e!="string")return null;let t=e.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let r=t.toLowerCase();return r.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:r.startsWith("https://")||r.startsWith("blob:")?t:r.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function To(e,t,r,i,n,a,s,o){if(i===void 0||!t.accessors?.[i])return null;let l=Fi(t,r,t.accessors[i],a);if(!l)return null;o&&(l=l.slice(),sp(l,o));let c=e.createBuffer();return s.push(c),e.bindBuffer(34962,c),e.bufferData(34962,l,35044),e.enableVertexAttribArray(n),e.vertexAttribPointer(n,a,5126,!1,0,0),l}function Po(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function mh(e,t,r){let i=Ao(),n=So,a=i.fs,s=!1;for(let l of Lt)if(l.onResolveShader){let c=l.onResolveShader(t,r,n,a);c&&(n=c.vs,a=c.fs,s=!0)}let o=s?_i(e,n,a):null;return{program:o,uniforms:o?ba(e,o,i.uniforms):null}}function gp(e,t,r){let i=t.instanceMatrices;if(!i||i.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let n=i.length>>4,a=t.instanceColors,s=new Float32Array(n*20);for(let l=0;l<n;l++)s.set(i.subarray(l*16,l*16+16),l*20),s[l*20+16]=a?a[l*3]:1,s[l*20+17]=a?a[l*3+1]:1,s[l*20+18]=a?a[l*3+2]:1,s[l*20+19]=1;let o=e.createBuffer();r.push(o),e.bindBuffer(34962,o),e.bufferData(34962,s,35044);for(let l=0;l<5;l++)e.enableVertexAttribArray(8+l),e.vertexAttribPointer(8+l,4,5126,!1,80,l*16),e.vertexAttribDivisor(8+l,1);return!0}function yp(e,t){let r=e.materials?.[t?.material];if(!r)return null;let i=[r.pbrMetallicRoughness?.baseColorTexture,r.pbrMetallicRoughness?.metallicRoughnessTexture,r.normalTexture,r.occlusionTexture,r.emissiveTexture];for(let n of i){let a=n?.extensions?.KHR_texture_transform;if(a&&typeof a=="object")return a}return null}var bp=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),ph=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function xa(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function dh(e,t){let r=e?.pbrMetallicRoughness,i=r?.baseColorFactor,n=e?.emissiveFactor,a=e?.extensions?.KHR_materials_clearcoat,s=o=>o!==void 0&&t[o.index]?t[o.index]:null;return{baseColor:i?[i[0],i[1],i[2],i[3]??1]:[.8,.8,.8,1],metallic:r?.metallicFactor??.1,roughness:r?.roughnessFactor??.5,clearcoat:a?a.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,a?.clearcoatRoughnessFactor??.04),texture:s(r?.baseColorTexture),metallicRoughnessTexture:s(r?.metallicRoughnessTexture),normalTexture:s(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:s(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,emissiveTexture:s(e?.emissiveTexture),emissiveFactor:Array.isArray(n)&&n.length>=3?[n[0],n[1],n[2]]:[0,0,0],isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function gh(e,t,r){let i=new Set,n=a=>{a&&!i.has(a)&&(i.add(a),e.deleteTexture(a))};for(let a of t)for(let s of a.primitives){if(s.vao&&e.deleteVertexArray(s.vao),s.buffers)for(let l of s.buffers)e.deleteBuffer(l);for(let l of[s.texture,s.metallicRoughnessTexture,s.normalTexture,s.occlusionTexture,s.emissiveTexture])n(l);let o=new Set;s.customProgram&&o.add(s.customProgram);for(let l of s.programCache?.values()??[])l.program&&o.add(l.program);for(let l of o)e.deleteProgram(l)}if(r)for(let a of r)n(a)}function yh(e,t,r=ph,i){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return xp(e,t,r,i,n)}catch(a){let s=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;gh(e,s,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let o of n.buffers)e.deleteBuffer(o);throw a}}function xp(e,t,r,i,n){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:a}=t,s=ya("meshopt");s?.decodeBufferViews&&s.decodeBufferViews(a,t);let o=t.bin,l=[];n.meshes=l;let c=[],f=a.extensions?.KHR_materials_variants;f&&Array.isArray(f.variants)&&f.variants.forEach((P,R)=>{c.push(typeof P?.name=="string"&&P.name?P.name:`Variant_${R}`)});let m=An(a),h=[];if(Array.isArray(a.nodes))for(let P=0;P<a.nodes.length;P++){let R=a.nodes[P];R.mesh!==void 0&&a.meshes&&a.meshes[R.mesh]&&h.push({node:R,nodeIdx:P,meshIdx:R.mesh})}let p=h.length>0?h:(a.meshes||[]).map((P,R)=>({node:P,nodeIdx:-1,meshIdx:R})),g=[],x=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(a.asset?.extras?.lights)&&a.asset.extras.lights.length>0?a.asset.extras.lights:null;if(x)for(let P of x)g.push({...P,type:P.type||P.light_type||"point",groundColor:P.groundColor??P.ground_color,innerConeAngle:P.innerConeAngle??P.inner_cone_angle,outerConeAngle:P.outerConeAngle??P.outer_cone_angle});else a.extensions?.KHR_lights_punctual?.lights&&g.push(...hh(a,m));if(g.length===0&&(g.push({type:"ambient",color:[1,1,1],intensity:.35}),g.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),p.length>r.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${r.maxMeshes}). Found: ${p.length}`);let v=[];if(n.gpuTextures=v,a.textures&&a.images){if(a.textures.length>r.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${r.maxTextures}). Found: ${a.textures.length}`);for(let P=0;P<a.textures.length;P++){let R=a.textures[P],I=a.images[R.source];if(I){let F=e.createTexture();e.bindTexture(3553,F),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255]));for(let[Y,J]of[[10242,10497],[10243,10497],[10241,9729],[10240,9729]])e.texParameteri(3553,Y,J);let V=Y=>{F.__gpuImageSource=Y,e.bindTexture(3553,F),e.texImage2D(3553,0,6408,6408,5121,Y),e.generateMipmap(3553),i?.()};if(I.bufferView!==void 0){let Y=a.bufferViews[I.bufferView],J=Y.byteOffset||0,re=new Blob([o.slice(J,J+Y.byteLength)],{type:I.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(re).then(V).catch(()=>{})}else if(I.uri){let Y=dp(I.uri);if(Y){let J=new Image;J.crossOrigin="anonymous",J.referrerPolicy="no-referrer",J.onload=()=>V(J),J.src=Y}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",I.uri)}v.push(F)}else v.push(null)}}let y=[1/0,1/0,1/0],A=[-1/0,-1/0,-1/0],b=0,w=0;for(let P=0;P<p.length;P++){let R=p[P],I=a.meshes[R.meshIdx],F=R.nodeIdx>=0?m[R.nodeIdx]:lt(),V=new Float32Array(9);rr(V,F);let Y=R.node?.extras?.shadow,J={name:R.node.name||I.name||`Mesh_${R.meshIdx}`,nodeIndex:R.nodeIdx,transform:F,normalMatrix:V,primitives:[],extras:R.node.extras||I.extras,...R.node?.visible===!1||R.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{},...typeof Y?.cast=="boolean"?{castShadow:Y.cast}:{},...typeof Y?.receive=="boolean"?{receiveShadow:Y.receive}:{}};n.mesh=J;let re=R.node?.extensions?.EXT_mesh_gpu_instancing;if(re&&re.attributes&&typeof re.attributes=="object"){let Q=re.attributes,ee=Q.TRANSLATION!==void 0?a.accessors?.[Q.TRANSLATION]:null,k=Q.ROTATION!==void 0?a.accessors?.[Q.ROTATION]:null,G=Q.SCALE!==void 0?a.accessors?.[Q.SCALE]:null,q=Q._COLOR_0!==void 0?a.accessors?.[Q._COLOR_0]:null,H=Number(ee?.count??k?.count??G?.count??0);if(!Number.isFinite(H)||H<0||H>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${H}`);if(H>0){let te=(_e,Le)=>{if(!_e||_e.bufferView===void 0||!a.bufferViews?.[_e.bufferView])return null;let ne=_e.componentType??5126,Re=D=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${D})`),null);if(ne!==5120&&ne!==5121&&ne!==5122&&ne!==5123&&ne!==5126)return Re(`componentType ${ne}`);if(!(Number(_e.count)>=H))return Re(`count ${_e.count} < ${H}`);let W=null;try{W=Fi(a,o,{..._e,count:H},Le)}catch{return Re("out of bounds")}return!W||!W.every(Number.isFinite)?Re("non-finite value"):W},Z=te(ee,3),ae=te(k,4),ie=te(G,3),de=q?.type==="VEC4"?4:3,me=te(q,de),Se=new Float32Array(H*16),ke=lt();for(let _e=0;_e<H;_e++){let Le=_e*3,ne=_e*4;Sn(ke,ae?[ae[ne],ae[ne+1],ae[ne+2],ae[ne+3]]:[0,0,0,1],Z?[Z[Le],Z[Le+1],Z[Le+2]]:[0,0,0],ie?[ie[Le],ie[Le+1],ie[Le+2]]:[1,1,1]),Se.set(ke,_e*16)}if(J.instanceMatrices=Se,me){let _e=new Float32Array(H*3);for(let Le=0;Le<H;Le++)_e[Le*3]=me[Le*de],_e[Le*3+1]=me[Le*de+1],_e[Le*3+2]=me[Le*de+2];J.instanceColors=_e}}}for(let Q of I.primitives||[]){if(Q.extensions?.KHR_draco_mesh_compression){let z=ya("draco");z&&z.decodePrimitive(a,Q,o)}let ee=[],k=e.createVertexArray();n.vao=k,n.buffers=ee,e.bindVertexArray(k);let G=gp(e,J,ee),q=a.accessors[Q.attributes.POSITION],H=Number(q?.count??0);if(!Number.isFinite(H)||H<0||b+H>r.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${r.maxVertices}).`);if(b+=H,q?.min&&q?.max){let z=O=>{for(let X=0;X<3;X++){let se=O[12+X],ce=se;for(let pe=0;pe<3;pe++){let xe=O[pe*4+X]*q.min[pe],he=O[pe*4+X]*q.max[pe];se+=xe<he?xe:he,ce+=xe>he?xe:he}se<y[X]&&(y[X]=se),ce>A[X]&&(A[X]=ce)}};if(J.instanceMatrices&&J.instanceMatrices.length>=16){let O=J.instanceMatrices.length>>4,X=lt();for(let se=0;se<O;se++)ft(X,F,J.instanceMatrices.subarray(se*16,se*16+16)),z(X)}else z(F)}let te=To(e,a,o,Q.attributes.POSITION,0,3,ee),Z=To(e,a,o,Q.attributes.NORMAL,1,3,ee),ae=To(e,a,o,Q.attributes.TEXCOORD_0,2,2,ee,yp(a,Q)),ie=0,de=5123,me=null;if(Q.indices!==void 0){let z=a.accessors[Q.indices],O=(a.bufferViews[z.bufferView].byteOffset||0)+(z.byteOffset||0);if(ie=Number(z.count??0),!Number.isFinite(ie)||ie<0||w+ie>r.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${r.maxIndices}).`);w+=ie,de=z.componentType===5125?5125:5123;let X=e.createBuffer();ee.push(X),e.bindBuffer(34963,X),z.componentType===5125?me=new Uint32Array(o,O,z.count):z.componentType===5121?me=Uint16Array.from(new Uint8Array(o,O,z.count)):me=O%2===0?new Uint16Array(o,O,z.count):new Uint16Array(o.slice(O,O+z.count*2)),e.bufferData(34963,me,35044)}else ie=q.count;let Se={};for(let z of Lt)if(z.onBuildPrimitiveVAO){let O=z.onBuildPrimitiveVAO(e,k,Q,a,o);O&&(Se[z.name]=O)}e.bindVertexArray(null);let ke=a.materials&&Q.material!==void 0?a.materials[Q.material]:null,{program:_e,uniforms:Le}=mh(e,Q,ke),ne=dh(ke,v),Re=!!(ke?.extensions?.KHR_materials_transmission||Se.materials?.isTransmissive),W=Q.extensions?.KHR_materials_variants?.mappings,D=Array.isArray(W)?W.filter(z=>z&&typeof z.material=="number"&&Array.isArray(z.variants)).map(z=>({material:z.material|0,variants:z.variants.map(O=>Number(O)|0)})):void 0;J.primitives.push({vao:k,instanced:G,indexCount:ie,indexType:de,...ne,positions:te,normals:Z,uvs:ae,indices:me,buffers:ee,materialIndex:Q.material,defaultMaterialIndex:Q.material,variantMappings:D,primitiveDef:Q,programCache:new Map([[Q.material??-1,{program:_e,uniforms:Le}]]),pluginData:Se,customProgram:_e,customUniforms:Le,isTransmissive:Re})}l.push(J)}isFinite(y[0])||(y=[-1,-1,-1]),isFinite(A[0])||(A=[1,1,1]);let S=[(y[0]+A[0])/2,(y[1]+A[1])/2,(y[2]+A[2])/2],E=Math.max(Math.hypot(A[0]-y[0],A[1]-y[1],A[2]-y[2])/2,.5),N=[...y],C=[...A],_=t.animations;if(t.animationsParsed===!1||!_){for(let P of Lt)if(P.onParseGLB?.(t),t.animations){_=t.animations;break}}return _||(_=[]),{meshes:l,bounds:{center:S,radius:E,min:N,max:C},lights:g,animations:_,worldMatrices:m,gpuTextures:v,availableVariants:c}}function va(){return typeof performance<"u"?performance.now():Date.now()}function Cn(e){let t=e.customTarget||e.bounds.center,r=e.currDistance*Math.cos(e.currPhi);return[t[0]+r*Math.sin(e.currTheta),t[1]+e.currDistance*Math.sin(e.currPhi),t[2]+r*Math.cos(e.currTheta)]}var ir=class{constructor(e,t,r){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=lt(),this.clearColor=[0,0,0,0],this.envIntensity=1,this.exposure=1,this.shadowIntensity=0,this.shadowSoftness=.5,this.toneMapping="neutral",this.environmentTexture=null,this.environmentSource=null,this.animations=[],this.currentClip=null,this.animationTime=0,this.isPlayingAnimation=!1,this.autoplay=!1,this.animationName="",this.gpuTextures=[],this.availableVariants=[],this.activeVariantName=null,this.gltf=null,this.worldMatrices=[],this.initialNodeTransforms=[],this.projMatrix=lt(),this.viewMatrix=lt(),this.activeViewMatrix=null,this.modelMatrix=lt(),this.mvpMatrix=lt(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshNames=new Set,this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:lt(),rawValueToMeters:.001,format:0},this.container=e;let i,n;if(t&&typeof t.getContext=="function"?(i=t,n=r):(n=t,i=n?.canvas),!i){let l=e.querySelector("canvas");l||(l=document.createElement("canvas"),l.style.cssText="width:100%;height:100%;display:block;touch-action:none",e.prepend(l)),i=l}this.canvas=i;let a=this.opts=n||{};a.clearColor&&(this.clearColor=a.clearColor);let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;a.autoRotate!==void 0?this.autoRotate=a.autoRotate&&!s:s&&(this.autoRotate=!1),a.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=a.autoRotateSpeed),a.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(a.autoRotateDelay)||0)),a.exposure!==void 0&&(this.exposure=Po(a.exposure)),a.camera&&this.setInitialCamera(a.camera.theta,a.camera.phi,a.camera.distance,a.camera.zoom),(a.shadowIntensity!==void 0||a.shadowSoftness!==void 0)&&this.setShadow(a.shadowIntensity??0,a.shadowSoftness),a.shadowMaps!==void 0&&(this.shadowMaps=a.shadowMaps),a.toneMapping!==void 0&&(this.toneMapping=Bi(a.toneMapping)),a.autoplay!==void 0&&(this.autoplay=a.autoplay),a.animationName!==void 0&&(this.animationName=a.animationName),a.variantName!==void 0&&(this.activeVariantName=a.variantName||null),a.fieldOfView!==void 0&&(this.fov=a.fieldOfView*Math.PI/180),a.distanceMode!==void 0&&(this.distanceMode=a.distanceMode),a.cameraTarget!==void 0&&(this.setTarget(a.cameraTarget[0],a.cameraTarget[1],a.cameraTarget[2]),this.initialCustomTarget=[...a.cameraTarget]),(a.minCameraOrbit||a.maxCameraOrbit)&&this.setOrbitLimits({minTheta:a.minCameraOrbit?.theta,maxTheta:a.maxCameraOrbit?.theta,minPhi:a.minCameraOrbit?.phi,maxPhi:a.maxCameraOrbit?.phi,minDistance:a.minCameraOrbit?.distance,maxDistance:a.maxCameraOrbit?.distance});let o=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!o)throw new Error("WebGL2 not supported");this.gl=o,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),a.environmentImage&&this.setEnvironmentImage(a.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&a.autoStart!==!1&&this.start()}static registerDecoder(e,t){up(e,t)}static getDecoder(e){return ya(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=Ao();this.renderProg=_i(e,So,t.fs),this.pickProg=_i(e,fp,mp),this.uRender=ba(e,this.renderProg,t.uniforms),this.uPick=ba(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}recompileRenderProgram(){if(this.contextLost)return;let e=this.gl,t=Ao();this.renderProg&&e.deleteProgram(this.renderProg),this.renderProg=_i(e,So,t.fs),this.uRender=ba(e,this.renderProg,t.uniforms);for(let r of this.meshes)for(let i of r.primitives)i.customProgram&&(e.deleteProgram(i.customProgram),i.programCache?.clear(),this.applyPrimitiveProgram(i,i.materialIndex,this.gltf?.materials?.[i.materialIndex??-1]??null))}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of Lt)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;typeof e.createFramebuffer=="function"&&(this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer(),this.resizePickingFbo(this.canvas.width,this.canvas.height),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null))}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),n=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=n,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,n,0,6408,5121,null),r.texParameteri(3553,10241,9728),r.texParameteri(3553,10240,9728),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,n)}loadGLBData(e,t){let{meshes:r,bounds:i,lights:n,animations:a,worldMatrices:s,gpuTextures:o,availableVariants:l}=yh(this.gl,e,t,()=>this.render());this.lastGlbData=e,this.lastLimits=t,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=n,this.animations=a||[],this.worldMatrices=s||[],this.gpuTextures=o||[],this.availableVariants=l||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=(e.gltf?.nodes||[]).map(m=>({t:[m.translation?.[0]??0,m.translation?.[1]??0,m.translation?.[2]??0],r:[m.rotation?.[0]??0,m.rotation?.[1]??0,m.rotation?.[2]??0,m.rotation?.[3]??1],s:[m.scale?.[0]??1,m.scale?.[1]??1,m.scale?.[2]??1]})),this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let m of Lt)m.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let c=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;c!==void 0&&(this.exposure=Po(c));let f=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;f!==void 0&&(this.envIntensity=Math.max(0,Number(f)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(ch(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of Lt)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(zi(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=zi(e),{meshes:i}=yh(this.gl,r,ph,()=>this.render());if(t)for(let n of i)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],rr(n.normalMatrix,n.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(e,t,r,i=1){this.clearColor=[e,t,r,i]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let r=this.meshes[t],i=e instanceof Map?e.get(r.name)??e.get(t):Array.isArray(e)?e[t]:e&&typeof e=="object"?Object.prototype.hasOwnProperty.call(e,r.name)?e[r.name]:Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0:void 0;i&&i.length===16&&(r.transform.set(i),rr(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[0,0,0,0,0,0,0,1,0],n=!1,a=[],s=[],o=[],l=[],c=[],f=[];for(let m of this.lights){let h=m.color||[1,1,1],p=m.intensity!==void 0?m.intensity:1;if(m.type==="ambient")r=[h[0]*p,h[1]*p,h[2]*p];else if(m.type==="hemisphere"){n=!0;let g=m.groundColor||[.2,.2,.2],x=p*.65;for(let A=0;A<3;A++)i[A]+=h[A]*x,i[A+3]+=g[A]*x;let v=m.position||[0,1,0],y=Math.hypot(v[0],v[1],v[2]);y>1e-5&&(i[6]=v[0]/y,i[7]=v[1]/y,i[8]=v[2]/y)}else if(m.type==="directional"&&a.length<6){let g=m.direction||[.5,1,.8];a.push(g[0],g[1],g[2]),s.push(h[0]*p,h[1]*p,h[2]*p)}else if((m.type==="point"||m.type==="spot")&&o.length<6){let g=m.position||[0,0,0];if(o.push(g[0],g[1],g[2]),l.push(h[0]*p,h[1]*p,h[2]*p),m.type==="spot"){let x=m.direction||[0,-1,0],v=Math.max(.01,Math.min(Math.PI/2,m.outerConeAngle??Math.PI/3)),y=Math.max(0,Math.min(v-1e-4,m.innerConeAngle??0));c.push(x[0],x[1],x[2]),f.push(Math.cos(y),Math.cos(v))}else c.push(0,-1,0),f.push(-2,-3)}}a.length===0&&!n&&(a.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),e.uHemi&&t.uniformMatrix3fv(e.uHemi,!1,i),t.uniform1i(e.uNumDirLights,a.length/3),a.length>0&&(t.uniform3fv(e.uDirLightDir,a),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,o.length/3),o.length>0&&(t.uniform3fv(e.uPointLightPos,o),t.uniform3fv(e.uPointLightColor,l),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,c),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,f)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Po(e)}getExposure(){return this.exposure}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=Bi(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){this.environmentSource=e&&typeof e=="object"?e:null;for(let t of Lt)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e),this.render();return}this.render()}async setSkyboxImage(e){for(let t of Lt)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(f=>f.primitives.filter(m=>m.materialIndex===r||e.length===1&&m.materialIndex===void 0)),n=i[0],a=n?[...n.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],s=n?n.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,o=n?n.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,l=(f,m,h)=>{c[f]=h,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness[f]=h);for(let p of i)p[m]=h;this.render()},c={baseColorFactor:a,metallicFactor:s,roughnessFactor:o,setBaseColorFactor:f=>l("baseColorFactor","baseColor",[f[0],f[1],f[2],f[3]??1]),setMetallicFactor:f=>l("metallicFactor","metallic",f),setRoughnessFactor:f=>l("roughnessFactor","roughness",f)};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:c}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let n of this.meshes)for(let a of n.primitives){let s=a.defaultMaterialIndex;if(!t&&Array.isArray(a.variantMappings)){for(let l of a.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(r)){s=l.material;break}}let o=s!==void 0?i[s]:void 0;a.materialIndex=o?s:void 0,Object.assign(a,dh(o,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,o??null)}return!0}applyPrimitiveProgram(e,t,r){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let i=t??-1,n=e.programCache.get(i);n||(n=mh(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,n)),e.customProgram=n.program,e.customUniforms=n.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of Lt)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,r){this.customTarget=[e,t,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){let t=Math.PI/180,r=Math.PI*.48;e.minTheta!==void 0&&(this.minTheta=e.minTheta*t),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*t),e.minPhi!==void 0&&(this.minPhi=Math.max(-r,e.minPhi*t)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(r,e.maxPhi*t)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){let e=180/Math.PI;return{minTheta:isFinite(this.minTheta)?this.minTheta*e:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*e:void 0,minPhi:this.minPhi*e,maxPhi:this.maxPhi*e,minDistance:this.minDistanceLimit??void 0,maxDistance:this.maxDistanceLimit??void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.bounds?.radius;return Math.max(this.minDistanceLimit??(t?t*.5:.1),Math.min(this.maxDistanceLimit??(t?t*8:100),e))}setCamera(e,t,r,i){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(e,t,r,i){e!==void 0&&(this.initialTheta=this.targetTheta=this.currTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.initialPhi=this.targetPhi=this.currPhi=this.clampPhi(t*Math.PI/180));let n=r!==void 0&&r>0?r:i!==void 0&&i>0?this.bounds.radius*2.5/i:null;this.customDistance=n!==null,this.initialDistance=this.targetDistance=this.currDistance=this.clampDistance(n??(this.distanceMode==="absolute"?3:this.bounds.radius*2.5)),this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.targetDistance=this.clampDistance(this.initialDistance??this.bounds.radius*2.5),this.customTarget=this.initialCustomTarget?[...this.initialCustomTarget]:null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let r=lt();ft(r,this.projMatrix,this.viewMatrix);let i=(C,_,P=1)=>[C[0]*_[0]+C[4]*_[1]+C[8]*_[2]+C[12]*P,C[1]*_[0]+C[5]*_[1]+C[9]*_[2]+C[13]*P,C[2]*_[0]+C[6]*_[1]+C[10]*_[2]+C[14]*P,C[3]*_[0]+C[7]*_[1]+C[11]*_[2]+C[15]*P],n=this.modelRootMatrix,[a,s,o]=n?i(n,e):e,[l,c,f]=t?n?i(n,t,0):t:[0,0,0],[m,h,p,g]=i(r,[a,s,o]);if(g<=1e-4)return{x:0,y:0,z:1,visible:!1};let x=m/g,v=h/g,y=p/g,A=this.canvas.getBoundingClientRect(),b=A.width||this.canvas.clientWidth||this.canvas.width||300,w=A.height||this.canvas.clientHeight||this.canvas.height||150,S=(x*.5+.5)*b,E=(-v*.5+.5)*w,N=x>=-1.1&&x<=1.1&&v>=-1.1&&v<=1.1&&y>=-1&&y<=1;if(N&&t){let[C,_,P]=Cn(this),R=[a-C,s-_,o-P];l*R[0]+c*R[1]+f*R[2]>.05&&(N=!1)}return{x:S,y:E,z:y,visible:N}}setSelectedMesh(e){this.setSelectedMeshes([e])}setSelectedMeshes(e){this.selectedMeshNames=new Set(e.filter(Boolean))}getSelectedMesh(){return[...this.selectedMeshNames][0]||""}setupEvents(){let e=this.canvas,t=va;this.boundContextMenu=r=>{r.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=r=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=t(),this.lastPointerX=r.clientX,this.lastPointerY=r.clientY,this.totalDragDist=0,this.activePointers.set(r.pointerId,{x:r.clientX,y:r.clientY}),this.isPanning=r.button===2||r.shiftKey||this.activePointers.size===2,e.setPointerCapture(r.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=r=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=t();let i=this.activePointers.get(r.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},n=r.clientX-i.x,a=r.clientY-i.y;if(this.activePointers.set(r.pointerId,{x:r.clientX,y:r.clientY}),this.lastPointerX=r.clientX,this.lastPointerY=r.clientY,this.totalDragDist+=Math.hypot(n,a),this.isPanning||r.button===2||r.shiftKey||this.activePointers.size===2){let s=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],o=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],l=this.customTarget?[...this.customTarget]:[...this.bounds.center],c=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;l[0]+=(-n*s[0]+a*o[0])*c,l[1]+=(-n*s[1]+a*o[1])*c,l[2]+=(-n*s[2]+a*o[2])*c,this.customTarget=l}else this.targetTheta=this.clampTheta(this.targetTheta-n*.008),this.targetPhi=this.clampPhi(this.targetPhi+a*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=r=>{this.lastInteractionTime=t(),this.activePointers.delete(r.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(r.pointerId)}catch{}if(this.totalDragDist<5&&r.button===0){let i=e.getBoundingClientRect(),n=Math.floor((r.clientX-i.left)*(e.width/Math.max(i.width,1))),a=Math.floor((r.clientY-i.top)*(e.height/Math.max(i.height,1)));this.performMeshPick(n,a,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=r=>{if(!this.interactive)return;r.preventDefault(),this.lastInteractionTime=t();let i=Math.exp(r.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*i)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=r=>{let i=r.detail||{};i.reset?this.resetCamera():this.setCamera(i.theta,i.phi,i.distance,i.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=r=>{if(this.interactive){switch(r.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=t(),r.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(r,i,n)=>{this[n]&&(r.removeEventListener(i,this[n]),this[n]=null)},t=this.canvas;for(let[r,i]of[["webglcontextlost","boundContextLost"],["webglcontextrestored","boundContextRestored"],["contextmenu","boundContextMenu"],["pointerdown","boundPointerDown"],["pointermove","boundPointerMove"],["pointerup","boundPointerUp"],["wheel","boundWheel"],["keydown","boundKeyDown"]])e(t,r,i);e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),n=r.width||300,a=r.height||300,s=i.width>0?Math.floor((e-i.left)*(n/i.width)):Math.floor(e),o=i.height>0?Math.floor((t-i.top)*(a/i.height)):Math.floor(t);return this.performMeshPick(s,o,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,n=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,n);let s=lt();ft(s,this.projMatrix,this.viewMatrix);let o=[],l=Math.max(0,Math.min(n-1,e)),c=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==n||this.pickFboHeight!==a)&&this.resizePickingFbo(n,a),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,n,a),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16640),i.useProgram(this.pickProg);for(let S=0;S<this.meshes.length;S++){let E=this.meshes[S];if(E.visible===!1||E.isPluginMesh)continue;let N=S+1,C=(N&255)/255,_=(N>>8&255)/255,P=(N>>16&255)/255;i.uniform4f(this.uPick.uColorId,C,_,P,1),ft(this.modelMatrix,this.modelRootMatrix,E.transform);let R=E.instanceMatrices;if(R&&R.length>=16){let I=R.length>>4,F=lt();for(let V of E.primitives){i.bindVertexArray(V.vao);for(let Y=0;Y<I;Y++)ft(F,this.modelMatrix,R.subarray(Y*16,Y*16+16)),ft(this.mvpMatrix,s,F),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),xa(i,V)}}else{ft(this.mvpMatrix,s,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let I of E.primitives)i.bindVertexArray(I.vao),xa(i,I)}}let b=new Uint8Array(4);i.readPixels(l,c,1,1,6408,5121,b),i.bindFramebuffer(36160,null);let w=b[0]+(b[1]<<8)+(b[2]<<16);w>0&&w<=this.meshes.length&&(o=[this.meshes[w-1]])}o.length===0&&(o=this.meshes.filter(b=>b.visible!==!1));let f=null,m=1/0,h=[0,0,0],p=[0,1,0],[g,x,v]=Cn(this),y=lt();for(let b of o){ft(y,this.modelRootMatrix,b.transform);let w=b.instanceMatrices,S=w&&w.length>=16?w.length>>4:1;for(let E=0;E<S;E++){w&&w.length>=16?ft(this.modelMatrix,y,w.subarray(E*16,E*16+16)):this.modelMatrix.set(y),ft(this.mvpMatrix,s,this.modelMatrix);let N=lt();if(!co(N,this.mvpMatrix))continue;let C=(l+.5)/n*2-1,_=(c+.5)/a*2-1,P=[0,0,0],R=[0,0,0];Zc(P,C,_,-1,N),Zc(R,C,_,1,N);let I=R[0]-P[0],F=R[1]-P[1],V=R[2]-P[2],Y=Math.hypot(I,F,V)||1,J=I/Y,re=F/Y,Q=V/Y,ee={distance:1/0,point:[0,0,0],normal:[0,1,0]};for(let k of b.primitives){if(!k.positions)continue;let G=k.positions,q=k.indices,H=Math.floor(q?q.length/3:G.length/9);for(let te=0;te<H;te++){let Z=(q?q[te*3]:te*3)*3,ae=(q?q[te*3+1]:te*3+1)*3,ie=(q?q[te*3+2]:te*3+2)*3;W0(P[0],P[1],P[2],J,re,Q,G[Z],G[Z+1],G[Z+2],G[ae],G[ae+1],G[ae+2],G[ie],G[ie+1],G[ie+2],ee,1e-4)}}if(isFinite(ee.distance)){let k=ee.point[0],G=ee.point[1],q=ee.point[2],H=this.modelMatrix,te=H[0]*k+H[4]*G+H[8]*q+H[12],Z=H[1]*k+H[5]*G+H[9]*q+H[13],ae=H[2]*k+H[6]*G+H[10]*q+H[14],ie=te-g,de=Z-x,me=ae-v,Se=Math.hypot(ie,de,me);if(Se<m){rr(this.normalMatrix,this.modelMatrix);let ke=this.normalMatrix,_e=ee.normal[0],Le=ee.normal[1],ne=ee.normal[2],Re=ke[0]*_e+ke[3]*Le+ke[6]*ne,W=ke[1]*_e+ke[4]*Le+ke[7]*ne,D=ke[2]*_e+ke[5]*Le+ke[8]*ne,z=Math.hypot(Re,W,D)||1;Re/=z,W/=z,D/=z,Re*ie+W*de+D*me>0&&(Re=-Re,W=-W,D=-D);let O=X=>Math.round(X*1e3)/1e3;f=b,m=O(Se),h=[O(te),O(Z),O(ae)],p=[O(Re),O(W),O(D)]}}}}if(!f)return null;let A={meshIndex:this.meshes.indexOf(f),meshName:f.name,nodeIndex:f.nodeIndex,distance:m,hitPoint:h,normal:p,screenX:e,screenY:t};if(r){for(let b of Lt)b.onMeshSelect?.(this,A);this.opts.onMeshClick&&this.opts.onMeshClick(A),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:A}))}return A}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,n=i?e-r:e,a=i?Math.max(1,t-r):r,s=(n+.5)/a*2-1;return Math.floor((s*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);uo(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;_n(this.viewMatrix,Cn(this),r,[0,1,0]),ft(this.mvpMatrix,this.projMatrix,this.viewMatrix),rr(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let r of Lt)r.onXRSessionEnd?.(this);if(this.lastTime=va(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of Lt)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=va();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),[r,,i]=this.bounds.center;this.modelRootMatrix.set([e,0,-t,0,0,1,0,0,t,0,e,0,r-(e*r+t*i),0,i-(-t*r+e*i),1])}setVisible(e){this.isVisible=e}update(e){for(let a of Lt)a.onUpdate?.(this,e);let t=va();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let a of Lt)a.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),n=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(n-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=n;let a={theta:r,phi:i,zoom:n,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(a),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:a}))}}renderXRView(e,t,r,i,n=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let s=e?.transform?.inverse?.matrix||this.viewMatrix,o=e?.projectionMatrix||this.projMatrix,l=e?.transform?.position,c=l?[l.x,l.y,l.z]:[0,1.6,0];t&&this.modelRootMatrix.set(t),this.render({viewMatrix:s,projMatrix:o,eyePos:c,viewport:i,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:n})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let E=Math.max(2,this.canvas.width||2),N=Math.max(1,this.canvas.height||1),C=Math.max(1,Math.floor(E*.5)),_=Math.max(1,E-C),P=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),R=this.customTarget||this.bounds.center,[I,F,V]=Cn(this),Y=Math.cos(this.currTheta),J=-Math.sin(this.currTheta),re=.032;for(let Q of[-1,1]){let ee=lt(),k=lt(),G=Q<0?C:_,q=[I+Q*Y*re,F,V+Q*J*re];uo(ee,this.fov,G/N,.1,P),_n(k,q,[R[0]+Q*Y*re*.25,R[1],R[2]+Q*J*re*.25],[0,1,0]),this.render({viewMatrix:k,projMatrix:ee,eyePos:q,viewport:[Q<0?0:C,0,G,N],eye:Q<0?"left":"right",clear:Q<0,isAR:!1})}this.gl.viewport(0,0,E,N);return}let t=this.gl,[r,i,n,a]=e?.viewport||[0,0,this.canvas.width,this.canvas.height];if(t.viewport(r,i,n,a),t.enable(2929),!e||e.clear!==!1){let E=e?.isAR?[0,0,0,0]:this.clearColor;t.clearColor(E[0],E[1],E[2],E[3]),t.clear(16640)}let s=lt(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o;let l=e?.projMatrix??this.projMatrix;ft(s,l,o);let c=We(),f=c.xrDepthShader,m=op(this.toneMapping),[h,p,g]=e?e.eyePos:Cn(this);for(let E of Lt)E.onBeforeDrawScene?.(this,t,s,[h,p,g],m);let x=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&x===0){c.gpuSceneAccelerator?.hideLayer?.(this);return}let v=e?.eye||"none",y=!e||e.clear!==!1;if(!this.xrSessionActive&&c.gpuSceneAccelerator?.renderScene(this,s,l,o,[h,p,g],m,[r,i,n,a],v,y,!!e?.isAR)){y&&!this.skyboxTexture&&(t.clearColor(0,0,0,0),t.clear(16384));for(let E of Lt)E.name.includes("webgpu")&&E.onAfterRender?.(t,this,s,v,[r,i,n,a],l);return}let A=!1,b=x>0?[...this.backdropMeshes,...this.meshes]:this.meshes,w=(E,N,C,_)=>{N?(t.activeTexture(33984+E),t.bindTexture(3553,N),t.uniform1i(C,E),t.uniform1i(_,1)):t.uniform1i(_,0)},S=E=>{for(let N=0;N<b.length;N++){let C=b[N];if(C.visible===!1)continue;let _=this.selectedMeshNames.has(C.name);if(N<x||C.worldSpace===!0||C.name==="__xr_reticle__")this.modelMatrix.set(C.transform);else{ft(this.modelMatrix,this.modelRootMatrix,C.transform);let Y=!e&&(C.extras?.xr?.billboard??C.userData?.xr?.billboard);if(Y){let J=this.modelMatrix,re=Math.hypot(J[0],J[1],J[2])||1,Q=Math.hypot(J[4],J[5],J[6])||1,ee=Math.hypot(J[8],J[9],J[10])||1,k=Y==="y"||Y==="cylindrical"||Y==="capsule",G=h-J[12],q=g-J[14],H=Math.hypot(G,q),te=H>1e-5?G/H:0,Z=H>1e-5?q/H:1;J.set(k?[Z*re,0,-te*re,0,0,Q,0,0,te*ee,0,Z*ee]:[o[0]*re,o[4]*re,o[8]*re,0,o[1]*Q,o[5]*Q,o[9]*Q,0,o[2]*ee,o[6]*ee,o[10]*ee])}}ft(this.mvpMatrix,s,this.modelMatrix),rr(C.normalMatrix,this.modelMatrix);let P=C.extras?.xr?.stereo||C.userData?.xr?.stereo,R=0,I=0,F=1,V=1;P==="sbs"?(F=.5,R=v==="right"?.5:0):P==="ou"&&(V=.5,I=v==="right"?.5:0);for(let Y of C.primitives){let J=!!Y.isTransmissive;if(!E&&J){A=!0;continue}if(E&&!J)continue;let re=Y.customProgram||this.renderProg,Q=Y.customUniforms||this.uRender;t.useProgram(re),t.vertexAttrib3f(3,0,0,0),Q.uInstanced&&t.uniform1i(Q.uInstanced,0),t.uniform1i(Q.uToneMapping,m),t.uniform1f(Q.uEnvIntensity,this.envIntensity),Q.uExposure&&t.uniform1f(Q.uExposure,this.exposure),t.uniform3f(Q.uCameraPos,h,p,g),t.uniform1f(Q.uEmissive,_?1:0),t.uniformMatrix4fv(Q.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(Q.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(Q.uNormalMatrix,!1,C.normalMatrix),Q.uUvTransform&&t.uniform4f(Q.uUvTransform,R,I,F,V),Q.uViewportSize&&t.uniform2f(Q.uViewportSize,Math.max(1,n),Math.max(1,a)),f?.bind(t,Q,this.xrDepthState,o,[r,i,Math.max(1,n),Math.max(1,a)]),c.shadowMapShader?.bind(t,Q,this,C),w(4,this.environmentTexture,Q.uEnvironmentMap,Q.uHasEnvironmentMap),this.bindLights(Q),Q.uSectionEnabled&&t.uniform1i(Q.uSectionEnabled,0);for(let k of Lt)k.onBeforeDrawPrimitive?.(t,re,Y,C,this.worldMatrices||[],this.gltf);t.uniform4fv(Q.uBaseColor,Y.baseColor),t.uniform1f(Q.uMetallic,Y.metallic),t.uniform1f(Q.uRoughness,Y.roughness),Q.uClearcoat&&t.uniform2f(Q.uClearcoat,Y.clearcoat??0,Y.clearcoatRoughness??.04),w(0,Y.texture,Q.uBaseColorTexture,Q.uHasTexture),w(1,Y.metallicRoughnessTexture,Q.uMetallicRoughnessTexture,Q.uHasMetallicRoughnessTexture),w(2,Y.normalTexture,Q.uNormalTexture,Q.uHasNormalTexture),Y.normalTexture&&t.uniform1f(Q.uNormalScale,Y.normalScale),w(3,Y.occlusionTexture,Q.uOcclusionTexture,Q.uHasOcclusionTexture),Y.occlusionTexture&&t.uniform1f(Q.uOcclusionStrength,Y.occlusionStrength),t.uniform3fv(Q.uEmissiveFactor,Y.emissiveFactor),w(8,Y.emissiveTexture,Q.uEmissiveTexture,Q.uHasEmissiveTexture),t.bindVertexArray(Y.vao);let ee=C.instanceMatrices;if(Y.instanceCount!==void 0)t.drawElementsInstanced(4,Y.indexCount,Y.indexType,0,Y.instanceCount);else if(ee&&ee.length>=16&&Y.instanced&&Q.uInstanced&&Q.uViewProj){let k=ee.length>>4;t.uniform1i(Q.uInstanced,1),t.uniformMatrix4fv(Q.uViewProj,!1,s),Y.indices?t.drawElementsInstanced(4,Y.indexCount,Y.indexType,0,k):t.drawArraysInstanced(4,0,Y.indexCount,k),t.uniform1i(Q.uInstanced,0)}else if(ee&&ee.length>=16){let k=ee.length>>4,G=C.instanceColors,q=lt(),H=new Float32Array(9);for(let te=0;te<k;te++){if(ft(q,this.modelMatrix,ee.subarray(te*16,te*16+16)),ft(this.mvpMatrix,s,q),rr(H,q),t.uniformMatrix4fv(Q.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(Q.uModel,!1,q),t.uniformMatrix3fv(Q.uNormalMatrix,!1,H),G){let Z=Y.baseColor,ae=te*3;t.uniform4fv(Q.uBaseColor,[Z[0]*G[ae],Z[1]*G[ae+1],Z[2]*G[ae+2],Z[3]])}xa(t,Y)}}else xa(t,Y)}}};if(S(!1),A){for(let E of Lt)E.onBeforeTransmissivePass?.(t,this);S(!0)}for(let E of Lt)E.onAfterRender?.(t,this,s,v,[r,i,n,a],l)}disposeMeshListGpuResources(e,t){gh(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of Lt)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};ir.registerPlugin=Rt,ir.getRegisteredPlugins=Wc;function vp(e){return e+3&-4}var Ye=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function No(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function bh(e,t,r){let i=Math.hypot(e,t,r)||1,n=e/i,a=t/i,s=-(r/i);if(s<-.999999)return[0,1,0,0];let o=Math.sqrt((1+s)*2);return[a/o,-n/o,0,o*.5]}function xh(e,t=0){let[r,i,n,,a,s,o,,l,c,f,,m,h,p]=Array.from({length:15},(ee,k)=>Ye(e[t+k],k%5===0?1:0)),g=Math.hypot(r,i,n),x=Math.hypot(a,s,o),v=Math.hypot(l,c,f);r*(s*f-c*o)-a*(i*f-c*n)+l*(i*o-s*n)<0&&(g=-g);let y=Math.abs(g)>1e-8?1/g:0,A=Math.abs(x)>1e-8?1/x:0,b=Math.abs(v)>1e-8?1/v:0,w=r*y,S=i*y,E=n*y,N=a*A,C=s*A,_=o*A,P=l*b,R=c*b,I=f*b,F=w+C+I,V=0,Y=0,J=0,re=1;if(F>0){let ee=.5/Math.sqrt(F+1);re=.25/ee,V=(_-R)*ee,Y=(P-E)*ee,J=(S-N)*ee}else if(w>C&&w>I){let ee=2*Math.sqrt(Math.max(0,1+w-C-I));ee>1e-8&&(re=(_-R)/ee,V=.25*ee,Y=(N+S)/ee,J=(P+E)/ee)}else if(C>I){let ee=2*Math.sqrt(Math.max(0,1+C-w-I));ee>1e-8&&(re=(P-E)/ee,V=(N+S)/ee,Y=.25*ee,J=(_+R)/ee)}else{let ee=2*Math.sqrt(Math.max(0,1+I-w-C));ee>1e-8&&(re=(S-N)/ee,V=(P+E)/ee,Y=(_+R)/ee,J=.25*ee)}let Q=Math.hypot(V,Y,J,re);return Q>1e-8&&Number.isFinite(Q)?(V/=Q,Y/=Q,J/=Q,re/=Q):(V=0,Y=0,J=0,re=1),{t:[m,h,p],r:[V,Y,J,re],s:[g,x,v]}}function wp(e){let t={};return e.grab&&(t.interactable={mode:typeof e.grab=="string"?e.grab:"2-hand"},t.movable={scaleInZ:!!e.scale,minScale:typeof e.scale=="object"?e.scale.min??.1:.1,maxScale:typeof e.scale=="object"?e.scale.max??10:10}),e.billboard&&(t.billboard={mode:typeof e.billboard=="string"?e.billboard:"capsule"}),e.follow&&(t.follow={target:typeof e.follow=="object"?e.follow.mode??"head":e.follow}),e.anchor&&(t.anchor={plane:e.anchor}),e.physics&&e.physics!=="none"&&(t.rigidbody={type:e.physics}),t}var Lr=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function vh(e){let t=e?.audioEmitter??e?.spatialAudio??(typeof e?.audio=="object"&&e.audio&&("preset"in e.audio||"distanceModel"in e.audio||"coneInnerAngle"in e.audio||"maxDistance"in e.audio||"volume"in e.audio)?e.audio:typeof e?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(e.audio)?{preset:e.audio}:void 0);if(!t||typeof t=="object"&&t.enabled===!1)return null;let r=typeof t=="string"?{preset:t}:t,i=typeof r.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(r.src)?r.src:void 0,n=typeof r.preset=="string"?r.preset:void 0;return!i&&!n?null:{ae:r,src:i,preset:n,volume:Lr(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function Mp(e){let t=e?.material,r=t?._presetMaps?.map;if(!r||r!==t.map)return null;let i=/^ai_([0-9a-f]{16})_albedo$/.exec(String(r.name??""));return i?i[1]:null}function Vi(e,t){return wh(e,t)[0]}function wh(e,t){e.updateMatrixWorld(!0);let r=[],i=0,n=[],a=[],s=[],o=[],l=new Set,c=[],f=[],m=new Map,h=[],p=[],g=[],x=new Map,v=[],y=[],A=[],b=!1;function w(k){let G=m.get(k);if(G!==void 0)return G;G=f.length,m.set(k,G);let q=k,H=q.color?.r??1,te=q.color?.g??1,Z=q.color?.b??1,ae=q.opacity??1,ie={baseColorFactor:[H,te,Z,ae],metallicFactor:q.metalness??0,roughnessFactor:q.roughness??.5},de={},me=he=>{if(!he)return;let Ne=(typeof he=="string"?he:typeof he.source=="string"?he.source:typeof he.image=="string"?he.image:"").trim();if(!Ne||/[\x00-\x1f\x7f\\]|\.\./.test(Ne)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(Ne)||!Ne.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(Ne)))return;let ge=x.get(Ne);if(ge===void 0){let Ae=h.length;h.push({uri:Ne}),p.length===0&&p.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),ge=g.length,g.push({sampler:0,source:Ae}),x.set(Ne,ge)}return{index:ge}},Se=q._packPbr?.(),ke=me(q.map);ke&&(ie.baseColorTexture=ke);let _e=me(Se?.mrUri||q.roughnessMap||q.metalnessMap);_e&&(ie.metallicRoughnessTexture=_e);let Le=q.map?.avgColor;Array.isArray(Le)&&Le.length>=3&&(de.avgColor=[Le[0],Le[1],Le[2]]);let ne=me(Se?.normUri||q.normalMap),Re=q.normalScale,W=Se?.normUri?Se.normScale??1:typeof Re=="number"?Math.max(0,Ye(Re,1)):Re?Math.max(0,(Ye(Re.x,1)+Ye(Re.y,1))*.5):1;ne&&W!==1&&(ne.scale=W);let D=me(q.emissiveMap),z=me(q.aoMap),O=Math.max(0,Math.min(1,Ye(q.aoMapIntensity,1)));z&&O!==1&&(z.strength=O);let X={name:q.name||"",pbrMetallicRoughness:ie,doubleSided:q.side===2||!!q.doubleSided,...ae<1||q.transparent?{alphaMode:"BLEND"}:{},...ne?{normalTexture:ne}:{},...D?{emissiveTexture:D}:{},...z?{occlusionTexture:z}:{},...Object.keys(de).length>0?{extras:de}:{}},se=Math.max(0,Ye(q.emissiveIntensity,1)),ce=q.emissive&&(q.emissive.r>0||q.emissive.g>0||q.emissive.b>0);(ce||D&&!q._em&&se>0)&&(X.emissiveFactor=ce?[q.emissive.r*se,q.emissive.g*se,q.emissive.b*se]:[se,se,se]);let pe={};q.clearcoat&&q.clearcoat>0&&(pe.KHR_materials_clearcoat={clearcoatFactor:q.clearcoat,clearcoatRoughnessFactor:q.clearcoatRoughness||0}),q.sheen&&q.sheen>0&&(pe.KHR_materials_sheen={sheenColorFactor:q.sheenColor?[q.sheenColor.r,q.sheenColor.g,q.sheenColor.b]:[1,1,1],sheenRoughnessFactor:q.sheenRoughness||0}),q.transmission&&q.transmission>0&&(pe.KHR_materials_transmission={transmissionFactor:q.transmission}),q.thickness&&q.thickness>0&&(pe.KHR_materials_volume={thicknessFactor:q.thickness,attenuationDistance:q.attenuationDistance??1/0,attenuationColor:q.attenuationColor?[q.attenuationColor.r,q.attenuationColor.g,q.attenuationColor.b]:[1,1,1]}),q.ior!==void 0&&q.ior!==1.5&&(pe.KHR_materials_ior={ior:q.ior}),q.dispersion&&q.dispersion>0&&(pe.KHR_materials_dispersion={dispersion:q.dispersion}),q.iridescence&&q.iridescence>0&&(pe.KHR_materials_iridescence={iridescenceFactor:q.iridescence,iridescenceIor:q.iridescenceIOR??1.3});let xe=q._serializeTslGraph?.();return xe&&(pe.GOOGLE_material_tsl=xe,l.add("GOOGLE_material_tsl")),Object.keys(pe).length>0&&(X.extensions=pe),f.push(X),G}function S(k,G){let q=new Uint8Array(k.buffer,k.byteOffset,k.byteLength),H=vp(q.byteLength),te=new Uint8Array(H);te.set(q),r.push(te);let Z=n.length;return n.push({buffer:0,byteOffset:i,byteLength:q.byteLength,target:G}),i+=H,Z}function E(k,G,q,H,te,Z,ae){let ie=S(k,q),de=a.length,me={bufferView:ie,byteOffset:0,componentType:H,count:te,type:G};return Z&&(me.min=Z),ae&&(me.max=ae),a.push(me),de}let N=[],C=[],_=new Set([e]),P=[];if(Array.isArray(e.children))for(let k=e.children.length-1;k>=0;k--)P.push({obj:e.children[k],parentKids:C});for(;P.length>0;){let{obj:k,parentKids:G}=P.pop();if(!k||typeof k!="object"||_.has(k))continue;_.add(k),k._bakeAuthorGeometry?.(),We().materializeDeclarativeGeometry?.(k);let q=!!(k.userData&&(k.userData.xr&&typeof k.userData.xr=="object"&&Object.keys(k.userData.xr).length>0||k.userData.interactivity&&typeof k.userData.interactivity=="object"&&Object.keys(k.userData.interactivity).length>0)),H={name:k.name||(q?`Node_${o.length}`:"")},te=Ye(k.position?.x,0),Z=Ye(k.position?.y,0),ae=Ye(k.position?.z,0),ie=Ye(k.quaternion?.x,0),de=Ye(k.quaternion?.y,0),me=Ye(k.quaternion?.z,0),Se=Ye(k.quaternion?.w,1),ke=Ye(k.scale?.x,1),_e=Ye(k.scale?.y,1),Le=Ye(k.scale?.z,1);if((te||Z||ae)&&(H.translation=[te,Z,ae]),(ie||de||me||Se!==1)&&(H.rotation=[ie,de,me,Se]),(ke!==1||_e!==1||Le!==1)&&(H.scale=[ke,_e,Le]),k.visible===!1&&(H.extensions={...H.extensions||{},KHR_node_visibility:{visible:!1}},l.add("KHR_node_visibility")),k.userData&&Object.keys(k.userData).length>0&&(H.extras=JSON.parse(JSON.stringify(k.userData,(z,O)=>{if(!(z==="__proto__"||z==="prototype"||z==="constructor"))return typeof O=="function"?void 0:O})),k.userData.xr)){let z=wp(k.userData.xr);H.extensions={...H.extensions||{},MOZ_hubs_components:z,ANDROID_xr_scenecore:z},We().xrTraitSerializer?.gltfNode(H,k.userData.xr);let O=Mp(k),X=H.extras?.xr?.material;O&&X&&typeof X=="object"&&!Array.isArray(X)&&(X.textureKey=O),l.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}let ne=k,Re=ne.isLight||ne.color&&ne.intensity!==void 0;if(!Re&&(ne._castShdSet||ne._recvShdSet||k.castShadow||k.receiveShadow)&&(H.extras={...H.extras||{},shadow:{cast:!!k.castShadow,receive:ne._recvShdSet?!!k.receiveShadow:!!(k.receiveShadow||k.castShadow)}}),Re){let z=ne.matrixWorld?.elements,O=Ye(z?z[12]:k.position?.x,0),X=Ye(z?z[13]:k.position?.y,0),se=Ye(z?z[14]:k.position?.z,0),ce=ne.target,pe=ce?.parent?ce?.matrixWorld?.elements:void 0,xe=Ye(pe?pe[12]:ce?.position?.x,0),he=Ye(pe?pe[13]:ce?.position?.y,0),Ne=Ye(pe?pe[14]:ce?.position?.z,0),ge=xe-O,Ae=he-X,Ee=Ne-se,$e=Math.hypot(ge,Ae,Ee),De=Math.max(.01,Math.min(Math.PI/2,Ye(ne.angle,Math.PI/3))),Be=Math.max(0,Math.min(1,Ye(ne.penumbra,0))),Fe=Math.max(0,De*(1-Be)),Ve=Math.max(0,Ye(ne.distance,0)),qe=k.type==="directional"||k.type==="spot"||k.type==="point",je;if(k.castShadow&&qe){let Je=ne.shadow,Dt=Math.max(256,Math.min(2048,Math.round(Ye(Je?.mapSize?.x??Je?.mapSize?.width,1024))));je={cast:!0,mapSize:Dt<=384?256:Dt<=768?512:Dt<=1536?1024:2048,bias:Lr(Je?.bias,-.05,.05,-5e-4),normalBias:Lr(Je?.normalBias,0,.2,.015),radius:Lr(Je?.radius,0,8,1.5)},b=!0}let ut=O-xe,it=X-he,nt=se-Ne,ct=Math.hypot(ut,it,nt);y.push({type:k.type,color:[k.color.r,k.color.g,k.color.b],intensity:k.intensity,position:k.type==="directional"?[ut,it,nt]:[O,X,se],...k.type==="directional"?{direction:ct>1e-6?[ut/ct,it/ct,nt/ct]:[0,1,0]}:k.type==="spot"?{direction:$e>1e-6?[ge/$e,Ae/$e,Ee/$e]:[0,-1,0],outerConeAngle:De,innerConeAngle:Fe,range:Ve}:k.type==="point"?{range:Ve}:k.type==="hemisphere"&&ne.groundColor?{groundColor:[ne.groundColor.r,ne.groundColor.g,ne.groundColor.b]}:{},...je?{shadow:je}:{}}),qe&&N.push({node:H,obj:k,px:O,py:X,pz:se,tx:xe,ty:he,tz:Ne,dx:ge,dy:Ae,dz:Ee,dLen:$e,outerAngle:De,innerAngle:Fe,range:Ve,shadowSpec:je})}if(k.geometry){let z=k.geometry,O=z.attributes.position;if(O&&O.count>0){let X=[1/0,1/0,1/0],se=[-1/0,-1/0,-1/0];for(let ge=0;ge<O.count;ge++){let Ae=O.getX(ge),Ee=O.getY(ge),$e=O.getZ(ge);Ae<X[0]&&(X[0]=Ae),Ae>se[0]&&(se[0]=Ae),Ee<X[1]&&(X[1]=Ee),Ee>se[1]&&(se[1]=Ee),$e<X[2]&&(X[2]=$e),$e>se[2]&&(se[2]=$e)}let ce={attributes:{POSITION:E(O.array,"VEC3",34962,5126,O.count,X,se)}};if(z.attributes.normal&&(ce.attributes.NORMAL=E(z.attributes.normal.array,"VEC3",34962,5126,z.attributes.normal.count)),z.attributes.uv&&(ce.attributes.TEXCOORD_0=E(z.attributes.uv.array,"VEC2",34962,5126,z.attributes.uv.count)),z.index){let ge=z.index.array instanceof Uint32Array;ce.indices=E(z.index.array,"SCALAR",34963,ge?5125:5123,z.index.count)}let pe=Array.isArray(k.material)?k.material[0]:k.material;pe&&(ce.material=w(pe));let xe=k.userData?.variants;if(xe&&typeof xe=="object"){let ge=new Map;for(let Ae of Object.keys(xe)){if(!Ae||Ae==="__proto__"||Ae==="constructor"||Ae==="prototype")continue;let Ee=xe[Ae];if(!Ee||typeof Ee!="object")continue;let $e=v.indexOf(Ae);if($e===-1&&v.length<256&&($e=v.length,v.push(Ae)),$e===-1)continue;let De=w(Ee),Be=ge.get(De);Be||(Be=[],ge.set(De,Be)),Be.push($e)}if(ge.size>0){let Ae=[];for(let[Ee,$e]of ge.entries())Ae.push({material:Ee,variants:$e});ce.extensions={...ce.extensions||{},KHR_materials_variants:{mappings:Ae}},l.add("KHR_materials_variants")}}let he=k;if(he.isInstancedMesh&&typeof he.count=="number"&&he.count>0&&he.instanceMatrix?.array){let ge=Math.min(1e4,Math.floor(he.count)),Ae=he.instanceMatrix.array,Ee=new Float32Array(ge*3),$e=new Float32Array(ge*4),De=new Float32Array(ge*3);for(let Fe=0;Fe<ge;Fe++){let{t:Ve,r:qe,s:je}=xh(Ae,Fe*16);Ee[Fe*3]=Ve[0],Ee[Fe*3+1]=Ve[1],Ee[Fe*3+2]=Ve[2],$e[Fe*4]=qe[0],$e[Fe*4+1]=qe[1],$e[Fe*4+2]=qe[2],$e[Fe*4+3]=qe[3],De[Fe*3]=je[0],De[Fe*3+1]=je[1],De[Fe*3+2]=je[2]}let Be={TRANSLATION:E(Ee,"VEC3",0,5126,ge),ROTATION:E($e,"VEC4",0,5126,ge),SCALE:E(De,"VEC3",0,5126,ge)};if(he.instanceColor?.array&&he.instanceColor.array.length>=ge*3){let Fe=new Float32Array(he.instanceColor.array.subarray(0,ge*3));Be._COLOR_0=E(Fe,"VEC3",0,5126,ge)}H.extensions={...H.extensions||{},EXT_mesh_gpu_instancing:{attributes:Be}},l.add("EXT_mesh_gpu_instancing")}let Ne=s.length;s.push({primitives:[ce],name:k.name,...H.extras?{extras:H.extras}:{}}),H.mesh=Ne}}let W=o.length;o.push(H),c.push(k),G.push(W);let D=k.children;if(Array.isArray(D)&&D.length>0){let z=[];H.children=z;for(let O=D.length-1;O>=0;O--)P.push({obj:D[O],parentKids:z})}}if(b)for(let k of N){let G=A.length;if(A.push({name:k.obj.name||`Light_${G}`,type:k.obj.type,color:[k.obj.color.r,k.obj.color.g,k.obj.color.b],intensity:k.obj.intensity,...k.range>0&&(k.obj.type==="point"||k.obj.type==="spot")?{range:k.range}:{},...k.obj.type==="spot"?{spot:{innerConeAngle:k.innerAngle,outerConeAngle:k.outerAngle}}:{},...k.shadowSpec?{extras:{shadow:k.shadowSpec}}:{}}),k.node.extensions={...k.node.extensions||{},KHR_lights_punctual:{light:G}},l.add("KHR_lights_punctual"),k.obj.type==="directional"||k.obj.type==="spot"){let q=k.dLen>1e-6?k.dx/k.dLen:0,H=k.dLen>1e-6?k.dy/k.dLen:-1,te=k.dLen>1e-6?k.dz/k.dLen:0;k.node.rotation=bh(q,H,te),k.obj.type==="directional"&&(k.tx||k.ty||k.tz)&&(k.node.translation=[k.px-k.tx,k.py-k.ty,k.pz-k.tz])}}for(let k=0;k<o.length;k++){let G=o[k];G.children&&G.children.length===0?delete G.children:G.children&&G.children.length>0&&(G.extras?.xr?.lod||G.extensions?.ANDROID_xr_scenecore?.lod||c[k]?.isLOD)&&(G.extensions={...G.extensions||{},MSFT_lod:{ids:[...G.children]}},l.add("MSFT_lod"))}let R=t?.animateCallback||t?.animateFn||(typeof e.userData?.animate=="function"?e.userData.animate:typeof e.__animateFn=="function"?e.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),I=[];if(typeof R=="function"&&c.length>0){let k=t?.duration??4,G=t?.fps??15,q=Math.max(2,Math.round(k*G)+1),H=new Float32Array(q),te=c.map(_e=>[Ye(_e.position?.x,0),Ye(_e.position?.y,0),Ye(_e.position?.z,0),Ye(_e.quaternion?.x,0),Ye(_e.quaternion?.y,0),Ye(_e.quaternion?.z,0),Ye(_e.quaternion?.w,1),Ye(_e.scale?.x,1),Ye(_e.scale?.y,1),Ye(_e.scale?.z,1)]),Z=c.map(()=>new Float32Array(q*3)),ae=c.map(()=>new Float32Array(q*4)),ie=c.map(()=>new Float32Array(q*3));for(let _e=0;_e<q;_e++){let Le=_e/(q-1)*k;H[_e]=Le;try{R(Le)}catch{}for(let ne=0;ne<c.length;ne++){let Re=c[ne];Z[ne][_e*3]=Ye(Re.position?.x,0),Z[ne][_e*3+1]=Ye(Re.position?.y,0),Z[ne][_e*3+2]=Ye(Re.position?.z,0);let W=Ye(Re.quaternion?.x,0),D=Ye(Re.quaternion?.y,0),z=Ye(Re.quaternion?.z,0),O=Ye(Re.quaternion?.w,1),X=Math.hypot(W,D,z,O)||1;if(W/=X,D/=X,z/=X,O/=X,_e>0){let se=(_e-1)*4,ce=ae[ne];ce[se]*W+ce[se+1]*D+ce[se+2]*z+ce[se+3]*O<0&&(W=-W,D=-D,z=-z,O=-O)}ae[ne][_e*4]=W,ae[ne][_e*4+1]=D,ae[ne][_e*4+2]=z,ae[ne][_e*4+3]=O,ie[ne][_e*3]=Ye(Re.scale?.x,1),ie[ne][_e*3+1]=Ye(Re.scale?.y,1),ie[ne][_e*3+2]=Ye(Re.scale?.z,1)}}for(let _e=0;_e<c.length;_e++){let Le=c[_e],ne=te[_e];Le.position?.set(ne[0],ne[1],ne[2]),Le.quaternion?.set(ne[3],ne[4],ne[5],ne[6]),Le.scale?.set(ne[7],ne[8],ne[9])}e.updateMatrixWorld(!0);let de=null,me=()=>(de===null&&(de=E(H,"SCALAR",0,5126,q,[0],[k])),de),Se=[],ke=[];for(let _e=0;_e<c.length;_e++){let Le=te[_e],ne=(W,D,z)=>W.some((O,X)=>Math.abs(O-Le[z+X%D])>1e-4),Re=(W,D,z,O)=>{W&&ke.push({sampler:Se.push({input:me(),interpolation:"LINEAR",output:E(D,z,0,5126,q)})-1,target:{node:_e,path:O}})};Re(ne(Z[_e],3,0),Z[_e],"VEC3","translation"),Re(ne(ae[_e],4,3),ae[_e],"VEC4","rotation"),Re(ne(ie[_e],3,7),ie[_e],"VEC3","scale")}ke.length>0&&I.push({name:"ProceduralLoop",samplers:Se,channels:ke})}let F=H0(o,s,e.userData),V=[],Y=[],J=[];for(let k=0;k<o.length;k++){let G=o[k],q=vh(G.extras?.xr);if(!q)continue;let{ae:H,src:te,preset:Z,volume:ae,loop:ie,isGlobal:de}=q,me=G.name||`Node_${k}`,Se=Y.length;Y.push({name:`${me}_source`,gain:ae,loop:ie,autoPlay:typeof H.autoplay=="boolean"?H.autoplay:!0,...te!==void 0?{audio:V.push({uri:te})-1}:{},...Z?{extras:{preset:Z,pitch:Lr(H.pitch,.25,4,1)}}:{}});let ke=J.length,_e=Lr(H.refDistance,.05,100,1),Le=Lr(H.coneInnerAngle,0,360,360),ne=Lr(H.coneOuterAngle,Le,360,360);J.push({name:`${me}_emitter`,type:de?"global":"positional",gain:ae,sources:[Se],...de?{}:{positional:{distanceModel:H.distanceModel==="linear"||H.distanceModel==="exponential"?H.distanceModel:"inverse",refDistance:_e,maxDistance:Lr(H.maxDistance,_e,500,Math.max(_e,25)),rolloffFactor:Lr(H.rolloffFactor,0,10,1),coneInnerAngle:+(Le*Math.PI/180).toFixed(6),coneOuterAngle:+(ne*Math.PI/180).toFixed(6),coneOuterGain:Lr(H.coneOuterGain,0,1,0)}}}),G.extensions={...G.extensions||{},KHR_audio_emitter:{emitter:ke}},l.add("KHR_audio_emitter")}let re={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity,...y.length>0?{lights:y}:{}}},scenes:[{nodes:C}],scene:0,nodes:o,meshes:s,materials:f,...h.length>0?{images:h}:{},...p.length>0?{samplers:p}:{},...g.length>0?{textures:g}:{},accessors:a,bufferViews:n,buffers:[{byteLength:i}],...I.length>0?{animations:I}:{},...F||l.size>0?{extensionsUsed:[...F?["KHR_interactivity"]:[],...l]}:{},...F||v.length>0||J.length>0||A.length>0?{extensions:{...F?{KHR_interactivity:F}:{},...v.length>0?{KHR_materials_variants:{variants:v.map(k=>({name:k}))}}:{},...J.length>0?{KHR_audio_emitter:{...V.length>0?{audio:V}:{},sources:Y,emitters:J}}:{},...A.length>0?{KHR_lights_punctual:{lights:A}}:{}}}:{}},Q=new Uint8Array(i),ee=0;for(let k of r)Q.set(k,ee),ee+=k.byteLength;return[{gltf:re,bin:Q.buffer,lights:y,environmentIntensity:e.environmentIntensity},c]}function Co(e){return new TextEncoder().encode(e)}function En(e,t){let{gltf:r,bin:i}=Vi(e,t),n=JSON.stringify(r),a=Co(n),s=(4-a.byteLength%4)%4,o=a.byteLength+s,l=20+o+8+i.byteLength,c=new Uint8Array(l),f=new DataView(c.buffer);f.setUint32(0,1179937895,!0),f.setUint32(4,2,!0),f.setUint32(8,l,!0),f.setUint32(12,o,!0),f.setUint32(16,1313821514,!0),c.set(a,20);for(let h=0;h<s;h++)c[20+a.byteLength+h]=32;let m=20+o;return f.setUint32(m,i.byteLength,!0),f.setUint32(m+4,5130562,!0),c.set(new Uint8Array(i),m+8),c}function _p(e,t){let[r,i]=wh(e,t);return Mh(r,i)}function Mh(e,t){let r=[],i=e.gltf,n=We().decoders.get("meshopt");n&&typeof n.decodeBufferViews=="function"&&n.decodeBufferViews(i,e);let a=e.bin,s=a instanceof ArrayBuffer?a:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),o=i.accessors||[],l=i.bufferViews||[],c=i.materials||[],f=i.meshes||[],m=i.nodes||[],h=i.textures||[],p=i.images||[],g=i.samplers||[],x=new Set,v=c.map((C,_)=>No(x,Ln(C?.name,`Material_${_}`))),y=new Map;function A(C){let _=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(C);if(!_)return null;let P=_[2].replace(/\s+/g,""),R=P.endsWith("==")?2:P.endsWith("=")?1:0,I=new Uint8Array((P.length*3>>2)-R),F=Y=>{let J=P.charCodeAt(Y);return J>96?J-71:J>64?J-65:J>47?J+4:J===43?62:J===47?63:0},V=0;for(let Y=0;Y<P.length;Y+=4){let J=F(Y)<<18|F(Y+1)<<12|F(Y+2)<<6|F(Y+3);I[V++]=J>>16&255,V<I.length&&(I[V++]=J>>8&255),V<I.length&&(I[V++]=J&255)}return I}function b(C,_,P){let R=C?.index;if(typeof R!="number")return;let I=h[R],F=I?.source;if(typeof F!="number"||!p[F])return;let V=y.get(F);if(V===void 0){V=null;let re=p[F],Q=null;if(typeof re.bufferView=="number"){let ee=l[re.bufferView],k=ee?.byteOffset||0,G=ee?.byteLength||0;ee&&G>0&&k>=0&&k+G<=s.byteLength&&(Q=new Uint8Array(s,k,G))}else typeof re.uri=="string"&&(Q=A(re.uri));if(Q&&Q.byteLength>0){let ee=Q[0]===255&&Q[1]===216&&Q[2]===255||!(Q[0]===137&&Q[1]===80)&&/jpe?g/i.test(re.mimeType||re.uri||"");V={file:`texture_${F}.${ee?"jpg":"png"}`,data:Q}}y.set(F,V)}if(!V)return;let Y=typeof I.sampler=="number"?g[I.sampler]:void 0,J=re=>re===33071?"clamp":re===33648?"mirror":"repeat";return{file:V.file,data:V.data,wrapS:J(Y?.wrapS),wrapT:J(Y?.wrapT),..._?{scale:_}:{},...P?{bias:P}:{}}}function w(C){let _=o[C];if(!_)throw new Error(`Accessor ${C} not found`);let P=l[_.bufferView||0],R=(P.byteOffset||0)+(_.byteOffset||0),I=P.byteLength||0;return{acc:_,buffer:s.slice(R,R+I)}}function S(C,_,P,R){let I=[],F=f[C];if(!F)return I;let V=F.primitives||[];for(let Y=0;Y<V.length;Y++){let J=V[Y],re=J.attributes?.POSITION;if(re===void 0)continue;let{acc:Q,buffer:ee}=w(re),k=new Float32Array(ee,0,Q.count*3),G,q=J.attributes?.NORMAL;if(q!==void 0){let{acc:D,buffer:z}=w(q),O=new Float32Array(z,0,D.count*3);G=new Float32Array(O.length);for(let X=0;X<D.count;X++){let se=O[X*3],ce=O[X*3+1],pe=O[X*3+2],xe=Math.hypot(se,ce,pe)||1;G[X*3]=se/xe,G[X*3+1]=ce/xe,G[X*3+2]=pe/xe}}let H,te=J.attributes?.TEXCOORD_0;if(te!==void 0){let{acc:D,buffer:z}=w(te);H=new Float32Array(z,0,D.count*2)}let Z;if(J.indices!==void 0){let{acc:D,buffer:z}=w(J.indices);Z=D.componentType===5125?new Uint32Array(z,0,D.count):new Uint16Array(z,0,D.count);let O=Q.count;for(let X of Z)if(X>=O)throw new Error(`SecurityError: Index buffer value (${X}) out of vertex bounds [0, ${O}).`)}else{let D=Q.count;Z=D>65535?new Uint32Array(D):new Uint16Array(D);for(let z=0;z<D;z++)Z[z]=z}let ae="DefaultMaterial",ie=[1,1,1],de=.5,me=0,Se=0,ke=0,_e=1.5,Le=1,ne=[0,0,0],Re,W={};if(J.material!==void 0&&c[J.material]){let D=c[J.material];ae=v[J.material]||`Material_${J.material}`;let z=D.pbrMetallicRoughness||{},O=(Fe,Ve)=>Array.isArray(Fe)&&Fe.length>=3?[Fe[0],Fe[1],Fe[2]]:Ve;ie=O(z.baseColorFactor,[1,1,1]);let X=Array.isArray(z.baseColorFactor)&&typeof z.baseColorFactor[3]=="number"?z.baseColorFactor[3]:1,se=ie[0]!==1||ie[1]!==1||ie[2]!==1||X!==1,ce=b(z.baseColorTexture,se?[ie[0],ie[1],ie[2],X]:void 0),pe=D.extras?.avgColor;!ce&&Array.isArray(pe)&&pe.length>=3&&(ie=[ie[0]*pe[0],ie[1]*pe[1],ie[2]*pe[2]]),typeof z.roughnessFactor=="number"&&(de=z.roughnessFactor),typeof z.metallicFactor=="number"&&(me=z.metallicFactor);let xe=typeof z.roughnessFactor=="number"?z.roughnessFactor:1,he=typeof z.metallicFactor=="number"?z.metallicFactor:1,Ne=b(z.metallicRoughnessTexture,xe!==1||he!==1?[1,xe,he,1]:void 0);ne=O(D.emissiveFactor,[0,0,0]);let ge=(ne[0]>0||ne[1]>0||ne[2]>0)&&(ne[0]!==1||ne[1]!==1||ne[2]!==1)?[ne[0],ne[1],ne[2],1]:void 0,Ae=b(D.emissiveTexture,ge),Ee=typeof D.normalTexture?.scale=="number"?D.normalTexture.scale:1,$e=b(D.normalTexture,[2*Ee,2*Ee,2,1],[-Ee,-Ee,-1,0]),De=typeof D.occlusionTexture?.strength=="number"?D.occlusionTexture.strength:1,Be=De!==1?b(D.occlusionTexture,[De,De,De,1],[1-De,1-De,1-De,0]):b(D.occlusionTexture);(ce||Ne||$e||Ae||Be)&&(Re=[ce,Ne,$e,Ae,Be]),W=D.extensions||{},W.KHR_materials_clearcoat&&(Se=W.KHR_materials_clearcoat.clearcoatFactor??0,ke=W.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof W.KHR_materials_ior?.ior=="number"&&(_e=W.KHR_materials_ior.ior),Le=X*(1-(W.KHR_materials_transmission?.transmissionFactor??0))}I.push({name:V.length>1?`${_}_p${Y}`:_,positions:k,indices:Z,normals:G,uvs:H,materialName:ae,color:ie,roughness:de,metallic:me,clearcoat:Se,clearcoatRoughness:ke,ior:_e,opacity:Le,emissiveColor:ne,...Re?{textures:Re}:{},...W.GOOGLE_material_tsl?{tslGraph:W.GOOGLE_material_tsl}:{},xrTraits:P||F.extras?.xr,...R?{invisible:!0}:{}})}return I}if(m.length>0){let C=new Float32Array(0),_=new Uint16Array(0),P=(k,G)=>{if(k===void 0)return null;let{acc:q,buffer:H}=w(k);return new Float32Array(H,0,q.count*G)},R=(k,G)=>Array.isArray(k)&&k.length>=3?[Ye(k[0],G),Ye(k[1],G),Ye(k[2],G)]:[G,G,G],I=(k,G,q)=>k&&k.length>=(G+1)*3?[k[G*3],k[G*3+1],k[G*3+2]]:q,F=(k,G,q)=>k&&k.length>=(G+1)*4?[k[G*4],k[G*4+1],k[G*4+2],k[G*4+3]]:q,V=new Map,Y=i.animations?.[0];if(Y&&Array.isArray(Y.channels)&&Array.isArray(Y.samplers))for(let k of Y.channels){let G=Y.samplers[k?.sampler],q=k?.target?.node,H=k?.target?.path;if(!G||typeof q!="number"||G.input===void 0)continue;let te=V.get(q);te||(te={input:G.input},V.set(q,te)),H==="translation"?te.t=G.output:H==="rotation"?te.r=G.output:H==="scale"&&(te.s=G.output)}let J=i.scenes?.[i.scene??0]?.nodes??[];if(!Array.isArray(J)||J.length===0){let k=new Set;for(let G of m)if(Array.isArray(G?.children))for(let q of G.children)k.add(q);J=[];for(let G=0;G<m.length;G++)k.has(G)||J.push(G);J.length===0&&(J=[0])}let re=new Set,Q=[],ee=(k,G)=>{if(Array.isArray(k))for(let q=k.length-1;q>=0;q--)Q.push({idx:k[q],out:G})};for(ee(J,r);Q.length>0;){let{idx:k,out:G}=Q.pop();if(typeof k!="number"||k<0||k>=m.length||re.has(k))continue;re.add(k);let q=m[k];if(!q)continue;let H=[0,0,0],te=[0,0,0,1],Z=[1,1,1];if(Array.isArray(q.matrix)&&q.matrix.length===16){let Le=xh(q.matrix);H=Le.t,te=Le.r,Z=Le.s}else H=R(q.translation,0),Array.isArray(q.rotation)&&q.rotation.length>=4&&(te=[Ye(q.rotation[0],0),Ye(q.rotation[1],0),Ye(q.rotation[2],0),Ye(q.rotation[3],1)]),Z=R(q.scale,1);let ae,ie=V.get(k);if(ie){let Le=P(ie.input,1);if(Le&&Le.length>0){let ne=P(ie.t,3),Re=P(ie.r,4),W=P(ie.s,3),D=Array.from(Le),z=[],O=[],X=[];for(let se=0;se<Le.length;se++)z.push(I(ne,se,H)),O.push(F(Re,se,te)),X.push(I(W,se,Z));ae={times:D,translations:z,rotations:O,scales:X}}}let de=Array.isArray(q.children)?q.children:[],me=typeof q.mesh=="number"&&q.mesh>=0&&q.mesh<f.length,Se=t?.[k]?.userData?.xr??q.extras?.xr;if(!me&&de.length===0&&(q.camera!==void 0||q.extensions?.KHR_lights_punctual||!q.name&&!q.extras&&!Se&&!ae))continue;let ke=(Le,ne,Re)=>({name:Le,positions:C,indices:_,isXform:!0,xrTraits:Se,timeSamples:ae,translation:H,rotation:te,scale:Z,children:ne,...Re?{invisible:!0}:{}}),_e=q.visible===!1||q.extensions?.KHR_node_visibility?.visible===!1||t?.[k]?.visible===!1;if(me){let Le=q.name||f[q.mesh]?.name||`Mesh_${k}`,ne=S(q.mesh,Le,Se,_e),Re=t?.[k],W=!!(Re?._castShdSet||Re?._recvShdSet),D=typeof q.extras?.shadow?.cast=="boolean"?q.extras.shadow.cast:W?!!Re?.castShadow:void 0;if(D!==void 0)for(let O of ne)O.castShadow=D;let z=q.extensions?.EXT_mesh_gpu_instancing?.attributes;if(z&&typeof z=="object"&&ne.length>0){let O=P(z.TRANSLATION,3),X=P(z.ROTATION,4),se=P(z.SCALE,3),ce=P(z._COLOR_0,3),pe=Math.min(1e3,O?O.length/3:X?X.length/4:se?se.length/3:0);if(pe>0){let xe=[];for(let he=0;he<pe;he++){let Ne=I(O,he,[0,0,0]),ge=F(X,he,[0,0,0,1]),Ae=I(se,he,[1,1,1]);for(let Ee of ne){let $e=Ee.color||[.8,.8,.8],De=ce&&ce.length>=(he+1)*3;xe.push({...Ee,name:`${Ee.name}_${he}`,materialName:De?`${Ee.materialName}_inst_${he}`:Ee.materialName,color:De?[$e[0]*ce[he*3],$e[1]*ce[he*3+1],$e[2]*ce[he*3+2]]:Ee.color,translation:Ne,rotation:ge,scale:Ae})}}ee(de,xe),G.push(ke(Le,xe,_e));continue}}if(ne.length===1)ne[0].translation=H,ne[0].rotation=te,ne[0].scale=Z,ne[0].timeSamples=ae,de.length>0&&(ne[0].children=[],ee(de,ne[0].children)),G.push(ne[0]);else{let O=[...ne];ee(de,O),G.push(ke(Le,O,_e))}}else{let Le=[];ee(de,Le),G.push(ke(q.name||`Group_${k}`,Le,_e))}}}else for(let C=0;C<f.length;C++){let _=f[C].name||`Mesh_${C}`;r.push(...S(C,_,f[C].extras?.xr))}let E=(Array.isArray(e.lights)&&e.lights.length>0?e.lights:void 0)??hh(i)??(Array.isArray(i?.asset?.extras?.lights)?i.asset.extras.lights:[]),N=[];for(let C=0;C<E.length;C++){let _=E[C];_?.shadow?.cast&&(_.type==="directional"||_.type==="spot"||_.type==="point")&&N.push({name:`Light_${C}`,type:_.type,color:_.color,intensity:_.intensity,position:_.position,direction:_.direction,range:_.range,innerConeAngle:_.innerConeAngle,outerConeAngle:_.outerConeAngle,shadow:_.shadow})}return N.length>0&&(r.__usdaShadowLights=N),r}function Ln(e,t){if(!e||typeof e!="string")return t;let r=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(r)&&(r="_"+r),r||t}function wa(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function It(e){if(!Number.isFinite(e)||Math.abs(e)<1e-7)return"0";let t=Number(e.toFixed(5)).toString();return t.indexOf(".")===-1?`${t}.0`:t}var Rr=(e,t,r)=>`(${It(e)}, ${It(t)}, ${It(r)})`,Rn=(e,t,r,i)=>`(${It(e)}, ${It(t)}, ${It(r)}, ${It(i)})`;function _h(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=Rr(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function Sp(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${It(e[i*2])}, ${It(1-e[i*2+1])})`;return r.join(", ")}function Ap(e){return Array.from(e).join(", ")}function Tp(e,t){let r=(t??e.__usdaShadowLights??[]).filter(v=>v?.shadow?.cast),i=new Map,n=0,a=null,s=[...e];for(;s.length>0;){let v=s.pop();if(!v.isXform&&v.positions&&v.positions.length>0){let y=Ln(v.materialName,"DefaultMaterial");i.has(y)||i.set(y,{color:v.color||[1,1,1],roughness:v.roughness??.5,metallic:v.metallic??0,clearcoat:v.clearcoat??0,clearcoatRoughness:v.clearcoatRoughness??0,ior:v.ior??1.5,opacity:v.opacity??1,emissiveColor:v.emissiveColor||[0,0,0],textures:v.textures,tslGraph:v.tslGraph})}if(v.timeSamples&&v.timeSamples.times.length>0){let y=v.timeSamples.times[v.timeSamples.times.length-1];y>n&&(n=y)}else v.tslGraph&&n<=0&&JSON.stringify(v.tslGraph).includes('"time"')&&(n=60);if(v.xrTraits?.anchor&&!a&&(a=v.xrTraits.anchor==="vertical"||v.xrTraits.anchor==="wall"?"vertical":"horizontal"),v.children)for(let y=v.children.length-1;y>=0;y--)s.push(v.children[y])}let o="";n>0&&(o=`startTimeCode = 0
216
+ endTimeCode = ${It(n)}
252
217
  timeCodesPerSecond = 1.0
253
- `);let l="";i&&(l=`uniform token preliminary:anchoring:type = "plane"
254
- uniform token preliminary:planeAnchoring:alignment = "${i}"
255
- `);let o=`#usda 1.0
218
+ `);let l="";a&&(l=`uniform token preliminary:anchoring:type = "plane"
219
+ uniform token preliminary:planeAnchoring:alignment = "${a}"
220
+ `);let c=`#usda 1.0
256
221
  (
257
222
  defaultPrim = "Root"
258
223
  metersPerUnit = 1.0
259
224
  upAxis = "Y"
260
- ${s})
225
+ ${o})
261
226
 
262
227
  def Xform "Root" (
263
228
  kind = "component"
@@ -265,141 +230,224 @@ kind = "component"
265
230
  {
266
231
  ${l}def Scope "Materials"
267
232
  {
268
- `;for(let[f,g]of t.entries()){let[x,b,v]=g.color,[p,y,M]=g.emissiveColor,P=`/Root/Materials/${f}`,[F,G,T,E,S]=g.textures||[],B=(I,H)=>`.connect = <${P}/${I}.outputs:${H}>`,k=F?`color3f inputs:diffuseColor${B("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${bt(x,b,v)}`,w=G?`float inputs:metallic${B("MetallicRoughnessTexture","b")}
269
- float inputs:roughness${B("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${$e(g.metallic)}
270
- float inputs:roughness = ${$e(g.roughness)}`,ie="";g.clearcoat>0&&(ie+=`float inputs:clearcoat = ${$e(g.clearcoat)}
271
- `,ie+=`float inputs:clearcoatRoughness = ${$e(g.clearcoatRoughness)}
272
- `),g.ior!==1.5&&(ie+=`float inputs:ior = ${$e(g.ior)}
273
- `),g.opacity<1&&(ie+=`float inputs:opacity = ${$e(g.opacity)}
274
- `),E?ie+=`color3f inputs:emissiveColor${B("EmissiveTexture","rgb")}
275
- `:(p>0||y>0||M>0)&&(ie+=`color3f inputs:emissiveColor = ${bt(p,y,M)}
276
- `),T&&(ie+=`normal3f inputs:normal${B("NormalTexture","rgb")}
277
- `),S&&(ie+=`float inputs:occlusion${B("OcclusionTexture","r")}
278
- `);let oe="";if(F||G||T||E||S){oe+=`def Shader "PrimvarReader"
233
+ `;for(let[v,y]of i.entries()){let[A,b,w]=y.color,[S,E,N]=y.emissiveColor,C=`/Root/Materials/${v}`,[_,P,R,I,F]=y.textures||[],V=(G,q)=>`.connect = <${C}/${G}.outputs:${q}>`,Y=_?`color3f inputs:diffuseColor${V("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${Rr(A,b,w)}`,J=P?`float inputs:metallic${V("MetallicRoughnessTexture","b")}
234
+ float inputs:roughness${V("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${It(y.metallic)}
235
+ float inputs:roughness = ${It(y.roughness)}`,re="";y.clearcoat>0&&(re+=`float inputs:clearcoat = ${It(y.clearcoat)}
236
+ `,re+=`float inputs:clearcoatRoughness = ${It(y.clearcoatRoughness)}
237
+ `),y.ior!==1.5&&(re+=`float inputs:ior = ${It(y.ior)}
238
+ `),y.opacity<1&&(re+=`float inputs:opacity = ${It(y.opacity)}
239
+ `),I?re+=`color3f inputs:emissiveColor${V("EmissiveTexture","rgb")}
240
+ `:(S>0||E>0||N>0)&&(re+=`color3f inputs:emissiveColor = ${Rr(S,E,N)}
241
+ `),R&&(re+=`normal3f inputs:normal${V("NormalTexture","rgb")}
242
+ `),F&&(re+=`float inputs:occlusion${V("OcclusionTexture","r")}
243
+ `);let Q="";if(_||P||R||I||F){Q+=`def Shader "PrimvarReader"
279
244
  {
280
245
  uniform token info:id = "UsdPrimvarReader_float2"
281
246
  string inputs:varname = "st"
282
247
  float2 outputs:result
283
248
  }
284
- `;let I=(H,C,z,ue)=>{if(!C)return;let he=C.scale?`float4 inputs:scale = ${Vr(C.scale[0],C.scale[1],C.scale[2],C.scale[3])}
285
- `:"",O=C.bias?`float4 inputs:bias = ${Vr(C.bias[0],C.bias[1],C.bias[2],C.bias[3])}
286
- `:"";oe+=`def Shader "${H}"
249
+ `;let G=(q,H,te,Z)=>{if(!H)return;let ae=H.scale?`float4 inputs:scale = ${Rn(H.scale[0],H.scale[1],H.scale[2],H.scale[3])}
250
+ `:"",ie=H.bias?`float4 inputs:bias = ${Rn(H.bias[0],H.bias[1],H.bias[2],H.bias[3])}
251
+ `:"";Q+=`def Shader "${q}"
287
252
  {
288
253
  uniform token info:id = "UsdUVTexture"
289
- asset inputs:file = @${Fr(C.file)}@
290
- float2 inputs:st${B("PrimvarReader","result")}
291
- token inputs:sourceColorSpace = "${z}"
292
- token inputs:wrapS = "${C.wrapS||"repeat"}"
293
- token inputs:wrapT = "${C.wrapT||"repeat"}"
294
- ${he}${O}${ue}}
295
- `};I("DiffuseTexture",F,"sRGB",`float3 outputs:rgb
296
- `),I("MetallicRoughnessTexture",G,"raw",`float outputs:g
254
+ asset inputs:file = @${wa(H.file)}@
255
+ float2 inputs:st${V("PrimvarReader","result")}
256
+ token inputs:sourceColorSpace = "${te}"
257
+ token inputs:wrapS = "${H.wrapS||"repeat"}"
258
+ token inputs:wrapT = "${H.wrapT||"repeat"}"
259
+ ${ae}${ie}${Z}}
260
+ `};G("DiffuseTexture",_,"sRGB",`float3 outputs:rgb
261
+ `),G("MetallicRoughnessTexture",P,"raw",`float outputs:g
297
262
  float outputs:b
298
- `),I("NormalTexture",T,"raw",`float3 outputs:rgb
299
- `),I("EmissiveTexture",E,"sRGB",`float3 outputs:rgb
300
- `),I("OcclusionTexture",S,"raw",`float outputs:r
301
- `)}o+=`def Material "${f}"
263
+ `),G("NormalTexture",R,"raw",`float3 outputs:rgb
264
+ `),G("EmissiveTexture",I,"sRGB",`float3 outputs:rgb
265
+ `),G("OcclusionTexture",F,"raw",`float outputs:r
266
+ `)}let ee=`${Y}
267
+ ${J}
268
+ ${re}`,k=y.tslGraph&&We().tslUsdzSerializer?.(y.tslGraph,v,ee);k&&(ee=k.surfaceInputsUsda||ee,Q+=k.nodeGraphUsda),c+=`def Material "${v}"
302
269
  {
303
270
  def Shader "PBRShader"
304
271
  {
305
272
  uniform token info:id = "UsdPreviewSurface"
306
- ${k}
307
- ${w}
308
- ${ie}token outputs:surface
273
+ ${ee}token outputs:surface
309
274
  }
310
- token outputs:surface${B("PBRShader","surface")}
311
- ${oe}}
312
- `}o+=`}
275
+ token outputs:surface${V("PBRShader","surface")}
276
+ ${Q}}
277
+ `}c+=`}
313
278
  def Scope "Meshes"
314
279
  {
315
- `;let a=(f,g,x)=>{let b=[];g&&b.push('"MaterialBindingAPI"');let v=!!(f?.rigidBody&&f.rigidBody!=="none"&&(typeof f.rigidBody!="object"||f.rigidBody.enabled!==!1)),p=!!(f?.physics&&f.physics!=="none"||v);p&&b.push(...v?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let y=[];if(b.length>0&&y.push(`prepend apiSchemas = [${b.join(", ")}]`),f){let T=Ae().xrTraitSerializer?.usdLines(f,Fr)??[];if(!T.length)for(let E of["grab","billboard","follow","anchor","physics"]){let S=E==="follow"&&typeof f.follow=="object"?f.follow.mode??"head":f[E];S!==void 0&&T.push(`string ${E} = "${Fr(S)}"`)}T.length>0&&y.push(`customData = {
280
+ `;let f=(v,y,A)=>{let b=[];y&&b.push('"MaterialBindingAPI"');let w=!!(v?.rigidBody&&v.rigidBody!=="none"&&(typeof v.rigidBody!="object"||v.rigidBody.enabled!==!1)),S=!!(v?.physics&&v.physics!=="none"||w);S&&b.push(...w?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let E=[];b.length>0&&E.push(`prepend apiSchemas = [${b.join(", ")}]`);let N=We().xrTraitSerializer;if(v){let I=N?.usdLines(v,wa)??[];if(!I.length)for(let F of["grab","billboard","follow","anchor","physics"]){let V=F==="follow"&&typeof v.follow=="object"?v.follow.mode??"head":v[F];V!==void 0&&I.push(`string ${F} = "${wa(V)}"`)}I.length>0&&E.push(`customData = {
316
281
  dictionary xr = {
317
- ${T.join(`
282
+ ${I.join(`
318
283
  `)}
319
284
  }
320
- }`)}let M=y.length>0?` (
321
- ${y.join(`
285
+ }`)}let C=E.length>0?` (
286
+ ${E.join(`
322
287
  `)}
323
- )`:"",P=x?`uniform token visibility = "invisible"
324
- `:"";if(p){let T=f?.rigidBody??f?.physics,E=T?.body??T?.mode??T;P+=`bool physics:rigidBodyEnabled = true
325
- bool physics:kinematicEnabled = ${E==="static"||E==="kinematic"}
288
+ )`:"",_=A?`uniform token visibility = "invisible"
289
+ `:"";if(S){let I=v?.rigidBody??v?.physics,F=I?.body??I?.mode??I;_+=`bool physics:rigidBodyEnabled = true
290
+ bool physics:kinematicEnabled = ${F==="static"||F==="kinematic"}
326
291
  bool physics:collisionEnabled = true
327
- `,T?.mass>0&&Number.isFinite(T.mass)&&(P+=`float physics:mass = ${$e(T.mass)}
328
- `)}let F=ca(f),G=F?`def SpatialAudio "AudioEmitter"
292
+ `,I?.mass>0&&Number.isFinite(I.mass)&&(_+=`float physics:mass = ${It(I.mass)}
293
+ `)}let P=vh(v),R=(P?`def SpatialAudio "AudioEmitter"
329
294
  {
330
- ${F.src?`asset inputs:file = @${Fr(F.src)}@
331
- `:""}uniform token inputs:auralMode = "${F.isGlobal?"nonSpatial":"spatial"}"
332
- uniform token inputs:playbackMode = "${F.loop?"loopFromStart":"onceFromStart"}"
333
- double gain = ${$e(F.volume)}
334
- }
335
- `:"";return{header:M,body:P,tail:G}},u=f=>{if(f.timeSamples&&f.timeSamples.times.length>0){let y=f.timeSamples,M=(T,E,S)=>y.times.map((B,k)=>`${$e(B)}: ${S(T?.[k]||E)}`).join(", "),P=M(y.translations,[0,0,0],T=>bt(T[0],T[1],T[2])),F=M(y.rotations,[0,0,0,1],T=>{let E=Math.hypot(T[0],T[1],T[2],T[3])||1;return Vr(T[3]/E,T[0]/E,T[1]/E,T[2]/E)}),G=M(y.scales,[1,1,1],T=>bt(T[0],T[1],T[2]));return`double3 xformOp:translate.timeSamples = { ${P} }
336
- quatf xformOp:orient.timeSamples = { ${F} }
337
- double3 xformOp:scale.timeSamples = { ${G} }
295
+ ${P.src?`asset inputs:file = @${wa(P.src)}@
296
+ `:""}uniform token inputs:auralMode = "${P.isGlobal?"nonSpatial":"spatial"}"
297
+ uniform token inputs:playbackMode = "${P.loop?"loopFromStart":"onceFromStart"}"
298
+ double gain = ${It(P.volume)}
299
+ }
300
+ `:"")+(v?N?.usdPrims?.(v)??"":"");return{header:C,body:_,tail:R}},m=v=>{if(v.timeSamples&&v.timeSamples.times.length>0){let E=v.timeSamples,N=(R,I,F)=>E.times.map((V,Y)=>`${It(V)}: ${F(R?.[Y]||I)}`).join(", "),C=N(E.translations,[0,0,0],R=>Rr(R[0],R[1],R[2])),_=N(E.rotations,[0,0,0,1],R=>{let I=Math.hypot(R[0],R[1],R[2],R[3])||1;return Rn(R[3]/I,R[0]/I,R[1]/I,R[2]/I)}),P=N(E.scales,[1,1,1],R=>Rr(R[0],R[1],R[2]));return`double3 xformOp:translate.timeSamples = { ${C} }
301
+ quatf xformOp:orient.timeSamples = { ${_} }
302
+ double3 xformOp:scale.timeSamples = { ${P} }
338
303
  uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
339
- `}let g=[],x="",b=f.translation;b&&(Math.abs(b[0])>1e-7||Math.abs(b[1])>1e-7||Math.abs(b[2])>1e-7)&&(x+=`double3 xformOp:translate = ${bt(b[0],b[1],b[2])}
340
- `,g.push('"xformOp:translate"'));let v=f.rotation;if(v){let y=Math.hypot(v[0],v[1],v[2],v[3])||1,M=v[0]/y,P=v[1]/y,F=v[2]/y,G=v[3]/y;(1-Math.abs(G)>1e-7||Math.hypot(M,P,F)>1e-7)&&(x+=`quatf xformOp:orient = ${Vr(G,M,P,F)}
341
- `,g.push('"xformOp:orient"'))}let p=f.scale;return p&&(Math.abs(p[0]-1)>1e-7||Math.abs(p[1]-1)>1e-7||Math.abs(p[2]-1)>1e-7)&&(x+=`float3 xformOp:scale = ${bt(p[0],p[1],p[2])}
342
- `,g.push('"xformOp:scale"')),g.length>0&&(x+=`uniform token[] xformOpOrder = [${g.join(", ")}]
343
- `),x},h=f=>{let g=f.positions.length/3,x=1/0,b=1/0,v=1/0,p=-1/0,y=-1/0,M=-1/0;for(let E=0;E<g;E++){let S=f.positions[E*3],B=f.positions[E*3+1],k=f.positions[E*3+2];S<x&&(x=S),S>p&&(p=S),B<b&&(b=B),B>y&&(y=B),k<v&&(v=k),k>M&&(M=k)}isFinite(x)||(x=b=v=-1,p=y=M=1);let P=Math.floor(f.indices.length/3),F=kr(f.materialName,"DefaultMaterial"),G=P>0?P===1?"3":"3, ".repeat(P-1)+"3":"",T=`float3[] extent = [${bt(x,b,v)}, ${bt(p,y,M)}]
344
- int[] faceVertexCounts = [${G}]
345
- int[] faceVertexIndices = [${gl(f.indices)}]
346
- point3f[] points = [${pa(f.positions)}]
347
- `;return f.normals&&f.normals.length===f.positions.length&&(T+=`normal3f[] normals = [${pa(f.normals)}] (
304
+ `}let y=[],A="",b=v.translation;b&&(Math.abs(b[0])>1e-7||Math.abs(b[1])>1e-7||Math.abs(b[2])>1e-7)&&(A+=`double3 xformOp:translate = ${Rr(b[0],b[1],b[2])}
305
+ `,y.push('"xformOp:translate"'));let w=v.rotation;if(w){let E=Math.hypot(w[0],w[1],w[2],w[3])||1,N=w[0]/E,C=w[1]/E,_=w[2]/E,P=w[3]/E;(1-Math.abs(P)>1e-7||Math.hypot(N,C,_)>1e-7)&&(A+=`quatf xformOp:orient = ${Rn(P,N,C,_)}
306
+ `,y.push('"xformOp:orient"'))}let S=v.scale;return S&&(Math.abs(S[0]-1)>1e-7||Math.abs(S[1]-1)>1e-7||Math.abs(S[2]-1)>1e-7)&&(A+=`float3 xformOp:scale = ${Rr(S[0],S[1],S[2])}
307
+ `,y.push('"xformOp:scale"')),y.length>0&&(A+=`uniform token[] xformOpOrder = [${y.join(", ")}]
308
+ `),A},h=v=>{let y=v.positions.length/3,A=1/0,b=1/0,w=1/0,S=-1/0,E=-1/0,N=-1/0;for(let I=0;I<y;I++){let F=v.positions[I*3],V=v.positions[I*3+1],Y=v.positions[I*3+2];F<A&&(A=F),F>S&&(S=F),V<b&&(b=V),V>E&&(E=V),Y<w&&(w=Y),Y>N&&(N=Y)}isFinite(A)||(A=b=w=-1,S=E=N=1);let C=Math.floor(v.indices.length/3),_=Ln(v.materialName,"DefaultMaterial"),P=C>0?C===1?"3":"3, ".repeat(C-1)+"3":"",R=`float3[] extent = [${Rr(A,b,w)}, ${Rr(S,E,N)}]
309
+ int[] faceVertexCounts = [${P}]
310
+ int[] faceVertexIndices = [${Ap(v.indices)}]
311
+ point3f[] points = [${_h(v.positions)}]
312
+ `;return v.normals&&v.normals.length===v.positions.length&&(R+=`normal3f[] normals = [${_h(v.normals)}] (
348
313
  interpolation = "vertex"
349
314
  )
350
- `),f.uvs&&f.uvs.length===g*2&&(T+=`texCoord2f[] primvars:st = [${dl(f.uvs,g)}] (
315
+ `),v.uvs&&v.uvs.length===y*2&&(R+=`texCoord2f[] primvars:st = [${Sp(v.uvs,y)}] (
351
316
  interpolation = "vertex"
352
317
  )
353
- `),T+=`rel material:binding = </Root/Materials/${F}>
354
- `,T},m=new Set,c=[];for(let f=e.length-1;f>=0;f--)c.push({node:e[f],siblings:m});let d=0;for(;c.length>0;){let f=c.pop();if(f.close){o+=`}
355
- `;continue}let{node:g,siblings:x}=f,b=!!(g.isXform||g.positions.length===0),v=ua(x,kr(g.name,b?`Group_${d}`:`Mesh_${d}`));d++;let p=g.children||[];if(b){let y=a(g.xrTraits,!1,g.invisible);o+=`def Xform "${v}"${y.header}
318
+ `),R+=`rel material:binding = </Root/Materials/${_}>
319
+ `,v.castShadow===!1&&r.length>0&&(R+=`bool primvars:doNotCastShadows = 1
320
+ `),R},p=new Set,g=[];for(let v=e.length-1;v>=0;v--)g.push({node:e[v],siblings:p});let x=0;for(;g.length>0;){let v=g.pop();if(v.close){c+=`}
321
+ `;continue}let{node:y,siblings:A}=v,b=!!(y.isXform||y.positions.length===0),w=No(A,Ln(y.name,b?`Group_${x}`:`Mesh_${x}`));x++;let S=y.children||[];if(b){let E=f(y.xrTraits,!1,y.invisible);c+=`def Xform "${w}"${E.header}
356
322
  {
357
- ${y.body}${u(g)}${y.tail}`,c.push({close:!0});let M=new Set;for(let P=p.length-1;P>=0;P--)c.push({node:p[P],siblings:M})}else if(p.length>0){let y=a(g.xrTraits,!1,g.invisible),M=`${v}_mesh`;o+=`def Xform "${v}"${y.header}
323
+ ${E.body}${m(y)}${E.tail}`,g.push({close:!0});let N=new Set;for(let C=S.length-1;C>=0;C--)g.push({node:S[C],siblings:N})}else if(S.length>0){let E=f(y.xrTraits,!1,y.invisible),N=`${w}_mesh`;c+=`def Xform "${w}"${E.header}
358
324
  {
359
- ${y.body}${u(g)}${y.tail}`,o+=`def Mesh "${M}" (
325
+ ${E.body}${m(y)}${E.tail}`,c+=`def Mesh "${N}" (
360
326
  prepend apiSchemas = ["MaterialBindingAPI"]
361
327
  )
362
328
  {
363
- ${h(g)}}
364
- `,c.push({close:!0});let P=new Set([M]);for(let F=p.length-1;F>=0;F--)c.push({node:p[F],siblings:P})}else{let y=a(g.xrTraits,!0,g.invisible);o+=`def Mesh "${v}"${y.header}
329
+ ${h(y)}}
330
+ `,g.push({close:!0});let C=new Set([N]);for(let _=S.length-1;_>=0;_--)g.push({node:S[_],siblings:C})}else{let E=f(y.xrTraits,!0,y.invisible);c+=`def Mesh "${w}"${E.header}
331
+ {
332
+ ${E.body}${m(y)}${h(y)}${E.tail}}
333
+ `}}if(c+=`}
334
+ `,r.length>0){c+=`def Scope "Lights"
335
+ {
336
+ `;let v=new Set;for(let y=0;y<r.length;y++){let A=r[y],b=No(v,Ln(A.name,`Light_${y}`)),w=A.type==="directional"?"DistantLight":A.type==="spot"?"DiskLight":"SphereLight",S=A.type==="spot"?'["ShapingAPI", "ShadowAPI"]':'["ShadowAPI"]',[E,N,C]=A.color||[1,1,1],[_,P,R]=A.position||[0,5,5],I=-_,F=-P,V=-R;A.direction&&A.direction.length>=3&&(A.type==="directional"?(I=-A.direction[0],F=-A.direction[1],V=-A.direction[2]):(I=A.direction[0],F=A.direction[1],V=A.direction[2]));let[Y,J,re,Q]=bh(I,F,V),ee="",k=[];A.type!=="directional"&&(Math.abs(_)>1e-7||Math.abs(P)>1e-7||Math.abs(R)>1e-7)&&(ee+=`double3 xformOp:translate = ${Rr(_,P,R)}
337
+ `,k.push('"xformOp:translate"')),A.type!=="point"&&(1-Math.abs(Q)>1e-7||Math.hypot(Y,J,re)>1e-7)&&(ee+=`quatf xformOp:orient = ${Rn(Q,Y,J,re)}
338
+ `,k.push('"xformOp:orient"')),k.length>0&&(ee+=`uniform token[] xformOpOrder = [${k.join(", ")}]
339
+ `);let G="";if(A.type==="spot"){let q=(A.outerConeAngle??Math.PI/3)*180/Math.PI,H=(A.innerConeAngle??q*.8)*180/Math.PI,te=q>1e-4?Math.max(0,Math.min(1,1-H/q)):0;G=`float inputs:shaping:cone:angle = ${It(q)}
340
+ float inputs:shaping:cone:softness = ${It(te)}
341
+ `}c+=`def ${w} "${b}" (
342
+ prepend apiSchemas = ${S}
343
+ )
344
+ {
345
+ color3f inputs:color = ${Rr(E,N,C)}
346
+ float inputs:intensity = ${It(A.intensity??1)}
347
+ bool inputs:shadow:enable = 1
348
+ ${G}${ee}}
349
+ `}c+=`}
350
+ `}return c+=`}
351
+ `,c}var Ma=null;function Eo(e){if(!Ma){Ma=new Uint32Array(256);for(let r=0;r<256;r++){let i=r;for(let n=0;n<8;n++)i=i&1?3988292384^i>>>1:i>>>1;Ma[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=Ma[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function Pp(e){let t=[],r=0,i=[];for(let f of e){let m=Co(f.filename),h=Eo(f.data),p=f.data.length,g=30+m.length,x=(r+g)%64,v=x!==0?64-x:0;v>0&&v<4&&(v+=64);let y=new Uint8Array(g+v),A=new DataView(y.buffer);A.setUint32(0,67324752,!0),A.setUint16(4,20,!0),A.setUint32(14,h,!0),A.setUint32(18,p,!0),A.setUint32(22,p,!0),A.setUint16(26,m.length,!0),A.setUint16(28,v,!0),y.set(m,30),v>=4&&(A.setUint16(g,6534,!0),A.setUint16(g+2,v-4,!0)),t.push({offset:r,size:p,crc:h,filenameBytes:m,entry:f}),i.push(y,f.data),r+=y.length+f.data.length}let n=r;for(let f of t){let m=new Uint8Array(46+f.filenameBytes.length),h=new DataView(m.buffer);h.setUint32(0,33639248,!0),h.setUint16(4,20,!0),h.setUint16(6,20,!0),h.setUint32(16,f.crc,!0),h.setUint32(20,f.size,!0),h.setUint32(24,f.size,!0),h.setUint16(28,f.filenameBytes.length,!0),h.setUint32(42,f.offset,!0),m.set(f.filenameBytes,46),i.push(m),r+=m.length}let a=r-n,s=new Uint8Array(22),o=new DataView(s.buffer);o.setUint32(0,101010256,!0),o.setUint16(8,t.length,!0),o.setUint16(10,t.length,!0),o.setUint32(12,a,!0),o.setUint32(16,n,!0),i.push(s),r+=22;let l=new Uint8Array(r),c=0;for(let f of i)l.set(f,c),c+=f.length;return l}function Sh(e){let t=[{filename:"model.usda",data:Co(Tp(e))}],r=new Set(["model.usda"]),i=[...e];for(;i.length>0;){let n=i.pop();for(let a of n.textures||[])a?.file&&a.data?.byteLength&&!r.has(a.file)&&(r.add(a.file),t.push({filename:a.file,data:a.data}));if(n.children)for(let a=n.children.length-1;a>=0;a--)i.push(n.children[a])}return Pp(t)}function In(e){return Sh(_p(e))}function _a(e){return Sh(Mh(zi(e)))}function Sa(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():_a(e)}function Aa(e){let t=Sa(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function Ta(e,t){if(!e||!e.MeshPhysicalMaterial)return null;if(t?.authorNamespace?.TSL&&t?.authorNamespace?.MeshStandardNodeMaterial)return{TSL:t.authorNamespace.TSL,MeshStandardNodeMaterial:t.authorNamespace.MeshStandardNodeMaterial,MeshPhysicalNodeMaterial:t.authorNamespace.MeshPhysicalNodeMaterial};let r=128,i=16,n=0,a=(N,C,_)=>{typeof e.warnUnsupported=="function"&&e.warnUnsupported(`${C} [${N}]`,_)},s=N=>N==="vec4"?4:N==="vec3"?3:N==="vec2"?2:1,o=N=>N===4?"vec4":N===3?"vec3":N===2?"vec2":"float",l=(N,C=0)=>{let _=Number(N);return Number.isFinite(_)?Math.fround(_):C},c=N=>!!(N&&N.isTSLNode===!0),f=(N,C=1)=>{if(c(N))return N;if(typeof N=="number"||typeof N=="boolean"){let _=l(Number(N),0);return C>1?new p("const",o(C),[],new Array(C).fill(_)):new p("const","float",[],[_])}if(typeof N=="string"){let _=new e.Color(N);return new p("const","vec3",[],[l(_.r,1),l(_.g,1),l(_.b,1)])}if(Array.isArray(N)||N instanceof Float32Array){let _=Math.max(1,Math.min(4,N.length)),P=[];for(let R=0;R<_;R++)P.push(l(N[R],0));return new p("const",o(_),[],P)}if(N&&typeof N=="object"){let _=N;if("isColor"in _||"r"in _&&"g"in _&&"b"in _)return new p("const","vec3",[],[l(_.r,1),l(_.g,1),l(_.b,1)]);if("x"in _&&"y"in _)return"z"in _&&"w"in _?new p("const","vec4",[],[l(_.x),l(_.y),l(_.z),l(_.w,1)]):"z"in _?new p("const","vec3",[],[l(_.x),l(_.y),l(_.z)]):new p("const","vec2",[],[l(_.x),l(_.y)])}return new p("const","float",[],[0])},m=(N,C)=>{let _=f(N),P=f(C);if(_._type===P._type)return[_,P,_._type];if(_._type==="float")return[_,P,P._type];if(P._type==="float")return[_,P,_._type];let R=s(_._type),I=s(P._type);if(I>R)P=P.swizzle("xyzw".slice(0,R));else{let F=[P];for(let V=I;V<R;V++)F.push(new p("const","float",[],[0]));P=new p("construct",_._type,F)}return[_,P,_._type]},h=(N,C)=>{let _=f(N);if(_._type===C)return _;let P=s(C),R=s(_._type);if(P===1)return _.swizzle("x");if(R===1)return _._op==="const"&&_._val?new p("const",C,[],new Array(P).fill(_._val[0])):new p("construct",C,[_]);if(R>P)return _.swizzle("xyzw".slice(0,P));let I=[_];for(let F=R;F<P;F++)I.push(new p("const","float",[],[F===3?1:0]));return new p("construct",C,I)};class p{constructor(C,_,P,R,I,F){this.isTSLNode=!0,this._op=C,this._type=_,this._args=P,R!==void 0&&(this._val=R),I!==void 0&&(this._name=I),F!==void 0&&(this._mask=F)}get nodeType(){return this._type}get value(){return this._uVal}set value(C){this._op==="uniform"&&(this._uVal=C)}swizzle(C){let _=String(C||"x").trim().replace(/[rgba]/g,R=>"xyzw"["rgba".indexOf(R)]);if(!/^[xyzw]{1,4}$/.test(_))return a("TL501",`Invalid TSL swizzle '${C}'`,".x"),new p("const","float",[],[0]);let P=s(this._type);if(P===1&&_==="x")return this;for(let R=0;R<_.length;R++)if("xyzw".indexOf(_[R])>=P)return a("TL501",`TSL swizzle '.${C}' out of range`,"0"),new p("const",o(_.length),[],new Array(_.length).fill(0));return new p("swizzle",o(_.length),[this],void 0,void 0,_)}clamp(C=0,_=1){let P=f(C),R=f(_);return(P._type!=="float"||R._type!=="float")&&(P=h(P,this._type),R=h(R,this._type)),new p("clamp",this._type,[this,P,R])}saturate(){return this.clamp(0,1)}oneMinus(){return f(1,s(this._type)).sub(this)}mix(C,_){let[P,R,I]=m(this,C),F=f(_);return F._type!=="float"&&F._type!==I&&(F=h(F,I)),new p("mix",I,[P,R,F])}step(C){let _=f(C);return this._type==="float"?new p("step",_._type,[this,_]):new p("step",this._type,[this,h(_,this._type)])}smoothstep(C,_){let P=f(_),R=this,I=f(C);return(R._type!=="float"||I._type!=="float")&&(R=h(R,P._type),I=h(I,P._type)),new p("smoothstep",P._type,[R,I,P])}dot(C){let[_,P]=m(this,C);return new p("dot","float",[_,P])}cross(C){return new p("cross","vec3",[h(this,"vec3"),h(C,"vec3")])}length(){return new p("length","float",[this])}distance(C){let[_,P]=m(this,C);return new p("distance","float",[_,P])}reflect(C){let _=this._type==="float"?h(this,"vec3"):this;return new p("reflect",_._type,[_,h(C,_._type)])}remap(C,_,P,R){let I=this.sub(C).div(f(_).sub(C)).clamp(0,1);return f(P).mix(R,I)}}let g=p.prototype;for(let[N,C]of[["x","x"],["y","y"],["z","z"],["w","w"],["r","x"],["g","y"],["b","z"],["a","w"],["xy","xy"],["xz","xz"],["yz","yz"],["xyz","xyz"],["rgb","xyz"],["xyzw","xyzw"],["rgba","xyzw"]])Object.defineProperty(g,N,{get(){return this.swizzle(C)}});let x=["add","sub","mul","div","mod","pow","atan2","min","max"];for(let N of x)g[N]=function(C){let[_,P,R]=m(this,C);return new p(N,R,[_,P])};let v=["neg","abs","sign","floor","ceil","fract","sqrt","exp","log","sin","cos","normalize"];for(let N of v)g[N]=function(){return new p(N,this._type,[this])};let y=(N,C)=>{let _=new p("builtin",C,[],void 0,N),P=()=>_;return Object.setPrototypeOf(P,g),Object.defineProperty(P,"length",{value:g.length,configurable:!0}),Object.assign(P,_),P},A=(N,C)=>{let _=s(N);if(C.length===0)return new p("const",N,[],new Array(_).fill(0));if(C.length===1)return h(C[0],N);let P=C.map(Y=>f(Y)),R=!0,I=[],F=0;for(let Y of P)if(F+=s(Y._type),Y._op==="const"&&Y._val)for(let J of Y._val)I.push(J);else R=!1;if(R&&I.length>=_)return new p("const",N,[],I.slice(0,_));if(F===_)return new p("construct",N,P);let V=[];for(let Y of P){let J=s(Y._type);for(let re=0;re<J&&V.length<_;re++)V.push(J===1?Y:Y.swizzle("xyzw"[re]))}for(;V.length<_;)V.push(new p("const","float",[],[V.length===3?1:0]));return new p("construct",N,V)},b=y("positionWorld","vec3"),w={float:(N=0)=>h(N,"float"),vec2:(...N)=>A("vec2",N),vec3:(...N)=>A("vec3",N),vec4:(...N)=>A("vec4",N),color:(N=16777215,C,_)=>{if(typeof N=="number"&&typeof C=="number"&&typeof _=="number"){let R=new e.Color(N,C,_);return new p("const","vec3",[],[l(R.r,1),l(R.g,1),l(R.b,1)])}if(c(N))return h(N,"vec3");let P=new e.Color(N);return new p("const","vec3",[],[l(P.r,1),l(P.g,1),l(P.b,1)])},uniform:(N=0,C)=>{let _=f(N),P=typeof C=="string"&&C.trim().length>0?C.trim().replace(/[^A-Za-z0-9_]/g,"_").slice(0,63):`uParam_${n++}`;/^[0-9]/.test(P)&&(P="_"+P.slice(0,62)),(P==="__proto__"||P==="constructor"||P==="prototype")&&(P=`uParam_${n++}`);let R=new p("uniform",_._type,[],void 0,P);return R._uVal=N,R},positionLocal:y("positionLocal","vec3"),positionWorld:b,normalLocal:y("normalLocal","vec3"),normalWorld:y("normalWorld","vec3"),viewDirection:y("viewDirection","vec3"),uv:y("uv","vec2"),vertexColor:y("vertexColor","vec4"),instanceIndex:y("instanceIndex","float"),time:y("time","float"),clamp:(N,C=0,_=1)=>f(N).clamp(C,_),saturate:N=>f(N).saturate(),oneMinus:N=>f(N).oneMinus(),mix:(N,C,_)=>f(N).mix(C,_),step:(N,C)=>f(N).step(C),smoothstep:(N,C,_)=>f(N).smoothstep(C,_),dot:(N,C)=>f(N).dot(C),cross:(N,C)=>f(N).cross(C),length:N=>f(N).length(),distance:(N,C)=>f(N).distance(C),reflect:(N,C)=>f(N).reflect(C),remap:(N,C,_,P,R)=>f(N).remap(C,_,P,R),fresnel:(N=2)=>new p("fresnel","float",[h(N,"float")]),simplexNoise2D:N=>new p("simplexNoise2D","float",[h(N,"vec2")]),simplexNoise3D:N=>new p("simplexNoise3D","float",[h(N,"vec3")]),voronoi2D:(N,C=1)=>new p("voronoi2D","float",[h(N,"vec2"),h(C,"float")]),checker:N=>new p("checker","float",[h(N,"vec2")]),triplanar:(N=1,C=4)=>{let _=f(N),P=_._type==="vec3"?_:b.mul(h(_,"float"));return new p("triplanar","float",[P,h(C,"float")])},hueShift:(N,C)=>new p("hueShift","vec3",[h(N,"vec3"),h(C,"float")]),bumpFromHeight:(N,C=1)=>new p("bumpFromHeight","vec3",[h(N,"float"),h(C,"float")]),Loop:()=>(a("TL504","THREE.TSL.Loop","loop-free TSL constant"),new p("const","float",[],[0])),While:()=>(a("TL504","THREE.TSL.While","loop-free TSL constant"),new p("const","float",[],[0]))};for(let N of x)w[N]=(C,_)=>f(C)[N](_);for(let N of v)w[N]=C=>f(C)[N]();class S extends e.MeshPhysicalMaterial{get opacityNode(){return this._opacityNode}set opacityNode(C){this._opacityNode=C,C!=null&&!(Number(this.alphaTest)>0)&&(this.transparent=!0)}constructor(C={}){super(C),this._opacityNode=null,this.isMeshStandardNodeMaterial=!0,this.colorNode=C.colorNode??null,this.opacityNode=C.opacityNode??null,this.emissiveNode=C.emissiveNode??null,this.roughnessNode=C.roughnessNode??null,this.metalnessNode=C.metalnessNode??null,this.normalScaleNode=C.normalScaleNode??null,this.bumpNode=C.bumpNode??null,this.positionNode=C.positionNode??null}_serializeTslGraph(){let C=[["color",this.colorNode,"vec3"],["opacity",this.opacityNode,"float"],["emissive",this.emissiveNode,"vec3"],["roughness",this.roughnessNode,"float"],["metalness",this.metalnessNode,"float"],["normalScale",this.normalScaleNode,"float"],["bump",this.bumpNode,"vec3"],["position",this.positionNode,"vec3"]],_=[];for(let[ee,k,G]of C)k!=null&&_.push([ee,h(k,G)]);if(_.length===0)return null;let P=[],R={},I=new Map,F=new Set,V="",Y="",J=(ee,k)=>{if(V)return 0;if(!ee||!ee.isTSLNode)return V="TL501",Y="Invalid non-TSL node in material socket",0;if(F.has(ee))return V="TL501",Y="Cyclic TSL node reference",0;if(k&&(ee._op==="builtin"&&ee._name==="viewDirection"||ee._op==="fresnel"||ee._op==="bumpFromHeight"))return V="TL503",Y=`Fragment-only TSL op '${ee._name||ee._op}' used in positionNode`,0;F.add(ee);let G=[];for(let ae of ee._args)if(G.push(J(ae,k)),V)return F.delete(ee),0;if(F.delete(ee),ee._op==="uniform"){let ae=ee._name||"uParam";if(ae in R){if(R[ae].type!==ee._type)return V="TL501",Y=`Conflicting types for TSL uniform '${ae}' (${R[ae].type} vs ${ee._type})`,0}else{if(Object.keys(R).length>=i)return V="TL502",Y=`TSL material exceeds MAX_TSL_UNIFORMS (${i})`,0;let ie=h(ee._uVal??0,ee._type)._val??[0];R[ae]={type:ee._type,value:ee._type==="float"?ie[0]:ie}}}let q=`${ee._op}|${ee._type}|${G.join(",")}|${ee._val?ee._val.join(","):""}|${ee._name??""}|${ee._mask??""}`,H=I.get(q);if(H!==void 0)return H;if(P.length>=r)return V="TL502",Y=`TSL material exceeds MAX_TSL_NODES (${r})`,0;let te=P.length,Z={op:ee._op,type:ee._type};return G.length>0&&(Z.args=G),ee._val&&(Z.value=[...ee._val]),ee._name&&(Z.name=ee._name),ee._mask&&(Z.mask=ee._mask),P.push(Z),I.set(q,te),te},re={};for(let[ee,k]of _)if(re[ee]=J(k,ee==="position"),V)return a(V,Y,"base MeshStandardMaterial factors"),null;let Q={version:1,nodes:P,outputs:re};return Object.keys(R).length>0&&(Q.uniforms=R),Q}clone(){let C=new S;for(let _ of["name","_em","roughness","metalness","emissiveIntensity","opacity","transparent","wireframe","side","doubleSided","map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap","aoMapIntensity","bumpMap","bumpScale","clearcoat","clearcoatRoughness","sheen","sheenRoughness","ior","transmission","thickness","attenuationDistance","dispersion","iridescence","iridescenceIOR","colorNode","opacityNode","emissiveNode","roughnessNode","metalnessNode","normalScaleNode","bumpNode","positionNode"])C[_]=this[_];return C.color.copy(this.color),C.emissive.copy(this.emissive),C.normalScale.copy(this.normalScale),C.sheenColor.copy(this.sheenColor),C.attenuationColor.copy(this.attenuationColor),C}}let E={TSL:w,TSLNode:p,MeshStandardNodeMaterial:S,MeshPhysicalNodeMaterial:S};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,E)),E}var Ui="GOOGLE_material_tsl",Ah=128,Th=16,Ph=3600,Np={positionLocal:"vec3",positionWorld:"vec3",normalLocal:"vec3",normalWorld:"vec3",viewDirection:"vec3",uv:"vec2",vertexColor:"vec4",instanceIndex:"float",time:"float"},Cp={color:"vec3",opacity:"float",emissive:"vec3",roughness:"float",metalness:"float",normalScale:"float",bump:"vec3",position:"vec3"},Ep=new Set(["neg","abs","sign","floor","ceil","fract","sqrt","exp","log","sin","cos","normalize"]),Lp=new Set(["add","sub","mul","div","mod","pow","atan2","min","max"]),Nh={cross:[["vec3","vec3"],"vec3"],fresnel:[["float"],"float"],simplexNoise2D:[["vec2"],"float"],checker:[["vec2"],"float"],simplexNoise3D:[["vec3"],"float"],voronoi2D:[["vec2","float"],"float"],triplanar:[["vec3","float"],"float"],hueShift:[["vec3","float"],"vec3"],bumpFromHeight:[["float","float"],"vec3"]},Rp=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,Ip=new Set(["__proto__","constructor","prototype"]);function Lo(e,t){let r=Math.abs(t)<1e-6?t<0?-1e-6:1e-6:t;return e-r*Math.floor(e/r)}function nr(e){return e==="vec4"?4:e==="vec3"?3:e==="vec2"?2:1}function Ro(e){return e===1?"float":e===2?"vec2":e===3?"vec3":e===4?"vec4":null}function Io(e){return e==="float"||e==="vec2"||e==="vec3"||e==="vec4"}function ht(e,t,r="Use loop-free THREE.TSL expressions on MeshStandardNodeMaterial (<= 128 nodes, <= 16 uniforms)."){return{ok:!1,issue:{code:e,message:t,hint:r}}}function Si(e,t){for(let r=0;r<t.length;r++)e=Math.imul((e^t.charCodeAt(r))>>>0,16777619)>>>0;return e}var Ch=new Float32Array(1),$p=new Uint32Array(Ch.buffer);function Dp(e,t){return Ch[0]=t,Math.imul((e^$p[0])>>>0,16777619)>>>0}function Pa(e,t){let r=nr(e);if(r===1){let n=typeof t=="number"?t:Array.isArray(t)&&t.length===1?Number(t[0]):NaN;return Number.isFinite(n)?[Math.fround(n),0,0,0]:null}if(!Array.isArray(t)&&!(t instanceof Float32Array)||t.length<r)return null;let i=[0,0,0,0];for(let n=0;n<r;n++){let a=Number(t[n]);if(!Number.isFinite(a))return null;i[n]=Math.fround(a)}return i}function Oi(e,t="Material"){if(!e||typeof e!="object"||Array.isArray(e))return ht("TL501",`Invalid GOOGLE_material_tsl on '${t}'.`);let r=e;if(r.version!==1)return ht("TL501",`Unsupported TSL version on '${t}'.`);let i=[],n=new Map,a=r.uniforms;if(a!=null){if(typeof a!="object"||Array.isArray(a))return ht("TL501",`Invalid TSL uniforms on '${t}'.`);let y=a,A=Object.keys(y).sort();if(A.length>16)return ht("TL502",`TSL '${t}' exceeds MAX_TSL_UNIFORMS (16).`);for(let b=0;b<A.length;b++){let w=A[b],S=y[w],E=S&&!Array.isArray(S)?S.type:null,N=Io(E)?Pa(E,S.value):null;if(Ip.has(w)||!Rp.test(w)||!Io(E)||!N)return ht("TL501",`Invalid TSL uniform '${w}' on '${t}'.`);let C={name:w,slot:b,type:E,defaultVec4:N};i.push(C),n.set(w,C)}}let s=r.nodes;if(!Array.isArray(s)||s.length===0)return ht("TL501",`Empty TSL nodes on '${t}'.`);if(s.length>128)return ht("TL502",`TSL '${t}' exceeds MAX_TSL_NODES (128).`);let o=[],l=2166136261;for(let y of i)l=Si(l,`U:${y.slot}:${y.type};`);for(let y=0;y<s.length;y++){let A=s[y];if(!A||typeof A!="object"||Array.isArray(A))return ht("TL501",`Invalid TSL node ${y} on '${t}'.`);let b=A,w=b.op,S=b.type;if(w==="loop"||w==="while"||w==="for"||w==="call")return ht("TL504",`Unsupported loop/call op '${w}' at node ${y} on '${t}'.`);if(typeof w!="string"||!Io(S))return ht("TL501",`Malformed TSL node ${y} on '${t}'.`);let E=w,N=b.args,C=[];if(N!==void 0){if(!Array.isArray(N)||N.length>4)return ht("TL501",`Invalid args at node ${y} on '${t}'.`);for(let P of N){if(typeof P!="number"||!Number.isInteger(P)||P<0||P>=y)return ht("TL501",`Cyclic or out-of-order arg at node ${y} on '${t}'.`);C.push(P)}}l=Si(l,`N${y}:${E}:${S}:`);for(let P of C)l=Si(l,`${P},`);let _=C.map(P=>o[P].type);if(E==="const"){let P=nr(S),R=b.value;if(C.length!==0||!Array.isArray(R)||R.length!==P)return ht("TL501",`Invalid const node ${y} on '${t}'.`);let I=[];for(let F=0;F<P;F++){let V=Number(R[F]);if(!Number.isFinite(V))return ht("TL501",`Non-finite const at node ${y}.`);let Y=Math.fround(V);I.push(Y),l=Dp(l,Y)}o.push({op:E,type:S,args:[],value:I})}else if(E==="builtin"){let P=b.name;if(C.length!==0||typeof P!="string"||Np[P]!==S)return ht("TL501",`Invalid builtin at node ${y}.`);l=Si(l,P),o.push({op:E,type:S,args:[],builtin:P})}else if(E==="uniform"){let P=b.name,R=typeof P=="string"?n.get(P):void 0;if(C.length!==0||!R||R.type!==S)return ht("TL501",`Invalid uniform ref at node ${y}.`);l=Si(l,`S${R.slot}`),o.push({op:E,type:S,args:[],uniformSlot:R.slot})}else if(E==="swizzle"){let P=b.mask;if(C.length!==1||typeof P!="string"||!/^[xyzw]{1,4}$/.test(P)||Ro(P.length)!==S)return ht("TL501",`Invalid swizzle at node ${y}.`);let R=nr(_[0]);for(let I=0;I<P.length;I++)if("xyzw".indexOf(P[I])>=R)return ht("TL501",`Swizzle '.${P}' out of bounds at node ${y}.`);l=Si(l,P),o.push({op:E,type:S,args:C,mask:P})}else if(E==="construct"){let P=nr(S),R=_.reduce((I,F)=>I+nr(F),0);if(C.length===0||!(C.length===1&&_[0]==="float")&&R!==P)return ht("TL501",`Invalid construct at node ${y}.`);o.push({op:E,type:S,args:C})}else if(Ep.has(E)){if(C.length!==1||_[0]!==S)return ht("TL501",`Type mismatch on '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(Lp.has(E)){if((C.length===2?_[0]===_[1]?_[0]:_[0]==="float"?_[1]:_[1]==="float"?_[0]:null:null)!==S)return ht("TL501",`Type mismatch on '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="step"){if(C.length!==2||_[0]!==_[1]&&_[0]!=="float"||S!==_[1])return ht("TL501",`Invalid 'step' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="clamp"){if(!(C.length===3&&S===_[0]&&(_[1]===_[0]&&_[2]===_[0]||_[1]==="float"&&_[2]==="float")))return ht("TL501",`Invalid 'clamp' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="mix"){if(!(C.length===3&&_[0]===_[1]&&S===_[0]&&(_[2]===_[0]||_[2]==="float")))return ht("TL501",`Invalid 'mix' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="smoothstep"){if(!(C.length===3&&S===_[2]&&(_[0]===_[2]&&_[1]===_[2]||_[0]==="float"&&_[1]==="float")))return ht("TL501",`Invalid 'smoothstep' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="dot"||E==="distance"){if(C.length!==2||_[0]!==_[1]||S!=="float")return ht("TL501",`Invalid '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="length"){if(C.length!==1||S!=="float")return ht("TL501",`Invalid 'length' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E==="reflect"){if(C.length!==2||_[0]!==_[1]||_[0]==="float"||S!==_[0])return ht("TL501",`Invalid 'reflect' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E in Nh){let[P,R]=Nh[E];if(C.length!==P.length||S!==R||P.some((I,F)=>_[F]!==I))return ht("TL501",`Invalid '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else return ht("TL501",`Unknown TSL op '${String(E)}' at node ${y}.`)}let c=r.outputs;if(!c||typeof c!="object"||Array.isArray(c))return ht("TL501",`Missing TSL outputs on '${t}'.`);let f=c,m={},h=0;for(let y of Object.keys(f).sort()){let A=Cp[y];if(!A)return ht("TL501",`Unknown TSL socket '${y}' on '${t}'.`);let b=f[y];if(b!=null){if(typeof b!="number"||!Number.isInteger(b)||b<0||b>=o.length||o[b].type!==A)return ht("TL501",`Invalid TSL output '${y}' on '${t}'.`);m[y]=b,h++,l=Si(l,`O:${y}=${b};`)}}if(h===0)return ht("TL501",`No active TSL outputs on '${t}'.`);let p=new Uint8Array(o.length),g=new Uint8Array(o.length);for(let[y,A]of Object.entries(m))y==="position"?g[A]=1:p[A]=1;for(let y=o.length-1;y>=0;y--){if(p[y])for(let A of o[y].args)p[A]=1;if(g[y])for(let A of o[y].args)g[A]=1}let x=!1,v=!1;for(let y=0;y<o.length;y++){let A=o[y];if(g[y]&&(A.op==="builtin"&&A.builtin==="viewDirection"||A.op==="fresnel"||A.op==="bumpFromHeight"))return ht("TL503",`Fragment-only TSL op '${A.builtin||A.op}' used in positionNode on '${t}'.`);(p[y]||g[y])&&(A.op==="builtin"&&A.builtin==="time"&&(x=!0),A.op==="bumpFromHeight"&&(v=!0))}return{ok:!0,graph:{nodes:o,outputs:m,uniformSlots:i,uniformSlotByName:n,hash:(l>>>0).toString(16).padStart(8,"0"),usesTime:x,usesVertexPosition:m.position!==void 0,usesDerivatives:v,fragmentReachable:p,vertexReachable:g}}}function Xr(e){if(!Number.isFinite(e)||e===0)return"0.0";let t=Math.fround(e),r=Math.abs(t);if(r>=1e-4&&r<1e6){let n=Number(t.toPrecision(7)).toString();return n.includes(".")?n:`${n}.0`}let i=t.toExponential(6).split("e");return`${i[0].replace(/(\.\d*?[1-9])0+$/,"$1").replace(/\.0+$/,".0")}e${i[1]}`}function Na(e,t,r){let i={div:!1,mod:r,pow:!1,clamp:!1,smooth:!1,atan2:!1,norm:!1,fresnel:!1,snoise2:!1,snoise3:!1,voronoi2:!1,checker:!1,triplanar:!1,hueShift:!1,bump:!1};for(let n=0;n<e.length;n++)if(t[n])switch(e[n].op){case"div":i.div=!0;break;case"mod":i.mod=!0;break;case"pow":i.pow=!0;break;case"clamp":i.clamp=!0;break;case"smoothstep":i.smooth=!0,i.div=!0,i.clamp=!0;break;case"atan2":i.atan2=!0;break;case"normalize":i.norm=!0;break;case"fresnel":i.fresnel=!0,i.pow=!0,i.norm=!0;break;case"simplexNoise2D":i.snoise2=!0;break;case"simplexNoise3D":i.snoise3=!0;break;case"voronoi2D":i.voronoi2=!0;break;case"checker":i.checker=!0,i.mod=!0;break;case"triplanar":i.triplanar=!0,i.snoise2=!0,i.pow=!0,i.norm=!0;break;case"hueShift":i.hueShift=!0;break;case"bumpFromHeight":i.bump=!0,i.norm=!0;break;default:break}return i}var kp=["x","y","z","w"],Eh=[[2,"vec2"],[3,"vec3"],[4,"vec4"]];function ji(e,t){return Eh.map(([r,i])=>{let n=kp.slice(0,r).map(a=>t===2?`${e}(a.${a},b.${a})`:`${e}(a.${a},b.${a},c.${a})`).join(",");return t===2?`${i} ${e}(${i} a,${i} b){return ${i}(${n});}`:`${i} ${e}(${i} a,${i} b,${i} c){return ${i}(${n});}`})}function Lh(e,t){let r=[];return e.div&&r.push("float _tslDiv(float a,float b){return a/(abs(b)<1e-6?(b<0.0?-1e-6:1e-6):b);}",...ji("_tslDiv",2)),e.mod&&r.push("float _tslMod(float a,float b){float d=abs(b)<1e-6?(b<0.0?-1e-6:1e-6):b;return a-d*floor(a/d);}",...ji("_tslMod",2)),e.pow&&r.push("float _tslPow(float a,float b){float e=clamp(b,-64.0,64.0);return abs(e)<1e-8?1.0:(a<=0.0?0.0:pow(max(a,1e-8),e));}",...ji("_tslPow",2)),e.clamp&&r.push("float _tslClamp(float a,float b,float c){return clamp(a,min(b,c),max(b,c));}",...ji("_tslClamp",3)),e.smooth&&r.push("float _tslSmooth(float a,float b,float c){float t=_tslClamp(_tslDiv(c-a,b-a),0.0,1.0);return t*t*(3.0-2.0*t);}",...ji("_tslSmooth",3)),e.atan2&&r.push("float _tslAtan2(float a,float b){return(abs(a)<1e-8&&abs(b)<1e-8)?0.0:atan(a,b);}",...ji("_tslAtan2",2)),e.norm&&r.push("float _tslNorm(float v){return abs(v)>1e-6?sign(v):0.0;}",...Eh.map(([,i])=>`${i} _tslNorm(${i} v){float l=length(v);return l>1e-6?v/l:${i}(0.0);}`)),(e.snoise2||e.snoise3||e.voronoi2)&&r.push("float _tslM289(float x){return x-floor(x*(1.0/289.0))*289.0;}","float _tslPerm(float x){return _tslM289((x*34.0+10.0)*x);}"),e.snoise2&&r.push("float _tslSNoise2(vec2 v){const float c0=0.21132487,c1=0.3660254,c2=-0.57735026,c3=0.024390243;float s=(v.x+v.y)*c1,ix=floor(v.x+s),iy=floor(v.y+s),t=(ix+iy)*c0,x0=v.x-ix+t,y0=v.y-iy+t,i1x=x0>y0?1.0:0.0,i1y=1.0-i1x,x1=x0+c0-i1x,y1=y0+c0-i1y,x2=x0+c2,y2=y0+c2;ix=_tslM289(ix);iy=_tslM289(iy);float p0=_tslPerm(_tslPerm(iy)+ix),p1=_tslPerm(_tslPerm(iy+i1y)+ix+i1x),p2=_tslPerm(_tslPerm(iy+1.0)+ix+1.0);vec3 m=max(0.5-vec3(x0*x0+y0*y0,x1*x1+y1*y1,x2*x2+y2*y2),0.0);m=m*m;m=m*m;vec3 gx=2.0*fract(vec3(p0,p1,p2)*c3)-1.0,hy=abs(gx)-0.5,ox=gx-floor(gx+0.5);m*=1.7928429-0.85373473*(ox*ox+hy*hy);return clamp(0.5+65.0*dot(m,ox*vec3(x0,x1,x2)+hy*vec3(y0,y1,y2)),0.0,1.0);}"),e.snoise3&&r.push("float _tslSNoise3(vec3 v){const float c0=0.16666667,c1=0.33333334,ns=0.14285715;float s=(v.x+v.y+v.z)*c1,i0=floor(v.x+s),i1=floor(v.y+s),i2=floor(v.z+s),t=(i0+i1+i2)*c0;vec3 p0=v-vec3(i0,i1,i2)+t,g=step(p0.yzx,p0.xyz),l=1.0-g.zxy,a1=min(g,l),a2=max(g,l),p1=p0-a1+c0,p2=p0-a2+c1,p3=p0-0.5;i0=_tslM289(i0);i1=_tslM289(i1);i2=_tslM289(i2);vec4 hs=vec4(_tslPerm(_tslPerm(_tslPerm(i2)+i1)+i0),_tslPerm(_tslPerm(_tslPerm(i2+a1.z)+i1+a1.y)+i0+a1.x),_tslPerm(_tslPerm(_tslPerm(i2+a2.z)+i1+a2.y)+i0+a2.x),_tslPerm(_tslPerm(_tslPerm(i2+1.0)+i1+1.0)+i0+1.0));float sum=0.0;for(int k=0;k<4;k++){float pk=hs[k],j=pk-49.0*floor(pk*ns*ns),x_=floor(j*ns),y_=floor(j-7.0*x_),gx=x_*(2.0/7.0)+(1.0/7.0)-1.0,gy=y_*(2.0/7.0)+(1.0/7.0)-1.0,gz=1.0-abs(gx)-abs(gy),sz=gz<0.0?1.0:0.0;gx-=sz*(gx>=0.0?1.0:-1.0);gy-=sz*(gy>=0.0?1.0:-1.0);float inv=1.7928429-0.85373473*(gx*gx+gy*gy+gz*gz);vec3 q=k==0?p0:(k==1?p1:(k==2?p2:p3));float m=max(0.6-dot(q,q),0.0);m=m*m;m=m*m;sum+=m*inv*(gx*q.x+gy*q.y+gz*q.z);}return clamp(0.5+21.0*sum,0.0,1.0);}"),e.voronoi2&&r.push("float _tslVoronoi2(vec2 u,float jit){vec2 n=floor(u),fr=u-n;float jt=clamp(jit,0.0,1.0),md=8.0;for(int dy=-1;dy<=1;dy++)for(int dx=-1;dx<=1;dx++){float qx=_tslM289(n.x+float(dx)),qy=_tslM289(n.y+float(dy)),hx=fract(_tslPerm(_tslPerm(qx)+qy)*(1.0/41.0)),hy=fract(_tslPerm(_tslPerm(qy+7.0)+qx+13.0)*(1.0/41.0));md=min(md,length(vec2(float(dx),float(dy))+0.5+(vec2(hx,hy)-0.5)*jt-fr));}return clamp(md,0.0,1.0);}"),e.checker&&r.push("float _tslChecker(vec2 p){return _tslMod(floor(p.x)+floor(p.y),2.0)>=1.0?1.0:0.0;}"),e.fresnel&&r.push("float _tslFresnel(float pw,vec3 nw,vec3 vd){return _tslPow(1.0-clamp(dot(_tslNorm(nw),_tslNorm(vd)),0.0,1.0),max(pw,1e-3));}"),e.triplanar&&r.push("float _tslTriplanar(vec3 p,float sh,vec3 nw){vec3 w=_tslPow(max(abs(_tslNorm(nw)),vec3(1e-4)),vec3(clamp(sh,0.5,16.0)));return(w.x*_tslSNoise2(p.yz)+w.y*_tslSNoise2(p.xz)+w.z*_tslSNoise2(p.xy))/max(w.x+w.y+w.z,1e-6);}"),e.hueShift&&r.push("vec3 _tslHueShift(vec3 rgb,float ang){const vec3 k=vec3(0.57735026);float c=cos(ang),s=sin(ang);return rgb*c+cross(k,rgb)*s+k*dot(k,rgb)*(1.0-c);}"),e.bump&&t&&r.push("vec3 _tslBump(float h,float st,vec3 nw,vec3 wp){vec3 n=_tslNorm(nw),dx=dFdx(wp),dy=dFdy(wp),r1=cross(dy,n),r2=cross(n,dx);float det=dot(dx,r1);return abs(det)<1e-8?n:_tslNorm(abs(det)*n-st*(det<0.0?-1.0:1.0)*(dFdx(h)*r1+dFdy(h)*r2));}"),r.join(`
352
+ `)}var Fp={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function Rh(e,t){let r=[],i=(a,s)=>a==="float"?s:`${a}(${s})`,n=(a,s,o)=>s===o?a:`${o}(${a})`;for(let a=0;a<e.length;a++){if(!t[a])continue;let s=e[a],o=s.type,l=s.args[0]!==void 0?`_t${s.args[0]}`:"",c=s.args[1]!==void 0?`_t${s.args[1]}`:"",f=s.args[2]!==void 0?`_t${s.args[2]}`:"",m=s.args[0]!==void 0?e[s.args[0]].type:"float",h=s.args[1]!==void 0?e[s.args[1]].type:"float",p=s.args[2]!==void 0?e[s.args[2]].type:"float",g=i(o,"0.0");switch(s.op){case"const":{let x=(s.value??[0]).map(Xr);g=o==="float"?x[0]:`${o}(${x.join(",")})`;break}case"builtin":g=s.builtin==="time"?`_tslMod(uTslTime,${Xr(3600)})`:Fp[s.builtin]??"0.0";break;case"uniform":{let x=`uTslParams[${s.uniformSlot??0}]`,v=nr(o);g=v===4?x:`${x}.${"xyz".slice(0,v)}`;break}case"swizzle":g=m==="float"?i(o,l):`${l}.${s.mask}`;break;case"construct":g=o==="float"?l:`${o}(${s.args.map(x=>`_t${x}`).join(",")})`;break;case"neg":g=`(-${l})`;break;case"abs":case"sign":case"floor":case"ceil":case"fract":case"sin":case"cos":g=`${s.op}(${l})`;break;case"sqrt":g=`sqrt(max(${l},${i(o,"0.0")}))`;break;case"exp":g=`exp(clamp(${l},${i(o,"-80.0")},${i(o,"80.0")}))`;break;case"log":g=`log(max(${l},${i(o,"1.0e-8")}))`;break;case"normalize":g=`_tslNorm(${l})`;break;case"add":case"sub":case"mul":{let x=s.op==="add"?"+":s.op==="sub"?"-":"*";g=`(${n(l,m,o)}${x}${n(c,h,o)})`;break}case"div":case"mod":case"pow":case"atan2":{g=`${s.op==="div"?"_tslDiv":s.op==="mod"?"_tslMod":s.op==="pow"?"_tslPow":"_tslAtan2"}(${n(l,m,o)},${n(c,h,o)})`;break}case"min":case"max":case"step":g=`${s.op}(${n(l,m,o)},${n(c,h,o)})`;break;case"clamp":g=`_tslClamp(${n(l,m,o)},${n(c,h,o)},${n(f,p,o)})`;break;case"mix":g=`mix(${l},${c},${n(f,p,o)})`;break;case"smoothstep":g=`_tslSmooth(${n(l,m,o)},${n(c,h,o)},${n(f,p,o)})`;break;case"dot":g=m==="float"?`(${l}*${c})`:`dot(${l},${c})`;break;case"length":g=m==="float"?`abs(${l})`:`length(${l})`;break;case"distance":g=m==="float"?`abs(${l}-${c})`:`distance(${l},${c})`;break;case"cross":case"reflect":g=`${s.op}(${l},${c})`;break;case"fresnel":g=`_tslFresnel(${l},_tslNW,_tslVD)`;break;case"simplexNoise2D":g=`_tslSNoise2(${l})`;break;case"simplexNoise3D":g=`_tslSNoise3(${l})`;break;case"voronoi2D":g=`_tslVoronoi2(${l},${c})`;break;case"checker":g=`_tslChecker(${l})`;break;case"triplanar":g=`_tslTriplanar(${l},${c},_tslNW)`;break;case"hueShift":g=`_tslHueShift(${l},${c})`;break;case"bumpFromHeight":g=`_tslBump(${l},${c},_tslNW,_tslPW)`;break;default:break}r.push(`${o} _t${a}=${g};`)}return r.join(`
353
+ `)}function $o(e,t,r){let i=`uniform vec4 uTslParams[16];
354
+ uniform float uTslTime;`,n=e.fragmentReachable.some(l=>l===1),a=t.replace("out vec2 vUV;",`${i}
355
+ out vec2 vUV;
356
+ out vec3 vTslLP,vTslLN;
357
+ flat out float vTslII;`),s=a.includes("morphedPos")?"morphedPos":"aPosition";if(e.usesVertexPosition&&e.outputs.position!==void 0){let l=Lh(Na(e.nodes,e.vertexReachable,e.usesTime),!1),c=Rh(e.nodes,e.vertexReachable),f=`${l}
358
+ vec3 _tslEvalPos(vec3 _tslPL,vec3 _tslNL,vec2 _tslUV,vec4 _tslVC,float _tslII,mat4 _m,mat3 _nm){
359
+ vec3 _tslPW=(_m*vec4(_tslPL,1.0)).xyz,_rn=_nm*_tslNL,_tslNW=length(_rn)>1e-5?normalize(_rn):vec3(0.0,1.0,0.0),_tslVD=vec3(0.0,0.0,1.0);
360
+ ${c}
361
+ return _t${e.outputs.position};}`;a=a.replace("void main(){",`${f}
362
+ void main(){`);let m=`vec2 _tslScUV=uUvTransform.zw;if(_tslScUV.x==0.0&&_tslScUV.y==0.0)_tslScUV=vec2(1.0);vec2 _tslVtxUV=aUV*_tslScUV+uUvTransform.xy;
363
+ float _tslInstF=float(gl_InstanceID);vec3 _tslBaseP=${s},_tslNewP=_tslEvalPos(_tslBaseP,aNormal,_tslVtxUV,vInstTint,_tslInstF,uModel,uNormalMatrix),_tslNewN=aNormal;
364
+ if(length(aNormal)>1e-4){vec3 _n0=normalize(aNormal),_tg1=normalize(abs(_n0.y)<0.99?cross(vec3(0.0,1.0,0.0),_n0):cross(vec3(1.0,0.0,0.0),_n0)),_tg2=cross(_n0,_tg1),_cn=cross(_tslEvalPos(_tslBaseP+_tg1*1e-3,aNormal,_tslVtxUV,vInstTint,_tslInstF,uModel,uNormalMatrix)-_tslNewP,_tslEvalPos(_tslBaseP+_tg2*1e-3,aNormal,_tslVtxUV,vInstTint,_tslInstF,uModel,uNormalMatrix)-_tslNewP);if(length(_cn)>1e-10)_tslNewN=normalize(_cn);}
365
+ vTslLP=_tslNewP;vTslLN=_tslNewN;vTslII=_tslInstF;vec3 _rnDisp=uNormalMatrix*_tslNewN;vNormal=length(_rnDisp)>1e-5?normalize(_rnDisp):vec3(0.0);`;a.includes(`vec4 world=uModel*(skinMatrix*vec4(${s},1.0));`)?a=a.replace(`vec4 world=uModel*(skinMatrix*vec4(${s},1.0));`,`${m}
366
+ vec4 world=uModel*(skinMatrix*vec4(_tslNewP,1.0));`).replace(`gl_Position=uMVP*(skinMatrix*vec4(${s},1.0));`,"gl_Position=uMVP*(skinMatrix*vec4(_tslNewP,1.0));"):a=a.replace(`vec4 world=uModel*vec4(${s},1.0);`,`${m}
367
+ vec4 world=uModel*vec4(_tslNewP,1.0);`).replace(`gl_Position=uMVP*vec4(${s},1.0);`,"gl_Position=uMVP*vec4(_tslNewP,1.0);")}else a=a.replace("gl_Position=",`vTslLP=${s};vTslLN=aNormal;vTslII=float(gl_InstanceID);
368
+ gl_Position=`);let o=r.replace("in vec2 vUV;",`${i}
369
+ in vec2 vUV;
370
+ in vec3 vTslLP,vTslLN;
371
+ flat in float vTslII;`);if(n){let l=Lh(Na(e.nodes,e.fragmentReachable,e.usesTime),!0),c=Rh(e.nodes,e.fragmentReachable);l&&(o=o.replace("void main(){",`${l}
372
+ void main(){`)),e.outputs.opacity!==void 0&&(o=o.replace("if(base.a<0.004)discard;","")),o=o.replace("if(length(vNormal)<1e-4&&uHasTexture==1){","if(false&&length(vNormal)<1e-4&&uHasTexture==1){");let f=[];if(e.outputs.color!==void 0&&f.push(`base.rgb=max(_t${e.outputs.color},vec3(0.0))*vInstTint.rgb;`),e.outputs.opacity!==void 0&&f.push(`base.a=clamp(_t${e.outputs.opacity},0.0,1.0)*vInstTint.a;`,"if(base.a<0.004)discard;"),e.outputs.emissive!==void 0&&f.push(`em=max(_t${e.outputs.emissive},vec3(0.0));`),e.outputs.roughness!==void 0&&f.push(`roughness=clamp(_t${e.outputs.roughness},0.04,1.0);`),e.outputs.metalness!==void 0&&f.push(`metallic=clamp(_t${e.outputs.metalness},0.0,1.0);`),e.outputs.normalScale!==void 0&&e.outputs.bump===void 0&&(o=o.replace("if(uHasNormalTexture==1){",`vec3 _tslBaseN=N;
373
+ if(uHasNormalTexture==1){`),f.push(`if(uHasNormalTexture==1){N=perturbNormal(_tslBaseN,V,vUV,uNormalTexture,max(_t${e.outputs.normalScale},0.0));}`)),e.outputs.bump!==void 0){let m=e.outputs.normalScale!==void 0?`max(_t${e.outputs.normalScale},0.0)`:"1.0";f.push(`{vec3 _bn=_t${e.outputs.bump};float _bl=length(_bn);if(_bl>1e-6){vec3 _bm=N+(_bn/_bl-N)*(${m});float _ml=length(_bm);if(_ml>1e-6)N=_bm/_ml;}}`)}o=o.replace("metallic=clamp(metallic,0.0,1.0);",`metallic=clamp(metallic,0.0,1.0);
374
+ {vec3 _tslPL=vTslLP,_tslPW=vWorldPos,_tslNL=length(vTslLN)>1e-5?normalize(vTslLN):vec3(0.0,1.0,0.0),_tslNW=N,_tslVD=V;vec2 _tslUV=vUV;vec4 _tslVC=vInstTint;float _tslII=vTslII;
375
+ ${c}
376
+ ${f.join(`
377
+ `)}}`)}return{vs:a,fs:o}}var Bp={float:"float",vec2:"float2",vec3:"float3",vec4:"float4"},zp={float:"float",vec2:"vector2",vec3:"vector3",vec4:"vector4"};function gr(e){return Bp[e]||"float"}function ui(e){return zp[e]||"float"}function $n(e,t){if(t===1)return Xr(e[0]??0);let r=[];for(let i=0;i<t;i++)r.push(Xr(e[i]??0));return`(${r.join(", ")})`}function Do(e,t,r=""){let i;if(e&&typeof e=="object"&&"fragmentReachable"in e)i=e;else{let w=Oi(e,t);if(!w.ok)return null;i=w.graph}if(!i.fragmentReachable.some(w=>w===1))return null;let n=`/Root/Materials/${(t||"Material").replace(/[^A-Za-z0-9_]/g,"_").replace(/^([0-9])/,"_$1")||"Material"}/TSLGraph`,a=[],s=[],o=0;for(let w of i.uniformSlots){let S=gr(w.type),E=nr(w.type);s.push(`${S} inputs:u_${w.slot} = ${$n(w.defaultVec4,E)}`)}let l=(w,S,E,N)=>(a.push(`def Shader "${w}"
365
378
  {
366
- ${y.body}${u(g)}${h(g)}${y.tail}}
367
- `}}return o+=`}
379
+ uniform token info:id = "${S}"
380
+ ${N.join(`
381
+ `)}${N.length>0?`
382
+ `:""}${E} outputs:out
383
+ }`),`${n}/${w}.outputs:out`),c=(w,S)=>{let E=nr(w),N=`C_${o++}`;return l(N,`ND_constant_${ui(w)}`,gr(w),[`${gr(w)} inputs:value = ${$n(S,E)}`])},f=(w,S)=>{if(S==="float")return w;let E=nr(S),N=`B_${o++}`,C=[];for(let _=1;_<=E;_++)C.push(`float inputs:in${_}.connect = <${w}>`);return l(N,`ND_combine${E}_${ui(S)}`,gr(S),C)},m=(w,S,E)=>S===E?w:f(w,E),h=(w,S,E)=>{if(S==="float")return w;let N=`E_${o++}`;return l(N,`ND_extract_${ui(S)}`,"float",[`${gr(S)} inputs:in.connect = <${w}>`,`int inputs:index = ${E}`])},p=new Map,g=w=>{let S=p.get(w);if(S)return S;let E="";switch(w){case"positionLocal":E=l("BI_posLocal","ND_position_vector3","float3",['string inputs:space = "object"']);break;case"positionWorld":E=l("BI_posWorld","ND_position_vector3","float3",['string inputs:space = "world"']);break;case"normalLocal":E=l("BI_normLocal","ND_normal_vector3","float3",['string inputs:space = "object"']);break;case"normalWorld":E=l("BI_normWorld","ND_normal_vector3","float3",['string inputs:space = "world"']);break;case"viewDirection":{let N=l("BI_rawView","ND_viewdirection_vector3","float3",['string inputs:space = "world"']);E=l("BI_viewDir","ND_multiply_vector3FA","float3",[`float3 inputs:in1.connect = <${N}>`,"float inputs:in2 = -1.0"]);break}case"uv":E=l("BI_uv","ND_texcoord_vector2","float2",["int inputs:index = 0"]);break;case"vertexColor":{let N=l("BI_vcCol","ND_geomcolor_color4","color4f",["int inputs:index = 0"]);E=l("BI_vcVec","ND_convert_color4_vector4","float4",[`color4f inputs:in.connect = <${N}>`]);break}case"instanceIndex":E=c("float",[0]);break;case"time":{let N=l("BI_rawTime","ND_time_float","float",[]);E=l("BI_time","ND_modulo_float","float",[`float inputs:in1.connect = <${N}>`,`float inputs:in2 = ${Xr(3600)}`]);break}default:E=c("float",[0]);break}return p.set(w,E),E},x=new Array(i.nodes.length).fill("");for(let w=0;w<i.nodes.length;w++){if(!i.fragmentReachable[w])continue;let S=i.nodes[w],E=S.type,N=gr(E),C=ui(E),_=nr(E),P=S.args[0]!==void 0?x[S.args[0]]:"",R=S.args[1]!==void 0?x[S.args[1]]:"",I=S.args[2]!==void 0?x[S.args[2]]:"",F=S.args[0]!==void 0?i.nodes[S.args[0]].type:"float",V=S.args[1]!==void 0?i.nodes[S.args[1]].type:"float",Y=S.args[2]!==void 0?i.nodes[S.args[2]].type:"float",J=`N${w}`;switch(S.op){case"const":x[w]=l(J,`ND_constant_${C}`,N,[`${N} inputs:value = ${$n(S.value??[0],_)}`]);break;case"builtin":x[w]=g(S.builtin??"time");break;case"uniform":x[w]=`${n}.inputs:u_${S.uniformSlot??0}`;break;case"swizzle":{let re=S.mask??"x";if(F==="float")x[w]=f(P,E);else if(re.length===1)x[w]=h(P,F,"xyzw".indexOf(re[0]));else{let Q=Array.from(re).map(ee=>h(P,F,"xyzw".indexOf(ee)));x[w]=l(J,`ND_combine${re.length}_${C}`,N,Q.map((ee,k)=>`float inputs:in${k+1}.connect = <${ee}>`))}break}case"construct":{if(E==="float")x[w]=P;else if(S.args.length===1&&F==="float")x[w]=f(P,E);else{let re=[];for(let Q of S.args){let ee=i.nodes[Q].type,k=x[Q],G=nr(ee);if(G===1)re.push(k);else for(let q=0;q<G;q++)re.push(h(k,ee,q))}x[w]=l(J,`ND_combine${_}_${C}`,N,re.slice(0,_).map((Q,ee)=>`float inputs:in${ee+1}.connect = <${Q}>`))}break}case"neg":{x[w]=l(J,`ND_multiply_${C}`,N,[`${N} inputs:in1.connect = <${P}>`,`${N} inputs:in2 = ${$n([-1,-1,-1,-1],_)}`]);break}case"abs":case"sign":case"floor":case"ceil":case"sqrt":case"exp":case"sin":case"cos":case"normalize":{let re=S.op==="abs"?"absval":S.op;S.op==="normalize"&&E==="float"?x[w]=l(J,"ND_sign_float","float",[`float inputs:in.connect = <${P}>`]):x[w]=l(J,`ND_${re}_${C}`,N,[`${N} inputs:in.connect = <${P}>`]);break}case"log":x[w]=l(J,`ND_ln_${C}`,N,[`${N} inputs:in.connect = <${P}>`]);break;case"fract":{x[w]=l(J,`ND_modulo_${C}`,N,[`${N} inputs:in1.connect = <${P}>`,`${N} inputs:in2 = ${$n([1,1,1,1],_)}`]);break}case"add":case"sub":case"mul":case"div":case"mod":case"pow":case"atan2":case"min":case"max":{let re={add:"add",sub:"subtract",mul:"multiply",div:"divide",mod:"modulo",pow:"power",atan2:"atan2",min:"min",max:"max"},Q=m(P,F,E),ee=m(R,V,E);x[w]=l(J,`ND_${re[S.op]}_${C}`,N,[`${N} inputs:in1.connect = <${Q}>`,`${N} inputs:in2.connect = <${ee}>`]);break}case"step":{let re=m(P,F,E);if(E==="float")x[w]=l(J,"ND_ifgreater_float","float",[`float inputs:value1.connect = <${R}>`,`float inputs:value2.connect = <${re}>`,"float inputs:in1 = 1.0","float inputs:in2 = 0.0"]);else{let Q=[];for(let ee=0;ee<_;ee++){let k=h(re,E,ee),G=h(R,E,ee);Q.push(l(`S_${o++}`,"ND_ifgreater_float","float",[`float inputs:value1.connect = <${G}>`,`float inputs:value2.connect = <${k}>`,"float inputs:in1 = 1.0","float inputs:in2 = 0.0"]))}x[w]=l(J,`ND_combine${_}_${C}`,N,Q.map((ee,k)=>`float inputs:in${k+1}.connect = <${ee}>`))}break}case"clamp":{let re=m(R,V,E),Q=m(I,Y,E);x[w]=l(J,`ND_clamp_${C}`,N,[`${N} inputs:in.connect = <${P}>`,`${N} inputs:low.connect = <${re}>`,`${N} inputs:high.connect = <${Q}>`]);break}case"mix":{let re=m(I,Y,E);x[w]=l(J,`ND_mix_${C}`,N,[`${N} inputs:bg.connect = <${P}>`,`${N} inputs:fg.connect = <${R}>`,`${N} inputs:mix.connect = <${re}>`]);break}case"smoothstep":{let re=m(P,F,E),Q=m(R,V,E);x[w]=l(J,`ND_smoothstep_${C}`,N,[`${N} inputs:in.connect = <${I}>`,`${N} inputs:low.connect = <${re}>`,`${N} inputs:high.connect = <${Q}>`]);break}case"dot":F==="float"?x[w]=l(J,"ND_multiply_float","float",[`float inputs:in1.connect = <${P}>`,`float inputs:in2.connect = <${R}>`]):x[w]=l(J,`ND_dotproduct_${ui(F)}`,"float",[`${gr(F)} inputs:in1.connect = <${P}>`,`${gr(F)} inputs:in2.connect = <${R}>`]);break;case"length":F==="float"?x[w]=l(J,"ND_absval_float","float",[`float inputs:in.connect = <${P}>`]):x[w]=l(J,`ND_magnitude_${ui(F)}`,"float",[`${gr(F)} inputs:in.connect = <${P}>`]);break;case"distance":{let re=l(`D_${o++}`,`ND_subtract_${ui(F)}`,gr(F),[`${gr(F)} inputs:in1.connect = <${P}>`,`${gr(F)} inputs:in2.connect = <${R}>`]);x[w]=F==="float"?l(J,"ND_absval_float","float",[`float inputs:in.connect = <${re}>`]):l(J,`ND_magnitude_${ui(F)}`,"float",[`${gr(F)} inputs:in.connect = <${re}>`]);break}case"cross":x[w]=l(J,"ND_crossproduct_vector3","float3",[`float3 inputs:in1.connect = <${P}>`,`float3 inputs:in2.connect = <${R}>`]);break;case"reflect":if(E==="vec3")x[w]=l(J,"ND_reflect_vector3","float3",[`float3 inputs:in.connect = <${P}>`,`float3 inputs:normal.connect = <${R}>`]);else{let re=E==="float"?l(`RF_${o++}`,"ND_multiply_float","float",[`float inputs:in1.connect = <${R}>`,`float inputs:in2.connect = <${P}>`]):l(`RF_${o++}`,`ND_dotproduct_${C}`,"float",[`${N} inputs:in1.connect = <${R}>`,`${N} inputs:in2.connect = <${P}>`]),Q=l(`RF_${o++}`,"ND_multiply_float","float",[`float inputs:in1.connect = <${re}>`,"float inputs:in2 = 2.0"]),ee=l(`RF_${o++}`,`ND_multiply_${C}`,N,[`${N} inputs:in1.connect = <${R}>`,`${N} inputs:in2.connect = <${m(Q,"float",E)}>`]);x[w]=l(J,`ND_subtract_${C}`,N,[`${N} inputs:in1.connect = <${P}>`,`${N} inputs:in2.connect = <${ee}>`])}break;case"fresnel":{let re=g("normalWorld"),Q=g("viewDirection"),ee=l(`FR_${o++}`,"ND_dotproduct_vector3","float",[`float3 inputs:in1.connect = <${re}>`,`float3 inputs:in2.connect = <${Q}>`]),k=l(`FR_${o++}`,"ND_clamp_float","float",[`float inputs:in.connect = <${ee}>`,"float inputs:low = 0.0","float inputs:high = 1.0"]),G=l(`FR_${o++}`,"ND_subtract_float","float",["float inputs:in1 = 1.0",`float inputs:in2.connect = <${k}>`]);x[w]=l(J,"ND_power_float","float",[`float inputs:in1.connect = <${G}>`,`float inputs:in2.connect = <${P}>`]);break}case"simplexNoise2D":x[w]=l(J,"ND_noise2d_float","float",[`float2 inputs:texcoord.connect = <${P}>`,"float inputs:amplitude = 0.5","float inputs:pivot = 0.5"]);break;case"simplexNoise3D":x[w]=l(J,"ND_noise3d_float","float",[`float3 inputs:position.connect = <${P}>`,"float inputs:amplitude = 0.5","float inputs:pivot = 0.5"]);break;case"voronoi2D":x[w]=l(J,"ND_cellnoise2d_float","float",[`float2 inputs:texcoord.connect = <${P}>`]);break;case"checker":{let re=l(`CK_${o++}`,"ND_floor_vector2","float2",[`float2 inputs:in.connect = <${P}>`]),Q=h(re,"vec2",0),ee=h(re,"vec2",1),k=l(`CK_${o++}`,"ND_add_float","float",[`float inputs:in1.connect = <${Q}>`,`float inputs:in2.connect = <${ee}>`]),G=l(`CK_${o++}`,"ND_modulo_float","float",[`float inputs:in1.connect = <${k}>`,"float inputs:in2 = 2.0"]);x[w]=l(J,"ND_ifgreater_float","float",[`float inputs:value1.connect = <${G}>`,"float inputs:value2 = 0.999","float inputs:in1 = 1.0","float inputs:in2 = 0.0"]);break}case"triplanar":x[w]=l(J,"ND_noise3d_float","float",[`float3 inputs:position.connect = <${P}>`,"float inputs:amplitude = 0.5","float inputs:pivot = 0.5"]);break;case"hueShift":{let re=l(`HS_${o++}`,"ND_convert_vector3_color3","color3f",[`float3 inputs:in.connect = <${P}>`]),Q=l(`HS_${o++}`,"ND_multiply_float","float",[`float inputs:in1.connect = <${R}>`,"float inputs:in2 = 0.15915494"]),ee=l(`HS_${o++}`,"ND_combine3_vector3","float3",[`float inputs:in1.connect = <${Q}>`,"float inputs:in2 = 1.0","float inputs:in3 = 1.0"]),k=l(`HS_${o++}`,"ND_hsvadjust_color3","color3f",[`color3f inputs:in.connect = <${re}>`,`float3 inputs:amount.connect = <${ee}>`]);x[w]=l(J,"ND_convert_color3_vector3","float3",[`color3f inputs:in.connect = <${k}>`]);break}case"bumpFromHeight":{x[w]=l(J,"ND_heighttonormal_vector3","float3",[`float inputs:in.connect = <${P}>`,`float inputs:scale.connect = <${R}>`]);break}default:x[w]=c(E,[0,0,0,0]);break}}let v=[],y={};if(i.outputs.color!==void 0){let w=l("OUT_color","ND_convert_vector3_color3","color3f",[`float3 inputs:in.connect = <${x[i.outputs.color]}>`]);v.push(`color3f outputs:diffuseColor.connect = <${w}>`),y.diffuseColor=`${n}.outputs:diffuseColor`}if(i.outputs.emissive!==void 0){let w=l("OUT_emissive","ND_convert_vector3_color3","color3f",[`float3 inputs:in.connect = <${x[i.outputs.emissive]}>`]);v.push(`color3f outputs:emissiveColor.connect = <${w}>`),y.emissiveColor=`${n}.outputs:emissiveColor`}if(i.outputs.opacity!==void 0&&(v.push(`float outputs:opacity.connect = <${x[i.outputs.opacity]}>`),y.opacity=`${n}.outputs:opacity`),i.outputs.roughness!==void 0&&(v.push(`float outputs:roughness.connect = <${x[i.outputs.roughness]}>`),y.roughness=`${n}.outputs:roughness`),i.outputs.metalness!==void 0&&(v.push(`float outputs:metallic.connect = <${x[i.outputs.metalness]}>`),y.metallic=`${n}.outputs:metallic`),i.outputs.bump!==void 0&&(v.push(`normal3f outputs:normal.connect = <${x[i.outputs.bump]}>`),y.normal=`${n}.outputs:normal`),v.length===0)return null;let A=[["diffuseColor","color3f"],["metallic","float"],["roughness","float"],["opacity","float"],["emissiveColor","color3f"],["normal","normal3f"]],b=r;for(let[w,S]of A){let E=y[w];if(!E)continue;let N=`${S} inputs:${w}.connect = <${E}>`,C=new RegExp(`^${S}\\s+inputs:${w}[^
384
+ ]*$`,"m");C.test(b)?b=b.replace(C,N):b+=`${b.endsWith(`
385
+ `)||!b?"":`
386
+ `}${N}
387
+ `}return{nodeGraphUsda:`def NodeGraph "TSLGraph"
388
+ {
389
+ ${[...s,...v,...a].join(`
390
+ `)}
368
391
  }
369
- `,o}var Ur=null;function Xi(e){if(!Ur){Ur=new Uint32Array(256);for(let r=0;r<256;r++){let i=r;for(let n=0;n<8;n++)i=i&1?3988292384^i>>>1:i>>>1;Ur[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=Ur[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function bl(e){let t=[],r=0,i=[];for(let h of e){let m=ji(h.filename),c=Xi(h.data),d=h.data.length,f=30+m.length,g=(r+f)%64,x=g!==0?64-g:0;x>0&&x<4&&(x+=64);let b=new Uint8Array(f+x),v=new DataView(b.buffer);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint32(14,c,!0),v.setUint32(18,d,!0),v.setUint32(22,d,!0),v.setUint16(26,m.length,!0),v.setUint16(28,x,!0),b.set(m,30),x>=4&&(v.setUint16(f,6534,!0),v.setUint16(f+2,x-4,!0)),t.push({offset:r,size:d,crc:c,filenameBytes:m,entry:h}),i.push(b,h.data),r+=b.length+h.data.length}let n=r;for(let h of t){let m=new Uint8Array(46+h.filenameBytes.length),c=new DataView(m.buffer);c.setUint32(0,33639248,!0),c.setUint16(4,20,!0),c.setUint16(6,20,!0),c.setUint32(16,h.crc,!0),c.setUint32(20,h.size,!0),c.setUint32(24,h.size,!0),c.setUint16(28,h.filenameBytes.length,!0),c.setUint32(42,h.offset,!0),m.set(h.filenameBytes,46),i.push(m),r+=m.length}let s=r-n,l=new Uint8Array(22),o=new DataView(l.buffer);o.setUint32(0,101010256,!0),o.setUint16(8,t.length,!0),o.setUint16(10,t.length,!0),o.setUint32(12,s,!0),o.setUint32(16,n,!0),i.push(l),r+=22;let a=new Uint8Array(r),u=0;for(let h of i)a.set(h,u),u+=h.length;return a}function da(e){let t=[{filename:"model.usda",data:ji(yl(e))}],r=new Set(["model.usda"]),i=[...e];for(;i.length>0;){let n=i.pop();for(let s of n.textures||[])s?.file&&s.data?.byteLength&&!r.has(s.file)&&(r.add(s.file),t.push({filename:s.file,data:s.data}));if(n.children)for(let s=n.children.length-1;s>=0;s--)i.push(n.children[s])}return bl(t)}function pr(e){return da(pl(e))}function Br(e){return da(fa(Yt(e)))}function Or(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():Br(e)}function zr(e){let t=Or(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function Tt(e,t,r,i){let n=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,n))}function xl(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function qi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function vl(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function Ml(e){let t=qi(e);if(!t)return null;let r=t.target;return{target:xl(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:Tt(t.radius,.01,50,.5),speed:Tt(t.speed,-20,20,.5),height:Tt(t.height,-10,10,0),phase:Tt(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var wl=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],Al=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],Tu=new Set(wl),Su=new Set(Al);function ga(e,t){let r=vl(e,16)?.trim();if(!r)return t;let i=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(r);return i?`#${i[1].toLowerCase()}`:t}function ya(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:qi(e);if(!t||t.enabled===!1)return null;let r=Tt(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:Tt(t.threshold,0,4,.8),radius:Tt(t.radius,0,2,.5)}:null}function Ki(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:qi(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:ga(t.color,"#38bdf8"),thickness:Tt(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var lt=class Ro{constructor(t=0,r=0){this.x=Number(t),this.y=Number(r)}set(t,r){return this.x=Number(t),this.y=Number(r),this}clone(){return new Ro(this.x,this.y)}copy(t){return this.set(t.x,t.y)}add(t){return this.x+=t.x,this.y+=t.y,this}sub(t){return this.x-=t.x,this.y-=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t)}},xe=class Po{constructor(t=0,r=0,i=0){this.x=Number(t),this.y=Number(r),this.z=Number(i)}set(t,r,i){return this.x=Number(t),this.y=Number(r),this.z=Number(i),this}clone(){return new Po(this.x,this.y,this.z)}copy(t){return this.set(t.x,t.y,t.z)}add(t){return this.addVectors(this,t)}addVectors(t,r){return this.set(t.x+r.x,t.y+r.y,t.z+r.z)}sub(t){return this.subVectors(this,t)}subVectors(t,r){return this.set(t.x-r.x,t.y-r.y,t.z-r.z)}multiplyScalar(t){return this.set(this.x*t,this.y*t,this.z*t)}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t,t)}addScaledVector(t,r){return this.set(this.x+t.x*r,this.y+t.y*r,this.z+t.z*r)}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let t=this.length();return t>1e-5?this.multiplyScalar(1/t):this}cross(t){return this.crossVectors(this,t)}crossVectors(t,r){let i=t.x,n=t.y,s=t.z,l=r.x,o=r.y,a=r.z;return this.set(n*a-s*o,s*l-i*a,i*o-n*l)}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}distanceTo(t){return Math.hypot(this.x-t.x,this.y-t.y,this.z-t.z)}lerp(t,r){return this.lerpVectors(this,t,r)}lerpVectors(t,r,i){return this.x=t.x+(r.x-t.x)*i,this.y=t.y+(r.y-t.y)*i,this.z=t.z+(r.z-t.z)*i,this}applyMatrix4(t){let r=this.x,i=this.y,n=this.z,s=t.elements,l=1/(s[3]*r+s[7]*i+s[11]*n+s[15]);return this.x=(s[0]*r+s[4]*i+s[8]*n+s[12])*l,this.y=(s[1]*r+s[5]*i+s[9]*n+s[13])*l,this.z=(s[2]*r+s[6]*i+s[10]*n+s[14])*l,this}},Yi=class{constructor(e=0,t=0,r=0,i=1){this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i)}set(e,t,r,i){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i),this}},$r=class Eo{constructor(t=0,r=0,i=0,n="XYZ"){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=n}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}set(t,r,i,n=this.order){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=n,this._onChangeCallback?.(),this}copy(t){return this.set(t.x,t.y,t.z,t.order)}clone(){return new Eo(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},dr=class Co{constructor(t=0,r=0,i=0,n=1){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(n)}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}get w(){return this._w}set w(t){this._w=Number(t),this._onChangeCallback?.()}set(t,r,i,n){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(n),this._onChangeCallback?.(),this}copy(t){return this.set(t.x,t.y,t.z,t.w)}clone(){return new Co(this._x,this._y,this._z,this._w)}identity(){return this.set(0,0,0,1)}setFromEuler(t,r=!0){let i=t.x,n=t.y,s=t.z,l=Math.cos(i/2),o=Math.cos(n/2),a=Math.cos(s/2),u=Math.sin(i/2),h=Math.sin(n/2),m=Math.sin(s/2);return this._x=u*o*a+l*h*m,this._y=l*h*a-u*o*m,this._z=l*o*m+u*h*a,this._w=l*o*a-u*h*m,r&&this._onChangeCallback?.(),this}setFromAxisAngle(t,r){let i=r/2,n=Math.sin(i);return this.set(t.x*n,t.y*n,t.z*n,Math.cos(i))}normalize(){let t=Math.hypot(this._x,this._y,this._z,this._w);return t===0?this.set(0,0,0,1):this.set(this._x/t,this._y/t,this._z/t,this._w/t)}setFromUnitVectors(t,r){let i=t.dot(r)+1;return i<1e-6?(Math.abs(t.x)>Math.abs(t.z)?this.set(-t.y,t.x,0,0):this.set(0,-t.z,t.y,0)).normalize():this.set(t.y*r.z-t.z*r.y,t.z*r.x-t.x*r.z,t.x*r.y-t.y*r.x,i).normalize()}multiply(t){return this.multiplyQuaternions(this,t)}multiplyQuaternions(t,r){let i=t.x,n=t.y,s=t.z,l=t.w,o=r.x,a=r.y,u=r.z,h=r.w;return this._x=i*h+l*o+n*u-s*a,this._y=n*h+l*a+s*o-i*u,this._z=s*h+l*u+i*a-n*o,this._w=l*h-i*o-n*a-s*u,this._onChangeCallback?.(),this}_onChange(t){return this._onChangeCallback=t,this}},_t=class No{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let t=this.elements;return t.fill(0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,this}copy(t){return this.elements.set(t.elements),this}clone(){let t=new No;return t.copy(this),t}compose(t,r,i){return lr(this.elements,[r.x,r.y,r.z,r.w],[t.x,t.y,t.z],[i.x,i.y,i.z]),this}multiply(t){return this.multiplyMatrices(this,t)}multiplyMatrices(t,r){return ke(this.elements,t.elements,r.elements),this}lookAt(t,r,i){return Er(this.elements,[t.x,t.y,t.z],[r.x,r.y,r.z],[i.x,i.y,i.z]),this}makeRotationFromQuaternion(t){let r=new xe(0,0,0),i=new xe(1,1,1);return this.compose(r,t,i)}makeTranslation(t,r,i){return this.identity(),this.elements[12]=Number(t),this.elements[13]=Number(r),this.elements[14]=Number(i),this}makeScale(t,r,i){return this.identity(),this.elements[0]=Number(t),this.elements[5]=Number(r),this.elements[10]=Number(i),this}},Zi=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[4]=1,e[8]=1,this}getNormalMatrix(e){return Ye(this.elements,e.elements),this}},Qe=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,Hr=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,ba={black:0,white:16777215,red:16711680,green:32768,lime:65280,blue:255,yellow:16776960,cyan:65535,aqua:65535,magenta:16711935,fuchsia:16711935,gray:8421504,grey:8421504,silver:12632256,orange:16753920,purple:8388736,pink:16761035,gold:16766720},ft=class Lo{constructor(t,r,i){this.r=1,this.g=1,this.b=1,t!==void 0&&(r!==void 0&&i!==void 0?this.setRGB(t,r,i):this.set(t))}set(t){return typeof t=="number"?this.setHex(t):typeof t=="string"?this.setStyle(t):(t&&typeof t=="object"&&"r"in t&&(this.r=Number(t.r),this.g=Number(t.g),this.b=Number(t.b)),this)}setStyle(t){let r=t.trim().toLowerCase();if(r[0]==="#"){let i=r.slice(1);i.length===3||i.length===4?i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]:i.length===8&&(i=i.slice(0,6));let n=parseInt(i,16);i.length===6&&!Number.isNaN(n)&&this.setHex(n)}else if(r in ba)this.setHex(ba[r]);else if(r.startsWith("hsl")){let i=/^hsla?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);i&&i.length>=3&&this.setHSL((parseFloat(i[0])||0)/360,(parseFloat(i[1])||0)/100,(parseFloat(i[2])||0)/100)}else{let i=/^rgba?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);if(i&&i.length>=3){let n=s=>Qe(Math.max(0,Math.min(1,(parseFloat(s)||0)/(s.endsWith("%")?100:255))));this.setRGB(n(i[0]),n(i[1]),n(i[2]))}}return this}setHSL(t,r,i){if(t=((Number(t)||0)%1+1)%1,r=Math.max(0,Math.min(1,Number(r)||0)),i=Math.max(0,Math.min(1,Number(i)||0)),r===0){let o=Qe(i);return this.setRGB(o,o,o)}let n=i<=.5?i*(1+r):i+r-i*r,s=2*i-n,l=o=>(o<0&&(o+=1),o>1&&(o-=1),o<1/6?s+(n-s)*6*o:o<1/2?n:o<2/3?s+(n-s)*6*(2/3-o):s);return this.setRGB(Qe(l(t+1/3)),Qe(l(t)),Qe(l(t-1/3)))}lerp(t,r){return this.lerpColors(this,t,r)}lerpColors(t,r,i){let n=Number(i)||0;return this.setRGB(t.r+(r.r-t.r)*n,t.g+(r.g-t.g)*n,t.b+(r.b-t.b)*n)}multiplyScalar(t){let r=Number(t)||0;return this.setRGB(this.r*r,this.g*r,this.b*r)}setScalar(t){let r=Number(t)||0;return this.setRGB(r,r,r)}setHex(t){let r=Math.floor(t);return this.setRGB(Qe((r>>16&255)/255),Qe((r>>8&255)/255),Qe((r&255)/255))}setRGB(t,r,i){return this.r=Number(t),this.g=Number(r),this.b=Number(i),this}convertSRGBToLinear(){return this.setRGB(Qe(this.r),Qe(this.g),Qe(this.b))}convertLinearToSRGB(){return this.setRGB(Hr(this.r),Hr(this.g),Hr(this.b))}getHex(){let t=r=>Math.round(Hr(Math.max(0,Math.min(1,r)))*255);return t(this.r)<<16|t(this.g)<<8|t(this.b)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(t){return this.setRGB(t.r,t.g,t.b)}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}clone(){return new Lo(this.r,this.g,this.b)}},Qi={degToRad:e=>e*Math.PI/180,radToDeg:e=>e*180/Math.PI,clamp:(e,t,r)=>Math.max(t,Math.min(r,e)),lerp:(e,t,r)=>e+(t-e)*r,generateUUID:()=>Math.random().toString(36).substring(2,15),randFloat:(e,t)=>e+Math.random()*(t-e)},He=class _o{constructor(t,r){if(this.needsUpdate=!1,typeof r!="number"||!Number.isInteger(r)||r<1||r>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(r)}`);Array.isArray(t)?this.array=new Float32Array(t):this.array=t,this.itemSize=r;let i=this.array?this.array.length:0;if(!Number.isFinite(i)||i<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(i)}`);this.count=Math.floor(i/r)}getX(t){return this.array[t*this.itemSize]}getY(t){return this.array[t*this.itemSize+1]}getZ(t){return this.array[t*this.itemSize+2]}setX(t,r){return this.array[t*this.itemSize]=r,this.needsUpdate=!0,this}setY(t,r){return this.array[t*this.itemSize+1]=r,this.needsUpdate=!0,this}setZ(t,r){return this.array[t*this.itemSize+2]=r,this.needsUpdate=!0,this}setXYZ(t,r,i,n){let s=t*this.itemSize;return this.array[s]=r,this.array[s+1]=i,this.array[s+2]=n,this.needsUpdate=!0,this}setUsage(t){return this}clone(){let t=this.array?.constructor||Float32Array;return new _o(new t(this.array),this.itemSize)}},Ji=class extends He{constructor(e,t){super(e instanceof Float32Array||Array.isArray(e)?e:new Float32Array(e),t)}},en=class extends He{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},tn=class extends He{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},Ue=class Io{constructor(){this.name="",this.attributes={},this.index=null,this.boundingBox=null}setAttribute(t,r){return this.attributes[t]=r,this}getAttribute(t){return this.attributes[t]}setIndex(t){if(t instanceof He)this.index=t;else if(Array.isArray(t)){let r=0;for(let i of t)i>r&&(r=i);this.index=new He(new(r>65535?Uint32Array:Uint16Array)(t),1)}else t&&t.buffer&&(this.index=new He(t,1));return this}computeVertexNormals(){let t=this.attributes.position;if(!t)return this;let r=!1;if(typeof r=="function"){let a=r(t.array,this.index?.array);return this.setAttribute("normal",new He(a,3)),this}let i=t.count,n=t.array,s=new Float32Array(i*3),l=this.index?.array,o=l?l.length:i;for(let a=0;a<o;a+=3){let u=(l?l[a]:a)*3,h=(l?l[a+1]:a+1)*3,m=(l?l[a+2]:a+2)*3,c=n[h],d=n[h+1],f=n[h+2],g=n[m]-c,x=n[m+1]-d,b=n[m+2]-f,v=n[u]-c,p=n[u+1]-d,y=n[u+2]-f,M=x*y-b*p,P=b*v-g*y,F=g*p-x*v;s[u]+=M,s[u+1]+=P,s[u+2]+=F,s[h]+=M,s[h+1]+=P,s[h+2]+=F,s[m]+=M,s[m+1]+=P,s[m+2]+=F}for(let a=0;a<i*3;a+=3){let u=s[a],h=s[a+1],m=s[a+2],c=Math.hypot(u,h,m)||1;s[a]=u/c,s[a+1]=h/c,s[a+2]=m/c}return this.setAttribute("normal",new He(s,3)),this}setFromBuffers(t,r,i,n){this.setAttribute("position",new He(t,3)),this.setAttribute("normal",new He(r,3)),this.setAttribute("uv",new He(i,2)),this.setIndex(n)}setFromPoints(t){let r=[];if(Array.isArray(t))for(let i of t)r.push(Number(i?.x)||0,Number(i?.y)||0,Number(i?.z)||0);return this.setAttribute("position",new He(r,3))}computeBoundingBox(){let t=this.attributes.position,r=new xe(1/0,1/0,1/0),i=new xe(-1/0,-1/0,-1/0);if(t&&t.count>0)for(let n=0;n<t.count;n++){let s=t.getX(n),l=t.getY(n),o=t.getZ(n);s<r.x&&(r.x=s),l<r.y&&(r.y=l),o<r.z&&(r.z=o),s>i.x&&(i.x=s),l>i.y&&(i.y=l),o>i.z&&(i.z=o)}else r.set(0,0,0),i.set(0,0,0);return this.boundingBox={min:r,max:i},this.boundingBox}center(){let t=this.computeBoundingBox();return this.translate(-(t.min.x+t.max.x)*.5,-(t.min.y+t.max.y)*.5,-(t.min.z+t.max.z)*.5)}_xform(t,r){let i=this.attributes.position;if(i){let n=i.array;for(let s=0;s<n.length;s+=3)t(n,s);i.needsUpdate=!0,r&&this.computeVertexNormals(),this.computeBoundingBox()}return this}translate(t=0,r=0,i=0){return this._xform((n,s)=>{n[s]+=t,n[s+1]+=r,n[s+2]+=i})}scale(t=1,r=1,i=1){return this._xform((n,s)=>{n[s]*=t,n[s+1]*=r,n[s+2]*=i},!0)}_rot(t,r,i){let n=Math.cos(i),s=Math.sin(i);for(let l of[this.attributes.position,this.attributes.normal]){if(!l)continue;let o=l.array;for(let a=0;a<o.length;a+=3){let u=o[a+t],h=o[a+r];o[a+t]=u*n-h*s,o[a+r]=u*s+h*n}l.needsUpdate=!0}return this}rotateX(t){return this._rot(1,2,t)}rotateY(t){return this._rot(2,0,t)}rotateZ(t){return this._rot(0,1,t)}applyMatrix4(t){let r=this.attributes.position;if(r&&t?.elements){let i=new xe;for(let n=0;n<r.count;n++)i.set(r.getX(n),r.getY(n),r.getZ(n)).applyMatrix4(t),r.setXYZ(n,i.x,i.y,i.z);this.computeVertexNormals()}return this}clone(){let t=new Io;t.name=this.name;for(let r of Object.keys(this.attributes))t.attributes[r]=this.attributes[r].clone();return this.index&&(t.index=this.index.clone()),t}dispose(){}},Gr=class extends Ue{constructor(e=1,t=1,r=1){super();let i=e/2,n=t/2,s=r/2,l=[-i,-n,s,i,-n,s,i,n,s,-i,n,s,i,-n,-s,-i,-n,-s,-i,n,-s,i,n,-s,-i,n,s,i,n,s,i,n,-s,-i,n,-s,-i,-n,-s,i,-n,-s,i,-n,s,-i,-n,s,i,-n,s,i,-n,-s,i,n,-s,i,n,s,-i,-n,-s,-i,-n,s,-i,n,s,-i,n,-s],o=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0],a=[],u=[];for(let h=0;h<6;h++){let m=h*4;a.push(0,0,1,0,1,1,0,1),u.push(m,m+1,m+2,m,m+2,m+3)}this.setFromBuffers(l,o,a,u)}},rn=class extends Ue{constructor(e=1,t=1,r=1,i=1){super(),r=Math.max(1,Math.floor(r)),i=Math.max(1,Math.floor(i));let n=[],s=[],l=[],o=[];for(let a=0;a<=i;a++){let u=a/i;for(let h=0;h<=r;h++){let m=h/r;if(n.push((m-.5)*e,(.5-u)*t,0),s.push(0,0,1),l.push(m,1-u),a>0&&h>0){let c=(r+1)*a+h-1,d=c-(r+1);o.push(d,c,d+1,c,c+1,d+1)}}}this.setFromBuffers(n,s,l,o)}},nn=class extends Ue{constructor(e=1,t=16,r=12,i=0,n=Math.PI*2,s=0,l=Math.PI){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let o=[],a=[],u=[],h=[],m=Math.min(s+l,Math.PI);for(let c=0;c<=r;c++){let d=c/r,f=s+d*l;for(let g=0;g<=t;g++){let x=g/t,b=i+x*n,v=-Math.cos(b)*Math.sin(f),p=Math.cos(f),y=Math.sin(b)*Math.sin(f);if(o.push(e*v,e*p,e*y),a.push(v,p,y),u.push(x,1-d),c>0&&g>0){let M=(t+1)*c+g,P=M-(t+1),F=P-1,G=M-1;(c!==1||s>0)&&h.push(P,F,M),(c!==r||m<Math.PI)&&h.push(F,G,M)}}}this.setFromBuffers(o,a,u,h)}},Wr=class extends Ue{constructor(e=1,t=1,r=1,i=16,n=1,s=!1,l=0,o=Math.PI*2){super(),i=Math.max(3,Math.floor(i)),n=Math.max(1,Math.floor(Number(n)||1));let a=[],u=[],h=[],m=[],c=r/2,d=(t-e)/(r||1),f=i+1;for(let x=0;x<=n;x++){let b=x/n,v=b*(t-e)+e,p=c-b*r;for(let y=0;y<=i;y++){let M=y/i,P=l+M*o,F=Math.sin(P),G=Math.cos(P),T=Math.hypot(F,d,G)||1;if(a.push(v*F,p,v*G),u.push(F/T,d/T,G/T),h.push(M,1-b),x<n&&y<i){let E=x*f+y,S=E+f;m.push(E,S,E+1,S,S+1,E+1)}}}let g=(x,b)=>{if(s||x<=0)return;let v=b*c,p=a.length/3;a.push(0,v,0),u.push(0,b,0),h.push(.5,.5);let y=p+1;for(let M=0;M<=i;M++){let P=l+M/i*o,F=Math.sin(P),G=Math.cos(P);a.push(x*F,v,x*G),u.push(0,b,0),h.push(G*.5+.5,.5+b*F*.5),M<i&&m.push(p,y+M+(b>0?0:1),y+M+(b>0?1:0))}};g(e,1),g(t,-1),this.setFromBuffers(a,u,h,m)}},sn=class extends Wr{constructor(e=1,t=1,r=16,i=1,n=!1,s=0,l=Math.PI*2){super(0,e,t,r,i,n,s,l)}},an=class extends Ue{constructor(e=1,t=.4,r=12,i=48,n=Math.PI*2){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let s=[],l=[],o=[],a=[];for(let u=0;u<=r;u++){let h=u/r*Math.PI*2,m=Math.cos(h),c=Math.sin(h);for(let d=0;d<=i;d++){let f=d/i*n,g=Math.cos(f),x=Math.sin(f);if(s.push((e+t*m)*g,(e+t*m)*x,t*c),l.push(m*g,m*x,c),o.push(d/i,u/r),u>0&&d>0){let b=(i+1)*u+d-1,v=b-(i+1);a.push(b,v,b+1,v,v+1,b+1)}}}this.setFromBuffers(s,l,o,a)}};function xa(e,t,r,i,n){let s=Math.max(2,Math.min(256,Math.floor(Number(t)||64))),l=Math.max(3,Math.min(64,Math.floor(Number(r)||8))),o=Number(i)||.1,a=[],u=[],h=[],m=[],c=[],d=new xe,f=new xe,g=new xe;for(let b=0;b<=s;b++){let v=new xe;n(b/s,v),c.push(v)}let x=l+1;for(let b=0;b<=s;b++){let v=b/s,p=c[b];d.subVectors(c[Math.min(s,b+1)],c[Math.max(0,b-1)]).normalize(),b===0&&f.set(Math.abs(d.y)>.9?1:0,Math.abs(d.y)>.9?0:1,0),g.crossVectors(d,f).normalize(),f.crossVectors(g,d).normalize();for(let y=0;y<=l;y++){let M=y/l*Math.PI*2,P=-Math.cos(M),F=Math.sin(M),G=P*f.x+F*g.x,T=P*f.y+F*g.y,E=P*f.z+F*g.z;if(a.push(p.x+o*G,p.y+o*T,p.z+o*E),u.push(G,T,E),h.push(v,y/l),b>0&&y>0){let S=x*(b-1)+y-1,B=S+x;m.push(S,B,S+1,B,B+1,S+1)}}}e.setFromBuffers(a,u,h,m)}var on=class extends Ue{constructor(e=1,t=.4,r=64,i=8,n=2,s=3){super(),r=Math.floor(r),i=Math.floor(i),xa(this,r,i,t,(l,o)=>{let a=l*n*Math.PI*2,u=s/n*a,h=e*(2+Math.cos(u))*.5;o.set(h*Math.cos(a),h*Math.sin(a),e*Math.sin(u)*.5)})}},St=class{getPoint(e,t=new xe){return t}getPointAt(e,t=new xe){return this.getPoint(e,t)}getTangent(e,t=new xe){return t.subVectors(this.getPoint(Math.min(1,e+.001)),this.getPoint(Math.max(0,e-.001))).normalize()}getPoints(e=5){let t=Math.max(1,Math.min(512,Math.floor(Number(e)||5))),r=[];for(let i=0;i<=t;i++)r.push(this.getPoint(i/t));return r}getSpacedPoints(e=5){return this.getPoints(e)}},ln=class extends St{constructor(e=new xe,t=new xe){super(),this.v1=e,this.v2=t}getPoint(e,t=new xe){return t.lerpVectors(this.v1,this.v2,e)}},un=class extends St{constructor(e=new xe,t=new xe,r=new xe){super(),this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new xe){return t.lerpVectors(this.v0,this.v1,e).lerp(new xe().lerpVectors(this.v1,this.v2,e),e)}},hn=class extends St{constructor(e=new xe,t=new xe,r=new xe,i=new xe){super(),this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new xe){let r=new xe().lerpVectors(this.v0,this.v1,e),i=new xe().lerpVectors(this.v1,this.v2,e),n=new xe().lerpVectors(this.v2,this.v3,e);return t.lerpVectors(r.lerp(i,e),i.lerp(n,e),e)}},cn=class extends St{constructor(e=[],t=!1){super(),this.points=Array.isArray(e)?e:[],this.closed=!!t}getPoint(e,t=new xe){let r=this.points,i=r.length;if(!i)return t.set(0,0,0);if(i===1)return t.copy(r[0]);let n=(this.closed?i:i-1)*Math.max(0,Math.min(1,Number(e)||0)),s=Math.floor(n),l=n-s;!this.closed&&s>=i-1&&(s=i-2,l=1);let o=g=>r[this.closed?(g%i+i)%i:Math.max(0,Math.min(i-1,g))],a=o(s-1),u=o(s),h=o(s+1),m=o(s+2),c=l*l,d=c*l,f=(g,x,b,v)=>.5*(2*x+(b-g)*l+(2*g-5*x+4*b-v)*c+(3*x-g-3*b+v)*d);return t.set(f(a.x,u.x,h.x,m.x),f(a.y,u.y,h.y,m.y),f(a.z,u.z,h.z,m.z))}},jr=class extends Ue{constructor(e=[new lt(0,-.5),new lt(.5,0),new lt(0,.5)],t=12,r=0,i=Math.PI*2){super();let n=Array.isArray(e)&&e.length>=2?e:[new lt(.2,0),new lt(.2,.5)],s=Math.max(3,Math.min(128,Math.floor(Number(t)||12))),l=[],o=[],a=[],u=[],h=n.length;for(let m=0;m<=s;m++){let c=m/s,d=r+c*i,f=Math.sin(d),g=Math.cos(d),x=m*h;for(let b=0;b<h;b++){let v=n[b],p=Number(v?.x)||0,y=Number(v?.y)||0;l.push(p*f,y,p*g);let M=n[Math.max(0,b-1)],P=n[Math.min(h-1,b+1)],F=(Number(P?.x)||0)-(Number(M?.x)||0),G=(Number(P?.y)||0)-(Number(M?.y)||0),T=Math.hypot(G,F)||1;if(o.push(G/T*f,-F/T,G/T*g),a.push(c,b/(h-1)),m<s&&b<h-1){let E=x+b,S=E+h;u.push(E,S,E+1,S,S+1,E+1)}}}this.setFromBuffers(l,o,a,u)}},mn=class extends Ue{constructor(e,t=64,r=1,i=8,n=!1){super(),xa(this,t,i,r,(s,l)=>{let o=e?.getPointAt??e?.getPoint;if(typeof o=="function"){let a=o.call(e,s,l);a&&a!==l&&l.copy(a)}else l.set(0,s,0)})}},Xr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gr=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new lt(1,1),this.offset=new lt(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},fn=class extends gr{constructor(e=null,t=1,r=1,i=1023,n=1009,s,l=1001,o=1001,a=1003,u=1003,h=1,m=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1,this._sig=0;let c=Number(t),d=Number(r),f=e&&typeof e.length=="number"?e:null;this.width=c,this.height=d,this.image={data:f,width:c,height:d},this.format=Number(i)||1023,this.type=Number(n)||1009,this.wrapS=Number(l)||1001,this.wrapT=Number(o)||1001,this.magFilter=Number(a)||1003,this.minFilter=Number(u)||1003,this.colorSpace=m||"",this._bake()}get needsUpdate(){return!1}set needsUpdate(e){e&&this._bake()}_bake(){let e=this.image,t=e?.data,r=Number(e?.width??this.width),i=Number(e?.height??this.height);if(!t||!t.length||!(r>0&&i>0)||r>2048||i>2048){this.source="";return}let n=Math.max(1,r|0),s=Math.max(1,i|0),l=n*s,o=this.format,a=o===1021||o===1024||o===1028||t.length===l?1:o===1025||o===1030||t.length===l*2?2:o===1022||t.length===l*3?3:4,u=this.type===1015||this.type===1016||t instanceof Float32Array||t instanceof Float64Array,h=Math.min(n,48),m=Math.min(s,48),c=(this.flipY?257:1)^this.colorSpace.length^t.length,d=Math.max(1,t.length>>6|0);for(let B=0;B<t.length;B+=d)c=Math.imul(c^(t[B]*256|0),16777619)|0;if(c===this._sig&&this.source)return;this._sig=c;let f=m*(1+h*4),g=new Uint8Array(68+f),x=new DataView(g.buffer);x.setUint32(0,2303741511),x.setUint32(4,218765834),x.setUint32(8,13),x.setUint32(12,1229472850),x.setUint32(16,h),x.setUint32(20,m),g[24]=8,g[25]=6,x.setUint32(29,Xi(g.subarray(12,29))),x.setUint32(33,f+11),x.setUint32(37,1229209940),g[41]=120,g[42]=1,g[43]=1,x.setUint16(44,f,!0),x.setUint16(46,~f&65535,!0);let b=48,v=1,p=0,y=0,M=0,P=0,F=0,G=B=>{if(!Number.isFinite(B))return 0;let k=u&&B<=1?B*255:B;return k>0?k<255?k+.5|0:255:0};for(let B=0;B<m;B++){let k=B*s/m|0,w=this.flipY?s-1-k:k;g[b++]=0,p+=v;for(let ie=0;ie<h;ie++){let oe=(w*n+(ie*n/h|0))*a,I=o===1021?255:G(t[oe]??0),H=a>=3||o===1030?G(t[oe+1]??0):I,C=a>=3?G(t[oe+2]??0):o===1030?0:I,z=a===4?G(t[oe+3]??255):o===1021?G(t[oe]??255):o===1025?G(t[oe+1]??255):255;g[b++]=I,v+=I,p+=v,g[b++]=H,v+=H,p+=v,g[b++]=C,v+=C,p+=v,g[b++]=z,v+=z,p+=v,y+=I,M+=H,P+=C,F+=z}v%=65521,p%=65521}x.setUint32(b,(p<<16|v)>>>0),x.setUint32(b+4,Xi(g.subarray(37,b+4))),x.setUint32(b+12,1229278788),x.setUint32(b+16,2923585666);let T=h*m*255,E=this.colorSpace==="srgb-linear";this.avgColor=[E?y/T:Qe(y/T),E?M/T:Qe(M/T),E?P/T:Qe(P/T),F/T];let S=["data:image/png;base64,"];for(let B=0;B<g.length;B+=3){let k=g[B]<<16|(g[B+1]??0)<<8|(g[B+2]??0);S.push(Xr[k>>18&63]+Xr[k>>12&63]+(B+1<g.length?Xr[k>>6&63]:"=")+(B+2<g.length?Xr[k&63]:"="))}this.source=S.join("")}},pn=class{load(e,t){let r=new gr(e);return t?.(r),r}};function qe(e,t){return e!==void 0?Number(e):t}function dn(e,t){return e!==void 0?!!e:t}var tt=class{constructor(e={}){this.name=e.name||"",this.color=new ft(e.color??16777215),this.emissive=new ft(e.emissive??0),this.emissiveIntensity=qe(e.emissiveIntensity,1),this.roughness=qe(e.roughness,.5),this.metalness=qe(e.metalness,0),this.opacity=qe(e.opacity,1),this.transparent=dn(e.transparent,!1),this.wireframe=dn(e.wireframe,!1),this.side=qe(e.side,2),this.doubleSided=dn(e.doubleSided,!0),this.map=e.map||null;for(let t of["normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"])e[t]&&(this[t]=e[t]);this.clearcoat=qe(e.clearcoat,0),this.clearcoatRoughness=qe(e.clearcoatRoughness,0),this.sheen=qe(e.sheen,0),this.sheenColor=new ft(e.sheenColor??0),this.sheenRoughness=qe(e.sheenRoughness,0),this.transmission=qe(e.transmission,0),this.thickness=qe(e.thickness,0),this.attenuationColor=new ft(e.attenuationColor??16777215),this.attenuationDistance=qe(e.attenuationDistance,1/0),this.ior=qe(e.ior,1.5),this.dispersion=qe(e.dispersion,0),this.iridescence=qe(e.iridescence,0),this.iridescenceIOR=qe(e.iridescenceIOR,1.3)}dispose(){}},Qt=class extends tt{},gn=class extends tt{},yn=class extends tt{},bn=class extends tt{},xn=class extends tt{},pt=class Do{constructor(){this.name="",this.matrixAutoUpdate=!0,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.parent=null,this.children=[],this.userData={},this.position=new xe,this.rotation=new $r,this.quaternion=new dr,this.scale=new xe(1,1,1),this.matrix=new _t,this.matrixWorld=new _t,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let t=this.quaternion,r=Math.atan2(2*(t.w*t.x+t.y*t.z),1-2*(t.x*t.x+t.y*t.y)),i=Math.asin(Math.max(-1,Math.min(1,2*(t.w*t.y-t.z*t.x)))),n=Math.atan2(2*(t.w*t.z+t.x*t.y),1-2*(t.y*t.y+t.z*t.z));this.rotation.set(r,i,n)})}add(...t){for(let r of t)r&&r instanceof Do&&(r.parent&&r.parent.remove(r),r.parent=this,this.children.push(r));return this}remove(...t){for(let r of t){let i=this.children.indexOf(r);i!==-1&&(r.parent=null,this.children.splice(i,1))}return this}traverse(t){let r=new Set,i=[this];for(;i.length>0;){let n=i.pop();if(!n||typeof n!="object"||r.has(n))continue;r.add(n),t(n);let s=n.children;if(Array.isArray(s))for(let l=s.length-1;l>=0;l--)i.push(s[l])}}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(t=!1){this.traverse(r=>{va(r),(r.matrixAutoUpdate||t)&&r.updateMatrix?.(),r.parent&&r.parent.matrixWorld?r.matrixWorld?.multiplyMatrices(r.parent.matrixWorld,r.matrix):r.matrix&&r.matrixWorld?.copy(r.matrix)})}lookAt(t,r,i){let n=typeof t=="object"?t:new xe(t,r,i);this.target instanceof xe?this.target.copy(n):this.target?.position instanceof xe&&this.target.position.copy(n),this.updateMatrixWorld(!0);let s=new _t;s.lookAt(this.position,n,new xe(0,1,0));let l=s.elements,o=l[0],a=l[4],u=l[8],h=l[1],m=l[5],c=l[9],d=l[2],f=l[6],g=l[10],x=o+m+g;if(x>0){let b=.5/Math.sqrt(x+1);this.quaternion.set((f-c)*b,(u-d)*b,(h-a)*b,.25/b)}}translateOnAxis(t,r){let i=t.clone().applyMatrix4(new _t().makeRotationFromQuaternion(this.quaternion)).multiplyScalar(r);return this.position.add(i),this}translateX(t){return this.translateOnAxis(new xe(1,0,0),t)}translateY(t){return this.translateOnAxis(new xe(0,1,0),t)}translateZ(t){return this.translateOnAxis(new xe(0,0,1),t)}rotateX(t){return this.rotation.x+=t,this}rotateY(t){return this.rotation.y+=t,this}rotateZ(t){return this.rotation.z+=t,this}_chain(){let t=[];for(let r=this;r&&t.length<64;r=r.parent)t.push(r);return t}_syncWorld(){let t=this._chain();for(let r=t.length-1;r>=0;r--){let i=t[r];i.updateMatrix?.(),i.parent?.matrixWorld?i.matrixWorld.multiplyMatrices(i.parent.matrixWorld,i.matrix):i.matrixWorld?.copy(i.matrix)}return this.matrixWorld.elements}getWorldPosition(t=new xe){let r=this._syncWorld();return t.set(r[12],r[13],r[14])}getWorldScale(t=new xe){let r=this._syncWorld();return t.set(Math.hypot(r[0],r[1],r[2]),Math.hypot(r[4],r[5],r[6]),Math.hypot(r[8],r[9],r[10]))}getWorldDirection(t=new xe){let r=this._syncWorld();return t.set(r[8],r[9],r[10]).normalize()}getWorldQuaternion(t=new dr){let r=this._chain();t.set(0,0,0,1);for(let i=r.length-1;i>=0;i--)t.multiply(r[i].quaternion);return t}clone(t=!0){let r=this instanceof Dt?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof xt?new xt(this.geometry,this.material):new this.constructor;r.name=this.name,r.position.copy(this.position),r.quaternion.copy(this.quaternion),r.scale.copy(this.scale),r.visible=this.visible,r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow;try{r.userData=JSON.parse(JSON.stringify(this.userData||{}))}catch{r.userData={...this.userData||{}}}if(t)for(let i of this.children)r.add(i.clone(!0));return r}},vn=class extends pt{},xt=class extends pt{constructor(e,t){super(),this.isMesh=!0;let r=Array.isArray(t)?t[0]:t;this.geometry=e instanceof Ue?e:e?(Pt("unsupported geometry","BoxGeometry"),new Gr(.5,.5,.5)):new Ue,this.material=r instanceof tt?r:r?(Pt("unsupported material","MeshStandardMaterial"),new Qt({color:13421772})):new Qt}};function va(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=Ae().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var Jt=1e4,qr=class extends xt{constructor(e,t,r=1){super(e,t),this.instanceColor=null,this.isInstancedMesh=!0;let i=Number(r);if(!Number.isFinite(i)||i<0||i>Jt)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${Jt})`);this.count=Math.floor(i);let n=new Float32Array(this.count*16);for(let s=0;s<this.count;s++){let l=s*16;n[l]=1,n[l+5]=1,n[l+10]=1,n[l+15]=1}this.instanceMatrix=new He(n,16)}setMatrixAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t||!t.elements)return;let i=this.instanceMatrix.array,n=r*16;if(!(n+16>i.length))for(let s=0;s<16;s++){let l=Number(t.elements[s]);i[n+s]=Number.isFinite(l)?l:s%5===0?1:0}}getMatrixAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t||!t.elements)return;let i=this.instanceMatrix.array,n=r*16;if(!(n+16>i.length))for(let s=0;s<16;s++)t.elements[s]=i[n+s]}setColorAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let s=new Float32Array(this.count*3);s.fill(1),this.instanceColor=new He(s,3)}let i=this.instanceColor.array,n=r*3;i[n]=Number.isFinite(t.r)?t.r:1,i[n+1]=Number.isFinite(t.g)?t.g:1,i[n+2]=Number.isFinite(t.b)?t.b:1}getColorAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<(r+1)*3){t.setRGB(1,1,1);return}let i=this.instanceColor.array,n=r*3;t.setRGB(i[n],i[n+1],i[n+2])}dispose(){}},er=class extends pt{constructor(e=16777215,t=1){super(),this.color=new ft(e),this.intensity=Number(t),this.type="directional"}},Kr=class extends er{constructor(e,t){super(e,t),this.type="ambient"}},Mn=class extends er{constructor(e,t){super(e,t),this.target=new pt,this.type="directional"}},Yr=class extends er{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},Zr=class extends pt{},wn=class extends Zr{constructor(e=45,t=1,r=.1,i=1e3){super(),this.target=new xe(0,0,0),this.fov=Number(e),this.aspect=Number(t),this.near=Number(r),this.far=Number(i)}},Qr=class extends pt{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return vt.validate(this),Zt(this)}toGLB(){return vt.validate(this),fr(this)}toUSDZ(){return vt.validate(this),pr(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof xt){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},Jr=Zt,ei=fr,An=pr,vt=class{static validate(e){let t=0,r=0,i=0,n=new Set,s=(o,a,u)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${o} (${a}). Found: ${u}`)},l=(o,a)=>{if(!Number.isFinite(a))throw new Error(`SecurityError: Scene reports a non-finite ${o} count (${String(a)}), which cannot be bounds-checked.`);return a};e.traverse(o=>{if(va(o),o instanceof xt||o.geometry?.attributes?.position?.count){if(i++,i>1e3&&s("MESHES",1e3,i),o instanceof qr){let u=l("instance",o.count);(u<0||u>Jt)&&s("INSTANCES",Jt,u)}let a=o.geometry;if(a){let u=0;if(a.attributes.position&&(u=l("vertex",a.attributes.position.count),t+=u,t>1e5&&s("VERTICES",1e5,t)),a.index){let h=l("index",a.index.count);r+=h,r>3e5&&s("INDICES",3e5,r);let m=a.index.array;if(m&&u>0){let c=Math.min(h,m.length);for(let d=0;d<c;d++){let f=m[d];if(!Number.isFinite(f)||f<0||f>=u)throw new Error(`SecurityError: Index buffer value (${String(f)}) out of vertex bounds [0, ${u}).`)}}}}if(o.material){let u=o.material;for(let h of["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"])u[h]&&n.add(u[h])}}}),n.size>16&&s("TEXTURES",16,n.size);for(let o of n){let a=o,u=a.image,h=Number(u?.width??a.width??0)||0,m=Number(u?.height??a.height??0)||0;(!Number.isFinite(h)||!Number.isFinite(m)||h>2048||m>2048)&&s("TEXTURE_DIMENSION",2048,Math.max(h,m))}}},Tn=class{constructor(e={}){this.shadowMap={enabled:!1,type:0},this.capabilities={isWebGL2:!0,maxTextures:16},this.boundViewer=null,this.hasInitialModelRendered=!1,this.domElement=e.canvas||(typeof document<"u"?document.createElement("canvas"):{}),e.viewer&&(this.boundViewer=e.viewer),e.container?.threeLiveViewer&&(this.boundViewer=e.container.threeLiveViewer),e.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=e.canvas.parentElement.threeLiveViewer);let t=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=e.isSandboxed||t,this.containerId=e.containerId||""}setSize(e,t){return this}setPixelRatio(e){return this}setClearColor(e,t=1){let r=new ft(e);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(r.r,r.g,r.b,t),this}clear(){return this}dispose(){}render(e,t){if(this.isSandboxed){vt.validate(e);let i=(n,s)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(s&&s.length?self.postMessage(n,s):self.postMessage(n))};if(this.hasInitialModelRendered){let n=e.getMeshTransforms(),s={};for(let[l,o]of n.entries())s[l]=Array.from(o);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:s})}else{this.hasInitialModelRendered=!0;let n=Jr(e),s=ei(e),l=(n.lights||[]).map(o=>({type:o.type,color:o.color,intensity:o.intensity,position:o.position}));i({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:s.buffer,dynamicLights:l,camera:t?{fov:t.fov||60,position:[t.position.x,t.position.y,t.position.z]}:void 0},[s.buffer])}return}let r=this.boundViewer;!r&&this.domElement?.parentElement&&this.domElement.parentElement.threeLiveViewer&&(r=this.domElement.parentElement.threeLiveViewer,this.boundViewer=r),!r&&typeof window<"u"&&(r=window.__three_live_active_viewer__,this.boundViewer=r),r&&typeof r.loadModel=="function"&&(r._hasThreeLiveModelLoaded?typeof r.updateMeshTransforms=="function"&&r.updateMeshTransforms(e.getMeshTransforms()):(r.loadModel(e.toCanvas3D()),r._hasThreeLiveModelLoaded=!0))}};function Ma(){return typeof globalThis<"u"&&typeof globalThis.__three_live_sim_time_ms__=="number"?globalThis.__three_live_sim_time_ms__:typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Sn=class{constructor(e=!0){this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1,this.autoStart=e,e&&this.start()}start(){this.startTime=Ma(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running&&this.start(),this.running){let t=Ma();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Tl(){}var tr=new Proxy(Tl,{get:(e,t)=>{if(t==="isProxy")return!0;if(!(t==="constructor"||t==="__proto__"||t==="prototype"))return t==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:t==="shadowMap"?{enabled:!1,type:0}:t==="capabilities"?{isWebGL2:!0,maxTextures:16}:t===Symbol.toPrimitive?()=>0:tr},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>tr,construct:()=>tr}),wa=(()=>{try{if(typeof document>"u")return null;let e=document.currentScript;return e?.src?e.src:e?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([e.textContent],{type:"text/javascript"})):null}catch{return null}})();function ti(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function It(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,ti());return!(i.protocol!=="https:"&&i.protocol!=="http:"&&i.protocol!=="blob:"||t?.requireSameOrigin&&i.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&i.origin!==location.origin)}catch{return!1}}var Aa,yr;function Rn(e){if(!It(e))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${e}".`);let t=globalThis.trustedTypes;if(!t||typeof t.createPolicy!="function")return e;if(yr===void 0||Aa!==t){Aa=t;try{yr=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!It(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{yr=null}}return yr?yr.createScriptURL(e):e}function Ta(e){Ae().sandboxEngineSrc=e}function ri(){let e=Ae().sandboxEngineSrc;if(e)return e;if(wa)return wa;try{if(typeof document>"u")return null;let t=ti(),r=Array.from(document.querySelectorAll("script[src]"));for(let i of r){let n=i.src;if(!n)continue;let s=new URL(n,t).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(s)&&It(n,{requireSameOrigin:!0}))return n}}catch{}return null}function Pn(e,t){if(!It(e))throw new Error(`SecurityError: Refusing to load ${t} from disallowed URL "${e}". Only http:, https:, and blob: URLs are permitted.`);return new URL(e,ti()).href}function Sl(){let e=ri();if(!e)throw new Error("Three-Live could not locate its own bundle URL, which the worker sandbox needs in order to load the THREE runtime. Set it explicitly, e.g. ThreeLiveElement.sandboxEngineSrc = new URL('three-live.min.js', import.meta.url).href. Refusing to execute the script, because unsandboxed host-realm execution is prohibited.");return Pn(e,"sandbox engine")}function Sa(e){Ae().sandboxIframeSrc=e}function En(){let e=Ae().sandboxIframeSrc;if(e)return e;let t=ri();if(!t||!It(t))return null;let r=new URL(t,ti());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function Rl(){let e=En();if(!e)throw new Error("Three-Live could not locate three-live-sandbox.html for iframe sandbox execution. Set ThreeLiveElement.sandboxIframeSrc (or ThreeLiveElement.sandboxEngineSrc) explicitly.");return Pn(e,"sandbox iframe")}function Ra(e){Ae().allowClientScripts=e}function Cn(){return!!Ae().allowClientScripts}function Pl(e){return Pn(e,"procedural scene script")}var El=["fetch","XMLHttpRequest","WebSocket","WebSocketStream","WebTransport","EventSource","importScripts","Request","Response","Headers","navigator","WorkerNavigator","WorkerLocation","RTCPeerConnection","RTCDataChannel","FontFace","FontFaceSet","fonts","PerformanceObserver","ReportingObserver","indexedDB","IDBFactory","caches","CacheStorage","Cache","cookieStore","StorageManager","FileSystemHandle","Worker","SharedWorker","ServiceWorker","ServiceWorkerContainer","ServiceWorkerRegistration","registration","clients","BroadcastChannel","MessageChannel","MessagePort","createImageBitmap","OffscreenCanvas","WebAssembly","WorkerGlobalScope","DedicatedWorkerGlobalScope","trustedTypes","TrustedTypePolicyFactory","SharedArrayBuffer","Atomics"];function Cl(e,t){let r=self,i=e.nonce,n=e.engineSrc,s=e.allowedScriptUrl,l=e.allowClientScripts,o=e.revoked,a=r.postMessage.bind(r);function u(p){a({type:"ERROR",nonce:i,message:String(p)})}let h=typeof r.importScripts=="function"?r.importScripts.bind(r):null,m=s,c=null;try{let p=n;if(typeof r.trustedTypes<"u"&&r.trustedTypes&&typeof r.trustedTypes.createPolicy=="function")try{let y={createScriptURL:function(P){if(P!==n&&(!s||P!==s))throw new TypeError("Disallowed worker importScripts URL");return P}};l&&(y.createScript=function(P){return String(P)});let M=r.trustedTypes.createPolicy("three-live#worker-boot",y);p=M.createScriptURL(n),s&&(m=M.createScriptURL(s)),l&&typeof M.createScript=="function"&&(c=M.createScript.bind(M))}catch{}h(p)}catch(p){u('Sandbox failed to load the Three-Live engine from "'+n+'". It must be a same-origin (or CORS-enabled) IIFE bundle such as three-live.min.js. Underlying error: '+(p&&p.message||p));return}let d=r.THREE;if(!d||typeof d.Scene!="function"){u('Sandbox loaded "'+n+'" but it did not install a THREE namespace. Point sandboxEngineSrc at an IIFE build (three-live.min.js), not an ES module build.');return}if(Array.isArray(t)){let p=r.__THREE_LIVE_REGISTRY__;for(let y=0;y<t.length;y++)if(typeof t[y]=="function")try{t[y](d,p)}catch{}}function f(p,y,M){let P=r;for(;P&&P!==Object.prototype;){if(!M&&P!==r)try{delete P[p]}catch{}if(!M||P===r||Object.prototype.hasOwnProperty.call(P,p))try{Object.defineProperty(P,p,M?{value:y,writable:!1,configurable:!1}:{value:y,writable:!1,configurable:!1,enumerable:!1})}catch{}try{P=Object.getPrototypeOf(P)}catch{break}}}for(let p=0;p<o.length;p++)f(o[p],void 0);f("performance",Object.freeze({now:function(){return Date.now()}}));let g=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],x=!1;function b(p,y){if(p.type==="3D_MODEL_READY"){if(x)return;x=!0}p.nonce=i,y&&y.length?a(p,y):a(p)}f("postMessage",function(p,y){if(!p||g.indexOf(p.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");b(p,y)},!0);let v=!1;r.onmessage=function(p){let y=p&&p.data;if(!(!y||y.nonce!==i)&&!(y.type!=="EXECUTE"&&y.type!=="EXECUTE_URL")&&!v){v=!0;try{let M=new d.Scene,P=new d.PerspectiveCamera(60,1,.1,1e3),F=new d.WebGLRenderer({isSandboxed:!0});if(y.type==="EXECUTE_URL"){if(!s||y.scriptUrl!==s||typeof h!="function"){u("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let G=m||s,T=h;if(h=null,m=null,r.THREE=d,r.scene=M,r.camera=P,r.renderer=F,T(G),typeof r.__THREE_LIVE_SCENE__=="function"){let E=r.__THREE_LIVE_SCENE__(d,M,P,F);E&&typeof E.toGLB=="function"&&(M=E)}else r.scene&&typeof r.scene.toGLB=="function"&&(M=r.scene)}else{if(!l){u("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let G=c?(0,eval)(c(`(function (THREE, scene, camera, renderer) {
392
+ `,surfaceConnections:y,surfaceInputsUsda:b,usesTime:i.usesTime}}function ci(e,t,r,i){let n=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,n))}function Vp(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function ko(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Up(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function Op(e){let t=ko(e);if(!t)return null;let r=t.target;return{target:Vp(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:ci(t.radius,.01,50,.5),speed:ci(t.speed,-20,20,.5),height:ci(t.height,-10,10,0),phase:ci(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var jp=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],Gp=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],Lg=new Set(jp),Rg=new Set(Gp);function Ih(e,t){let r=Up(e,16)?.trim();if(!r)return t;let i=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(r);return i?`#${i[1].toLowerCase()}`:t}function $h(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:ko(e);if(!t||t.enabled===!1)return null;let r=ci(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:ci(t.threshold,0,4,.8),radius:ci(t.radius,0,2,.5)}:null}function Fo(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:ko(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:Ih(t.color,"#38bdf8"),thickness:ci(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var ar=class g0{constructor(t=0,r=0){this.x=Number(t),this.y=Number(r)}set(t,r){return this.x=Number(t),this.y=Number(r),this}clone(){return new g0(this.x,this.y)}copy(t){return this.set(t.x,t.y)}add(t){return this.x+=t.x,this.y+=t.y,this}sub(t){return this.x-=t.x,this.y-=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t)}get width(){return this.x}set width(t){this.x=Number(t)}get height(){return this.y}set height(t){this.y=Number(t)}},Ze=class y0{constructor(t=0,r=0,i=0){this.x=Number(t),this.y=Number(r),this.z=Number(i)}set(t,r,i){return this.x=Number(t),this.y=Number(r),this.z=Number(i),this}clone(){return new y0(this.x,this.y,this.z)}copy(t){return this.set(t.x,t.y,t.z)}add(t){return this.addVectors(this,t)}addVectors(t,r){return this.set(t.x+r.x,t.y+r.y,t.z+r.z)}sub(t){return this.subVectors(this,t)}subVectors(t,r){return this.set(t.x-r.x,t.y-r.y,t.z-r.z)}multiplyScalar(t){return this.set(this.x*t,this.y*t,this.z*t)}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t,t)}addScaledVector(t,r){return this.set(this.x+t.x*r,this.y+t.y*r,this.z+t.z*r)}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let t=this.length();return t>1e-5?this.multiplyScalar(1/t):this}cross(t){return this.crossVectors(this,t)}crossVectors(t,r){let i=t.x,n=t.y,a=t.z,s=r.x,o=r.y,l=r.z;return this.set(n*l-a*o,a*s-i*l,i*o-n*s)}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}distanceTo(t){return Math.hypot(this.x-t.x,this.y-t.y,this.z-t.z)}lerp(t,r){return this.lerpVectors(this,t,r)}lerpVectors(t,r,i){return this.x=t.x+(r.x-t.x)*i,this.y=t.y+(r.y-t.y)*i,this.z=t.z+(r.z-t.z)*i,this}applyMatrix4(t){let r=this.x,i=this.y,n=this.z,a=t.elements,s=1/(a[3]*r+a[7]*i+a[11]*n+a[15]);return this.x=(a[0]*r+a[4]*i+a[8]*n+a[12])*s,this.y=(a[1]*r+a[5]*i+a[9]*n+a[13])*s,this.z=(a[2]*r+a[6]*i+a[10]*n+a[14])*s,this}},Bo=class{constructor(e=0,t=0,r=0,i=1){this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i)}set(e,t,r,i){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this.w=Number(i),this}},Ca=class b0{constructor(t=0,r=0,i=0,n="XYZ"){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=n}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}set(t,r,i,n=this.order){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=n,this._onChangeCallback?.(),this}copy(t){return this.set(t.x,t.y,t.z,t.order)}clone(){return new b0(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},Dn=class x0{constructor(t=0,r=0,i=0,n=1){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(n)}get x(){return this._x}set x(t){this._x=Number(t),this._onChangeCallback?.()}get y(){return this._y}set y(t){this._y=Number(t),this._onChangeCallback?.()}get z(){return this._z}set z(t){this._z=Number(t),this._onChangeCallback?.()}get w(){return this._w}set w(t){this._w=Number(t),this._onChangeCallback?.()}set(t,r,i,n){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(n),this._onChangeCallback?.(),this}copy(t){return this.set(t.x,t.y,t.z,t.w)}clone(){return new x0(this._x,this._y,this._z,this._w)}identity(){return this.set(0,0,0,1)}setFromEuler(t,r=!0){let i=t.x,n=t.y,a=t.z,s=Math.cos(i/2),o=Math.cos(n/2),l=Math.cos(a/2),c=Math.sin(i/2),f=Math.sin(n/2),m=Math.sin(a/2);return this._x=c*o*l+s*f*m,this._y=s*f*l-c*o*m,this._z=s*o*m+c*f*l,this._w=s*o*l-c*f*m,r&&this._onChangeCallback?.(),this}setFromAxisAngle(t,r){let i=r/2,n=Math.sin(i);return this.set(t.x*n,t.y*n,t.z*n,Math.cos(i))}normalize(){let t=Math.hypot(this._x,this._y,this._z,this._w);return t===0?this.set(0,0,0,1):this.set(this._x/t,this._y/t,this._z/t,this._w/t)}setFromUnitVectors(t,r){let i=t.dot(r)+1;return i<1e-6?(Math.abs(t.x)>Math.abs(t.z)?this.set(-t.y,t.x,0,0):this.set(0,-t.z,t.y,0)).normalize():this.set(t.y*r.z-t.z*r.y,t.z*r.x-t.x*r.z,t.x*r.y-t.y*r.x,i).normalize()}multiply(t){return this.multiplyQuaternions(this,t)}multiplyQuaternions(t,r){let i=t.x,n=t.y,a=t.z,s=t.w,o=r.x,l=r.y,c=r.z,f=r.w;return this._x=i*f+s*o+n*c-a*l,this._y=n*f+s*l+a*o-i*c,this._z=a*f+s*c+i*l-n*o,this._w=s*f-i*o-n*l-a*c,this._onChangeCallback?.(),this}_onChange(t){return this._onChangeCallback=t,this}},Ai=class v0{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let t=this.elements;return t.fill(0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,this}copy(t){return this.elements.set(t.elements),this}clone(){let t=new v0;return t.copy(this),t}compose(t,r,i){return Sn(this.elements,[r.x,r.y,r.z,r.w],[t.x,t.y,t.z],[i.x,i.y,i.z]),this}multiply(t){return this.multiplyMatrices(this,t)}multiplyMatrices(t,r){return ft(this.elements,t.elements,r.elements),this}lookAt(t,r,i){return _n(this.elements,[t.x,t.y,t.z],[r.x,r.y,r.z],[i.x,i.y,i.z]),this}makeRotationFromQuaternion(t){let r=new Ze(0,0,0),i=new Ze(1,1,1);return this.compose(r,t,i)}makeTranslation(t,r,i){return this.identity(),this.elements[12]=Number(t),this.elements[13]=Number(r),this.elements[14]=Number(i),this}makeScale(t,r,i){return this.identity(),this.elements[0]=Number(t),this.elements[5]=Number(r),this.elements[10]=Number(i),this}},zo=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[4]=1,e[8]=1,this}getNormalMatrix(e){return rr(this.elements,e.elements),this}},sr=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,Ea=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,Dh={black:0,white:16777215,red:16711680,green:32768,lime:65280,blue:255,yellow:16776960,cyan:65535,aqua:65535,magenta:16711935,fuchsia:16711935,gray:8421504,grey:8421504,silver:12632256,orange:16753920,purple:8388736,pink:16761035,gold:16766720},Br=class w0{constructor(t,r,i){this.r=1,this.g=1,this.b=1,t!==void 0&&(r!==void 0&&i!==void 0?this.setRGB(t,r,i):this.set(t))}set(t){return typeof t=="number"?this.setHex(t):typeof t=="string"?this.setStyle(t):(t&&typeof t=="object"&&"r"in t&&(this.r=Number(t.r),this.g=Number(t.g),this.b=Number(t.b)),this)}setStyle(t){let r=t.trim().toLowerCase();if(r[0]==="#"){let i=r.slice(1);i.length===3||i.length===4?i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]:i.length===8&&(i=i.slice(0,6));let n=parseInt(i,16);i.length===6&&!Number.isNaN(n)&&this.setHex(n)}else if(r in Dh)this.setHex(Dh[r]);else if(r.startsWith("hsl")){let i=/^hsla?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);i&&i.length>=3&&this.setHSL((parseFloat(i[0])||0)/360,(parseFloat(i[1])||0)/100,(parseFloat(i[2])||0)/100)}else{let i=/^rgba?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);if(i&&i.length>=3){let n=a=>sr(Math.max(0,Math.min(1,(parseFloat(a)||0)/(a.endsWith("%")?100:255))));this.setRGB(n(i[0]),n(i[1]),n(i[2]))}}return this}setHSL(t,r,i){if(t=((Number(t)||0)%1+1)%1,r=Math.max(0,Math.min(1,Number(r)||0)),i=Math.max(0,Math.min(1,Number(i)||0)),r===0){let o=sr(i);return this.setRGB(o,o,o)}let n=i<=.5?i*(1+r):i+r-i*r,a=2*i-n,s=o=>(o<0&&(o+=1),o>1&&(o-=1),o<1/6?a+(n-a)*6*o:o<1/2?n:o<2/3?a+(n-a)*6*(2/3-o):a);return this.setRGB(sr(s(t+1/3)),sr(s(t)),sr(s(t-1/3)))}lerp(t,r){return this.lerpColors(this,t,r)}lerpColors(t,r,i){let n=Number(i)||0;return this.setRGB(t.r+(r.r-t.r)*n,t.g+(r.g-t.g)*n,t.b+(r.b-t.b)*n)}multiplyScalar(t){let r=Number(t)||0;return this.setRGB(this.r*r,this.g*r,this.b*r)}setScalar(t){let r=Number(t)||0;return this.setRGB(r,r,r)}setHex(t){let r=Math.floor(t);return this.setRGB(sr((r>>16&255)/255),sr((r>>8&255)/255),sr((r&255)/255))}setRGB(t,r,i){return this.r=Number(t),this.g=Number(r),this.b=Number(i),this}convertSRGBToLinear(){return this.setRGB(sr(this.r),sr(this.g),sr(this.b))}convertLinearToSRGB(){return this.setRGB(Ea(this.r),Ea(this.g),Ea(this.b))}getHex(){let t=r=>Math.round(Ea(Math.max(0,Math.min(1,r)))*255);return t(this.r)<<16|t(this.g)<<8|t(this.b)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(t){return this.setRGB(t.r,t.g,t.b)}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}clone(){return new w0(this.r,this.g,this.b)}},Vo=1234567,Uo={degToRad:e=>e*Math.PI/180,radToDeg:e=>e*180/Math.PI,clamp:(e,t,r)=>Math.max(t,Math.min(r,e)),lerp:(e,t,r)=>e+(t-e)*r,generateUUID:()=>Math.random().toString(36).substring(2,15),randInt:(e,t)=>e+Math.floor(Math.random()*(t-e+1)),randFloat:(e,t)=>e+Math.random()*(t-e),randFloatSpread:e=>e*(.5-Math.random()),seededRandom:e=>{e!==void 0&&(Vo=Number.isFinite(e)?e|0:0);let t=Vo=Vo+1831565813|0;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}},zt=class M0{constructor(t,r){if(this.needsUpdate=!1,typeof r!="number"||!Number.isInteger(r)||r<1||r>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(r)}`);Array.isArray(t)?this.array=new Float32Array(t):this.array=t,this.itemSize=r;let i=this.array?this.array.length:0;if(!Number.isFinite(i)||i<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(i)}`);this.count=Math.floor(i/r)}getX(t){return this.array[t*this.itemSize]}getY(t){return this.itemSize>=2?this.array[t*this.itemSize+1]:0}getZ(t){return this.itemSize>=3?this.array[t*this.itemSize+2]:0}setX(t,r){return this.array[t*this.itemSize]=r,this.needsUpdate=!0,this}setY(t,r){return this.array[t*this.itemSize+1]=r,this.needsUpdate=!0,this}setZ(t,r){return this.array[t*this.itemSize+2]=r,this.needsUpdate=!0,this}setXYZ(t,r,i,n){let a=t*this.itemSize;return this.array[a]=r,this.array[a+1]=i,this.array[a+2]=n,this.needsUpdate=!0,this}setUsage(t){return this}clone(){let t=this.array?.constructor||Float32Array;return new M0(new t(this.array),this.itemSize)}},Oo=class extends zt{constructor(e,t){super(e instanceof Float32Array||Array.isArray(e)?e:new Float32Array(e),t)}},jo=class extends zt{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Go=class extends zt{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},$t=class _0{constructor(){this.name="",this.attributes={},this.index=null,this.boundingBox=null}setAttribute(t,r){return this.attributes[t]=r,this}getAttribute(t){return this.attributes[t]}setIndex(t){if(t instanceof zt)this.index=t;else if(Array.isArray(t)){let r=0;for(let i of t)i>r&&(r=i);this.index=new zt(new(r>65535?Uint32Array:Uint16Array)(t),1)}else t&&t.buffer&&(this.index=new zt(t,1));return this}computeVertexNormals(){let t=this.attributes.position;if(!t)return this;let r=!1;if(typeof r=="function"){let l=r(t.array,this.index?.array);return this.setAttribute("normal",new zt(l,3)),this}let i=t.count,n=t.array,a=new Float32Array(i*3),s=this.index?.array,o=s?s.length:i;for(let l=0;l<o;l+=3){let c=(s?s[l]:l)*3,f=(s?s[l+1]:l+1)*3,m=(s?s[l+2]:l+2)*3,h=n[f],p=n[f+1],g=n[f+2],x=n[m]-h,v=n[m+1]-p,y=n[m+2]-g,A=n[c]-h,b=n[c+1]-p,w=n[c+2]-g,S=v*w-y*b,E=y*A-x*w,N=x*b-v*A;a[c]+=S,a[c+1]+=E,a[c+2]+=N,a[f]+=S,a[f+1]+=E,a[f+2]+=N,a[m]+=S,a[m+1]+=E,a[m+2]+=N}for(let l=0;l<i*3;l+=3){let c=a[l],f=a[l+1],m=a[l+2],h=Math.hypot(c,f,m)||1;a[l]=c/h,a[l+1]=f/h,a[l+2]=m/h}return this.setAttribute("normal",new zt(a,3)),this}setFromBuffers(t,r,i,n){this.setAttribute("position",new zt(t,3)),this.setAttribute("normal",new zt(r,3)),this.setAttribute("uv",new zt(i,2)),this.setIndex(n)}setFromPoints(t){let r=[];if(Array.isArray(t))for(let i of t)r.push(Number(i?.x)||0,Number(i?.y)||0,Number(i?.z)||0);return this.setAttribute("position",new zt(r,3))}computeBoundingBox(){let t=this.attributes.position,r=new Ze(1/0,1/0,1/0),i=new Ze(-1/0,-1/0,-1/0);if(t&&t.count>0)for(let n=0;n<t.count;n++){let a=t.getX(n),s=t.getY(n),o=t.getZ(n);a<r.x&&(r.x=a),s<r.y&&(r.y=s),o<r.z&&(r.z=o),a>i.x&&(i.x=a),s>i.y&&(i.y=s),o>i.z&&(i.z=o)}else r.set(0,0,0),i.set(0,0,0);return this.boundingBox={min:r,max:i},this.boundingBox}center(){let t=this.computeBoundingBox();return t.max.x<t.min.x?this:this.translate(-(t.min.x+t.max.x)*.5,-(t.min.y+t.max.y)*.5,-(t.min.z+t.max.z)*.5)}_xform(t,r){let i=this.attributes.position;if(i){let n=i.array;for(let a=0;a<n.length;a+=3)t(n,a);i.needsUpdate=!0,r&&this.computeVertexNormals(),this.computeBoundingBox()}return this}translate(t=0,r=0,i=0){return this._xform((n,a)=>{n[a]+=t,n[a+1]+=r,n[a+2]+=i})}scale(t=1,r=1,i=1){return this._xform((n,a)=>{n[a]*=t,n[a+1]*=r,n[a+2]*=i},!0)}_rot(t,r,i){let n=Math.cos(i),a=Math.sin(i);for(let s of[this.attributes.position,this.attributes.normal]){if(!s)continue;let o=s.array;for(let l=0;l<o.length;l+=3){let c=o[l+t],f=o[l+r];o[l+t]=c*n-f*a,o[l+r]=c*a+f*n}s.needsUpdate=!0}return this}rotateX(t){return this._rot(1,2,t)}rotateY(t){return this._rot(2,0,t)}rotateZ(t){return this._rot(0,1,t)}applyMatrix4(t){let r=this.attributes.position;if(r&&t?.elements){let i=new Ze;for(let n=0;n<r.count;n++)i.set(r.getX(n),r.getY(n),r.getZ(n)).applyMatrix4(t),r.setXYZ(n,i.x,i.y,i.z);this.computeVertexNormals()}return this}clone(){let t=new _0;t.name=this.name;for(let r of Object.keys(this.attributes))t.attributes[r]=this.attributes[r].clone();return this.index&&(t.index=this.index.clone()),t}dispose(){}},La=class extends $t{constructor(e=1,t=1,r=1){super();let i=e/2,n=t/2,a=r/2,s=[-i,-n,a,i,-n,a,i,n,a,-i,n,a,i,-n,-a,-i,-n,-a,-i,n,-a,i,n,-a,-i,n,a,i,n,a,i,n,-a,-i,n,-a,-i,-n,-a,i,-n,-a,i,-n,a,-i,-n,a,i,-n,a,i,-n,-a,i,n,-a,i,n,a,-i,-n,-a,-i,-n,a,-i,n,a,-i,n,-a],o=[],l=[],c=[];for(let f=0;f<6;f++){let m=f*4,h=2-(f>>1),p=f&1?-1:1;for(let g=0;g<4;g++)o.push(h===0?p:0,h===1?p:0,h===2?p:0);l.push(0,0,1,0,1,1,0,1),c.push(m,m+1,m+2,m,m+2,m+3)}this.setFromBuffers(s,o,l,c)}},Ho=class extends $t{constructor(e=1,t=1,r=1,i=1){super(),r=Math.max(1,Math.floor(r)),i=Math.max(1,Math.floor(i));let n=[],a=[],s=[],o=[];for(let l=0;l<=i;l++){let c=l/i;for(let f=0;f<=r;f++){let m=f/r;if(n.push((m-.5)*e,(.5-c)*t,0),a.push(0,0,1),s.push(m,1-c),l>0&&f>0){let h=(r+1)*l+f-1,p=h-(r+1);o.push(p,h,p+1,h,h+1,p+1)}}}this.setFromBuffers(n,a,s,o)}},qo=class extends $t{constructor(e=1,t=16,r=12,i=0,n=Math.PI*2,a=0,s=Math.PI){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let o=[],l=[],c=[],f=[],m=Math.min(a+s,Math.PI);for(let h=0;h<=r;h++){let p=h/r,g=a+p*s;for(let x=0;x<=t;x++){let v=x/t,y=i+v*n,A=-Math.cos(y)*Math.sin(g),b=Math.cos(g),w=Math.sin(y)*Math.sin(g);if(o.push(e*A,e*b,e*w),l.push(A,b,w),c.push(v,1-p),h>0&&x>0){let S=(t+1)*h+x,E=S-(t+1),N=E-1,C=S-1;(h!==1||a>0)&&f.push(E,N,S),(h!==r||m<Math.PI)&&f.push(N,C,S)}}}this.setFromBuffers(o,l,c,f)}},Ra=class extends $t{constructor(e=1,t=1,r=1,i=16,n=1,a=!1,s=0,o=Math.PI*2){super(),i=Math.max(3,Math.floor(i)),n=Math.max(1,Math.floor(Number(n)||1));let l=[],c=[],f=[],m=[],h=r/2,p=(t-e)/(r||1),g=i+1;for(let v=0;v<=n;v++){let y=v/n,A=y*(t-e)+e,b=h-y*r;for(let w=0;w<=i;w++){let S=w/i,E=s+S*o,N=Math.sin(E),C=Math.cos(E),_=Math.hypot(N,p,C)||1;if(l.push(A*N,b,A*C),c.push(N/_,p/_,C/_),f.push(S,1-y),v<n&&w<i){let P=v*g+w,R=P+g;m.push(P,R,P+1,R,R+1,P+1)}}}let x=(v,y)=>{if(a||v<=0)return;let A=y*h,b=l.length/3;l.push(0,A,0),c.push(0,y,0),f.push(.5,.5);let w=b+1;for(let S=0;S<=i;S++){let E=s+S/i*o,N=Math.sin(E),C=Math.cos(E);l.push(v*N,A,v*C),c.push(0,y,0),f.push(C*.5+.5,.5+y*N*.5),S<i&&m.push(b,w+S+(y>0?0:1),w+S+(y>0?1:0))}};x(e,1),x(t,-1),this.setFromBuffers(l,c,f,m)}},Wo=class extends Ra{constructor(e=1,t=1,r=16,i=1,n=!1,a=0,s=Math.PI*2){super(0,e,t,r,i,n,a,s)}},Ko=class extends $t{constructor(e=1,t=.4,r=12,i=48,n=Math.PI*2){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let a=[],s=[],o=[],l=[];for(let c=0;c<=r;c++){let f=c/r*Math.PI*2,m=Math.cos(f),h=Math.sin(f);for(let p=0;p<=i;p++){let g=p/i*n,x=Math.cos(g),v=Math.sin(g);if(a.push((e+t*m)*x,(e+t*m)*v,t*h),s.push(m*x,m*v,h),o.push(p/i,c/r),c>0&&p>0){let y=(i+1)*c+p-1,A=y-(i+1);l.push(y,A,y+1,A,A+1,y+1)}}}this.setFromBuffers(a,s,o,l)}};function kh(e,t,r,i,n){let a=Math.max(2,Math.min(256,Math.floor(Number(t)||64))),s=Math.max(3,Math.min(64,Math.floor(Number(r)||8))),o=Number(i)||.1,l=[],c=[],f=[],m=[],h=[],p=new Ze,g=new Ze,x=new Ze;for(let y=0;y<=a;y++){let A=new Ze;n(y/a,A),h.push(A)}let v=s+1;for(let y=0;y<=a;y++){let A=y/a,b=h[y];p.subVectors(h[Math.min(a,y+1)],h[Math.max(0,y-1)]).normalize(),y===0&&g.set(Math.abs(p.y)>.9?1:0,Math.abs(p.y)>.9?0:1,0),x.crossVectors(p,g).normalize(),g.crossVectors(x,p).normalize();for(let w=0;w<=s;w++){let S=w/s*Math.PI*2,E=-Math.cos(S),N=Math.sin(S),C=E*g.x+N*x.x,_=E*g.y+N*x.y,P=E*g.z+N*x.z;if(l.push(b.x+o*C,b.y+o*_,b.z+o*P),c.push(C,_,P),f.push(A,w/s),y>0&&w>0){let R=v*(y-1)+w-1,I=R+v;m.push(R,I,R+1,I,I+1,R+1)}}}e.setFromBuffers(l,c,f,m)}var Xo=class extends $t{constructor(e=1,t=.4,r=64,i=8,n=2,a=3){super(),r=Math.floor(r),i=Math.floor(i),kh(this,r,i,t,(s,o)=>{let l=s*n*Math.PI*2,c=a/n*l,f=e*(2+Math.cos(c))*.5;o.set(f*Math.cos(l),f*Math.sin(l),e*Math.sin(c)*.5)})}},hi=class{getPoint(e,t=new Ze){return t}getPointAt(e,t=new Ze){return this.getPoint(e,t)}getTangent(e,t=new Ze){return t.subVectors(this.getPoint(Math.min(1,e+.001)),this.getPoint(Math.max(0,e-.001))).normalize()}getPoints(e=5){let t=Math.max(1,Math.min(512,Math.floor(Number(e)||5))),r=[];for(let i=0;i<=t;i++)r.push(this.getPoint(i/t));return r}getSpacedPoints(e=5){return this.getPoints(e)}},Yo=class extends hi{constructor(e=new Ze,t=new Ze){super(),this.v1=e,this.v2=t}getPoint(e,t=new Ze){return t.lerpVectors(this.v1,this.v2,e)}},Qo=class extends hi{constructor(e=new Ze,t=new Ze,r=new Ze){super(),this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new Ze){return t.lerpVectors(this.v0,this.v1,e).lerp(new Ze().lerpVectors(this.v1,this.v2,e),e)}},Zo=class extends hi{constructor(e=new Ze,t=new Ze,r=new Ze,i=new Ze){super(),this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new Ze){let r=new Ze().lerpVectors(this.v0,this.v1,e),i=new Ze().lerpVectors(this.v1,this.v2,e),n=new Ze().lerpVectors(this.v2,this.v3,e);return t.lerpVectors(r.lerp(i,e),i.lerp(n,e),e)}},Jo=class extends hi{constructor(e=[],t=!1){super(),this.points=Array.isArray(e)?e:[],this.closed=!!t}getPoint(e,t=new Ze){let r=this.points,i=r.length;if(!i)return t.set(0,0,0);if(i===1)return t.copy(r[0]);let n=(this.closed?i:i-1)*Math.max(0,Math.min(1,Number(e)||0)),a=Math.floor(n),s=n-a;!this.closed&&a>=i-1&&(a=i-2,s=1);let o=x=>r[this.closed?(x%i+i)%i:Math.max(0,Math.min(i-1,x))],l=o(a-1),c=o(a),f=o(a+1),m=o(a+2),h=s*s,p=h*s,g=(x,v,y,A)=>.5*(2*v+(y-x)*s+(2*x-5*v+4*y-A)*h+(3*v-x-3*y+A)*p);return t.set(g(l.x,c.x,f.x,m.x),g(l.y,c.y,f.y,m.y),g(l.z,c.z,f.z,m.z))}},Ia=class extends $t{constructor(e=[new ar(0,-.5),new ar(.5,0),new ar(0,.5)],t=12,r=0,i=Math.PI*2){super();let n=Array.isArray(e)&&e.length>=2?e:[new ar(.2,0),new ar(.2,.5)],a=Math.max(3,Math.min(128,Math.floor(Number(t)||12))),s=[],o=[],l=[],c=[],f=n.length;for(let m=0;m<=a;m++){let h=m/a,p=r+h*i,g=Math.sin(p),x=Math.cos(p),v=m*f;for(let y=0;y<f;y++){let A=n[y],b=Number(A?.x)||0,w=Number(A?.y)||0;s.push(b*g,w,b*x);let S=n[Math.max(0,y-1)],E=n[Math.min(f-1,y+1)],N=(Number(E?.x)||0)-(Number(S?.x)||0),C=(Number(E?.y)||0)-(Number(S?.y)||0),_=Math.hypot(C,N)||1;if(o.push(C/_*g,-N/_,C/_*x),l.push(h,y/(f-1)),m<a&&y<f-1){let P=v+y,R=P+f;c.push(P,R,P+1,R,R+1,P+1)}}}this.setFromBuffers(s,o,l,c)}},el=class extends $t{constructor(e,t=64,r=1,i=8,n=!1){super(),kh(this,t,i,r,(a,s)=>{let o=e?.getPointAt??e?.getPoint;if(typeof o=="function"){let l=o.call(e,a,s);l&&l!==s&&s.copy(l)}else s.set(0,a,0)})}},$a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",kn=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new ar(1,1),this.offset=new ar(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},tl=class extends kn{constructor(e=null,t=1,r=1,i=1023,n=1009,a,s=1001,o=1001,l=1003,c=1003,f=1,m=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1,this._sig=0;let h=Number(t),p=Number(r),g=e&&typeof e.length=="number"?e:null;this.width=h,this.height=p,this.image={data:g,width:h,height:p},this.format=Number(i)||1023,this.type=Number(n)||1009,this.wrapS=Number(s)||1001,this.wrapT=Number(o)||1001,this.magFilter=Number(l)||1003,this.minFilter=Number(c)||1003,this.colorSpace=m||"",this._bake()}get needsUpdate(){return!1}set needsUpdate(e){e&&this._bake()}_bake(){let e=this.image,t=e?.data,r=Number(e?.width??this.width),i=Number(e?.height??this.height);if(!t||!t.length||!(r>0&&i>0)||r>2048||i>2048){this.source="";return}let n=Math.max(1,r|0),a=Math.max(1,i|0),s=n*a,o=this.format,l=o===1021||o===1024||o===1028||t.length===s?1:o===1025||o===1030||t.length===s*2?2:o===1022||t.length===s*3?3:4,c=this.type===1015||this.type===1016||t instanceof Float32Array||t instanceof Float64Array,f=Math.min(n,64),m=Math.min(a,64),h=(this.flipY?257:1)^this.colorSpace.length^t.length,p=Math.max(1,t.length>>6|0);for(let I=0;I<t.length;I+=p)h=Math.imul(h^(t[I]*256|0),16777619)|0;if(h===this._sig&&this.source)return;this._sig=h;let g=m*(1+f*4),x=new Uint8Array(68+g),v=new DataView(x.buffer);v.setUint32(0,2303741511),v.setUint32(4,218765834),v.setUint32(8,13),v.setUint32(12,1229472850),v.setUint32(16,f),v.setUint32(20,m),x[24]=8,x[25]=6,v.setUint32(29,Eo(x.subarray(12,29))),v.setUint32(33,g+11),v.setUint32(37,1229209940),x[41]=120,x[42]=1,x[43]=1,v.setUint16(44,g,!0),v.setUint16(46,~g&65535,!0);let y=48,A=1,b=0,w=0,S=0,E=0,N=0,C=I=>{if(!Number.isFinite(I))return 0;let F=c&&I<=1?I*255:I;return F>0?F<255?F+.5|0:255:0};for(let I=0;I<m;I++){let F=I*a/m|0,V=this.flipY?a-1-F:F;x[y++]=0,b+=A;for(let Y=0;Y<f;Y++){let J=(V*n+(Y*n/f|0))*l,re=o===1021?255:C(t[J]??0),Q=l>=3||o===1030?C(t[J+1]??0):re,ee=l>=3?C(t[J+2]??0):o===1030?0:re,k=l===4?C(t[J+3]??255):o===1021?C(t[J]??255):o===1025?C(t[J+1]??255):255;x[y++]=re,A+=re,b+=A,x[y++]=Q,A+=Q,b+=A,x[y++]=ee,A+=ee,b+=A,x[y++]=k,A+=k,b+=A,w+=re,S+=Q,E+=ee,N+=k}A%=65521,b%=65521}v.setUint32(y,(b<<16|A)>>>0),v.setUint32(y+4,Eo(x.subarray(37,y+4))),v.setUint32(y+12,1229278788),v.setUint32(y+16,2923585666);let _=f*m*255,P=this.colorSpace==="srgb-linear";this.avgColor=[P?w/_:sr(w/_),P?S/_:sr(S/_),P?E/_:sr(E/_),N/_];let R=["data:image/png;base64,"];for(let I=0;I<x.length;I+=3){let F=x[I]<<16|(x[I+1]??0)<<8|(x[I+2]??0);R.push($a[F>>18&63]+$a[F>>12&63]+(I+1<x.length?$a[F>>6&63]:"=")+(I+2<x.length?$a[F&63]:"="))}this.source=R.join("")}},rl=class{load(e,t){let r=new kn(e);return t?.(r),r}};function kt(e,t){return e!==void 0?Number(e):t}function il(e,t){return e!==void 0?!!e:t}var _r=class{constructor(e={}){this.name=e.name||"",this.color=new Br(e.color??16777215),this._em=e.emissive!==void 0,this.emissive=new Br(e.emissive??0),this.emissiveIntensity=kt(e.emissiveIntensity,1),this.roughness=kt(e.roughness,e.roughnessMap?1:.5),this.metalness=kt(e.metalness,e.metalnessMap?1:0),this.opacity=kt(e.opacity,1),this.transparent=il(e.transparent,!1),this.wireframe=il(e.wireframe,!1),this.side=kt(e.side,2),this.doubleSided=il(e.doubleSided,!0),this.map=e.map||null,this.normalMap=e.normalMap||null;let t=e.normalScale;this.normalScale=typeof t=="number"?new ar(t,t):new ar(kt(t?.x,1),kt(t?.y,1)),this.roughnessMap=e.roughnessMap||null,this.metalnessMap=e.metalnessMap||null,this.emissiveMap=e.emissiveMap||null,this.aoMap=e.aoMap||null,this.aoMapIntensity=kt(e.aoMapIntensity,1),this.bumpMap=e.bumpMap||null,this.bumpScale=kt(e.bumpScale,1),this.clearcoat=kt(e.clearcoat,0),this.clearcoatRoughness=kt(e.clearcoatRoughness,0),this.sheen=kt(e.sheen,0),this.sheenColor=new Br(e.sheenColor??0),this.sheenRoughness=kt(e.sheenRoughness,0),this.transmission=kt(e.transmission,0),this.thickness=kt(e.thickness,0),this.attenuationColor=new Br(e.attenuationColor??16777215),this.attenuationDistance=kt(e.attenuationDistance,1/0),this.ior=kt(e.ior,1.5),this.dispersion=kt(e.dispersion,0),this.iridescence=kt(e.iridescence,0),this.iridescenceIOR=kt(e.iridescenceIOR,1.3)}dispose(){}},Gi=class extends _r{},nl=class extends _r{},al=class extends _r{},sl=class extends _r{},ol=class extends _r{},zr=class S0{constructor(){this.name="",this.matrixAutoUpdate=!0,this.visible=!0,this._castShd=!1,this._castShdSet=!1,this._recvShd=!1,this._recvShdSet=!1,this.parent=null,this.children=[],this.userData={},this.position=new Ze,this.rotation=new Ca,this.quaternion=new Dn,this.scale=new Ze(1,1,1),this.matrix=new Ai,this.matrixWorld=new Ai,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let t=this.quaternion,r=Math.atan2(2*(t.w*t.x+t.y*t.z),1-2*(t.x*t.x+t.y*t.y)),i=Math.asin(Math.max(-1,Math.min(1,2*(t.w*t.y-t.z*t.x)))),n=Math.atan2(2*(t.w*t.z+t.x*t.y),1-2*(t.y*t.y+t.z*t.z));this.rotation.set(r,i,n)})}get castShadow(){return this._castShd}set castShadow(t){this._castShd=!!t,this._castShdSet=!0}get receiveShadow(){return this._recvShd}set receiveShadow(t){this._recvShd=!!t,this._recvShdSet=!0}add(...t){for(let r of t)r&&r instanceof S0&&(r.parent&&r.parent.remove(r),r.parent=this,this.children.push(r));return this}remove(...t){for(let r of t){let i=this.children.indexOf(r);i!==-1&&(r.parent=null,this.children.splice(i,1))}return this}traverse(t){let r=new Set,i=[this];for(;i.length>0;){let n=i.pop();if(!n||typeof n!="object"||r.has(n))continue;r.add(n),t(n);let a=n.children;if(Array.isArray(a))for(let s=a.length-1;s>=0;s--)i.push(a[s])}}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(t=!1){this.traverse(r=>{Fh(r),(r.matrixAutoUpdate||t)&&r.updateMatrix?.(),r.parent&&r.parent.matrixWorld?r.matrixWorld?.multiplyMatrices(r.parent.matrixWorld,r.matrix):r.matrix&&r.matrixWorld?.copy(r.matrix)})}lookAt(t,r,i){let n=typeof t=="object"?t:new Ze(t,r,i);this.target instanceof Ze?this.target.copy(n):this.target?.position instanceof Ze&&this.target.position.copy(n),this.updateMatrixWorld(!0);let a=new Ai;a.lookAt(this.position,n,new Ze(0,1,0));let s=a.elements,o=s[0],l=s[4],c=s[8],f=s[1],m=s[5],h=s[9],p=s[2],g=s[6],x=s[10],v=o+m+x;if(v>0){let y=.5/Math.sqrt(v+1);this.quaternion.set((g-h)*y,(c-p)*y,(f-l)*y,.25/y)}}translateOnAxis(t,r){let i=t.clone().applyMatrix4(new Ai().makeRotationFromQuaternion(this.quaternion)).multiplyScalar(r);return this.position.add(i),this}translateX(t){return this.translateOnAxis(new Ze(1,0,0),t)}translateY(t){return this.translateOnAxis(new Ze(0,1,0),t)}translateZ(t){return this.translateOnAxis(new Ze(0,0,1),t)}rotateX(t){return this.rotation.x+=t,this}rotateY(t){return this.rotation.y+=t,this}rotateZ(t){return this.rotation.z+=t,this}_chain(){let t=[];for(let r=this;r&&t.length<64;r=r.parent)t.push(r);return t}_syncWorld(){let t=this._chain();for(let r=t.length-1;r>=0;r--){let i=t[r];i.updateMatrix?.(),i.parent?.matrixWorld?i.matrixWorld.multiplyMatrices(i.parent.matrixWorld,i.matrix):i.matrixWorld?.copy(i.matrix)}return this.matrixWorld.elements}getWorldPosition(t=new Ze){let r=this._syncWorld();return t.set(r[12],r[13],r[14])}getWorldScale(t=new Ze){let r=this._syncWorld();return t.set(Math.hypot(r[0],r[1],r[2]),Math.hypot(r[4],r[5],r[6]),Math.hypot(r[8],r[9],r[10]))}getWorldDirection(t=new Ze){let r=this._syncWorld();return t.set(r[8],r[9],r[10]).normalize()}getWorldQuaternion(t=new Dn){let r=this._chain();t.set(0,0,0,1);for(let i=r.length-1;i>=0;i--)t.multiply(r[i].quaternion);return t}clone(t=!0){let r=typeof this._cloneCustom=="function"?this._cloneCustom():this instanceof Pi?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof Yr?new Yr(this.geometry,this.material):new this.constructor;if(this instanceof fi){r.color.copy(this.color),r.intensity=this.intensity,r.shadow.copy(this.shadow);let i=this.target;i?.position&&r.target?.position&&r.target.position.copy(i.position),this instanceof Za&&r.groundColor.copy(this.groundColor)}r.name=this.name,r.position.copy(this.position),r.quaternion.copy(this.quaternion),r.scale.copy(this.scale),r.visible=this.visible,this._castShdSet&&(r.castShadow=this.castShadow),this._recvShdSet&&(r.receiveShadow=this.receiveShadow);try{r.userData=JSON.parse(JSON.stringify(this.userData||{}))}catch{r.userData={...this.userData||{}}}if(t)for(let i of this.children)r.add(i.clone(!0));return r}},ll=class extends zr{},Yr=class extends zr{constructor(e,t){super(),this.isMesh=!0;let r=Array.isArray(t)?t[0]:t;this.geometry=e instanceof $t?e:e?(Zr("unsupported geometry","BoxGeometry"),new La(.5,.5,.5)):new $t,this.material=r instanceof _r?r:r?(Zr("unsupported material","MeshStandardMaterial"),new Gi({color:13421772})):new Gi}};function Fh(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=We().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var Hi=1e4,Da=class extends Yr{constructor(e,t,r=1){super(e,t),this.instanceColor=null,this.isInstancedMesh=!0;let i=Number(r);if(!Number.isFinite(i)||i<0||i>Hi)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${Hi})`);this.count=Math.floor(i);let n=new Float32Array(this.count*16);for(let a=0;a<this.count;a++){let s=a*16;n[s]=1,n[s+5]=1,n[s+10]=1,n[s+15]=1}this.instanceMatrix=new zt(n,16)}setMatrixAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t||!t.elements)return;let i=this.instanceMatrix.array,n=r*16;if(!(n+16>i.length))for(let a=0;a<16;a++){let s=Number(t.elements[a]);i[n+a]=Number.isFinite(s)?s:a%5===0?1:0}}getMatrixAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t||!t.elements)return;let i=this.instanceMatrix.array,n=r*16;if(!(n+16>i.length))for(let a=0;a<16;a++)t.elements[a]=i[n+a]}setColorAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let a=new Float32Array(this.count*3);a.fill(1),this.instanceColor=new zt(a,3)}let i=this.instanceColor.array,n=r*3;i[n]=Number.isFinite(t.r)?t.r:1,i[n+1]=Number.isFinite(t.g)?t.g:1,i[n+2]=Number.isFinite(t.b)?t.b:1}getColorAt(e,t){let r=Math.floor(Number(e));if(!Number.isFinite(r)||r<0||r>=this.count||!t)return;if(!this.instanceColor||this.instanceColor.array.length<(r+1)*3){t.setRGB(1,1,1);return}let i=this.instanceColor.array,n=r*3;t.setRGB(i[n],i[n+1],i[n+2])}dispose(){}},ka=class A0{constructor(){this.mapSize=new ar(1024,1024),this.bias=-5e-4,this.normalBias=.015,this.radius=1.5,this.camera={near:.1,far:100,left:-5,right:5,top:5,bottom:-5,fov:50,updateProjectionMatrix:()=>{}}}copy(t){return this.mapSize.copy(t.mapSize),this.bias=Number(t.bias),this.normalBias=Number(t.normalBias),this.radius=Number(t.radius),this}clone(){return new A0().copy(this)}},fi=class extends zr{constructor(e=16777215,t=1){super(),this.isLight=!0,this.shadow=new ka,this.color=new Br(e),this.intensity=Number(t),this.type="directional"}},Fa=class extends fi{constructor(e,t){super(e,t),this.type="ambient"}},ul=class extends fi{constructor(e,t){super(e,t),this.target=new zr,this.type="directional"}},Ba=class extends fi{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},za=class extends zr{},cl=class extends za{constructor(e=45,t=1,r=.1,i=1e3){super(),this.target=new Ze(0,0,0),this.fov=Number(e),this.aspect=Number(t),this.near=Number(r),this.far=Number(i)}},Va=class extends zr{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return Qr.validate(this),Vi(this)}toGLB(){return Qr.validate(this),En(this)}toUSDZ(){return Qr.validate(this),In(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof Yr){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},Ua=Vi,Oa=En,hl=In;We().makePngDeflater=oh;var Qr=class{static validate(e){let t=0,r=0,i=0,n=new Set,a=(o,l,c)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${o} (${l}). Found: ${c}`)},s=(o,l)=>{if(!Number.isFinite(l))throw new Error(`SecurityError: Scene reports a non-finite ${o} count (${String(l)}), which cannot be bounds-checked.`);return l};e.traverse(o=>{if(Fh(o),o instanceof Yr||o.geometry?.attributes?.position?.count){if(i++,i>1e3&&a("MESHES",1e3,i),o instanceof Da){let c=s("instance",o.count);(c<0||c>Hi)&&a("INSTANCES",Hi,c)}let l=o.geometry;if(l){let c=0;if(l.attributes.position&&(c=s("vertex",l.attributes.position.count),t+=c,t>1e5&&a("VERTICES",1e5,t)),l.index){let f=s("index",l.index.count);r+=f,r>3e5&&a("INDICES",3e5,r);let m=l.index.array;if(m&&c>0){let h=Math.min(f,m.length);for(let p=0;p<h;p++){let g=m[p];if(!Number.isFinite(g)||g<0||g>=c)throw new Error(`SecurityError: Index buffer value (${String(g)}) out of vertex bounds [0, ${c}).`)}}}}if(o.material){let c=o.material;for(let f of["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap","bumpMap"])c[f]&&n.add(c[f])}}}),n.size>16&&a("TEXTURES",16,n.size);for(let o of n){let l=o,c=l.image,f=Number(c?.width??l.width??0)||0,m=Number(c?.height??l.height??0)||0;(!Number.isFinite(f)||!Number.isFinite(m)||f>2048||m>2048)&&a("TEXTURE_DIMENSION",2048,Math.max(f,m))}}},fl=class{constructor(e={}){this.shadowMap={enabled:!1,type:0},this.capabilities={isWebGL2:!0,maxTextures:16},this.boundViewer=null,this.hasInitialModelRendered=!1,this.domElement=e.canvas||(typeof document<"u"?document.createElement("canvas"):{}),e.viewer&&(this.boundViewer=e.viewer),e.container?.threeLiveViewer&&(this.boundViewer=e.container.threeLiveViewer),e.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=e.canvas.parentElement.threeLiveViewer);let t=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=e.isSandboxed||t,this.containerId=e.containerId||""}setSize(e,t){return this}setPixelRatio(e){return this}setClearColor(e,t=1){let r=new Br(e);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(r.r,r.g,r.b,t),this}clear(){return this}dispose(){}render(e,t){if(this.isSandboxed){Qr.validate(e);let i=(n,a)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(a&&a.length?self.postMessage(n,a):self.postMessage(n))};if(this.hasInitialModelRendered){let n=e.getMeshTransforms(),a={};for(let[s,o]of n.entries())a[s]=Array.from(o);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:a})}else{this.hasInitialModelRendered=!0;let n=Ua(e),a=Oa(e),s=(n.lights||[]).map(o=>({type:o.type,color:o.color,intensity:o.intensity,position:o.position}));i({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:a.buffer,dynamicLights:s,camera:t?{fov:t.fov||60,position:[t.position.x,t.position.y,t.position.z]}:void 0},[a.buffer])}return}let r=this.boundViewer;!r&&this.domElement?.parentElement&&this.domElement.parentElement.threeLiveViewer&&(r=this.domElement.parentElement.threeLiveViewer,this.boundViewer=r),!r&&typeof window<"u"&&(r=window.__three_live_active_viewer__,this.boundViewer=r),r&&typeof r.loadModel=="function"&&(r._hasThreeLiveModelLoaded?typeof r.updateMeshTransforms=="function"&&r.updateMeshTransforms(e.getMeshTransforms()):(r.loadModel(e.toCanvas3D()),r._hasThreeLiveModelLoaded=!0))}};function Bh(){return typeof globalThis<"u"&&typeof globalThis.__three_live_sim_time_ms__=="number"?globalThis.__three_live_sim_time_ms__:typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ml=class{constructor(e=!0){this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1,this.autoStart=e,e&&this.start()}start(){this.startTime=Bh(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running&&this.start(),this.running){let t=Bh();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Hp(){}var qi=new Proxy(Hp,{get:(e,t)=>{if(t==="isProxy")return!0;if(!(t==="constructor"||t==="__proto__"||t==="prototype"))return t==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:t==="shadowMap"?{enabled:!1,type:0}:t==="capabilities"?{isWebGL2:!0,maxTextures:16}:t===Symbol.toPrimitive?()=>0:qi},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>qi,construct:()=>qi}),zh=(()=>{try{if(typeof document>"u")return null;let e=document.currentScript;return e?.src?e.src:e?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([e.textContent],{type:"text/javascript"})):null}catch{return null}})();function ja(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Ti(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,ja());return!(i.protocol!=="https:"&&i.protocol!=="http:"&&i.protocol!=="blob:"||t?.requireSameOrigin&&i.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&i.origin!==location.origin)}catch{return!1}}var Vh,Fn;function pl(e){if(!Ti(e))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${e}".`);let t=globalThis.trustedTypes;if(!t||typeof t.createPolicy!="function")return e;if(Fn===void 0||Vh!==t){Vh=t;try{Fn=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!Ti(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{Fn=null}}return Fn?Fn.createScriptURL(e):e}function Uh(e){We().sandboxEngineSrc=e}function Ga(){let e=We().sandboxEngineSrc;if(e)return e;if(zh)return zh;try{if(typeof document>"u")return null;let t=ja(),r=Array.from(document.querySelectorAll("script[src]"));for(let i of r){let n=i.src;if(!n)continue;let a=new URL(n,t).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(a)&&Ti(n,{requireSameOrigin:!0}))return n}}catch{}return null}function dl(e,t){if(!Ti(e))throw new Error(`SecurityError: Disallowed ${t} URL "${e}" (http:, https:, or blob: required).`);return new URL(e,ja()).href}function qp(){let e=Ga();if(!e)throw new Error("SecurityError: Could not locate Three-Live bundle URL for worker sandbox; set ThreeLiveElement.sandboxEngineSrc explicitly.");return dl(e,"sandbox engine")}function Oh(e){We().sandboxIframeSrc=e}function gl(){let e=We().sandboxIframeSrc;if(e)return e;let t=Ga();if(!t||!Ti(t))return null;let r=new URL(t,ja());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function Wp(){let e=gl();if(!e)throw new Error("SecurityError: Could not locate three-live-sandbox.html; set ThreeLiveElement.sandboxIframeSrc explicitly.");return dl(e,"sandbox iframe")}function jh(e){We().allowClientScripts=e}function yl(){return!!We().allowClientScripts}function Kp(e){return dl(e,"procedural scene script")}var Xp="fetch XMLHttpRequest WebSocket WebSocketStream WebTransport EventSource importScripts Request Response Headers navigator WorkerNavigator WorkerLocation RTCPeerConnection RTCDataChannel FontFace FontFaceSet fonts PerformanceObserver ReportingObserver indexedDB IDBFactory caches CacheStorage Cache cookieStore StorageManager FileSystemHandle Worker SharedWorker ServiceWorker ServiceWorkerContainer ServiceWorkerRegistration registration clients BroadcastChannel MessageChannel MessagePort createImageBitmap OffscreenCanvas WebAssembly WorkerGlobalScope DedicatedWorkerGlobalScope trustedTypes TrustedTypePolicyFactory SharedArrayBuffer Atomics".split(" ");function Yp(e,t,r){let i=self,n=e.nonce,a=e.engineSrc,s=e.allowedScriptUrl,o=e.allowClientScripts,l=e.revoked,c=i.postMessage.bind(i),f=null;try{f=r?r(i.CompressionStream):null}catch{}let m=null;function h(N,C){let _=()=>C&&C.length?c(N,C):c(N);m?m=m.then(_,_):_()}function p(N){h({type:"ERROR",nonce:n,message:String(N)})}let g=typeof i.importScripts=="function"?i.importScripts.bind(i):null,x=s,v=null;try{let N=a;if(typeof i.trustedTypes<"u"&&i.trustedTypes&&typeof i.trustedTypes.createPolicy=="function")try{let C={createScriptURL:function(P){if(P!==a&&(!s||P!==s))throw new TypeError("Disallowed worker importScripts URL");return P}};o&&(C.createScript=function(P){return String(P)});let _=i.trustedTypes.createPolicy("three-live#worker-boot",C);N=_.createScriptURL(a),s&&(x=_.createScriptURL(s)),o&&typeof _.createScript=="function"&&(v=_.createScript.bind(_))}catch{}g(N)}catch(N){p('Sandbox failed to load "'+a+'" (must be an IIFE bundle like three-live.min.js): '+(N&&N.message||N));return}let y=i.THREE;if(!y||typeof y.Scene!="function"){p('Sandbox "'+a+'" did not install THREE; point sandboxEngineSrc at three-live.min.js.');return}if(Array.isArray(t)){let N=i.__THREE_LIVE_REGISTRY__;for(let C=0;C<t.length;C++)if(typeof t[C]=="function")try{t[C](y,N)}catch{}}function A(N,C,_){let P=i;for(;P&&P!==Object.prototype;){if(!_&&P!==i)try{delete P[N]}catch{}if(!_||P===i||Object.prototype.hasOwnProperty.call(P,N))try{Object.defineProperty(P,N,_?{value:C,writable:!1,configurable:!1}:{value:C,writable:!1,configurable:!1,enumerable:!1})}catch{}try{P=Object.getPrototypeOf(P)}catch{break}}}for(let N=0;N<l.length;N++)A(l[N],void 0);A("performance",Object.freeze({now:function(){return Date.now()}}));let b=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],w=!1;function S(N,C){if(N.type==="3D_MODEL_READY"){if(w)return;w=!0}if(N.nonce=n,N.type==="3D_MODEL_READY"&&f&&N.glbBuffer instanceof ArrayBuffer){let _=N.glbBuffer;m=(m||Promise.resolve()).then(()=>f.glb(new Uint8Array(_))).then(P=>{P.buffer!==_&&(N.glbBuffer=P.byteOffset===0&&P.byteLength===P.buffer.byteLength?P.buffer:P.slice().buffer),c(N,[N.glbBuffer])},()=>c(N,[_]));return}C&&C.length?h(N,C):h(N)}A("postMessage",function(N,C){if(!N||b.indexOf(N.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+b.join(", ")+").");S(N,C)},!0);let E=!1;i.onmessage=function(N){let C=N&&N.data;if(!C||C.nonce!==n||C.type!=="EXECUTE"&&C.type!=="EXECUTE_URL"||E)return;E=!0;let _=C.texturePack;if(_&&typeof _=="object"){let P=Object.create(null),R=0;for(let I of Object.keys(_)){let F=_[I],V=F&&F.size;R<64&&/^[0-9a-f]{16}$/.test(I)&&(V===256||V===512||V===1024)&&F.rgba instanceof Uint8Array&&F.rgba.length===V*V*4&&(P[I]=Object.freeze({size:V,rgba:F.rgba}),R++)}i.__three_live_texture_pack__=Object.freeze(P)}try{let P=new y.Scene,R=new y.PerspectiveCamera(60,1,.1,1e3),I=new y.WebGLRenderer({isSandboxed:!0});if(C.type==="EXECUTE_URL"){if(!s||C.scriptUrl!==s||typeof g!="function"){p("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let F=x||s,V=g;if(g=null,x=null,i.THREE=y,i.scene=P,i.camera=R,i.renderer=I,V(F),typeof i.__THREE_LIVE_SCENE__=="function"){let Y=i.__THREE_LIVE_SCENE__(y,P,R,I);Y&&typeof Y.toGLB=="function"&&(P=Y)}else i.scene&&typeof i.scene.toGLB=="function"&&(P=i.scene)}else{if(!o){p("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let F=v?(0,eval)(v(`(function (THREE, scene, camera, renderer) {
370
393
  return (function () {
371
- `+y.script+`
394
+ `+C.script+`
372
395
  ;
373
396
  return typeof scene === "object" && scene ? scene : undefined;
374
397
  })();
375
398
  })`)):new Function("THREE","scene","camera","renderer",`return (function () {
376
- `+y.script+`
399
+ `+C.script+`
377
400
  ;
378
401
  return typeof scene === "object" && scene ? scene : undefined;
379
- })();`);c=null;let T=G(d,M,P,F);T&&typeof T.toGLB=="function"&&(M=T)}if(!x){d.SceneQuotaValidator&&d.SceneQuotaValidator.validate(M);let G=M.toGLB(),T=G instanceof ArrayBuffer?G:G.buffer.slice(G.byteOffset,G.byteOffset+G.byteLength);b({type:"3D_MODEL_READY",glbBuffer:T},[T])}a({type:"DONE",nonce:i})}catch(M){u(M&&M.message||M)}}},a({type:"READY",nonce:i})}function ii(e,t,r){let i=r?.allowedScriptUrl??null,n=r?.allowClientScripts??i===null,s={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:n,revoked:El},l=(Ae().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${Cl.toString()})(${JSON.stringify(s)},[${l}]);`}function Pa(e){e.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),e.onToast?.("Security Error: script timed out and was stopped.")}var Rt=0;function Ea(){try{let e=new Uint32Array(4);return globalThis.crypto?.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function Nl(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var Ll=1024,_l=256;function Ca(e){if(!Array.isArray(e)&&!(e instanceof Float32Array)||e.length!==16)return!1;for(let t=0;t<16;t++){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))return!1}return!0}function ni(e,t){if(!e||typeof e!="object")return null;let r=e;if(r.nonce!==t)return null;switch(r.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof r.message=="string"?r.message:String(r.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,Ll)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let n of i)if(!Ca(n))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:i}}if(i&&typeof i=="object"){let n=Object.keys(i);if(n.length>1e3)return null;let s=Object.create(null),l=i;for(let o of n){if(o.length>_l||o==="__proto__"||o==="constructor"||o==="prototype")return null;let a=l[o];if(!Ca(a))return null;s[o]=a}return{type:"3D_UPDATE_TRANSFORMS",transforms:s}}return null}case"3D_MODEL_READY":{let i=r.glbBuffer;return!(i instanceof ArrayBuffer)||i.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:i}}default:return null}}function Il(e){let t=Nl(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Na(e,t,r,i){switch(e.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":t.onUpdateTransforms?.(e.transforms);return;case"3D_MODEL_READY":if(i.modelDispatched)return;i.modelDispatched=!0,t.onModelReady(e.payload);return;case"DONE":r();return;case"ERROR":r(),t.onError?.(new Error(`Worker script error: ${e.message}`));return;default:return e}}function Dl(e,t,r,i){let n=Ea(),s=ii(t,n,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),l=document.createElement("iframe");l.setAttribute("sandbox","allow-scripts"),l.setAttribute("aria-hidden","true"),l.tabIndex=-1,l.style.display="none",l.src=r,Rt++;let o=!1,a=!1,u={modelDispatched:!1},h,m=()=>{if(o||a)return;let g=l.contentWindow;!g||typeof g.postMessage!="function"||(a=!0,g.postMessage(e.kind==="url"?{type:"SANDBOX_RUN",nonce:n,workerSource:s,scriptUrl:e.scriptUrl}:{type:"SANDBOX_RUN",nonce:n,workerSource:s,script:e.script},"*"))},c=()=>{},d=g=>{if(o||!l.contentWindow||g.source!==l.contentWindow)return;let x=g.data;if(x&&typeof x=="object"&&x.type==="IFRAME_READY"){m();return}let b=ni(x,n);b&&Na(b,i,c,u)};c=()=>{o||(o=!0,h!==void 0&&clearTimeout(h),Rt=Math.max(0,Rt-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",d),typeof l.remove=="function"?l.remove():l.parentNode&&l.parentNode.removeChild(l))},h=setTimeout(()=>{o||(c(),Pa(i))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",d),l.onload=()=>{m()},l.onerror=()=>{c(),i.onError?.(new Error(`Sandbox iframe failed to load "${r}". Verify that three-live-sandbox.html is served at that URL.`))};let f=document.body||document.documentElement;if(!f||typeof f.appendChild!="function"){c();let g=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw i.onError?.(g),g}return f.appendChild(l),{terminate:c}}function La(e,t,r,i){if(t==="worker"&&typeof Worker>"u")return i("Sandboxed procedural execution requires Web Workers, but Workers are unavailable in this environment. For host security, Three-Live prohibits unsandboxed in-process evaluation.","Security Error: Web Workers unavailable. Script execution aborted.");if(t==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return i("Sandboxed iframe execution requires a DOM environment with document.createElement. Refusing to evaluate in the host realm.","Security Error: DOM unavailable for iframe sandbox.");if(Rt>=32)return i(`SecurityError: ${Rt} sandbox workers are already running, which meets SECURITY_3D_MAX_CONCURRENT_TASKS (32). Refusing to start another.`,"Security Error: too many concurrent sandboxed scripts.");let n;try{n=Sl()}catch(c){let d=c instanceof Error?c.message:String(c);return i(d,"Security Error: sandbox engine URL is not configured.")}if(t==="iframe"){let c;try{c=Rl()}catch(d){let f=d instanceof Error?d.message:String(d);return i(f,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Dl(e,n,c,r))}catch(d){return Promise.reject(d)}}let s=Ea(),l=ii(n,s,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),o;try{let c=new Blob([l],{type:"application/javascript"}),d=URL.createObjectURL(c);try{let f=Rn(d);o=new Worker(f)}finally{URL.revokeObjectURL(d)}}catch(c){let d=c instanceof Error?c.message:String(c);return i(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${d}`,"Security Error: Failed to start Worker sandbox.")}Rt++;let a=!1,u={modelDispatched:!1},h,m=()=>{a||(a=!0,h!==void 0&&clearTimeout(h),Rt=Math.max(0,Rt-1),o.terminate())};return h=setTimeout(()=>{a||(m(),Pa(r))},3e3),o.onmessage=c=>{let d=ni(c.data,s);d&&Na(d,r,m,u)},o.onerror=c=>{m(),r.onError?.(new Error(`Worker execution error: ${c.message}`))},e.kind==="url"?o.postMessage({type:"EXECUTE_URL",scriptUrl:e.scriptUrl,nonce:s}):o.postMessage({type:"EXECUTE",script:e.script,nonce:s}),Promise.resolve({terminate:m})}function _a(e,t){return e==="none"||e==="unsafe-host-realm"?t(`SecurityError: sandbox="${e}" is prohibited. Sandboxing is mandatory for live compilation and cannot be bypassed. Use sandbox="worker" (default) or sandbox="iframe".`,`Security Error: sandbox="${e}" is not permitted.`):e!=="worker"&&e!=="iframe"?t(`SecurityError: Unsupported sandbox mode "${e}". Live compilation requires sandbox="worker" or sandbox="iframe".`,"Security Error: unsupported sandbox mode."):null}var Ia=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},br={execute(e,t,r,i){let n=Ia(r),s=_a(t,n);if(s)return s;try{Il(e)}catch(l){let o=l instanceof Error?l.message:String(l);return n(o,"Security Error: script exceeds the size limit.")}return i?.allowClientScripts??Cn()?La({kind:"script",script:e},t,r,n):n(ks,Fs)},executeUrl(e,t,r){let i=Ia(r),n=_a(t,i);if(n)return n;let s;try{s=Pl(e)}catch(l){let o=l instanceof Error?l.message:String(l);return i(o,"Security Error: disallowed scene script URL.")}return La({kind:"url",scriptUrl:s},t,r,i)}},si=new Set;function Pt(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;si.has(r)||(si.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function Nn(){return Array.from(si)}function Ln(){si.clear()}var ai=class extends Qt{constructor(e={}){Pt("ShaderMaterial","MeshStandardMaterial");let t=e.uniforms||{},r=t.color?.value??t.uColor?.value??t.diffuse?.value??e.color;super({color:r!==void 0?r:8421504,opacity:t.opacity?.value??e.opacity??1,transparent:!!e.transparent,wireframe:!!e.wireframe,side:e.side}),this.uniforms=t}},_n=ai,Et=class extends Ue{constructor(e=[],t=[],r=1,i=0){super();let n=Number(r)||1,s=Math.max(0,Math.min(7,Math.floor(Number(i)||0))),l=s+1,o=[],a=[],u=[],h=[],m=new xe,c=new xe,d=new xe,f=(b,v)=>v.set(e[b*3]||0,e[b*3+1]||0,e[b*3+2]||0),g=(b,v)=>{let p=b.clone().normalize();o.push(p.x*n,p.y*n,p.z*n),a.push(v.x,v.y,v.z),u.push(Math.atan2(p.z,-p.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,p.y)))/Math.PI)},x=(b,v,p)=>{let y=o.length/3,M=s===0?new xe().subVectors(p,v).cross(new xe().subVectors(b,v)).normalize():null;g(b,M||b.clone().normalize()),g(v,M||v.clone().normalize()),g(p,M||p.clone().normalize()),h.push(y,y+1,y+2)};for(let b=0;b<t.length;b+=3){f(t[b],m),f(t[b+1],c),f(t[b+2],d);let v=[];for(let p=0;p<=l;p++){v[p]=[];let y=m.clone().lerp(d,p/l),M=c.clone().lerp(d,p/l),P=l-p;for(let F=0;F<=P;F++)v[p][F]=P===0?y.clone():y.clone().lerp(M,F/P)}for(let p=0;p<l;p++)for(let y=0;y<2*(l-p)-1;y++){let M=y>>1;(y&1)===0?x(v[p][M+1],v[p+1][M],v[p][M]):x(v[p][M+1],v[p+1][M+1],v[p+1][M])}}this.setFromBuffers(o,a,u,h)}},Da=Et,In=class extends Et{constructor(e=1,t=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],e,t)}},oi=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],ka=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],Dn=class extends Et{constructor(e=1,t=0){super(oi,ka,e,t)}},De=(1+Math.sqrt(5))/2,kn=class extends Et{constructor(e=1,t=0){super([-1,De,0,1,De,0,-1,-De,0,1,-De,0,0,-1,De,0,1,De,0,-1,-De,0,1,-De,De,0,-1,De,0,1,-De,0,-1,-De,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],e,t)}},rt=1/De,Fn=class extends Et{constructor(e=1,t=0){super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-rt,-De,0,-rt,De,0,rt,-De,0,rt,De,-rt,-De,0,-rt,De,0,rt,-De,0,rt,De,0,-De,0,-rt,De,0,-rt,-De,0,rt,De,0,rt],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],e,t)}},Vn=class extends jr{constructor(e=1,t=1,r=4,i=8){let n=Math.max(1e-4,Number(e)||1),s=Math.max(0,Number.isFinite(Number(t))?Number(t):1)*.5,l=Math.max(2,Math.min(64,Math.floor(Number(r)||4))),o=[];for(let a=-1;a<=1;a+=2)for(let u=0;u<=l;u++){if(a>0&&u===0&&s===0)continue;let h=(a<0?u/l-1:u/l)*(Math.PI/2);o.push(new lt(Math.max(0,Math.cos(h)*n),a*s+Math.sin(h)*n))}super(o,Math.max(4,Math.min(128,Math.floor(Number(i)||8))))}},li=class extends Ue{constructor(e=.5,t=1,r=32,i=1,n=0,s=Math.PI*2){super();let l=Math.max(1e-4,Number(t)||1),o=Number(e),a=Number.isFinite(o)?Math.max(0,o):l*.5,u=Math.max(l,a),h=Math.min(u*.999,Math.min(l,a)),m=Math.max(3,Math.min(256,Math.floor(Number(r)||32))),c=Math.max(1,Math.min(64,Math.floor(Number(i)||1))),d=Number.isFinite(Number(n))?Number(n):0,f=Number.isFinite(Number(s))?Number(s):Math.PI*2,g=[],x=[],b=[],v=[];for(let p=0;p<=c;p++){let y=h+p/c*(u-h);for(let M=0;M<=m;M++){let P=d+M/m*f,F=Math.cos(P),G=Math.sin(P);if(g.push(y*F,y*G,0),x.push(0,0,1),b.push(y/u*F*.5+.5,y/u*G*.5+.5),p<c&&M<m){let T=p*(m+1)+M,E=T+m+1;y>1e-6&&v.push(T,E,T+1),v.push(E,E+1,T+1)}}}this.setFromBuffers(g,x,b,v)}},Un=class extends li{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},ui=class extends tt{constructor(e={}){super({roughness:.35,metalness:.1,side:2,...e});let t=Number(e.size);this.size=Number.isFinite(t)?Math.max(.002,Math.min(2,t)):.05,this.sizeAttenuation=e.sizeAttenuation!==!1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35)}},xr=class extends tt{constructor(e={}){super({roughness:.4,metalness:.1,side:2,...e});let t=Number(e.linewidth);this.linewidth=Number.isFinite(t)?Math.max(.5,Math.min(20,t)):1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.3)}},Bn=class extends xr{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function Fa(e,t){let r=e?.attributes?.position;if(!r?.array||r.count<3)return new Float32Array(0);let i=r.array,n=e?.index?.array,s=Math.min(8192,Math.floor((n?n.length:r.count)/3)),l=c=>`${Math.round((i[c*3]||0)*1e4)},${Math.round((i[c*3+1]||0)*1e4)},${Math.round((i[c*3+2]||0)*1e4)}`,o=t===void 0,a=o?1:Math.cos(t*Math.PI/180),u={},h=[],m=(c,d)=>h.push(i[c*3]||0,i[c*3+1]||0,i[c*3+2]||0,i[d*3]||0,i[d*3+1]||0,i[d*3+2]||0);for(let c=0;c<s;c++){let d=n?n[c*3]:c*3,f=n?n[c*3+1]:c*3+1,g=n?n[c*3+2]:c*3+2,x=i[d*3]||0,b=i[d*3+1]||0,v=i[d*3+2]||0,p=(i[f*3]||0)-x,y=(i[f*3+1]||0)-b,M=(i[f*3+2]||0)-v,P=(i[g*3]||0)-x,F=(i[g*3+1]||0)-b,G=(i[g*3+2]||0)-v,T=y*G-M*F,E=M*P-p*G,S=p*F-y*P,B=Math.hypot(T,E,S);if(!o&&B<1e-8)continue;B>0&&(T/=B,E/=B,S/=B);let k=[d,f,g];for(let w=0;w<3;w++){let ie=k[w],oe=k[(w+1)%3],I=l(ie),H=l(oe);if(I===H)continue;let C=I<H?`${I}|${H}`:`${H}|${I}`,z=u[C];z?z.m||(z.m=1,z.nx*T+z.ny*E+z.nz*S<=a&&m(ie,oe)):(u[C]={va:ie,vb:oe,nx:T,ny:E,nz:S,m:o?1:0},o&&m(ie,oe))}}if(!o){let c=Object.keys(u);for(let d=0;d<c.length;d++){let f=u[c[d]];f&&!f.m&&m(f.va,f.vb)}}return new Float32Array(h)}var On=class extends Ue{constructor(e){super(),this.setAttribute("position",new He(Fa(e),3)),this.__isSegmentPairs=!0}},zn=class extends Ue{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new He(Fa(e,r),3)),this.__isSegmentPairs=!0}};function kl(e,t,r=1){let i=new Ue;i.__baked=!0;let n=e?.attributes?.position;if(!n?.array||n.count<2)return i;let s=n.array,l=e.index?.array,o=e.__isSegmentPairs?"segments":t,a=l?l.length:n.count,u=Math.min(4096,Math.max(0,o==="segments"?Math.floor(a/2):o==="loop"&&a>=3?a:a-1));if(u===0)return i;e.computeBoundingBox();let h=e.boundingBox,m=h&&h.max.distanceTo(h.min)||1,c=Math.max(.0015,Math.min(.025,m*.003))*(.5+.5*Math.max(.5,Math.min(6,Number(r)||1))),d=[],f=[],g=[],x=[];for(let b=0;b<u;b++){let v=o==="segments"?b*2:b,p=o==="segments"?b*2+1:(b+1)%a,y=l?l[v]:v,M=l?l[p]:p,P=s[y*3]||0,F=s[y*3+1]||0,G=s[y*3+2]||0,T=(s[M*3]||0)-P,E=(s[M*3+1]||0)-F,S=(s[M*3+2]||0)-G,B=Math.hypot(T,E,S);if(B<1e-6)continue;let k=T/B,w=E/B,ie=S/B,oe=(Math.abs(w)<.9?Math.hypot(ie,k):Math.hypot(ie,w))||1,I=Math.abs(w)<.9?ie/oe:0,H=Math.abs(w)<.9?0:-ie/oe,C=Math.abs(w)<.9?-k/oe:w/oe,z=w*C-ie*H,ue=ie*I-k*C,he=k*H-w*I,O=d.length/3,$=[[I,H,C],[z,ue,he],[-I,-H,-C],[-z,-ue,-he]];for(let _=0;_<2;_++){let W=P+_*T,j=F+_*E,X=G+_*S;for(let D=0;D<4;D++){let Y=$[D];d.push(W+Y[0]*c,j+Y[1]*c,X+Y[2]*c),f.push(Y[0],Y[1],Y[2]),g.push(D/4,_)}}for(let _=0;_<4;_++){let W=(_+1)%4;x.push(O+_,O+W,O+4+W,O+_,O+4+W,O+4+_)}}return d.length>0&&i.setFromBuffers(d,f,g,x),i}function Fl(e,t=.05){let r=new Ue;r.__baked=!0;let i=e?.attributes?.position;if(!i?.array||i.count<1)return r;let n=i.array,s=i.count,l=Math.min(s,5e3),o=Math.max(.003,Math.min(.25,(Number(t)||.05)*.6)),a=[],u=[],h=[],m=[];for(let c=0;c<l;c++){let d=s<=5e3?c:Math.floor(c*s/l),f=n[d*3]||0,g=n[d*3+1]||0,x=n[d*3+2]||0,b=c*6;for(let v=0;v<6;v++){let p=oi[v*3],y=oi[v*3+1],M=oi[v*3+2];a.push(f+p*o,g+y*o,x+M*o),u.push(p,y,M),h.push(.5,.5)}for(let v=0;v<24;v++)m.push(b+ka[v])}return r.setFromBuffers(a,u,h,m),r}var Dt=class extends xt{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},n=t instanceof tt?t:r==="points"?new ui(i):new xr(i),s=e instanceof Ue?e:new Ue;super(s,n),this.isLine=!0,this._lineMode=r,this._sourceGeo=s}computeLineDistances(){return this}_bakeAuthorGeometry(){this.geometry&&!this.geometry.__baked&&(this._sourceGeo=this.geometry);let e=this._lineMode==="points";if(e){let t=this._sourceGeo?.attributes?.color;if(t?.array&&t.count>0&&this.material?.color.r===1&&this.material.color.g===1&&this.material.color.b===1){let r=t.array,i=Math.min(t.count,64),n=0,s=0,l=0;for(let o=0;o<i;o++)n+=r[o*3]||0,s+=r[o*3+1]||0,l+=r[o*3+2]||0;this.material.color.setRGB(n/i,s/i,l/i)}}!this.geometry?.__baked&&this._sourceGeo?.attributes?.position?.count>=(e?1:2)&&(this.geometry=e?Fl(this._sourceGeo,this.material?.size??.05):kl(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},$n=class extends Dt{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},Hn=class extends Dt{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},Gn=class extends Dt{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},Wn=class extends Yr{constructor(e,t,r=0,i=Math.PI/3,n=0,s=2){super(e,t,r,s),this.target=new pt,this.type="spot";let l=Number(i);this.angle=Number.isFinite(l)?Math.max(.01,Math.min(Math.PI/2,l)):Math.PI/3;let o=Number(n);this.penumbra=Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}},hi=class extends Kr{constructor(e,t,r){Pt("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new ft(t??4473924)}},jn=hi,Va={Vector2:lt,Vector3:xe,Vector4:Yi,Euler:$r,Quaternion:dr,Matrix4:_t,Matrix3:Zi,Color:ft,MathUtils:Qi,BufferAttribute:He,Float32BufferAttribute:Ji,Uint16BufferAttribute:en,Uint32BufferAttribute:tn,BufferGeometry:Ue,BoxGeometry:Gr,PlaneGeometry:rn,SphereGeometry:nn,CylinderGeometry:Wr,ConeGeometry:sn,TorusGeometry:an,TorusKnotGeometry:on,Curve:St,Curve3:St,LineCurve3:ln,QuadraticBezierCurve3:un,CubicBezierCurve3:hn,CatmullRomCurve3:cn,LatheGeometry:jr,TubeGeometry:mn,PolyhedronGeometry:Et,IcosahedronGeometry:kn,OctahedronGeometry:Dn,DodecahedronGeometry:Fn,TetrahedronGeometry:In,CapsuleGeometry:Vn,RingGeometry:li,CircleGeometry:Un,WireframeGeometry:On,EdgesGeometry:zn,FrontSide:0,BackSide:1,DoubleSide:2,NoBlending:0,NormalBlending:1,AdditiveBlending:2,MultiplyBlending:4,RepeatWrapping:1e3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002,NearestFilter:1003,NearestMipmapNearestFilter:1004,NearestMipmapLinearFilter:1005,LinearFilter:1006,LinearMipmapNearestFilter:1007,LinearMipmapLinearFilter:1008,UnsignedByteType:1009,ByteType:1010,ShortType:1011,UnsignedShortType:1012,IntType:1013,UnsignedIntType:1014,FloatType:1015,HalfFloatType:1016,AlphaFormat:1021,RGBFormat:1022,RGBAFormat:1023,LuminanceFormat:1024,LuminanceAlphaFormat:1025,RedFormat:1028,RGFormat:1030,NoColorSpace:"",SRGBColorSpace:"srgb",LinearSRGBColorSpace:"srgb-linear",StaticDrawUsage:35044,DynamicDrawUsage:35048,ACESFilmicToneMapping:4,PCFSoftShadowMap:2,Texture:gr,DataTexture:fn,TextureLoader:pn,Material:tt,MeshStandardMaterial:Qt,MeshBasicMaterial:gn,MeshLambertMaterial:yn,MeshPhongMaterial:bn,MeshPhysicalMaterial:xn,PointsMaterial:ui,LineBasicMaterial:xr,LineDashedMaterial:Bn,ShaderMaterial:ai,RawShaderMaterial:_n,Object3D:pt,Group:vn,Mesh:xt,InstancedMesh:qr,Line:Dt,LineLoop:$n,LineSegments:Hn,Points:Gn,Light:er,AmbientLight:Kr,DirectionalLight:Mn,PointLight:Yr,SpotLight:Wn,HemisphereLight:hi,RectAreaLight:jn,Camera:Zr,PerspectiveCamera:wn,Scene:Qr,WebGLRenderer:Tn,Clock:Sn,SceneQuotaValidator:vt,exportSceneToCanvas3D:Jr,exportSceneToGLB:ei,exportSceneToUSDZ:An,generateUSDZ:Or,glbToUSDZ:Br,sceneToCanvas3D:Zt,sceneToGLB:fr,sceneToUSDZ:pr,authorScriptRunner:br,getAuthorWarnings:Nn,clearAuthorWarnings:Ln};Object.freeze(vt),Object.freeze(vt.prototype),Object.freeze(Qr.prototype),Object.freeze(Va);var kt=new Proxy(Va,{get:(e,t)=>{if(t in e)return e[t];let r=Ae().authorNamespace;return r&&typeof t=="string"&&t in r?r[t]:(typeof t=="string"&&t!=="then"&&t!=="toJSON"&&!t.startsWith("__")&&Pt(`THREE.${t}`,"no-op proxy"),tr)},has:(e,t)=>{if(t in e)return!0;let r=Ae().authorNamespace;return!!(r&&typeof t=="string"&&t in r)},set:(e,t)=>{throw new TypeError(`Cannot assign to read only property '${String(t)}' of #<THREE>`)},defineProperty:(e,t)=>{throw new TypeError(`Cannot define property '${String(t)}', object is not extensible`)},deleteProperty:(e,t)=>{throw new TypeError(`Cannot delete property '${String(t)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),ci=Ae();if(ci.threeNamespace=kt,ci.workerExtensionInstallers)for(let e of ci.workerExtensionInstallers)e(kt,ci);var rr={name:"three_author",THREE:kt},Ua=rr,Mt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof Mt.THREE>"u"&&(Mt.THREE=kt),typeof Mt.requestAnimationFrame!="function"&&(Mt.requestAnimationFrame=e=>(typeof e=="function"&&typeof Mt.__three_live_raf_cb__!="function"&&(Mt.__three_live_raf_cb__=e),Mt.__three_live_in_step__||Pt("requestAnimationFrame","single-frame static evaluation"),0)),typeof Mt.cancelAnimationFrame!="function"&&(Mt.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=kt,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=rr,e.ThreeLivePlugins.three_author=rr,e.ThreeLivePlugins["three-author"]=rr}function mi(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var Xn=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),Vl=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(e,t){super(e,t),this.detail=t?.detail??null}});var fi=class Ge extends Vl{constructor(){super(...arguments),this.viewer=null,this.canvas=null,this.posterEl=null,this.arButton=null,this.currentModel=null,this.activeXRSession=null,this.toastTimer=null,this.currentModelLimits=void 0,this.isModelLoaded=!1,this.scriptHandle=null,this.loadController=null,this.resizeObserver=null,this.mutationObserver=null}static get arProvider(){return Ae().arProvider}static set arProvider(t){Ae().arProvider=t}static get scriptRunner(){return Ae().scriptRunner}static set scriptRunner(t){Ae().scriptRunner=t}static get sandboxEngineSrc(){return Ae().sandboxEngineSrc??null}static set sandboxEngineSrc(t){Ae().sandboxEngineSrc=t}static get sandboxIframeSrc(){return Ae().sandboxIframeSrc??null}static set sandboxIframeSrc(t){Ae().sandboxIframeSrc=t}static get allowClientScripts(){return!!Ae().allowClientScripts}static set allowClientScripts(t){Ae().allowClientScripts=t}static registerScriptRunner(t){Ge.scriptRunner=t}static defineModelViewer(t="model-viewer"){if(typeof customElements>"u")return!1;let r=customElements.get(t);if(r!=null)return r===Ge||r.prototype instanceof Ge;class i extends Ge{}return customElements.define(t,i),!0}static registerDecoder(t,r){Ze.registerDecoder(t,r)}static getDecoder(t){return Ze.getDecoder(t)}static registerAR(t){typeof t=="function"?Ge.arProvider={activateAR:t}:Ge.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof Ge&&r.updateARButtonVisibility()})}static isARSupported(){return!!Ge.arProvider}getLoadedModel(){return this.currentModel}beginLoad(){let t=this.loadController,r=this.scriptHandle,i=new AbortController;return this.loadController=i,this.scriptHandle=null,t?.abort(),r?.terminate(),i}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let t=this.getAttribute("src"),r=this.getAttribute("script-src");if(t)this.loadModel(t).catch(()=>{});else if(r)this.loadScriptFromSrc(r).catch(()=>{});else{let i=this.querySelector('script[type="text/three"], script[type="text/three-live"]');i&&i.textContent&&this.executeScript(i.textContent).catch(()=>{})}for(let i of Ze.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of Ze.getRegisteredPlugins())t.onElementDisconnected?.(this);this.beginLoad().abort(),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,this.viewer?.destroy(),this.viewer=null,this.isModelLoaded=!1}attributeChangedCallback(t,r,i){if(r!==i){switch(t){case"src":i&&this.loadModel(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let n=parseFloat(i);isNaN(n)||this.viewer.setExposure(n)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer?.setToneMapping(qt(i));break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let n=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(n),this.canvas&&(this.canvas.style.touchAction=n?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(i!==null&&i!=="false");break;case"animation-name":this.viewer&&i!==null&&this.viewer.setAnimationName(i);break;case"variant-name":this.viewer&&this.selectVariant(i);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(i!==null&&i!=="false");break;case"auto-rotate-delay":this.viewer&&this.viewer.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":this.viewer&&this.viewer.setAutoRotateSpeed(this.parseRotationPerSecond(i));break;case"ar":this.updateARButtonVisibility();break}for(let n of Ze.getRegisteredPlugins())n.onAttributeChanged?.(this,t,r,i)}}getAttr(t){return this.getAttribute(t)}setAttr(t,r){r!==null?this.setAttribute(t,String(r)):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttr(t)!=="false"}setBoolAttr(t,r){this.setAttr(t,r?"":null)}getFloatAttr(t,r){let i=this.getAttr(t);return i!==null?parseFloat(i):r}get src(){return this.getAttr("src")}set src(t){this.setAttr("src",t)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(t){this.setBoolAttr("camera-controls",t)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(t){this.setAttr("camera-orbit",t)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(t){this.setAttr("camera-target",t)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(t){this.setAttr("min-camera-orbit",t)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(t){this.setAttr("max-camera-orbit",t)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(t){this.setAttr("field-of-view",t)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(t){this.setAttr("ios-src",t)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(t){this.setAttr("script-src",t)}get sandbox(){return this.getAttr("sandbox")||(Ae().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||Ge.allowClientScripts}set allowClientScripts(t){this.setBoolAttr("allow-client-scripts",t)}get poster(){return this.getAttr("poster")}set poster(t){this.setAttr("poster",t)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(t){this.setAttr("selected-mesh",t)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(t){this.setAttr("exposure",t)}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(t){this.setBoolAttr("auto-rotate",t)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(t){this.setAttr("auto-rotate-delay",t)}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(t){this.setAttr("rotation-per-second",t)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(t){this.setBoolAttr("ar",t)}get arScale(){return this.getAttr("ar-scale")||"auto"}set arScale(t){this.setAttr("ar-scale",t)}get arPlacement(){return this.getAttr("ar-placement")||"floor"}set arPlacement(t){this.setAttr("ar-placement",t)}get canActivateAR(){return Ge.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(t){this.setAttr("shadow-intensity",t)}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(t){this.setAttr("shadow-softness",t)}get toneMapping(){return qt(this.getAttr("tone-mapping"))}set toneMapping(t){this.setAttr("tone-mapping",t)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(t){this.setAttr("bloom",t)}get bloomThreshold(){return mi(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return mi(this.getAttr("bloom-radius"),.75)}set bloomRadius(t){this.setAttr("bloom-radius",t)}get outlineSelected(){return this.getBoolAttr("outline-selected")}set outlineSelected(t){this.setBoolAttr("outline-selected",t)}get outlineColor(){return this.getAttr("outline-color")||"#38bdf8"}set outlineColor(t){this.setAttr("outline-color",t)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(t){this.setAttr("environment-image",t)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(t){this.setAttr("skybox-image",t)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(t){this.setBoolAttr("autoplay",t)}get animationName(){return this.getAttr("animation-name")}set animationName(t){this.setAttr("animation-name",t)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(t){this.setAttr("variant-name",t)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}fireEvent(t,r){this.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:r}))}setSlotVisible(t,r){let i=typeof this.querySelector=="function"?this.querySelector(`[slot="${t}"]`):null;i&&(i.hidden=!r,i.style&&(i.style.display=r?"":"none"))}emitError(t,r="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:t}),this.fireEvent("three-error",{error:t,message:t?.message||String(t),stage:r})}selectVariant(t){if(!this.viewer)return!1;let r=this.viewer.selectVariant(t);return r&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),r}get model(){let t=this.viewer?this.viewer.getModelMaterials():[];return{materials:t,getMaterialByName(r){return t.find(i=>i.name===r)??null}}}play(){this.viewer&&this.viewer.playAnimation(this.animationName||void 0)}pause(){this.viewer&&this.viewer.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(t=0){this.viewer?.resetTurntableRotation(t)}setCamera(t,r,i,n){this.viewer&&this.viewer.setCamera(t,r,i,n)}getCameraOrbit(){return this.viewer?this.viewer.getCameraOrbit():{theta:0,phi:0,radius:3,toString(){return"0rad 0rad 3m"}}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():Xn(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,r){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(t,r):""}toBlob(t){return this.viewer?.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(n=>{n?r(n):i(new Error("Failed to capture canvas blob."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,r){let i=this.viewer?.raycastFromScreenPoint(t,r);if(!i)return null;let[n,s,l]=i.hitPoint||i.point,[o,a,u]=i.normal;return{position:Xn(n,s,l),normal:Xn(o,a,u)}}loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,r,i=this.beginLoad()){if(i.signal.throwIfAborted(),!this.viewer){this.currentModel=t,this.currentModelLimits=r;return}try{let n;if(typeof t=="string"){let a=await fetch(t,{signal:i.signal});if(!a.ok)throw new Error(`Failed to load "${t}": HTTP ${a.status}`);n=await a.arrayBuffer()}else n=t;i.signal.throwIfAborted();let s=Yt(n);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let l=this.getAttr("selected-mesh");l&&this.viewer.setSelectedMesh(l);let o=this.getAttr("variant-name");o&&this.selectVariant(o),this.fireEvent("load",{model:s}),this.fireEvent("three-load",{model:s,source:typeof t=="string"?"src":"model"})}catch(n){throw i.signal.aborted||this.emitError(n,"load"),n}}showToast(t,r=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=t,this.toastTimer&&clearTimeout(this.toastTimer);let n=()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(n):n(),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let t=(n,s=n.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:n}),this.showToast(s,6e3),n};this.currentModel||t(new Error("No 3D model is loaded in <three-live>.")),Ge.arProvider||t(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let r=this.getAttr("ios-src"),i=(this.getAttr("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let n=await Ge.arProvider.activateAR({model:r||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:i.length>0?i:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"not-presenting"})},onError:s=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(`AR error: ${s.message}`,6e3)}}});if(n.success){n.session&&(this.activeXRSession=n.session);let s=n.mode==="quick-look"?"Opening Apple AR Quick Look...":n.mode==="scene-viewer"?"Opening Google Scene Viewer...":n.mode==="webxr"?"WebXR AR session started.":"";s&&this.showToast(s)}else{let s=n.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(this.isDesktopMac()&&typeof document<"u"&&this.currentModel&&Ge.arProvider.createUSDZBlob)try{let l=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:Ge.arProvider.createUSDZBlob(this.currentModel),o=URL.createObjectURL(l),a=document.createElement("a");a.href=o,a.download="three_live_model.usdz",document.body.appendChild(a),a.click(),document.body.removeChild(a),setTimeout(()=>URL.revokeObjectURL(o),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(s,6e3)}else this.showToast(s,6e3);n.error&&this.fireEvent("ar-status",{status:"failed",error:n.error})}return n}catch(n){return this.activeXRSession=null,t(n,`AR error: ${n.message||String(n)}`)}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(t)),this.canvas=t,typeof t.addEventListener=="function"&&!t.__tlCtxBound&&(t.__tlCtxBound=!0,t.addEventListener("webglcontextlost",i=>this.fireEvent("three-context-lost",{originalEvent:i})),t.addEventListener("webglcontextrestored",i=>this.fireEvent("three-context-restored",{originalEvent:i}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);let r=this.getAttr("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;let t=this.autoRotate,r=this.exposure,i=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),n=this.parseOrbitLimit(this.getAttr("max-camera-orbit")),s=this.parseCameraTarget(this.getAttr("camera-target")),l=this.parseFieldOfView(this.getAttr("field-of-view"));this.viewer=new Ze(this,this.canvas,{autoRotate:t,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttr("rotation-per-second")),exposure:r,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttr("variant-name")||void 0,fieldOfView:l,cameraTarget:s,minCameraOrbit:i,maxCameraOrbit:n,onMeshClick:a=>{this.fireEvent("meshclick",a)},onCameraChange:a=>{this.updateHotspots();for(let u of Ze.getRegisteredPlugins())u.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",a)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let o=this.getAttr("camera-orbit");o&&this.applyCameraOrbit(o),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(t){if(!(typeof document>"u")){if(!t){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.alt="3D Scene Preview",this.posterEl.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}isDesktopMac(){let t=typeof navigator<"u"&&navigator.userAgent||"";return/Macintosh/i.test(t)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1)&&!/Android|iPhone|iPad|iPod/i.test(t)}syncARButtonLabel(t){let r=this.isDesktopMac(),i=r?"Quick Look (.usdz)":"View in AR",n=r?"Download .usdz preview for macOS Quick Look (live camera AR requires iOS or Android)":"View in Augmented Reality";typeof t.setAttribute=="function"&&(t.setAttribute("aria-label",n),t.setAttribute("title",n));let s=t._labelSpan||(typeof t.querySelector=="function"?t.querySelector("span"):null);s&&(s.textContent=i)}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.type="button",t.className="three-live-ar-button",t.setAttribute("part","default-ar-button");let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let n=document.createElementNS(r,"svg");for(let[l,o]of[["width","20"],["height","20"],["viewBox","0 0 24 24"],["fill","none"],["stroke","currentColor"],["stroke-width","2"],["stroke-linecap","round"],["stroke-linejoin","round"]])n.setAttribute(l,o);n.style.marginRight="6px";let s=document.createElementNS(r,"path");s.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),n.appendChild(s),t.appendChild(n)}let i=document.createElement("span");t._labelSpan=i,t.appendChild(i),this.syncARButtonLabel(t),t.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",t.addEventListener("mouseenter",()=>{t.style.backgroundColor="rgba(30, 41, 59, 0.95)",t.style.transform="scale(1.04)"}),t.addEventListener("mouseleave",()=>{t.style.backgroundColor="rgba(15, 23, 42, 0.85)",t.style.transform="scale(1)"}),t.addEventListener("click",n=>{n.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&!!Ge.arProvider,r=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;r?(this.arButton&&(this.arButton.style.display="none"),r.__tlARBound||(r.__tlARBound=!0,r.addEventListener("click",i=>{i.stopPropagation(),this.activateAR()})),r.dataset.tlOrigDisplay===void 0&&(r.dataset.tlOrigDisplay=r.style.display==="none"?"":r.style.display),r.style.display=t?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.syncARButtonLabel(this.arButton),this.arButton.style.display=t?"flex":"none")}applyCameraOrbit(t){if(!(!t||!this.viewer))try{let r=JSON.parse(t);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=this.parseOrbitLimit(t);(r.theta!==void 0||r.phi!==void 0)&&this.viewer.setInitialCamera(r.theta,r.phi,r.distance)}}parseOrbitLimit(t){if(!t)return{};let[r,i,n]=t.trim().split(/\s+/),s=n&&n!=="auto"?parseFloat(n):NaN;return{theta:r&&r!=="auto"?this.parseFieldOfView(r):void 0,phi:i&&i!=="auto"?this.parseFieldOfView(i):void 0,distance:isNaN(s)?void 0:s}}applyOrbitLimits(){if(!this.viewer)return;let t=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttr("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:t.theta,maxTheta:r.theta,minPhi:t.phi,maxPhi:r.phi,minDistance:t.distance,maxDistance:r.distance})}parseCameraTarget(t){if(!t)return;let r=t.trim().split(/\s+/).map(parseFloat);return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(t){if(!t)return;let r=parseFloat(t);return isNaN(r)?void 0:t.endsWith("rad")?r*180/Math.PI:r}parseRotationPerSecond(t){if(!t)return Math.PI/6;let r=t.trim(),i=parseFloat(r);return isNaN(i)?Math.PI/6:r.endsWith("rad")?i:r.endsWith("%")?i/100*Math.PI*2:i*Math.PI/180}applyCameraTarget(t){let r=this.parseCameraTarget(t);this.viewer&&r&&this.viewer.setTarget(r[0],r[1],r[2])}applyFieldOfView(t){let r=this.parseFieldOfView(t);this.viewer&&r!==void 0&&this.viewer.setFieldOfView(r)}updateHotspot(t){let r=this.querySelector(`[slot="${t.name}"]`);r&&(t.position!==void 0&&r.setAttribute("data-position",t.position),t.normal!==void 0&&r.setAttribute("data-normal",t.normal)),this.updateHotspots()}updateHotspots(){for(let t of Ze.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=Ge.scriptRunner;if(!r){let s=new Error('Script execution requires "three-live/full" or registerScriptRunner().');return this.showToast(s.message),this.emitError(s,"script"),Promise.reject(s)}let i=this.beginLoad(),n=()=>!i.signal.aborted;return new Promise((s,l)=>{let o=()=>l(i.signal.reason);if(i.signal.addEventListener("abort",o,{once:!0}),!n()){o();return}let a={onModelReady:u=>{this.loadModelWithLimits(u,hl,i).then(()=>s(u),l)},onUpdateTransforms:u=>{n()&&this.viewer?.updateMeshTransforms(u)},onError:u=>{n()&&(this.showToast(u.message),this.emitError(u,"script"),l(u))},onToast:u=>{n()&&this.showToast(u)}};t(r,a).then(u=>{n()?this.scriptHandle=u||null:u?.terminate()},u=>{n()&&a.onError?.(u)})})}loadScriptFromSrc(t){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let n=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(n),Promise.reject(n)}return r.executeUrl(t,this.sandbox,i)})}executeScript(t){if(!Ge.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(ks);return this.showToast(Fs),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};fi.observedAttributes=["src","ios-src","script-src","sandbox","allow-client-scripts","poster","camera-controls","camera-orbit","camera-target","min-camera-orbit","max-camera-orbit","field-of-view","selected-mesh","ar","ar-modes","ar-scale","ar-placement","exposure","shadow-intensity","shadow-softness","tone-mapping","bloom","bloom-threshold","bloom-radius","outline","outline-selected","outline-color","environment-image","skybox-image","autoplay","animation-name","variant-name","auto-rotate","auto-rotate-delay","rotation-per-second"],fi.registerPlugin=Ze.registerPlugin,fi.getRegisteredPlugins=Ze.getRegisteredPlugins;var Ft=fi;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",Ft);function Ba(e="model-viewer"){return Ft.defineModelViewer(e)}function Oa(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function qn(e,t,r,i){let n=t[0],s=t[1],l=t[2],o=t[3],a=r[0],u=r[1],h=r[2],m=r[3],c=n*a+s*u+l*h+o*m;if(c<0&&(a=-a,u=-u,h=-h,m=-m,c=-c),Math.abs(c)>=1)return e[0]=n,e[1]=s,e[2]=l,e[3]=o,e;let d=Math.acos(c),f=Math.sqrt(1-c*c);if(Math.abs(f)<.001)return e[0]=.5*(n+a),e[1]=.5*(s+u),e[2]=.5*(l+h),e[3]=.5*(o+m),e;let g=Math.sin((1-i)*d)/f,x=Math.sin(i*d)/f;return e[0]=n*g+a*x,e[1]=s*g+u*x,e[2]=l*g+h*x,e[3]=o*g+m*x,e}function za(e,t,r,i){return e[0]=t[0]+i*(r[0]-t[0]),e[1]=t[1]+i*(r[1]-t[1]),e[2]=t[2]+i*(r[2]-t[2]),e}function Kn(e,t){if(!Array.isArray(e?.animations))return[];let r=[];for(let i=0;i<e.animations.length;i++){let n=e.animations[i],s=n.name||`Animation_${i}`,l=[],o=0;if(Array.isArray(n.channels)&&Array.isArray(n.samplers))for(let a of n.channels){if(!a.target||a.target.node===void 0||!a.target.path)continue;let u=n.samplers[a.sampler];if(!u)continue;let h=e.accessors?.[u.input],m=e.accessors?.[u.output];if(!h||!m)continue;let c=e.bufferViews?.[h.bufferView],d=e.bufferViews?.[m.bufferView];if(!c||!d)continue;let f=(c.byteOffset||0)+(h.byteOffset||0),g=(d.byteOffset||0)+(m.byteOffset||0),x=jt(e,t,h,1)??Oa(t,f,h.count);x.length>0&&x[x.length-1]>o&&(o=x[x.length-1]);let b=a.target.path==="rotation"?4:a.target.path==="weights"?Math.max(1,Math.round(m.count/Math.max(1,h.count))):3,v=a.target.path==="weights"?1:b,p=jt(e,t,m,v)??Oa(t,g,m.count*v),y=u.interpolation==="STEP"?"STEP":"LINEAR";l.push({nodeIndex:a.target.node,path:a.target.path,times:x,values:p,interpolation:y})}l.length>0&&r.push({name:s,duration:o,channels:l})}return r}function ir(e,t,r){let{times:i,values:n,path:s,interpolation:l}=e,o=i.length;if(o===0)return;let a=s==="rotation"?4:s==="weights"?Math.max(1,Math.round(n.length/o)):3;if(t<=i[0]){for(let v=0;v<a;v++)r[v]=n[v];return}if(t>=i[o-1]){let v=(o-1)*a;for(let p=0;p<a;p++)r[p]=n[v+p];return}let u=0,h=o-1;for(;u<=h;){let v=u+h>>1;i[v]<=t?u=v+1:h=v-1}let m=Math.max(0,h),c=Math.min(o-1,m+1);if(l==="STEP"||m===c){let v=m*a;for(let p=0;p<a;p++)r[p]=n[v+p];return}let d=i[m],f=i[c],g=(t-d)/Math.max(1e-5,f-d),x=m*a,b=c*a;if(s==="rotation"){let v=[n[x],n[x+1],n[x+2],n[x+3]],p=[n[b],n[b+1],n[b+2],n[b+3]];qn(r,v,p,g)}else for(let v=0;v<a;v++)r[v]=n[x+v]+g*(n[b+v]-n[x+v])}var vr=new WeakMap;function Yn(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(o=>o.name===t);if(!i)return;let n=vr.get(e);n||(n=[],e.currentClip&&n.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),vr.set(e,n));let s=r>0?1/r:1e3;for(let o of n)o.clip.name!==t&&(o.fadeSpeed=-s);let l=n.find(o=>o.clip.name===t);l?l.fadeSpeed=s:n.push({clip:i,time:0,weight:r>0?0:1,fadeSpeed:s}),e.currentClip=i,e.isPlayingAnimation=!0}function Zn(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=vr.get(e);if(!r||r.length===0){if(!e.currentClip)return;r=[{clip:e.currentClip,time:t,weight:1,fadeSpeed:0}]}let i=e.gltf.nodes.length,n=[];for(let m=0;m<i;m++){let c=e.initialNodeTransforms[m];c?n.push({t:[c.t[0],c.t[1],c.t[2]],r:[c.r[0],c.r[1],c.r[2],c.r[3]],s:[c.s[0],c.s[1],c.s[2]]}):n.push({t:[0,0,0],r:[0,0,0,1],s:[1,1,1]})}let s=[0,0,0],l=[0,0,0,1],o=[1,1,1],a=new Float32Array(64);for(let m of r){let c=Math.max(0,Math.min(1,m.weight));if(!(c<=1e-4))for(let d of m.clip.channels){if(d.nodeIndex<0||d.nodeIndex>=i)continue;let f=n[d.nodeIndex];if(d.path==="translation")ir(d,m.time,s),za(f.t,f.t,s,c);else if(d.path==="rotation")ir(d,m.time,l),qn(f.r,f.r,l,c);else if(d.path==="scale")ir(d,m.time,o),za(f.s,f.s,o,c);else if(d.path==="weights"&&(ir(d,m.time,a),e.meshes)){for(let g of e.meshes)if(g.nodeIndex===d.nodeIndex){for(let x of g.primitives)if(x.pluginData?.morph?.weights){let b=x.pluginData.morph.weights,v=x.pluginData.morph.numTargets||b.length;for(let p=0;p<v;p++)b[p]=b[p]*(1-c)+a[p]*c}}}}}let u=[];for(let m=0;m<i;m++){let c=Pe(),{t:d,r:f,s:g}=n[m];lr(c,f,d,g),u.push(c)}let h=Cr(e.gltf,u);e.worldMatrices=h;for(let m of e.meshes)m.nodeIndex>=0&&m.nodeIndex<h.length&&(m.transform.set(h[m.nodeIndex]),Ye(m.normalMatrix,m.transform))}var Qn=e=>{vr.delete(e)},Jn={name:"keyframes",evaluateAnimation:Zn,crossFadeTo:Yn,onParseGLB(e){!e.animations&&e.gltf?.animations&&(e.animations=Kn(e.gltf,e.bin))},onLoadModel:Qn,onClearScene:Qn,onDestroy:(e,t)=>Qn(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=vr.get(e);if(r&&r.length>0){for(let i=r.length-1;i>=0;i--){let n=r[i];if(n.time+=t,n.clip.duration>0&&(n.time%=n.clip.duration),n.fadeSpeed!==0)if(n.weight+=n.fadeSpeed*t,n.weight<=0){r.splice(i,1);continue}else n.weight>=1&&(n.weight=1,n.fadeSpeed=0)}r.length>0&&(e.animationTime=r[r.length-1].time),Zn(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),Zn(e,e.animationTime))}},Mr=64;function $a(e,t,r){if(!(!e?.meshes||t<0||t>=Mr))for(let i of e.meshes)for(let n of i.primitives){let s=n.pluginData?.morph;s?.weights&&(s.weights[t]=r)}}var es={name:"morph",onResolveShader(e,t,r,i){if(!Array.isArray(e?.targets)||e.targets.length===0)return null;let n=r.replace("uniform mat4 uMVP,uModel;",`uniform mat4 uMVP,uModel;
402
+ })();`);v=null;let V=F(y,P,R,I);V&&typeof V.toGLB=="function"&&(P=V)}if(!w){y.SceneQuotaValidator&&y.SceneQuotaValidator.validate(P);let F=P.toGLB(),V=F instanceof ArrayBuffer?F:F.buffer.slice(F.byteOffset,F.byteOffset+F.byteLength);S({type:"3D_MODEL_READY",glbBuffer:V},[V])}h({type:"DONE",nonce:n})}catch(P){p(P&&P.message||P)}},h({type:"READY",nonce:n})}function Ha(e,t,r){let i=r?.allowedScriptUrl??null,n=r?.allowClientScripts??i===null,a={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:n,revoked:Xp},s=(We().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${Yp.toString()})(${JSON.stringify(a)},[${s}],(${oh.toString()}));`}function Gh(e){e.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),e.onToast?.("Security Error: script timed out and was stopped.")}var mi=0;function Hh(){try{let e=new Uint32Array(4);return globalThis.crypto?.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function Qp(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var Zp=1024,Jp=256;function qh(e){if(!Array.isArray(e)&&!(e instanceof Float32Array)||e.length!==16)return!1;for(let t=0;t<16;t++){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))return!1}return!0}function qa(e,t){if(!e||typeof e!="object")return null;let r=e;if(r.nonce!==t)return null;switch(r.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof r.message=="string"?r.message:String(r.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,Zp)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let n of i)if(!qh(n))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:i}}if(i&&typeof i=="object"){let n=Object.keys(i);if(n.length>1e3)return null;let a=Object.create(null),s=i;for(let o of n){if(o.length>Jp||o==="__proto__"||o==="constructor"||o==="prototype")return null;let l=s[o];if(!qh(l))return null;a[o]=l}return{type:"3D_UPDATE_TRANSFORMS",transforms:a}}return null}case"3D_MODEL_READY":{let i=r.glbBuffer;return!(i instanceof ArrayBuffer)||i.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:i}}default:return null}}function ed(e){let t=Qp(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Wh(e,t,r,i){switch(e.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":t.onUpdateTransforms?.(e.transforms);return;case"3D_MODEL_READY":if(i.modelDispatched)return;i.modelDispatched=!0,t.onModelReady(e.payload);return;case"DONE":r();return;case"ERROR":r(),t.onError?.(new Error(`Worker script error: ${e.message}`));return;default:return e}}function td(e,t,r,i){let n=Hh(),a=Ha(t,n,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),s=document.createElement("iframe");s.setAttribute("sandbox","allow-scripts"),s.setAttribute("aria-hidden","true"),s.tabIndex=-1,s.style.display="none",s.src=r,mi++;let o=!1,l=!1,c={modelDispatched:!1},f,m=()=>{if(o||l)return;let x=s.contentWindow;!x||typeof x.postMessage!="function"||(l=!0,x.postMessage(e.kind==="url"?{type:"SANDBOX_RUN",nonce:n,workerSource:a,scriptUrl:e.scriptUrl,texturePack:e.texturePack??null}:{type:"SANDBOX_RUN",nonce:n,workerSource:a,script:e.script,texturePack:e.texturePack??null},"*"))},h=()=>{},p=x=>{if(o||!s.contentWindow||x.source!==s.contentWindow)return;let v=x.data;if(v&&typeof v=="object"&&v.type==="IFRAME_READY"){m();return}let y=qa(v,n);y&&Wh(y,i,h,c)};h=()=>{o||(o=!0,f!==void 0&&clearTimeout(f),mi=Math.max(0,mi-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",p),typeof s.remove=="function"?s.remove():s.parentNode&&s.parentNode.removeChild(s))},f=setTimeout(()=>{o||(h(),Gh(i))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",p),s.onload=()=>{m()},s.onerror=()=>{h(),i.onError?.(new Error(`Sandbox iframe failed to load "${r}". Verify that three-live-sandbox.html is served at that URL.`))};let g=document.body||document.documentElement;if(!g||typeof g.appendChild!="function"){h();let x=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw i.onError?.(x),x}return g.appendChild(s),{terminate:h}}function Kh(e,t,r,i){if(t==="worker"&&typeof Worker>"u")return i("SecurityError: Web Workers are unavailable for sandboxed execution.","Security Error: Web Workers unavailable.");if(t==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return i("SecurityError: DOM unavailable for iframe sandbox execution.","Security Error: DOM unavailable for iframe sandbox.");if(mi>=32)return i(`SecurityError: ${mi} workers running, meeting SECURITY_3D_MAX_CONCURRENT_TASKS (32).`,"Security Error: too many concurrent sandboxed scripts.");let n;try{n=qp()}catch(h){let p=h instanceof Error?h.message:String(h);return i(p,"Security Error: sandbox engine URL is not configured.")}if(t==="iframe"){let h;try{h=Wp()}catch(p){let g=p instanceof Error?p.message:String(p);return i(g,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(td(e,n,h,r))}catch(p){return Promise.reject(p)}}let a=Hh(),s=Ha(n,a,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),o;try{let h=new Blob([s],{type:"application/javascript"}),p=URL.createObjectURL(h);try{let g=pl(p);o=new Worker(g)}finally{URL.revokeObjectURL(p)}}catch(h){let p=h instanceof Error?h.message:String(h);return i(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${p}`,"Security Error: Failed to start Worker sandbox.")}mi++;let l=!1,c={modelDispatched:!1},f,m=()=>{l||(l=!0,f!==void 0&&clearTimeout(f),mi=Math.max(0,mi-1),o.terminate())};return f=setTimeout(()=>{l||(m(),Gh(r))},3e3),o.onmessage=h=>{let p=qa(h.data,a);p&&Wh(p,r,m,c)},o.onerror=h=>{m(),r.onError?.(new Error(`Worker execution error: ${h.message}`))},e.kind==="url"?o.postMessage({type:"EXECUTE_URL",scriptUrl:e.scriptUrl,nonce:a,texturePack:e.texturePack??null}):o.postMessage({type:"EXECUTE",script:e.script,nonce:a,texturePack:e.texturePack??null}),Promise.resolve({terminate:m})}function Xh(e,t){return e!=="worker"&&e!=="iframe"?t(`SecurityError: Unsupported sandbox="${e}"; require "worker" or "iframe".`,`Security Error: sandbox="${e}" is not permitted.`):null}var Yh=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},Bn={execute(e,t,r,i){let n=Yh(r),a=Xh(t,n);if(a)return a;try{ed(e)}catch(s){let o=s instanceof Error?s.message:String(s);return n(o,"Security Error: script exceeds the size limit.")}return i?.allowClientScripts??yl()?Kh({kind:"script",script:e,texturePack:i?.texturePack},t,r,n):n(Hc,qc)},executeUrl(e,t,r,i){let n=Yh(r),a=Xh(t,n);if(a)return a;let s;try{s=Kp(e)}catch(o){let l=o instanceof Error?o.message:String(o);return n(l,"Security Error: disallowed scene script URL.")}return Kh({kind:"url",scriptUrl:s,texturePack:i?.texturePack},t,r,n)}},Wa=new Set;function Zr(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;Wa.has(r)||(Wa.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function bl(){return Array.from(Wa)}function xl(){Wa.clear()}var Ka=class extends Gi{constructor(e={}){Zr("ShaderMaterial","MeshStandardMaterial");let t=e.uniforms||{},r=t.color?.value??t.uColor?.value??t.diffuse?.value??e.color;super({color:r!==void 0?r:8421504,opacity:t.opacity?.value??e.opacity??1,transparent:!!e.transparent,wireframe:!!e.wireframe,side:e.side}),this.uniforms=t}},vl=Ka,pi=class extends $t{constructor(e=[],t=[],r=1,i=0){super();let n=Number(r)||1,a=Math.max(0,Math.min(7,Math.floor(Number(i)||0))),s=a+1,o=[],l=[],c=[],f=[],m=new Ze,h=new Ze,p=new Ze,g=(y,A)=>A.set(e[y*3]||0,e[y*3+1]||0,e[y*3+2]||0),x=(y,A)=>{let b=y.clone().normalize();o.push(b.x*n,b.y*n,b.z*n),l.push(A.x,A.y,A.z),c.push(Math.atan2(b.z,-b.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,b.y)))/Math.PI)},v=(y,A,b)=>{let w=o.length/3,S=a===0?new Ze().subVectors(b,A).cross(new Ze().subVectors(y,A)).normalize():null;x(y,S||y.clone().normalize()),x(A,S||A.clone().normalize()),x(b,S||b.clone().normalize()),f.push(w,w+1,w+2)};for(let y=0;y<t.length;y+=3){g(t[y],m),g(t[y+1],h),g(t[y+2],p);let A=[];for(let b=0;b<=s;b++){A[b]=[];let w=m.clone().lerp(p,b/s),S=h.clone().lerp(p,b/s),E=s-b;for(let N=0;N<=E;N++)A[b][N]=E===0?w.clone():w.clone().lerp(S,N/E)}for(let b=0;b<s;b++)for(let w=0;w<2*(s-b)-1;w++){let S=w>>1;(w&1)===0?v(A[b][S+1],A[b+1][S],A[b][S]):v(A[b][S+1],A[b+1][S+1],A[b+1][S])}}this.setFromBuffers(o,l,c,f)}},Qh=pi,wl=class extends pi{constructor(e=1,t=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],e,t)}},Ml=e=>Array.from(e,t=>parseInt(t,36)),Xa=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],Zh=Ml("024043035052125153134142"),_l=class extends pi{constructor(e=1,t=0){super(Xa,Zh,e,t)}},Tt=(1+Math.sqrt(5))/2,Sl=class extends pi{constructor(e=1,t=0){super([-1,Tt,0,1,Tt,0,-1,-Tt,0,1,-Tt,0,0,-1,Tt,0,1,Tt,0,-1,-Tt,0,1,-Tt,Tt,0,-1,Tt,0,1,-Tt,0,-1,-Tt,0,1],Ml("0b505101707a0ab1595b4ba2a7671839434232636838949524b62a867981"),e,t)}},Sr=1/Tt,Al=class extends pi{constructor(e=1,t=0){super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-Sr,-Tt,0,-Sr,Tt,0,Sr,-Tt,0,Sr,Tt,-Sr,-Tt,0,-Sr,Tt,0,Sr,-Tt,0,Sr,Tt,0,-Tt,0,-Sr,Tt,0,-Sr,-Tt,0,Sr,Tt,0,Sr],Ml("3b737f3fd7jh7h676fh48h8aha680g8g282a0c101i0ig6a262d6df2gi2i323di19i9bib34ec4c0408b95b5jbj7j5eje4j4h1ce1e5159"),e,t)}},Tl=class extends Ia{constructor(e=1,t=1,r=4,i=8){let n=Math.max(1e-4,Number(e)||1),a=Math.max(0,Number.isFinite(Number(t))?Number(t):1)*.5,s=Math.max(2,Math.min(64,Math.floor(Number(r)||4))),o=[];for(let l=-1;l<=1;l+=2)for(let c=0;c<=s;c++){if(l>0&&c===0&&a===0)continue;let f=(l<0?c/s-1:c/s)*(Math.PI/2);o.push(new ar(Math.max(0,Math.cos(f)*n),l*a+Math.sin(f)*n))}super(o,Math.max(4,Math.min(128,Math.floor(Number(i)||8))))}},Ya=class extends $t{constructor(e=.5,t=1,r=32,i=1,n=0,a=Math.PI*2){super();let s=Math.max(1e-4,Number(t)||1),o=Number(e),l=Number.isFinite(o)?Math.max(0,o):s*.5,c=Math.max(s,l),f=Math.min(c*.999,Math.min(s,l)),m=Math.max(3,Math.min(256,Math.floor(Number(r)||32))),h=Math.max(1,Math.min(64,Math.floor(Number(i)||1))),p=Number.isFinite(Number(n))?Number(n):0,g=Number.isFinite(Number(a))?Number(a):Math.PI*2,x=[],v=[],y=[],A=[];for(let b=0;b<=h;b++){let w=f+b/h*(c-f);for(let S=0;S<=m;S++){let E=p+S/m*g,N=Math.cos(E),C=Math.sin(E);if(x.push(w*N,w*C,0),v.push(0,0,1),y.push(w/c*N*.5+.5,w/c*C*.5+.5),b<h&&S<m){let _=b*(m+1)+S,P=_+m+1;w>1e-6&&A.push(_,P,_+1),A.push(P,P+1,_+1)}}}this.setFromBuffers(x,v,y,A)}},Pl=class extends Ya{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},Qa=class extends _r{constructor(e={}){super({roughness:.35,metalness:.1,side:2,...e});let t=Number(e.size);this.size=Number.isFinite(t)?Math.max(.002,Math.min(2,t)):.05,this.sizeAttenuation=e.sizeAttenuation!==!1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35)}},zn=class extends _r{constructor(e={}){super({roughness:.4,metalness:.1,side:2,...e});let t=Number(e.linewidth);this.linewidth=Number.isFinite(t)?Math.max(.5,Math.min(20,t)):1,e.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.3)}},Nl=class extends zn{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function Jh(e,t){let r=e?.attributes?.position;if(!r?.array||r.count<3)return new Float32Array(0);let i=r.array,n=e?.index?.array,a=Math.min(8192,Math.floor((n?n.length:r.count)/3)),s=h=>`${Math.round((i[h*3]||0)*1e4)},${Math.round((i[h*3+1]||0)*1e4)},${Math.round((i[h*3+2]||0)*1e4)}`,o=t===void 0,l=o?1:Math.cos(t*Math.PI/180),c={},f=[],m=(h,p)=>f.push(i[h*3]||0,i[h*3+1]||0,i[h*3+2]||0,i[p*3]||0,i[p*3+1]||0,i[p*3+2]||0);for(let h=0;h<a;h++){let p=n?n[h*3]:h*3,g=n?n[h*3+1]:h*3+1,x=n?n[h*3+2]:h*3+2,v=i[p*3]||0,y=i[p*3+1]||0,A=i[p*3+2]||0,b=(i[g*3]||0)-v,w=(i[g*3+1]||0)-y,S=(i[g*3+2]||0)-A,E=(i[x*3]||0)-v,N=(i[x*3+1]||0)-y,C=(i[x*3+2]||0)-A,_=w*C-S*N,P=S*E-b*C,R=b*N-w*E,I=Math.hypot(_,P,R);if(!o&&I<1e-8)continue;I>0&&(_/=I,P/=I,R/=I);let F=[p,g,x];for(let V=0;V<3;V++){let Y=F[V],J=F[(V+1)%3],re=s(Y),Q=s(J);if(re===Q)continue;let ee=re<Q?`${re}|${Q}`:`${Q}|${re}`,k=c[ee];k?k.m||(k.m=1,k.nx*_+k.ny*P+k.nz*R<=l&&m(Y,J)):(c[ee]={va:Y,vb:J,nx:_,ny:P,nz:R,m:o?1:0},o&&m(Y,J))}}if(!o){let h=Object.keys(c);for(let p=0;p<h.length;p++){let g=c[h[p]];g&&!g.m&&m(g.va,g.vb)}}return new Float32Array(f)}var Cl=class extends $t{constructor(e){super(),this.setAttribute("position",new zt(Jh(e),3)),this.__isSegmentPairs=!0}},El=class extends $t{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new zt(Jh(e,r),3)),this.__isSegmentPairs=!0}};function rd(e,t,r=1){let i=new $t;i.__baked=!0;let n=e?.attributes?.position;if(!n?.array||n.count<2)return i;let a=n.array,s=e.index?.array,o=e.__isSegmentPairs?"segments":t,l=s?s.length:n.count,c=Math.min(4096,Math.max(0,o==="segments"?Math.floor(l/2):o==="loop"&&l>=3?l:l-1));if(c===0)return i;e.computeBoundingBox();let f=e.boundingBox,m=f&&f.max.x>=f.min.x&&f.max.distanceTo(f.min)||1,h=Math.max(.0015,Math.min(.025,m*.003))*(.5+.5*Math.max(.5,Math.min(6,Number(r)||1))),p=[],g=[],x=[],v=[];for(let y=0;y<c;y++){let A=o==="segments"?y*2:y,b=o==="segments"?y*2+1:(y+1)%l,w=s?s[A]:A,S=s?s[b]:b,E=a[w*3]||0,N=a[w*3+1]||0,C=a[w*3+2]||0,_=(a[S*3]||0)-E,P=(a[S*3+1]||0)-N,R=(a[S*3+2]||0)-C,I=Math.hypot(_,P,R);if(I<1e-6)continue;let F=_/I,V=P/I,Y=R/I,J=(Math.abs(V)<.9?Math.hypot(Y,F):Math.hypot(Y,V))||1,re=Math.abs(V)<.9?Y/J:0,Q=Math.abs(V)<.9?0:-Y/J,ee=Math.abs(V)<.9?-F/J:V/J,k=V*ee-Y*Q,G=Y*re-F*ee,q=F*Q-V*re,H=p.length/3,te=[[re,Q,ee],[k,G,q],[-re,-Q,-ee],[-k,-G,-q]];for(let Z=0;Z<2;Z++){let ae=E+Z*_,ie=N+Z*P,de=C+Z*R;for(let me=0;me<4;me++){let Se=te[me];p.push(ae+Se[0]*h,ie+Se[1]*h,de+Se[2]*h),g.push(Se[0],Se[1],Se[2]),x.push(me/4,Z)}}for(let Z=0;Z<4;Z++){let ae=(Z+1)%4;v.push(H+Z,H+ae,H+4+ae,H+Z,H+4+ae,H+4+Z)}}return p.length>0&&i.setFromBuffers(p,g,x,v),i}function id(e,t=.05){let r=new $t;r.__baked=!0;let i=e?.attributes?.position;if(!i?.array||i.count<1)return r;let n=i.array,a=i.count,s=Math.min(a,5e3),o=Math.max(.003,Math.min(.25,(Number(t)||.05)*.6)),l=[],c=[],f=[],m=[];for(let h=0;h<s;h++){let p=a<=5e3?h:Math.floor(h*a/s),g=n[p*3]||0,x=n[p*3+1]||0,v=n[p*3+2]||0,y=h*6;for(let A=0;A<6;A++){let b=Xa[A*3],w=Xa[A*3+1],S=Xa[A*3+2];l.push(g+b*o,x+w*o,v+S*o),c.push(b,w,S),f.push(.5,.5)}for(let A=0;A<24;A++)m.push(y+Zh[A])}return r.setFromBuffers(l,c,f,m),r}var Pi=class extends Yr{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},n=t instanceof _r?t:r==="points"?new Qa(i):new zn(i),a=e instanceof $t?e:new $t;super(a,n),this.isLine=!0,this._lineMode=r,this._sourceGeo=a}computeLineDistances(){return this}_bakeAuthorGeometry(){this.geometry&&!this.geometry.__baked&&(this._sourceGeo=this.geometry);let e=this._lineMode==="points";if(e){let t=this._sourceGeo?.attributes?.color;if(t?.array&&t.count>0&&this.material?.color.r===1&&this.material.color.g===1&&this.material.color.b===1){let r=t.array,i=Math.min(t.count,64),n=0,a=0,s=0;for(let o=0;o<i;o++)n+=r[o*3]||0,a+=r[o*3+1]||0,s+=r[o*3+2]||0;this.material.color.setRGB(n/i,a/i,s/i)}}!this.geometry?.__baked&&this._sourceGeo?.attributes?.position?.count>=(e?1:2)&&(this.geometry=e?id(this._sourceGeo,this.material?.size??.05):rd(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},Ll=class extends Pi{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},Rl=class extends Pi{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},Il=class extends Pi{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},$l=class extends Ba{constructor(e,t,r=0,i=Math.PI/3,n=0,a=2){super(e,t,r,a),this.target=new zr,this.type="spot";let s=Number(i);this.angle=Number.isFinite(s)?Math.max(.01,Math.min(Math.PI/2,s)):Math.PI/3;let o=Number(n);this.penumbra=Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}},Za=class extends fi{constructor(e,t,r){super(e,r),this.type="hemisphere",this.groundColor=new Br(t??4473924),this.position.set(0,1,0)}},Dl=class extends Fa{constructor(e,t){Zr("RectAreaLight","AmbientLight"),super(e,t)}},ef={Vector2:ar,Vector3:Ze,Vector4:Bo,Euler:Ca,Quaternion:Dn,Matrix4:Ai,Matrix3:zo,Color:Br,MathUtils:Uo,BufferAttribute:zt,Float32BufferAttribute:Oo,Uint16BufferAttribute:jo,Uint32BufferAttribute:Go,BufferGeometry:$t,BoxGeometry:La,PlaneGeometry:Ho,SphereGeometry:qo,CylinderGeometry:Ra,ConeGeometry:Wo,TorusGeometry:Ko,TorusKnotGeometry:Xo,Curve:hi,Curve3:hi,LineCurve3:Yo,QuadraticBezierCurve3:Qo,CubicBezierCurve3:Zo,CatmullRomCurve3:Jo,LatheGeometry:Ia,TubeGeometry:el,PolyhedronGeometry:pi,IcosahedronGeometry:Sl,OctahedronGeometry:_l,DodecahedronGeometry:Al,TetrahedronGeometry:wl,CapsuleGeometry:Tl,RingGeometry:Ya,CircleGeometry:Pl,WireframeGeometry:Cl,EdgesGeometry:El,FrontSide:0,BackSide:1,DoubleSide:2,NoBlending:0,NormalBlending:1,AdditiveBlending:2,MultiplyBlending:4,RepeatWrapping:1e3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002,NearestFilter:1003,NearestMipmapNearestFilter:1004,NearestMipmapLinearFilter:1005,LinearFilter:1006,LinearMipmapNearestFilter:1007,LinearMipmapLinearFilter:1008,UnsignedByteType:1009,ByteType:1010,ShortType:1011,UnsignedShortType:1012,IntType:1013,UnsignedIntType:1014,FloatType:1015,HalfFloatType:1016,AlphaFormat:1021,RGBFormat:1022,RGBAFormat:1023,LuminanceFormat:1024,LuminanceAlphaFormat:1025,RedFormat:1028,RGFormat:1030,NoColorSpace:"",SRGBColorSpace:"srgb",LinearSRGBColorSpace:"srgb-linear",StaticDrawUsage:35044,DynamicDrawUsage:35048,ACESFilmicToneMapping:4,BasicShadowMap:0,PCFShadowMap:1,PCFSoftShadowMap:2,VSMShadowMap:3,Texture:kn,DataTexture:tl,TextureLoader:rl,Material:_r,MeshStandardMaterial:Gi,MeshBasicMaterial:nl,MeshLambertMaterial:al,MeshPhongMaterial:sl,MeshPhysicalMaterial:ol,PointsMaterial:Qa,LineBasicMaterial:zn,LineDashedMaterial:Nl,ShaderMaterial:Ka,RawShaderMaterial:vl,Object3D:zr,Group:ll,Mesh:Yr,InstancedMesh:Da,Line:Pi,LineLoop:Ll,LineSegments:Rl,Points:Il,LightShadow:ka,Light:fi,AmbientLight:Fa,DirectionalLight:ul,PointLight:Ba,SpotLight:$l,HemisphereLight:Za,RectAreaLight:Dl,Camera:za,PerspectiveCamera:cl,Scene:Va,WebGLRenderer:fl,Clock:ml,SceneQuotaValidator:Qr,exportSceneToCanvas3D:Ua,exportSceneToGLB:Oa,exportSceneToUSDZ:hl,generateUSDZ:Sa,glbToUSDZ:_a,sceneToCanvas3D:Vi,sceneToGLB:En,sceneToUSDZ:In,authorScriptRunner:Bn,warnUnsupported:Zr,getAuthorWarnings:bl,clearAuthorWarnings:xl};Object.freeze(Qr),Object.freeze(Qr.prototype),Object.freeze(Va.prototype),Object.freeze(ef);var Ni=new Proxy(ef,{get:(e,t)=>{if(t in e)return e[t];let r=We().authorNamespace;return r&&typeof t=="string"&&t in r?r[t]:(typeof t=="string"&&t!=="then"&&t!=="toJSON"&&!t.startsWith("__")&&Zr(`THREE.${t}`,"no-op proxy"),qi)},has:(e,t)=>{if(t in e)return!0;let r=We().authorNamespace;return!!(r&&typeof t=="string"&&t in r)},set:(e,t)=>{throw new TypeError(`Cannot assign to read only property '${String(t)}' of #<THREE>`)},defineProperty:(e,t)=>{throw new TypeError(`Cannot define property '${String(t)}', object is not extensible`)},deleteProperty:(e,t)=>{throw new TypeError(`Cannot delete property '${String(t)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),Ja=We();if(Ja.threeNamespace=Ni,Ja.workerExtensionInstallers)for(let e of Ja.workerExtensionInstallers)e(Ni,Ja);var Wi={name:"three_author",THREE:Ni},tf=Wi,Jr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof Jr.THREE>"u"&&(Jr.THREE=Ni),typeof Jr.requestAnimationFrame!="function"&&(Jr.requestAnimationFrame=e=>(typeof e=="function"&&typeof Jr.__three_live_raf_cb__!="function"&&(Jr.__three_live_raf_cb__=e),Jr.__three_live_in_step__||Zr("requestAnimationFrame","single-frame static evaluation"),0)),typeof Jr.cancelAnimationFrame!="function"&&(Jr.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=Ni,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=Wi,e.ThreeLivePlugins.three_author=Wi,e.ThreeLivePlugins["three-author"]=Wi}function es(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var kl=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),nd=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(e,t){super(e,t),this.detail=t?.detail??null}});var ts=class xi extends nd{constructor(){super(...arguments),this.viewer=null,this.canvas=null,this.posterEl=null,this.arButton=null,this.currentModel=null,this.activeXRSession=null,this.toastTimer=null,this.currentModelLimits=void 0,this.isModelLoaded=!1,this.scriptHandle=null,this.loadController=null,this.resizeObserver=null,this.mutationObserver=null}static get sandboxEngineSrc(){return We().sandboxEngineSrc??null}static set sandboxEngineSrc(t){We().sandboxEngineSrc=t}static get sandboxIframeSrc(){return We().sandboxIframeSrc??null}static set sandboxIframeSrc(t){We().sandboxIframeSrc=t}static get allowClientScripts(){return!!We().allowClientScripts}static set allowClientScripts(t){We().allowClientScripts=t}static registerScriptRunner(t){We().scriptRunner=t}static defineModelViewer(t="model-viewer"){if(typeof customElements>"u")return!1;let r=customElements.get(t);return r!=null?r===xi||r.prototype instanceof xi:(customElements.define(t,class extends xi{}),!0)}static registerDecoder(t,r){ir.registerDecoder(t,r)}static getDecoder(t){return ir.getDecoder(t)}static registerAR(t){We().arProvider=typeof t=="function"?{activateAR:t}:t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof xi&&r.updateARButtonVisibility()})}static isARSupported(){return!!We().arProvider}getLoadedModel(){return this.currentModel}beginLoad(){let t=this.loadController,r=this.scriptHandle,i=new AbortController;return this.loadController=i,this.scriptHandle=null,t?.abort(),r?.terminate(),i}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let t=this.getAttribute("src"),r=this.getAttribute("script-src");t?this.loadModel(t).catch(()=>{}):r?this.loadScriptFromSrc(r).catch(()=>{}):this.scheduleInlineScript();for(let i of ir.getRegisteredPlugins())i.onElementConnected?.(this)}scheduleInlineScript(){let t=this.loadController,r=()=>{let i=this.querySelector('script[type="text/three"], script[type="text/three-live"]');return this.loadController===t&&i?.textContent?(this.executeScript(i.textContent).catch(()=>{}),!0):!1};queueMicrotask(()=>r()||document.addEventListener("DOMContentLoaded",r))}disconnectedCallback(){for(let t of ir.getRegisteredPlugins())t.onElementDisconnected?.(this);this.beginLoad().abort(),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,this.viewer?.destroy(),this.viewer=null,this.isModelLoaded=!1}attributeChangedCallback(t,r,i){if(r===i)return;let n=this.viewer;switch(t){case"src":i&&this.loadModel(i).catch(()=>{});break;case"camera-target":{let a=this.parseCameraTarget(i);n&&a&&n.setTarget(a[0],a[1],a[2]);break}case"min-camera-orbit":case"max-camera-orbit":if(n){let a=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttr("max-camera-orbit"));n.setOrbitLimits({minTheta:a.theta,maxTheta:s.theta,minPhi:a.phi,maxPhi:s.phi,minDistance:a.distance,maxDistance:s.distance})}break;case"field-of-view":{let a=this.parseFieldOfView(i);n&&a!==void 0&&n.setFieldOfView(a);break}case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":n?.setSelectedMesh(i??"");break;case"exposure":if(n&&i!==null){let a=parseFloat(i);isNaN(a)||n.setExposure(a)}break;case"shadow-intensity":case"shadow-softness":n?.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":n?.setToneMapping(Bi(i));break;case"environment-image":n?.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":n?.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let a=this.cameraControls;n?.setInteractive?.(a),this.canvas&&(this.canvas.style.touchAction=a?"none":"auto");break}case"autoplay":n?.setAutoplay(i!==null&&i!=="false");break;case"animation-name":n&&i!==null&&n.setAnimationName(i);break;case"variant-name":n&&this.selectVariant(i);break;case"auto-rotate":n?.setAutoRotate(i!==null&&i!=="false");break;case"auto-rotate-delay":n?.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":n?.setAutoRotateSpeed(this.parseRotationPerSecond(i));break;case"ar":this.updateARButtonVisibility();break;case"renderer":n?.render();break;case"shadow-maps":n&&(n.shadowMaps=i!==null?this.shadowMaps:void 0),n?.render();break}for(let a of ir.getRegisteredPlugins())a.onAttributeChanged?.(this,t,r,i)}getAttr(t){return this.getAttribute(t)}setAttr(t,r){r!==null?this.setAttribute(t,String(r)):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttr(t)!=="false"}setBoolAttr(t,r){this.setAttr(t,r?"":null)}getFloatAttr(t,r){let i=this.getAttr(t);return i!==null?parseFloat(i):r}get sandbox(){return this.getAttr("sandbox")||(We().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||xi.allowClientScripts}set allowClientScripts(t){this.setBoolAttr("allow-client-scripts",t)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(t){this.setBoolAttr("ar",t)}get canActivateAR(){return xi.isARSupported()}get toneMapping(){return Bi(this.getAttr("tone-mapping"))}set toneMapping(t){this.setAttr("tone-mapping",t)}get bloomThreshold(){return es(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return es(this.getAttr("bloom-radius"),.75)}set bloomRadius(t){this.setAttr("bloom-radius",t)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(t){this.setAttr("variant-name",t)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}get renderer(){let t=this.getAttr("renderer")?.trim().toLowerCase();return t==="webgpu"||t==="webgl2"?t:"auto"}set renderer(t){this.setAttr("renderer",t)}get shadowMaps(){let t=this.getAttr("shadow-maps")?.trim().toLowerCase();return t==="pcf"||t==="off"?t:"auto"}set shadowMaps(t){this.setAttr("shadow-maps",t)}fireEvent(t,r){this.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:r}))}setSlotVisible(t,r){let i=typeof this.querySelector=="function"?this.querySelector(`[slot="${t}"]`):null;i&&(i.hidden=!r,i.style&&(i.style.display=r?"":"none"))}emitError(t,r="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:t}),this.fireEvent("three-error",{error:t,message:t?.message||String(t),stage:r})}selectVariant(t){if(!this.viewer)return!1;let r=this.viewer.selectVariant(t);return r&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),r}get model(){let t=this.viewer?this.viewer.getModelMaterials():[];return{materials:t,getMaterialByName(r){return t.find(i=>i.name===r)??null}}}play(){this.viewer?.playAnimation(this.animationName||void 0)}pause(){this.viewer?.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(t=0){this.viewer?.resetTurntableRotation(t)}setCamera(t,r,i,n){this.viewer?.setCamera(t,r,i,n)}getCameraOrbit(){return this.viewer?.getCameraOrbit()??{theta:0,phi:0,radius:3,toString:()=>"0rad 0rad 3m"}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():kl(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,r){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(t,r):""}toBlob(t){return this.viewer?.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(n=>{n?r(n):i(new Error("Failed to capture canvas blob."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,r){let i=this.viewer?.raycastFromScreenPoint(t,r);if(!i)return null;let[n,a,s]=i.hitPoint||i.point,[o,l,c]=i.normal;return{position:kl(n,a,s),normal:kl(o,l,c)}}loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,r,i=this.beginLoad()){if(i.signal.throwIfAborted(),!this.viewer){this.currentModel=t,this.currentModelLimits=r;return}try{let n;if(typeof t=="string"){let l=await fetch(t,{signal:i.signal});if(!l.ok)throw new Error(`Failed to load "${t}": HTTP ${l.status}`);n=await l.arrayBuffer()}else n=t;i.signal.throwIfAborted();let a=zi(n);this.viewer.loadGLBData(a,r),this.currentModel=a,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let s=this.getAttr("selected-mesh");s&&this.viewer.setSelectedMesh(s);let o=this.getAttr("variant-name");o&&this.selectVariant(o),this.fireEvent("load",{model:a}),this.fireEvent("three-load",{model:a,source:typeof t=="string"?"src":"model"})}catch(n){throw i.signal.aborted||this.emitError(n,"load"),n}}showToast(t,r=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background:rgba(15,23,42,.94);color:#f8fafc;border:1px solid rgba(56,189,248,.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s,transform .25s;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=t,this.toastTimer&&clearTimeout(this.toastTimer);let n=()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(n):n(),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let t=(a,s=a.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:a}),this.showToast(s,6e3),a};this.currentModel||t(new Error("No 3D model is loaded in <three-live>."));let r=We().arProvider;r||t(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let i=this.getAttr("ios-src"),n=(this.getAttr("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let a=await r.activateAR({model:i||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:n.length>0?n:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"not-presenting"})},onError:s=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(`AR error: ${s.message}`,6e3)}}});if(a.success){a.session&&(this.activeXRSession=a.session);let s={"quick-look":"Opening Apple AR Quick Look...","scene-viewer":"Opening Google Scene Viewer...",webxr:"WebXR AR session started."}[a.mode||""]||"";s&&this.showToast(s)}else{let s=a.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(this.isDesktopMac()&&typeof document<"u"&&this.currentModel&&r.createUSDZBlob)try{let o=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:r.createUSDZBlob(this.currentModel),l=URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download="three_live_model.usdz",document.body.appendChild(c),c.click(),document.body.removeChild(c),setTimeout(()=>URL.revokeObjectURL(l),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(s,6e3)}else this.showToast(s,6e3);a.error&&this.fireEvent("ar-status",{status:"failed",error:a.error})}return a}catch(a){return this.activeXRSession=null,t(a,`AR error: ${a.message||String(a)}`)}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(t)),this.canvas=t,typeof t.addEventListener=="function"&&!t.__tlCtxBound&&(t.__tlCtxBound=!0,t.addEventListener("webglcontextlost",i=>this.fireEvent("three-context-lost",{originalEvent:i})),t.addEventListener("webglcontextrestored",i=>this.fireEvent("three-context-restored",{originalEvent:i}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);let r=this.getAttr("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;this.viewer=new ir(this,this.canvas,{autoRotate:this.autoRotate,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttr("rotation-per-second")),exposure:this.exposure,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,shadowMaps:this.hasAttribute("shadow-maps")?this.shadowMaps:void 0,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttr("variant-name")||void 0,fieldOfView:this.parseFieldOfView(this.getAttr("field-of-view")),cameraTarget:this.parseCameraTarget(this.getAttr("camera-target")),minCameraOrbit:this.parseOrbitLimit(this.getAttr("min-camera-orbit")),maxCameraOrbit:this.parseOrbitLimit(this.getAttr("max-camera-orbit")),onMeshClick:r=>{this.fireEvent("meshclick",r)},onCameraChange:r=>{this.updateHotspots();for(let i of ir.getRegisteredPlugins())i.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",r)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let t=this.getAttr("camera-orbit");t&&this.applyCameraOrbit(t),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(t){if(!(typeof document>"u")){if(!t){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.alt="3D Scene Preview",this.posterEl.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}isDesktopMac(){let t=typeof navigator<"u"&&navigator.userAgent||"";return/Macintosh/i.test(t)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1)&&!/Android|iPhone|iPad|iPod/i.test(t)}syncARButtonLabel(t){let r=this.isDesktopMac(),i=r?"Quick Look (.usdz)":"View in AR",n=r?"Download .usdz preview for macOS Quick Look (live camera AR requires iOS or Android)":"View in Augmented Reality";typeof t.setAttribute=="function"&&(t.setAttribute("aria-label",n),t.setAttribute("title",n));let a=t._labelSpan||(typeof t.querySelector=="function"?t.querySelector("span"):null);a&&(a.textContent=i)}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.type="button",t.className="three-live-ar-button",t.setAttribute("part","default-ar-button");let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let n=document.createElementNS(r,"svg");for(let[s,o]of Object.entries({width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}))n.setAttribute(s,o);n.style.marginRight="6px";let a=document.createElementNS(r,"path");a.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),n.appendChild(a),t.appendChild(n)}let i=document.createElement("span");t._labelSpan=i,t.appendChild(i),this.syncARButtonLabel(t),t.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,.85);color:#fff;border:1px solid rgba(255,255,255,.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,.25);transition:transform .15s,background-color .15s;display:none";for(let[n,a,s]of[["mouseenter","rgba(30, 41, 59, 0.95)","scale(1.04)"],["mouseleave","rgba(15, 23, 42, 0.85)","scale(1)"]])t.addEventListener(n,()=>{t.style.backgroundColor=a,t.style.transform=s});t.addEventListener("click",n=>{n.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&xi.isARSupported(),r=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;r?(this.arButton&&(this.arButton.style.display="none"),r.__tlARBound||(r.__tlARBound=!0,r.addEventListener("click",i=>{i.stopPropagation(),this.activateAR()})),r.dataset.tlOrigDisplay===void 0&&(r.dataset.tlOrigDisplay=r.style.display==="none"?"":r.style.display),r.style.display=t?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.syncARButtonLabel(this.arButton),this.arButton.style.display=t?"flex":"none")}applyCameraOrbit(t){if(!(!t||!this.viewer))try{let r=JSON.parse(t);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=this.parseOrbitLimit(t);(r.theta!==void 0||r.phi!==void 0)&&this.viewer.setInitialCamera(r.theta,r.phi,r.distance)}}parseOrbitLimit(t){if(!t)return{};let[r,i,n]=t.trim().split(/\s+/),a=n&&n!=="auto"?parseFloat(n):NaN;return{theta:r&&r!=="auto"?this.parseFieldOfView(r):void 0,phi:i&&i!=="auto"?this.parseFieldOfView(i):void 0,distance:isNaN(a)?void 0:a}}parseCameraTarget(t){if(!t)return;let r=t.trim().split(/\s+/).map(parseFloat);return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(t){if(!t)return;let r=parseFloat(t);return isNaN(r)?void 0:t.endsWith("rad")?r*180/Math.PI:r}parseRotationPerSecond(t){if(!t)return Math.PI/6;let r=t.trim(),i=parseFloat(r);return isNaN(i)?Math.PI/6:r.endsWith("rad")?i:r.endsWith("%")?i/100*Math.PI*2:i*Math.PI/180}updateHotspot(t){let r=this.querySelector(`[slot="${t.name}"]`);r&&(t.position!==void 0&&r.setAttribute("data-position",t.position),t.normal!==void 0&&r.setAttribute("data-normal",t.normal)),this.updateHotspots()}updateHotspots(){for(let t of ir.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=We().scriptRunner;if(!r){let a=new Error('Script execution requires "three-live/full" or registerScriptRunner().');return this.showToast(a.message),this.emitError(a,"script"),Promise.reject(a)}let i=this.beginLoad(),n=()=>!i.signal.aborted;return new Promise((a,s)=>{let o=()=>s(i.signal.reason);if(i.signal.addEventListener("abort",o,{once:!0}),!n()){o();return}let l={onModelReady:c=>{this.loadModelWithLimits(c,bp,i).then(()=>a(c),s)},onUpdateTransforms:c=>{n()&&this.viewer?.updateMeshTransforms(c)},onError:c=>{n()&&(this.showToast(c.message),this.emitError(c,"script"),s(c))},onToast:c=>{n()&&this.showToast(c)}};t(r,l).then(c=>{n()?this.scriptHandle=c||null:c?.terminate()},c=>{n()&&l.onError?.(c)})})}loadScriptFromSrc(t){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let n=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(n),Promise.reject(n)}return r.executeUrl(t,this.sandbox,i)})}executeScript(t){if(!We().scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Hc);return this.showToast(qc),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};ts.observedAttributes="src ios-src script-src sandbox allow-client-scripts poster camera-controls camera-orbit camera-target min-camera-orbit max-camera-orbit field-of-view selected-mesh ar ar-modes ar-scale ar-placement exposure shadow-intensity shadow-softness tone-mapping bloom bloom-threshold bloom-radius outline outline-selected outline-color environment-image skybox-image autoplay animation-name variant-name auto-rotate auto-rotate-delay rotation-per-second renderer shadow-maps".split(" "),ts.registerPlugin=ir.registerPlugin,ts.getRegisteredPlugins=ir.getRegisteredPlugins;var di=ts;{let e=di.prototype,t=(i,n,a)=>Object.defineProperty(e,i,{get:n,set:a,configurable:!0}),r=i=>i.replace(/[A-Z]/g,n=>"-"+n.toLowerCase());for(let i of"src cameraOrbit cameraTarget minCameraOrbit maxCameraOrbit fieldOfView iosSrc scriptSrc poster selectedMesh environmentImage skyboxImage animationName".split(" ")){let n=r(i);t(i,function(){return this.getAttr(n)},function(a){this.setAttr(n,a)})}for(let i of"cameraControls autoRotate outlineSelected autoplay".split(" ")){let n=r(i);t(i,function(){return this.getBoolAttr(n)},function(a){this.setBoolAttr(n,a)})}for(let[i,n]of[["exposure",1],["autoRotateDelay",3e3],["shadowIntensity",0],["shadowSoftness",.5],["bloom",0]]){let a=r(i);t(i,function(){return this.getFloatAttr(a,n)},function(s){this.setAttr(a,s)})}for(let[i,n]of[["rotationPerSecond","30deg"],["arScale","auto"],["arPlacement","floor"],["outlineColor","#38bdf8"]]){let a=r(i);t(i,function(){return this.getAttr(a)||n},function(s){this.setAttr(a,s)})}}typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",di);function rf(e="model-viewer"){return di.defineModelViewer(e)}var nf={eye:[0,1.6,5],target:[0,.8,0]},af=new Set("the a an please can could would you will i want wanna to me my that this those these of one ones object objects thing things item items mesh meshes piece pieces part parts just only also too is are there here which select pick choose highlight grab focus on in at by some most side hand them it its and s now again as well other others".split(" ")),ad=["sofa couch settee","lamp light lantern","door gate doorway","table desk","chair seat stool","rug carpet mat","cup mug","tv television screen monitor","car vehicle automobile","box crate cube","ball sphere orb","floor ground","plant tree bush","cabinet cupboard closet"].map(e=>e.split(" ")),rs=[["red",[220,40,40],"red"],["orange",[245,140,30],"orange"],["yellow",[240,220,40],"yellow"],["gold",[212,175,55],"yellow"],["green",[50,170,60],"green"],["teal",[0,128,128],"green"],["cyan",[40,200,220],"blue"],["blue",[40,80,220],"blue"],["navy",[20,30,100],"blue"],["purple",[130,50,180],"purple"],["magenta",[220,40,200],"pink"],["pink",[240,120,180],"pink"],["brown",[130,80,40],"brown"],["beige",[225,205,160],"brown"],["white",[245,245,245],"white"],["silver",[192,192,192],"gray"],["gray",[128,128,128],"gray"],["black",[20,20,20],"black"]],sf={grey:"gray",golden:"gold",crimson:"red",maroon:"red",violet:"purple",aqua:"cyan",turquoise:"cyan",tan:"beige"},Fl={};function Ir(e,t){for(let r of e.split(" "))Fl[r]=t}Ir("left leftmost",["right",!1]),Ir("right rightmost",["right",!0]),Ir("front nearest closest frontmost",["depth",!1]),Ir("back farthest furthest rear far backmost",["depth",!0]),Ir("top highest upper topmost",["up",!0]),Ir("bottom lowest lower bottommost",["up",!1]),Ir("biggest largest big large huge bigger larger",["size",!0]),Ir("smallest small tiny little smaller",["size",!1]),Ir("tallest tall taller",["height",!0]),Ir("shortest short shorter",["height",!1]),Ir("middle center centre central","middle");var of={first:0,second:1,third:2,fourth:3,fifth:4,last:-1},lf={two:2,pair:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10},uf=new Set(["all","every","everything","each","everybody"]),Bl=e=>/^[0-9]+$/.test(e),is=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),zl=e=>is(Fl,e)?Fl[e]:null,cf=e=>is(of,e)?of[e]:null;function hf(e){let t;if(is(lf,e))t=lf[e];else if(/^[0-9]{1,3}$/.test(e))t=Number(e);else return null;return t>=1&&t<=50?t:null}function ff(e){return is(sf,e)?sf[e]:rs.some(t=>t[0]===e)?e:null}function sd(e){for(let t=0;t<e.length;t++){let r=e[t],i=e[t+1]??"";if(/^(near|nearby|beside|behind|under|underneath|beneath|above|below|between|inside|within|against|with|beyond|around)$/.test(r)||(r==="next"||r==="close")&&i==="to"||(r==="front"||r==="top")&&i==="of")return!0;if(r==="on"||r==="by"){let n=t+1;for(;n<e.length&&/^(the|a|an|its|my)$/.test(e[n]);)n++;let a=e[n];if(a!==void 0&&!zl(a)&&a!=="side"&&a!=="end")return!0}}return!1}function od(e){return String(e??"").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function mf(e){let t=e.length;if(t>4&&e.endsWith("ies"))return e.slice(0,-3)+"y";if(t>4&&e.endsWith("ves"))return e.slice(0,-3)+"f";for(let r of["ches","shes","xes","sses","zes"])if(t>r.length+1&&e.endsWith(r))return e.slice(0,-2);return t>3&&e.endsWith("s")&&!e.endsWith("ss")&&!e.endsWith("us")?e.slice(0,-1):e}function ld(e){let t=[],r="",i="",n=o=>o>="a"&&o<="z",a=o=>o>="A"&&o<="Z",s=o=>o>="0"&&o<="9";for(let o of String(e)){if(!(n(o)||a(o)||s(o))){r&&t.push(r),r="",i="";continue}i&&r&&(n(i)&&a(o)||s(i)!==s(o))&&(t.push(r),r=""),r+=o.toLowerCase(),i=o}return r&&t.push(r),t.map(mf)}var ud=e=>e.replace(/[^A-Za-z0-9]/g,"").toLowerCase(),cd=(e,t)=>ad.some(r=>r.includes(e)&&r.includes(t));function pf(e,t){return e===t||cd(e,t)||t.length>=4&&e.length>=4&&(e.startsWith(t)||t.startsWith(e))}function Vl(e){let t=Math.min(1,Math.max(0,Number.isFinite(e)?e:0));return(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)*255}function hd(e){let t=[Vl(e[0]),Vl(e[1]),Vl(e[2])],r=rs[0][0],i=1/0;for(let[n,a]of rs){let s=(t[0]-a[0])**2+(t[1]-a[1])**2+(t[2]-a[2])**2;s<i&&(i=s,r=n)}return r}var fd=e=>rs.find(t=>t[0]===e)?.[2]??"";function md(e,t){return e.words.includes(t)?!0:e.colorName!=null&&(e.colorName===t||fd(e.colorName)===t)}function ns(e){return e.map((t,r)=>{let i=[0,1,2].map(n=>Math.abs(t.max[n]-t.min[n]));return{id:r,name:t.name,words:ld(t.name),colorName:t.color?hd(t.color):null,size:Math.max(i[0],.01)*Math.max(i[1],.01)*Math.max(i[2],.01),height:i[1],center:[0,1,2].map(n=>(t.min[n]+t.max[n])/2)}})}function pd(e){let t=[0,1,2].map(s=>e.target[s]-e.eye[s]),r=Math.hypot(t[0],t[1],t[2]),i=r<1e-9?[0,0,-1]:t.map(s=>s/r),n=[-i[2],0,i[0]],a=Math.hypot(n[0],n[1],n[2]);return{eye:e.eye,right:a<1e-9?[1,0,0]:n.map(s=>s/a)}}function Ki(e,t,r){let i=[0,1,2].map(n=>e.center[n]-r.eye[n]);switch(t){case"right":return i[0]*r.right[0]+i[1]*r.right[1]+i[2]*r.right[2];case"depth":return Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]);case"up":return e.center[1];case"size":return e.size;default:return e.height}}var df=e=>e.length?e.reduce((t,r)=>t+r,0)/e.length:0;function Ul(e,t,r){let i;if(t==="middle"){if(e.length<3)return e;let n=e.map(o=>Ki(o,"right",r)),a=Math.min(...n),s=Math.max(...n);i=e.filter((o,l)=>n[l]>a+1e-6&&n[l]<s-1e-6)}else{let n=e.map(s=>Ki(s,t[0],r)),a=df(n);i=e.filter((s,o)=>t[1]?n[o]>a+1e-6:n[o]<a-1e-6)}return i.length?i:e}function gf(e,t,r){let i;if(t==="middle"){let n=df(e.map(a=>Ki(a,"right",r)));i=e.map(a=>[a,Math.abs(Ki(a,"right",r)-n)])}else i=e.map(n=>[n,t[1]?-Ki(n,t[0],r):Ki(n,t[0],r)]);return i.sort((n,a)=>n[1]-a[1])}function or(e,t,r){let i=[...e].sort((s,o)=>s.id-o.id),n=[...new Set(i.map(s=>s.id))],a=[];for(let s of i)!a.includes(s.name)&&a.length<50&&a.push(s.name);return t==="high"?{ids:n,names:a,confidence:t,candidates:[],reason:r}:t==="ambiguous"?{ids:[],names:[],confidence:t,candidates:a.slice(0,10),reason:r}:{ids:[],names:[],confidence:t,candidates:[],reason:r}}var Ci=e=>or([],"none",e);function Ol(e,t,r=nf,i){let n=i?e.filter(s=>i.includes(s.name)):[...e],a=od(t);for(let s=0;s<a.length;s++){let o=a[s],l=a[s+1]??"",c=o==="except"||o==="excluding";if(!(c||o==="but"&&l==="not"||o==="other"&&l==="than"))continue;let f=jl(n,a.slice(0,s),r);if(f.confidence!=="high")return f;let m=n.filter(g=>f.ids.includes(g.id)),h=jl(m,a.slice(s+(c?1:2)),r);if(h.confidence!=="high")return or(m,"ambiguous","except");let p=m.filter(g=>!h.ids.includes(g.id));return p.length?or(p,"high","match"):Ci("no_match")}return jl(n,a,r)}function dd(e){return!(af.has(e)||uf.has(e)||e==="both"||hf(e)!==null||cf(e)!==null||ff(e)!==null||zl(e)!==null||Bl(e))}function jl(e,t,r){let i=[[]];for(let l of t)l==="and"?i.push([]):i[i.length-1].push(l);let n=i.filter(l=>l.length);if(n.length<2||!n.every(l=>l.some(dd)))return yf(e,t,r);let a=[],s=!1;for(let l of n){let c=yf(e,l,r);if(c.confidence==="none")return c;c.confidence==="ambiguous"?(s=!0,a.push(...e.filter(f=>c.candidates.includes(f.name)))):a.push(...e.filter(f=>c.ids.includes(f.id)))}let o=[...new Map(a.map(l=>[l.id,l])).values()];return s?or(o,"ambiguous","multiple"):or(o,"high","match")}function yf(e,t,r){if(!e.length)return Ci("no_match");let i=0;for(;i<t.length&&/^(select|pick|choose|highlight|grab|the|a|an|just|only)$/.test(t[i]);)i++;let n=t.slice(i).join("");if(n){let y=e.filter(A=>ud(A.name)===n);if(y.length)return or(y,"high","exact")}if(sd(t))return Ci("relation");let a=[],s=!1,o=!1,l=null,c=null,f=[],m=[],h=!1;for(let y of t){if(h&&Bl(y)){a.push(y);continue}h=!1;let A,b,w;if(uf.has(y))o=!0,s=!0;else if(y==="both")l=2,s=!0;else if((A=hf(y))!==null)l=A,s=s||A>1;else if((A=cf(y))!==null)c=A;else if((b=ff(y))!==null)f.push(b);else if((w=zl(y))!==null)m.push(w);else if(!af.has(y)){let S=mf(y);S!==y&&(s=!0),a.push(S),h=!0}}if(!a.length&&!f.length&&!m.length&&c===null&&!o&&l===null)return Ci("empty");let p=pd(r),g=e;if(a.length){let y=g.map(S=>({e:S,n:a.filter(E=>S.words.some(N=>pf(N,E))).length})),A=Math.max(0,...y.map(S=>S.n));if(A===0)return Ci("no_match");g=y.filter(S=>S.n===A).map(S=>S.e);let b=S=>S.words.filter(E=>!Bl(E)&&!a.some(N=>pf(E,N))).length,w=Math.min(...g.map(b));g=g.filter(S=>b(S)===w)}if(f.length&&(g=g.filter(y=>f.some(A=>md(y,A)))),!g.length)return Ci("no_match");if(c!==null){for(let w of m)g=Ul(g,w,p);let y=gf(g,["right",!1],p),A=Math.min(l??1,y.length),b;if(c<0)b=y.slice(y.length-A);else{let w=c*(l!==null?A:1);if(w>=y.length)return Ci("no_match");b=y.slice(w,w+A)}return or(b.map(w=>w[0]),"high","match")}let x=!s&&l===null,v=x?1:o?null:l;if(v!==null&&m.length){for(let b of m.slice(0,-1))g=Ul(g,b,p);let y=gf(g,m[m.length-1],p),A=v;if(y.length<A)return or(y.map(b=>b[0]),"ambiguous","count_mismatch");if(y.length>A&&Math.abs(y[A][1]-y[A-1][1])<=1e-6){let b=y[A-1][1];return or(y.filter(w=>Math.abs(w[1]-b)<=1e-6).map(w=>w[0]),"ambiguous","multiple")}return or(y.slice(0,A).map(b=>b[0]),"high","match")}for(let y of m)g=Ul(g,y,p);return x?g.length===1?or(g,"high","match"):or(g,"ambiguous","multiple"):l!==null&&g.length!==l?or(g,"ambiguous","count_mismatch"):or(g,"high","match")}var bf="make paint color colour turn move rotate scale resize delete remove change set add put give raise lower shrink enlarge hide show swap replace spin flip double halve duplicate copy animate brighten darken".split(" "),as=(e,t)=>{for(let r of t)if(e.startsWith(r))return e.slice(r.length).trim()||null;return null},Gl=(e,t)=>{for(let r of t)if(e.endsWith(r))return e.slice(0,-r.length).trim()||null;return null},Hl=e=>e.replace(/[.!?,]+$/,"");function gd(e){let t=e.split(" ");for(let r=0;r<t.length;r++){let i=t[r].endsWith(","),n=r>0&&(t[r]==="and"||t[r]==="then");if(!(i||n))continue;let a=r+1;for(;a<t.length&&(t[a]==="then"||t[a]==="and");)a++;if(a>=t.length||!bf.includes(t[a]))continue;let s=(n?t.slice(0,r):t.slice(0,r+1)).join(" ").replace(/,+$/,"").trim();if(s)return[s,t.slice(a).join(" ")]}return[e,null]}function xf(e,t){let r=e.split(/\s+/).filter(Boolean);return r.length&&Hl(r[r.length-1]).toLowerCase()==="please"&&r.pop(),Hl(r.slice(Math.max(0,r.length-t)).join(" "))}function ql(e,t,r){let[i,n]=gd(t),a=Gl(i,[" too"," as well"," also"]);if(a!==null&&e==="replace"&&(e="add",i=a),n!==null){let s=n.split(/\s+/).filter(Boolean).length;return{kind:"mixed",mode:e,query:i,instruction:xf(r,s)}}return{kind:"select",mode:e,query:i}}var yd=["please ","ok ","ok, ","okay ","okay, ","now ","now, ","hey ","um ","um, ","uh ","uh, ","so ","so, ","and "],bd=new Set(["clear selection","clear the selection","reset selection","reset the selection","select nothing","select none","deselect","deselect all","deselect everything","unselect","unselect all","unselect everything","clear","clear all"]),xd=["select only ","select just ","only select ","just select ","select ","pick ","choose ","highlight ","grab ","focus on "];function Wl(e){let t=String(e??"").trim(),r=t.toLowerCase().replace(/[\u2018\u2019]/g,"'").split(/\s+/).filter(Boolean).join(" ");for(r=Hl(r);;){let n=r.length;for(let a of yd)r.startsWith(a)&&(r=r.slice(a.length));if(r.endsWith(" please")&&(r=r.slice(0,-7).replace(/,+$/,"")),r.length===n)break}if(r=r.trim(),bd.has(r))return{kind:"clear",mode:"clear"};let i=as(r,["deselect ","unselect ","don't select ","do not select "]);if(i!==null)return ql("remove",i,t);for(let n of["remove ","take "])if(r.startsWith(n)){let a=Gl(r.slice(n.length),[" from the selection"," from selection"," out of the selection"]);if(a!==null)return{kind:"select",mode:"remove",query:a}}if(i=as(r,["also select ","also pick ","also choose ","also add "]),i!==null)return ql("add",i,t);if(r.startsWith("add ")){let n=Gl(r.slice(4),[" to the selection"," to selection"]);if(n!==null)return{kind:"select",mode:"add",query:n}}return i=as(r,xd),i!==null||(i=as(r,["just ","only "]),i!==null&&!bf.includes(i.split(" ")[0]))?ql("replace",i,t):{kind:"edit",instruction:xf(t,1/0)}}var vf=50;function Kl(e){let t=[];for(let r of e){let i=typeof r=="string"?r.slice(0,200):"";if(i&&!t.includes(i)&&t.push(i),t.length>=vf)break}return t}function yr(e){let t=e.__tlSelection??[],r=e.selectedMesh||null;return(t[0]??null)!==r?r?[r]:[]:[...t]}function Ar(e,t,r={}){let i=r.mode??"replace",n=yr(e),a=Kl(typeof t=="string"?[t]:t??[]),s;switch(i){case"clear":s=[];break;case"add":s=Kl([...n,...a]);break;case"remove":s=n.filter(f=>!a.includes(f));break;case"toggle":s=Kl([...n.filter(f=>!a.includes(f)),...a.filter(f=>!n.includes(f))]);break;default:s=a}let o=s.filter(f=>!n.includes(f)),l=n.filter(f=>!s.includes(f));if(!o.length&&!l.length&&s.join(`
403
+ `)===n.join(`
404
+ `))return null;e.__tlSelection=s,e.selectedMesh=s[0]??null,e.viewer?.setSelectedMeshes?.(s);let c={mesh:s[0]??null,meshes:s,added:o,removed:l,source:r.source??"api",...r.query?{query:String(r.query).slice(0,2e3)}:{}};return e.fireEvent?.("three-live-select",c),c}function vd(e){!e||e.__tlSelectionInstalled||(e.__tlSelectionInstalled=!0,"selectedMeshes"in e||Object.defineProperty(e,"selectedMeshes",{get:()=>yr(e),set:t=>{Ar(e,t??[],{mode:"replace",source:"api"})},configurable:!0}),e.addEventListener?.("three-load",()=>{let t=yr(e);t.length>1&&e.viewer?.setSelectedMeshes?.(t)}))}function ss(e){if(!e.length)return"The user cleared the selection.";if(e.length===1)return`The user selected the mesh "${e[0]}". "This" or "it" now refers to it.`;let t=e.slice(0,20).map(i=>`"${i}"`),r=e.length>20?` and ${e.length-20} more`:"";return`The user selected ${e.length} meshes: ${t.join(", ")}${r}. "These", "them", or "it" refer to them.`}var Xl=new WeakMap;function wd(e){let t=e;if(Xl.has(t))return Xl.get(t);let r=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(let a=0;a+2<e.length;a+=3)for(let s=0;s<3;s++){let o=e[a+s];o<r[s]&&(r[s]=o),o>i[s]&&(i[s]=o)}let n=Number.isFinite(r[0])?[r,i]:null;return Xl.set(t,n),n}function Vn(e){let t=e.viewer?.meshes??[],r=[];for(let i of t.slice(0,5e3)){if(!i?.name||i.visible===!1)continue;let n=i.transform,a=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0];for(let l of i.primitives??[]){let c=l.positions?wd(l.positions):null;if(c)for(let f=0;f<8;f++){let m=c[f&1?1:0][0],h=c[f&2?1:0][1],p=c[f&4?1:0][2];for(let g=0;g<3;g++){let x=n?n[g]*m+n[4+g]*h+n[8+g]*p+n[12+g]:[m,h,p][g];x<a[g]&&(a[g]=x),x>s[g]&&(s[g]=x)}}}if(!Number.isFinite(a[0]))continue;let o=i.primitives?.[0]?.baseColor;r.push({name:i.name,min:a,max:s,color:o?[o[0],o[1],o[2]]:null})}return r}function os(e){let t=e.viewer,r=t?.getCameraOrbit?.(),i=t?.getCameraTarget?.();if(!r||!i||![r.theta,r.phi,r.radius,i.x,i.y,i.z].every(Number.isFinite))return nf;let n=r.radius*Math.cos(r.phi);return{eye:[i.x+n*Math.sin(r.theta),i.y+r.radius*Math.sin(r.phi),i.z+n*Math.cos(r.theta)],target:[i.x,i.y,i.z]}}function Yl(e,t,r={}){let i=ns(Vn(e));return Ol(i,t,os(e),r.within??null)}var Md=["You find the objects a user means in a 3D scene.",'Reply with JSON only: {"ids": [numbers], "confidence": "high" or "low", "question": "text"}.',"Use only ids from the objects list.",`Left and right are as seen from the camera: "right" is the camera's right direction.`,'If several objects fit equally, or none fits, set confidence to "low" and ask one short question that names the options.'].join(" "),Xi=e=>Math.round(e*100)/100;function Ql(e,t,r,i=[]){let n=[0,1,2].map(o=>r.target[o]-r.eye[o]),a=Math.hypot(n[2],n[0])||1,s={camera:{eye:r.eye.map(Xi),target:r.target.map(Xi),right:[Xi(-n[2]/a),0,Xi(n[0]/a)]},objects:e.slice(0,300).map(o=>({id:o.id,name:o.name,color:o.colorName,center:o.center.map(Xi),size:Xi(Math.cbrt(o.size))})),selected:i.slice(0,50),request:String(t).slice(0,500)};return[{role:"system",content:Md},{role:"user",content:JSON.stringify(s)}]}function Zl(e,t){let r=String(e??""),i=r.indexOf("{"),n=r.lastIndexOf("}"),a={};if(i>=0&&n>i)try{a=JSON.parse(r.slice(i,n+1))??{}}catch{}let s=[];for(let l of Array.isArray(a.ids)?a.ids:[]){let c=Number.isInteger(l)?t[l]:void 0;c&&!s.includes(c.name)&&s.length<vf&&s.push(c.name)}let o=(typeof a.question=="string"?a.question:"").replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,300);return{names:s,confidence:a.confidence==="high"&&s.length?"high":"low",question:o}}async function Jl(e,t,r,i={}){let n=Vn(e);i.within&&(n=n.filter(o=>i.within.includes(o.name)));let a=ns(n);if(!a.length)return{names:[],confidence:"low",question:""};let s=await r.complete({messages:Ql(a,t,os(e),yr(e)),signal:i.signal});return Zl(s,a)}var _d=32,Sd=32,Ad=80,wf=2e3,ls=32*1024*1024,Td=1024,Pd=256,Nd=2048,eu=["You reconstruct a 3D scene from a reference image into a Three.js script for Three-Live, which compiles it to glTF for Web, Android, and iOS.","Reply with the COMPLETE script in a single ```js code block and nothing else.","Rules:","- Use the pre-defined globals `THREE`, `scene`, and `camera`. No imports, renderer, loaders, DOM, network, or timers.","- Decompose visible objects into `THREE.Group` and `THREE.Mesh` hierarchies with a unique, descriptive `.name` on every Mesh and Group (for example `Table`, `Chair_Left`, `Desk_Lamp`) before attaching `userData.xr` or `userData.interactivity`.","- Use real-world meters (1 unit = 1 m), +Y up, with the floor or resting surface at y = 0 (or the given metric floorY).","- When metric spatial priors (floor height, camera pose, planes, or 3D object boxes) are provided, place meshes at those exact metric [x, y, z] coordinates, dimensions, and yaw angles, and set `mesh.userData.xr = { grab: true }` on movable props.","- Supported: core geometries (`BoxGeometry`, `SphereGeometry`, `CylinderGeometry`, `ConeGeometry`, `CapsuleGeometry`, `PlaneGeometry`, `TorusGeometry`, `LatheGeometry`, `ExtrudeGeometry`, `TubeGeometry`, `Shape`, `Path`), `THREE.CSG`, `MeshStandardMaterial` / `MeshPhysicalMaterial` / `MeshStandardNodeMaterial` (loop-free `THREE.TSL`), `THREE.CanvasTexture`, `THREE.ProceduralTexture` presets (`wood`, `marble`, `brick`, `concrete`, `brushedMetal`, `rust`, `leather`, `fabric`, `carbonFiber`, `checkerboard`, `grid`), lights (`AmbientLight`, `HemisphereLight`, `DirectionalLight`, `PointLight`, `SpotLight`), and canonical `node.userData.xr` traits (`grab`, `anchor`, `physics`, `joint`, `handles`, `dimensions`, `billboard`, `orbit`, `follow`).","- Always include balanced lighting (`AmbientLight` or `HemisphereLight` plus a `DirectionalLight` or `PointLight`) and frame `camera.position.set(x, y, z)` and `camera.lookAt(tx, ty, tz)` so 100% of meshes are inside the camera frustum."].join(`
405
+ `);function Mf(e){if(typeof e!="string")return"";let t="",r=!0;for(let i of e){let n=i.charCodeAt(0);n<=32||n===127||i==='"'||/\s/.test(i)?r||(t+=" ",r=!0):(t+=i,r=!1)}return Array.from(t.trim()).slice(0,Ad).join("")}function ei(e){let t=Math.round(e*100)/100;return(Object.is(t,-0)||Math.abs(t)<1e-9?0:t).toFixed(2)}function _f(e){let t=Math.round(e),r=Object.is(t,-0)?0:t;return String(r)}function Yi(e){if(!Array.isArray(e)||e.length<3)return null;let t=Number(e[0]),r=Number(e[1]),i=Number(e[2]);return!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(i)?null:[t,r,i]}function Cd(e){if(!Array.isArray(e)||e.length<2)return null;let t=Number(e[0]),r=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(r)||t<=0||r<=0?null:[t,r]}function Ed(e){let t=Yi(e);return!t||t[0]<=0||t[1]<=0||t[2]<=0?null:t}function Un(e){return`[${ei(e[0])}, ${ei(e[1])}, ${ei(e[2])}]`}function us(e){if(!e||typeof e!="object")return"";let t=[];if(typeof e.floorY=="number"&&Number.isFinite(e.floorY)&&t.push(`- Floor height: y = ${ei(e.floorY)} m`),e.camera&&typeof e.camera=="object"){let r=Yi(e.camera.eye),i=Yi(e.camera.target);if(r&&i){let n=`- Camera: eye ${Un(r)}, target ${Un(i)}`,a=Number(e.camera.fovDeg);Number.isFinite(a)&&a>=1&&a<=179&&(n+=`, fov ${_f(a)} deg`),t.push(n)}}if(Array.isArray(e.planes)){let r=[];for(let i of e.planes){if(r.length>=_d)break;if(!i||typeof i!="object")continue;let n=Yi(i.center);if(!n)continue;let a=String(i.orientation??"").toLowerCase()==="vertical"?"vertical":"horizontal",s=Mf(i.label),o=Cd(i.extent),l=Yi(i.normal),c=` ${r.length+1}. ${a}`;s&&(c+=` "${s}"`),c+=` at ${Un(n)}`,o&&(c+=`, extent ${ei(o[0])}m x ${ei(o[1])}m`),l&&(c+=`, normal ${Un(l)}`),r.push(c)}r.length>0&&t.push("- Planes:",...r)}if(Array.isArray(e.objects)){let r=[];for(let i of e.objects){if(r.length>=Sd)break;if(!i||typeof i!="object")continue;let n=Mf(i.label),a=Yi(i.center);if(!n||!a)continue;let s=Ed(i.size),o=typeof i.yawDeg=="number"&&Number.isFinite(i.yawDeg)?i.yawDeg:null,l=` ${r.length+1}. "${n}" at ${Un(a)}`;s&&(l+=`, size ${ei(s[0])}m x ${ei(s[1])}m x ${ei(s[2])}m`),o!==null&&(l+=`, yaw ${_f(o)} deg`),r.push(l)}r.length>0&&t.push("- Detected 3D objects (place meshes at these metric bounds):",...r)}return t.length===0?"":`Metric spatial priors (world meters, +Y up):
406
+ ${t.join(`
407
+ `)}
408
+ `}function $r(e){let t=String(e??"").trim();if(!t)return!1;if(/^data:image\/(png|jpeg|jpg|webp);base64,[A-Za-z0-9+/=\s]+$/i.test(t)){let r=t.indexOf(",");return r>0&&t.slice(r+1).trim().length>0}if(/[\s\x00-\x1f\x7f]/.test(t))return!1;try{let r=new URL(t);return r.protocol==="https:"?!!r.hostname:r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname)}catch{return!1}}function tu(e,t){let r=`Reconstruct the 3D scene shown in this reference image as a complete Three-Live script.
409
+ `;r+=us(t);let i=Array.from(String(e??"").trim()).slice(0,wf).join("");return i&&(r+=`Additional instructions: ${i}
410
+ `),r+="Return only the complete script in a single ```js code block.",r}function ru(e,t,r){let i=String(e??"").trim();if(!$r(i))throw new Error("compileFromImage: imageUrl must be a base64 data:image/(png|jpeg|webp) URI or an https:// URL.");let n=tu(t,r);return[{role:"system",content:eu},{role:"user",content:[{type:"image_url",image_url:{url:i}},{type:"text",text:n}]}]}function iu(e,t){let r=String(e??"").trim(),i=(t??[]).map(n=>String(n??"").trim()).filter(Boolean).slice(0,20);if(r){let n=`That script was rejected by the Three-Live sandbox: ${r}
411
+ `;return i.length>0&&(n+=`Additional diagnostics:
412
+ ${i.map(a=>`- ${a}`).join(`
413
+ `)}
414
+ `),n+="Return the complete corrected script in a single ```js code block.",n}return i.length>0?`The script compiled, but the Three-Live linter reported warnings that should be fixed:
415
+ ${i.map(n=>`- ${n}`).join(`
416
+ `)}
417
+ Fix every warning above (assign unique \`.name\` values before attaching \`userData.xr\`, use only canonical \`userData.xr\` traits, replace unsupported classes with supported Three-Live primitives, and frame \`camera.position\` and \`camera.lookAt\` so all meshes are inside the frustum) while keeping the full scene intact.
418
+ Return the complete corrected script in a single \`\`\`js code block.`:"Return the complete corrected script in a single ```js code block."}function nu(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":null}function Ld(e){let t=globalThis;if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64");let r="",i=8192;for(let n=0;n<e.length;n+=i){let a=e.subarray(n,Math.min(n+i,e.length));r+=String.fromCharCode(...a)}return btoa(r)}function Rd(e){let t=Number(e);return Number.isFinite(t)?Math.max(Pd,Math.min(Nd,Math.round(t))):Td}function cs(e){if(e.byteLength===0)throw new Error("compileFromImage: image buffer is empty.");if(e.byteLength>ls)throw new Error("compileFromImage: image exceeds the 32 MB limit.");let t=nu(e);if(!t)throw new Error("compileFromImage: unsupported image format (expected PNG, JPEG, or WebP magic bytes).");return`data:${t};base64,${Ld(e)}`}function Id(e,t,r,i){let n=Math.max(t,r),a=n>i?i/n:1,s=Math.max(1,Math.round(t*a)),o=Math.max(1,Math.round(r*a)),l=e;if(a===1&&typeof l.toDataURL=="function")try{let c=l.toDataURL("image/jpeg",.88);if($r(c))return c}catch{}if(typeof document<"u"&&typeof document.createElement=="function")try{let c=document.createElement("canvas");if(c&&typeof c.getContext=="function"){c.width=s,c.height=o;let f=c.getContext("2d");if(f&&typeof f.drawImage=="function"&&(f.drawImage(e,0,0,s,o),typeof c.toDataURL=="function")){let m=c.toDataURL("image/jpeg",.88);if($r(m))return m}}}catch{}if(typeof l.toDataURL=="function")try{let c=l.toDataURL("image/jpeg",.88);if($r(c))return c}catch{}return null}async function hs(e,t={}){if(t.signal?.aborted)throw t.signal.reason??new Error("compileFromImage aborted");if(e==null)throw new Error("compileFromImage: image input is required.");let r=Rd(t.maxEdge);if(typeof e=="string"){let s=e.trim();if(!s)throw new Error("compileFromImage: image input is empty.");if(/^data:/i.test(s)){if(!$r(s))throw new Error("compileFromImage: data URI must be a base64-encoded image/png, image/jpeg, or image/webp.");let p=s.indexOf(","),g=s.slice(0,p).toLowerCase().replace("image/jpg","image/jpeg"),x=s.slice(p+1).replace(/\s+/g,"");if(Math.floor(x.length*3/4)>ls)throw new Error("compileFromImage: image exceeds the 32 MB limit.");return`${g},${x}`}if(/^(javascript|vbscript|file|ftp|ws|wss):/i.test(s))throw new Error("compileFromImage: unsupported or unsafe image URL scheme.");if(/^http:/i.test(s)&&!$r(s))throw new Error("compileFromImage: remote image URLs must use https:// (or http:// on localhost).");let o=/^https?:/i.test(s)&&$r(s);if(o&&!t.fetch)return s;let l=s;if(!/^https?:|^blob:/i.test(s)){let p=globalThis.location?.href;if(!p)throw new Error("compileFromImage: imageUrl must be a base64 data:image/(png|jpeg|webp) URI or an https:// URL.");if(l=new URL(s,p).href,!/^blob:/i.test(l)&&!$r(l))throw new Error("compileFromImage: resolved image URL must use https:// (or http:// on localhost).")}let c=t.fetch??globalThis.fetch?.bind(globalThis);if(typeof c!="function"){if(o)return s;throw new Error("compileFromImage: no fetch() implementation is available.")}let f=await c(l,{mode:"cors",credentials:"omit",signal:t.signal});if(!f.ok)throw new Error(`compileFromImage: failed to fetch image (HTTP ${f.status}).`);let m=Number(f.headers?.get?.("content-length"));if(Number.isFinite(m)&&m>ls)throw new Error("compileFromImage: image exceeds the 32 MB limit.");let h=await f.arrayBuffer();if(t.signal?.aborted)throw t.signal.reason??new Error("compileFromImage aborted");return cs(new Uint8Array(h))}if(e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]")return cs(new Uint8Array(e));if(ArrayBuffer.isView(e))return cs(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(typeof Blob<"u"&&e instanceof Blob||typeof e.arrayBuffer=="function"){let s=e;if(typeof s.size=="number"&&s.size>ls)throw new Error("compileFromImage: image exceeds the 32 MB limit.");let o=await s.arrayBuffer();if(t.signal?.aborted)throw t.signal.reason??new Error("compileFromImage aborted");return cs(new Uint8Array(o))}let i=e,n=Number(i.videoWidth||i.naturalWidth||i.width||0),a=Number(i.videoHeight||i.naturalHeight||i.height||0);if(n>0&&a>0){let s=Id(e,n,a,r);if(s)return s}if(typeof i.toDataURL=="function"){let s=i.toDataURL("image/jpeg",.88);if($r(s))return s}if(typeof i.src=="string"&&i.src.trim())return hs(i.src,t);throw new Error("compileFromImage: unsupported or unloaded image source.")}async function au(e,t,r={}){if(!e?.allowClientScripts)throw new Error("compileFromImage requires client scripts: add the allow-client-scripts attribute.");let i=Su(e,r,"compileFromImage"),n=Au(e);e.__tlAiAbort?.abort(new Error("compileFromImage superseded by a newer call"));let a=new AbortController;e.__tlAiAbort=a;let s=()=>a.abort(r.signal?.reason);r.signal?.aborted&&s(),r.signal?.addEventListener("abort",s,{once:!0});let o=a.signal,l=Array.from(String(r.prompt??"").trim()).slice(0,wf).join(""),c=us(r.priors).length>0,f=Math.max(0,Math.min(3,Math.floor(Number(r.maxRepairs??1))||0)),m="",h="",p=[],g=0,x=null;try{let y=await hs(t,{maxEdge:r.maxEdge,signal:o,fetch:r.fetch});if(o.aborted)throw o.reason;let A=ru(y,l,r.priors);e.fireEvent?.("three-live-image-start",{prompt:l,hasPriors:c});for(let b=0;b<=f;b++){let w=await i.complete({messages:A,signal:o});if(o.aborted)throw o.reason;if(m=As(w),p=[],!m)h="The model reply did not contain a scene script.";else if(new TextEncoder().encode(m).length>Of)h="The generated script exceeds the 1 MB script limit.";else try{let S=await qf(e,m,o,"compileFromImage");p=[...S.warnings];let E=Hf(S.model);E.unnamedXrNodes>0&&!p.some(N=>N.includes("TL204"))&&p.push("[TL204] Node with userData.xr is missing a unique .name."),E.meshes===0?h="The generated scene contains no meshes.":(h="",x={code:m,warnings:[...p]})}catch(S){if(o.aborted)throw o.reason;let E=S,N=String(E?.message||S);h=E?.name&&E.name!=="Error"&&!N.startsWith(E.name)?`${E.name}: ${N}`:N}if(!h&&p.length===0)break;b<f&&(g++,A.push({role:"assistant",content:w},{role:"user",content:iu(h,p)}))}}finally{r.signal?.removeEventListener("abort",s),e.__tlAiAbort===a&&(e.__tlAiAbort=null)}if(h&&x&&(m=x.code,p=x.warnings,h=""),!h&&!r.dryRun)try{if(await e.executeScript(m),n.trim()){let y=e.__tlAiHistory??(e.__tlAiHistory=[]);y.push(n),y.length>jf&&y.shift()}e.__tlAiSource=m,Ar(e,[],{mode:"clear",source:"api"})}catch(y){h=`The generated scene compiled but failed to load: ${y?.message||String(y)}`,e.__tlAiSource=n,n.trim()&&e.executeScript(n).catch(()=>{})}let v={applied:!h,code:m,repairs:g,warnings:p,...h?{error:h}:{}};return e.fireEvent?.("three-live-image",{prompt:l,...v}),v}var su="three-live-texture-pack",ou=1,Sf=64,Af=6*1024*1024,fs=16*1024*1024,$d=64*1024*1024,lu=" Seamless tileable PBR albedo texture, flat even lighting, orthographic top-down view, no perspective, no shadows, no text.";function Tf(){return We()}function Pf(e){let t=Tf().canonicalTextureSpec;if(typeof t!="function")throw new Error("AI textures need the procedural plugin (three-live-procedural.min.js or a full bundle).");return t(e)}function Dd(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)}catch{return!1}}function ms(e,t){let r=e.replace(/\s+/g,"");if(r.length>Math.ceil(t*4/3)+4)throw new Error("image exceeds the size limit");let i=atob(r),n=new Uint8Array(i.length);for(let a=0;a<i.length;a++)n[a]=i.charCodeAt(a);return n}function kd(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function Fd(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e&&typeof e.arrayBuffer=="function")return new Uint8Array(await e.arrayBuffer());throw new Error("image provider returned no image bytes")}function uu(e){let t=String(e?.endpoint??"");if(!Dd(t))throw new Error("ai-image: endpoint must be an https:// URL (or http:// on localhost).");let r=e.fetch??globalThis.fetch?.bind(globalThis);if(typeof r!="function")throw new Error("ai-image: no fetch() implementation is available.");let i=Math.max(1e3,Number(e.timeoutMs)||12e4),n=new URL(t).origin;return{name:"openai-images",model:e.model,async generateImage({prompt:a,signal:s}){let o=new AbortController,l=()=>o.abort(s?.reason);s?.aborted&&l(),s?.addEventListener("abort",l,{once:!0});let c=setTimeout(()=>o.abort(new Error(`ai-image: timed out after ${i} ms`)),i);try{let f={prompt:a+lu,n:1,size:e.imageSize||"1024x1024"};e.model&&(f.model=e.model),e.responseFormat!==null&&(f.response_format=e.responseFormat??"b64_json");let m=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...e.headers},body:JSON.stringify(f),signal:o.signal}),h=await m.text();if(!m.ok)throw new Error(`ai-image: HTTP ${m.status} from endpoint: ${h.slice(0,300)}`);let p;try{p=JSON.parse(h)}catch{throw new Error("ai-image: endpoint returned non-JSON content.")}let g=p?.data?.[0];if(typeof g?.b64_json=="string")return ms(g.b64_json,fs);let x=typeof g?.url=="string"?g.url:"";if(x.startsWith("data:image/"))return ms(x.slice(x.indexOf(",")+1),fs);if(x){let v=!1;try{v=new URL(x,t).origin===n}catch{}if(!e.allowResponseUrls||!v)throw new Error('ai-image: the endpoint returned an image URL; use response_format "b64_json" (or allowResponseUrls for same-origin URLs).');let y=await r(new URL(x,t).href,{signal:o.signal});if(!y.ok)throw new Error(`ai-image: HTTP ${y.status} fetching the image.`);let A=new Uint8Array(await y.arrayBuffer());if(A.length>fs)throw new Error("ai-image: image exceeds 16 MB.");return A}throw new Error("ai-image: response had no image.")}finally{clearTimeout(c),s?.removeEventListener("abort",l)}}}}function Nf(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"webp":null}var On={async decode(e){let t=Nf(e);if(!t)throw new Error("image must be PNG, JPEG, or WebP");let r=new Blob([e],{type:`image/${t}`}),i=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"}),{width:n,height:a}=i,s=(typeof OffscreenCanvas<"u"?new OffscreenCanvas(n,a):Object.assign(document.createElement("canvas"),{width:n,height:a})).getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("2D canvas unavailable for image decoding");s.drawImage(i,0,0),i.close?.();let o=s.getImageData(0,0,n,a).data;return{width:n,height:a,rgba:new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}},async encodePng(e,t){let r=Tf().encodeRgbaPngDataUri;if(typeof r=="function"){let i=r(e,t,t),n=ms(i.slice(i.indexOf(",")+1),1/0),a=We().makePngDeflater?.(globalThis.CompressionStream);return a?a.png(n):n}throw new Error("PNG encoding needs the procedural plugin")}};function Bd(e,t,r,i,n){let a=new Uint8Array(i*n*4);for(let s=0;s<n;s++){let o=Math.floor(s*r/n),l=Math.min(r,Math.max(o+1,Math.floor((s+1)*r/n)));for(let c=0;c<i;c++){let f=Math.floor(c*t/i),m=Math.min(t,Math.max(f+1,Math.floor((c+1)*t/i))),h=0,p=0,g=0,x=0,v=0;for(let A=o;A<l;A++)for(let b=f;b<m;b++){let w=(A*t+b)*4;h+=e[w],p+=e[w+1],g+=e[w+2],x+=e[w+3],v++}let y=(s*i+c)*4;a[y]=Math.floor((h+v/2)/v),a[y+1]=Math.floor((p+v/2)/v),a[y+2]=Math.floor((g+v/2)/v),a[y+3]=Math.floor((x+v/2)/v)}}return a}function zd(e,t){let r=Math.max(1,Math.floor(t/8)),i=Math.floor(t/2),n=s=>{let o=Math.max(0,Math.min(1,s));return o*o*(3-2*o)},a=new Uint8Array(t*t*4);for(let s=0;s<t;s++){let o=(Math.min(s,t-1-s)+.5)/r;for(let l=0;l<t;l++){let c=(Math.min(l,t-1-l)+.5)/r,f=1-n(Math.min(c,o)),m=(s*t+l)*4,h=((s+i)%t*t+(l+i)%t)*4;for(let p=0;p<3;p++){let g=e[m+p];a[m+p]=Math.max(0,Math.min(255,Math.floor(g+(e[h+p]-g)*f+.5)))}a[m+3]=255}}return a}function cu(e,t){let r=Math.min(e.width,e.height);if(!(r>0))throw new Error("generated image is empty");let i=Math.floor((e.width-r)/2),n=Math.floor((e.height-r)/2),a=new Uint8Array(r*r*4);for(let o=0;o<r;o++){let l=((n+o)*e.width+i)*4;a.set(e.rgba.subarray(l,l+r*4),o*r*4)}let s=r===t?a:Bd(a,r,r,t,t);for(let o=3;o<s.length;o+=4)s[o]=255;return zd(s,t)}async function hu(e,t=On){let r=typeof e=="string"?JSON.parse(e):e;if(!r||r.format!==su)throw new Error(`texture pack: format must be "${su}"`);if(r.version!==ou)throw new Error(`texture pack: version must be ${ou}`);if(!r.entries||typeof r.entries!="object"||Array.isArray(r.entries))throw new Error("texture pack: entries must be an object");let i=Object.keys(r.entries);if(i.length>Sf)throw new Error(`texture pack: more than ${Sf} entries`);let n=new Map;for(let a of i){let s=r.entries[a];if(!/^[0-9a-f]{16}$/.test(a))throw new Error(`texture pack: invalid key '${a}'`);let o=Pf(s?.spec);if(!o)throw new Error(`texture pack: entry ${a}: invalid spec`);if(o.key!==a)throw new Error(`texture pack: entry ${a}: key does not match its spec (${o.key})`);let l=typeof s?.albedo=="string"?s.albedo:"",c="data:image/png;base64,";if(!l.startsWith(c))throw new Error(`texture pack: entry ${a}: albedo must be a data:image/png;base64 URL`);let f=ms(l.slice(c.length),Af);if(f.length>Af||Nf(f)!=="png")throw new Error(`texture pack: entry ${a}: albedo is not a PNG within 6 MB`);let m=await t.decode(f);if(m.width!==o.size||m.height!==o.size)throw new Error(`texture pack: entry ${a}: albedo is ${m.width}x${m.height}, expected ${o.size}x${o.size}`);let h=new Uint8Array(m.rgba);for(let g=3;g<h.length;g+=4)h[g]=255;let p=s.provenance&&typeof s.provenance=="object"?s.provenance:void 0;n.set(a,{key:a,spec:{prompt:o.prompt,size:o.size,seed:o.seed},rgba:h,...p?{provenance:p}:{}})}return n}async function fu(e,t=On){let r={};for(let i of[...e.keys()].sort()){let n=e.get(i),a=await t.encodePng(n.rgba,n.spec.size);r[i]={spec:n.spec,albedo:`data:image/png;base64,${kd(a)}`,...n.provenance?{provenance:n.provenance}:{}}}return{format:su,version:ou,entries:r}}function Vd(e){let t=e?.gltf;if(t)return t;if(e instanceof ArrayBuffer&&e.byteLength>=20){let r=new DataView(e);if(r.getUint32(0,!0)===1179937895)try{return JSON.parse(new TextDecoder().decode(new Uint8Array(e,20,r.getUint32(12,!0))))}catch{}}return null}function ps(e){let t=new Map;for(let r of Vd(e)?.nodes??[]){let i=r?.extras?.xr?.material;if(!i||typeof i!="object"||i.prompt==null)continue;let n=Pf(i);if(!n)continue;let a=t.get(n.key)??{spec:{prompt:n.prompt,size:n.size,seed:n.seed},meshes:[]};typeof r.name=="string"&&r.name&&a.meshes.push(r.name),t.set(n.key,a)}return[...t].map(([r,i])=>({key:r,spec:i.spec,meshes:i.meshes}))}function mu(e=$d){if(typeof indexedDB>"u")return null;let t=null,r=()=>t??(t=new Promise((n,a)=>{let s=indexedDB.open("three-live-textures",1);s.onupgradeneeded=()=>{s.result.createObjectStore("textures",{keyPath:"key"})},s.onsuccess=()=>n(s.result),s.onerror=()=>a(s.error)})),i=(n,a)=>r().then(s=>new Promise((o,l)=>{let c=s.transaction("textures",n),f=a(c.objectStore("textures"));c.oncomplete=()=>o(f?f.result:void 0),c.onerror=()=>l(c.error)}));return{async get(n){try{let a=await i("readonly",s=>s.get(n));return!a||!(a.rgba instanceof Uint8Array)?null:(i("readwrite",s=>s.put({...a,t:Date.now()})).catch(()=>{}),a)}catch{return null}},async put(n){try{await i("readwrite",l=>l.put({...n,t:Date.now()}));let a=await i("readonly",l=>l.getAll())??[],s=a.reduce((l,c)=>l+(c.rgba?.byteLength??0),0);a.sort((l,c)=>l.t-c.t);let o=[];for(let l of a){if(s<=e)break;s-=l.rgba?.byteLength??0,o.push(l.key)}o.length&&await i("readwrite",l=>{for(let c of o)l.delete(c)})}catch{}}}}var jn=null,Cf=!1;function Vr(e){return e.__tlTex??(e.__tlTex={pack:new Map,packJson:null,failed:new Set,inflight:new Map,lastModel:null,lastRun:null,cache:void 0,loadSeq:0})}function Ud(e){let t=e.__tlTex;if(!t||t.pack.size===0)return null;let r={};for(let[i,n]of t.pack)r[i]={size:n.spec.size,rgba:n.rgba};return r}function Od(){let e=We(),t=e.scriptRunner;if(!t||t.__tlTexWrapped)return;let r=i=>jn&&!i?.texturePack?{...i,texturePack:jn}:i;e.scriptRunner={__tlTexWrapped:!0,execute:(i,n,a,s)=>t.execute(i,n,a,r(s)),...typeof t.executeUrl=="function"?{executeUrl:(i,n,a,s)=>t.executeUrl(i,n,a,r(s))}:{}}}function Ef(e,t){Od();let r=jn;jn=Ud(e);try{return t()}finally{jn=r}}function Lf(e,t){let r=t??e.aiImageProvider;if(r&&typeof r.generateImage=="function")return r;let i=e.getAttribute?.("ai-image-endpoint");return i?uu({endpoint:i,model:e.getAttribute?.("ai-image-model")||void 0}):null}function Rf(e){if(e.textureCache!==void 0)return e.textureCache;let t=Vr(e);return t.cache===void 0&&(t.cache=mu()),t.cache}function pu(e){return e.textureCodec??On}function Gn(e){let t=e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent,r=Vr(e).lastRun??(t?{kind:"script",value:t}:null);return r?r.kind==="url"&&typeof e.loadScriptFromSrc=="function"?e.loadScriptFromSrc(r.value):e.executeScript(r.value):Promise.resolve()}function If(e,t){let r=Vr(e);r.pack.set(t.key,t),r.packJson=null,r.failed.delete(t.key)}async function $f(e,t){let r=Rf(e);if(!r)return[];let i=[];for(let n of t){let a=await r.get(n.key);a&&a.spec?.size===n.spec.size&&a.rgba?.length===n.spec.size*n.spec.size*4&&(If(e,{key:n.key,spec:n.spec,rgba:a.rgba,provenance:a.provenance}),e.fireEvent?.("three-live-texture",{key:n.key,meshes:n.meshes,source:"cache"}),i.push(n.key))}return i}async function Df(e,t,r,i){let n=Vr(e),a=n.inflight.get(r.key);if(a)return a;let s=(async()=>{try{let o=await Fd(await t.generateImage({...r.spec,signal:i}));if(o.length>fs)throw new Error("generated image exceeds 16 MB");let l=cu(await pu(e).decode(o),r.spec.size),c={provider:t.name??"custom",...t.model?{model:t.model}:{},createdAt:new Date().toISOString()};return If(e,{key:r.key,spec:r.spec,rgba:l,provenance:c}),Rf(e)?.put({key:r.key,spec:r.spec,rgba:l,provenance:c}),e.fireEvent?.("three-live-texture",{key:r.key,meshes:r.meshes,source:"provider"}),!0}catch(o){return n.failed.add(r.key),e.fireEvent?.("three-live-texture-error",{key:r.key,meshes:r.meshes,error:String(o?.message||o)}),!1}finally{n.inflight.delete(r.key)}})();return n.inflight.set(r.key,s),s}async function jd(e,t,r){let i=0,n=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;)await r(e[i++])});await Promise.all(n)}function kf(e,t){let r=Vr(e);r.lastModel=t;let i;try{i=ps(t).filter(a=>!r.pack.has(a.key))}catch{return}let n=i.filter(a=>!r.failed.has(a.key)&&!r.inflight.has(a.key));n.length&&(async()=>{if((await $f(e,n)).length){await Gn(e).catch(()=>{});return}if((e.getAttribute?.("ai-textures")||"auto").toLowerCase()==="manual")return;let a=Lf(e);if(!a)return;e.fireEvent?.("three-live-texture-start",{keys:n.map(o=>o.key)});let s=(await Promise.all(n.map(o=>Df(e,a,o)))).filter(Boolean).length;s&&(Cf||(Cf=!0,console.info(`[three-live] Generated ${s} AI texture(s) at runtime. Each visitor without a cached copy triggers new (and different) generations. For consistent results, save el.exportTexturePack() and load it via texture-pack.`)),await Gn(e).catch(()=>{}))})()}function Ff(e,t){Vr(e).lastRun=t}async function du(e,t){let r=Vr(e),i=++r.loadSeq;if(t==null){r.pack=new Map,r.packJson=null,await Gn(e).catch(()=>{});return}try{let n=await hu(t,pu(e));if(i!==r.loadSeq)return;r.pack=n,r.packJson=typeof t=="string"?JSON.parse(t):t,r.failed.clear(),await Gn(e).catch(()=>{})}catch(n){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(n?.message||n)})}}async function Bf(e,t){try{let r=typeof document<"u"?document.baseURI:void 0,i=await fetch(new URL(t,r).href,{credentials:"same-origin"});if(!i.ok)throw new Error(`HTTP ${i.status} loading texture-pack "${t}"`);await du(e,await i.json())}catch(r){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(r?.message||r)})}}async function Gd(e,t={}){let r=Vr(e),i=t.meshes?new Set(t.meshes):null,n=ps(r.lastModel).filter(c=>(t.force||!r.pack.has(c.key))&&(!i||c.meshes.some(f=>i.has(f)))),a=[],s=[],o=[],l=n;if(!t.force){let c=new Set(await $f(e,n));a.push(...c),l=n.filter(f=>!c.has(f.key))}if(l.length){let c=Lf(e,t.provider);if(!c)throw new Error("generateTextures: no image provider. Set el.aiImageProvider, or the ai-image-endpoint (and ai-image-model) attributes.");e.fireEvent?.("three-live-texture-start",{keys:l.map(h=>h.key)});let f=Math.max(1,Math.min(4,Math.floor(Number(t.concurrency??2))||2)),m=h=>o.push(h);await jd(l,f,async h=>{r.failed.delete(h.key),t.force&&r.pack.delete(h.key),await Df(e,c,h,t.signal)?s.push(h.key):m({key:h.key,error:"generation failed (see three-live-texture-error)"})})}return(a.length||s.length)&&await Gn(e).catch(()=>{}),{generated:s,cached:a,failed:o,pack:await zf(e)}}async function zf(e){let t=Vr(e);return t.packJson??(t.packJson=await fu(t.pack,pu(e)))}function Hd(e){if(!e||e.__tlTexInstalled)return;e.__tlTexInstalled=!0,Vr(e),Object.defineProperty(e,"texturePack",{get:()=>e.__tlTex?.packJson??null,set:n=>{du(e,n)},configurable:!0}),e.generateTextures=n=>Gd(e,n),e.exportTexturePack=()=>zf(e);let t=e.querySelector?.('script[type="application/three-live-texture-pack"]');t?.textContent?.trim()&&du(e,t.textContent);let r=e.getAttribute?.("texture-pack");r&&Bf(e,r);let i=e;typeof MutationObserver<"u"&&i&&typeof i.nodeType=="number"&&new MutationObserver(()=>{let n=e.getAttribute?.("texture-pack");n&&Bf(e,n)}).observe(i,{attributes:!0,attributeFilter:["texture-pack"]})}var ds=12;function gs(e){return String(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Za-z])([0-9])/g,"$1 $2").replace(/[_\-.]+/g," ").trim().slice(0,60)}function qd(e){if(typeof document>"u")return!1;let t=(e.getAttribute?.("ai-select-chips")??"").toLowerCase();return t!=="off"&&t!=="false"}function ys(e,t,r,i=!1){let n=document.createElement("button");return n.type="button",n.textContent=e,n.setAttribute("aria-label",t),Object.assign(n.style,{border:"none",borderRadius:"14px",padding:"4px 10px",font:"13px system-ui, sans-serif",cursor:"pointer",background:i?"#1a73e8":"rgba(255,255,255,0.92)",color:i?"#fff":"#202124"}),n.addEventListener("click",a=>{a.stopPropagation(),r()}),n}function Hn(e){let t=e.__tlChips;t&&(t.off(),t.root.remove(),e.__tlChips=null)}function gu(e,t,r){if(!qd(e))return null;let i=e.__tlChips;if(!i){let n=document.createElement("div");n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.setAttribute("part","selection-chips"),Object.assign(n.style,{position:"absolute",left:"64px",bottom:"12px",maxWidth:"calc(100% - 76px)",boxSizing:"border-box",display:"flex",flexWrap:"wrap",alignItems:"center",gap:"6px",padding:"6px 8px",borderRadius:"18px",background:"rgba(32,33,36,0.85)",boxShadow:"0 1px 4px rgba(0,0,0,0.3)",zIndex:"10",font:"13px system-ui, sans-serif",color:"#fff",pointerEvents:"auto"});let a=()=>{e.__tlChips&&!e.__tlChips.state.question&&bs(e,e.__tlChips.state,r)};e.addEventListener?.("three-live-select",a),e.appendChild?.(n),i={root:n,off:()=>e.removeEventListener?.("three-live-select",a),state:t},e.__tlChips=i}return bs(e,t,r),i.root}function bs(e,t,r){let i=e.__tlChips;if(!i)return;i.state=t;let n=i.root;n.replaceChildren();let a=s=>{let o=document.createElement("span");o.textContent=s,n.appendChild(o)};if(t.question){a(t.question);for(let s of(t.candidates??[]).slice(0,ds))n.appendChild(ys(gs(s),`Select ${gs(s)}`,()=>{Ar(e,[s],{mode:t.mode==="add"||t.mode==="remove"?t.mode:"replace",source:"tap",query:t.query}),bs(e,{pending:t.pending},r)}))}else{let s=yr(e);if(!s.length&&!t.pending){Hn(e);return}a(s.length?"Selected:":"Nothing selected");for(let o of s.slice(0,ds))n.appendChild(ys(`${gs(o)} \xD7`,`Remove ${gs(o)} from the selection`,()=>Ar(e,[o],{mode:"remove",source:"tap"})));if(s.length>ds&&a(`+${s.length-ds} more`),t.pending&&r&&s.length){let o=t.pending;n.appendChild(ys(`Apply: ${o.slice(0,40)}`,`Apply: ${o.slice(0,200)}`,()=>{bs(e,{},r),r(o)},!0))}}n.appendChild(ys("\u2715","Dismiss",()=>Hn(e)))}var Wd=500,Qi=2e3,Kd=8,Xd=[{name:"edit_scene",description:'Change the 3D scene the user is looking at. Call this whenever the user asks to add, remove, move, resize, recolor, or otherwise modify anything. Pass their request as a clear, self-contained instruction. If they selected a mesh, "this" or "it" refers to that mesh; the tool knows which one.',parameters:{type:"object",properties:{instruction:{type:"string",description:'The requested change, e.g. "make the roof red".'}},required:["instruction"]}},{name:"undo_edit",description:"Undo the last scene change.",parameters:{type:"object",properties:{}}},{name:"select_meshes",description:'Select objects in the scene so the user can see what an edit will change. Call this when the user refers to objects by name, color, or position ("the two red chairs on the left"). Pass their words as query, or exact mesh names as names. The result lists the selection, or a question to ask when the reference was unclear.',parameters:{type:"object",properties:{query:{type:"string",description:`The user's words for the objects, e.g. "the lamp next to the sofa".`},names:{type:"array",items:{type:"string"},description:"Exact mesh names, when known."},mode:{type:"string",enum:["replace","add","remove","clear"],description:"replace (default), add, remove, or clear."}}}}],Yd=["You are a voice assistant inside a live 3D scene editor.","Keep spoken replies short: one sentence.","To change the scene, call edit_scene with the request; never describe code.","After a tool result, say briefly what changed, or why it could not be done.","When the user refers to objects by name, color, or position, call select_meshes with their words first.","If its result has a question, ask it and wait; otherwise say what is selected, and if they also asked for a change, call edit_scene."].join(" ");function Qd(e){try{let t=new URL(e);return t.protocol==="wss:"?!0:t.protocol==="ws:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)}catch{return!1}}function Zd(e){if(!Qd(e))throw new Error("connectVoice: url must be wss:// (or ws:// on localhost).");let t=new WebSocket(e),r=[],i={send(n){let a=JSON.stringify(n);t.readyState===1?t.send(a):t.readyState===0&&r.length<256&&r.push(a)},close(){r.length=0,t.onopen=t.onmessage=t.onclose=null,t.close(),i.onClose?.()}};return t.onopen=()=>{for(let n of r.splice(0))t.send(n)},t.onmessage=async n=>{let a=i.onMessage;try{let s=typeof n.data=="string"?n.data:await n.data.text(),o=JSON.parse(s);o&&typeof o=="object"&&a?.(o)}catch{}},t.onclose=()=>i.onClose?.(),i}function At(e){return typeof e=="string"?e:""}function Tr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function yu(e,t){let r={...e};for(let[i,n]of Object.entries(t??{})){if(i==="__proto__"||i==="constructor"||i==="prototype")continue;let a=r[i];r[i]=n&&typeof n=="object"&&!Array.isArray(n)&&a&&typeof a=="object"&&!Array.isArray(a)?yu(a,n):n}return r}function Vf(e){if(e&&typeof e=="object")return Tr(e);try{return Tr(JSON.parse(At(e)||"{}"))}catch{return{}}}var bu={name:"ai-realtime",inputRate:24e3,setup(e){let t={type:"realtime",instructions:e.instructions,audio:{input:{format:{type:"audio/pcm",rate:24e3},turn_detection:{type:"server_vad"}},output:{format:{type:"audio/pcm",rate:24e3},...e.voice?{voice:e.voice}:{}}},tools:e.tools.map(r=>({type:"function",...r})),tool_choice:"auto",...e.model?{model:e.model}:{}};return[{type:"session.update",session:yu(t,e.overrides)}]},audio(e){return{type:"input_audio_buffer.append",audio:e}},text(e,t){let r=[{type:"conversation.item.create",item:{type:"message",role:t?"user":"system",content:[{type:"input_text",text:e}]}}];return t&&r.push({type:"response.create"}),r},toolResult(e,t,r){return[{type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(r)}},{type:"response.create"}]},parse(e){switch(At(e.type)){case"response.output_audio.delta":case"response.audio.delta":return At(e.delta)?[{type:"audio",base64:At(e.delta),rate:24e3}]:[];case"response.output_audio_transcript.delta":case"response.audio_transcript.delta":return[{type:"transcript",speaker:"model",text:At(e.delta),isFinal:!1}];case"response.output_audio_transcript.done":case"response.audio_transcript.done":return[{type:"transcript",speaker:"model",text:At(e.transcript),isFinal:!0}];case"conversation.item.input_audio_transcription.delta":return[{type:"transcript",speaker:"user",text:At(e.delta),isFinal:!1}];case"conversation.item.input_audio_transcription.completed":return[{type:"transcript",speaker:"user",text:At(e.transcript),isFinal:!0}];case"response.function_call_arguments.done":return[{type:"toolCall",id:At(e.call_id)||At(e.item_id),name:At(e.name),args:Vf(e.arguments)}];case"input_audio_buffer.speech_started":return[{type:"interrupted"}];case"response.done":return[{type:"turnComplete"}];case"error":return[{type:"error",message:At(Tr(e.error).message)||"Realtime server error"}];default:return[]}}},xu={name:"gemini-live",inputRate:16e3,setup(e){let t={...e.model?{model:e.model}:{},generationConfig:{responseModalities:["AUDIO"],...e.voice?{speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice}}}}:{}},systemInstruction:{parts:[{text:e.instructions}]},tools:[{functionDeclarations:e.tools.map(r=>({...r}))}],inputAudioTranscription:{},outputAudioTranscription:{}};return[{setup:yu(t,e.overrides)}]},audio(e){return{realtimeInput:{audio:{mimeType:"audio/pcm;rate=16000",data:e}}}},text(e,t){return[{clientContent:{turns:[{role:"user",parts:[{text:e}]}],turnComplete:t}}]},toolResult(e,t,r){return[{toolResponse:{functionResponses:[{id:e,name:t,response:r}]}}]},parse(e){let t=[],r=Tr(e.serverContent);r.interrupted&&t.push({type:"interrupted"});let i=Tr(r.inputTranscription);At(i.text)&&t.push({type:"transcript",speaker:"user",text:At(i.text),isFinal:!1});let n=Tr(r.outputTranscription);At(n.text)&&t.push({type:"transcript",speaker:"model",text:At(n.text),isFinal:!1});let a=Tr(r.modelTurn).parts;for(let l of Array.isArray(a)?a:[]){let c=Tr(Tr(l).inlineData),f=At(c.mimeType);if(f.startsWith("audio/pcm")&&At(c.data)){let m=Number(/rate=(\d+)/.exec(f)?.[1])||24e3;t.push({type:"audio",base64:At(c.data),rate:m})}}r.turnComplete&&t.push({type:"turnComplete"});let s=Tr(e.toolCall).functionCalls;for(let l of Array.isArray(s)?s:[]){let c=Tr(l);t.push({type:"toolCall",id:At(c.id),name:At(c.name),args:Vf(c.args)})}let o=Tr(e.error);return At(o.message)&&t.push({type:"error",message:At(o.message)}),t}},Jd={"ai-realtime":bu,"gemini-live":xu};function e1(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let i=0;i<t.length;i+=32768)r+=String.fromCharCode(...t.subarray(i,i+32768));return btoa(r)}function t1(e,t,r){let i=t/r,n=Math.max(0,Math.floor(e.length/i)),a=new Int16Array(n);for(let s=0;s<n;s++){let o=s*i,l=Math.floor(o),c=Math.min(l+1,e.length-1),f=e[l]+(e[c]-e[l])*(o-l),m=Math.max(-1,Math.min(1,f));a[s]=m<0?m*32768:m*32767}return a}function r1(e){let t=atob(e),r=t.length>>1,i=new Float32Array(r);for(let n=0;n<r;n++){let a=t.charCodeAt(n*2)|t.charCodeAt(n*2+1)<<8;a&32768&&(a-=65536),i[n]=a/32768}return i}function Uf(){let e=globalThis;return e.AudioContext??e.webkitAudioContext}function i1(){let e=null,t=null,r=null;return{async start(i,n){let a=Uf(),s=globalThis.navigator?.mediaDevices;if(!a||!s?.getUserMedia)throw new Error("connectVoice: microphone capture is not available here.");e=await s.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,channelCount:1}}),t=new a;let o=t.createMediaStreamSource(e);r=t.createScriptProcessor(4096,1,1);let l=t.sampleRate;r.onaudioprocess=c=>{let f=t1(c.inputBuffer.getChannelData(0),l,i);f.length&&n(e1(f))},o.connect(r),r.connect(t.destination)},stop(){r&&(r.onaudioprocess=null),r?.disconnect();for(let i of e?.getTracks()??[])i.stop();t?.close(),r=null,e=null,t=null}}}function n1(){let e=null,t=0,r=new Set,i={play(n,a){let s=Uf();if(!e&&s)try{e=new s}catch{return}if(!e)return;e.state==="suspended"&&e.resume?.();let o=r1(n);if(!o.length)return;let l=e.createBuffer(1,o.length,a);l.getChannelData(0).set(o);let c=e.createBufferSource();c.buffer=l,c.connect(e.destination);let f=Math.max(e.currentTime,t);c.start(f),t=f+l.duration,r.add(c),c.onended=()=>r.delete(c)},flush(){for(let n of r)try{n.stop()}catch{}r.clear(),t=0},close(){i.flush(),e?.close(),e=null}};return i}function Ut(e,t){e.fireEvent?.("three-live-voice",t)}var vu=class{constructor(e,t){this.el=e,this.options=t,this.state="connecting",this.userText="",this.modelText="",this.onSelect=n=>{let a=n.detail;if(a?.source==="voice")return;let s=Array.isArray(a?.meshes)?a.meshes:a?.mesh?[a.mesh]:[];this.sendContext(ss(s))};let r=t.provider??"ai-realtime",i=Jd[r];if(!i)throw new Error(`connectVoice: unknown provider '${r}' (use ai-realtime or gemini-live).`);if(this.adapter=i,t.transport)this.transport=t.transport;else if(t.url)this.transport=Zd(t.url);else throw new Error("connectVoice: pass a wss:// url or a transport.");this.mic=t.microphone===!1?null:t.microphoneSource??i1(),this.sink=t.playAudio===!1?null:t.audioSink??n1()}async start(){this.transport.onMessage=r=>this.handle(r),this.transport.onClose=()=>this.shutdown();let e=[Yd,this.options.instructions].filter(Boolean).join(`
419
+ `);for(let r of this.adapter.setup({instructions:e,tools:Xd,model:this.options.model,voice:this.options.voice,overrides:this.options.session}))this.transport.send(r);this.sink?.play("",24e3),this.el.addEventListener?.("three-live-select",this.onSelect);let t=yr(this.el);t.length&&this.sendContext(ss(t));try{await this.mic?.start(this.adapter.inputRate,r=>{this.state!=="closed"&&this.transport.send(this.adapter.audio(r))})}catch(r){throw this.setState("error",{error:r?.message||String(r)}),this.close(),r}return this.setState("listening"),this}sendText(e){let t=String(e??"").trim().slice(0,Qi);if(!(!t||this.state==="closed"))for(let r of this.adapter.text(t,!0))this.transport.send(r)}close(){this.state!=="closed"&&(this.transport.onClose=void 0,this.transport.close(),this.shutdown())}shutdown(){this.state!=="closed"&&(this.mic?.stop(),this.sink?.close(),this.el.removeEventListener?.("three-live-select",this.onSelect),this.el.__tlVoiceSession===this&&(this.el.__tlVoiceSession=null),this.setState("closed"))}sendContext(e){if(this.state!=="closed")for(let t of this.adapter.text(e,!1))this.transport.send(t)}setState(e,t={}){this.state=e,Ut(this.el,{state:e,...t})}handle(e){if(this.state==="closed")return;let t=0;for(let r of this.adapter.parse(e))switch(r.type){case"audio":this.state!=="editing"&&(this.state="speaking"),this.sink?.play(r.base64,r.rate);break;case"interrupted":this.sink?.flush();break;case"transcript":r.speaker==="user"?(this.userText=(r.isFinal?r.text:this.userText+r.text).slice(-Qi),Ut(this.el,{state:this.state,transcript:this.userText,isFinal:r.isFinal}),r.isFinal&&(this.userText="")):(this.modelText=(r.isFinal?r.text:this.modelText+r.text).slice(-Qi),Ut(this.el,{state:this.state,reply:this.modelText,isFinal:r.isFinal}),r.isFinal&&(this.modelText=""));break;case"turnComplete":this.userText&&(Ut(this.el,{state:this.state,transcript:this.userText,isFinal:!0}),this.userText=""),this.modelText&&(Ut(this.el,{state:this.state,reply:this.modelText,isFinal:!0}),this.modelText=""),(this.state==="speaking"||this.state==="thinking")&&this.setState("listening");break;case"toolCall":++t<=Kd&&this.runTool(r.id,r.name,r.args);break;case"error":Ut(this.el,{state:this.state,error:r.message});break}}async runTool(e,t,r){let i;try{if(t==="edit_scene"){let n=At(r.instruction).trim().slice(0,Qi);if(!n)throw new Error("instruction is empty");if(typeof this.el.editScene!="function")throw new Error("scene editing is not available on this element");this.setState("editing",{transcript:n});let a=await this.el.editScene(n,{provider:this.options.editProvider});i=a.applied?{applied:!0,repairs:a.repairs}:{applied:!1,error:a.error??"edit rejected"},this.setState("thinking",{result:a})}else if(t==="select_meshes"){let n=At(r.mode),a=["replace","add","remove","clear"].includes(n)?n:"replace",s=Array.isArray(r.names)?r.names.filter(l=>typeof l=="string"):[],o=s.length&&a!=="clear"?Mu(this.el,s,a):await qn(this.el,At(r.query),{mode:a,provider:this.options.editProvider??this.el.__tlSelectProvider?.()??null});i={changed:o.applied,selected:o.meshes.slice(0,50),say:o.say,...o.applied?{}:{question:o.say,candidates:o.match?.candidates??[]}}}else t==="undo_edit"?i=await this.el.undoEdit?.()??!1?{undone:!0}:{undone:!1,error:"nothing to undo"}:i={error:`unknown tool ${t}`}}catch(n){i={applied:!1,error:n?.message||String(n)},this.state==="editing"&&this.setState("thinking")}if(this.state!=="closed")for(let n of this.adapter.toolResult(e,t,i))this.transport.send(n)}};async function xs(e,t){if(!t?.editProvider&&!e.aiProvider&&!e.getAttribute?.("ai-endpoint"))throw new Error("connectVoice: edits need a code model. Set el.aiProvider, the ai-endpoint attribute, or options.editProvider.");e.__tlVoiceSession?.close();let r=new vu(e,t??{});return e.__tlVoiceSession=r,Ut(e,{state:"connecting"}),r.start()}function wu(){let e=globalThis,t=e.SpeechRecognition??e.webkitSpeechRecognition;return t?{listen({lang:r,signal:i,onPartial:n}){return new Promise((a,s)=>{let o=new t;o.lang=r||globalThis.document?.documentElement?.lang||"en-US",o.interimResults=!0,o.continuous=!1,o.maxAlternatives=1;let l="",c="",f=!1,m=p=>{f||(f=!0,i?.removeEventListener("abort",h),p())},h=()=>{try{o.abort()}catch{}m(()=>s(i?.reason??new Error("voice edit aborted")))};if(o.onresult=p=>{let g="";for(let x=p.resultIndex;x<p.results.length;x++){let v=p.results[x];v.isFinal?l+=v[0].transcript:g+=v[0].transcript}c=(l+g).trim(),n?.(c)},o.onerror=p=>{p?.error==="no-speech"||p?.error==="aborted"||m(()=>s(new Error(`Speech recognition failed: ${p?.error||"unknown error"}`)))},o.onend=()=>m(()=>a((l||c).trim())),i?.aborted)return h();i?.addEventListener("abort",h,{once:!0});try{o.start()}catch(p){m(()=>s(p))}})}}:null}function vs(e,t){let r=globalThis;if(!(!r.speechSynthesis||!r.SpeechSynthesisUtterance))try{r.speechSynthesis.cancel();let i=new r.SpeechSynthesisUtterance(e);t&&(i.lang=t),r.speechSynthesis.speak(i)}catch{}}function ws(e){return String(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Za-z])([0-9])/g,"$1 $2").replace(/[_\-.]+/g," ").replace(/\s+/g," ").trim()}function Zi(e,t="and"){let r=e.slice(0,5).map(ws),i=e.length-r.length;return i>0?`${r.join(", ")} ${t} ${i} more`:r.length<2?r.join(""):`${r.slice(0,-1).join(", ")} ${t} ${r[r.length-1]}`}function Ji(e,t,r,i){if(e==="clear")return"Selection cleared.";if(!t)return"Which object?";if(t.confidence==="high")return e==="remove"?r.length?`Removed ${Zi(t.names)}. ${r.length} selected.`:`Removed ${Zi(t.names)}. Nothing is selected.`:e==="add"?`Added ${Zi(t.names)}. ${r.length} selected.`:t.names.length===1?`Selected ${ws(t.names[0])}.`:`Selected ${t.names.length}: ${Zi(t.names)}.`;if(t.confidence==="ambiguous")return t.reason==="count_mismatch"?`I found ${t.candidates.length}: ${Zi(t.candidates)}. Which ones?`:`Which one: ${Zi(t.candidates,"or")}?`;let n=String(i).replace(/\s+/g," ").trim().slice(0,80);return t.reason==="relation"?`I can't tell which one "${n}" is yet. Try its name or color, or tap it.`:t.reason==="empty"?"Which object?":`I couldn't find "${n}".`}async function qn(e,t,r={}){let i=r.mode??"replace",n=String(t??"").slice(0,Qi);if(i==="clear")return Ar(e,[],{mode:"clear",source:"voice",query:n||"clear"}),{mode:i,query:n,match:null,applied:!0,tier:1,meshes:[],say:Ji(i,null,[],n)};let a=i==="remove"?yr(e):null;if(a&&!a.length)return{mode:i,query:n,match:null,applied:!1,tier:1,meshes:[],say:"Nothing is selected."};let s=Yl(e,n,{within:a}),o=1,l="",c=r.provider===void 0?e.__tlSelectProvider?.()??null:r.provider;if(c&&n.trim()&&s.confidence==="none"&&(s.reason==="relation"||s.reason==="no_match"))try{let p=await Jl(e,n,c,{within:a,signal:r.signal});o=2,l=p.question,s=p.confidence==="high"?{ids:[],names:p.names,confidence:"high",candidates:[],reason:"model"}:{ids:[],names:[],confidence:p.names.length?"ambiguous":"none",candidates:p.names.slice(0,10),reason:"model"}}catch(p){if(r.signal?.aborted)throw p}let f=!1;s.confidence==="high"&&s.names.length&&(Ar(e,s.names,{mode:i,source:"voice",query:n}),f=!0);let m=yr(e),h=!f&&l?l:Ji(i,s,m,n);return{mode:i,query:n,match:s,applied:f,tier:o,meshes:m,say:h}}function Mu(e,t,r="replace"){let i=new Set(Vn(e).map(l=>l.name)),n=t.filter(l=>typeof l=="string"&&i.has(l)).slice(0,50),a=t.filter(l=>typeof l=="string").join(", ").slice(0,200);if(!n.length){let l={ids:[],names:[],confidence:"none",candidates:[],reason:"no_match"},c=yr(e);return{mode:r,query:a,match:l,applied:!1,tier:1,meshes:c,say:Ji(r,l,c,a)}}Ar(e,n,{mode:r,source:"voice",query:a});let s={ids:[],names:n,confidence:"high",candidates:[],reason:"exact"},o=yr(e);return{mode:r,query:a,match:s,applied:!0,tier:1,meshes:o,say:Ji(r,s,o,a)}}function Ms(e){return e.applied?"Done.":`Sorry, I couldn't apply that: ${String(e.error??"the edit was rejected").replace(/\s+/g," ").slice(0,160)}`}async function a1(e,t,r){if(typeof e.editScene!="function")return;Ut(e,{state:"editing",transcript:t,isFinal:!0});let i;try{i=await e.editScene(t)}catch(n){i={applied:!1,code:"",repairs:0,warnings:[],error:n?.message||String(n)}}Ut(e,{state:"idle",transcript:t,isFinal:!0,result:i}),r.speak!==!1&&vs(Ms(i),r.lang)}async function _s(e,t={}){if(typeof e.editScene!="function")throw new Error("startVoiceEdit needs three-live-ai.min.js (el.editScene).");let r=t.recognizer??wu();if(!r)throw new Error("startVoiceEdit: this browser has no speech recognition; use el.connectVoice() (ai-realtime or gemini-live) instead.");Ut(e,{state:"listening"});let i="";try{i=(await r.listen({lang:t.lang,signal:t.signal,onPartial:l=>Ut(e,{state:"listening",transcript:l,isFinal:!1})})).trim().slice(0,Qi)}catch(l){throw Ut(e,{state:"error",error:l?.message||String(l)}),l}if(!i){let l="I didn't catch that.";throw Ut(e,{state:"idle",transcript:i,isFinal:!0,error:l}),t.speak!==!1&&vs(l,t.lang),new Error(`startVoiceEdit: ${l}`)}let n=i,a,s=t.talkToSelect===!1?null:Wl(i);if(s&&s.kind!=="edit"){Ut(e,{state:"thinking",transcript:i,isFinal:!0});try{a=await qn(e,s.kind==="clear"?"":s.query,{mode:s.mode,signal:t.signal})}catch(m){throw Ut(e,{state:"error",error:m?.message||String(m)}),m}let l=s.kind==="mixed"?s.instruction:void 0,c=l!==void 0&&a.applied&&a.tier===1,f=t.chips!==!1&&!e.__tlVoiceSession;if(f){let m=a;gu(e,m.applied||m.mode==="clear"?{pending:c?void 0:l}:m.match?.candidates.length?{question:m.say,candidates:m.match.candidates,mode:m.mode,query:m.query,pending:l}:{},h=>a1(e,h,t))}if(!c){if(Ut(e,{state:"idle",transcript:i,isFinal:!0,selection:a}),t.speak!==!1){let m=l!==void 0&&a.applied?f&&e.__tlChips?" Tap Apply to make the change.":" Say the change again to apply it.":"";vs(a.say+m,t.lang)}return{transcript:i,result:null,selection:a}}n=l}else t.chips!==!1&&e.__tlChips&&Hn(e);Ut(e,{state:"editing",transcript:i,isFinal:!0,...a?{selection:a}:{}});let o;try{o=await e.editScene(n,{signal:t.signal})}catch(l){o={applied:!1,code:"",repairs:0,warnings:[],error:l?.message||String(l)}}if(Ut(e,{state:"idle",transcript:i,isFinal:!0,result:o,...a?{selection:a}:{}}),t.speak!==!1){let l=Ms(o);vs(a?`${a.say} ${l}`:l,t.lang)}return{transcript:i,result:o,...a?{selection:a}:{}}}function Ss(e,t){if(!t){e.__tlTapHandler&&e.removeEventListener?.("meshclick",e.__tlTapHandler),e.__tlTapDown&&e.removeEventListener?.("pointerdown",e.__tlTapDown),e.__tlTapHandler=null,e.__tlTapDown=null;return}if(e.__tlTapHandler)return;let r=!1,i=0,n=a=>{let s=a;r=!!(s.shiftKey||s.ctrlKey||s.metaKey),i=Date.now()};e.__tlTapDown=n,e.addEventListener?.("pointerdown",n),e.__tlTapHandler=a=>{let s=a.detail?.meshName;if(typeof s!="string"||!s)return;let o=i>0&&Date.now()-i>=Wd,l=yr(e);r||o?Ar(e,[s],{mode:"toggle",source:"tap"}):l.length===1&&l[0]===s?Ar(e,[],{mode:"clear",source:"tap"}):Ar(e,[s],{mode:"replace",source:"tap"}),r=!1,i=0},e.addEventListener?.("meshclick",e.__tlTapHandler)}var s1='<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true" fill="currentColor"><path d="M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3zm5-3a5 5 0 0 1-10 0H5a7 7 0 0 0 6 6.92V21h2v-3.08A7 7 0 0 0 19 11h-2z"/></svg>';function o1(e){if(e.__tlVoiceButton||typeof document>"u")return;let t=e.querySelector?.('[slot="voice-button"]'),r=t??document.createElement("button");t||(r.setAttribute("type","button"),r.setAttribute("aria-label","Edit the scene by voice"),r.innerHTML=s1,Object.assign(r.style,{position:"absolute",left:"12px",bottom:"12px",width:"44px",height:"44px",borderRadius:"22px",border:"none",background:"rgba(32,33,36,0.85)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",zIndex:"10",boxShadow:"0 1px 4px rgba(0,0,0,0.3)"}),e.appendChild?.(r)),e.__tlVoiceButton=r;let i=null,n=a=>{r.setAttribute("aria-pressed",a?"true":"false"),t||(r.style.background=a?"rgba(217,48,37,0.9)":"rgba(32,33,36,0.85)")};r.addEventListener("click",a=>{a.stopPropagation();let s=e.getAttribute?.("ai-voice-url");if(s){if(e.__tlVoiceSession){e.__tlVoiceSession.close(),n(!1);return}n(!0);let o=e.getAttribute?.("ai-voice-provider")||"ai-realtime";xs(e,{provider:o,url:s,model:e.getAttribute?.("ai-voice-model")||void 0}).then(l=>{e.addEventListener?.("three-live-voice",function c(f){f.detail?.state==="closed"&&(e.removeEventListener?.("three-live-voice",c),e.__tlVoiceSession!==l&&n(!1))})}).catch(()=>n(!1));return}if(i){i.abort(new Error("voice edit cancelled"));return}i=new AbortController,n(!0),_s(e,{signal:i.signal}).catch(()=>{}).finally(()=>{i=null,n(!1)})})}var Of=1048576,jf=20,Gf=15e3,l1=["You edit Three.js scene scripts for Three-Live, which compiles them to glTF for Web, Android, and iOS.","Reply with the COMPLETE updated script in a single ```js code block and nothing else.","Rules:","- Use the pre-defined globals `THREE`, `scene`, and `camera`. No imports, renderer, loaders, DOM, network, or timers.","- Change only what the instruction asks; keep every other object, name, and value as it is.","- Give new meshes and groups descriptive `.name` values; keep existing names stable.","- Keep objects resting on y = 0 and within view of the camera.","- Supported: core geometries and materials (MeshStandardMaterial / MeshPhysicalMaterial with PBR maps, and MeshStandardNodeMaterial with loop-free THREE.TSL colorNode / emissiveNode / roughnessNode / metalnessNode / opacityNode / bumpNode / positionNode), lights, Group, InstancedMesh, THREE.CSG, THREE.CanvasTexture, THREE.ProceduralTexture presets (wood, marble, brick, concrete, brushedMetal, rust, leather, fabric, carbonFiber, checkerboard, grid), and declarative mesh.userData.xr traits. Optional per-frame motion: function animate(t) { ... }.","- Keep every userData.xr.material preset; add a prompt (AI texture) only when the instruction asks for a specific surface."].join(`
420
+ `);function u1(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)}catch{return!1}}function _u(e){let t=String(e?.endpoint??"");if(!u1(t))throw new Error("ai-chat: endpoint must be an https:// URL (or http:// on localhost).");let r=e.fetch??globalThis.fetch?.bind(globalThis);if(typeof r!="function")throw new Error("ai-chat: no fetch() implementation is available.");let i=Number.isFinite(e.temperature)?Number(e.temperature):.2,n=Math.max(1e3,Number(e.timeoutMs)||12e4);return{async complete({messages:a,signal:s}){let o=new AbortController,l=()=>o.abort(s?.reason);s?.aborted&&l(),s?.addEventListener("abort",l,{once:!0});let c=setTimeout(()=>o.abort(new Error(`ai-chat: timed out after ${n} ms`)),n);try{let f={messages:a,temperature:i,stream:!1};e.model&&(f.model=e.model);let m=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...e.headers},body:JSON.stringify(f),signal:o.signal}),h=await m.text();if(!m.ok)throw new Error(`ai-chat: HTTP ${m.status} from endpoint: ${h.slice(0,300)}`);let p;try{p=JSON.parse(h)}catch{throw new Error("ai-chat: endpoint returned non-JSON content.")}let g=p?.choices?.[0]?.message?.content,x=Array.isArray(g)?g.map(v=>typeof v=="string"?v:String(v?.text??"")).join(""):g;if(typeof x!="string"||!x.trim())throw new Error("ai-chat: response had no message content.");return x}finally{clearTimeout(c),s?.removeEventListener("abort",l)}}}}function As(e){let t=String(e??""),r=/```[ \t]*([A-Za-z0-9_+-]*)[^\n]*\n([\s\S]*?)```/g,i,n="";for(;i=r.exec(t);){let s=i[1].toLowerCase();if(n||(n=i[2]),["js","javascript","ts","typescript","mjs"].includes(s))return i[2].trim()}if(n)return n.trim();let a=/```[^\n]*\n([\s\S]*)$/.exec(t);return a?a[1].trim():/\bscene\b/.test(t)?t.trim():""}function Hf(e){let t=new Set,r=e?.gltf;if(!r&&e instanceof ArrayBuffer&&e.byteLength>=20){let a=new DataView(e);if(a.getUint32(0,!0)===1179937895){let s=a.getUint32(12,!0);try{r=JSON.parse(new TextDecoder().decode(new Uint8Array(e,20,s)))}catch{}}}let i=0,n=0;for(let a of r?.nodes??[]){let s=typeof a?.name=="string"?a.name.trim():"",o=/^Node_\d+$/.test(s),l=s.length>0&&!o;l&&t.add(s),a?.mesh!==void 0&&i++,!l&&(a?.extras?.xr!=null||a?.extras?.interactivity!=null)&&n++}return{meshNames:t,meshes:i,unnamedXrNodes:n}}function qf(e,t,r,i="editScene"){let n=We().scriptRunner;if(!n||typeof n.execute!="function")return Promise.reject(new Error(`${i} needs a script runner (load three-live.min.js or three-live-full.min.js).`));let a=[];return new Promise((s,o)=>{let l,c=!1,f=p=>{if(!c){c=!0,clearTimeout(h),r?.removeEventListener("abort",m);try{l?.terminate?.()}catch{}p()}},m=()=>f(()=>o(r?.reason??new Error("editScene aborted"))),h=setTimeout(()=>f(()=>o(new Error(`Scene did not finish compiling within ${Gf} ms.`))),Gf);if(r?.aborted)return m();r?.addEventListener("abort",m,{once:!0}),Promise.resolve(n.execute(t,e.sandbox??"worker",{onModelReady:p=>f(()=>s({model:p,warnings:a})),onError:p=>f(()=>o(p instanceof Error?p:new Error(String(p)))),onToast:p=>{a.length<20&&a.push(String(p))}},{allowClientScripts:!0})).then(p=>{if(l=p,c)try{p?.terminate?.()}catch{}},p=>f(()=>o(p instanceof Error?p:new Error(String(p)))))})}var c1=50;function h1(e){let t=typeof e=="string"?[e]:Array.isArray(e)?e:[],r=[];for(let i of t){let n=typeof i=="string"?i.slice(0,200):"";if(n&&!r.includes(n)&&r.push(n),r.length>=c1)break}return r}function f1(e){return e.length===0?"":e.length===1?`The user selected the mesh named "${e[0]}"; the instruction refers to it.
421
+ `:`The user selected the meshes named ${e.map(t=>`"${t}"`).join(", ")}; the instruction refers to them.
422
+ `}function Su(e,t,r="editScene"){let i=t.provider??e.aiProvider;if(i&&typeof i.complete=="function")return i;let n=e.getAttribute?.("ai-endpoint");if(!n)throw new Error(`${r}: no AI provider. Set el.aiProvider, or the ai-endpoint (and ai-model) attributes.`);let a=(e.getAttribute?.("ai-provider")||"ai-chat").toLowerCase();if(a!=="ai-chat")throw new Error(`${r}: unknown ai-provider '${a}' (supported: ai-chat, or set el.aiProvider).`);return _u({endpoint:n,model:e.getAttribute?.("ai-model")||void 0})}function Au(e){return typeof e.__tlAiSource=="string"?e.__tlAiSource:e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent??""}async function Tu(e,t,r={}){let i=String(t??"").trim();if(!i)throw new Error("editScene: instruction is empty.");if(!e?.allowClientScripts)throw new Error("editScene requires client scripts: add the allow-client-scripts attribute.");let n=r.source??Au(e);if(!n.trim())throw new Error('editScene needs a Three.js scene script (inline <script type="text/three"> or a prior editScene/executeScript).');let a=Su(e,r);e.__tlAiAbort?.abort(new Error("editScene superseded by a newer call"));let s=new AbortController;e.__tlAiAbort=s;let o=()=>s.abort(r.signal?.reason);r.signal?.aborted&&o(),r.signal?.addEventListener("abort",o,{once:!0});let l=s.signal,c=h1(r.selection===void 0?e.selectedMeshes??e.selectedMesh:r.selection),f=c.length>1?c:c[0]??null,m=Math.max(0,Math.min(3,Math.floor(Number(r.maxRepairs??1))||0)),h=[{role:"system",content:l1},{role:"user",content:`Current scene script:
423
+ \`\`\`js
424
+ ${n}
425
+ \`\`\`
426
+ `+f1(c)+`Instruction: ${i}`}];e.fireEvent?.("three-live-edit-start",{instruction:i,selection:f});let p="",g="",x=[],v=0;try{for(let A=0;A<=m;A++){let b=await a.complete({messages:h,signal:l});if(l.aborted)throw l.reason;if(p=As(b),!p)g="The model reply did not contain a scene script.";else if(new TextEncoder().encode(p).length>Of)g="The generated script exceeds the 1 MB script limit.";else try{let w=await qf(e,p,l);x=w.warnings;let S=Hf(w.model);if(S.meshes===0)g="The edited scene contains no meshes.";else if(c.some(E=>!S.meshNames.has(E))&&!/\b(remove|delete|rename)\b/i.test(i)){let E=c.filter(N=>!S.meshNames.has(N));g=E.length===1?`The edited scene no longer contains the selected mesh "${E[0]}".`:`The edited scene no longer contains the selected meshes ${E.map(N=>`"${N}"`).join(", ")}.`}else g=""}catch(w){if(l.aborted)throw l.reason;let S=w,E=String(S?.message||w);g=S?.name&&S.name!=="Error"&&!E.startsWith(S.name)?`${S.name}: ${E}`:E}if(!g)break;A<m&&(v++,h.push({role:"assistant",content:b},{role:"user",content:`That script was rejected by the Three-Live sandbox: ${g}
427
+ Return the complete corrected script in a single \`\`\`js code block.`}))}}finally{r.signal?.removeEventListener("abort",o),e.__tlAiAbort===s&&(e.__tlAiAbort=null)}if(!g&&!r.dryRun)try{await e.executeScript(p);let A=e.__tlAiHistory??(e.__tlAiHistory=[]);A.push(n),A.length>jf&&A.shift(),e.__tlAiSource=p}catch(A){g=`The edit compiled but failed to load: ${A?.message||String(A)}`,e.__tlAiSource=n,e.executeScript(n).catch(()=>{})}let y={applied:!g,code:p,repairs:v,warnings:x,...g?{error:g}:{}};return e.fireEvent?.("three-live-edit",{instruction:i,...y}),y}async function Pu(e){let t=e?.__tlAiHistory?.pop();return typeof t!="string"?!1:(e.__tlAiSource=t,await e.executeScript(t),!0)}var Ts={name:"ai",onRegister(){typeof document>"u"||document.querySelectorAll?.("three-live, xr-live").forEach(e=>Ts.onElementConnected?.(e))},onElementConnected(e){let t=e;if(!t||t.__tlAiInstalled)return;t.__tlAiInstalled=!0,t.editScene=(s,o)=>Tu(t,s,o),t.compileFromImage=(s,o)=>au(t,s,o),t.undoEdit=()=>Pu(t),vd(t);let r=t;t.startVoiceEdit=s=>_s(r,s),r.__tlSelectProvider=()=>{try{return Su(t,{})}catch{return null}},t.selectByVoice=(s,o)=>qn(r,s,o),t.connectVoice=s=>xs(r,s),t.setSelectOnTap=s=>Ss(r,s),t.hasAttribute?.("ai-select-on-tap")&&Ss(r,!0),t.hasAttribute?.("ai-voice-button")&&o1(r),"sceneSource"in t||Object.defineProperty(t,"sceneSource",{get:()=>Au(t),configurable:!0});let i=t;Hd(i);let n=t.executeScript;typeof n=="function"&&(t.executeScript=s=>(Ff(i,{kind:"script",value:String(s)}),Ef(i,()=>n.call(t,s)).then(o=>(t.__tlAiSource=String(s),kf(i,o),o))));let a=i.loadScriptFromSrc;typeof a=="function"&&(i.loadScriptFromSrc=s=>(Ff(i,{kind:"url",value:String(s)}),Ef(i,()=>a.call(t,s)).then(o=>(kf(i,o),o))))}};Rt(Ts);function Wf(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function Nu(e,t,r,i){let n=t[0],a=t[1],s=t[2],o=t[3],l=r[0],c=r[1],f=r[2],m=r[3],h=n*l+a*c+s*f+o*m;if(h<0&&(l=-l,c=-c,f=-f,m=-m,h=-h),Math.abs(h)>=1)return e[0]=n,e[1]=a,e[2]=s,e[3]=o,e;let p=Math.acos(h),g=Math.sqrt(1-h*h);if(Math.abs(g)<.001)return e[0]=.5*(n+l),e[1]=.5*(a+c),e[2]=.5*(s+f),e[3]=.5*(o+m),e;let x=Math.sin((1-i)*p)/g,v=Math.sin(i*p)/g;return e[0]=n*x+l*v,e[1]=a*x+c*v,e[2]=s*x+f*v,e[3]=o*x+m*v,e}function Kf(e,t,r,i){return e[0]=t[0]+i*(r[0]-t[0]),e[1]=t[1]+i*(r[1]-t[1]),e[2]=t[2]+i*(r[2]-t[2]),e}function Cu(e,t){if(!Array.isArray(e?.animations))return[];let r=[];for(let i=0;i<e.animations.length;i++){let n=e.animations[i],a=n.name||`Animation_${i}`,s=[],o=0;if(Array.isArray(n.channels)&&Array.isArray(n.samplers))for(let l of n.channels){if(!l.target||l.target.node===void 0||!l.target.path)continue;let c=n.samplers[l.sampler];if(!c)continue;let f=e.accessors?.[c.input],m=e.accessors?.[c.output];if(!f||!m)continue;let h=e.bufferViews?.[f.bufferView],p=e.bufferViews?.[m.bufferView];if(!h||!p)continue;let g=(h.byteOffset||0)+(f.byteOffset||0),x=(p.byteOffset||0)+(m.byteOffset||0),v=Fi(e,t,f,1)??Wf(t,g,f.count);v.length>0&&v[v.length-1]>o&&(o=v[v.length-1]);let y=l.target.path==="rotation"?4:l.target.path==="weights"?Math.max(1,Math.round(m.count/Math.max(1,f.count))):3,A=l.target.path==="weights"?1:y,b=Fi(e,t,m,A)??Wf(t,x,m.count*A),w=c.interpolation==="STEP"?"STEP":"LINEAR";s.push({nodeIndex:l.target.node,path:l.target.path,times:v,values:b,interpolation:w})}s.length>0&&r.push({name:a,duration:o,channels:s})}return r}function en(e,t,r){let{times:i,values:n,path:a,interpolation:s}=e,o=i.length;if(o===0)return;let l=a==="rotation"?4:a==="weights"?Math.max(1,Math.round(n.length/o)):3;if(t<=i[0]){for(let A=0;A<l;A++)r[A]=n[A];return}if(t>=i[o-1]){let A=(o-1)*l;for(let b=0;b<l;b++)r[b]=n[A+b];return}let c=0,f=o-1;for(;c<=f;){let A=c+f>>1;i[A]<=t?c=A+1:f=A-1}let m=Math.max(0,f),h=Math.min(o-1,m+1);if(s==="STEP"||m===h){let A=m*l;for(let b=0;b<l;b++)r[b]=n[A+b];return}let p=i[m],g=i[h],x=(t-p)/Math.max(1e-5,g-p),v=m*l,y=h*l;if(a==="rotation"){let A=[n[v],n[v+1],n[v+2],n[v+3]],b=[n[y],n[y+1],n[y+2],n[y+3]];Nu(r,A,b,x)}else for(let A=0;A<l;A++)r[A]=n[v+A]+x*(n[y+A]-n[v+A])}var Wn=new WeakMap;function Eu(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(o=>o.name===t);if(!i)return;let n=Wn.get(e);n||(n=[],e.currentClip&&n.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),Wn.set(e,n));let a=r>0?1/r:1e3;for(let o of n)o.clip.name!==t&&(o.fadeSpeed=-a);let s=n.find(o=>o.clip.name===t);s?s.fadeSpeed=a:n.push({clip:i,time:0,weight:r>0?0:1,fadeSpeed:a}),e.currentClip=i,e.isPlayingAnimation=!0}function Lu(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=Wn.get(e);if(!r||r.length===0){if(!e.currentClip)return;r=[{clip:e.currentClip,time:t,weight:1,fadeSpeed:0}]}let i=e.gltf.nodes.length,n=[];for(let m=0;m<i;m++){let h=e.initialNodeTransforms[m];h?n.push({t:[h.t[0],h.t[1],h.t[2]],r:[h.r[0],h.r[1],h.r[2],h.r[3]],s:[h.s[0],h.s[1],h.s[2]]}):n.push({t:[0,0,0],r:[0,0,0,1],s:[1,1,1]})}let a=[0,0,0],s=[0,0,0,1],o=[1,1,1],l=new Float32Array(64);for(let m of r){let h=Math.max(0,Math.min(1,m.weight));if(!(h<=1e-4))for(let p of m.clip.channels){if(p.nodeIndex<0||p.nodeIndex>=i)continue;let g=n[p.nodeIndex];if(p.path==="translation")en(p,m.time,a),Kf(g.t,g.t,a,h);else if(p.path==="rotation")en(p,m.time,s),Nu(g.r,g.r,s,h);else if(p.path==="scale")en(p,m.time,o),Kf(g.s,g.s,o,h);else if(p.path==="weights"&&(en(p,m.time,l),e.meshes)){for(let x of e.meshes)if(x.nodeIndex===p.nodeIndex){for(let v of x.primitives)if(v.pluginData?.morph?.weights){let y=v.pluginData.morph.weights,A=v.pluginData.morph.numTargets||y.length;for(let b=0;b<A;b++)y[b]=y[b]*(1-h)+l[b]*h}}}}}let c=[];for(let m=0;m<i;m++){let h=lt(),{t:p,r:g,s:x}=n[m];Sn(h,g,p,x),c.push(h)}let f=An(e.gltf,c);e.worldMatrices=f;for(let m of e.meshes)m.nodeIndex>=0&&m.nodeIndex<f.length&&(m.transform.set(f[m.nodeIndex]),rr(m.normalMatrix,m.transform))}var Ru=e=>{Wn.delete(e)},Iu={name:"keyframes",evaluateAnimation:Lu,crossFadeTo:Eu,onParseGLB(e){(e.animationsParsed===!1||!e.animations)&&(e.animations=Cu(e.gltf,e.bin),e.animationsParsed=!0)},onLoadModel:Ru,onClearScene:Ru,onDestroy:(e,t)=>Ru(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=Wn.get(e);if(r&&r.length>0){for(let i=r.length-1;i>=0;i--){let n=r[i];if(n.time+=t,n.clip.duration>0&&(n.time%=n.clip.duration),n.fadeSpeed!==0)if(n.weight+=n.fadeSpeed*t,n.weight<=0){r.splice(i,1);continue}else n.weight>=1&&(n.weight=1,n.fadeSpeed=0)}r.length>0&&(e.animationTime=r[r.length-1].time),Lu(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),Lu(e,e.animationTime))}},Kn=64;function Xf(e,t,r){if(!(!e?.meshes||t<0||t>=Kn))for(let i of e.meshes)for(let n of i.primitives){let a=n.pluginData?.morph;a?.weights&&(a.weights[t]=r)}}var $u={name:"morph",onResolveShader(e,t,r,i){if(!Array.isArray(e?.targets)||e.targets.length===0)return null;let n=r.replace("uniform mat4 uMVP,uModel;",`uniform mat4 uMVP,uModel;
380
428
  uniform sampler2D uMorphDeltasTex;
381
- uniform float uMorphWeights[${Mr}];
429
+ uniform float uMorphWeights[${Kn}];
382
430
  uniform int uNumMorphTargets;`);return n=n.replace("vec4 world=uModel*vec4(aPosition,1.0);",`vec3 morphedPos = aPosition;
383
- for (int m = 0; m < ${Mr}; m++) {
431
+ for (int m = 0; m < ${Kn}; m++) {
384
432
  if (m >= uNumMorphTargets) break;
385
433
  float w = uMorphWeights[m];
386
434
  if (abs(w) > 0.0001) {
387
435
  morphedPos += texelFetch(uMorphDeltasTex, ivec2(gl_VertexID, m), 0).xyz * w;
388
436
  }
389
437
  }
390
- vec4 world=uModel*vec4(morphedPos,1.0);`).replace("gl_Position=uMVP*vec4(aPosition,1.0);","gl_Position=uMVP*vec4(morphedPos,1.0);"),{vs:n,fs:i}},onBuildPrimitiveVAO(e,t,r,i,n){let s=r?.targets;if(!Array.isArray(s)||s.length===0)return null;let l=r.attributes?.POSITION,o=i?.accessors?.[l];if(!o)return null;let a=o.count,u=Math.min(s.length,Mr),h=new Float32Array(a*u*4);for(let d=0;d<u;d++){let f=s[d].POSITION;if(f===void 0)continue;let g=i.accessors?.[f],x=i.bufferViews?.[g?.bufferView];if(!g||!x)continue;let b=jt(i,n,g,3);if(!b||b.length<a*3)continue;let v=d*a*4;for(let p=0;p<a;p++)h[v+p*4]=b[p*3],h[v+p*4+1]=b[p*3+1],h[v+p*4+2]=b[p*3+2],h[v+p*4+3]=0}let m=e.createTexture();e.bindTexture(3553,m),e.texImage2D(3553,0,34836,a,u,0,6408,5126,h),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728);let c=new Float32Array(Mr);return{hasMorph:!0,morphTex:m,numTargets:u,vertexCount:a,weights:c}},onBeforeDrawPrimitive(e,t,r,i,n,s){let l=r.pluginData?.morph;if(!l?.hasMorph||!l.morphTex)return;e.activeTexture(33989),e.bindTexture(3553,l.morphTex);let o=e.getUniformLocation(t,"uMorphDeltasTex");o&&e.uniform1i(o,5);let a=e.getUniformLocation(t,"uNumMorphTargets");a&&e.uniform1i(a,l.numTargets);let u=e.getUniformLocation(t,"uMorphWeights[0]");u&&e.uniform1fv(u,l.weights)}},ts=64,rs={name:"skinning",onResolveShader(e,t,r,i){if(e?.attributes?.JOINTS_0===void 0||e?.attributes?.WEIGHTS_0===void 0)return null;let n=r.replace("layout(location=2) in vec2 aUV;",`layout(location=2) in vec2 aUV;
438
+ vec4 world=uModel*vec4(morphedPos,1.0);`).replace("gl_Position=uMVP*vec4(aPosition,1.0);","gl_Position=uMVP*vec4(morphedPos,1.0);"),{vs:n,fs:i}},onBuildPrimitiveVAO(e,t,r,i,n){let a=r?.targets;if(!Array.isArray(a)||a.length===0)return null;let s=r.attributes?.POSITION,o=i?.accessors?.[s];if(!o)return null;let l=o.count,c=Math.min(a.length,Kn),f=new Float32Array(l*c*4);for(let p=0;p<c;p++){let g=a[p].POSITION;if(g===void 0)continue;let x=i.accessors?.[g],v=i.bufferViews?.[x?.bufferView];if(!x||!v)continue;let y=Fi(i,n,x,3);if(!y||y.length<l*3)continue;let A=p*l*4;for(let b=0;b<l;b++)f[A+b*4]=y[b*3],f[A+b*4+1]=y[b*3+1],f[A+b*4+2]=y[b*3+2],f[A+b*4+3]=0}let m=e.createTexture();e.bindTexture(3553,m),e.texImage2D(3553,0,34836,l,c,0,6408,5126,f),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728);let h=new Float32Array(Kn);return{hasMorph:!0,morphTex:m,numTargets:c,vertexCount:l,weights:h}},onBeforeDrawPrimitive(e,t,r,i,n,a){let s=r.pluginData?.morph;if(!s?.hasMorph||!s.morphTex)return;e.activeTexture(33989),e.bindTexture(3553,s.morphTex);let o=e.getUniformLocation(t,"uMorphDeltasTex");o&&e.uniform1i(o,5);let l=e.getUniformLocation(t,"uNumMorphTargets");l&&e.uniform1i(l,s.numTargets);let c=e.getUniformLocation(t,"uMorphWeights[0]");c&&e.uniform1fv(c,s.weights)}},Du=64,ku={name:"skinning",onResolveShader(e,t,r,i){if(e?.attributes?.JOINTS_0===void 0||e?.attributes?.WEIGHTS_0===void 0)return null;let n=r.replace("layout(location=2) in vec2 aUV;",`layout(location=2) in vec2 aUV;
391
439
  layout(location=4) in uvec4 aJoints;
392
440
  layout(location=5) in vec4 aWeights;
393
- uniform mat4 uJointMatrix[${ts}];`),s=n.includes("morphedPos")?"morphedPos":"aPosition";return n=n.replace(`vec4 world=uModel*vec4(${s},1.0);`,`mat4 skinMatrix =
441
+ uniform mat4 uJointMatrix[${Du}];`),a=n.includes("morphedPos")?"morphedPos":"aPosition";return n=n.replace(`vec4 world=uModel*vec4(${a},1.0);`,`mat4 skinMatrix =
394
442
  aWeights.x * uJointMatrix[int(aJoints.x)] +
395
443
  aWeights.y * uJointMatrix[int(aJoints.y)] +
396
444
  aWeights.z * uJointMatrix[int(aJoints.z)] +
397
445
  aWeights.w * uJointMatrix[int(aJoints.w)];
398
- vec4 world=uModel*(skinMatrix*vec4(${s},1.0));`).replace(`gl_Position=uMVP*vec4(${s},1.0);`,`gl_Position=uMVP*(skinMatrix*vec4(${s},1.0));`),{vs:n,fs:i}},onBuildPrimitiveVAO(e,t,r,i,n){let s=r?.attributes;if(!s||s.JOINTS_0===void 0||s.WEIGHTS_0===void 0)return null;let l=i.accessors[s.JOINTS_0],o=i.accessors[s.WEIGHTS_0];if(!l||!o)return null;let a=i.bufferViews[l.bufferView],u=i.bufferViews[o.bufferView];if(!a||!u)return null;let h=(a.byteOffset||0)+(l.byteOffset||0),m=(u.byteOffset||0)+(o.byteOffset||0),c=e.createBuffer();e.bindBuffer(34962,c);let d=l.componentType===5121?5121:5123,f=d===5121?new Uint8Array(n,h,l.count*4):new Uint16Array(n,h,l.count*4);e.bufferData(34962,f,35044),e.enableVertexAttribArray(4),e.vertexAttribIPointer(4,4,d,0,0);let g=e.createBuffer();e.bindBuffer(34962,g);let x=jt(i,n,o,4)??new Float32Array(n,m,o.count*4);return e.bufferData(34962,x,35044),e.enableVertexAttribArray(5),e.vertexAttribPointer(5,4,5126,!1,0,0),{hasSkin:!0,buffers:[c,g]}},onBeforeDrawPrimitive(e,t,r,i,n,s){if(!r.pluginData?.skinning?.hasSkin)return;let l=s?.nodes?.[i.nodeIndex]?.skin;if(l===void 0||!s.skins||!s.skins[l])return;let o=s.skins[l].joints||[],a=new Float32Array(ts*16);for(let h=0;h<o.length&&h<ts;h++){let m=o[h],c=n[m]||Pe();a.subarray(h*16,(h+1)*16).set(c)}let u=e.getUniformLocation(t,"uJointMatrix[0]");u&&e.uniformMatrix4fv(u,!1,a)}};je(es),je(Jn),je(rs),je(Oi),je(Ci);var Ul=`#version 300 es
399
- layout(location=0) in vec3 aPosition;layout(location=1) in vec2 aUV;uniform mat4 uMVP;out vec2 vUV;void main(){vUV=aUV;gl_Position=uMVP*vec4(aPosition,1.);}`,Bl=`#version 300 es
400
- precision highp float;in vec2 vUV;uniform float uShadowIntensity,uShadowSoftness;out vec4 fragColor;void main(){vec2 p=(vUV-.5)*2.;float d=clamp(length(p),0.,1.);fragColor=vec4(0.,0.,0.,pow(1.-d*d,mix(1.2,2.8,uShadowSoftness))*smoothstep(1.,.85-uShadowSoftness*.6,d)*uShadowIntensity);}`,wr=new WeakMap,Ha=new Float32Array(20);function is(e,t){let[r,i,n,s,l,o]=t;return[e[0]*r+e[4]*i+e[8]*n+e[12],e[1]*r+e[5]*i+e[9]*n+e[13],e[2]*r+e[6]*i+e[10]*n+e[14],Math.abs(e[0])*s+Math.abs(e[4])*l+Math.abs(e[8])*o,Math.abs(e[1])*s+Math.abs(e[5])*l+Math.abs(e[9])*o,Math.abs(e[2])*s+Math.abs(e[6])*l+Math.abs(e[10])*o]}function Ol(e){if(e._lb!==void 0)return e._lb;let t=1e9,r=1e9,i=1e9,n=-1e9,s=-1e9,l=-1e9;for(let o of e.primitives||[]){let a=o.positions;if(a)for(let u=0;u<a.length;u+=3)a[u]<t&&(t=a[u]),a[u+1]<r&&(r=a[u+1]),a[u+2]<i&&(i=a[u+2]),a[u]>n&&(n=a[u]),a[u+1]>s&&(s=a[u+1]),a[u+2]>l&&(l=a[u+2])}return e._lb=t<=n?[(t+n)*.5,(r+s)*.5,(i+l)*.5,(n-t)*.5,(s-r)*.5,(l-i)*.5]:null}function zl(e){let t=wr.get(e);if(t)return t;let r=(o,a)=>{let u=e.createShader(o);return e.shaderSource(u,a),e.compileShader(u),u},i=e.createProgram();e.attachShader(i,r(35633,Ul)),e.attachShader(i,r(35632,Bl)),e.linkProgram(i);let n=e.createVertexArray(),s=e.createBuffer(),l=e.createBuffer();return e.bindVertexArray(n),e.bindBuffer(34962,s),e.bufferData(34962,80,35048),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,3,5126,!1,20,0),e.enableVertexAttribArray(1),e.vertexAttribPointer(1,2,5126,!1,20,12),e.bindBuffer(34963,l),e.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),e.bindVertexArray(null),t={prog:i,vao:n,vbo:s,ibo:l,uMVP:e.getUniformLocation(i,"uMVP"),uIntensity:e.getUniformLocation(i,"uShadowIntensity"),uSoftness:e.getUniformLocation(i,"uShadowSoftness")},wr.set(e,t),t}var pi={name:"contact-shadow",onContextRestored(e){wr.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let n=zl(e),s=!t.xrSessionActive&&(t.backdropMeshes?.length??0)>0,l=[],o=[];for(let f of t.meshes||[]){if(!f||f.visible===!1||f.isPluginMesh||f.name==="__xr_reticle__"||f.name?.startsWith("__xr_slot_"))continue;let g=Ol(f);if(!g)continue;f.transform&&(g=is(f.transform,g)),t.modelRootMatrix&&(g=is(t.modelRootMatrix,g));let[x,b,v,p,y,M]=g,P=[x,v,p,M,b-y,b+y];/floor|table|pedestal|ground|base|plane/i.test(f.name||"")||y<.14&&Math.min(p,M)>.45?o.push(P):l.push(P)}let a=[],u=t.bounds.center||[0,0,0],h=Math.max(.05,Number(t.bounds.radius)||.5),m=t.bounds.min,c=m?[u[0],u[1],u[2],h,Math.max(.01,u[1]-m[1]),h]:[u[0],u[1],u[2],h,h,h];t.modelRootMatrix&&(c=is(t.modelRootMatrix,c));let d=t.xrSessionActive&&o.length===0&&String(t.container?.tagName||"").toLowerCase()==="xr-live"?(t.modelRootMatrix?t.modelRootMatrix[5]*-.25+t.modelRootMatrix[13]:-.25)+.002:c[1]-c[4]+.002;for(let[f,g,x,b,v]of l){let p=-1/0;for(let[M,P,F,G,,T]of o)v>=T-.08&&Math.abs(f-M)<=F&&Math.abs(g-P)<=G&&T+.002>p&&(p=T+.002);s&&(p=Math.max(p,f>=.04&&f<=.36&&g>=-.34&&g<=-.04&&v>=.01?.036:Math.hypot(f,g)<=.66&&v>=-.06?.003:-.477)),isFinite(p)||(p=d);let y=a.find(M=>Math.hypot(f-M[0],g-M[1])<.06&&Math.abs(p-M[5])<.05);y?(y[2]=Math.max(y[2],x*.78),y[3]=Math.max(y[3],b*.78),y[4]=Math.min(y[4],v)):a.push([f,g,x,b,v,p])}if(a.length===0){let f=Math.max(.1,c[3]*1.5)/1.45;a.push([c[0],c[2],f,f,d,d])}e.useProgram(n.prog),e.uniformMatrix4fv(n.uMVP,!1,r),e.enable(3042),(e.blendFuncSeparate||e.blendFunc).call(e,770,771,1,771),e.depthMask(!1),e.bindVertexArray(n.vao),e.bindBuffer(34962,n.vbo);for(let[f,g,x,b,v,p]of a){let y=Math.max(0,v-p),M=i/(1+y*2);if(M<.02)continue;let P=1+Math.min(.75,y*.85),F=Math.max(.045,x*1.45*P),G=Math.max(.045,b*1.45*P);Ha.set([f-F,p,g-G,0,0,f+F,p,g-G,1,0,f+F,p,g+G,1,1,f-F,p,g+G,0,1]),e.bufferSubData(34962,0,Ha),e.uniform1f(n.uIntensity,M),e.uniform1f(n.uSoftness,Math.min(1,t.shadowSoftness+Math.min(.45,y*.6))),e.drawElements(4,6,5123,0)}e.bindVertexArray(null),e.depthMask(!0),e.disable(3042)},onDestroy(e){let t=wr.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),wr.delete(e))}};function ns(){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function ss(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function as(){if(typeof navigator>"u")return!1;let e=navigator;if(!e.xr||typeof e.xr.isSessionSupported!="function")return!1;try{return await e.xr.isSessionSupported("immersive-ar")?!0:await e.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function Ga(){return(await di()).bestMode}async function di(){let[e,t,r]=await Promise.all([as(),Promise.resolve(ns()),Promise.resolve(ss())]),i=[];t&&i.push("quick-look"),e&&i.push("webxr"),r&&i.push("scene-viewer");let n=null;return t?n="quick-look":e?n="webxr":r&&(n="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:r,availableModes:i,bestMode:n}}function Wa(e,t={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let r,i=!1;if(typeof e=="string"){if(r=$l(e),!r)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else r=URL.createObjectURL(e),i=!0;let n=[];if(t.allowScale===!1&&n.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let o=gi(t.canonicalWebPageUrl,!1);o&&n.push(`canonicalWebPageURL=${encodeURIComponent(o)}`)}t.checkoutTitle&&n.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&n.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&n.push(`price=${encodeURIComponent(t.price)}`),n.length>0&&(r+=`#${n.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",r);let l=document.createElement("img");l.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),l.style.display="none",s.appendChild(l),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),i&&URL.revokeObjectURL(r.split("#")[0])},3e3)}function gi(e,t=!1){if(typeof e!="string")return"";let r=e.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!r)return"";if(/^[\\/]{2}/.test(r))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${r.slice(0,32)}`);let i=r.toLowerCase();if(i.startsWith("https://")||i.startsWith("http://")||t&&i.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(r))return r;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${r.slice(0,32)}`)}function $l(e){try{return gi(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function Hl(e,t={}){let r=gi(e,!0),i=t.mode||"ar_preferred",n=new URLSearchParams({file:r,mode:i,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&n.set("title",t.title),t.link&&n.set("link",gi(t.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${n.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function Gl(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=Hl(e,t);window.location.href=r}var Vt=null;function Wl(e,t){let r=new Float32Array(144),i=new Float32Array(144),n=new Float32Array(96),s=new Uint16Array(144);for(let h=0;h<24;h++){let m=h/24*Math.PI*2,c=Math.cos(m),d=Math.sin(m),f=h*2,g=f+1,x=(h+1)%24*2;r[f*3]=c*.11,r[f*3+1]=.002,r[f*3+2]=d*.11,r[g*3]=c*.145,r[g*3+1]=.002,r[g*3+2]=d*.145,i[f*3+1]=i[g*3+1]=1,s.set([f,x,g,g,x,x+1],h*6)}let l=e.createVertexArray();e.bindVertexArray(l);let o=(h,m,c)=>{let d=e.createBuffer();return e.bindBuffer(34962,d),e.bufferData(34962,h,35044),e.enableVertexAttribArray(m),e.vertexAttribPointer(m,c,5126,!1,0,0),d},a=[o(r,0,3),o(i,1,3),o(n,2,2)],u=e.createBuffer();return a.push(u),e.bindBuffer(34963,u),e.bufferData(34963,s,35044),e.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:l,indexCount:s.length,indexType:5123,baseColor:t&&t.length>=3?[t[0],t[1],t[2],t[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:s,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:a}]}}function ja(e,t,r,i,n){let s=Math.cos(i),l=Math.sin(i),o=Math.max(.01,n);e.fill(0),e[0]=o*s,e[2]=-o*l,e[5]=o,e[8]=o*l,e[10]=o*s,e[12]=t[0]-o*(s*r[0]+l*r[2]),e[13]=t[1]-o*r[1],e[14]=t[2]-o*(-l*r[0]+s*r[2]),e[15]=1}var jl=class{constructor(e={}){this.s=null,this.placed=!1,this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.cleanFn=null,this.opts=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");Vt&&Vt!==this&&Vt.isSessionActive()&&await Vt.stop().catch(()=>{});let r=navigator.xr,i=this.opts,n=t||e?.container,s=String(n?.tagName||"").toLowerCase()==="xr-live",l=e?.bounds,o=Number(l?.radius)||1,a=Array.isArray(l?.center)?l.center:[0,0,0],u=Array.isArray(l?.min)?l.min:[-.5,-.5,-.5],h=typeof navigator<"u"&&navigator.userAgent||"",m=/Android|iPhone|iPad|iPod/i.test(h)&&!/Quest|Oculus|Pico|Vision/i.test(h),c=s?i.arScale==="fixed"?1:m?.55:1:i.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,d=s?[0,-.25,0]:[a[0]||0,i.arPlacement==="wall"?a[1]:u[1]??0,a[2]||0],f="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(f="immersive-vr")}catch{f="immersive-vr"}let g=n?.querySelector?.('[slot="ar-overlay"]')||null,x=!1,b=null,v=()=>{x&&g?.parentNode&&g.parentNode.removeChild(g),g=null,b=null,x=!1};if(f==="immersive-ar"){if(g)g.addEventListener?.("beforexrselect",_=>_.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let _=document.createElement("div");_.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let W=document.createElement("button");W.type="button",W.textContent="\u2715 Exit AR",W.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",W.addEventListener("beforexrselect",j=>j.preventDefault()),W.addEventListener("click",j=>{j.stopPropagation(),this.stop().catch(()=>{})}),b=document.createElement("div"),b.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",b.textContent="Move phone to detect a surface \u2022 Tap to place",_.appendChild(W),_.appendChild(b),document.body.appendChild(_),g=_,x=!0}}let p=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),y={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(p)};g&&(p.add("dom-overlay"),y.optionalFeatures=Array.from(p),y.domOverlay={root:g});for(let _ of Ve)_.onConfigureXRSessionInit?.(n,y);Array.isArray(y.optionalFeatures)&&y.optionalFeatures.includes("dom-overlay")&&!y.domOverlay?.root&&(y.optionalFeatures=y.optionalFeatures.filter(_=>_!=="dom-overlay"));let M=_=>{let W=String(_?.name||"");return W==="NotAllowedError"||W==="SecurityError"};try{this.s=await r.requestSession(f,y)}catch(_){if(v(),M(_))throw i.onError?.(_),_;try{this.s=await r.requestSession(f,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(W){if(M(W))throw i.onError?.(W),W;try{this.s=await r.requestSession(f)}catch(j){throw i.onError?.(j),j}}}let P=this.s;Vt=this,this.placed=!1;let F=null,G=null,T=null,E=null,S=null,B=[0,-.25,-1.2],k=[0,-.25,-1.2],w=new Float32Array(16),ie=new Float32Array(16),oe=!1,I=1,H=0,C=!1,z=null,ue=null,he=0,O=null,$=()=>{Vt===this&&(Vt=null),O?.(),O=null;try{G?.cancel?.()}catch{}if(G=null,T){let _=e?.meshes;if(Array.isArray(_)){let j=_.indexOf(T);j!==-1&&_.splice(j,1)}let W=e.getGLContext?.()||e?.gl;if(W)for(let j of T.primitives||[]){W.deleteVertexArray?.(j.vao);for(let X of j.buffers||[])W.deleteBuffer?.(X)}T=null}e?.setXRSessionActive?.(!1),v(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=$,P.addEventListener("end",()=>{$(),i.onExit?.()}),P.addEventListener("select",()=>{if(!this.placed){let _=S||B;k=[_[0],_[1],_[2]],ja(this.placedMat,k,d,H,c*I),this.placed=!0,T&&(T.visible=!1),b&&(b.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let _=e.getGLContext?.()||e?.gl;_&&typeof _.makeXRCompatible=="function"&&await _.makeXRCompatible();let W=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;_&&typeof W=="function"&&typeof P.updateRenderState=="function"&&P.updateRenderState({baseLayer:new W(P,_,{alpha:!0})});try{F=await P.requestReferenceSpace("local")}catch{try{F=await P.requestReferenceSpace("local-floor")}catch{F=await P.requestReferenceSpace("viewer")}}let j=await P.requestReferenceSpace("viewer").catch(()=>F);if(typeof P.requestHitTestSource=="function"&&j&&(G=await P.requestHitTestSource({space:j}).catch(()=>null)),f==="immersive-ar"&&_&&typeof _.createVertexArray=="function"&&Array.isArray(e.meshes)&&(T=Wl(_,i.reticleColor),e.meshes.push(T)),typeof window<"u"&&typeof window.addEventListener=="function"){let D=V=>Math.hypot(V.touches[1].clientX-V.touches[0].clientX,V.touches[1].clientY-V.touches[0].clientY),Y=V=>Math.atan2(V.touches[1].clientY-V.touches[0].clientY,V.touches[1].clientX-V.touches[0].clientX),te=V=>{this.s&&(V.touches.length===1&&this.placed?C=!0:V.touches.length>=2&&(C=!1,z=D(V),ue=Y(V)))},se=V=>{if(!this.s||V.touches.length<2)return;let ee=D(V),R=Y(V);if(z&&z>4&&i.arScale!=="fixed"&&(I=Math.max(.15,Math.min(6,I*(ee/z)))),ue!==null){let A=R-ue;A>Math.PI&&(A-=Math.PI*2),A<-Math.PI&&(A+=Math.PI*2),H-=A}z=ee,ue=R},le=V=>{(!V.touches||V.touches.length===0)&&(C=!1),(!V.touches||V.touches.length<2)&&(z=null,ue=null)};window.addEventListener("touchstart",te,{passive:!0}),window.addEventListener("touchmove",se,{passive:!0}),window.addEventListener("touchend",le,{passive:!0}),window.addEventListener("touchcancel",le,{passive:!0}),O=()=>{window.removeEventListener("touchstart",te),window.removeEventListener("touchmove",se),window.removeEventListener("touchend",le),window.removeEventListener("touchcancel",le)}}e.setXRSessionActive?.(!0);let X=(D,Y)=>{if(this.s!==P)return;P.requestAnimationFrame(X);let te=he>0?Math.min(Math.max((D-he)/1e3,0),.1):1/60;he=D,e?.stepXRUpdate?.(te);let se=Y.getViewerPose(F);if(!se)return;let le=se.views?.[0];if(!oe&&le?.transform){let N=le.transform.position,U=le.transform.matrix,Q=N?.x??(U?U[12]:0),q=N?.y??(U?U[13]:0),Z=N?.z??(U?U[14]:0),J=U?-U[8]:0,K=U?-U[10]:-1,ae=Math.hypot(J,K);ae>1e-4?(J/=ae,K/=ae):(J=0,K=-1),B=[Q+J*1.2,q-.25,Z+K*1.2],H=Math.atan2(-J,-K),oe=!0}if(G&&typeof Y.getHitTestResults=="function"&&(!this.placed||C)){let N=Y.getHitTestResults(G)||[],U=!1;for(let Q of N){let q=Q.getPose(F);if(q?.transform?.matrix){let Z=q.transform.matrix,J=Z[5];if(i.arPlacement==="wall"&&Math.abs(J)>.35||i.arPlacement==="floor"&&Math.abs(J)<.65)continue;E||(E=new Float32Array(16)),E.set(Z),S=[Z[12],Z[13],Z[14]],this.placed&&C&&(k=[Z[12],Z[13],Z[14]]),T&&(T.visible=!this.placed||C,T.transform.set(Z)),!this.placed&&b&&(b.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(E),U=!0;break}}!U&&T&&(T.visible=!1)}ja(w,this.placed?k:S||B,d,H,c*I),this.placed&&this.placedMat.set(w);let V=e.xrRigMatrix;V instanceof Float32Array&&V.length===16?ke(ie,V,w):ie.set(w),e.modelRootMatrix&&e.modelRootMatrix.set(ie);for(let N of Ve)N.onXRFrame?.(e,P,Y,F);let ee=e.getGLContext?.()||e?.gl,R=P.renderState?.baseLayer;ee&&R&&R.framebuffer!==void 0&&ee.bindFramebuffer(36160,R.framebuffer);let A=f==="immersive-ar",L=se.views||[];for(let N=0;N<L.length;N++){let U=L[N];if(typeof e.renderXRView=="function"){let Q;if(R&&typeof R.getViewport=="function"){let q=R.getViewport(U);q&&q.width>0&&q.height>0&&(Q=[q.x,q.y,q.width,q.height])}else R?.framebufferWidth>0&&R?.framebufferHeight>0&&(Q=[0,0,R.framebufferWidth,R.framebufferHeight]);e.renderXRView(U,ie,this.placed,Q,A,N)}}ee&&R&&R.framebuffer&&ee.bindFramebuffer(36160,null)};P.requestAnimationFrame(X)}catch(_){throw typeof P.end=="function"&&await P.end().catch(()=>{}),$(),i.onError?.(_),_}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function os(e){let t=await di(),r=e.preferredModes||["quick-look","webxr","scene-viewer"],i=null;for(let o of r)if(t.availableModes.includes(o)){i=o;break}if(i||(i=t.bestMode),!i)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let n={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},s={...e.sceneViewerOptions,resizable:e.arScale==="fixed"?!1:e.sceneViewerOptions?.resizable,enableVerticalPlacement:e.arPlacement==="wall"?!0:e.sceneViewerOptions?.enableVerticalPlacement},l={...e.webXROptions,arScale:e.arScale||e.webXROptions?.arScale,arPlacement:e.arPlacement||e.webXROptions?.arPlacement};try{if(i==="quick-look"){let o;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")o=e.model;else{if(typeof e.model=="string")return Wa(e.model,n),{mode:"quick-look",success:!0};o=zr(e.model)}return Wa(o,n),{mode:"quick-look",success:!0}}if(i==="scene-viewer"){let o=e.glbUrl||(typeof e.model=="string"?e.model:null);if(!o)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return Gl(o,s),{mode:"scene-viewer",success:!0}}if(i==="webxr"){if(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let o=new jl(l);return await o.start(e.view,e.element),{mode:"webxr",success:!0,session:o}}}catch(o){return{mode:i,success:!1,error:o}}return{mode:i,success:!1,error:new Error(`Unhandled AR mode: ${i}`)}}Ft.registerAR({activateAR:os,createUSDZBlob:zr}),Ft.registerScriptRunner(br),je(pi);var ls=new WeakMap;function us(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);ls.set(e,r)}function Xa(e){return ls.get(e)}async function Xl(e,t){if(!t)return null;let r;if(typeof t=="string")if(typeof fetch<"u"&&typeof createImageBitmap=="function"){let n=await(await fetch(t)).blob();r=await createImageBitmap(n)}else if(typeof Image<"u")r=await new Promise((n,s)=>{let l=new Image;l.crossOrigin="anonymous",l.onload=()=>n(l),l.onerror=s,l.src=t});else return null;else r=t;let i=e.createTexture();return e.bindTexture(3553,i),e.texImage2D(3553,0,6408,6408,5121,r),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9987),e.texParameteri(3553,10240,9729),e.generateMipmap(3553),i}var hs=new WeakMap,qa=new Float32Array(16);async function Ka(e,t,r){let i=r?await Xl(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var cs={name:"environment-map",onContextRestored(e){hs.delete(e)},setEnvironmentImage(e,t){return Ka(e,"environmentTexture",t)},setSkyboxImage(e,t){return Ka(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,n){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let s=hs.get(t);if(!s){let m=(f,g)=>{let x=t.createShader(f);return t.shaderSource(x,g),t.compileShader(x),x},c=t.createProgram();t.attachShader(c,m(35633,`#version 300 es
401
- out vec2 vNDC;void main(){vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2);vNDC=p*2.-1.;gl_Position=vec4(vNDC,.999999,1.);}`)),t.attachShader(c,m(35632,`#version 300 es
402
- precision highp float;in vec2 vNDC;uniform mat4 uInvVP;uniform vec3 uCameraPos;uniform sampler2D uSkyboxMap;uniform float uExposure;out vec4 fragColor;vec2 eqUV(vec3 d){return vec2(atan(d.x,d.z)/6.2831853+.5,asin(clamp(d.y,-1.,1.))/3.1415926+.5);}void main(){vec4 fp=uInvVP*vec4(vNDC,1.,1.);vec3 dir=normalize(fp.xyz/fp.w-uCameraPos);fragColor=vec4(pow(texture(uSkyboxMap,eqUV(dir)).rgb*uExposure,vec3(1./2.2)),1.);}`)),t.linkProgram(c);let d=typeof t.createVertexArray=="function"?t.createVertexArray():null;s={program:c,vao:d},hs.set(t,s)}let l=Li(qa,r)||qa;t.depthMask(!1),t.useProgram(s.program),s.vao&&t.bindVertexArray(s.vao),t.activeTexture(33984),t.bindTexture(3553,e.skyboxTexture);let o=t.getUniformLocation(s.program,"uSkyboxMap");o&&t.uniform1i(o,0);let a=t.getUniformLocation(s.program,"uInvVP");a&&t.uniformMatrix4fv(a,!1,l);let u=t.getUniformLocation(s.program,"uCameraPos");u&&t.uniform3f(u,i[0],i[1],i[2]);let h=t.getUniformLocation(s.program,"uExposure");h&&t.uniform1f(h,e.exposure??1),t.drawArrays(4,0,3),t.depthMask(!0)},onResolveShader(e,t,r,i){if(i.includes("evalSHIrradiance"))return null;let n=i.replace("out vec4 fragColor;",`uniform vec3 uSH[9];
446
+ vec4 world=uModel*(skinMatrix*vec4(${a},1.0));`).replace(`gl_Position=uMVP*vec4(${a},1.0);`,`gl_Position=uMVP*(skinMatrix*vec4(${a},1.0));`),{vs:n,fs:i}},onBuildPrimitiveVAO(e,t,r,i,n){let a=r?.attributes;if(!a||a.JOINTS_0===void 0||a.WEIGHTS_0===void 0)return null;let s=i.accessors[a.JOINTS_0],o=i.accessors[a.WEIGHTS_0];if(!s||!o)return null;let l=i.bufferViews[s.bufferView],c=i.bufferViews[o.bufferView];if(!l||!c)return null;let f=(l.byteOffset||0)+(s.byteOffset||0),m=(c.byteOffset||0)+(o.byteOffset||0),h=e.createBuffer();e.bindBuffer(34962,h);let p=s.componentType===5121?5121:5123,g=p===5121?new Uint8Array(n,f,s.count*4):new Uint16Array(n,f,s.count*4);e.bufferData(34962,g,35044),e.enableVertexAttribArray(4),e.vertexAttribIPointer(4,4,p,0,0);let x=e.createBuffer();e.bindBuffer(34962,x);let v=Fi(i,n,o,4)??new Float32Array(n,m,o.count*4);return e.bufferData(34962,v,35044),e.enableVertexAttribArray(5),e.vertexAttribPointer(5,4,5126,!1,0,0),{hasSkin:!0,buffers:[h,x]}},onBeforeDrawPrimitive(e,t,r,i,n,a){if(!r.pluginData?.skinning?.hasSkin)return;let s=a?.nodes?.[i.nodeIndex]?.skin;if(s===void 0||!a.skins||!a.skins[s])return;let o=a.skins[s].joints||[],l=new Float32Array(Du*16);for(let f=0;f<o.length&&f<Du;f++){let m=o[f],h=n[m]||lt();l.subarray(f*16,(f+1)*16).set(h)}let c=e.getUniformLocation(t,"uJointMatrix[0]");c&&e.uniformMatrix4fv(c,!1,l)}};Rt($u),Rt(Iu),Rt(ku),Rt(vo),Rt(lo);var m1=`#version 300 es
447
+ layout(location=0) in vec3 aPosition;layout(location=1) in vec2 aUV;uniform mat4 uMVP;out vec2 vUV;void main(){vUV=aUV;gl_Position=uMVP*vec4(aPosition,1.);}`,p1=`#version 300 es
448
+ precision highp float;in vec2 vUV;uniform float uShadowIntensity,uShadowSoftness;out vec4 fragColor;void main(){vec2 p=(vUV-.5)*2.;float d=clamp(length(p),0.,1.);fragColor=vec4(0.,0.,0.,pow(1.-d*d,mix(1.2,2.8,uShadowSoftness))*smoothstep(1.,.85-uShadowSoftness*.6,d)*uShadowIntensity);}`,Xn=new WeakMap,Yf=new Float32Array(20);function Fu(e,t){let[r,i,n,a,s,o]=t;return[e[0]*r+e[4]*i+e[8]*n+e[12],e[1]*r+e[5]*i+e[9]*n+e[13],e[2]*r+e[6]*i+e[10]*n+e[14],Math.abs(e[0])*a+Math.abs(e[4])*s+Math.abs(e[8])*o,Math.abs(e[1])*a+Math.abs(e[5])*s+Math.abs(e[9])*o,Math.abs(e[2])*a+Math.abs(e[6])*s+Math.abs(e[10])*o]}function d1(e){if(e._lb!==void 0)return e._lb;let t=1e9,r=1e9,i=1e9,n=-1e9,a=-1e9,s=-1e9;for(let o of e.primitives||[]){let l=o.positions;if(l)for(let c=0;c<l.length;c+=3)l[c]<t&&(t=l[c]),l[c+1]<r&&(r=l[c+1]),l[c+2]<i&&(i=l[c+2]),l[c]>n&&(n=l[c]),l[c+1]>a&&(a=l[c+1]),l[c+2]>s&&(s=l[c+2])}return e._lb=t<=n?[(t+n)*.5,(r+a)*.5,(i+s)*.5,(n-t)*.5,(a-r)*.5,(s-i)*.5]:null}function g1(e){let t=Xn.get(e);if(t)return t;let r=(o,l)=>{let c=e.createShader(o);return e.shaderSource(c,l),e.compileShader(c),c},i=e.createProgram();e.attachShader(i,r(35633,m1)),e.attachShader(i,r(35632,p1)),e.linkProgram(i);let n=e.createVertexArray(),a=e.createBuffer(),s=e.createBuffer();return e.bindVertexArray(n),e.bindBuffer(34962,a),e.bufferData(34962,80,35048),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,3,5126,!1,20,0),e.enableVertexAttribArray(1),e.vertexAttribPointer(1,2,5126,!1,20,12),e.bindBuffer(34963,s),e.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),e.bindVertexArray(null),t={prog:i,vao:n,vbo:a,ibo:s,uMVP:e.getUniformLocation(i,"uMVP"),uIntensity:e.getUniformLocation(i,"uShadowIntensity"),uSoftness:e.getUniformLocation(i,"uShadowSoftness")},Xn.set(e,t),t}var Ps={name:"contact-shadow",onContextRestored(e){Xn.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let n=g1(e),a=!t.xrSessionActive&&(t.backdropMeshes?.length??0)>0,s=[],o=[];for(let g of t.meshes||[]){if(!g||g.visible===!1||g.isPluginMesh||g.name==="__xr_reticle__"||g.name?.startsWith("__xr_slot_"))continue;let x=d1(g);if(!x)continue;g.transform&&(x=Fu(g.transform,x)),t.modelRootMatrix&&(x=Fu(t.modelRootMatrix,x));let[v,y,A,b,w,S]=x,E=[v,A,b,S,y-w,y+w];/floor|table|pedestal|ground|base|plane/i.test(g.name||"")||w<.14&&Math.min(b,S)>.45?o.push(E):s.push(E)}let l=[],c=t.bounds.center||[0,0,0],f=Math.max(.05,Number(t.bounds.radius)||.5),m=t.bounds.min,h=m?[c[0],c[1],c[2],f,Math.max(.01,c[1]-m[1]),f]:[c[0],c[1],c[2],f,f,f];t.modelRootMatrix&&(h=Fu(t.modelRootMatrix,h));let p=t.xrSessionActive&&o.length===0&&String(t.container?.tagName||"").toLowerCase()==="xr-live"?(t.modelRootMatrix?t.modelRootMatrix[5]*-.25+t.modelRootMatrix[13]:-.25)+.002:h[1]-h[4]+.002;for(let[g,x,v,y,A]of s){let b=-1/0;for(let[S,E,N,C,,_]of o)A>=_-.08&&Math.abs(g-S)<=N&&Math.abs(x-E)<=C&&_+.002>b&&(b=_+.002);a&&(b=Math.max(b,g>=.04&&g<=.36&&x>=-.34&&x<=-.04&&A>=.01?.036:Math.hypot(g,x)<=.66&&A>=-.06?.003:-.477)),isFinite(b)||(b=p);let w=l.find(S=>Math.hypot(g-S[0],x-S[1])<.06&&Math.abs(b-S[5])<.05);w?(w[2]=Math.max(w[2],v*.78),w[3]=Math.max(w[3],y*.78),w[4]=Math.min(w[4],A)):l.push([g,x,v,y,A,b])}if(l.length===0){let g=Math.max(.1,h[3]*1.5)/1.45;l.push([h[0],h[2],g,g,p,p])}e.useProgram(n.prog),e.uniformMatrix4fv(n.uMVP,!1,r),e.enable(3042),(e.blendFuncSeparate||e.blendFunc).call(e,770,771,1,771),e.depthMask(!1),e.bindVertexArray(n.vao),e.bindBuffer(34962,n.vbo);for(let[g,x,v,y,A,b]of l){let w=Math.max(0,A-b),S=i/(1+w*2);if(S<.02)continue;let E=1+Math.min(.75,w*.85),N=Math.max(.045,v*1.45*E),C=Math.max(.045,y*1.45*E);Yf.set([g-N,b,x-C,0,0,g+N,b,x-C,1,0,g+N,b,x+C,1,1,g-N,b,x+C,0,1]),e.bufferSubData(34962,0,Yf),e.uniform1f(n.uIntensity,S),e.uniform1f(n.uSoftness,Math.min(1,t.shadowSoftness+Math.min(.45,w*.6))),e.drawElements(4,6,5123,0)}e.bindVertexArray(null),e.depthMask(!0),e.disable(3042)},onDestroy(e){let t=Xn.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),Xn.delete(e))}};function Bu(){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function zu(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function Vu(){if(typeof navigator>"u")return!1;let e=navigator;if(!e.xr||typeof e.xr.isSessionSupported!="function")return!1;try{return await e.xr.isSessionSupported("immersive-ar")?!0:await e.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function Qf(){return(await Ns()).bestMode}async function Ns(){let[e,t,r]=await Promise.all([Vu(),Promise.resolve(Bu()),Promise.resolve(zu())]),i=[];t&&i.push("quick-look"),e&&i.push("webxr"),r&&i.push("scene-viewer");let n=null;return t?n="quick-look":e?n="webxr":r&&(n="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:r,availableModes:i,bestMode:n}}function Zf(e,t={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let r,i=!1;if(typeof e=="string"){if(r=y1(e),!r)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else r=URL.createObjectURL(e),i=!0;let n=[];if(t.allowScale===!1&&n.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let o=Cs(t.canonicalWebPageUrl,!1);o&&n.push(`canonicalWebPageURL=${encodeURIComponent(o)}`)}t.checkoutTitle&&n.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&n.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&n.push(`price=${encodeURIComponent(t.price)}`),n.length>0&&(r+=`#${n.join("&")}`);let a=document.createElement("a");a.setAttribute("rel","ar"),a.setAttribute("href",r);let s=document.createElement("img");s.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),s.style.display="none",a.appendChild(s),document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),i&&URL.revokeObjectURL(r.split("#")[0])},3e3)}function Cs(e,t=!1){if(typeof e!="string")return"";let r=e.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!r)return"";if(/^[\\/]{2}/.test(r))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${r.slice(0,32)}`);let i=r.toLowerCase();if(i.startsWith("https://")||i.startsWith("http://")||t&&i.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(r))return r;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${r.slice(0,32)}`)}function y1(e){try{return Cs(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function b1(e,t={}){let r=Cs(e,!0),i=t.mode||"ar_preferred",n=new URLSearchParams({file:r,mode:i,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&n.set("title",t.title),t.link&&n.set("link",Cs(t.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${n.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function x1(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=b1(e,t);window.location.href=r}var Ei=null;function v1(e,t){let r=new Float32Array(144),i=new Float32Array(144),n=new Float32Array(96),a=new Uint16Array(144);for(let f=0;f<24;f++){let m=f/24*Math.PI*2,h=Math.cos(m),p=Math.sin(m),g=f*2,x=g+1,v=(f+1)%24*2;r[g*3]=h*.11,r[g*3+1]=.002,r[g*3+2]=p*.11,r[x*3]=h*.145,r[x*3+1]=.002,r[x*3+2]=p*.145,i[g*3+1]=i[x*3+1]=1,a.set([g,v,x,x,v,v+1],f*6)}let s=e.createVertexArray();e.bindVertexArray(s);let o=(f,m,h)=>{let p=e.createBuffer();return e.bindBuffer(34962,p),e.bufferData(34962,f,35044),e.enableVertexAttribArray(m),e.vertexAttribPointer(m,h,5126,!1,0,0),p},l=[o(r,0,3),o(i,1,3),o(n,2,2)],c=e.createBuffer();return l.push(c),e.bindBuffer(34963,c),e.bufferData(34963,a,35044),e.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:s,indexCount:a.length,indexType:5123,baseColor:t&&t.length>=3?[t[0],t[1],t[2],t[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:a,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:l}]}}function Jf(e,t,r,i,n){let a=Math.cos(i),s=Math.sin(i),o=Math.max(.01,n);e.fill(0),e[0]=o*a,e[2]=-o*s,e[5]=o,e[8]=o*s,e[10]=o*a,e[12]=t[0]-o*(a*r[0]+s*r[2]),e[13]=t[1]-o*r[1],e[14]=t[2]-o*(-s*r[0]+a*r[2]),e[15]=1}var w1=class{constructor(e={}){this.s=null,this.placed=!1,this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.cleanFn=null,this.opts=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");Ei&&Ei!==this&&Ei.isSessionActive()&&await Ei.stop().catch(()=>{});let r=navigator.xr,i=this.opts,n=t||e?.container,a=String(n?.tagName||"").toLowerCase()==="xr-live",s=e?.bounds,o=Number(s?.radius)||1,l=Array.isArray(s?.center)?s.center:[0,0,0],c=Array.isArray(s?.min)?s.min:[-.5,-.5,-.5],f=typeof navigator<"u"&&navigator.userAgent||"",m=/Android|iPhone|iPad|iPod/i.test(f)&&!/Quest|Oculus|Pico|Vision/i.test(f),h=a?i.arScale==="fixed"?1:m?.55:1:i.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,p=a?[0,-.25,0]:[l[0]||0,i.arPlacement==="wall"?l[1]:c[1]??0,l[2]||0],g="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(g="immersive-vr")}catch{g="immersive-vr"}let x=n?.querySelector?.('[slot="ar-overlay"]')||null,v=!1,y=null,A=()=>{v&&x?.parentNode&&x.parentNode.removeChild(x),x=null,y=null,v=!1};if(g==="immersive-ar"){if(x)x.addEventListener?.("beforexrselect",Z=>Z.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let Z=document.createElement("div");Z.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let ae=document.createElement("button");ae.type="button",ae.textContent="\u2715 Exit AR",ae.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",ae.addEventListener("beforexrselect",ie=>ie.preventDefault()),ae.addEventListener("click",ie=>{ie.stopPropagation(),this.stop().catch(()=>{})}),y=document.createElement("div"),y.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",y.textContent="Move phone to detect a surface \u2022 Tap to place",Z.appendChild(ae),Z.appendChild(y),document.body.appendChild(Z),x=Z,v=!0}}let b=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),w={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(b)};x&&(b.add("dom-overlay"),w.optionalFeatures=Array.from(b),w.domOverlay={root:x});for(let Z of Lt)Z.onConfigureXRSessionInit?.(n,w);Array.isArray(w.optionalFeatures)&&w.optionalFeatures.includes("dom-overlay")&&!w.domOverlay?.root&&(w.optionalFeatures=w.optionalFeatures.filter(Z=>Z!=="dom-overlay"));let S=Z=>{let ae=String(Z?.name||"");return ae==="NotAllowedError"||ae==="SecurityError"};try{this.s=await r.requestSession(g,w)}catch(Z){if(A(),S(Z))throw i.onError?.(Z),Z;try{this.s=await r.requestSession(g,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(ae){if(S(ae))throw i.onError?.(ae),ae;try{this.s=await r.requestSession(g)}catch(ie){throw i.onError?.(ie),ie}}}let E=this.s;Ei=this,this.placed=!1;let N=null,C=null,_=null,P=null,R=null,I=[0,-.25,-1.2],F=[0,-.25,-1.2],V=new Float32Array(16),Y=new Float32Array(16),J=!1,re=1,Q=0,ee=!1,k=null,G=null,q=0,H=null,te=()=>{Ei===this&&(Ei=null),H?.(),H=null;try{C?.cancel?.()}catch{}if(C=null,_){let Z=e?.meshes;if(Array.isArray(Z)){let ie=Z.indexOf(_);ie!==-1&&Z.splice(ie,1)}let ae=e.getGLContext?.()||e?.gl;if(ae)for(let ie of _.primitives||[]){ae.deleteVertexArray?.(ie.vao);for(let de of ie.buffers||[])ae.deleteBuffer?.(de)}_=null}e?.setXRSessionActive?.(!1),A(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=te,E.addEventListener("end",()=>{te(),i.onExit?.()}),E.addEventListener("select",()=>{if(!this.placed){let Z=R||I;F=[Z[0],Z[1],Z[2]],Jf(this.placedMat,F,p,Q,h*re),this.placed=!0,_&&(_.visible=!1),y&&(y.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let Z=e.getGLContext?.()||e?.gl;Z&&typeof Z.makeXRCompatible=="function"&&await Z.makeXRCompatible();let ae=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;Z&&typeof ae=="function"&&typeof E.updateRenderState=="function"&&E.updateRenderState({baseLayer:new ae(E,Z,{alpha:!0})});try{N=await E.requestReferenceSpace("local")}catch{try{N=await E.requestReferenceSpace("local-floor")}catch{N=await E.requestReferenceSpace("viewer")}}let ie=await E.requestReferenceSpace("viewer").catch(()=>N);if(typeof E.requestHitTestSource=="function"&&ie&&(C=await E.requestHitTestSource({space:ie}).catch(()=>null)),g==="immersive-ar"&&Z&&typeof Z.createVertexArray=="function"&&Array.isArray(e.meshes)&&(_=v1(Z,i.reticleColor),e.meshes.push(_)),typeof window<"u"&&typeof window.addEventListener=="function"){let me=ne=>Math.hypot(ne.touches[1].clientX-ne.touches[0].clientX,ne.touches[1].clientY-ne.touches[0].clientY),Se=ne=>Math.atan2(ne.touches[1].clientY-ne.touches[0].clientY,ne.touches[1].clientX-ne.touches[0].clientX),ke=ne=>{this.s&&(ne.touches.length===1&&this.placed?ee=!0:ne.touches.length>=2&&(ee=!1,k=me(ne),G=Se(ne)))},_e=ne=>{if(!this.s||ne.touches.length<2)return;let Re=me(ne),W=Se(ne);if(k&&k>4&&i.arScale!=="fixed"&&(re=Math.max(.15,Math.min(6,re*(Re/k)))),G!==null){let D=W-G;D>Math.PI&&(D-=Math.PI*2),D<-Math.PI&&(D+=Math.PI*2),Q-=D}k=Re,G=W},Le=ne=>{(!ne.touches||ne.touches.length===0)&&(ee=!1),(!ne.touches||ne.touches.length<2)&&(k=null,G=null)};window.addEventListener("touchstart",ke,{passive:!0}),window.addEventListener("touchmove",_e,{passive:!0}),window.addEventListener("touchend",Le,{passive:!0}),window.addEventListener("touchcancel",Le,{passive:!0}),H=()=>{window.removeEventListener("touchstart",ke),window.removeEventListener("touchmove",_e),window.removeEventListener("touchend",Le),window.removeEventListener("touchcancel",Le)}}e.setXRSessionActive?.(!0);let de=(me,Se)=>{if(this.s!==E)return;E.requestAnimationFrame(de);let ke=q>0?Math.min(Math.max((me-q)/1e3,0),.1):1/60;q=me,e?.stepXRUpdate?.(ke);let _e=Se.getViewerPose(N);if(!_e)return;let Le=_e.views?.[0];if(!J&&Le?.transform){let O=Le.transform.position,X=Le.transform.matrix,se=O?.x??(X?X[12]:0),ce=O?.y??(X?X[13]:0),pe=O?.z??(X?X[14]:0),xe=X?-X[8]:0,he=X?-X[10]:-1,Ne=Math.hypot(xe,he);Ne>1e-4?(xe/=Ne,he/=Ne):(xe=0,he=-1),I=[se+xe*1.2,ce-.25,pe+he*1.2],Q=Math.atan2(-xe,-he),J=!0}if(C&&typeof Se.getHitTestResults=="function"&&(!this.placed||ee)){let O=Se.getHitTestResults(C)||[],X=!1;for(let se of O){let ce=se.getPose(N);if(ce?.transform?.matrix){let pe=ce.transform.matrix,xe=pe[5];if(i.arPlacement==="wall"&&Math.abs(xe)>.35||i.arPlacement==="floor"&&Math.abs(xe)<.65)continue;P||(P=new Float32Array(16)),P.set(pe),R=[pe[12],pe[13],pe[14]],this.placed&&ee&&(F=[pe[12],pe[13],pe[14]]),_&&(_.visible=!this.placed||ee,_.transform.set(pe)),!this.placed&&y&&(y.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(P),X=!0;break}}!X&&_&&(_.visible=!1)}Jf(V,this.placed?F:R||I,p,Q,h*re),this.placed&&this.placedMat.set(V);let ne=e.xrRigMatrix;ne instanceof Float32Array&&ne.length===16?ft(Y,ne,V):Y.set(V),e.modelRootMatrix&&e.modelRootMatrix.set(Y);for(let O of Lt)O.onXRFrame?.(e,E,Se,N);let Re=e.getGLContext?.()||e?.gl,W=E.renderState?.baseLayer;Re&&W&&W.framebuffer!==void 0&&Re.bindFramebuffer(36160,W.framebuffer);let D=g==="immersive-ar",z=_e.views||[];for(let O=0;O<z.length;O++){let X=z[O];if(typeof e.renderXRView=="function"){let se;if(W&&typeof W.getViewport=="function"){let ce=W.getViewport(X);ce&&ce.width>0&&ce.height>0&&(se=[ce.x,ce.y,ce.width,ce.height])}else W?.framebufferWidth>0&&W?.framebufferHeight>0&&(se=[0,0,W.framebufferWidth,W.framebufferHeight]);e.renderXRView(X,Y,this.placed,se,D,O)}}Re&&W&&W.framebuffer&&Re.bindFramebuffer(36160,null)};E.requestAnimationFrame(de)}catch(Z){throw typeof E.end=="function"&&await E.end().catch(()=>{}),te(),i.onError?.(Z),Z}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function Uu(e){let t=await Ns(),r=e.preferredModes||["quick-look","webxr","scene-viewer"],i=null;for(let o of r)if(t.availableModes.includes(o)){i=o;break}if(i||(i=t.bestMode),!i)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let n={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},a={...e.sceneViewerOptions,resizable:e.arScale==="fixed"?!1:e.sceneViewerOptions?.resizable,enableVerticalPlacement:e.arPlacement==="wall"?!0:e.sceneViewerOptions?.enableVerticalPlacement},s={...e.webXROptions,arScale:e.arScale||e.webXROptions?.arScale,arPlacement:e.arPlacement||e.webXROptions?.arPlacement};try{if(i==="quick-look"){let o;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")o=e.model;else{if(typeof e.model=="string")return Zf(e.model,n),{mode:"quick-look",success:!0};o=Aa(e.model)}return Zf(o,n),{mode:"quick-look",success:!0}}if(i==="scene-viewer"){let o=e.glbUrl||(typeof e.model=="string"?e.model:null);if(!o)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return x1(o,a),{mode:"scene-viewer",success:!0}}if(i==="webxr"){if(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let o=new w1(s);return await o.start(e.view,e.element),{mode:"webxr",success:!0,session:o}}}catch(o){return{mode:i,success:!1,error:o}}return{mode:i,success:!1,error:new Error(`Unhandled AR mode: ${i}`)}}di.registerAR({activateAR:Uu,createUSDZBlob:Aa}),di.registerScriptRunner(Bn),Rt(Ps),Rt(_o);var Ou=new WeakMap;function ju(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);Ou.set(e,r)}function em(e){return Ou.get(e)}async function M1(e,t){if(!t)return null;let r;if(typeof t=="string")if(typeof fetch<"u"&&typeof createImageBitmap=="function"){let n=await(await fetch(t)).blob();r=await createImageBitmap(n)}else if(typeof Image<"u")r=await new Promise((n,a)=>{let s=new Image;s.crossOrigin="anonymous",s.onload=()=>n(s),s.onerror=a,s.src=t});else return null;else r=t;let i=e.createTexture();return e.bindTexture(3553,i),e.texImage2D(3553,0,6408,6408,5121,r),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9987),e.texParameteri(3553,10240,9729),e.generateMipmap(3553),i&&(i.__gpuImageSource=r),i}var Gu=new WeakMap,tm=new Float32Array(16);async function rm(e,t,r){let i=r?await M1(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var Hu={name:"environment-map",onContextRestored(e){Gu.delete(e)},setEnvironmentImage(e,t){return rm(e,"environmentTexture",t)},setSkyboxImage(e,t){return rm(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,n){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let a=Gu.get(t);if(!a){let m=(g,x)=>{let v=t.createShader(g);return t.shaderSource(v,x),t.compileShader(v),v},h=t.createProgram();t.attachShader(h,m(35633,`#version 300 es
449
+ out vec2 vNDC;void main(){vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2);vNDC=p*2.-1.;gl_Position=vec4(vNDC,.999999,1.);}`)),t.attachShader(h,m(35632,`#version 300 es
450
+ precision highp float;in vec2 vNDC;uniform mat4 uInvVP;uniform vec3 uCameraPos;uniform sampler2D uSkyboxMap;uniform float uExposure;out vec4 fragColor;vec2 eqUV(vec3 d){return vec2(atan(d.x,d.z)/6.2831853+.5,asin(clamp(d.y,-1.,1.))/3.1415926+.5);}void main(){vec4 fp=uInvVP*vec4(vNDC,1.,1.);vec3 dir=normalize(fp.xyz/fp.w-uCameraPos);fragColor=vec4(pow(texture(uSkyboxMap,eqUV(dir)).rgb*uExposure,vec3(1./2.2)),1.);}`)),t.linkProgram(h);let p=typeof t.createVertexArray=="function"?t.createVertexArray():null;a={program:h,vao:p},Gu.set(t,a)}let s=co(tm,r)||tm;t.depthMask(!1),t.useProgram(a.program),a.vao&&t.bindVertexArray(a.vao),t.activeTexture(33984),t.bindTexture(3553,e.skyboxTexture);let o=t.getUniformLocation(a.program,"uSkyboxMap");o&&t.uniform1i(o,0);let l=t.getUniformLocation(a.program,"uInvVP");l&&t.uniformMatrix4fv(l,!1,s);let c=t.getUniformLocation(a.program,"uCameraPos");c&&t.uniform3f(c,i[0],i[1],i[2]);let f=t.getUniformLocation(a.program,"uExposure");f&&t.uniform1f(f,e.exposure??1),t.drawArrays(4,0,3),t.depthMask(!0)},onResolveShader(e,t,r,i){if(i.includes("evalSHIrradiance"))return null;let n=i.replace("out vec4 fragColor;",`uniform vec3 uSH[9];
403
451
  uniform int uHasSH;
404
452
  out vec4 fragColor;`).replace("void main(){",`vec3 integrateBRDFApprox(vec3 f0,float r,float NoV){vec4 c0=vec4(-1.,-.0275,-.572,.022),c1=vec4(1.,.0425,1.04,-.04),rv=r*c0+c1;float a=min(rv.x*rv.x,exp2(-9.28*NoV))*rv.x+rv.y;vec2 ab=vec2(-1.04,1.04)*a+rv.zw;return f0*ab.x+vec3(ab.y);}
405
453
  vec3 evalSHIrradiance(vec3 n){return max(vec3(0.),uSH[0]+uSH[1]*n.y+uSH[2]*n.z+uSH[3]*n.x+uSH[4]*(n.x*n.y)+uSH[5]*(n.y*n.z)+uSH[6]*(3.*n.z*n.z-1.)+uSH[7]*(n.x*n.z)+uSH[8]*(n.x*n.x-n.y*n.y));}
@@ -412,15 +460,15 @@ envDiffuse=uHasSH==1?evalSHIrradiance(N):textureLod(uEnvironmentMap,equirectangu
412
460
  }else if(uHasSH==1){
413
461
  specularIBL=getStudioRadiance(R,roughness)*integrateBRDFApprox(F,roughness,NoV);
414
462
  envDiffuse=evalSHIrradiance(N);
415
- }`),{vs:r,fs:n}},onBeforeDrawPrimitive(e,t,r,i,n,s){let l=ls.get(e),o=e.getUniformLocation(t,"uHasSH");if(l&&l.length>=27){o&&e.uniform1i(o,1);let a=e.getUniformLocation(t,"uSH");a&&e.uniform3fv(a,l)}else o&&e.uniform1i(o,0)},onAttributeChanged(e,t,r,i){t==="environment-image"&&e.viewer?this.setEnvironmentImage?.(e.viewer,i):t==="skybox-image"&&e.viewer&&this.setSkyboxImage?.(e.viewer,i)}},ms=new WeakMap;function fs(e,t){let r=t||e.viewer;if(!r||typeof r.projectPointToScreen!="function")return;let i=e.mockHotspots||e.querySelectorAll('[slot^="hotspot-"], [data-position]');for(let n=0;n<i.length;n++){let s=i[n],l=s.getAttribute("data-position");if(!l)continue;let o=l.trim().split(/\s+/).map(m=>parseFloat(m.replace(/m$/,"")));if(o.length<3||o.some(isNaN))continue;let a=s.getAttribute("data-normal"),u;if(a){let m=a.trim().split(/\s+/).map(c=>parseFloat(c));m.length>=3&&!m.some(isNaN)&&(u=[m[0],m[1],m[2]])}let h=r.projectPointToScreen([o[0],o[1],o[2]],u);s.style.position="absolute",s.style.left="0",s.style.top="0",s.style.transform=`translate(-50%, -50%) translate3d(${h.x}px, ${h.y}px, 0)`,s.style.zIndex="3",h.visible?(s.style.opacity="1",s.style.pointerEvents="auto",s.removeAttribute("data-occluded")):(s.style.opacity="0",s.style.pointerEvents="none",s.setAttribute("data-occluded",""))}}var ps={name:"hotspots",updateHotspotsForElement:fs,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{fs(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),ms.set(e,t)},onCameraChange(e,t){t&&fs(t,e)},onElementDisconnected(e){let t=ms.get(e);t&&(t.disconnect(),ms.delete(e))}},Ya=1024,ds=256,yi=2048,ql=128,Kl=64,Yl=16,Zl=1e4,Ql=8,wt=new Set(["__proto__","constructor","prototype"]),Za={neg:e=>-e,abs:Math.abs,sign:Math.sign,floor:Math.floor,ceil:Math.ceil,round:Math.round,trunc:Math.trunc,fract:e=>e-Math.floor(e),sqrt:e=>Math.sqrt(Math.max(0,e)),cbrt:Math.cbrt,exp:Math.exp,log:e=>e>0?Math.log(e):0,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:e=>Math.asin(Math.max(-1,Math.min(1,e))),acos:e=>Math.acos(Math.max(-1,Math.min(1,e))),atan:Math.atan,rad:e=>e*Math.PI/180,deg:e=>e*180/Math.PI,saturate:e=>Math.max(0,Math.min(1,e))},Qa={add:(e,t)=>e+t,sub:(e,t)=>e-t,mul:(e,t)=>e*t,div:(e,t)=>Math.abs(t)<1e-12?0:e/t,rem:(e,t)=>Math.abs(t)<1e-12?0:e%t,mod:(e,t)=>Math.abs(t)<1e-12?0:e%t,min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2},bi={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},xi=(e,t)=>e!==null&&typeof e=="object"&&!wt.has(t)&&Object.prototype.hasOwnProperty.call(e,t),it=e=>Array.isArray(e)?[...e]:e,Ja=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&xi(e,"value")?e.value:e,_e=(e,t)=>xi(e.configuration,t)?Ja(e.configuration[t]):void 0,fe=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},Ut=e=>Math.max(0,Math.min(1,e)),ut=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function Ar(e){if(typeof e!="string"||!e.startsWith("/"))return null;let t=[];for(let r of e.slice(1).split("/")){let i=r.replace(/~1/g,"/").replace(/~0/g,"~");if(!i||wt.has(i)||wt.has(r))return null;t.push(i)}return{segments:t}}var nr=(e,t)=>{if(e===void 0||!/^\d+$/.test(e))return-1;let r=Number(e);return Number.isSafeInteger(r)&&r>=0&&r<t?r:-1},eo=e=>{let t=fe(e[0]),r=fe(e[1]),i=fe(e[2]),n=fe(e[3],1),s=Math.hypot(t,r,i,n);return s>1e-8?[t/s,r/s,i/s,n/s]:[0,0,0,1]},to=(e,t,r,i)=>{if(typeof e=="number"&&typeof t=="number")return e+(t-e)*r;if(Array.isArray(e)&&Array.isArray(t)){if(i&&e.length===4&&t.length===4){let n=[0,0,0,1];return qn(n,eo(e),eo(t),r),n}return e.slice(0,t.length).map((n,s)=>n+(t[s]-n)*r)}return r>=.5?t:e},gs=(e,t,r)=>Array.isArray(e)&&Array.isArray(t)?e.slice(0,t.length).map((i,n)=>r(fe(i),fe(t[n]))):Array.isArray(e)?e.map(i=>r(fe(i),fe(t))):Array.isArray(t)?t.map(i=>r(fe(e),fe(i))):r(fe(e),fe(t)),Jl=(e,t)=>Array.isArray(e)?e.map(r=>t(fe(r))):t(fe(e)),ro=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((r,i)=>Math.abs(r-t[i])<=1e-6):e===t,ys=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>Ya)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${Ya})`);let n=Array.isArray(r.variables)?r.variables:[];if(n.length>ds)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${ds})`);let s=Array.isArray(r.declarations)?r.declarations:[],l=Array.isArray(r.events)?r.events:[],o=new Map,a=new Map,u=new Map,h=new Map,m=new Map,c=new Map,d=[],f=[],g=new Map,x=1,b=0,v=0,p=0,y=0,M=!1,P=!1,F=!1;n.forEach((O,$)=>{if(!O||typeof O!="object")return;let _=it(Ja(O.value));o.set($,_);let W=O.id??O.name;typeof W=="string"&&W&&!wt.has(W)&&o.set(W,_)}),(t?.nodes||[]).forEach((O,$)=>{for(let _ of O?.children||[])typeof _=="number"&&g.set(_,$)});let G=O=>O.op||typeof O.declaration=="number"&&s[O.declaration]?.op||"",T=(O,$,_)=>{if(wt.has($))return;let W=a.get(O);W||a.set(O,W=Object.create(null)),W[$]=_},E=(O,$)=>{if(typeof O!="number"&&typeof O!="string"||typeof O=="string"&&wt.has(O)||!o.has(O)&&o.size>=ds*2)return;let _=it($);if(o.set(O,_),typeof O=="number"){let W=n[O]?.id??n[O]?.name;typeof W=="string"&&!wt.has(W)&&o.set(W,_)}},S=O=>typeof O=="number"?l[O]?.id??String(O):typeof O=="string"?/^\d+$/.test(O)&&l[Number(O)]?.id?l[Number(O)].id:O:"",B=(O,$)=>{for(let _=O,W=0;_!==void 0&&_>=0&&W<128;_=g.get(_),W++)if(_===$)return!0;return!1},k=O=>{for(let $=d.length-1;$>=0;$--)d[$].key===O&&d.splice($,1)},w=O=>{k(O.key),d.length>=ql&&d.shift(),d.push(O)},ie=O=>{let $=Ar(O)?.segments;if($){if($[0]==="nodes"&&Array.isArray(t?.nodes)){let _=t.nodes[nr($[1],t.nodes.length)];if(!_)return;let W=$[2];if(W in bi){let j=bi[W],X=_[W]||j;return j.map((D,Y)=>fe(X[Y],D))}if(W==="weights"){let j=Array.isArray(_.weights)?_.weights:[0],X=$.length===4?nr($[3],64):-2;return X===-2?j.map(D=>fe(D)):X>=0?fe(j[X]):void 0}if(W==="visible"||W==="extensions"&&$[3]==="KHR_node_visibility"&&$[4]==="visible")return _.extensions?.KHR_node_visibility?.visible??_.visible??!0}else if($[0]==="materials"&&Array.isArray(t?.materials)){let _=t.materials[nr($[1],t.materials.length)];if(!_)return;let W=_.pbrMetallicRoughness||{};if($[2]==="pbrMetallicRoughness"){if($[3]==="baseColorFactor"){let j=W.baseColorFactor||[1,1,1,1];return[fe(j[0],1),fe(j[1],1),fe(j[2],1),fe(j[3],1)]}if($[3]==="metallicFactor"||$[3]==="roughnessFactor")return fe(W[$[3]],1)}if($[2]==="emissiveFactor"){let j=_.emissiveFactor||[0,0,0];return[fe(j[0]),fe(j[1]),fe(j[2])]}if($[2]==="alphaCutoff")return fe(_.alphaCutoff,.5)}}},oe=(O,$)=>{let _=Ar(O)?.segments;if(!_)return!1;if(_[0]==="nodes"&&Array.isArray(t?.nodes)){let W=nr(_[1],t.nodes.length),j=t.nodes[W];if(!j)return!1;let X=_[2];if(X in bi&&Array.isArray($)){let D=bi[X];if($.length<D.length)return!1;let Y=D.map((se,le)=>fe($[le],se));if(X==="rotation"){let se=Math.hypot(...Y);Y=se>1e-8?Y.map(le=>le/se):[0,0,0,1]}j[X]=Y,delete j.matrix;let te=e?.initialNodeTransforms?.[W];return te&&(te[X[0]]=[...Y]),M=!0,!0}if(X==="weights"){Array.isArray(j.weights)||(j.weights=[]);let D=(Y,te)=>{for(let se of e?.meshes||[])if(se.nodeIndex===W)for(let le of se.primitives||[])le.pluginData?.morph?.weights&&(le.pluginData.morph.weights[Y]=te)};if(_.length===4){let Y=nr(_[3],64);if(Y<0)return!1;D(Y,j.weights[Y]=fe($))}else if(Array.isArray($))j.weights=$.slice(0,64).map(Y=>fe(Y)),j.weights.forEach((Y,te)=>D(te,Y));else return!1;return F=!0,!0}if(X==="visible"||X==="extensions"&&_[3]==="KHR_node_visibility"&&_[4]==="visible"){let D=ut($);return j.visible=D,(!j.extensions||typeof j.extensions!="object")&&(j.extensions={}),j.extensions.KHR_node_visibility={visible:D},P=!0,!0}}else if(_[0]==="materials"&&Array.isArray(t?.materials)){let W=nr(_[1],t.materials.length),j=t.materials[W];if(!j)return!1;let X=j.pbrMetallicRoughness||(j.pbrMetallicRoughness={}),D=Y=>{for(let te of e?.meshes||[])for(let se of te.primitives||[])(se.materialIndex??0)===W&&Y(se)};if(_[2]==="pbrMetallicRoughness"){if(_[3]==="baseColorFactor"&&Array.isArray($)&&$.length>=3){let Y=[Ut(fe($[0],1)),Ut(fe($[1],1)),Ut(fe($[2],1)),$[3]!==void 0?Ut(fe($[3],1)):X.baseColorFactor?.[3]??1];return X.baseColorFactor=Y,D(te=>te.baseColor=[...Y]),F=!0}if(_[3]==="metallicFactor"||_[3]==="roughnessFactor"){let Y=_[3]==="metallicFactor",te=Ut(fe($,Y?0:.5));return X[_[3]]=te,D(se=>se[Y?"metallic":"roughness"]=te),F=!0}}if(_[2]==="emissiveFactor"&&Array.isArray($)&&$.length>=3)return j.emissiveFactor=[0,1,2].map(Y=>Math.max(0,fe($[Y]))),F=!0;if(_[2]==="alphaCutoff")return j.alphaCutoff=Ut(fe($,.5)),F=!0}return!1},I=(O,$,_=new Set)=>{let W=_e($,"pointer");if(typeof W!="string"||!W.startsWith("/"))return null;let j=W.replace(/\{([a-zA-Z0-9_]+)\}/g,(X,D)=>{let Y=Math.trunc(Number(H(O,D,void 0,_)??_e($,D)));return Number.isSafeInteger(Y)&&Y>=0?String(Y):"-1"});return Ar(j)?j:null},H=(O,$,_,W)=>{let j=i[O]?.values;if(!xi(j,$))return _;let X=j[$];if(X==null)return _;if(typeof X!="object"||Array.isArray(X))return it(X);let D=X;return typeof D.node=="number"?C(D.node,D.socket||"value",W):xi(D,"value")?it(D.value):_},C=(O,$,_)=>{if(O<0||O>=i.length||_.has(O)||_.size>128||++p>Zl)return;let W=i[O],j=G(W);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(j))return it(a.get(O)?.[$]);_.add(O);try{let X=(D,Y=0)=>H(O,D,Y,_);if(j==="variable/get"){let D=_e(W,"variable")??_e(W,"id");return typeof D=="number"||typeof D=="string"?it(o.get(D)):void 0}if(j==="pointer/get"){let D=I(O,W,_);return D?ie(D):void 0}if(j.startsWith("math/")){let D=j.slice(5);if(D in Za)return Jl(X("a"),Za[D]);if(D in Qa){let Y=/^(mul|div|rem|mod|pow)$/.test(D)?1:0;return gs(X("a",D==="mul"?1:0),X("b",Y),Qa[D])}if(D==="pi")return Math.PI;if(D==="e")return Math.E;if(D==="random")return Math.random();if(D==="clamp")return gs(gs(X("a"),X("b",X("min",0)),Math.max),X("c",X("max",1)),Math.min);if(D==="mix"||D==="quatSlerp")return to(X("a",0),X("b",1),fe(X("c",X("t",.5)),.5),D==="quatSlerp");if(D==="dot"){let Y=X("a"),te=X("b");return Array.isArray(Y)&&Array.isArray(te)?Y.reduce((se,le,V)=>se+(le||0)*(te[V]||0),0):fe(Y)*fe(te)}if(D==="cross"){let Y=X("a",[0,0,0]),te=X("b",[0,0,0]);return Array.isArray(Y)&&Array.isArray(te)?[(Y[1]||0)*(te[2]||0)-(Y[2]||0)*(te[1]||0),(Y[2]||0)*(te[0]||0)-(Y[0]||0)*(te[2]||0),(Y[0]||0)*(te[1]||0)-(Y[1]||0)*(te[0]||0)]:[0,0,0]}if(D==="length"){let Y=X("a");return Array.isArray(Y)?Math.hypot(...Y):Math.abs(fe(Y))}if(D==="distance"){let Y=X("a"),te=X("b");return Array.isArray(Y)&&Array.isArray(te)?Math.hypot(...Y.map((se,le)=>(se||0)-(te[le]||0))):Math.abs(fe(Y)-fe(te))}if(D==="normalize"){let Y=X("a");if(!Array.isArray(Y))return fe(Y)>=0?1:-1;let te=Math.hypot(...Y);return te>1e-8?Y.map(se=>se/te):Y.map(()=>0)}if(D.startsWith("combine"))return["a","b","c","d"].slice(0,Number(D[7])||2).map(Y=>fe(X(Y)));if(D.startsWith("extract")){let Y=X("a");return Array.isArray(Y)?Y[$==="0"||$==="x"?0:$==="1"||$==="y"?1:$==="2"||$==="z"?2:3]??0:0}if(D==="eq")return ro(X("a"),X("b"));if(D==="ne")return!ro(X("a"),X("b"));if(D==="lt")return fe(X("a"))<fe(X("b"));if(D==="le")return fe(X("a"))<=fe(X("b"));if(D==="gt")return fe(X("a"))>fe(X("b"));if(D==="ge")return fe(X("a"))>=fe(X("b"));if(D==="isNaN")return Number.isNaN(Number(X("a")));if(D==="isInf"){let Y=Number(X("a"));return!Number.isFinite(Y)&&!Number.isNaN(Y)}return D==="and"?ut(X("a",!1))&&ut(X("b",!1)):D==="or"?ut(X("a",!1))||ut(X("b",!1)):D==="xor"?ut(X("a",!1))!==ut(X("b",!1)):D==="not"?!ut(X("a",!1)):D==="select"?it(ut(X("condition",!1))?X("a"):X("b")):void 0}return j==="type/boolToInt"||j==="type/boolToFloat"?ut(X("a",!1))?1:0:j==="type/intToBool"||j==="type/floatToBool"?fe(X("a",0))!==0:j==="type/intToFloat"?fe(X("a",0)):j==="type/floatToInt"?Math.trunc(fe(X("a",0))):void 0}finally{_.delete(O)}},z=()=>{if(M){M=!1,F=!0;let O=Cr(t);if(e){e.worldMatrices=O;for(let $ of e.meshes||[])$.nodeIndex>=0&&$.nodeIndex<O.length&&($.transform.set(O[$.nodeIndex]),Ye($.normalMatrix,$.transform))}}if(P){P=!1,F=!0;let O=t?.nodes;if(Array.isArray(e?.meshes)&&Array.isArray(O))for(let $ of e.meshes){let _=!0;for(let W=$.nodeIndex,j=0;W!==void 0&&W>=0&&j<128;W=g.get(W),j++){let X=O[W];if(X?.visible===!1||X?.extensions?.KHR_node_visibility?.visible===!1){_=!1;break}}$.visible=_}}F&&(F=!1,e?.render?.())},ue=(O,$={steps:0})=>{if(!O||typeof O.node!="number")return;$.steps===0&&(p=0);let _=[O],W=j=>{_.length+$.steps<yi&&_.push(j)};for(;_.length>0&&$.steps<yi;){$.steps++;let j=_.shift();if(!j||j.node<0||j.node>=i.length)continue;let X=j.node,D=i[X];if(!D)continue;let Y=j.socket||"in",te=G(D),se=(V,ee=void 0)=>H(X,V,ee,new Set),le=(V="out")=>{let ee=D.flows?.[V];ee&&W(ee)};switch(te){case"flow/branch":le(ut(se("condition",!1))?"true":"false");break;case"flow/sequence":for(let V of Object.keys(D.flows||{}).sort((ee,R)=>Number(ee)-Number(R)||ee.localeCompare(R)))le(V);break;case"flow/switch":{let V=D.flows?.[String(se("selection",se("value",0)))]??D.flows?.default;V&&W(V);break}case"flow/for":{let V=Math.trunc(fe(se("startIndex",0))),ee=Math.trunc(fe(se("endIndex",0))),R=Math.max(1,Math.trunc(fe(se("step",1),1))),A=D.flows?.body;if(A&&ee>V&&y<Ql){let N=Math.min(Math.ceil((ee-V)/R),yi);y++;try{for(let U=0;U<N&&$.steps<yi;U++)T(X,"index",V+U*R),ue(A,$)}finally{y--}}let L=D.flows?.completed??D.flows?.out;L&&W(L);break}case"flow/doN":{let V=Y==="reset"?0:(u.get(X)||0)+1;if(u.set(X,V),T(X,"currentCount",V),T(X,"count",V),Y!=="reset"){let ee=Math.trunc(fe(se("n",_e(D,"stopIterations")??_e(D,"n")??1),1));V<=ee&&le()}break}case"flow/multiGate":{if(Y==="reset"){c.set(X,0);break}let V=Object.keys(D.flows||{}).sort();if(!V.length)break;let ee=_e(D,"isRandom")?Math.floor(Math.random()*V.length):c.get(X)||0;ee<V.length&&(le(V[ee]),c.set(X,_e(D,"isLoop")!==!1?(ee+1)%V.length:ee+1));break}case"flow/waitAll":{if(Y==="reset"){h.delete(X);break}let V=h.get(X);V||h.set(X,V=new Set),V.add(Y),V.size>=Math.max(1,Math.trunc(Number(_e(D,"inputFlows")??2)||2))&&(V.clear(),le("out"),le("completed"));break}case"flow/throttle":{if(Y==="reset"){m.delete(X);break}let V=Math.max(0,fe(se("duration",0))),ee=m.get(X);ee===void 0||b-ee>=V?(m.set(X,b),T(X,"lastRemainingTime",0),le()):T(X,"lastRemainingTime",Math.max(0,V-(b-ee)));break}case"flow/delay":case"flow/setDelay":{if(Y==="cancel"){for(let A=f.length-1;A>=0;A--)f[A].nodeIdx===X&&f.splice(A,1);T(X,"lastDelayIndex",-1);break}let V=Math.max(0,fe(se("duration",_e(D,"duration")??0))),ee=D.flows?.done??D.flows?.out;if(V<=0){T(X,"lastDelayIndex",-1),ee&&W(ee);break}f.length>=Kl&&f.shift();let R=x++;T(X,"lastDelayIndex",R),f.push({id:R,nodeIdx:X,rem:V,done:ee}),te==="flow/setDelay"&&D.flows?.out&&D.flows?.done&&le("out");break}case"flow/cancelDelay":{let V=Math.trunc(fe(se("delayIndex",-1),-1));if(V<0)f.length=0;else for(let ee=f.length-1;ee>=0;ee--)f[ee].id===V&&f.splice(ee,1);le();break}case"variable/set":E(_e(D,"variable")??_e(D,"id"),se("value")),le();break;case"variable/interpolate":{let V=_e(D,"variable")??_e(D,"id"),ee=se("value",se("target")),R=Math.max(0,fe(se("duration",_e(D,"duration")??.3),.3));V!==void 0&&ee!==void 0&&w({key:`var:${String(V)}`,varKey:V,from:it(se("from")??o.get(V)??0),to:it(ee),dur:R,elapsed:0,quat:!1,linear:_e(D,"easing")==="linear",done:D.flows?.done}),le();break}case"pointer/set":{let V=I(X,D),ee=se("value");V&&ee!==void 0&&(k(`ptr:${V}`),oe(V,ee)),le();break}case"pointer/interpolate":{let V=I(X,D),ee=se("value",se("target")),R=Math.max(0,fe(se("duration",_e(D,"duration")??.3),.3));if(V&&ee!==void 0){let A=se("from")??ie(V);A!==void 0&&(R<=0?(oe(V,ee),le("done")):w({key:`ptr:${V}`,ptr:V,from:it(A),to:it(ee),dur:R,elapsed:0,quat:V.endsWith("/rotation"),linear:_e(D,"easing")==="linear",done:D.flows?.done}))}le();break}case"animation/start":{let V=se("animation")??_e(D,"animation")??_e(D,"clipName"),ee=typeof V=="number"?e?.animations?.[V]?.name??t?.animations?.[V]?.name:typeof V=="string"?V:void 0;e?.playAnimation?.(ee),F=!0,le();break}case"animation/stop":case"animation/resetAt":e?.pauseAnimation?.(),te==="animation/resetAt"&&e?.evaluateAnimation?.(fe(se("time",0))),F=!0,le();break;case"event/send":case"customEvent/send":{let V=S(_e(D,"event")??_e(D,"id")),ee={};for(let R of Object.keys(D.values||{}))wt.has(R)||(ee[R]=se(R));V&&(typeof CustomEvent<"u"&&typeof e?.container?.dispatchEvent=="function"&&e.container.dispatchEvent(new CustomEvent("interactivityEvent",{bubbles:!0,composed:!0,detail:{id:V,values:ee}})),he(V,ee,$)),le();break}default:le();break}}};this.readScenePointer=ie,this.writeScenePointer=oe,this.fireOnStart=()=>{i.forEach(O=>{G(O)==="event/onStart"&&ue(O.flows?.out)}),z()},this.fireOnSelect=O=>{if(!O)return;let $=typeof O.meshIndex=="number"?O.meshIndex:-1,_=typeof O.nodeIndex=="number"?O.nodeIndex:e?.meshes?.[$]?.nodeIndex??-1;i.forEach((W,j)=>{if(!/^(pointer|event|scene)\/onSelect$/.test(G(W)))return;let X=_e(W,"nodeIndex")??_e(W,"node")??H(j,"nodeIndex",void 0,new Set),D=_e(W,"meshName");if(typeof D=="string"&&D?O.meshName===D:X==null||Number(X)<0||Number.isNaN(Number(X))||B(_,Math.trunc(Number(X)))){if(T(j,"nodeIndex",_),T(j,"meshIndex",$),Array.isArray(O.hitPoint)){let Y=[fe(O.hitPoint[0]),fe(O.hitPoint[1]),fe(O.hitPoint[2])];T(j,"hitPoint",Y),T(j,"point",Y),T(j,"intersectionPoint",Y)}if(Array.isArray(O.normal)){let Y=[fe(O.normal[0]),fe(O.normal[1],1),fe(O.normal[2])];T(j,"normal",Y),T(j,"hitNormal",Y)}typeof O.distance=="number"&&T(j,"distance",O.distance),ue(W.flows?.out)}}),z()},this.receiveCustomEvent=(O,$={})=>he(O,$,{steps:0});function he(O,$,_){if(!(v>=Yl)){v++;try{let W=S(O);i.forEach((j,X)=>{if(!/^(customE|e)vent\/receive$/.test(G(j)))return;let D=_e(j,"event")??_e(j,"id");if(!(S(D)!==W&&String(D)!==String(O))){for(let[Y,te]of Object.entries($))wt.has(Y)||T(X,Y,it(te));ue(j.flows?.out,_)}}),z()}finally{v--}}}this.tick=O=>{if(!Number.isFinite(O)||O<0)return;let $=Math.min(O,.25);b+=$,i.forEach((W,j)=>{G(W)==="event/onTick"&&(T(j,"timeDelta",$),T(j,"dt",$),T(j,"timeElapsed",b),ue(W.flows?.out))});let _=[];for(let W=d.length-1;W>=0;W--){let j=d[W];j.elapsed+=$;let X=j.dur>1e-6?Ut(j.elapsed/j.dur):1,D=j.linear?X:X*X*(3-2*X),Y=to(j.from,j.to,D,j.quat);j.ptr?oe(j.ptr,Y):j.varKey!==void 0&&E(j.varKey,Y),X>=1&&(d.splice(W,1),j.done&&_.push(j.done))}for(let W=f.length-1;W>=0;W--){let j=f[W];j.rem-=$,j.rem<=0&&(f.splice(W,1),j.done&&_.push(j.done))}for(let W of _)ue(W);z()},this.dispose=()=>{d.length=0,f.length=0,o.clear(),a.clear(),u.clear(),h.clear(),m.clear(),c.clear()}}},dt=new WeakMap,vi=new WeakMap;function eu(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||Vs().some(o=>o.name==="xr-live-head-follow")||(typeof e.getAutoRotate=="function"?e.getAutoRotate():e.autoRotate)===!1)return;let r=e.gltf,i=r?.nodes;if(!Array.isArray(i)||i.length===0)return;let n=Math.min(t,.1),s=(vi.get(e)||0)+n,l=!1;for(let o=0;o<i.length;o++){let a=i[o],u=Ml(a?.extras?.xr?.orbit);if(!u)continue;let h=0,m=0,c=0;if(Array.isArray(u.target))h=u.target[0],m=u.target[1],c=u.target[2];else if(typeof u.target=="string"&&u.target!=="head"){let b=i.find(v=>v?.name===u.target);Array.isArray(b?.translation)&&(h=fe(b.translation[0]),m=fe(b.translation[1]),c=fe(b.translation[2]))}let d=u.phase+u.speed*s,f=h+Math.cos(d)*u.radius,g=m+u.height,x=c+Math.sin(d)*u.radius;if(a.translation=[f,g,x],u.faceCenter){let b=Math.atan2(h-f,c-x);a.rotation=[0,Math.sin(b*.5),0,Math.cos(b*.5)]}l=!0}if(l){vi.set(e,s);let o=Cr(r);e.worldMatrices=o;for(let a of e.meshes||[])a.nodeIndex>=0&&a.nodeIndex<o.length&&(a.transform.set(o[a.nodeIndex]),Ye(a.normalMatrix,a.transform))}}function Mi(e){if(!(!e||typeof e!="object"))return dt.get(e)||dt.get(e.viewer)||dt.get(e._view)}function bs(e,t,r){let i=Mi(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var xs={name:"khr-interactivity",sendInteractivityEvent:bs,getInteractivityVM:Mi,onLoadModel(e,t){if(!e||typeof e!="object")return;dt.get(e)?.dispose(),dt.delete(e),vi.delete(e);let r=t?.extensions?.KHR_interactivity,i=Array.isArray(r?.graphs)?r.graphs[r.graph??0]:r;if(!i||!Array.isArray(i.nodes))return;let n=new ys(e,t,i);dt.set(e,n),n.fireOnStart()},onMeshSelect(e,t){dt.get(e)?.fireOnSelect(t)},onUpdate(e,t){dt.get(e)?.tick(t),eu(e,t)},onDestroy(e,t){dt.get(t)?.dispose(),dt.delete(t),vi.delete(t)}},Tr=new Map,wi=new WeakMap;function io(e,t){Tr.set(e,t)}var vs={name:"materials",onContextRestored(e){wi.delete(e)},onBuildPrimitiveVAO(e,t,r,i,n){return(((i?.materials&&r.material!==void 0?i.materials[r.material]:null)?.extensions||{}).KHR_materials_transmission?.transmissionFactor??0)>0?{isTransmissive:!0}:null},onBeforeTransmissivePass(e,t){let r=wi.get(e);r||(r=e.createTexture(),wi.set(e,r));let i=Math.max(1,t.canvas.width),n=Math.max(1,t.canvas.height);e.activeTexture(33990),e.bindTexture(3553,r),e.copyTexImage2D(3553,0,6408,0,0,i,n,0),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9987),e.texParameteri(3553,10240,9729),e.generateMipmap(3553)},onResolveShader(e,t,r,i){if(!t)return null;if(t.name&&Tr.has(t.name)){let f=Tr.get(t.name);return{vs:f.vs||r,fs:f.fs||i}}let n=t.extensions||{},s=n.KHR_materials_clearcoat,l=n.KHR_materials_sheen,o=!!n.KHR_materials_transmission,a=!!n.KHR_materials_ior,u=n.KHR_materials_iridescence;if(!s&&!l&&!n.KHR_materials_unlit&&!o&&!n.KHR_materials_volume&&!a&&!n.KHR_materials_dispersion&&!u)return null;if(n.KHR_materials_unlit)return{vs:r,fs:i.replace("fragColor=vec4(color,outAlpha);","fragColor=vec4(base.rgb,outAlpha);").replace("fragColor=vec4(color,base.a);","fragColor=vec4(base.rgb,base.a);")};let h=i;if(o){let f=h.includes("uniform vec2 uViewportSize;")?"":`uniform vec2 uViewportSize;
416
- `;h=h.replace("out vec4 fragColor;",`uniform sampler2D uTransmissionTex;
417
- ${f}out vec4 fragColor;`)}let m=(f,g,x=0,b=1e6,v=3)=>{let p=Number(f);return(Number.isFinite(p)?Math.min(b,Math.max(x,p)):g).toFixed(v)},c=Number(n.KHR_materials_ior?.ior??1.5),d=Number.isFinite(c)?Math.min(10,Math.max(1,c)):1.5;if(a){let f=Math.pow((d-1)/(d+1),2);h=h.replace("vec3 F0=mix(vec3(0.04),base.rgb,metallic);",`vec3 F0=mix(vec3(${m(f,.04,0,1,4)}),base.rgb,metallic);`)}if(u){let f=m(u.iridescenceFactor,1,0,1),g=m(u.iridescenceIor,1.3,1,10);h=h.replace("vec3 F=F_SchlickRoughness(F0,roughness,NoV);",`vec3 F=F_SchlickRoughness(F0,roughness,NoV);vec3 iridColor=.5+.5*cos(800.*${g}*NoV*vec3(.015,.018,.022));F=mix(F,iridColor,${f}*pow(1.-NoV,2.));`)}if(o){let f=m(n.KHR_materials_transmission?.transmissionFactor,1,0,1),g=n.KHR_materials_volume||{},x=m(g.thicknessFactor,.5,0,1e4),b=m(g.attenuationDistance,1,.001,1e6),v=Array.isArray(g.attenuationColor)?g.attenuationColor:[1,1,1],p=m(n.KHR_materials_dispersion?.dispersion,0,0,10);h=h.replace("vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;",`vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
418
- vec2 sUV=gl_FragCoord.xy/max(uViewportSize,vec2(1.));float iorB=${m(d,1.5,1,10)},dV=${p},tV=${x},lod=clamp(roughness*5.,0.,5.),sc=.06*(1.+tV);
463
+ }`),{vs:r,fs:n}},onBeforeDrawPrimitive(e,t,r,i,n,a){let s=Ou.get(e),o=e.getUniformLocation(t,"uHasSH");if(s&&s.length>=27){o&&e.uniform1i(o,1);let l=e.getUniformLocation(t,"uSH");l&&e.uniform3fv(l,s)}else o&&e.uniform1i(o,0)},onAttributeChanged(e,t,r,i){t==="environment-image"&&e.viewer?this.setEnvironmentImage?.(e.viewer,i):t==="skybox-image"&&e.viewer&&this.setSkyboxImage?.(e.viewer,i)}},qu=new WeakMap;function Wu(e,t){let r=t||e.viewer;if(!r||typeof r.projectPointToScreen!="function")return;let i=e.mockHotspots||e.querySelectorAll('[slot^="hotspot-"], [data-position]');for(let n=0;n<i.length;n++){let a=i[n],s=a.getAttribute("data-position");if(!s)continue;let o=s.trim().split(/\s+/).map(m=>parseFloat(m.replace(/m$/,"")));if(o.length<3||o.some(isNaN))continue;let l=a.getAttribute("data-normal"),c;if(l){let m=l.trim().split(/\s+/).map(h=>parseFloat(h));m.length>=3&&!m.some(isNaN)&&(c=[m[0],m[1],m[2]])}let f=r.projectPointToScreen([o[0],o[1],o[2]],c);a.style.position="absolute",a.style.left="0",a.style.top="0",a.style.transform=`translate(-50%, -50%) translate3d(${f.x}px, ${f.y}px, 0)`,a.style.zIndex="3",f.visible?(a.style.opacity="1",a.style.pointerEvents="auto",a.removeAttribute("data-occluded")):(a.style.opacity="0",a.style.pointerEvents="none",a.setAttribute("data-occluded",""))}}var Ku={name:"hotspots",updateHotspotsForElement:Wu,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{Wu(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),qu.set(e,t)},onCameraChange(e,t){t&&Wu(t,e)},onElementDisconnected(e){let t=qu.get(e);t&&(t.disconnect(),qu.delete(e))}},im=1024,Xu=256,Es=2048,_1=128,S1=64,A1=16,T1=1e4,P1=8,ti=new Set(["__proto__","constructor","prototype"]),nm={neg:e=>-e,abs:Math.abs,sign:Math.sign,floor:Math.floor,ceil:Math.ceil,round:Math.round,trunc:Math.trunc,fract:e=>e-Math.floor(e),sqrt:e=>Math.sqrt(Math.max(0,e)),cbrt:Math.cbrt,exp:Math.exp,log:e=>e>0?Math.log(e):0,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:e=>Math.asin(Math.max(-1,Math.min(1,e))),acos:e=>Math.acos(Math.max(-1,Math.min(1,e))),atan:Math.atan,rad:e=>e*Math.PI/180,deg:e=>e*180/Math.PI,saturate:e=>Math.max(0,Math.min(1,e))},am={add:(e,t)=>e+t,sub:(e,t)=>e-t,mul:(e,t)=>e*t,div:(e,t)=>Math.abs(t)<1e-12?0:e/t,rem:(e,t)=>Math.abs(t)<1e-12?0:e%t,mod:(e,t)=>Math.abs(t)<1e-12?0:e%t,min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2},Ls={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},Rs=(e,t)=>e!==null&&typeof e=="object"&&!ti.has(t)&&Object.prototype.hasOwnProperty.call(e,t),Pr=e=>Array.isArray(e)?[...e]:e,sm=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&Rs(e,"value")?e.value:e,_t=(e,t)=>Rs(e.configuration,t)?sm(e.configuration[t]):void 0,Ge=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},Li=e=>Math.max(0,Math.min(1,e)),Dr=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function Yn(e){if(typeof e!="string"||!e.startsWith("/"))return null;let t=[];for(let r of e.slice(1).split("/")){let i=r.replace(/~1/g,"/").replace(/~0/g,"~");if(!i||ti.has(i)||ti.has(r))return null;t.push(i)}return{segments:t}}var tn=(e,t)=>{if(e===void 0||!/^\d+$/.test(e))return-1;let r=Number(e);return Number.isSafeInteger(r)&&r>=0&&r<t?r:-1},om=e=>{let t=Ge(e[0]),r=Ge(e[1]),i=Ge(e[2]),n=Ge(e[3],1),a=Math.hypot(t,r,i,n);return a>1e-8?[t/a,r/a,i/a,n/a]:[0,0,0,1]},lm=(e,t,r,i)=>{if(typeof e=="number"&&typeof t=="number")return e+(t-e)*r;if(Array.isArray(e)&&Array.isArray(t)){if(i&&e.length===4&&t.length===4){let n=[0,0,0,1];return Nu(n,om(e),om(t),r),n}return e.slice(0,t.length).map((n,a)=>n+(t[a]-n)*r)}return r>=.5?t:e},Yu=(e,t,r)=>Array.isArray(e)&&Array.isArray(t)?e.slice(0,t.length).map((i,n)=>r(Ge(i),Ge(t[n]))):Array.isArray(e)?e.map(i=>r(Ge(i),Ge(t))):Array.isArray(t)?t.map(i=>r(Ge(e),Ge(i))):r(Ge(e),Ge(t)),N1=(e,t)=>Array.isArray(e)?e.map(r=>t(Ge(r))):t(Ge(e)),um=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((r,i)=>Math.abs(r-t[i])<=1e-6):e===t,Qu=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>im)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${im})`);let n=Array.isArray(r.variables)?r.variables:[];if(n.length>Xu)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${Xu})`);let a=Array.isArray(r.declarations)?r.declarations:[],s=Array.isArray(r.events)?r.events:[],o=new Map,l=new Map,c=new Map,f=new Map,m=new Map,h=new Map,p=[],g=[],x=new Map,v=1,y=0,A=0,b=0,w=0,S=!1,E=!1,N=!1;n.forEach((H,te)=>{if(!H||typeof H!="object")return;let Z=Pr(sm(H.value));o.set(te,Z);let ae=H.id??H.name;typeof ae=="string"&&ae&&!ti.has(ae)&&o.set(ae,Z)}),(t?.nodes||[]).forEach((H,te)=>{for(let Z of H?.children||[])typeof Z=="number"&&x.set(Z,te)});let C=H=>H.op||typeof H.declaration=="number"&&a[H.declaration]?.op||"",_=(H,te,Z)=>{if(ti.has(te))return;let ae=l.get(H);ae||l.set(H,ae=Object.create(null)),ae[te]=Z},P=(H,te)=>{if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&ti.has(H)||!o.has(H)&&o.size>=Xu*2)return;let Z=Pr(te);if(o.set(H,Z),typeof H=="number"){let ae=n[H]?.id??n[H]?.name;typeof ae=="string"&&!ti.has(ae)&&o.set(ae,Z)}},R=H=>typeof H=="number"?s[H]?.id??String(H):typeof H=="string"?/^\d+$/.test(H)&&s[Number(H)]?.id?s[Number(H)].id:H:"",I=(H,te)=>{for(let Z=H,ae=0;Z!==void 0&&Z>=0&&ae<128;Z=x.get(Z),ae++)if(Z===te)return!0;return!1},F=H=>{for(let te=p.length-1;te>=0;te--)p[te].key===H&&p.splice(te,1)},V=H=>{F(H.key),p.length>=_1&&p.shift(),p.push(H)},Y=H=>{let te=Yn(H)?.segments;if(te){if(te[0]==="nodes"&&Array.isArray(t?.nodes)){let Z=t.nodes[tn(te[1],t.nodes.length)];if(!Z)return;let ae=te[2];if(ae in Ls){let ie=Ls[ae],de=Z[ae]||ie;return ie.map((me,Se)=>Ge(de[Se],me))}if(ae==="weights"){let ie=Array.isArray(Z.weights)?Z.weights:[0],de=te.length===4?tn(te[3],64):-2;return de===-2?ie.map(me=>Ge(me)):de>=0?Ge(ie[de]):void 0}if(ae==="visible"||ae==="extensions"&&te[3]==="KHR_node_visibility"&&te[4]==="visible")return Z.extensions?.KHR_node_visibility?.visible??Z.visible??!0}else if(te[0]==="materials"&&Array.isArray(t?.materials)){let Z=t.materials[tn(te[1],t.materials.length)];if(!Z)return;let ae=Z.pbrMetallicRoughness||{};if(te[2]==="pbrMetallicRoughness"){if(te[3]==="baseColorFactor"){let ie=ae.baseColorFactor||[1,1,1,1];return[Ge(ie[0],1),Ge(ie[1],1),Ge(ie[2],1),Ge(ie[3],1)]}if(te[3]==="metallicFactor"||te[3]==="roughnessFactor")return Ge(ae[te[3]],1)}if(te[2]==="emissiveFactor"){let ie=Z.emissiveFactor||[0,0,0];return[Ge(ie[0]),Ge(ie[1]),Ge(ie[2])]}if(te[2]==="alphaCutoff")return Ge(Z.alphaCutoff,.5)}}},J=(H,te)=>{let Z=Yn(H)?.segments;if(!Z)return!1;if(Z[0]==="nodes"&&Array.isArray(t?.nodes)){let ae=tn(Z[1],t.nodes.length),ie=t.nodes[ae];if(!ie)return!1;let de=Z[2];if(de in Ls&&Array.isArray(te)){let me=Ls[de];if(te.length<me.length)return!1;let Se=me.map((_e,Le)=>Ge(te[Le],_e));if(de==="rotation"){let _e=Math.hypot(...Se);Se=_e>1e-8?Se.map(Le=>Le/_e):[0,0,0,1]}ie[de]=Se,delete ie.matrix;let ke=e?.initialNodeTransforms?.[ae];return ke&&(ke[de[0]]=[...Se]),S=!0,!0}if(de==="weights"){Array.isArray(ie.weights)||(ie.weights=[]);let me=(Se,ke)=>{for(let _e of e?.meshes||[])if(_e.nodeIndex===ae)for(let Le of _e.primitives||[])Le.pluginData?.morph?.weights&&(Le.pluginData.morph.weights[Se]=ke)};if(Z.length===4){let Se=tn(Z[3],64);if(Se<0)return!1;me(Se,ie.weights[Se]=Ge(te))}else if(Array.isArray(te))ie.weights=te.slice(0,64).map(Se=>Ge(Se)),ie.weights.forEach((Se,ke)=>me(ke,Se));else return!1;return N=!0,!0}if(de==="visible"||de==="extensions"&&Z[3]==="KHR_node_visibility"&&Z[4]==="visible"){let me=Dr(te);return ie.visible=me,(!ie.extensions||typeof ie.extensions!="object")&&(ie.extensions={}),ie.extensions.KHR_node_visibility={visible:me},E=!0,!0}}else if(Z[0]==="materials"&&Array.isArray(t?.materials)){let ae=tn(Z[1],t.materials.length),ie=t.materials[ae];if(!ie)return!1;let de=ie.pbrMetallicRoughness||(ie.pbrMetallicRoughness={}),me=Se=>{for(let ke of e?.meshes||[])for(let _e of ke.primitives||[])(_e.materialIndex??0)===ae&&Se(_e)};if(Z[2]==="pbrMetallicRoughness"){if(Z[3]==="baseColorFactor"&&Array.isArray(te)&&te.length>=3){let Se=[Li(Ge(te[0],1)),Li(Ge(te[1],1)),Li(Ge(te[2],1)),te[3]!==void 0?Li(Ge(te[3],1)):de.baseColorFactor?.[3]??1];return de.baseColorFactor=Se,me(ke=>ke.baseColor=[...Se]),N=!0}if(Z[3]==="metallicFactor"||Z[3]==="roughnessFactor"){let Se=Z[3]==="metallicFactor",ke=Li(Ge(te,Se?0:.5));return de[Z[3]]=ke,me(_e=>_e[Se?"metallic":"roughness"]=ke),N=!0}}if(Z[2]==="emissiveFactor"&&Array.isArray(te)&&te.length>=3)return ie.emissiveFactor=[0,1,2].map(Se=>Math.max(0,Ge(te[Se]))),N=!0;if(Z[2]==="alphaCutoff")return ie.alphaCutoff=Li(Ge(te,.5)),N=!0}return!1},re=(H,te,Z=new Set)=>{let ae=_t(te,"pointer");if(typeof ae!="string"||!ae.startsWith("/"))return null;let ie=ae.replace(/\{([a-zA-Z0-9_]+)\}/g,(de,me)=>{let Se=Math.trunc(Number(Q(H,me,void 0,Z)??_t(te,me)));return Number.isSafeInteger(Se)&&Se>=0?String(Se):"-1"});return Yn(ie)?ie:null},Q=(H,te,Z,ae)=>{let ie=i[H]?.values;if(!Rs(ie,te))return Z;let de=ie[te];if(de==null)return Z;if(typeof de!="object"||Array.isArray(de))return Pr(de);let me=de;return typeof me.node=="number"?ee(me.node,me.socket||"value",ae):Rs(me,"value")?Pr(me.value):Z},ee=(H,te,Z)=>{if(H<0||H>=i.length||Z.has(H)||Z.size>128||++b>T1)return;let ae=i[H],ie=C(ae);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(ie))return Pr(l.get(H)?.[te]);Z.add(H);try{let de=(me,Se=0)=>Q(H,me,Se,Z);if(ie==="variable/get"){let me=_t(ae,"variable")??_t(ae,"id");return typeof me=="number"||typeof me=="string"?Pr(o.get(me)):void 0}if(ie==="pointer/get"){let me=re(H,ae,Z);return me?Y(me):void 0}if(ie.startsWith("math/")){let me=ie.slice(5);if(me in nm)return N1(de("a"),nm[me]);if(me in am){let Se=/^(mul|div|rem|mod|pow)$/.test(me)?1:0;return Yu(de("a",me==="mul"?1:0),de("b",Se),am[me])}if(me==="pi")return Math.PI;if(me==="e")return Math.E;if(me==="random")return Math.random();if(me==="clamp")return Yu(Yu(de("a"),de("b",de("min",0)),Math.max),de("c",de("max",1)),Math.min);if(me==="mix"||me==="quatSlerp")return lm(de("a",0),de("b",1),Ge(de("c",de("t",.5)),.5),me==="quatSlerp");if(me==="dot"){let Se=de("a"),ke=de("b");return Array.isArray(Se)&&Array.isArray(ke)?Se.reduce((_e,Le,ne)=>_e+(Le||0)*(ke[ne]||0),0):Ge(Se)*Ge(ke)}if(me==="cross"){let Se=de("a",[0,0,0]),ke=de("b",[0,0,0]);return Array.isArray(Se)&&Array.isArray(ke)?[(Se[1]||0)*(ke[2]||0)-(Se[2]||0)*(ke[1]||0),(Se[2]||0)*(ke[0]||0)-(Se[0]||0)*(ke[2]||0),(Se[0]||0)*(ke[1]||0)-(Se[1]||0)*(ke[0]||0)]:[0,0,0]}if(me==="length"){let Se=de("a");return Array.isArray(Se)?Math.hypot(...Se):Math.abs(Ge(Se))}if(me==="distance"){let Se=de("a"),ke=de("b");return Array.isArray(Se)&&Array.isArray(ke)?Math.hypot(...Se.map((_e,Le)=>(_e||0)-(ke[Le]||0))):Math.abs(Ge(Se)-Ge(ke))}if(me==="normalize"){let Se=de("a");if(!Array.isArray(Se))return Ge(Se)>=0?1:-1;let ke=Math.hypot(...Se);return ke>1e-8?Se.map(_e=>_e/ke):Se.map(()=>0)}if(me.startsWith("combine"))return["a","b","c","d"].slice(0,Number(me[7])||2).map(Se=>Ge(de(Se)));if(me.startsWith("extract")){let Se=de("a");return Array.isArray(Se)?Se[te==="0"||te==="x"?0:te==="1"||te==="y"?1:te==="2"||te==="z"?2:3]??0:0}if(me==="eq")return um(de("a"),de("b"));if(me==="ne")return!um(de("a"),de("b"));if(me==="lt")return Ge(de("a"))<Ge(de("b"));if(me==="le")return Ge(de("a"))<=Ge(de("b"));if(me==="gt")return Ge(de("a"))>Ge(de("b"));if(me==="ge")return Ge(de("a"))>=Ge(de("b"));if(me==="isNaN")return Number.isNaN(Number(de("a")));if(me==="isInf"){let Se=Number(de("a"));return!Number.isFinite(Se)&&!Number.isNaN(Se)}return me==="and"?Dr(de("a",!1))&&Dr(de("b",!1)):me==="or"?Dr(de("a",!1))||Dr(de("b",!1)):me==="xor"?Dr(de("a",!1))!==Dr(de("b",!1)):me==="not"?!Dr(de("a",!1)):me==="select"?Pr(Dr(de("condition",!1))?de("a"):de("b")):void 0}return ie==="type/boolToInt"||ie==="type/boolToFloat"?Dr(de("a",!1))?1:0:ie==="type/intToBool"||ie==="type/floatToBool"?Ge(de("a",0))!==0:ie==="type/intToFloat"?Ge(de("a",0)):ie==="type/floatToInt"?Math.trunc(Ge(de("a",0))):void 0}finally{Z.delete(H)}},k=()=>{if(S){S=!1,N=!0;let H=An(t);if(e){e.worldMatrices=H;for(let te of e.meshes||[])te.nodeIndex>=0&&te.nodeIndex<H.length&&(te.transform.set(H[te.nodeIndex]),rr(te.normalMatrix,te.transform))}}if(E){E=!1,N=!0;let H=t?.nodes;if(Array.isArray(e?.meshes)&&Array.isArray(H))for(let te of e.meshes){let Z=!0;for(let ae=te.nodeIndex,ie=0;ae!==void 0&&ae>=0&&ie<128;ae=x.get(ae),ie++){let de=H[ae];if(de?.visible===!1||de?.extensions?.KHR_node_visibility?.visible===!1){Z=!1;break}}te.visible=Z}}N&&(N=!1,e?.render?.())},G=(H,te={steps:0})=>{if(!H||typeof H.node!="number")return;te.steps===0&&(b=0);let Z=[H],ae=ie=>{Z.length+te.steps<Es&&Z.push(ie)};for(;Z.length>0&&te.steps<Es;){te.steps++;let ie=Z.shift();if(!ie||ie.node<0||ie.node>=i.length)continue;let de=ie.node,me=i[de];if(!me)continue;let Se=ie.socket||"in",ke=C(me),_e=(ne,Re=void 0)=>Q(de,ne,Re,new Set),Le=(ne="out")=>{let Re=me.flows?.[ne];Re&&ae(Re)};switch(ke){case"flow/branch":Le(Dr(_e("condition",!1))?"true":"false");break;case"flow/sequence":for(let ne of Object.keys(me.flows||{}).sort((Re,W)=>Number(Re)-Number(W)||Re.localeCompare(W)))Le(ne);break;case"flow/switch":{let ne=me.flows?.[String(_e("selection",_e("value",0)))]??me.flows?.default;ne&&ae(ne);break}case"flow/for":{let ne=Math.trunc(Ge(_e("startIndex",0))),Re=Math.trunc(Ge(_e("endIndex",0))),W=Math.max(1,Math.trunc(Ge(_e("step",1),1))),D=me.flows?.body;if(D&&Re>ne&&w<P1){let O=Math.min(Math.ceil((Re-ne)/W),Es);w++;try{for(let X=0;X<O&&te.steps<Es;X++)_(de,"index",ne+X*W),G(D,te)}finally{w--}}let z=me.flows?.completed??me.flows?.out;z&&ae(z);break}case"flow/doN":{let ne=Se==="reset"?0:(c.get(de)||0)+1;if(c.set(de,ne),_(de,"currentCount",ne),_(de,"count",ne),Se!=="reset"){let Re=Math.trunc(Ge(_e("n",_t(me,"stopIterations")??_t(me,"n")??1),1));ne<=Re&&Le()}break}case"flow/multiGate":{if(Se==="reset"){h.set(de,0);break}let ne=Object.keys(me.flows||{}).sort();if(!ne.length)break;let Re=_t(me,"isRandom")?Math.floor(Math.random()*ne.length):h.get(de)||0;Re<ne.length&&(Le(ne[Re]),h.set(de,_t(me,"isLoop")!==!1?(Re+1)%ne.length:Re+1));break}case"flow/waitAll":{if(Se==="reset"){f.delete(de);break}let ne=f.get(de);ne||f.set(de,ne=new Set),ne.add(Se),ne.size>=Math.max(1,Math.trunc(Number(_t(me,"inputFlows")??2)||2))&&(ne.clear(),Le("out"),Le("completed"));break}case"flow/throttle":{if(Se==="reset"){m.delete(de);break}let ne=Math.max(0,Ge(_e("duration",0))),Re=m.get(de);Re===void 0||y-Re>=ne?(m.set(de,y),_(de,"lastRemainingTime",0),Le()):_(de,"lastRemainingTime",Math.max(0,ne-(y-Re)));break}case"flow/delay":case"flow/setDelay":{if(Se==="cancel"){for(let D=g.length-1;D>=0;D--)g[D].nodeIdx===de&&g.splice(D,1);_(de,"lastDelayIndex",-1);break}let ne=Math.max(0,Ge(_e("duration",_t(me,"duration")??0))),Re=me.flows?.done??me.flows?.out;if(ne<=0){_(de,"lastDelayIndex",-1),Re&&ae(Re);break}g.length>=S1&&g.shift();let W=v++;_(de,"lastDelayIndex",W),g.push({id:W,nodeIdx:de,rem:ne,done:Re}),ke==="flow/setDelay"&&me.flows?.out&&me.flows?.done&&Le("out");break}case"flow/cancelDelay":{let ne=Math.trunc(Ge(_e("delayIndex",-1),-1));if(ne<0)g.length=0;else for(let Re=g.length-1;Re>=0;Re--)g[Re].id===ne&&g.splice(Re,1);Le();break}case"variable/set":P(_t(me,"variable")??_t(me,"id"),_e("value")),Le();break;case"variable/interpolate":{let ne=_t(me,"variable")??_t(me,"id"),Re=_e("value",_e("target")),W=Math.max(0,Ge(_e("duration",_t(me,"duration")??.3),.3));ne!==void 0&&Re!==void 0&&V({key:`var:${String(ne)}`,varKey:ne,from:Pr(_e("from")??o.get(ne)??0),to:Pr(Re),dur:W,elapsed:0,quat:!1,linear:_t(me,"easing")==="linear",done:me.flows?.done}),Le();break}case"pointer/set":{let ne=re(de,me),Re=_e("value");ne&&Re!==void 0&&(F(`ptr:${ne}`),J(ne,Re)),Le();break}case"pointer/interpolate":{let ne=re(de,me),Re=_e("value",_e("target")),W=Math.max(0,Ge(_e("duration",_t(me,"duration")??.3),.3));if(ne&&Re!==void 0){let D=_e("from")??Y(ne);D!==void 0&&(W<=0?(J(ne,Re),Le("done")):V({key:`ptr:${ne}`,ptr:ne,from:Pr(D),to:Pr(Re),dur:W,elapsed:0,quat:ne.endsWith("/rotation"),linear:_t(me,"easing")==="linear",done:me.flows?.done}))}Le();break}case"animation/start":{let ne=_e("animation")??_t(me,"animation")??_t(me,"clipName"),Re=typeof ne=="number"?e?.animations?.[ne]?.name??t?.animations?.[ne]?.name:typeof ne=="string"?ne:void 0;e?.playAnimation?.(Re),N=!0,Le();break}case"animation/stop":case"animation/resetAt":e?.pauseAnimation?.(),ke==="animation/resetAt"&&e?.evaluateAnimation?.(Ge(_e("time",0))),N=!0,Le();break;case"event/send":case"customEvent/send":{let ne=R(_t(me,"event")??_t(me,"id")),Re={};for(let W of Object.keys(me.values||{}))ti.has(W)||(Re[W]=_e(W));ne&&(typeof CustomEvent<"u"&&typeof e?.container?.dispatchEvent=="function"&&e.container.dispatchEvent(new CustomEvent("interactivityEvent",{bubbles:!0,composed:!0,detail:{id:ne,values:Re}})),q(ne,Re,te)),Le();break}default:Le();break}}};this.readScenePointer=Y,this.writeScenePointer=J,this.fireOnStart=()=>{i.forEach(H=>{C(H)==="event/onStart"&&G(H.flows?.out)}),k()},this.fireOnSelect=H=>{if(!H)return;let te=typeof H.meshIndex=="number"?H.meshIndex:-1,Z=typeof H.nodeIndex=="number"?H.nodeIndex:e?.meshes?.[te]?.nodeIndex??-1;i.forEach((ae,ie)=>{if(!/^(pointer|event|scene)\/onSelect$/.test(C(ae)))return;let de=_t(ae,"nodeIndex")??_t(ae,"node")??Q(ie,"nodeIndex",void 0,new Set),me=_t(ae,"meshName");if(typeof me=="string"&&me?H.meshName===me:de==null||Number(de)<0||Number.isNaN(Number(de))||I(Z,Math.trunc(Number(de)))){if(_(ie,"nodeIndex",Z),_(ie,"meshIndex",te),Array.isArray(H.hitPoint)){let Se=[Ge(H.hitPoint[0]),Ge(H.hitPoint[1]),Ge(H.hitPoint[2])];_(ie,"hitPoint",Se),_(ie,"point",Se),_(ie,"intersectionPoint",Se)}if(Array.isArray(H.normal)){let Se=[Ge(H.normal[0]),Ge(H.normal[1],1),Ge(H.normal[2])];_(ie,"normal",Se),_(ie,"hitNormal",Se)}typeof H.distance=="number"&&_(ie,"distance",H.distance),G(ae.flows?.out)}}),k()},this.receiveCustomEvent=(H,te={})=>q(H,te,{steps:0});function q(H,te,Z){if(!(A>=A1)){A++;try{let ae=R(H);i.forEach((ie,de)=>{if(!/^(customE|e)vent\/receive$/.test(C(ie)))return;let me=_t(ie,"event")??_t(ie,"id");if(!(R(me)!==ae&&String(me)!==String(H))){for(let[Se,ke]of Object.entries(te))ti.has(Se)||_(de,Se,Pr(ke));G(ie.flows?.out,Z)}}),k()}finally{A--}}}this.tick=H=>{if(!Number.isFinite(H)||H<0)return;let te=Math.min(H,.25);y+=te,i.forEach((ae,ie)=>{C(ae)==="event/onTick"&&(_(ie,"timeDelta",te),_(ie,"dt",te),_(ie,"timeElapsed",y),G(ae.flows?.out))});let Z=[];for(let ae=p.length-1;ae>=0;ae--){let ie=p[ae];ie.elapsed+=te;let de=ie.dur>1e-6?Li(ie.elapsed/ie.dur):1,me=ie.linear?de:de*de*(3-2*de),Se=lm(ie.from,ie.to,me,ie.quat);ie.ptr?J(ie.ptr,Se):ie.varKey!==void 0&&P(ie.varKey,Se),de>=1&&(p.splice(ae,1),ie.done&&Z.push(ie.done))}for(let ae=g.length-1;ae>=0;ae--){let ie=g[ae];ie.rem-=te,ie.rem<=0&&(g.splice(ae,1),ie.done&&Z.push(ie.done))}for(let ae of Z)G(ae);k()},this.dispose=()=>{p.length=0,g.length=0,o.clear(),l.clear(),c.clear(),f.clear(),m.clear(),h.clear()}}},Ur=new WeakMap,Is=new WeakMap;function C1(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||Wc().some(o=>o.name==="xr-live-head-follow")||(typeof e.getAutoRotate=="function"?e.getAutoRotate():e.autoRotate)===!1)return;let r=e.gltf,i=r?.nodes;if(!Array.isArray(i)||i.length===0)return;let n=Math.min(t,.1),a=(Is.get(e)||0)+n,s=!1;for(let o=0;o<i.length;o++){let l=i[o],c=Op(l?.extras?.xr?.orbit);if(!c)continue;let f=0,m=0,h=0;if(Array.isArray(c.target))f=c.target[0],m=c.target[1],h=c.target[2];else if(typeof c.target=="string"&&c.target!=="head"){let y=i.find(A=>A?.name===c.target);Array.isArray(y?.translation)&&(f=Ge(y.translation[0]),m=Ge(y.translation[1]),h=Ge(y.translation[2]))}let p=c.phase+c.speed*a,g=f+Math.cos(p)*c.radius,x=m+c.height,v=h+Math.sin(p)*c.radius;if(l.translation=[g,x,v],c.faceCenter){let y=Math.atan2(f-g,h-v);l.rotation=[0,Math.sin(y*.5),0,Math.cos(y*.5)]}s=!0}if(s){Is.set(e,a);let o=An(r);e.worldMatrices=o;for(let l of e.meshes||[])l.nodeIndex>=0&&l.nodeIndex<o.length&&(l.transform.set(o[l.nodeIndex]),rr(l.normalMatrix,l.transform))}}function $s(e){if(!(!e||typeof e!="object"))return Ur.get(e)||Ur.get(e.viewer)||Ur.get(e._view)}function Zu(e,t,r){let i=$s(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var Ju={name:"khr-interactivity",sendInteractivityEvent:Zu,getInteractivityVM:$s,onLoadModel(e,t){if(!e||typeof e!="object")return;Ur.get(e)?.dispose(),Ur.delete(e),Is.delete(e);let r=t?.extensions?.KHR_interactivity,i=Array.isArray(r?.graphs)?r.graphs[r.graph??0]:r;if(!i||!Array.isArray(i.nodes))return;let n=new Qu(e,t,i);Ur.set(e,n),n.fireOnStart()},onMeshSelect(e,t){Ur.get(e)?.fireOnSelect(t)},onUpdate(e,t){Ur.get(e)?.tick(t),C1(e,t)},onDestroy(e,t){Ur.get(t)?.dispose(),Ur.delete(t),Is.delete(t)}},Qn=new Map,Ds=new WeakMap;function cm(e,t){Qn.set(e,t)}var ec={name:"materials",onContextRestored(e){Ds.delete(e)},onBuildPrimitiveVAO(e,t,r,i,n){return(((i?.materials&&r.material!==void 0?i.materials[r.material]:null)?.extensions||{}).KHR_materials_transmission?.transmissionFactor??0)>0?{isTransmissive:!0}:null},onBeforeTransmissivePass(e,t){let r=Ds.get(e);r||(r=e.createTexture(),Ds.set(e,r));let i=Math.max(1,t.canvas.width),n=Math.max(1,t.canvas.height);e.activeTexture(33990),e.bindTexture(3553,r),e.copyTexImage2D(3553,0,6408,0,0,i,n,0),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9987),e.texParameteri(3553,10240,9729),e.generateMipmap(3553)},onResolveShader(e,t,r,i){if(!t)return null;if(t.name&&Qn.has(t.name)){let g=Qn.get(t.name);return{vs:g.vs||r,fs:g.fs||i}}let n=t.extensions||{},a=n.KHR_materials_clearcoat,s=n.KHR_materials_sheen,o=!!n.KHR_materials_transmission,l=!!n.KHR_materials_ior,c=n.KHR_materials_iridescence;if(!a&&!s&&!n.KHR_materials_unlit&&!o&&!n.KHR_materials_volume&&!l&&!n.KHR_materials_dispersion&&!c)return null;if(n.KHR_materials_unlit)return{vs:r,fs:i.replace("fragColor=vec4(color,outAlpha);","fragColor=vec4(base.rgb,outAlpha);").replace("fragColor=vec4(color,base.a);","fragColor=vec4(base.rgb,base.a);")};let f=i;if(o){let g=f.includes("uniform vec2 uViewportSize;")?"":`uniform vec2 uViewportSize;
464
+ `;f=f.replace("out vec4 fragColor;",`uniform sampler2D uTransmissionTex;
465
+ ${g}out vec4 fragColor;`)}let m=(g,x,v=0,y=1e6,A=3)=>{let b=Number(g);return(Number.isFinite(b)?Math.min(y,Math.max(v,b)):x).toFixed(A)},h=Number(n.KHR_materials_ior?.ior??1.5),p=Number.isFinite(h)?Math.min(10,Math.max(1,h)):1.5;if(l){let g=Math.pow((p-1)/(p+1),2);f=f.replace("vec3 F0=mix(vec3(0.04),base.rgb,metallic);",`vec3 F0=mix(vec3(${m(g,.04,0,1,4)}),base.rgb,metallic);`)}if(c){let g=m(c.iridescenceFactor,1,0,1),x=m(c.iridescenceIor,1.3,1,10);f=f.replace("vec3 F=F_SchlickRoughness(F0,roughness,NoV);",`vec3 F=F_SchlickRoughness(F0,roughness,NoV);vec3 iridColor=.5+.5*cos(800.*${x}*NoV*vec3(.015,.018,.022));F=mix(F,iridColor,${g}*pow(1.-NoV,2.));`)}if(o){let g=m(n.KHR_materials_transmission?.transmissionFactor,1,0,1),x=n.KHR_materials_volume||{},v=m(x.thicknessFactor,.5,0,1e4),y=m(x.attenuationDistance,1,.001,1e6),A=Array.isArray(x.attenuationColor)?x.attenuationColor:[1,1,1],b=m(n.KHR_materials_dispersion?.dispersion,0,0,10);f=f.replace("vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;",`vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
466
+ vec2 sUV=gl_FragCoord.xy/max(uViewportSize,vec2(1.));float iorB=${m(p,1.5,1,10)},dV=${b},tV=${v},lod=clamp(roughness*5.,0.,5.),sc=.06*(1.+tV);
419
467
  vec3 refractedR=refract(-V,N,1./(iorB-.02*dV)),rG=refract(-V,N,1./iorB),refractedB=refract(-V,N,1./(iorB+.02*dV));
420
468
  vec3 tr=vec3(textureLod(uTransmissionTex,clamp(sUV+refractedR.xy*sc,.001,.999),lod).r,textureLod(uTransmissionTex,clamp(sUV+rG.xy*sc,.001,.999),lod).g,textureLod(uTransmissionTex,clamp(sUV+refractedB.xy*sc,.001,.999),lod).b);
421
- vec3 aCol=vec3(${m(v[0],1,0,1)},${m(v[1],1,0,1)},${m(v[2],1,0,1)});
422
- vec3 volumeAtten=exp(-tV*(vec3(1.)-aCol)/max(${b},.001));
423
- diffuseIBL=mix(diffuseIBL,tr*volumeAtten*base.rgb,${f});`)}if(s&&!i.includes("uClearcoat")){let f=m(s.clearcoatFactor,1,0,1),g=m(s.clearcoatRoughnessFactor,0,0,1);h=h.replace("fragColor=vec4(color,base.a);",`vec3 ccF=F_SchlickRoughness(vec3(.04),${g},NoV)*${f};color=color*(vec3(1.)-ccF)+getStudioRadiance(R,${g})*ccF;fragColor=vec4(color,base.a);`)}if(l){let f=Array.isArray(l.sheenColorFactor)?l.sheenColorFactor:[1,1,1],g=`color+=vec3(${m(f[0],1,0,1)},${m(f[1],1,0,1)},${m(f[2],1,0,1)})*pow(1.-NoV,4.)*.5;`;h.includes("color=applyToneMapping(color,uToneMapping);")?h=h.replace("color=applyToneMapping(color,uToneMapping);",`${g}color=applyToneMapping(color,uToneMapping);`):h=h.replace("fragColor=vec4(color,base.a);",`${g}fragColor=vec4(color,base.a);`)}return{vs:r,fs:h}},onBeforeDrawPrimitive(e,t,r,i,n,s){let l=r.materialIndex;if(l!==void 0&&s?.materials){let o=s.materials[l];o?.name&&Tr.has(o.name)&&Tr.get(o.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let o=wi.get(e);if(o){e.activeTexture(33990),e.bindTexture(3553,o);let a=e.getUniformLocation(t,"uTransmissionTex");a&&e.uniform1i(a,6);let u=e.getUniformLocation(t,"uViewportSize");u&&e.uniform2f(u,e.drawingBufferWidth||1,e.drawingBufferHeight||1)}}}},no=64*1024*1024,so=128*1024*1024,tu=16777216;function ru(e){return(e>>>1^-(e&1))&255}function iu(e){return(e>>>1^-(e&1))&65535}function nu(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function ao(e){return(e<<1^e>>31)>>>0}function oo(e){if(e!==void 0&&e!=="NONE"&&e!=="OCTAHEDRAL"&&e!=="QUATERNION"&&e!=="EXPONENTIAL"&&e!=="COLOR")throw Re(`unknown filter "${String(e)}"`)}var we=Math.fround;function sr(e){return Math.trunc(we(e+(e>=0?.5:-.5)))}function Ms(e,t,r,i="NONE"){if(oo(i),!i||i==="NONE"||t<=0)return;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(i==="OCTAHEDRAL"){if(r!==4&&r!==8)throw Re(`OCTAHEDRAL filter requires byteStride 4 or 8 (got ${r})`);let m=r===8,c=m?32767:127,d=x=>m?n.getInt16(x,!0):n.getInt8(x),f=(x,b)=>m?n.setInt16(x,b,!0):n.setInt8(x,b<<24>>24),g=m?2:1;for(let x=0;x<t;x++){let b=x*r,v=d(b),p=d(b+g),y=we(d(b+2*g)-Math.abs(v)-Math.abs(p)),M=y>=0?0:y;v=we(v+(v>=0?M:-M)),p=we(p+(p>=0?M:-M));let P=we(Math.sqrt(we(we(we(v*v)+we(p*p))+we(y*y))));if(P===0){f(b,0),f(b+g,0),f(b+2*g,c);continue}let F=we(c/P);f(b,sr(we(v*F))),f(b+g,sr(we(p*F))),f(b+2*g,sr(we(y*F)))}return}if(i==="QUATERNION"){if(r!==8)throw Re(`QUATERNION filter requires byteStride 8 (got ${r})`);let m=we(32767/we(Math.SQRT2));for(let c=0;c<t;c++){let d=c*8,f=n.getInt16(d+6,!0),g=f|3,x=n.getInt16(d,!0),b=n.getInt16(d+2,!0),v=n.getInt16(d+4,!0),p=we(g*g),y=we(we(we(we(p*2)-we(x*x))-we(b*b))-we(v*v)),M=we(Math.sqrt(y>=0?y:0)),P=we(m/g),F=f&3,G=[0,0,0,0];G[F+1&3]=sr(we(x*P)),G[F+2&3]=sr(we(b*P)),G[F+3&3]=sr(we(v*P)),G[F]=Math.trunc(we(we(M*P)+.5));for(let T=0;T<4;T++)n.setInt16(d+T*2,G[T]<<16>>16,!0)}return}if(i==="EXPONENTIAL"){if(r<4||r%4!==0)throw Re(`EXPONENTIAL filter requires byteStride multiple of 4 (got ${r})`);let m=t*r>>>2;for(let c=0;c<m;c++){let d=c*4,f=n.getUint32(d,!0),g=f<<8>>8,x=f>>24;n.setUint32(d,x+127<<23>>>0,!0);let b=n.getFloat32(d,!0);n.setFloat32(d,we(b*g),!0)}return}if(r!==4&&r!==8)throw new Error(`KHR_meshopt_compression: COLOR filter requires byteStride 4 or 8 (got ${r})`);let s=r===8,l=s?65535:255,o=m=>s?n.getUint16(m,!0):n.getUint8(m),a=m=>s?n.getInt16(m,!0):n.getInt8(m),u=(m,c)=>s?n.setUint16(m,c&65535,!0):n.setUint8(m,c&255),h=s?2:1;for(let m=0;m<t;m++){let c=m*r,d=o(c+3*h);d|=d>>1,d|=d>>2,d|=d>>4,d|=d>>8;let f=o(c),g=a(c+h),x=a(c+2*h),b=f+g-x,v=f+x,p=f-g-x,y=o(c+3*h);y=y<<1&d|y&1;let M=d===0?0:we(l/d);u(c,Math.trunc(we(we(b*M)+.5))),u(c+h,Math.trunc(we(we(v*M)+.5))),u(c+2*h,Math.trunc(we(we(p*M)+.5))),u(c+3*h,Math.trunc(we(we(y*M)+.5)))}}var lo=160,gt=16,su=24,uo=32,au=24,ou=[0,2,4,8],lu=[0,1,2,4,8];function ho(e){let t=Math.floor(8192/e)&~(gt-1);return t<256?t:256}function Re(e){return new Error(`EXT_meshopt_compression: ${e}`)}function uu(e,t,r,i,n){if(n===0)return r.fill(0,i,i+gt),t;if(n===8)return r.set(e.subarray(t,t+gt),i),t+gt;let s=(1<<n)-1,l=8/n,o=t+gt*n/8;for(let a=0;a<gt;a++){let u=e[t+Math.floor(a/l)],h=a%l,m=n===1?u>>h&1:u>>8-n-h*n&s;r[i+a]=m===s?e[o++]:m}return o}function co(e,t,r,i,n,s,l,o){let a=s/gt,u=a+3>>2;if(r-t<u)throw Re("truncated ATTRIBUTES stream");let h=t;t+=u;for(let m=0;m<a;m++){if(r-t<su)throw Re("truncated ATTRIBUTES stream");let c=e[h+(m>>2)]>>(m&3)*2&3;t=uu(e,t,i,n+m*gt,l[o+c])}return t}function hu(e,t,r,i){if(r%4!==0||r>256)throw Re(`ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let n=e.byteLength;if(n<1)throw Re("truncated ATTRIBUTES stream");let s=e[0];if((s&240)!==lo)throw Re(`unsupported ATTRIBUTES header 0x${s.toString(16)}`);let l=s&15;if(l>1)throw Re(`unsupported ATTRIBUTES codec version ${l}`);let o=r+(l===0?0:r/4),a=l===0?uo:au,u=o<a?a:o;if(n-1<u)throw Re("truncated ATTRIBUTES stream");let h=n-o,m=e.slice(h,h+r),c=h+r,d=ho(r),f=new Uint8Array(256*4),g=1;for(let x=0;x<t;){let b=Math.min(d,t-x),v=b+gt-1&~(gt-1),p=l===0?0:r/4;if(n-g<p)throw Re("truncated ATTRIBUTES stream");let y=g;g+=p;for(let M=0;M<r;M+=4){let P=l===0?0:e[y+M/4];for(let T=0;T<4;T++){let E=P>>T*2&3;if(E===3){if(n-g<b)throw Re("truncated ATTRIBUTES stream");f.set(e.subarray(g,g+b),T*b),g+=b}else E===2?f.fill(0,T*b,T*b+b):g=l===0?co(e,g,n,f,T*b,v,ou,0):co(e,g,n,f,T*b,v,lu,E)}let F=l===0?0:e[c+M/4],G=F&3;if(G===0)for(let T=0;T<4;T++){let E=m[M+T];for(let S=0;S<b;S++)E=ru(f[T*b+S])+E&255,i[(x+S)*r+M+T]=E}else if(G===1)for(let T=0;T<4;T+=2){let E=m[M+T]|m[M+T+1]<<8,S=T*b;for(let B=0;B<b;B++){let k=f[S+B]|f[S+b+B]<<8;E=iu(k)+E&65535;let w=(x+B)*r+M+T;i[w]=E&255,i[w+1]=E>>8}}else if(G===2){let T=32-(F>>4)&31,E=(m[M]|m[M+1]<<8|m[M+2]<<16|m[M+3]<<24)>>>0;for(let S=0;S<b;S++){let B=(f[S]|f[b+S]<<8|f[2*b+S]<<16|f[3*b+S]<<24)>>>0;B=((B<<T|B>>>(32-T&31))^E)>>>0,E=B;let k=(x+S)*r+M;i[k]=B&255,i[k+1]=B>>>8&255,i[k+2]=B>>>16&255,i[k+3]=B>>>24}}else throw Re(`invalid ATTRIBUTES channel ${F}`)}m.set(i.subarray((x+b-1)*r,(x+b)*r)),x+=b}if(n-g!==u)throw Re("ATTRIBUTES trailing data")}var mo=224,fo=208;function po(e,t){let r=e[t.pos++]??0;if(r<128)return r;let i=r&127,n=7;for(let s=0;s<4;s++){let l=e[t.pos++]??0;if(i=(i|(l&127)<<n)>>>0,n+=7,l<128)break}return i>>>0}function Ai(e,t,r){let i=po(e,t),n=i>>>1^-(i&1);return r+n>>>0}function cu(e,t,r){if(t%3!==0)throw Re(`TRIANGLES count must be divisible by 3 (got ${t})`);let i=t/3;if(e.byteLength<1+i+16)throw Re("truncated TRIANGLES stream");let n=e[0];if((n&240)!==mo)throw Re(`unsupported TRIANGLES header 0x${n.toString(16)}`);let s=n&15;if(s>1)throw Re(`unsupported TRIANGLES codec version ${s}`);let l=new Uint32Array(16).fill(4294967295),o=new Uint32Array(16).fill(4294967295),a=new Uint32Array(16).fill(4294967295),u=0,h=0,m=(P,F)=>{l[u]=P,o[u]=F,u=u+1&15},c=(P,F=1)=>{a[h]=P,h=h+F&15},d=0,f=0,g=s>=1?13:15,x=1+i,b=e.byteLength-16,v=b,p={pos:x},y=0,M=(P,F,G)=>{r(y++,P),r(y++,F),r(y++,G)};for(let P=1;P<x;P++){let F=e[P];if(F<240){let G=F>>4,T=u-1-G&15,E=l[T],S=o[T],B=0,k=F&15;if(k<g){let w=a[h-1-k&15];B=k===0?d:w;let ie=k===0?1:0;d=d+ie>>>0,c(B,ie)}else{if(p.pos>b)throw Re("truncated TRIANGLES stream");B=k!==15?f+(k*2-27)>>>0:Ai(e,p,f),f=B,c(B)}m(B,S),m(E,B),M(E,S,B)}else if(F<254){let G=e[v+(F&15)],T=G>>4,E=G&15,S=d;d=d+1>>>0;let B=a[h-T&15],k=T===0?d:B,w=T===0?1:0;d=d+w>>>0;let ie=a[h-E&15],oe=E===0?d:ie,I=E===0?1:0;d=d+I>>>0,M(S,k,oe),c(S),c(k,w),c(oe,I),m(k,S),m(oe,k),m(S,oe)}else{if(p.pos>b)throw Re("truncated TRIANGLES stream");let G=e[p.pos++],T=F===254?0:15,E=G>>4,S=G&15;G===0&&(d=0);let B=0;T===0&&(B=d,d=d+1>>>0);let k;E===0?(k=d,d=d+1>>>0):k=a[h-E&15];let w;S===0?(w=d,d=d+1>>>0):w=a[h-S&15],T===15&&(f=B=Ai(e,p,f)),E===15&&(f=k=Ai(e,p,f)),S===15&&(f=w=Ai(e,p,f)),M(B,k,w),c(B),c(k,E===0||E===15?1:0),c(w,S===0||S===15?1:0),m(k,B),m(w,k),m(B,w)}}if(p.pos!==b)throw Re("TRIANGLES trailing data")}function mu(e,t,r){if(e.byteLength<1+t+4)throw Re("truncated INDICES stream");let i=e[0];if((i&240)!==fo)throw Re(`unsupported INDICES header 0x${i.toString(16)}`);let n=i&15;if(n>1)throw Re(`unsupported INDICES codec version ${n}`);let s=e.byteLength-4,l=[0,0],o={pos:1};for(let a=0;a<t;a++){if(o.pos>=s)throw Re("truncated INDICES stream");let u=po(e,o),h=u&1;u>>>=1;let m=u>>>1^-(u&1),c=l[h]+m>>>0;l[h]=c,r(a,c)}if(o.pos!==s)throw Re("INDICES trailing data")}function ws(e,t,r,i,n="NONE"){if(oo(n),!Number.isInteger(t)||t<0||t>tu||!Number.isInteger(r)||r<=0||r>256)throw Re(`invalid count (${t}) or byteStride (${r})`);let s=t*r;if(s>no)throw Re(`decompressed size (${s}) exceeds MAX_MESHOPT_BUFFER_BYTES (${no})`);if(t===0)return new Uint8Array(0);let l=new Uint8Array(s);if(i==="ATTRIBUTES")return hu(e,t,r,l),Ms(l,t,r,n),l;if(i==="TRIANGLES"||i==="INDICES"){if(r!==2&&r!==4)throw Re(`${i} byteStride must be 2 or 4 (got ${r})`);if(n&&n!=="NONE")throw Re(`filter ${n} is only valid for ATTRIBUTES`);let o=new DataView(l.buffer),a=r===2?(u,h)=>o.setUint16(u*2,h&65535,!0):(u,h)=>o.setUint32(u*4,h>>>0,!0);return i==="TRIANGLES"?cu(e,t,a):mu(e,t,a),l}throw Re(`unknown mode "${String(i)}"`)}function go(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function yo(e,t,r,i){let n=t*r;if(e.byteLength<n)throw new Error(`encodeMeshoptBuffer: raw buffer (${e.byteLength}) smaller than count * byteStride (${n})`);if(i==="ATTRIBUTES"){if(r%4!==0||r>256)throw new Error(`encodeMeshoptBuffer: ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let o=[lo],a=ho(r),u=new Uint8Array(r);t>0&&u.set(e.subarray(0,r));let h=u.slice(),m=new Uint8Array(256);for(let c=0;c<t;){let d=Math.min(a,t-c),f=d+15&-16;for(let g=0;g<r;g++){m.fill(0);let x=u[g];for(let p=0;p<d;p++){let y=e[(c+p)*r+g];m[p]=nu(y-x&255),x=y}u[g]=x;let b=f/16,v=o.length;for(let p=0;p<b+3>>2;p++)o.push(0);for(let p=0;p<b;p++){let y=m.subarray(p*16,p*16+16);if(!y.every(M=>M===0)){o[v+(p>>2)]|=3<<(p&3)*2;for(let M of y)o.push(M)}}}c+=d}for(let c=r;c<uo;c++)o.push(0);for(let c=0;c<r;c++)o.push(h[c]);return new Uint8Array(o)}if(r!==2&&r!==4)throw new Error(`encodeMeshoptBuffer: ${i} byteStride must be 2 or 4 (got ${r})`);let s=new DataView(e.buffer,e.byteOffset,e.byteLength),l=o=>r===2?s.getUint16(o*2,!0):s.getUint32(o*4,!0);if(i==="INDICES"){let o=[fo|1],a=0;for(let u=0;u<t;u++){let h=l(u),m=h-a|0;a=h,go(o,ao(m)<<1>>>0)}return o.push(0,0,0,0),new Uint8Array(o)}if(i==="TRIANGLES"){if(t%3!==0)throw new Error(`encodeMeshoptBuffer: TRIANGLES count must be divisible by 3 (got ${t})`);let o=t/3,a=[mo|1];for(let h=0;h<o;h++)a.push(255);let u=0;for(let h=0;h<o;h++){a.push(255);for(let m=0;m<3;m++){let c=l(h*3+m);go(a,ao(c-u|0)),u=c}}for(let h=0;h<16;h++)a.push(0);return new Uint8Array(a)}throw new Error(`encodeMeshoptBuffer: unknown mode "${String(i)}"`)}function Ti(e,t){let r=t&&typeof t=="object"?t:e,i=t&&typeof t=="object"?e:r?.gltf;if(!i||!Array.isArray(i.bufferViews))return;let n=new Uint8Array(r.bin),s=[],l=0;for(let m=0;m<i.bufferViews.length;m++){let c=i.bufferViews[m],d=c?.extensions?.KHR_meshopt_compression,f=d??c?.extensions?.EXT_meshopt_compression;if(!f||typeof f!="object")continue;let g=d?"KHR_meshopt_compression":"EXT_meshopt_compression",x=Number(f.count),b=Number(f.byteStride),v=Number(f.byteOffset??0),p=Number(f.byteLength??0),y=f.mode||"ATTRIBUTES",M=f.filter||"NONE";if(M==="COLOR"&&!d)throw Re(`bufferView ${m} uses the COLOR filter, which requires KHR_meshopt_compression`);if(Number(f.buffer??0)!==0)throw new Error(`${g}: bufferView ${m} references buffer ${String(f.buffer)}; only the GLB BIN chunk (buffer 0) is supported`);if(!Number.isInteger(v)||v<0||!Number.isInteger(p)||p<0||v+p>n.byteLength)throw new Error(`${g}: bufferView ${m} compressed range [${v}, ${v+p}] out of bounds (${n.byteLength})`);let P=x*b;if(l+=P,l>so)throw Re(`total decompressed size (${l}) exceeds MAX_MESHOPT_TOTAL_BYTES (${so})`);let F=n.subarray(v,v+p),G=ws(F,x,b,y,M);s.push({index:m,bytes:G,ext:f})}if(s.length===0)return;let o=n.byteLength+3&-4,a=0;for(let m of s)a+=m.bytes.byteLength+3&-4;let u=new Uint8Array(o+a);u.set(n,0);let h=o;for(let m of s){u.set(m.bytes,h);let c=i.bufferViews[m.index];c.buffer=0,c.byteOffset=h,c.byteLength=m.bytes.byteLength,c._decoded=m.bytes,m.ext.mode==="ATTRIBUTES"&&c.byteStride===void 0&&(c.byteStride=Number(m.ext.byteStride)),c.extensions&&(delete c.extensions.EXT_meshopt_compression,delete c.extensions.KHR_meshopt_compression),h+=m.bytes.byteLength+3&-4}r.bin=u.buffer}var Si={decodeBufferViews(e,t){Ti(t)},decodePrimitive(e,t,r){let i=t?.extensions;i?.EXT_meshopt_compression&&delete i.EXT_meshopt_compression,i?.KHR_meshopt_compression&&delete i.KHR_meshopt_compression}};Ae().decoders.set("meshopt",Si);var As={name:"meshopt",onParseGLB(e){Ae().decoders.set("meshopt",Si),Ti(e)}},fu=`#version 300 es
469
+ vec3 aCol=vec3(${m(A[0],1,0,1)},${m(A[1],1,0,1)},${m(A[2],1,0,1)});
470
+ vec3 volumeAtten=exp(-tV*(vec3(1.)-aCol)/max(${y},.001));
471
+ diffuseIBL=mix(diffuseIBL,tr*volumeAtten*base.rgb,${g});`)}if(a&&!i.includes("uClearcoat")){let g=m(a.clearcoatFactor,1,0,1),x=m(a.clearcoatRoughnessFactor,0,0,1);f=f.replace("fragColor=vec4(color,base.a);",`vec3 ccF=F_SchlickRoughness(vec3(.04),${x},NoV)*${g};color=color*(vec3(1.)-ccF)+getStudioRadiance(R,${x})*ccF;fragColor=vec4(color,base.a);`)}if(s){let g=Array.isArray(s.sheenColorFactor)?s.sheenColorFactor:[1,1,1],x=`color+=vec3(${m(g[0],1,0,1)},${m(g[1],1,0,1)},${m(g[2],1,0,1)})*pow(1.-NoV,4.)*.5;`;f.includes("color=applyToneMapping(color,uToneMapping);")?f=f.replace("color=applyToneMapping(color,uToneMapping);",`${x}color=applyToneMapping(color,uToneMapping);`):f=f.replace("fragColor=vec4(color,base.a);",`${x}fragColor=vec4(color,base.a);`)}return{vs:r,fs:f}},onBeforeDrawPrimitive(e,t,r,i,n,a){let s=r.materialIndex;if(s!==void 0&&a?.materials){let o=a.materials[s];o?.name&&Qn.has(o.name)&&Qn.get(o.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let o=Ds.get(e);if(o){e.activeTexture(33990),e.bindTexture(3553,o);let l=e.getUniformLocation(t,"uTransmissionTex");l&&e.uniform1i(l,6);let c=e.getUniformLocation(t,"uViewportSize");c&&e.uniform2f(c,e.drawingBufferWidth||1,e.drawingBufferHeight||1)}}}},hm=64*1024*1024,fm=128*1024*1024,E1=16777216;function L1(e){return(e>>>1^-(e&1))&255}function R1(e){return(e>>>1^-(e&1))&65535}function I1(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function mm(e){return(e<<1^e>>31)>>>0}function pm(e){if(e!==void 0&&e!=="NONE"&&e!=="OCTAHEDRAL"&&e!=="QUATERNION"&&e!=="EXPONENTIAL"&&e!=="COLOR")throw mt(`unknown filter "${String(e)}"`)}var st=Math.fround;function rn(e){return Math.trunc(st(e+(e>=0?.5:-.5)))}function tc(e,t,r,i="NONE"){if(pm(i),!i||i==="NONE"||t<=0)return;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(i==="OCTAHEDRAL"){if(r!==4&&r!==8)throw mt(`OCTAHEDRAL filter requires byteStride 4 or 8 (got ${r})`);let m=r===8,h=m?32767:127,p=v=>m?n.getInt16(v,!0):n.getInt8(v),g=(v,y)=>m?n.setInt16(v,y,!0):n.setInt8(v,y<<24>>24),x=m?2:1;for(let v=0;v<t;v++){let y=v*r,A=p(y),b=p(y+x),w=st(p(y+2*x)-Math.abs(A)-Math.abs(b)),S=w>=0?0:w;A=st(A+(A>=0?S:-S)),b=st(b+(b>=0?S:-S));let E=st(Math.sqrt(st(st(st(A*A)+st(b*b))+st(w*w))));if(E===0){g(y,0),g(y+x,0),g(y+2*x,h);continue}let N=st(h/E);g(y,rn(st(A*N))),g(y+x,rn(st(b*N))),g(y+2*x,rn(st(w*N)))}return}if(i==="QUATERNION"){if(r!==8)throw mt(`QUATERNION filter requires byteStride 8 (got ${r})`);let m=st(32767/st(Math.SQRT2));for(let h=0;h<t;h++){let p=h*8,g=n.getInt16(p+6,!0),x=g|3,v=n.getInt16(p,!0),y=n.getInt16(p+2,!0),A=n.getInt16(p+4,!0),b=st(x*x),w=st(st(st(st(b*2)-st(v*v))-st(y*y))-st(A*A)),S=st(Math.sqrt(w>=0?w:0)),E=st(m/x),N=g&3,C=[0,0,0,0];C[N+1&3]=rn(st(v*E)),C[N+2&3]=rn(st(y*E)),C[N+3&3]=rn(st(A*E)),C[N]=Math.trunc(st(st(S*E)+.5));for(let _=0;_<4;_++)n.setInt16(p+_*2,C[_]<<16>>16,!0)}return}if(i==="EXPONENTIAL"){if(r<4||r%4!==0)throw mt(`EXPONENTIAL filter requires byteStride multiple of 4 (got ${r})`);let m=t*r>>>2;for(let h=0;h<m;h++){let p=h*4,g=n.getUint32(p,!0),x=g<<8>>8,v=g>>24;n.setUint32(p,v+127<<23>>>0,!0);let y=n.getFloat32(p,!0);n.setFloat32(p,st(y*x),!0)}return}if(r!==4&&r!==8)throw new Error(`KHR_meshopt_compression: COLOR filter requires byteStride 4 or 8 (got ${r})`);let a=r===8,s=a?65535:255,o=m=>a?n.getUint16(m,!0):n.getUint8(m),l=m=>a?n.getInt16(m,!0):n.getInt8(m),c=(m,h)=>a?n.setUint16(m,h&65535,!0):n.setUint8(m,h&255),f=a?2:1;for(let m=0;m<t;m++){let h=m*r,p=o(h+3*f);p|=p>>1,p|=p>>2,p|=p>>4,p|=p>>8;let g=o(h),x=l(h+f),v=l(h+2*f),y=g+x-v,A=g+v,b=g-x-v,w=o(h+3*f);w=w<<1&p|w&1;let S=p===0?0:st(s/p);c(h,Math.trunc(st(st(y*S)+.5))),c(h+f,Math.trunc(st(st(A*S)+.5))),c(h+2*f,Math.trunc(st(st(b*S)+.5))),c(h+3*f,Math.trunc(st(st(w*S)+.5)))}}var dm=160,Or=16,$1=24,gm=32,D1=24,k1=[0,2,4,8],F1=[0,1,2,4,8];function ym(e){let t=Math.floor(8192/e)&~(Or-1);return t<256?t:256}function mt(e){return new Error(`EXT_meshopt_compression: ${e}`)}function B1(e,t,r,i,n){if(n===0)return r.fill(0,i,i+Or),t;if(n===8)return r.set(e.subarray(t,t+Or),i),t+Or;let a=(1<<n)-1,s=8/n,o=t+Or*n/8;for(let l=0;l<Or;l++){let c=e[t+Math.floor(l/s)],f=l%s,m=n===1?c>>f&1:c>>8-n-f*n&a;r[i+l]=m===a?e[o++]:m}return o}function bm(e,t,r,i,n,a,s,o){let l=a/Or,c=l+3>>2;if(r-t<c)throw mt("truncated ATTRIBUTES stream");let f=t;t+=c;for(let m=0;m<l;m++){if(r-t<$1)throw mt("truncated ATTRIBUTES stream");let h=e[f+(m>>2)]>>(m&3)*2&3;t=B1(e,t,i,n+m*Or,s[o+h])}return t}function z1(e,t,r,i){if(r%4!==0||r>256)throw mt(`ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let n=e.byteLength;if(n<1)throw mt("truncated ATTRIBUTES stream");let a=e[0];if((a&240)!==dm)throw mt(`unsupported ATTRIBUTES header 0x${a.toString(16)}`);let s=a&15;if(s>1)throw mt(`unsupported ATTRIBUTES codec version ${s}`);let o=r+(s===0?0:r/4),l=s===0?gm:D1,c=o<l?l:o;if(n-1<c)throw mt("truncated ATTRIBUTES stream");let f=n-o,m=e.slice(f,f+r),h=f+r,p=ym(r),g=new Uint8Array(256*4),x=1;for(let v=0;v<t;){let y=Math.min(p,t-v),A=y+Or-1&~(Or-1),b=s===0?0:r/4;if(n-x<b)throw mt("truncated ATTRIBUTES stream");let w=x;x+=b;for(let S=0;S<r;S+=4){let E=s===0?0:e[w+S/4];for(let _=0;_<4;_++){let P=E>>_*2&3;if(P===3){if(n-x<y)throw mt("truncated ATTRIBUTES stream");g.set(e.subarray(x,x+y),_*y),x+=y}else P===2?g.fill(0,_*y,_*y+y):x=s===0?bm(e,x,n,g,_*y,A,k1,0):bm(e,x,n,g,_*y,A,F1,P)}let N=s===0?0:e[h+S/4],C=N&3;if(C===0)for(let _=0;_<4;_++){let P=m[S+_];for(let R=0;R<y;R++)P=L1(g[_*y+R])+P&255,i[(v+R)*r+S+_]=P}else if(C===1)for(let _=0;_<4;_+=2){let P=m[S+_]|m[S+_+1]<<8,R=_*y;for(let I=0;I<y;I++){let F=g[R+I]|g[R+y+I]<<8;P=R1(F)+P&65535;let V=(v+I)*r+S+_;i[V]=P&255,i[V+1]=P>>8}}else if(C===2){let _=32-(N>>4)&31,P=(m[S]|m[S+1]<<8|m[S+2]<<16|m[S+3]<<24)>>>0;for(let R=0;R<y;R++){let I=(g[R]|g[y+R]<<8|g[2*y+R]<<16|g[3*y+R]<<24)>>>0;I=((I<<_|I>>>(32-_&31))^P)>>>0,P=I;let F=(v+R)*r+S;i[F]=I&255,i[F+1]=I>>>8&255,i[F+2]=I>>>16&255,i[F+3]=I>>>24}}else throw mt(`invalid ATTRIBUTES channel ${N}`)}m.set(i.subarray((v+y-1)*r,(v+y)*r)),v+=y}if(n-x!==c)throw mt("ATTRIBUTES trailing data")}var xm=224,vm=208;function wm(e,t){let r=e[t.pos++]??0;if(r<128)return r;let i=r&127,n=7;for(let a=0;a<4;a++){let s=e[t.pos++]??0;if(i=(i|(s&127)<<n)>>>0,n+=7,s<128)break}return i>>>0}function ks(e,t,r){let i=wm(e,t),n=i>>>1^-(i&1);return r+n>>>0}function V1(e,t,r){if(t%3!==0)throw mt(`TRIANGLES count must be divisible by 3 (got ${t})`);let i=t/3;if(e.byteLength<1+i+16)throw mt("truncated TRIANGLES stream");let n=e[0];if((n&240)!==xm)throw mt(`unsupported TRIANGLES header 0x${n.toString(16)}`);let a=n&15;if(a>1)throw mt(`unsupported TRIANGLES codec version ${a}`);let s=new Uint32Array(16).fill(4294967295),o=new Uint32Array(16).fill(4294967295),l=new Uint32Array(16).fill(4294967295),c=0,f=0,m=(E,N)=>{s[c]=E,o[c]=N,c=c+1&15},h=(E,N=1)=>{l[f]=E,f=f+N&15},p=0,g=0,x=a>=1?13:15,v=1+i,y=e.byteLength-16,A=y,b={pos:v},w=0,S=(E,N,C)=>{r(w++,E),r(w++,N),r(w++,C)};for(let E=1;E<v;E++){let N=e[E];if(N<240){let C=N>>4,_=c-1-C&15,P=s[_],R=o[_],I=0,F=N&15;if(F<x){let V=l[f-1-F&15];I=F===0?p:V;let Y=F===0?1:0;p=p+Y>>>0,h(I,Y)}else{if(b.pos>y)throw mt("truncated TRIANGLES stream");I=F!==15?g+(F*2-27)>>>0:ks(e,b,g),g=I,h(I)}m(I,R),m(P,I),S(P,R,I)}else if(N<254){let C=e[A+(N&15)],_=C>>4,P=C&15,R=p;p=p+1>>>0;let I=l[f-_&15],F=_===0?p:I,V=_===0?1:0;p=p+V>>>0;let Y=l[f-P&15],J=P===0?p:Y,re=P===0?1:0;p=p+re>>>0,S(R,F,J),h(R),h(F,V),h(J,re),m(F,R),m(J,F),m(R,J)}else{if(b.pos>y)throw mt("truncated TRIANGLES stream");let C=e[b.pos++],_=N===254?0:15,P=C>>4,R=C&15;C===0&&(p=0);let I=0;_===0&&(I=p,p=p+1>>>0);let F;P===0?(F=p,p=p+1>>>0):F=l[f-P&15];let V;R===0?(V=p,p=p+1>>>0):V=l[f-R&15],_===15&&(g=I=ks(e,b,g)),P===15&&(g=F=ks(e,b,g)),R===15&&(g=V=ks(e,b,g)),S(I,F,V),h(I),h(F,P===0||P===15?1:0),h(V,R===0||R===15?1:0),m(F,I),m(V,F),m(I,V)}}if(b.pos!==y)throw mt("TRIANGLES trailing data")}function U1(e,t,r){if(e.byteLength<1+t+4)throw mt("truncated INDICES stream");let i=e[0];if((i&240)!==vm)throw mt(`unsupported INDICES header 0x${i.toString(16)}`);let n=i&15;if(n>1)throw mt(`unsupported INDICES codec version ${n}`);let a=e.byteLength-4,s=[0,0],o={pos:1};for(let l=0;l<t;l++){if(o.pos>=a)throw mt("truncated INDICES stream");let c=wm(e,o),f=c&1;c>>>=1;let m=c>>>1^-(c&1),h=s[f]+m>>>0;s[f]=h,r(l,h)}if(o.pos!==a)throw mt("INDICES trailing data")}function rc(e,t,r,i,n="NONE"){if(pm(n),!Number.isInteger(t)||t<0||t>E1||!Number.isInteger(r)||r<=0||r>256)throw mt(`invalid count (${t}) or byteStride (${r})`);let a=t*r;if(a>hm)throw mt(`decompressed size (${a}) exceeds MAX_MESHOPT_BUFFER_BYTES (${hm})`);if(t===0)return new Uint8Array(0);let s=new Uint8Array(a);if(i==="ATTRIBUTES")return z1(e,t,r,s),tc(s,t,r,n),s;if(i==="TRIANGLES"||i==="INDICES"){if(r!==2&&r!==4)throw mt(`${i} byteStride must be 2 or 4 (got ${r})`);if(n&&n!=="NONE")throw mt(`filter ${n} is only valid for ATTRIBUTES`);let o=new DataView(s.buffer),l=r===2?(c,f)=>o.setUint16(c*2,f&65535,!0):(c,f)=>o.setUint32(c*4,f>>>0,!0);return i==="TRIANGLES"?V1(e,t,l):U1(e,t,l),s}throw mt(`unknown mode "${String(i)}"`)}function Mm(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function _m(e,t,r,i){let n=t*r;if(e.byteLength<n)throw new Error(`encodeMeshoptBuffer: raw buffer (${e.byteLength}) smaller than count * byteStride (${n})`);if(i==="ATTRIBUTES"){if(r%4!==0||r>256)throw new Error(`encodeMeshoptBuffer: ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let o=[dm],l=ym(r),c=new Uint8Array(r);t>0&&c.set(e.subarray(0,r));let f=c.slice(),m=new Uint8Array(256);for(let h=0;h<t;){let p=Math.min(l,t-h),g=p+15&-16;for(let x=0;x<r;x++){m.fill(0);let v=c[x];for(let b=0;b<p;b++){let w=e[(h+b)*r+x];m[b]=I1(w-v&255),v=w}c[x]=v;let y=g/16,A=o.length;for(let b=0;b<y+3>>2;b++)o.push(0);for(let b=0;b<y;b++){let w=m.subarray(b*16,b*16+16);if(!w.every(S=>S===0)){o[A+(b>>2)]|=3<<(b&3)*2;for(let S of w)o.push(S)}}}h+=p}for(let h=r;h<gm;h++)o.push(0);for(let h=0;h<r;h++)o.push(f[h]);return new Uint8Array(o)}if(r!==2&&r!==4)throw new Error(`encodeMeshoptBuffer: ${i} byteStride must be 2 or 4 (got ${r})`);let a=new DataView(e.buffer,e.byteOffset,e.byteLength),s=o=>r===2?a.getUint16(o*2,!0):a.getUint32(o*4,!0);if(i==="INDICES"){let o=[vm|1],l=0;for(let c=0;c<t;c++){let f=s(c),m=f-l|0;l=f,Mm(o,mm(m)<<1>>>0)}return o.push(0,0,0,0),new Uint8Array(o)}if(i==="TRIANGLES"){if(t%3!==0)throw new Error(`encodeMeshoptBuffer: TRIANGLES count must be divisible by 3 (got ${t})`);let o=t/3,l=[xm|1];for(let f=0;f<o;f++)l.push(255);let c=0;for(let f=0;f<o;f++){l.push(255);for(let m=0;m<3;m++){let h=s(f*3+m);Mm(l,mm(h-c|0)),c=h}}for(let f=0;f<16;f++)l.push(0);return new Uint8Array(l)}throw new Error(`encodeMeshoptBuffer: unknown mode "${String(i)}"`)}function Fs(e,t){let r=t&&typeof t=="object"?t:e,i=t&&typeof t=="object"?e:r?.gltf;if(!i||!Array.isArray(i.bufferViews))return;let n=new Uint8Array(r.bin),a=[],s=0;for(let m=0;m<i.bufferViews.length;m++){let h=i.bufferViews[m],p=h?.extensions?.KHR_meshopt_compression,g=p??h?.extensions?.EXT_meshopt_compression;if(!g||typeof g!="object")continue;let x=p?"KHR_meshopt_compression":"EXT_meshopt_compression",v=Number(g.count),y=Number(g.byteStride),A=Number(g.byteOffset??0),b=Number(g.byteLength??0),w=g.mode||"ATTRIBUTES",S=g.filter||"NONE";if(S==="COLOR"&&!p)throw mt(`bufferView ${m} uses the COLOR filter, which requires KHR_meshopt_compression`);if(Number(g.buffer??0)!==0)throw new Error(`${x}: bufferView ${m} references buffer ${String(g.buffer)}; only the GLB BIN chunk (buffer 0) is supported`);if(!Number.isInteger(A)||A<0||!Number.isInteger(b)||b<0||A+b>n.byteLength)throw new Error(`${x}: bufferView ${m} compressed range [${A}, ${A+b}] out of bounds (${n.byteLength})`);let E=v*y;if(s+=E,s>fm)throw mt(`total decompressed size (${s}) exceeds MAX_MESHOPT_TOTAL_BYTES (${fm})`);let N=n.subarray(A,A+b),C=rc(N,v,y,w,S);a.push({index:m,bytes:C,ext:g})}if(a.length===0)return;let o=n.byteLength+3&-4,l=0;for(let m of a)l+=m.bytes.byteLength+3&-4;let c=new Uint8Array(o+l);c.set(n,0);let f=o;for(let m of a){c.set(m.bytes,f);let h=i.bufferViews[m.index];h.buffer=0,h.byteOffset=f,h.byteLength=m.bytes.byteLength,h._decoded=m.bytes,m.ext.mode==="ATTRIBUTES"&&h.byteStride===void 0&&(h.byteStride=Number(m.ext.byteStride)),h.extensions&&(delete h.extensions.EXT_meshopt_compression,delete h.extensions.KHR_meshopt_compression),f+=m.bytes.byteLength+3&-4}r.bin=c.buffer}var Bs={decodeBufferViews(e,t){Fs(t)},decodePrimitive(e,t,r){let i=t?.extensions;i?.EXT_meshopt_compression&&delete i.EXT_meshopt_compression,i?.KHR_meshopt_compression&&delete i.KHR_meshopt_compression}};We().decoders.set("meshopt",Bs);var ic={name:"meshopt",onParseGLB(e){We().decoders.set("meshopt",Bs),Fs(e)}},O1=`#version 300 es
424
472
  layout(location=0) in vec3 aPosition;
425
473
  layout(location=1) in vec3 aNormal;
426
474
  uniform mat4 uMVP,uVP;
@@ -441,19 +489,19 @@ vec2 pxOffset=dir*(uOutlineThickness*2.0/max(uViewportSize,vec2(1.0)))*clipPos.w
441
489
  clipPos.xy+=pxOffset;
442
490
  clipPos.z+=1e-4*clipPos.w;
443
491
  gl_Position=clipPos;
444
- }`,pu=`#version 300 es
492
+ }`,j1=`#version 300 es
445
493
  precision highp float;
446
494
  uniform vec4 uOutlineColor;
447
495
  out vec4 fragColor;
448
496
  void main(){
449
497
  fragColor=uOutlineColor;
450
- }`,bo=`#version 300 es
498
+ }`,Sm=`#version 300 es
451
499
  out vec2 vUV;
452
500
  void main(){
453
501
  vec2 pos=vec2((gl_VertexID<<1)&2,gl_VertexID&2);
454
502
  vUV=pos;
455
503
  gl_Position=vec4(pos*2.0-1.0,0.0,1.0);
456
- }`,du=`#version 300 es
504
+ }`,G1=`#version 300 es
457
505
  precision highp float;
458
506
  in vec2 vUV;
459
507
  uniform sampler2D uSourceTex;
@@ -476,7 +524,7 @@ c+=prefilter(texture(uSourceTex,vUV+vec2(h.x,-h.y)).rgb)*0.125;
476
524
  c+=prefilter(texture(uSourceTex,vUV+vec2(-h.x,h.y)).rgb)*0.125;
477
525
  c+=prefilter(texture(uSourceTex,vUV+vec2(h.x,h.y)).rgb)*0.125;
478
526
  fragColor=vec4(c,1.0);
479
- }`,gu=`#version 300 es
527
+ }`,H1=`#version 300 es
480
528
  precision highp float;
481
529
  in vec2 vUV;
482
530
  uniform sampler2D uBloomTex;
@@ -498,4 +546,674 @@ sum+=texture(uBloomTex,vUV+vec2(-d.x,-d.y)).rgb*2.0;
498
546
  vec3 bloom=(sum/12.0)*uStrength;
499
547
  float a=clamp(min(bloom.r,min(bloom.g,bloom.b)),0.0,1.0);
500
548
  fragColor=vec4(bloom,a);
501
- }`,Ri=3,Sr=new WeakMap;function Ts(e,t=[.22,.74,.97]){let r=ga(e,"");if(!r.startsWith("#"))return[t[0],t[1],t[2]];let i=r.slice(1);if(i.length===3){let n=+("0x"+i[0]+i[0])/255,s=+("0x"+i[1]+i[1])/255,l=+("0x"+i[2]+i[2])/255;return[n,s,l]}if(i.length===6){let n=+("0x"+i.slice(0,2))/255,s=+("0x"+i.slice(2,4))/255,l=+("0x"+i.slice(4,6))/255;return[n,s,l]}return[t[0],t[1],t[2]]}function xo(e,t,r=.8,i=.5){let n=Number.isFinite(t)?Math.max(0,t):0;if(n<=0)return[0,0,0];let s=Math.max(0,Number(e[0])||0),l=Math.max(0,Number(e[1])||0),o=Math.max(0,Number(e[2])||0),a=Math.max(s,l,o);if(a<=1e-6)return[0,0,0];let u=Number.isFinite(r)?Math.max(0,r):.8,h=Math.max(u*Math.max(0,i),1e-4),m=Math.max(0,Math.min(2*h,a-u+h)),c=m*m/(4*h+1e-4),d=Math.min(1,Math.max(0,Math.max(c,a-u)/Math.max(a,1e-4)))*n;return[s*d,l*d,o*d]}function vo(e,t,r,i){let n=Number(e[0])||0,s=Number(e[1])||0,l=Math.hypot(n,s);if(l<=1e-5||t<=0||r<=0)return[0,0];let o=Math.max(1,Number(i[0])||1),a=Math.max(1,Number(i[1])||1),u=Math.max(0,r)*2*t;return[n/l*(u/o),s/l*(u/a)]}var Mo=new WeakSet;function wo(e){let t=Sr.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;Sr.delete(e)}if(Mo.has(e)||e.isContextLost?.())return null;let r=Xt(e,fu,pu,!1),i=Xt(e,bo,du,!1),n=Xt(e,bo,gu,!1);if(!r||!i||!n){for(let l of[r,i,n])l&&e.deleteProgram(l);return Mo.add(e),null}let s=typeof e.createVertexArray=="function"?e.createVertexArray():null;return t={outlineProg:r,uOutlineMVP:e.getUniformLocation(r,"uMVP"),uOutlineVP:e.getUniformLocation(r,"uVP"),uOutlineNormalMatrix:e.getUniformLocation(r,"uNormalMatrix"),uOutlineViewportSize:e.getUniformLocation(r,"uViewportSize"),uOutlineThickness:e.getUniformLocation(r,"uOutlineThickness"),uOutlineColor:e.getUniformLocation(r,"uOutlineColor"),downProg:i,uDownSourceTex:e.getUniformLocation(i,"uSourceTex"),uDownTexelSize:e.getUniformLocation(i,"uTexelSize"),uDownThreshold:e.getUniformLocation(i,"uThreshold"),upProg:n,uUpBloomTex:e.getUniformLocation(n,"uBloomTex"),uUpTexelSize:e.getUniformLocation(n,"uTexelSize"),uUpRadius:e.getUniformLocation(n,"uRadius"),uUpStrength:e.getUniformLocation(n,"uStrength"),fsVao:s,sceneTex:null,bloomTex:[],bloomFbo:[],mipWidth:[],mipHeight:[],texWidth:0,texHeight:0},Sr.set(e,t),t}function yu(e,t,r,i){if(typeof e.createFramebuffer!="function"||typeof e.copyTexSubImage2D!="function")return!1;let n=Math.max(2,r|0),s=Math.max(2,i|0);if(t.sceneTex&&t.bloomFbo.length===Ri&&t.texWidth===n&&t.texHeight===s)return!0;t.sceneTex||(t.sceneTex=e.createTexture()),e.bindTexture(3553,t.sceneTex),e.texImage2D(3553,0,6408,n,s,0,6408,5121,null),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071);let l=n,o=s;for(let a=0;a<Ri;a++)l=Math.max(1,l>>1),o=Math.max(1,o>>1),t.mipWidth[a]=l,t.mipHeight[a]=o,t.bloomTex[a]||(t.bloomTex[a]=e.createTexture()),e.bindTexture(3553,t.bloomTex[a]),e.texImage2D(3553,0,6408,l,o,0,6408,5121,null),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),t.bloomFbo[a]||(t.bloomFbo[a]=e.createFramebuffer()),e.bindFramebuffer(36160,t.bloomFbo[a]),e.framebufferTexture2D(36160,36064,3553,t.bloomTex[a],0);return e.bindFramebuffer(36160,null),t.texWidth=n,t.texHeight=s,!0}function bu(e){let t=e.container;if(t&&typeof t.getAttribute=="function"){let i=t.getAttribute("bloom");if(i!==null){let n=i.trim().toLowerCase();if(n==="false"||n==="0"||n==="none")return null;let s=n===""||n==="true"?.35:Number(n);if(!Number.isFinite(s)||s<=0)return null;let l=ya({strength:s,threshold:mi(t.getAttribute("bloom-threshold"),.62),radius:mi(t.getAttribute("bloom-radius"),.75)});if(l)return l}}let r=null;for(let i of e.meshes||[]){if(i.visible===!1)continue;let n=i?.extras?.xr?.bloom??i?.userData?.xr?.bloom,s=ya(n);s&&(!r||s.strength>r.strength)&&(r=s)}return r}function xu(e,t){if(e==null)return null;let r=e.trim(),i=r.toLowerCase();if(i==="false"||i==="0"||i==="none")return null;let n=t,s=3.5,l=!1;if(r&&i!=="true"){let o=r.split(/\s+/);for(let a of o)if(a.startsWith("#"))n=a;else if(a.toLowerCase()==="pulse")l=!0;else{let u=Number(a);Number.isFinite(u)&&u>0&&(s=u)}}return Ki({color:n,thickness:s,pulse:l})}var vu=new Set(["floor","pedestal","ground","table","grid","pad"]);function Mu(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>vu.has(t))}function wu(e,t){let r=e.container,i=typeof r?.getAttribute=="function"?r.getAttribute("outline"):null;if(i!=null){let h=i.trim().toLowerCase();if(h==="false"||h==="0"||h==="none")return null}let n=t?.extras?.xr?.outline??t?.userData?.xr?.outline,s=Ki(n);if(s)return s;let l=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",o=xu(i,l),a=r!=null&&typeof r.hasAttribute=="function"&&r.hasAttribute("outline-selected")&&r.getAttribute("outline-selected")!=="false",u=e.getSelectedMesh?.()||"";if(u)return t.name!==u?null:o||(a?Ki({color:l,thickness:3,pulse:!1}):null);if(o){let h=t.name||"";return Mu(h)?null:o}return null}var Ss={name:"postprocessing",onAttributeChanged(e,t){(t==="bloom"||t==="bloom-threshold"||t==="bloom-radius"||t==="outline"||t==="outline-selected"||t==="outline-color"||t==="selected-mesh")&&e.viewer?.render?.()},onAfterRender(e,t,r){if(!t.meshes||t.meshes.length===0)return;let i=Math.max(1,t.canvas?.width||300),n=Math.max(1,t.canvas?.height||150),s=[];for(let c of t.meshes){if(c.visible===!1)continue;let d=wu(t,c);d&&s.push({mesh:c,trait:d})}let l=s.length>0?wo(e):null;if(l){let c=l,d=Pe(),f=Pe(),g=new Float32Array(9),x=(typeof performance<"u"?performance.now():Date.now())*.001,b=typeof e.getParameter=="function"?e.getParameter(e.VIEWPORT):null,v=Math.max(1,b?.[2]||i),p=Math.max(1,b?.[3]||n);e.useProgram(c.outlineProg),c.uOutlineViewportSize&&e.uniform2f(c.uOutlineViewportSize,v,p),c.uOutlineVP&&e.uniformMatrix4fv(c.uOutlineVP,!1,r),e.enable(e.CULL_FACE),e.cullFace(e.FRONT),e.enable(2929),e.depthFunc(e.LEQUAL),e.depthMask(!1);for(let{mesh:y,trait:M}of s){let[P,F,G]=Ts(M.color),T=M.pulse?.8+.25*Math.sin(x*4):1;c.uOutlineColor&&e.uniform4f(c.uOutlineColor,P,F,G,1),c.uOutlineThickness&&e.uniform1f(c.uOutlineThickness,M.thickness*T),y.worldSpace===!0?d.set(y.transform):ke(d,t.modelRootMatrix,y.transform);let E=y.instanceMatrices;for(let S of y.primitives)if(!(S.pluginData?.skinning?.hasSkin||S.pluginData?.morph?.hasMorph))if(e.bindVertexArray(S.vao),E&&E.length>=16){let B=E.length>>4,k=Pe();for(let w=0;w<B;w++)ke(k,d,E.subarray(w*16,w*16+16)),ke(f,r,k),Ye(g,k),e.uniformMatrix4fv(c.uOutlineMVP,!1,f),e.uniformMatrix3fv(c.uOutlineNormalMatrix,!1,g),S.indices?e.drawElements(4,S.indexCount,S.indexType,0):e.drawArrays(4,0,S.indexCount)}else ke(f,r,d),Ye(g,d),e.uniformMatrix4fv(c.uOutlineMVP,!1,f),e.uniformMatrix3fv(c.uOutlineNormalMatrix,!1,g),S.indices?e.drawElements(4,S.indexCount,S.indexType,0):e.drawArrays(4,0,S.indexCount)}e.bindVertexArray(null),e.cullFace(e.BACK),e.disable(e.CULL_FACE),e.depthFunc(e.LESS),e.depthMask(!0)}if(t.xrSessionActive||t.stereoSBS)return;let o=bu(t);if(!o||o.strength<=0)return;let a=wo(e);if(!a||!yu(e,a,i,n)||!a.fsVao)return;e.activeTexture(33984),e.bindTexture(3553,a.sceneTex),e.copyTexSubImage2D(3553,0,0,0,0,0,i,n),e.disable(2929),e.depthMask(!1),e.disable(3042),e.useProgram(a.downProg),e.uniform1i(a.uDownSourceTex,0),e.bindVertexArray(a.fsVao);let u=a.sceneTex,h=i,m=n;for(let c=0;c<Ri;c++){let d=a.mipWidth[c],f=a.mipHeight[c];e.bindFramebuffer(36160,a.bloomFbo[c]),e.viewport(0,0,d,f),e.bindTexture(3553,u),e.uniform2f(a.uDownTexelSize,1/h,1/m),e.uniform1f(a.uDownThreshold,c===0?o.threshold:0),e.drawArrays(4,0,3),u=a.bloomTex[c],h=d,m=f}e.enable(3042),typeof e.blendFuncSeparate=="function"?e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,771):e.blendFunc(e.ONE,e.ONE),e.useProgram(a.upProg),e.uniform1i(a.uUpBloomTex,0),e.uniform1f(a.uUpRadius,o.radius);for(let c=Ri-1;c>=1;c--){let d=c-1;e.bindFramebuffer(36160,a.bloomFbo[d]),e.viewport(0,0,a.mipWidth[d],a.mipHeight[d]),e.bindTexture(3553,a.bloomTex[c]),e.uniform2f(a.uUpTexelSize,1/a.mipWidth[c],1/a.mipHeight[c]),e.uniform1f(a.uUpStrength,.85),e.drawArrays(4,0,3)}e.bindFramebuffer(36160,null),e.viewport(0,0,i,n),e.bindTexture(3553,a.bloomTex[0]),e.uniform2f(a.uUpTexelSize,1/a.mipWidth[0],1/a.mipHeight[0]),e.uniform1f(a.uUpStrength,o.strength),e.drawArrays(4,0,3),e.bindVertexArray(null),e.blendFunc(770,771),e.disable(3042),e.depthMask(!0),e.enable(2929)},onDestroy(e){let t=Sr.get(e);if(t){e.deleteProgram(t.outlineProg),e.deleteProgram(t.downProg),e.deleteProgram(t.upProg),t.fsVao&&e.deleteVertexArray(t.fsVao),t.sceneTex&&e.deleteTexture(t.sceneTex);for(let r of t.bloomTex)r&&e.deleteTexture(r);for(let r of t.bloomFbo)r&&e.deleteFramebuffer(r);Sr.delete(e)}}};function Rs(e){let t=e?.extensions?.KHR_materials_variants?.variants;if(!Array.isArray(t))return[];let r=[];for(let i=0;i<t.length&&r.length<256;i++){let n=t[i]?.name;r.push(typeof n=="string"&&n.length>0?n:`Variant_${i}`)}return r}function Ao(e){let t=e?.extensions?.KHR_materials_variants?.mappings;if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let n=i,s=Number(n.material);if(!Number.isInteger(s)||s<0)continue;let l=[];if(Array.isArray(n.variants))for(let o of n.variants){let a=Number(o);Number.isInteger(a)&&a>=0&&l.push(a)}l.length>0&&r.push({material:s,variants:l})}return r}function To(e,t,r,i=0){let n=e;if(n&&typeof n.selectVariant=="function"&&!Array.isArray(t))return n.selectVariant(typeof t=="string"?t:null);let s=e,l=Array.isArray(t)?t:[],o=r??null;if(!o)return i;let a=Rs(s).indexOf(o);if(a<0)return i;for(let u of l)if(u.variants.includes(a))return u.material;return i}var Ps={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},So=new WeakMap,Es={name:"webxr-suite",onConfigureXRSessionInit(e,t){let r=new Set(t.optionalFeatures||[]);r.add("hit-test"),r.add("light-estimation");let i=e?.querySelector?.('[slot="ar-overlay"]')||null;i&&(r.add("dom-overlay"),t.domOverlay={root:i},i.addEventListener?.("beforexrselect",n=>{n.preventDefault()})),t.optionalFeatures=Array.from(r)},onXRFrame(e,t,r,i){if(!e||!t||!r||!i)return;let n=So.get(t);if(n||(n={lightProbe:null},So.set(t,n),typeof t.requestLightProbe=="function"&&t.requestLightProbe().then(s=>{n&&s&&(n.lightProbe=s)}).catch(()=>{})),n.lightProbe&&typeof r.getLightEstimate=="function"){let s=r.getLightEstimate(n.lightProbe);if(s){let l=s.primaryLightDirection,o=s.primaryLightIntensity;if(l&&o&&Array.isArray(e.lights)){let a=e.lights.find(h=>h.type==="directional");a||(a={type:"directional",direction:[.5,1,.8],color:[1,1,1],intensity:1},e.lights.push(a)),a.direction=[l.x,l.y,l.z];let u=Math.max(o.x,o.y,o.z,.001);a.color=[o.x/u,o.y/u,o.z/u],a.intensity=u}s.sphericalHarmonicsCoefficients&&e.gl&&us(e.gl,s.sphericalHarmonicsCoefficients)}}}};je(pi),je(ps),je(cs),je(vs),je(Es),je(xs),je(As),je(Ps),je(Ss),je($i),Ft.registerScriptRunner(br),typeof window<"u"&&(window.ThreeLiveBundle=Ds);export{Kr as AmbientLight,Gr as BoxGeometry,He as BufferAttribute,Ue as BufferGeometry,Zr as Camera,Vn as CapsuleGeometry,cn as CatmullRomCurve3,Un as CircleGeometry,Sn as Clock,ft as Color,sn as ConeGeometry,hn as CubicBezierCurve3,St as Curve3,Wr as CylinderGeometry,fn as DataTexture,Mn as DirectionalLight,Fn as DodecahedronGeometry,zn as EdgesGeometry,$r as Euler,Ji as Float32BufferAttribute,vn as Group,hi as HemisphereLight,Gs as IKSolver,kn as IcosahedronGeometry,qr as InstancedMesh,ys as InteractivityVM,Ks as LOD,jr as LatheGeometry,er as Light,Dt as Line,xr as LineBasicMaterial,ln as LineCurve3,Bn as LineDashedMaterial,$n as LineLoop,Hn as LineSegments,zi as LodController,Bs as MAX_BSP_DEPTH,Us as MAX_CSG_TRIANGLES,Jt as MAX_INSTANCES_PER_MESH,zs as MAX_SHAPE_POINTS,Os as MAX_TEXT_GEOMETRY_CHARS,tt as Material,Qi as MathUtils,Zi as Matrix3,_t as Matrix4,xt as Mesh,gn as MeshBasicMaterial,yn as MeshLambertMaterial,bn as MeshPhongMaterial,xn as MeshPhysicalMaterial,Qt as MeshStandardMaterial,pt as Object3D,Dn as OctahedronGeometry,wn as PerspectiveCamera,rn as PlaneGeometry,Yr as PointLight,Gn as Points,ui as PointsMaterial,Da as PolyhedronFallbackGeometry,Et as PolyhedronGeometry,un as QuadraticBezierCurve3,dr as Quaternion,_n as RawShaderMaterial,jn as RectAreaLight,li as RingGeometry,Qr as Scene,vt as SceneQuotaValidator,ai as ShaderMaterial,nn as SphereGeometry,Wn as SpotLight,kt as THREE,In as TetrahedronGeometry,gr as Texture,pn as TextureLoader,Ft as ThreeLiveElement,Ze as ThreeView,an as TorusGeometry,on as TorusKnotGeometry,mn as TubeGeometry,en as Uint16BufferAttribute,tn as Uint32BufferAttribute,lt as Vector2,xe as Vector3,Yi as Vector4,Tn as WebGLRenderer,On as WireframeGeometry,os as activateAR,Ms as applyMeshoptFilter,br as authorScriptRunner,ii as buildSandboxWorkerSource,Ci as cadPlugin,Ln as clearAuthorWarnings,vo as computeOutlineClipOffset,pi as contactShadowPlugin,zr as createUSDZBlob,Yn as crossFadeTo,qs as decimateGeometry,ws as decodeMeshoptBuffer,Ti as decodeMeshoptGLB,Ba as defineModelViewer,yo as encodeMeshoptBuffer,cs as environmentMapPlugin,xo as evaluateKawaseBloom,ta as evaluateToneMapping,Jr as exportSceneToCanvas3D,ei as exportSceneToGLB,An as exportSceneToUSDZ,Rs as extractMaterialVariants,Ao as extractPrimitiveVariantMappings,Or as generateUSDZ,di as getARCapabilities,Cn as getAllowClientScripts,Nn as getAuthorWarnings,Ga as getBestARMode,Xa as getEnvironmentSH,Mi as getInteractivityVM,Ys as getLodController,ri as getSandboxEngineSrc,En as getSandboxIframeSrc,Br as glbToUSDZ,ps as hotspotPlugin,Oi as ikPlugin,Pr as installCadExtension,ur as installLodExtension,xs as interactivityPlugin,It as isAllowedSandboxEngineUrl,ns as isQuickLookSupported,ss as isSceneViewerSupported,as as isWebXRSupported,Jn as keyframeAnimationPlugin,$i as lodPlugin,vs as materialsPlugin,Si as meshoptDecoder,As as meshoptPlugin,es as morphPlugin,tr as noopProxy,Kn as parseAnimations,Ts as parseHexRgb,Ir as parseLod,Ar as parseSafeGltfPointer,Ss as postprocessingPlugin,Nr as quatFromUnitVectors,io as registerMaterialShader,ir as sampleChannel,Zt as sceneToCanvas3D,fr as sceneToGLB,pr as sceneToUSDZ,_r as selectLodLevelIndex,To as selectMaterialVariant,bs as sendInteractivityEvent,Ra as setAllowClientScripts,us as setEnvironmentSH,$a as setMorphTargetWeight,Ta as setSandboxEngineSrc,Sa as setSandboxIframeSrc,rs as skinningPlugin,Di as solveFABRIK,Ii as solveTwoBoneIK,rr as threeAuthorPlugin,Ua as threeMicroPlugin,Yt as toGLBData,Rn as toTrustedWorkerScriptURL,ni as validateSandboxWorkerMessage,Ps as variantsPlugin,Pt as warnUnsupported,Es as webxrPlugin};
549
+ }`,zs=3,Zn=new WeakMap;function nc(e,t=[.22,.74,.97]){let r=Ih(e,"");if(!r.startsWith("#"))return[t[0],t[1],t[2]];let i=r.slice(1);if(i.length===3){let n=+("0x"+i[0]+i[0])/255,a=+("0x"+i[1]+i[1])/255,s=+("0x"+i[2]+i[2])/255;return[n,a,s]}if(i.length===6){let n=+("0x"+i.slice(0,2))/255,a=+("0x"+i.slice(2,4))/255,s=+("0x"+i.slice(4,6))/255;return[n,a,s]}return[t[0],t[1],t[2]]}function Am(e,t,r=.8,i=.5){let n=Number.isFinite(t)?Math.max(0,t):0;if(n<=0)return[0,0,0];let a=Math.max(0,Number(e[0])||0),s=Math.max(0,Number(e[1])||0),o=Math.max(0,Number(e[2])||0),l=Math.max(a,s,o);if(l<=1e-6)return[0,0,0];let c=Number.isFinite(r)?Math.max(0,r):.8,f=Math.max(c*Math.max(0,i),1e-4),m=Math.max(0,Math.min(2*f,l-c+f)),h=m*m/(4*f+1e-4),p=Math.min(1,Math.max(0,Math.max(h,l-c)/Math.max(l,1e-4)))*n;return[a*p,s*p,o*p]}function Tm(e,t,r,i){let n=Number(e[0])||0,a=Number(e[1])||0,s=Math.hypot(n,a);if(s<=1e-5||t<=0||r<=0)return[0,0];let o=Math.max(1,Number(i[0])||1),l=Math.max(1,Number(i[1])||1),c=Math.max(0,r)*2*t;return[n/s*(c/o),a/s*(c/l)]}var Pm=new WeakSet;function Nm(e){let t=Zn.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;Zn.delete(e)}if(Pm.has(e)||e.isContextLost?.())return null;let r=_i(e,O1,j1,!1),i=_i(e,Sm,G1,!1),n=_i(e,Sm,H1,!1);if(!r||!i||!n){for(let s of[r,i,n])s&&e.deleteProgram(s);return Pm.add(e),null}let a=typeof e.createVertexArray=="function"?e.createVertexArray():null;return t={outlineProg:r,uOutlineMVP:e.getUniformLocation(r,"uMVP"),uOutlineVP:e.getUniformLocation(r,"uVP"),uOutlineNormalMatrix:e.getUniformLocation(r,"uNormalMatrix"),uOutlineViewportSize:e.getUniformLocation(r,"uViewportSize"),uOutlineThickness:e.getUniformLocation(r,"uOutlineThickness"),uOutlineColor:e.getUniformLocation(r,"uOutlineColor"),downProg:i,uDownSourceTex:e.getUniformLocation(i,"uSourceTex"),uDownTexelSize:e.getUniformLocation(i,"uTexelSize"),uDownThreshold:e.getUniformLocation(i,"uThreshold"),upProg:n,uUpBloomTex:e.getUniformLocation(n,"uBloomTex"),uUpTexelSize:e.getUniformLocation(n,"uTexelSize"),uUpRadius:e.getUniformLocation(n,"uRadius"),uUpStrength:e.getUniformLocation(n,"uStrength"),fsVao:a,sceneTex:null,bloomTex:[],bloomFbo:[],mipWidth:[],mipHeight:[],texWidth:0,texHeight:0},Zn.set(e,t),t}function q1(e,t,r,i){if(typeof e.createFramebuffer!="function"||typeof e.copyTexSubImage2D!="function")return!1;let n=Math.max(2,r|0),a=Math.max(2,i|0);if(t.sceneTex&&t.bloomFbo.length===zs&&t.texWidth===n&&t.texHeight===a)return!0;t.sceneTex||(t.sceneTex=e.createTexture()),e.bindTexture(3553,t.sceneTex),e.texImage2D(3553,0,6408,n,a,0,6408,5121,null),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071);let s=n,o=a;for(let l=0;l<zs;l++)s=Math.max(1,s>>1),o=Math.max(1,o>>1),t.mipWidth[l]=s,t.mipHeight[l]=o,t.bloomTex[l]||(t.bloomTex[l]=e.createTexture()),e.bindTexture(3553,t.bloomTex[l]),e.texImage2D(3553,0,6408,s,o,0,6408,5121,null),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),t.bloomFbo[l]||(t.bloomFbo[l]=e.createFramebuffer()),e.bindFramebuffer(36160,t.bloomFbo[l]),e.framebufferTexture2D(36160,36064,3553,t.bloomTex[l],0);return e.bindFramebuffer(36160,null),t.texWidth=n,t.texHeight=a,!0}function W1(e){let t=e.container;if(t&&typeof t.getAttribute=="function"){let i=t.getAttribute("bloom");if(i!==null){let n=i.trim().toLowerCase();if(n==="false"||n==="0"||n==="none")return null;let a=n===""||n==="true"?.35:Number(n);if(!Number.isFinite(a)||a<=0)return null;let s=$h({strength:a,threshold:es(t.getAttribute("bloom-threshold"),.62),radius:es(t.getAttribute("bloom-radius"),.75)});if(s)return s}}let r=null;for(let i of e.meshes||[]){if(i.visible===!1)continue;let n=i?.extras?.xr?.bloom??i?.userData?.xr?.bloom,a=$h(n);a&&(!r||a.strength>r.strength)&&(r=a)}return r}function K1(e,t){if(e==null)return null;let r=e.trim(),i=r.toLowerCase();if(i==="false"||i==="0"||i==="none")return null;let n=t,a=3.5,s=!1;if(r&&i!=="true"){let o=r.split(/\s+/);for(let l of o)if(l.startsWith("#"))n=l;else if(l.toLowerCase()==="pulse")s=!0;else{let c=Number(l);Number.isFinite(c)&&c>0&&(a=c)}}return Fo({color:n,thickness:a,pulse:s})}var X1=new Set(["floor","pedestal","ground","table","grid","pad"]);function Y1(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>X1.has(t))}function Q1(e,t){let r=e.container,i=typeof r?.getAttribute=="function"?r.getAttribute("outline"):null;if(i!=null){let f=i.trim().toLowerCase();if(f==="false"||f==="0"||f==="none")return null}let n=t?.extras?.xr?.outline??t?.userData?.xr?.outline,a=Fo(n);if(a)return a;let s=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",o=K1(i,s),l=r!=null&&typeof r.hasAttribute=="function"&&r.hasAttribute("outline-selected")&&r.getAttribute("outline-selected")!=="false",c=e.getSelectedMesh?.()||"";if(c)return t.name!==c?null:o||(l?Fo({color:s,thickness:3,pulse:!1}):null);if(o){let f=t.name||"";return Y1(f)?null:o}return null}var ac={name:"postprocessing",onAttributeChanged(e,t){(t==="bloom"||t==="bloom-threshold"||t==="bloom-radius"||t==="outline"||t==="outline-selected"||t==="outline-color"||t==="selected-mesh")&&e.viewer?.render?.()},onAfterRender(e,t,r){if(!t.meshes||t.meshes.length===0)return;let i=Math.max(1,t.canvas?.width||300),n=Math.max(1,t.canvas?.height||150),a=[];for(let h of t.meshes){if(h.visible===!1)continue;let p=Q1(t,h);p&&a.push({mesh:h,trait:p})}let s=a.length>0?Nm(e):null;if(s){let h=s,p=lt(),g=lt(),x=new Float32Array(9),v=(typeof performance<"u"?performance.now():Date.now())*.001,y=typeof e.getParameter=="function"?e.getParameter(2978):null,A=Math.max(1,y?.[2]||i),b=Math.max(1,y?.[3]||n);e.useProgram(h.outlineProg),h.uOutlineViewportSize&&e.uniform2f(h.uOutlineViewportSize,A,b),h.uOutlineVP&&e.uniformMatrix4fv(h.uOutlineVP,!1,r),e.enable(e.CULL_FACE),e.cullFace(e.FRONT),e.enable(2929),e.depthFunc(515),e.depthMask(!1);for(let{mesh:w,trait:S}of a){let[E,N,C]=nc(S.color),_=S.pulse?.8+.25*Math.sin(v*4):1;h.uOutlineColor&&e.uniform4f(h.uOutlineColor,E,N,C,1),h.uOutlineThickness&&e.uniform1f(h.uOutlineThickness,S.thickness*_),w.worldSpace===!0?p.set(w.transform):ft(p,t.modelRootMatrix,w.transform);let P=w.instanceMatrices;for(let R of w.primitives)if(!(R.pluginData?.skinning?.hasSkin||R.pluginData?.morph?.hasMorph))if(e.bindVertexArray(R.vao),P&&P.length>=16){let I=P.length>>4,F=lt();for(let V=0;V<I;V++)ft(F,p,P.subarray(V*16,V*16+16)),ft(g,r,F),rr(x,F),e.uniformMatrix4fv(h.uOutlineMVP,!1,g),e.uniformMatrix3fv(h.uOutlineNormalMatrix,!1,x),R.indices?e.drawElements(4,R.indexCount,R.indexType,0):e.drawArrays(4,0,R.indexCount)}else ft(g,r,p),rr(x,p),e.uniformMatrix4fv(h.uOutlineMVP,!1,g),e.uniformMatrix3fv(h.uOutlineNormalMatrix,!1,x),R.indices?e.drawElements(4,R.indexCount,R.indexType,0):e.drawArrays(4,0,R.indexCount)}e.bindVertexArray(null),e.cullFace(e.BACK),e.disable(e.CULL_FACE),e.depthFunc(e.LESS),e.depthMask(!0)}if(t.xrSessionActive||t.stereoSBS)return;let o=W1(t);if(!o||o.strength<=0)return;let l=Nm(e);if(!l||!q1(e,l,i,n)||!l.fsVao)return;e.activeTexture(33984),e.bindTexture(3553,l.sceneTex),e.copyTexSubImage2D(3553,0,0,0,0,0,i,n),e.disable(2929),e.depthMask(!1),e.disable(3042),e.useProgram(l.downProg),e.uniform1i(l.uDownSourceTex,0),e.bindVertexArray(l.fsVao);let c=l.sceneTex,f=i,m=n;for(let h=0;h<zs;h++){let p=l.mipWidth[h],g=l.mipHeight[h];e.bindFramebuffer(36160,l.bloomFbo[h]),e.viewport(0,0,p,g),e.bindTexture(3553,c),e.uniform2f(l.uDownTexelSize,1/f,1/m),e.uniform1f(l.uDownThreshold,h===0?o.threshold:0),e.drawArrays(4,0,3),c=l.bloomTex[h],f=p,m=g}e.enable(3042),typeof e.blendFuncSeparate=="function"?e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,771):e.blendFunc(e.ONE,e.ONE),e.useProgram(l.upProg),e.uniform1i(l.uUpBloomTex,0),e.uniform1f(l.uUpRadius,o.radius);for(let h=zs-1;h>=1;h--){let p=h-1;e.bindFramebuffer(36160,l.bloomFbo[p]),e.viewport(0,0,l.mipWidth[p],l.mipHeight[p]),e.bindTexture(3553,l.bloomTex[h]),e.uniform2f(l.uUpTexelSize,1/l.mipWidth[h],1/l.mipHeight[h]),e.uniform1f(l.uUpStrength,.85),e.drawArrays(4,0,3)}e.bindFramebuffer(36160,null),e.viewport(0,0,i,n),e.bindTexture(3553,l.bloomTex[0]),e.uniform2f(l.uUpTexelSize,1/l.mipWidth[0],1/l.mipHeight[0]),e.uniform1f(l.uUpStrength,o.strength),e.drawArrays(4,0,3),e.bindVertexArray(null),e.blendFunc(770,771),e.disable(3042),e.depthMask(!0),e.enable(2929)},onDestroy(e){let t=Zn.get(e);if(t){e.deleteProgram(t.outlineProg),e.deleteProgram(t.downProg),e.deleteProgram(t.upProg),t.fsVao&&e.deleteVertexArray(t.fsVao),t.sceneTex&&e.deleteTexture(t.sceneTex);for(let r of t.bloomTex)r&&e.deleteTexture(r);for(let r of t.bloomFbo)r&&e.deleteFramebuffer(r);Zn.delete(e)}}},Jn=4,sc=9,Z1=32*1024*1024,Vs=lt(),Cm=new Int32Array([-1,-1]);function oc(e,t,r,i){let n=Number(e);return Number.isFinite(n)?Math.max(t,Math.min(r,n)):i}var Em=new WeakMap,ri=new WeakMap,ea=new WeakMap,nn=lt(),Us=lt(),ii=lt(),an=lt(),Lm=new Float32Array(1),J1=new Uint32Array(Lm.buffer);function lc(e){if(typeof e!="string")return"auto";let t=e.trim().toLowerCase();return t==="pcf"||t==="off"?t:"auto"}function eg(e){let t=Em.get(e);if(t)return t;let r=1/0,i=1/0,n=1/0,a=-1/0,s=-1/0,o=-1/0;for(let c=0;c+2<e.length;c+=3){let f=e[c],m=e[c+1],h=e[c+2];f<r&&(r=f),f>a&&(a=f),m<i&&(i=m),m>s&&(s=m),h<n&&(n=h),h>o&&(o=h)}let l=Number.isFinite(r)?[r,i,n,a,s,o]:[-.5,-.5,-.5,.5,.5,.5];return Em.set(e,l),l}function sn(e,t,r,i){let n=(e[0]+e[3])*.5,a=(e[1]+e[4])*.5,s=(e[2]+e[5])*.5,o=Math.max(0,(e[3]-e[0])*.5),l=Math.max(0,(e[4]-e[1])*.5),c=Math.max(0,(e[5]-e[2])*.5),f=t[0]*n+t[4]*a+t[8]*s+t[12],m=t[1]*n+t[5]*a+t[9]*s+t[13],h=t[2]*n+t[6]*a+t[10]*s+t[14],p=Math.abs(t[0])*o+Math.abs(t[4])*l+Math.abs(t[8])*c,g=Math.abs(t[1])*o+Math.abs(t[5])*l+Math.abs(t[9])*c,x=Math.abs(t[2])*o+Math.abs(t[6])*l+Math.abs(t[10])*c;f-p<r[0]&&(r[0]=f-p),m-g<r[1]&&(r[1]=m-g),h-x<r[2]&&(r[2]=h-x),f+p>i[0]&&(i[0]=f+p),m+g>i[1]&&(i[1]=m+g),h+x>i[2]&&(i[2]=h+x)}function uc(e){let t=e||{},r=t.modelRootMatrix??Vs,i=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let m of t.meshes??[]){if(!hc(m))continue;m.worldSpace===!0?ii.set(m.transform):ft(ii,r,m.transform);let h=m.instanceMatrices;for(let p of m.primitives??[]){if(!p.positions||p.positions.length<3)continue;let g=eg(p.positions);if(h&&h.length>=16){let x=h.length>>4,v=x>64?Math.ceil(x/64):1;for(let y=0;y<x;y+=v)ft(an,ii,h.subarray(y*16,y*16+16)),sn(g,an,i,n);if(v>1){let y=x-1;ft(an,ii,h.subarray(y*16,y*16+16)),sn(g,an,i,n)}}else sn(g,ii,i,n)}}if(!Number.isFinite(i[0])){let m=t.bounds;m&&Array.isArray(m.min)&&Array.isArray(m.max)&&sn([m.min[0],m.min[1],m.min[2],m.max[0],m.max[1],m.max[2]],r,i,n)}Number.isFinite(i[0])||(i[0]=i[1]=i[2]=-1,n[0]=n[1]=n[2]=1);let a=(i[0]+n[0])*.5,s=(i[1]+n[1])*.5,o=(i[2]+n[2])*.5,l=Math.max(.03,(n[0]-i[0])*.5),c=Math.max(.03,(n[1]-i[1])*.5),f=Math.max(.03,(n[2]-i[2])*.5);return{center:[a,s,o],radius:Math.max(.05,Math.hypot(l,c,f)),min:[a-l,s-c,o-f],max:[a+l,s+c,o+f]}}function cc(e,t,r){let i=Number(t[0])||0,n=Number(t[1])||0,a=Number(t[2])||0,s=Math.hypot(i,n,a);s>1e-6?(i/=s,n/=s,a/=s):(i=.37139067,n=.74278135,a=.59422508);let o=Math.max(.05,r.radius),[l,c,f]=r.center,m=o*2.2,h=[l+i*m,c+n*m,f+a*m],p=Math.abs(n)>.99?[0,0,1]:[0,1,0];_n(nn,h,r.center,p);let g=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0];sn([...r.min,...r.max],nn,g,x);let v=Math.max(.02,o*.05),y=Math.max(.01,-x[2]-v),A=Math.max(y+.1,-g[2]+v);return q0(Us,g[0]-v,Math.max(g[0]+.05,x[0])+v,g[1]-v,Math.max(g[1]+.05,x[1])+v,y,A),ft(e,Us,nn)}function Os(e,t,r,i,n,a){let s=Number(t[0])||0,o=Number(t[1])||0,l=Number(t[2])||0,c=Number(r[0])||0,f=Number(r[1])||0,m=Number(r[2])||0,h=Math.hypot(c,f,m);h<=1e-6&&(c=a.center[0]-s,f=a.center[1]-o,m=a.center[2]-l,h=Math.hypot(c,f,m)),h>1e-6?(c/=h,f/=h,m/=h):(c=0,f=-1,m=0);let p=Math.abs(f)>.99?[0,0,1]:[0,1,0];_n(nn,[s,o,l],[s+c,o+f,l+m],p);let g=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0];sn([...a.min,...a.max],nn,g,x);let v=-x[2],y=-g[2],A=Math.max(.05,a.radius),b=Math.hypot(a.center[0]-s,a.center[1]-o,a.center[2]-l),w=Math.max(.5,y+A*.25,b+A),S=n&&n>0?Math.max(.25,Math.min(n,w)):w,E=Math.max(.02,S/1500),N=Math.min(S*.4,Math.max(E,Number.isFinite(v)?v-A*.05:E)),C=Math.max(.08,Math.min(2.35,i*2*1.04));return uo(Us,C,1,N,Math.max(N+.1,S)),ft(e,Us,nn)}function Rm(e){let t=e||{};for(let b of t.meshes??[])if(b.name==="__xr_section_gizmo__"&&b.visible!==!1&&b.worldMatrix&&b.worldMatrix.length>=16){let w=b.worldMatrix,S=Math.hypot(w[8],w[9],w[10])||1,E=w[8]/S,N=w[9]/S,C=w[10]/S;return{enabled:!0,normal:[E,N,C],constant:E*w[12]+N*w[13]+C*w[14]}}let r=(t.container?.getAttribute?.("section-plane")??"").trim().toLowerCase();if(!r||r==="none"||r==="false")return null;let i=[1,0,0],n=0;if(r==="interactive")n=t.bounds?.center[0]??0;else{let b=/^([+-]?[xyz])\s*:\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)$/.exec(r);if(!b)return null;let w=b[1].startsWith("-")?-1:1,S=b[1].replace(/^[+-]/,""),E=Math.max(-1e3,Math.min(1e3,Number(b[2])||0));i=S==="x"?[w,0,0]:S==="y"?[0,w,0]:[0,0,w],n=E*w}let a=t.modelRootMatrix??Vs,s=a[0]*i[0]+a[4]*i[1]+a[8]*i[2],o=a[1]*i[0]+a[5]*i[1]+a[9]*i[2],l=a[2]*i[0]+a[6]*i[1]+a[10]*i[2],c=Math.hypot(s,o,l)||1,f=s/c,m=o/c,h=l/c,p=i[0]*n,g=i[1]*n,x=i[2]*n,v=a[0]*p+a[4]*g+a[8]*x+a[12],y=a[1]*p+a[5]*g+a[9]*x+a[13],A=a[2]*p+a[6]*g+a[10]*x+a[14];return{enabled:!0,normal:[f,m,h],constant:f*v+m*y+h*A}}function hc(e){if(e.visible===!1||e.isPluginMesh||e.name==="__contact_shadow__"||e.name==="__xr_reticle__"||e.name==="__xr_section_gizmo__")return!1;let t=e.extras?.xr??e.userData?.xr;return!(t?.splatUrl||t?.splat)}function on(e,t){if(!hc(e))return!1;let r=e.castShadow??e.extras?.shadow?.cast;return r===!1?!1:t?!0:r===!0}function js(e,t){if(!e||typeof e!="object")return!1;let r=e;if(!hc(r))return!1;let i=r.receiveShadow??r.extras?.shadow?.receive;return i!==void 0?!!i:t}function fc(e){return!(e.isTransmissive||e.alphaMode==="BLEND"||(e.baseColor?.[3]??1)<.98)}function ni(e,t){return Math.imul((e^t>>>0)>>>0,16777619)>>>0}function ai(e,t){return Lm[0]=t||0,ni(e,J1[0])}function ta(e,t,r=64){let i=t.length;if(e=ni(e,i),i<=r)for(let n=0;n<i;n++)e=ai(e,t[n]);else{let n=Math.max(1,Math.floor(i/r));for(let a=0;a<i;a+=n)e=ai(e,t[a]);e=ai(e,t[i-1])}return e}function Gs(e){let t=e||{},r=t.shadowMaps??t.container?.getAttribute?.("shadow-maps")??"auto",i=lc(r),n=[-1,-1],a=[-1,-1],s=(I=!1)=>({mode:i,mapSize:0,slices:[],dirSlots:n,ptSlots:a,promoteAllCasters:I,promoteAllReceivers:I,digest:0,sectionPlane:null});if(i==="off")return s();let o=[],l=null,c=null,f=!1,m=0,h=0;for(let I of t.lights??[])I.type==="hemisphere"?f=!0:I.type==="directional"&&m<2?(l||(l=I),I.shadow?.cast&&o.length<Jn&&o.push({kind:"directional",subIdx:m,light:I}),m++):(I.type==="spot"||I.type==="point")&&h<2&&(c||(c={kind:I.type,light:I}),I.shadow?.cast&&o.length<Jn&&o.push({kind:I.type,subIdx:h,light:I}),h++);if(i==="pcf"&&o.length===0&&(l?o.push({kind:"directional",subIdx:0,light:l}):f?c&&o.push({kind:c.kind,subIdx:0,light:c.light}):o.push({kind:"directional",subIdx:0,light:{type:"directional",direction:[.5,1,.8]}})),o.length===0)return s();let p=t.meshes??[],g=!1;for(let I of p)if(I.castShadow!==void 0||I.receiveShadow!==void 0||I.extras?.shadow!==void 0){g=!0;break}let x=i==="pcf"||!g,v=x,y=!1;for(let I of p)if(on(I,x)){for(let F of I.primitives??[])if(fc(F)&&F.indexCount>0){y=!0;break}if(y)break}if(!y)return s(x);let A=1024;for(let I of o){let F=I.light.shadow?.mapSize;typeof F=="number"&&Number.isFinite(F)&&(A=Math.max(A,Math.round(F)))}let b=Math.max(256,Math.min(2048,A)),w=o.length;for(;b>256&&b*b*w*4>Z1;)b=Math.max(256,b>>1);let S=uc(t),E=S.radius*2.2/b,N=[];for(let I=0;I<o.length;I++){let F=o[I],V=F.light,Y=V.shadow,J=lt(),re;if(F.kind==="directional"){n[F.subIdx]=I;let G=V.direction??[.5,1,.8],q=Math.hypot(G[0]??.5,G[1]??1,G[2]??.8)||1;re=[-(G[0]??.5)/q,-(G[1]??1)/q,-(G[2]??.8)/q],cc(J,G,S)}else{a[F.subIdx]=I;let G=V.position??[0,2,0];if(F.kind==="spot"){let q=V.direction??[0,-1,0],H=Math.hypot(q[0]??0,q[1]??-1,q[2]??0)||1;re=[(q[0]??0)/H,(q[1]??-1)/H,(q[2]??0)/H];let te=Math.max(.02,Math.min(Math.PI/2,V.outerConeAngle??Math.PI/3));Os(J,G,re,te,V.range,S)}else{let q=S.center[0]-(G[0]??0),H=S.center[1]-(G[1]??0),te=S.center[2]-(G[2]??0),Z=Math.hypot(q,H,te);re=Z>1e-6?[q/Z,H/Z,te/Z]:[0,-1,0],Os(J,G,re,Math.PI/3,V.range,S)}}let Q=oc(Y?.bias,-.05,.05,-5e-4),ee=oc(Y?.normalBias,0,.5,.015),k=oc(Y?.radius,0,16,1.5);N.push({slot:I,viewProj:J,rayDir:re,depthBias:Q,normalBiasWorld:ee/.015*1.75*E,uvRadius:k*1.35/b})}let C=Rm(t),_=2166136261;_=ni(_,i==="pcf"?2:1),_=ni(_,b),_=ni(_,N.length);for(let I of N)_=ta(_,I.viewProj,16),_=ai(_,I.depthBias),_=ai(_,I.normalBiasWorld);C?.enabled?(_=ni(_,1),_=ai(_,C.normal[0]),_=ai(_,C.normal[1]),_=ai(_,C.normal[2]),_=ai(_,C.constant)):_=ni(_,0);let P=t.modelRootMatrix??Vs;_=ta(_,P,16);let R=0;for(let I of p){if(!on(I,x)){R++;continue}_=ni(_,R++),_=ta(_,I.transform,16),I.instanceMatrices&&(_=ta(_,I.instanceMatrices,64));for(let F of I.primitives??[])fc(F)&&(_=ni(_,F.indexCount),F.translations&&(_=ta(_,F.translations,48)))}return _===0&&(_=1),{mode:i,mapSize:b,slices:N,dirSlots:n,ptSlots:a,promoteAllCasters:x,promoteAllReceivers:v,digest:_,sectionPlane:C}}function Im(e){let t=ri.get(e);return t?{renderedPasses:t.renderedPasses,cacheHits:t.cacheHits,activeLights:t.activeLights,mapSize:t.allocSize}:{renderedPasses:0,cacheHits:0,activeLights:0,mapSize:0}}var tg=`#version 300 es
550
+ layout(location=0) in vec3 aPos;
551
+ layout(location=1) in vec3 aNormal;
552
+ layout(location=3) in vec3 aOff;
553
+ layout(location=8) in vec4 aInst0;
554
+ layout(location=9) in vec4 aInst1;
555
+ layout(location=10) in vec4 aInst2;
556
+ layout(location=11) in vec4 aInst3;
557
+ uniform mat4 uLightVP,uModel;
558
+ uniform vec4 uBiasRay;
559
+ uniform int uInstanced;
560
+ out vec3 vWorldPos;
561
+ void main(){
562
+ mat4 m=uInstanced==1?uModel*mat4(aInst0,aInst1,aInst2,aInst3):uModel;
563
+ vec4 wp=m*vec4(aPos+aOff,1.0);
564
+ vec3 wn=mat3(m)*aNormal;
565
+ float nl=length(wn);
566
+ if(nl>1e-5&&uBiasRay.w>0.0){
567
+ wn/=nl;
568
+ wp.xyz+=wn*(uBiasRay.w*max(1.0-abs(dot(wn,uBiasRay.xyz)),0.15));
569
+ }
570
+ vWorldPos=wp.xyz;
571
+ gl_Position=uLightVP*wp;
572
+ }`,rg=`#version 300 es
573
+ precision highp float;
574
+ in vec3 vWorldPos;
575
+ uniform vec4 uSecPlane;
576
+ uniform int uSecOn;
577
+ void main(){
578
+ if(uSecOn==1&&dot(vWorldPos,uSecPlane.xyz)>uSecPlane.w)discard;
579
+ }`,ig=`
580
+ uniform highp sampler2DArrayShadow uShadowMap;
581
+ uniform mat4 uShadowVP[4];
582
+ uniform vec4 uShadowParams[4];
583
+ uniform int uDirShdSlot[2],uPtShdSlot[2],uReceiveShadow;
584
+ const vec2 _VD[8]=vec2[8](
585
+ vec2(0.1768,0.0),vec2(-0.2265,0.2078),vec2(0.0355,-0.4150),vec2(0.3204,0.3888),
586
+ vec2(-0.5562,-0.1455),vec2(0.4916,-0.3806),vec2(-0.1419,0.6596),vec2(-0.5177,-0.5150));
587
+ float shdEval(int s,vec3 wp,vec3 N,vec3 L){
588
+ if(s<0||uReceiveShadow==0)return 1.0;
589
+ float nl=dot(N,L);
590
+ if(nl<=0.0)return 0.0;
591
+ mat4 vp=s==0?uShadowVP[0]:s==1?uShadowVP[1]:s==2?uShadowVP[2]:uShadowVP[3];
592
+ vec4 p=s==0?uShadowParams[0]:s==1?uShadowParams[1]:s==2?uShadowParams[2]:uShadowParams[3];
593
+ vec4 sc=vp*vec4(wp+N*(p.y*(1.0-nl)),1.0);
594
+ if(sc.w<=1e-6)return 1.0;
595
+ vec3 u=sc.xyz/sc.w*0.5+0.5;
596
+ if(u.x<=0.002||u.x>=0.998||u.y<=0.002||u.y>=0.998||u.z>1.0||u.z<0.0)return 1.0;
597
+ float rz=clamp(u.z+p.x,0.0,1.0);
598
+ if(p.z<=1e-6)return texture(uShadowMap,vec4(u.xy,float(s),rz));
599
+ float a=fract(52.9829189*fract(dot(gl_FragCoord.xy,vec2(0.06711056,0.00583715))))*6.2831853;
600
+ float ca=cos(a),sa=sin(a),sum=0.0;
601
+ mat2 rot=mat2(ca,sa,-sa,ca);
602
+ for(int k=0;k<8;k++)sum+=texture(uShadowMap,vec4(u.xy+rot*_VD[k]*p.z,float(s),rz));
603
+ return sum*0.125;
604
+ }`,ng=["uShadowMap","uShadowVP","uShadowParams","uDirShdSlot","uPtShdSlot","uReceiveShadow"];function ag(e){let t=ri.get(e);return t||(t={texArray:null,fbo:null,allocSize:0,allocLayers:0,lastDigest:0,renderedPasses:0,cacheHits:0,activeLights:0,vpFlat:new Float32Array(64),paramsFlat:new Float32Array(16),dirSlots:new Int32Array([-1,-1]),ptSlots:new Int32Array([-1,-1]),promoteAllReceivers:!1},ri.set(e,t)),t}function $m(e,t,r){let i=e.createTexture?.();if(!i)return null;let n=35866;if(e.bindTexture(n,i),typeof e.texStorage3D=="function")e.texStorage3D(n,1,33190,t,t,r);else if(typeof e.texImage3D=="function")e.texImage3D(n,0,33190,t,t,r,0,6402,5125,null);else return e.deleteTexture?.(i),null;return e.texParameteri(n,10241,9729),e.texParameteri(n,10240,9729),e.texParameteri(n,10242,33071),e.texParameteri(n,10243,33071),e.texParameteri(n,34892,34894),e.texParameteri(n,34893,515),i}function Dm(e){let t=ea.get(e);if(t&&(t.prog===null||e.isProgram?.(t.prog)!==!1))return t;let r=null,i=e.createShader?.(35633),n=e.createShader?.(35632);if(i&&n){e.shaderSource(i,tg),e.compileShader(i),e.shaderSource(n,rg),e.compileShader(n);let a=e.createProgram();a&&(e.attachShader(a,i),e.attachShader(a,n),e.linkProgram(a),e.detachShader?.(a,i),e.detachShader?.(a,n),e.getProgramParameter(a,35714)!==!1?r=a:e.deleteProgram(a)),e.deleteShader(i),e.deleteShader(n)}return t={prog:r,uLightVP:r?e.getUniformLocation(r,"uLightVP"):null,uModel:r?e.getUniformLocation(r,"uModel"):null,uBiasRay:r?e.getUniformLocation(r,"uBiasRay"):null,uInstanced:r?e.getUniformLocation(r,"uInstanced"):null,uSecPlane:r?e.getUniformLocation(r,"uSecPlane"):null,uSecOn:r?e.getUniformLocation(r,"uSecOn"):null,dummyArrayTex:$m(e,1,1)},ea.set(e,t),t}var km={uniformsGLSL:ig,dirGLSL:"*shdEval(uDirShdSlot[i],vWorldPos,N,normalize(uDirLightDir[i]))",ptGLSL:"*shdEval(uPtShdSlot[i],vWorldPos,N,L)",uniformNames:ng,bind(e,t,r,i){let n=t.uShadowMap;if(n===void 0)return;let a=r&&typeof r=="object"?ri.get(r):void 0,s=Dm(e),o=!!(a&&a.activeLights>0&&a.texArray),l=o?a.texArray:s.dummyArrayTex;l&&(e.activeTexture(33993),e.bindTexture(35866,l)),n&&e.uniform1i(n,sc);let c=t.uDirShdSlot,f=t.uPtShdSlot,m=t.uReceiveShadow;if(!o){c&&e.uniform1iv?.(c,Cm),f&&e.uniform1iv?.(f,Cm),m&&e.uniform1i?.(m,0);return}c&&e.uniform1iv?.(c,a.dirSlots),f&&e.uniform1iv?.(f,a.ptSlots);let h=t.uShadowVP;h&&e.uniformMatrix4fv?.(h,!1,a.vpFlat);let p=t.uShadowParams;p&&e.uniform4fv?.(p,a.paramsFlat),m&&e.uniform1i?.(m,js(i,a.promoteAllReceivers)?1:0)}};function Fm(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}var mc={name:"shadow-maps",onRegister(){We().shadowMapShader=km},onLoadModel(e){if(e&&typeof e=="object"){let t=ri.get(e);t&&(t.lastDigest=0)}},onClearScene(e){if(e&&typeof e=="object"){let t=ri.get(e);t&&(t.lastDigest=0,t.activeLights=0)}},onContextRestored(e,t){if(ea.delete(e),t&&typeof t=="object"){let r=ri.get(t);r&&(r.texArray=null,r.fbo=null,r.allocSize=0,r.allocLayers=0,r.lastDigest=0,r.activeLights=0)}},onDestroy(e,t){if(t&&typeof t=="object"){let r=ri.get(t);r&&(r.texArray&&e.deleteTexture?.(r.texArray),r.fbo&&e.deleteFramebuffer?.(r.fbo),ri.delete(t))}else if(e){let r=ea.get(e);r&&(r.prog&&e.deleteProgram?.(r.prog),r.dummyArrayTex&&e.deleteTexture?.(r.dummyArrayTex),ea.delete(e))}},onBeforeDrawScene(e,t){if(!e||typeof e!="object")return;let r=e,i=We();if(i.shadowMapShader||(i.shadowMapShader=km),r.uRender&&!("uShadowMap"in r.uRender)&&r.recompileRenderProgram?.(),i.gpuSceneAccelerator?.willRenderScene?.(e))return;let n=ag(e),a=Gs(r);if(n.promoteAllReceivers=a.promoteAllReceivers,n.dirSlots[0]=a.dirSlots[0],n.dirSlots[1]=a.dirSlots[1],n.ptSlots[0]=a.ptSlots[0],n.ptSlots[1]=a.ptSlots[1],a.slices.length===0||typeof t.framebufferTextureLayer!="function"){n.activeLights=0;return}let s=Dm(t);if(!s.prog){n.activeLights=0;return}let o=a.slices.length;if(!n.texArray||!n.fbo||n.allocSize!==a.mapSize||n.allocLayers<o){n.texArray&&t.deleteTexture?.(n.texArray);let p=Math.max(n.allocLayers,o);if(n.texArray=$m(t,a.mapSize,p),n.fbo||(n.fbo=t.createFramebuffer?.()??null),!n.texArray||!n.fbo){n.activeLights=0;return}n.allocSize=a.mapSize,n.allocLayers=p,n.lastDigest=0}n.activeLights=o,n.vpFlat.fill(0),n.paramsFlat.fill(0);for(let p of a.slices){n.vpFlat.set(p.viewProj,p.slot*16);let g=p.slot*4;n.paramsFlat[g]=p.depthBias,n.paramsFlat[g+1]=p.normalBiasWorld*.5,n.paramsFlat[g+2]=p.uvRadius}if(n.lastDigest===a.digest){n.cacheHits++;return}n.lastDigest=a.digest;let l=t.getParameter?.(36006)??null,c=t.getParameter?.(2978),f=c&&c.length>=4?[c[0],c[1],c[2],c[3]]:[0,0,Math.max(1,r.canvas?.width||1),Math.max(1,r.canvas?.height||1)],m=r.modelRootMatrix??Vs,h=r.meshes??[];t.bindFramebuffer(36160,n.fbo),t.drawBuffers?.([0]),t.readBuffer?.(0),t.viewport(0,0,a.mapSize,a.mapSize),t.colorMask?.(!1,!1,!1,!1),t.depthMask?.(!0),t.enable(2929),t.enable(32823),t.polygonOffset?.(1.5,4),t.useProgram(s.prog),s.uSecOn&&(a.sectionPlane?.enabled?(t.uniform1i(s.uSecOn,1),s.uSecPlane&&t.uniform4f(s.uSecPlane,a.sectionPlane.normal[0],a.sectionPlane.normal[1],a.sectionPlane.normal[2],a.sectionPlane.constant)):t.uniform1i(s.uSecOn,0));for(let p of a.slices){t.framebufferTextureLayer(36160,36096,n.texArray,0,p.slot),t.clear(256),s.uLightVP&&t.uniformMatrix4fv(s.uLightVP,!1,p.viewProj),s.uBiasRay&&t.uniform4f(s.uBiasRay,p.rayDir[0],p.rayDir[1],p.rayDir[2],p.normalBiasWorld);for(let g of h){if(!on(g,a.promoteAllCasters))continue;g.worldSpace===!0?ii.set(g.transform):ft(ii,m,g.transform);let x=g.instanceMatrices;for(let v of g.primitives??[])if(!(!v.vao||v.indexCount<=0||!fc(v)))if(t.bindVertexArray(v.vao),t.vertexAttrib3f?.(3,0,0,0),s.uInstanced&&t.uniform1i(s.uInstanced,0),s.uModel&&t.uniformMatrix4fv(s.uModel,!1,ii),v.instanceCount!==void 0)t.drawElementsInstanced(4,v.indexCount,v.indexType,0,v.instanceCount);else if(x&&x.length>=16&&v.instanced&&s.uInstanced){let y=x.length>>4;t.uniform1i(s.uInstanced,1),v.indices?t.drawElementsInstanced(4,v.indexCount,v.indexType,0,y):t.drawArraysInstanced(4,0,v.indexCount,y),t.uniform1i(s.uInstanced,0)}else if(x&&x.length>=16){let y=x.length>>4;for(let A=0;A<y;A++)ft(an,ii,x.subarray(A*16,A*16+16)),s.uModel&&t.uniformMatrix4fv(s.uModel,!1,an),Fm(t,v)}else Fm(t,v)}n.renderedPasses++}t.bindVertexArray(null),t.disable(32823),t.colorMask?.(!0,!0,!0,!0),t.bindFramebuffer(36160,l),t.viewport(f[0],f[1],f[2],f[3])}};function pc(e){let t=e?.extensions?.KHR_materials_variants?.variants;if(!Array.isArray(t))return[];let r=[];for(let i=0;i<t.length&&r.length<256;i++){let n=t[i]?.name;r.push(typeof n=="string"&&n.length>0?n:`Variant_${i}`)}return r}function Bm(e){let t=e?.extensions?.KHR_materials_variants?.mappings;if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let n=i,a=Number(n.material);if(!Number.isInteger(a)||a<0)continue;let s=[];if(Array.isArray(n.variants))for(let o of n.variants){let l=Number(o);Number.isInteger(l)&&l>=0&&s.push(l)}s.length>0&&r.push({material:a,variants:s})}return r}function zm(e,t,r,i=0){let n=e;if(n&&typeof n.selectVariant=="function"&&!Array.isArray(t))return n.selectVariant(typeof t=="string"?t:null);let a=e,s=Array.isArray(t)?t:[],o=r??null;if(!o)return i;let l=pc(a).indexOf(o);if(l<0)return i;for(let c of s)if(c.variants.includes(l))return c.material;return i}var dc={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},Vm=new WeakMap,gc={name:"webxr-suite",onConfigureXRSessionInit(e,t){let r=new Set(t.optionalFeatures||[]);r.add("hit-test"),r.add("light-estimation");let i=e?.querySelector?.('[slot="ar-overlay"]')||null;i&&(r.add("dom-overlay"),t.domOverlay={root:i},i.addEventListener?.("beforexrselect",n=>{n.preventDefault()})),t.optionalFeatures=Array.from(r)},onXRFrame(e,t,r,i){if(!e||!t||!r||!i)return;let n=Vm.get(t);if(n||(n={lightProbe:null},Vm.set(t,n),typeof t.requestLightProbe=="function"&&t.requestLightProbe().then(a=>{n&&a&&(n.lightProbe=a)}).catch(()=>{})),n.lightProbe&&typeof r.getLightEstimate=="function"){let a=r.getLightEstimate(n.lightProbe);if(a){let s=a.primaryLightDirection,o=a.primaryLightIntensity;if(s&&o&&Array.isArray(e.lights)){let l=e.lights.find(f=>f.type==="directional");l||(l={type:"directional",direction:[.5,1,.8],color:[1,1,1],intensity:1},e.lights.push(l)),l.direction=[s.x,s.y,s.z];let c=Math.max(o.x,o.y,o.z,.001);l.color=[o.x/c,o.y/c,o.z/c],l.intensity=c}a.sphericalHarmonicsCoefficients&&e.gl&&ju(e.gl,a.sphericalHarmonicsCoefficients)}}}};Rt(Ps),Rt(mc),Rt(Ku),Rt(Hu),Rt(ec),Rt(gc),Rt(Ju),Rt(ic),Rt(dc),Rt(ac),Rt(Mo);var Um=272,sg=["x","y","z","w"],Om=[[2,"vec2<f32>"],[3,"vec3<f32>"],[4,"vec4<f32>"]];function ln(e,t){return Om.map(([r,i])=>{let n=sg.slice(0,r).map(a=>t===2?`${e}1(a.${a},b.${a})`:`${e}1(a.${a},b.${a},c.${a})`).join(",");return t===2?`fn ${e}${r}(a:${i},b:${i})->${i}{return ${i}(${n});}`:`fn ${e}${r}(a:${i},b:${i},c:${i})->${i}{return ${i}(${n});}`})}function jm(e,t){let r=[];return e.div&&r.push("fn _tslDiv1(a:f32,b:f32)->f32{return a/select(b,select(1e-6,-1e-6,b<0.0),abs(b)<1e-6);}",...ln("_tslDiv",2)),e.mod&&r.push("fn _tslMod1(a:f32,b:f32)->f32{let d=select(b,select(1e-6,-1e-6,b<0.0),abs(b)<1e-6);return a-d*floor(a/d);}",...ln("_tslMod",2)),e.pow&&r.push("fn _tslPow1(a:f32,b:f32)->f32{let e=clamp(b,-64.0,64.0);if(abs(e)<1e-8){return 1.0;}if(a<=0.0){return 0.0;}return pow(max(a,1e-8),e);}",...ln("_tslPow",2)),e.clamp&&r.push("fn _tslClamp1(a:f32,b:f32,c:f32)->f32{return clamp(a,min(b,c),max(b,c));}",...ln("_tslClamp",3)),e.smooth&&r.push("fn _tslSmooth1(a:f32,b:f32,c:f32)->f32{let t=_tslClamp1(_tslDiv1(c-a,b-a),0.0,1.0);return t*t*(3.0-2.0*t);}",...ln("_tslSmooth",3)),e.atan2&&r.push("fn _tslAtan1(a:f32,b:f32)->f32{return select(atan2(a,b),0.0,abs(a)<1e-8&&abs(b)<1e-8);}",...ln("_tslAtan",2)),e.norm&&r.push("fn _tslNorm1(v:f32)->f32{return select(0.0,sign(v),abs(v)>1e-6);}",...Om.map(([i,n])=>`fn _tslNorm${i}(v:${n})->${n}{let l=length(v);return select(${n}(0.0),v/l,l>1e-6);}`)),(e.snoise2||e.snoise3||e.voronoi2)&&r.push("fn _tslM289(x:f32)->f32{return x-floor(x*(1.0/289.0))*289.0;}","fn _tslPerm(x:f32)->f32{return _tslM289((x*34.0+10.0)*x);}"),e.snoise2&&r.push("fn _tslSNoise2(v:vec2<f32>)->f32{let c0=0.21132487;let c1=0.3660254;let c2=-0.57735026;let c3=0.024390243;let s=(v.x+v.y)*c1;var ix=floor(v.x+s);var iy=floor(v.y+s);let t=(ix+iy)*c0;let x0=v.x-ix+t;let y0=v.y-iy+t;let i1x=select(0.0,1.0,x0>y0);let i1y=1.0-i1x;let x1=x0+c0-i1x;let y1=y0+c0-i1y;let x2=x0+c2;let y2=y0+c2;ix=_tslM289(ix);iy=_tslM289(iy);let p0=_tslPerm(_tslPerm(iy)+ix);let p1=_tslPerm(_tslPerm(iy+i1y)+ix+i1x);let p2=_tslPerm(_tslPerm(iy+1.0)+ix+1.0);var m=max(vec3<f32>(0.5)-vec3<f32>(x0*x0+y0*y0,x1*x1+y1*y1,x2*x2+y2*y2),vec3<f32>(0.0));m=m*m;m=m*m;let gx=2.0*fract(vec3<f32>(p0,p1,p2)*c3)-vec3<f32>(1.0);let hy=abs(gx)-vec3<f32>(0.5);let ox=gx-floor(gx+vec3<f32>(0.5));m*=vec3<f32>(1.7928429)-0.85373473*(ox*ox+hy*hy);return clamp(0.5+65.0*dot(m,ox*vec3<f32>(x0,x1,x2)+hy*vec3<f32>(y0,y1,y2)),0.0,1.0);}"),e.snoise3&&r.push("fn _tslSNoise3(v:vec3<f32>)->f32{let c0=0.16666667;let c1=0.33333334;let ns=0.14285715;let s=(v.x+v.y+v.z)*c1;var i0=floor(v.x+s);var i1=floor(v.y+s);var i2=floor(v.z+s);let t=(i0+i1+i2)*c0;let p0=v-vec3<f32>(i0,i1,i2)+vec3<f32>(t);let g=step(p0.yzx,p0.xyz);let l=vec3<f32>(1.0)-g.zxy;let a1=min(g,l);let a2=max(g,l);let p1=p0-a1+vec3<f32>(c0);let p2=p0-a2+vec3<f32>(c1);let p3=p0-vec3<f32>(0.5);i0=_tslM289(i0);i1=_tslM289(i1);i2=_tslM289(i2);let hs=array<f32,4>(_tslPerm(_tslPerm(_tslPerm(i2)+i1)+i0),_tslPerm(_tslPerm(_tslPerm(i2+a1.z)+i1+a1.y)+i0+a1.x),_tslPerm(_tslPerm(_tslPerm(i2+a2.z)+i1+a2.y)+i0+a2.x),_tslPerm(_tslPerm(_tslPerm(i2+1.0)+i1+1.0)+i0+1.0));let qs=array<vec3<f32>,4>(p0,p1,p2,p3);var sum=0.0;for(var k=0;k<4;k=k+1){let pk=hs[k];let j=pk-49.0*floor(pk*ns*ns);let x_=floor(j*ns);let y_=floor(j-7.0*x_);var gx=x_*(2.0/7.0)+(1.0/7.0)-1.0;var gy=y_*(2.0/7.0)+(1.0/7.0)-1.0;let gz=1.0-abs(gx)-abs(gy);let sz=select(0.0,1.0,gz<0.0);gx-=sz*select(-1.0,1.0,gx>=0.0);gy-=sz*select(-1.0,1.0,gy>=0.0);let inv=1.7928429-0.85373473*(gx*gx+gy*gy+gz*gz);let q=qs[k];var m=max(0.6-dot(q,q),0.0);m=m*m;m=m*m;sum+=m*inv*(gx*q.x+gy*q.y+gz*q.z);}return clamp(0.5+21.0*sum,0.0,1.0);}"),e.voronoi2&&r.push("fn _tslVoronoi2(u:vec2<f32>,jit:f32)->f32{let n=floor(u);let fr=u-n;let jt=clamp(jit,0.0,1.0);var md=8.0;for(var dy=-1;dy<=1;dy=dy+1){for(var dx=-1;dx<=1;dx=dx+1){let qx=_tslM289(n.x+f32(dx));let qy=_tslM289(n.y+f32(dy));let hx=fract(_tslPerm(_tslPerm(qx)+qy)*(1.0/41.0));let hy=fract(_tslPerm(_tslPerm(qy+7.0)+qx+13.0)*(1.0/41.0));md=min(md,length(vec2<f32>(f32(dx),f32(dy))+vec2<f32>(0.5)+(vec2<f32>(hx,hy)-vec2<f32>(0.5))*jt-fr));}}return clamp(md,0.0,1.0);}"),e.checker&&r.push("fn _tslChecker(p:vec2<f32>)->f32{return select(0.0,1.0,_tslMod1(floor(p.x)+floor(p.y),2.0)>=1.0);}"),e.fresnel&&r.push("fn _tslFresnel(pw:f32,nw:vec3<f32>,vd:vec3<f32>)->f32{return _tslPow1(1.0-clamp(dot(_tslNorm3(nw),_tslNorm3(vd)),0.0,1.0),max(pw,1e-3));}"),e.triplanar&&r.push("fn _tslTriplanar(p:vec3<f32>,sh:f32,nw:vec3<f32>)->f32{let w=_tslPow3(max(abs(_tslNorm3(nw)),vec3<f32>(1e-4)),vec3<f32>(clamp(sh,0.5,16.0)));return(w.x*_tslSNoise2(p.yz)+w.y*_tslSNoise2(p.xz)+w.z*_tslSNoise2(p.xy))/max(w.x+w.y+w.z,1e-6);}"),e.hueShift&&r.push("fn _tslHueShift(rgb:vec3<f32>,ang:f32)->vec3<f32>{let k=vec3<f32>(0.57735026);let c=cos(ang);let s=sin(ang);return rgb*c+cross(k,rgb)*s+k*dot(k,rgb)*(1.0-c);}"),e.bump&&t&&r.push("fn _tslBump(dhx:f32,dhy:f32,st:f32,nw:vec3<f32>,dx:vec3<f32>,dy:vec3<f32>)->vec3<f32>{let n=_tslNorm3(nw);let r1=cross(dy,n);let r2=cross(n,dx);let det=dot(dx,r1);if(abs(det)<1e-8){return n;}return _tslNorm3(abs(det)*n-st*select(1.0,-1.0,det<0.0)*(dhx*r1+dhy*r2));}"),r.join(`
605
+ `)}var og={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function yc(e,t){let r=[],i=s=>s==="float"?"f32":`${s}<f32>`,n=(s,o)=>s==="float"?o:`${s}<f32>(${o})`,a=(s,o,l)=>o===l?s:`${l}<f32>(${s})`;for(let s=0;s<e.length;s++){if(!t[s])continue;let o=e[s],l=o.type,c=nr(l),f=o.args[0]!==void 0?`_t${o.args[0]}`:"",m=o.args[1]!==void 0?`_t${o.args[1]}`:"",h=o.args[2]!==void 0?`_t${o.args[2]}`:"",p=o.args[0]!==void 0?e[o.args[0]].type:"float",g=o.args[1]!==void 0?e[o.args[1]].type:"float",x=o.args[2]!==void 0?e[o.args[2]].type:"float",v=n(l,"0.0");switch(o.op){case"const":{let y=(o.value??[0]).map(Xr);v=l==="float"?y[0]:`${l}<f32>(${y.join(",")})`;break}case"builtin":v=o.builtin==="time"?`_tslMod1(tslU.timeAndPad.x,${Xr(3600)})`:og[o.builtin]??"0.0";break;case"uniform":{let y=`tslU.params[${o.uniformSlot??0}]`;v=c===4?y:`${y}.${"xyz".slice(0,c)}`;break}case"swizzle":v=p==="float"?n(l,f):`${f}.${o.mask}`;break;case"construct":v=l==="float"?f:`${l}<f32>(${o.args.map(y=>`_t${y}`).join(",")})`;break;case"neg":v=`(-${f})`;break;case"abs":case"sign":case"floor":case"ceil":case"fract":case"sin":case"cos":v=`${o.op}(${f})`;break;case"sqrt":v=`sqrt(max(${f},${n(l,"0.0")}))`;break;case"exp":v=`exp(clamp(${f},${n(l,"-80.0")},${n(l,"80.0")}))`;break;case"log":v=`log(max(${f},${n(l,"1.0e-8")}))`;break;case"normalize":v=`_tslNorm${c}(${f})`;break;case"add":case"sub":case"mul":{let y=o.op==="add"?"+":o.op==="sub"?"-":"*";v=`(${a(f,p,l)}${y}${a(m,g,l)})`;break}case"div":case"mod":case"pow":case"atan2":{v=`${o.op==="div"?"_tslDiv":o.op==="mod"?"_tslMod":o.op==="pow"?"_tslPow":"_tslAtan"}${c}(${a(f,p,l)},${a(m,g,l)})`;break}case"min":case"max":case"step":v=`${o.op}(${a(f,p,l)},${a(m,g,l)})`;break;case"clamp":v=`_tslClamp${c}(${a(f,p,l)},${a(m,g,l)},${a(h,x,l)})`;break;case"mix":v=`mix(${f},${m},${a(h,x,l)})`;break;case"smoothstep":v=`_tslSmooth${c}(${a(f,p,l)},${a(m,g,l)},${a(h,x,l)})`;break;case"dot":v=p==="float"?`(${f}*${m})`:`dot(${f},${m})`;break;case"length":v=p==="float"?`abs(${f})`:`length(${f})`;break;case"distance":v=p==="float"?`abs(${f}-${m})`:`distance(${f},${m})`;break;case"cross":case"reflect":v=`${o.op}(${f},${m})`;break;case"fresnel":v=`_tslFresnel(${f},_tslNW,_tslVD)`;break;case"simplexNoise2D":v=`_tslSNoise2(${f})`;break;case"simplexNoise3D":v=`_tslSNoise3(${f})`;break;case"voronoi2D":v=`_tslVoronoi2(${f},${m})`;break;case"checker":v=`_tslChecker(${f})`;break;case"triplanar":v=`_tslTriplanar(${f},${m},_tslNW)`;break;case"hueShift":v=`_tslHueShift(${f},${m})`;break;case"bumpFromHeight":v=`_tslBump(dpdx(${f}),-dpdy(${f}),${m},_tslNW,p1,p2)`;break;default:break}r.push(` let _t${s}:${i(l)}=${v};`)}return r.join(`
606
+ `)}function bc(e,t,r){let i=`struct TslUniformBlock{params:array<vec4<f32>,16>,timeAndPad:vec4<f32>,};
607
+ `,n=new Uint8Array(e.nodes.length);for(let c=0;c<e.nodes.length;c++)n[c]=e.fragmentReachable[c]||e.vertexReachable[c];let a=e.fragmentReachable.some(c=>c===1),s=jm(Na(e.nodes,n,e.usesTime),!0),o=t.replace("@group(1) @binding(4) var emTex: texture_2d<f32>;",`@group(1) @binding(4) var emTex: texture_2d<f32>;
608
+ ${i}@group(2) @binding(0) var<uniform> tslU: TslUniformBlock;`).replace("@location(3) @interpolate(flat) instIdx: u32,",`@location(3) @interpolate(flat) instIdx: u32,
609
+ @location(4) localPos: vec3<f32>,
610
+ @location(5) localNorm: vec3<f32>,`).replace(`out.instIdx = instIdx;
611
+ return out;`,`out.instIdx = instIdx;
612
+ out.localPos = vec3<f32>(0.0);
613
+ out.localNorm = vec3<f32>(0.0, 1.0, 0.0);
614
+ return out;`);if(s&&(o=o.replace("@vertex",`${s}
615
+ @vertex`)),e.usesVertexPosition&&e.outputs.position!==void 0){let c=`fn _tslEvalPos(_tslPL:vec3<f32>,_tslNL:vec3<f32>,_tslUV:vec2<f32>,_tslVC:vec4<f32>,_tslII:f32,m:mat4x4<f32>)->vec3<f32>{
616
+ let _tslPW=(m*vec4<f32>(_tslPL,1.0)).xyz;let _rn=m[0].xyz*_tslNL.x+m[1].xyz*_tslNL.y+m[2].xyz*_tslNL.z;let _rl=length(_rn);
617
+ let _tslNW=select(vec3<f32>(0.0,1.0,0.0),_rn/_rl,_rl>1e-5);let _tslVD=vec3<f32>(0.0,0.0,1.0);
618
+ ${yc(e.nodes,e.vertexReachable)}
619
+ return _t${e.outputs.position};}`;o=o.replace("@vertex",`${c}
620
+ @vertex`).replace("let world = m * vec4<f32>(aPos, 1.0);",`let _tslInstF=f32(instIdx);let _tslNewP=_tslEvalPos(aPos,aNormal,aUV,vec4<f32>(1.0),_tslInstF,m);var _tslNewN=aNormal;
621
+ if(length(aNormal)>1e-4){let _n0=normalize(aNormal);let _tg1=normalize(select(cross(vec3<f32>(1.0,0.0,0.0),_n0),cross(vec3<f32>(0.0,1.0,0.0),_n0),abs(_n0.y)<0.99));let _tg2=cross(_n0,_tg1);let _cn=cross(_tslEvalPos(aPos+_tg1*1e-3,aNormal,aUV,vec4<f32>(1.0),_tslInstF,m)-_tslNewP,_tslEvalPos(aPos+_tg2*1e-3,aNormal,aUV,vec4<f32>(1.0),_tslInstF,m)-_tslNewP);if(length(_cn)>1e-10){_tslNewN=normalize(_cn);}}
622
+ let world = m * vec4<f32>(_tslNewP, 1.0);`).replace(`rawN = (adj0 * aNormal.x + adj1 * aNormal.y + adj2 * aNormal.z) * sgn;
623
+ } else {
624
+ rawN = c0 * aNormal.x + c1 * aNormal.y + c2 * aNormal.z;`,`rawN = (adj0 * _tslNewN.x + adj1 * _tslNewN.y + adj2 * _tslNewN.z) * sgn;
625
+ } else {
626
+ rawN = c0 * _tslNewN.x + c1 * _tslNewN.y + c2 * _tslNewN.z;`).replace(`out.instIdx = instIdx;
627
+ return out;`,`out.instIdx = instIdx;
628
+ out.localPos = _tslNewP;
629
+ out.localNorm = _tslNewN;
630
+ return out;`)}else o=o.replace(`out.instIdx = instIdx;
631
+ return out;`,`out.instIdx = instIdx;
632
+ out.localPos = aPos;
633
+ out.localNorm = aNormal;
634
+ return out;`);if(a){let c=` let _nL=length(in.normal);var _nU:vec3<f32>;if(_nL<1e-4){let _fc=cross(p1,p2);let _fl=length(_fc);_nU=select(vec3<f32>(0.0,1.0,0.0),_fc/_fl,_fl>1e-8);}else{_nU=in.normal/_nL;}if(!frontFacing){_nU=-_nU;}
635
+ let _toC=sc.camAndExp.xyz-in.worldPos;let _cD=length(_toC);let _tslVD=select(vec3<f32>(0.0,0.0,1.0),_toC/_cD,_cD>1e-6);let _tslNW=_nU;
636
+ let _lnL=length(in.localNorm);let _tslNL=select(vec3<f32>(0.0,1.0,0.0),in.localNorm/_lnL,_lnL>1e-5);let _tslPL=in.localPos;let _tslPW=in.worldPos;let _tslUV=in.uv;let _tslVC=vec4<f32>(1.0);let _tslII=f32(in.instIdx);
637
+ ${yc(e.nodes,e.fragmentReachable)}`;o=o.replace("let emTexel = textureSample(emTex, linSampler, in.uv);",`let emTexel = textureSample(emTex, linSampler, in.uv);
638
+ ${c}`),e.outputs.opacity!==void 0&&(o=o.replace(`if (base.a < 0.004) {
639
+ discard;
640
+ }`,`base.a = clamp(_t${e.outputs.opacity}, 0.0, 1.0);
641
+ if (base.a < 0.004) {
642
+ discard;
643
+ }`)),o=o.replace("if (nInLen < 1e-4 && (pFlags & 2u) != 0u) {","if (false && nInLen < 1e-4 && (pFlags & 2u) != 0u) {"),e.outputs.normalScale!==void 0&&e.outputs.bump===void 0&&(o=o.replace("q = vec3<f32>(q.xy * p.aux.x, q.z);",`q = vec3<f32>(q.xy * max(_t${e.outputs.normalScale}, 0.0), q.z);`));let f=[];if(e.outputs.color!==void 0&&f.push(` base=vec4<f32>(max(_t${e.outputs.color},vec3<f32>(0.0)),base.a);`),e.outputs.emissive!==void 0&&f.push(` em=max(_t${e.outputs.emissive},vec3<f32>(0.0));`),e.outputs.roughness!==void 0&&f.push(` roughness=clamp(_t${e.outputs.roughness},0.04,1.0);`),e.outputs.metalness!==void 0&&f.push(` metallic=clamp(_t${e.outputs.metalness},0.0,1.0);`),e.outputs.bump!==void 0){let m=e.outputs.normalScale!==void 0?`max(_t${e.outputs.normalScale},0.0)`:"1.0";f.push(` let _bn=_t${e.outputs.bump};let _bl=length(_bn);if(_bl>1e-6){let _bm=N+(_bn/_bl-N)*(${m});let _ml=length(_bm);if(_ml>1e-6){N=_bm/_ml;}}`)}f.length>0&&(o=o.replace("metallic = clamp(metallic, 0.0, 1.0);",`metallic = clamp(metallic, 0.0, 1.0);
644
+ ${f.join(`
645
+ `)}`))}let l=null;if(e.usesVertexPosition&&e.outputs.position!==void 0){let c=jm(Na(e.nodes,e.vertexReachable,e.usesTime),!1),f=yc(e.nodes,e.vertexReachable);l=r.replace("@group(0) @binding(1) var<storage, read> parts: array<PartInstance>;",`@group(0) @binding(1) var<storage, read> parts: array<PartInstance>;
646
+ ${i}@group(1) @binding(0) var<uniform> tslU: TslUniformBlock;
647
+ ${c}`).replace("@location(1) aNormal: vec3<f32>,",`@location(1) aNormal: vec3<f32>,
648
+ @location(2) aUV: vec2<f32>,`).replace("var wp = m * vec4<f32>(aPos, 1.0);",`let _tslPL=aPos;let _tslPW=(m*vec4<f32>(aPos,1.0)).xyz;let _tslNL=aNormal;let _rn=m[0].xyz*aNormal.x+m[1].xyz*aNormal.y+m[2].xyz*aNormal.z;let _rl=length(_rn);let _tslNW=select(vec3<f32>(0.0,1.0,0.0),_rn/_rl,_rl>1e-5);let _tslVD=vec3<f32>(0.0,0.0,1.0);let _tslUV=aUV;let _tslVC=vec4<f32>(1.0);let _tslII=f32(instIdx);
649
+ ${f}
650
+ var wp = m * vec4<f32>(_t${e.outputs.position}, 1.0);`)}return{hash:e.hash,pbrWgsl:o,shadowDepthWgsl:l}}var ra=new WeakMap,un=new WeakMap,Gm=new WeakMap,ia=new Map,lg=128;function ug(e,t){let r=Gm.get(t);return r||(r={paramsLoc:e.getUniformLocation(t,"uTslParams[0]")??e.getUniformLocation(t,"uTslParams"),timeLoc:e.getUniformLocation(t,"uTslTime")},Gm.set(t,r)),r}function cg(e,t){let r=new Float32Array(68);for(let i of t.uniformSlots){let n=i.slot*4;r[n]=i.defaultVec4[0],r[n+1]=i.defaultVec4[1],r[n+2]=i.defaultVec4[2],r[n+3]=i.defaultVec4[3]}return{name:e,hash:t.hash,graph:t,buf68:r,usesTime:t.usesTime,usesVertexPosition:t.usesVertexPosition,version:1}}function na(e,t){let r=new Map,i=new Map,n=!1,a=Array.isArray(t?.materials)?t.materials:[];for(let l=0;l<a.length;l++){let c=a[l],f=c?.extensions?.[Ui];if(!f)continue;let m=typeof c.name=="string"&&c.name.length>0?c.name:`Material_${l}`,h=Oi(f,m);if(!h.ok){console.warn(`[three-live] [${h.issue.code}] ${h.issue.message} Falling back to base PBR material.`);continue}let p=cg(m,h.graph);r.set(l,p);let g=i.get(m)??[];g.push(p),i.set(m,g),h.graph.usesTime&&(n=!0)}let s={materialsByIndex:r,materialsByName:i,hasAnimatedTsl:n,elapsedSec:0};ra.set(e,s);let o=e.gl;return o&&typeof o=="object"&&un.set(o,s),s}function Hm(e,t){let r=ra.get(e);if(!r){let i=t??e.gltf;if(!i)return null;r=na(e,i)}return r}function hg(e){if(e==null)return null;if(typeof e=="number"||Array.isArray(e)||e instanceof Float32Array)return e;if(typeof e=="object"){let t=e;if("r"in t&&"g"in t&&"b"in t)return[Number(t.r),Number(t.g),Number(t.b)];if("x"in t&&"y"in t&&"z"in t&&"w"in t)return[Number(t.x),Number(t.y),Number(t.z),Number(t.w)];if("x"in t&&"y"in t&&"z"in t)return[Number(t.x),Number(t.y),Number(t.z)];if("x"in t&&"y"in t)return[Number(t.x),Number(t.y)]}return null}function xc(e,t,r,i){if(!e||typeof e!="object")return!1;let n=e,a=n.viewer&&typeof n.viewer=="object"?n.viewer:e,s=Hm(a);if(!s||s.materialsByIndex.size===0)return!1;let o=t==="*"||t===""?Array.from(s.materialsByIndex.values()):s.materialsByName.get(t)??[];if(o.length===0)return!1;let l=hg(i);if(l===null)return!1;let c=!1;for(let f of o){let m=f.graph.uniformSlotByName.get(r);if(!m)continue;let h=Pa(m.type,l);if(!h)continue;let p=m.slot*4;f.buf68[p]=h[0],f.buf68[p+1]=h[1],f.buf68[p+2]=h[2],f.buf68[p+3]=h[3],f.version++,c=!0}return c&&a.animFrameId===null&&typeof a.render=="function"&&a.render(),c}function Hs(e){if(!e||typeof e!="object")return;let t=e;typeof t.setMaterialUniform!="function"&&(t.setMaterialUniform=(r,i,n)=>xc(e,r,i,n))}function fg(){let e=We();Mn(Ta);let t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t?Ta(t,e):e.authorNamespace||(e.authorNamespace={}),e.tslWgslCompiler=(r,i,n)=>!r||typeof r!="object"?null:bc(r,i,n),e.tslMaterialResolver=(r,i)=>i===void 0||i<0?null:Hm(r)?.materialsByIndex.get(i)??null,e.tslUsdzSerializer=Do}var vc={name:"tsl",onRegister(){fg()},onElementConnected(e){Hs(e),e?.viewer&&(Hs(e.viewer),e.viewer.gltf&&(na(e.viewer,e.viewer.gltf),e.viewer.recompileRenderProgram?.()))},onBuildPrimitiveVAO(e,t,r,i){let n=r?.material;if(typeof n!="number")return null;let a=i?.materials?.[n]?.extensions?.[Ui];if(!a)return null;let s=Oi(a,i?.materials?.[n]?.name||`Material_${n}`);return s.ok?{hash:s.graph.hash,materialIndex:n}:null},onResolveShader(e,t,r,i){let n=t?.extensions?.[Ui];if(!n)return null;let a=Oi(n,t?.name||"Material");if(!a.ok)return console.warn(`[three-live] [${a.issue.code}] ${a.issue.message} Falling back to base PBR shader.`),null;let s=`${a.graph.hash}|${r.length}|${i.length}|${i.slice(-64)}`,o=ia.get(s);if(!o){if(ia.size>=lg){let l=ia.keys().next().value;l!==void 0&&ia.delete(l)}o=$o(a.graph,r,i),ia.set(s,o)}return o},onLoadModel(e,t){Hs(e),e?.container&&Hs(e.container),na(e,t).hasAnimatedTsl&&e&&e.animFrameId===null&&typeof e.start=="function"&&e.opts?.autoStart!==!1&&typeof requestAnimationFrame<"u"&&e.start()},onUpdate(e,t){let r=ra.get(e);if(!r||!r.hasAnimatedTsl)return;let i=Number.isFinite(t)&&t>0?Math.min(t,.25):0;r.elapsedSec=Lo(r.elapsedSec+i,3600);for(let n of r.materialsByIndex.values())n.usesTime&&(n.buf68[64]=r.elapsedSec,n.version++)},onBeforeDrawPrimitive(e,t,r,i,n,a){let s=r?.materialIndex;if(typeof s!="number"||!a?.materials?.[s]?.extensions?.[Ui])return;let o=ug(e,t);if(!o.paramsLoc&&!o.timeLoc)return;let l=un.get(e);l||(l=na(e,a),un.set(e,l));let c=l.materialsByIndex.get(s);c&&(o.paramsLoc&&e.uniform4fv(o.paramsLoc,c.buf68,0,64),o.timeLoc&&e.uniform1f(o.timeLoc,c.buf68[64]))},onClearScene(e){ra.delete(e),e?.gl&&typeof e.gl=="object"&&un.delete(e.gl)},onContextRestored(e,t){if(t?.gltf){let r=na(t,t.gltf);e&&typeof e=="object"&&un.set(e,r)}},onDestroy(e,t){ra.delete(t),e&&typeof e=="object"&&un.delete(e)}};Rt(vc);var qm=800,Wm=32,Km=128,Xm=8,Ym=32;function aa(e,t){for(let r=0;r<4;r++){let i=r*4,n=t[i+2],a=t[i+3];e[i]=t[i],e[i+1]=t[i+1],e[i+2]=.5*(n+a),e[i+3]=a}return e}function qs(e,t){let r=new Float32Array(e,0,200),i=new Uint32Array(e,0,200),n=new Int32Array(e,0,200);r.fill(0),aa(r.subarray(0,16),t.vp);for(let x=0;x<16;x++)r[16+x]=t.modelRoot[x]??(x%5===0?1:0);r[32]=t.eyePos[0],r[33]=t.eyePos[1],r[34]=t.eyePos[2],r[35]=Number.isFinite(t.exposure)?Math.max(0,t.exposure):1;let a=.28,s=.28,o=.28,l=!1,c=0,f=1,m=0,h=0,p=0;for(let x of t.lights){let v=x.color??[1,1,1],y=x.intensity!==void 0?x.intensity:1;if(x.type==="ambient")a=(v[0]??1)*y,s=(v[1]??1)*y,o=(v[2]??1)*y;else if(x.type==="hemisphere"){l=!0;let A=x.groundColor??[.2,.2,.2],b=y*.65;r[40]+=(v[0]??1)*b,r[41]+=(v[1]??1)*b,r[42]+=(v[2]??1)*b,r[44]+=(A[0]??.2)*b,r[45]+=(A[1]??.2)*b,r[46]+=(A[2]??.2)*b;let w=x.position??[0,1,0],S=Math.hypot(w[0]??0,w[1]??1,w[2]??0);S>1e-5&&(c=(w[0]??0)/S,f=(w[1]??1)/S,m=(w[2]??0)/S)}else if(x.type==="directional"&&h<2){let A=x.direction??[.5,1,.8],b=52+h*8;r[b]=A[0]??.5,r[b+1]=A[1]??1,r[b+2]=A[2]??.8,r[b+4]=(v[0]??1)*y,r[b+5]=(v[1]??1)*y,r[b+6]=(v[2]??1)*y,h++}else if((x.type==="point"||x.type==="spot")&&p<2){let A=x.position??[0,0,0],b=68+p*16;if(r[b]=A[0]??0,r[b+1]=A[1]??0,r[b+2]=A[2]??0,r[b+4]=(v[0]??1)*y,r[b+5]=(v[1]??1)*y,r[b+6]=(v[2]??1)*y,x.type==="spot"){let w=x.direction??[0,-1,0],S=Math.max(.01,Math.min(Math.PI/2,x.outerConeAngle??Math.PI/3)),E=Math.max(0,Math.min(S-1e-4,x.innerConeAngle??0)),N=Math.hypot(w[0]??0,w[1]??-1,w[2]??0)||1;r[b+8]=(w[0]??0)/N,r[b+9]=(w[1]??-1)/N,r[b+10]=(w[2]??0)/N,r[b+12]=Math.cos(E),r[b+13]=Math.cos(S)}else r[b+9]=-1,r[b+12]=-2,r[b+13]=-3;p++}}h===0&&!l&&(r[52]=.5,r[53]=1,r[54]=.8,r[56]=1,r[57]=1,r[58]=1,h=1),r[36]=a,r[37]=s,r[38]=o,r[39]=Number.isFinite(t.envIntensity)?Math.max(0,t.envIntensity):1,r[48]=c,r[49]=f,r[50]=m;let g=0;if(t.hasEnvMap&&(g|=1),t.sectionPlane?.enabled&&(g|=2,r[100]=t.sectionPlane.normal[0],r[101]=t.sectionPlane.normal[1],r[102]=t.sectionPlane.normal[2],r[103]=t.sectionPlane.constant),t.isRightEye&&(g|=4),t.contactShadow&&t.contactShadow.intensity>0&&(r[104]=t.contactShadow.centerX,r[105]=t.contactShadow.floorY,r[106]=t.contactShadow.centerZ,r[107]=Math.max(.01,t.contactShadow.halfExtentX),r[108]=Math.max(.01,t.contactShadow.halfExtentZ),r[109]=Math.min(1,Math.max(0,t.contactShadow.intensity)),r[110]=Math.min(1,Math.max(0,t.contactShadow.softness))),i[112]=Math.max(0,t.toneMappingIndex|0)>>>0,i[113]=h>>>0,i[114]=p>>>0,i[115]=g>>>0,n[196]=-1,n[197]=-1,n[198]=-1,n[199]=-1,t.shadowMap&&t.shadowMap.slices.length>0){for(let x of t.shadowMap.slices){if(x.slot<0||x.slot>=4)continue;aa(r.subarray(116+x.slot*16,132+x.slot*16),x.viewProj);let v=180+x.slot*4;r[v]=x.depthBias,r[v+1]=x.normalBiasWorld*.5,r[v+2]=x.uvRadius}n[196]=t.shadowMap.dirSlots[0]|0,n[197]=t.shadowMap.dirSlots[1]|0,n[198]=t.shadowMap.ptSlots[0]|0,n[199]=t.shadowMap.ptSlots[1]|0}}function mg(e,t,r,i,n,a){let s=new Float32Array(e,0,44),o=new Uint32Array(e,0,44);s.fill(0),aa(s.subarray(0,16),t);for(let l=0;l<16;l++)s[16+l]=r[l]??(l%5===0?1:0);s[32]=i[0],s[33]=i[1],s[34]=i[2],s[35]=n,a?.enabled&&(s[36]=a.normal[0],s[37]=a.normal[1],s[38]=a.normal[2],s[39]=a.constant,o[40]=1)}var wc=`
651
+ struct SceneUniforms {
652
+ viewProj: mat4x4<f32>,
653
+ modelRoot: mat4x4<f32>,
654
+ camAndExp: vec4<f32>,
655
+ ambAndEnv: vec4<f32>,
656
+ hemiSky: vec4<f32>,
657
+ hemiGround: vec4<f32>,
658
+ hemiAxis: vec4<f32>,
659
+ dirDir0: vec4<f32>,
660
+ dirCol0: vec4<f32>,
661
+ dirDir1: vec4<f32>,
662
+ dirCol1: vec4<f32>,
663
+ ptPos0: vec4<f32>,
664
+ ptCol0: vec4<f32>,
665
+ ptSpotDir0: vec4<f32>,
666
+ ptSpotCone0: vec4<f32>,
667
+ ptPos1: vec4<f32>,
668
+ ptCol1: vec4<f32>,
669
+ ptSpotDir1: vec4<f32>,
670
+ ptSpotCone1: vec4<f32>,
671
+ sectionPlane: vec4<f32>,
672
+ shadowBox: vec4<f32>,
673
+ shadowParams: vec4<f32>,
674
+ flags: vec4<u32>,
675
+ shdVP0: mat4x4<f32>,
676
+ shdVP1: mat4x4<f32>,
677
+ shdVP2: mat4x4<f32>,
678
+ shdVP3: mat4x4<f32>,
679
+ shdParams0: vec4<f32>,
680
+ shdParams1: vec4<f32>,
681
+ shdParams2: vec4<f32>,
682
+ shdParams3: vec4<f32>,
683
+ shdSlots: vec4<i32>,
684
+ };
685
+
686
+ struct PartInstance {
687
+ model: mat4x4<f32>,
688
+ baseColor: vec4<f32>,
689
+ pbr: vec4<f32>,
690
+ emissive: vec4<f32>,
691
+ aux: vec2<f32>,
692
+ flags: u32,
693
+ pickId: u32,
694
+ };
695
+
696
+ @group(0) @binding(0) var<uniform> sc: SceneUniforms;
697
+ @group(0) @binding(1) var<storage, read> parts: array<PartInstance>;
698
+ @group(0) @binding(2) var linSampler: sampler;
699
+ @group(0) @binding(3) var envTex: texture_2d<f32>;
700
+ @group(0) @binding(4) var shadowSampler: sampler_comparison;
701
+ @group(0) @binding(5) var shadowTex: texture_depth_2d_array;
702
+ `,Ws=wc+`
703
+ @group(1) @binding(0) var baseTex: texture_2d<f32>;
704
+ @group(1) @binding(1) var mrTex: texture_2d<f32>;
705
+ @group(1) @binding(2) var normTex: texture_2d<f32>;
706
+ @group(1) @binding(3) var occTex: texture_2d<f32>;
707
+ @group(1) @binding(4) var emTex: texture_2d<f32>;
708
+
709
+ struct VsOut {
710
+ @builtin(position) clipPos: vec4<f32>,
711
+ @location(0) worldPos: vec3<f32>,
712
+ @location(1) normal: vec3<f32>,
713
+ @location(2) uv: vec2<f32>,
714
+ @location(3) @interpolate(flat) instIdx: u32,
715
+ };
716
+
717
+ @vertex
718
+ fn vsMain(
719
+ @location(0) aPos: vec3<f32>,
720
+ @location(1) aNormal: vec3<f32>,
721
+ @location(2) aUV: vec2<f32>,
722
+ @builtin(instance_index) instIdx: u32,
723
+ ) -> VsOut {
724
+ let p = parts[instIdx];
725
+ var out: VsOut;
726
+ if ((p.flags & 128u) != 0u) {
727
+ out.clipPos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
728
+ out.worldPos = vec3<f32>(0.0);
729
+ out.normal = vec3<f32>(0.0, 1.0, 0.0);
730
+ out.uv = vec2<f32>(0.0);
731
+ out.instIdx = instIdx;
732
+ return out;
733
+ }
734
+ var m: mat4x4<f32>;
735
+ if ((p.flags & 1u) != 0u) {
736
+ m = p.model;
737
+ } else {
738
+ m = sc.modelRoot * p.model;
739
+ }
740
+ let world = m * vec4<f32>(aPos, 1.0);
741
+
742
+ let c0 = m[0].xyz;
743
+ let c1 = m[1].xyz;
744
+ let c2 = m[2].xyz;
745
+ let adj0 = cross(c1, c2);
746
+ let adj1 = cross(c2, c0);
747
+ let adj2 = cross(c0, c1);
748
+ let det = dot(c0, adj0);
749
+ var rawN = vec3<f32>(0.0);
750
+ if (abs(det) > 1e-12) {
751
+ let sgn = select(-1.0, 1.0, det > 0.0);
752
+ rawN = (adj0 * aNormal.x + adj1 * aNormal.y + adj2 * aNormal.z) * sgn;
753
+ } else {
754
+ rawN = c0 * aNormal.x + c1 * aNormal.y + c2 * aNormal.z;
755
+ }
756
+ let nLen = length(rawN);
757
+
758
+ let stereoMode = (p.flags >> 8u) & 3u;
759
+ let isRight = (sc.flags.w & 4u) != 0u;
760
+ var uv = aUV;
761
+ if (stereoMode == 1u) {
762
+ uv = vec2<f32>(aUV.x * 0.5 + select(0.0, 0.5, isRight), aUV.y);
763
+ } else if (stereoMode == 2u) {
764
+ uv = vec2<f32>(aUV.x, aUV.y * 0.5 + select(0.0, 0.5, isRight));
765
+ }
766
+
767
+ out.clipPos = sc.viewProj * world;
768
+ out.worldPos = world.xyz;
769
+ out.normal = select(vec3<f32>(0.0), rawN / nLen, nLen > 1e-5);
770
+ out.uv = uv;
771
+ out.instIdx = instIdx;
772
+ return out;
773
+ }
774
+
775
+ fn envBRDF(r: f32, n: f32) -> vec2<f32> {
776
+ let c0 = vec4<f32>(-1.0, -0.0275, -0.572, 0.022);
777
+ let c1 = vec4<f32>(1.0, 0.0425, 1.04, -0.04);
778
+ let rv = r * c0 + c1;
779
+ let a = min(rv.x * rv.x, exp2(-9.28 * n)) * rv.x + rv.y;
780
+ return vec2<f32>(-1.04, 1.04) * a + rv.zw;
781
+ }
782
+
783
+ fn fSchlickRoughness(f0: vec3<f32>, r: f32, n: f32) -> vec3<f32> {
784
+ return f0 + (max(vec3<f32>(1.0 - r), f0) - f0) * pow(clamp(1.0 - n, 0.0, 1.0), 5.0);
785
+ }
786
+
787
+ fn getStudioRadiance(rDir: vec3<f32>, r: f32) -> vec3<f32> {
788
+ let kd = normalize(vec3<f32>(0.0, 1.0, 0.35));
789
+ let fd = normalize(vec3<f32>(-0.85, 0.45, -0.35));
790
+ let ki = pow(max(dot(rDir, kd), 0.0), mix(96.0, 1.5, r)) * mix(2.4, 0.5, r);
791
+ let fi = pow(max(dot(rDir, fd), 0.0), mix(36.0, 1.2, r)) * mix(1.3, 0.35, r);
792
+ let ri = pow(clamp(1.0 - abs(rDir.y), 0.0, 1.0), 3.5) * mix(0.55, 0.22, r);
793
+ return mix(vec3<f32>(0.06, 0.06, 0.08), vec3<f32>(0.48, 0.50, 0.55), rDir.y * 0.5 + 0.5)
794
+ + vec3<f32>(1.0, 0.98, 0.94) * ki
795
+ + vec3<f32>(0.85, 0.92, 1.0) * fi
796
+ + vec3<f32>(0.65, 0.72, 0.85) * ri;
797
+ }
798
+
799
+ fn equirectangularUV(dir: vec3<f32>) -> vec2<f32> {
800
+ let d = normalize(dir);
801
+ return vec2<f32>(
802
+ atan2(d.z, d.x) * 0.15915494309 + 0.5,
803
+ 0.5 - asin(clamp(d.y, -1.0, 1.0)) * 0.31830988618,
804
+ );
805
+ }
806
+
807
+ fn neutralToneMapping(cIn: vec3<f32>) -> vec3<f32> {
808
+ var c = cIn;
809
+ let x = min(c.r, min(c.g, c.b));
810
+ c -= select(0.04, x - 6.25 * x * x, x < 0.08);
811
+ let p = max(c.r, max(c.g, c.b));
812
+ if (p < 0.76) {
813
+ return clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
814
+ }
815
+ let n = 1.0 - 0.0576 / (p - 0.52);
816
+ c *= n / p;
817
+ return clamp(mix(c, vec3<f32>(n), 1.0 - 1.0 / (0.15 * (p - n) + 1.0)), vec3<f32>(0.0), vec3<f32>(1.0));
818
+ }
819
+
820
+ fn acesToneMapping(cIn: vec3<f32>) -> vec3<f32> {
821
+ let c = cIn * 0.6;
822
+ return clamp((c * (2.51 * c + 0.03)) / (c * (2.43 * c + 0.59) + 0.14), vec3<f32>(0.0), vec3<f32>(1.0));
823
+ }
824
+
825
+ fn agxToneMapping(cIn: vec3<f32>) -> vec3<f32> {
826
+ let c = max(cIn, vec3<f32>(0.0));
827
+ let inset = mat3x3<f32>(
828
+ vec3<f32>(0.84247906, 0.04232824, 0.04237565),
829
+ vec3<f32>(0.0784336, 0.87846864, 0.0784336),
830
+ vec3<f32>(0.07922375, 0.07916613, 0.87914297),
831
+ ) * c;
832
+ let e = clamp((log2(max(inset, vec3<f32>(1e-6))) + 12.47393) / 16.5, vec3<f32>(0.0), vec3<f32>(1.0));
833
+ let x2 = e * e;
834
+ let x4 = x2 * x2;
835
+ let s = 15.5 * x4 * x2 - 40.14 * x4 * e + 31.96 * x4 - 6.868 * x2 * e + 0.4298 * x2 + 0.1191 * e - 0.00232;
836
+ let outset = mat3x3<f32>(
837
+ vec3<f32>(1.196879, -0.05289685, -0.05297164),
838
+ vec3<f32>(-0.09802088, 1.15190313, -0.09804345),
839
+ vec3<f32>(-0.09902974, -0.09896118, 1.15107367),
840
+ ) * s;
841
+ return clamp(pow(max(outset, vec3<f32>(0.0)), vec3<f32>(2.2)), vec3<f32>(0.0), vec3<f32>(1.0));
842
+ }
843
+
844
+ fn applyToneMapping(c: vec3<f32>, mode: u32) -> vec3<f32> {
845
+ if (mode == 0u) { return neutralToneMapping(c); }
846
+ if (mode == 1u) { return c / (c + vec3<f32>(1.0)); }
847
+ if (mode == 3u) { return acesToneMapping(c); }
848
+ if (mode == 4u) { return agxToneMapping(c); }
849
+ return clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
850
+ }
851
+
852
+ fn evalLight(lDir: vec3<f32>, vDir: vec3<f32>, nDir: vec3<f32>, baseRgb: vec3<f32>, specExp: f32, specW: f32, cc: vec2<f32>) -> vec3<f32> {
853
+ let h = max(dot(nDir, normalize(lDir + vDir)), 0.0);
854
+ return baseRgb * max(dot(nDir, lDir), 0.0) * 0.75
855
+ + vec3<f32>(pow(h, specExp) * specW + cc.x * pow(h, mix(64.0, 512.0, 1.0 - cc.y)) * 0.35);
856
+ }
857
+
858
+ const VOGEL_DISK = array<vec2<f32>, 8>(
859
+ vec2<f32>(0.1768, 0.0),
860
+ vec2<f32>(-0.2265, 0.2078),
861
+ vec2<f32>(0.0355, -0.4150),
862
+ vec2<f32>(0.3204, 0.3888),
863
+ vec2<f32>(-0.5562, -0.1455),
864
+ vec2<f32>(0.4916, -0.3806),
865
+ vec2<f32>(-0.1419, 0.6596),
866
+ vec2<f32>(-0.5177, -0.5150),
867
+ );
868
+
869
+ fn evalShadow(slot: i32, recv: bool, wp: vec3<f32>, nDir: vec3<f32>, lDir: vec3<f32>, fragXY: vec2<f32>) -> f32 {
870
+ if (!recv || slot < 0) {
871
+ return 1.0;
872
+ }
873
+ let nl = dot(nDir, lDir);
874
+ if (nl <= 0.0) {
875
+ return 0.0;
876
+ }
877
+ var vp: mat4x4<f32>;
878
+ var sp: vec4<f32>;
879
+ if (slot == 0) {
880
+ vp = sc.shdVP0;
881
+ sp = sc.shdParams0;
882
+ } else if (slot == 1) {
883
+ vp = sc.shdVP1;
884
+ sp = sc.shdParams1;
885
+ } else if (slot == 2) {
886
+ vp = sc.shdVP2;
887
+ sp = sc.shdParams2;
888
+ } else {
889
+ vp = sc.shdVP3;
890
+ sp = sc.shdParams3;
891
+ }
892
+ let scPos = vp * vec4<f32>(wp + nDir * (sp.y * (1.0 - nl)), 1.0);
893
+ if (scPos.w <= 1e-6) {
894
+ return 1.0;
895
+ }
896
+ let ndc = scPos.xyz / scPos.w;
897
+ let suv = vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
898
+ if (suv.x <= 0.002 || suv.x >= 0.998 || suv.y <= 0.002 || suv.y >= 0.998 || ndc.z > 1.0 || ndc.z < 0.0) {
899
+ return 1.0;
900
+ }
901
+ let refZ = clamp(ndc.z + sp.x, 0.0, 1.0);
902
+ if (sp.z <= 1e-6) {
903
+ return textureSampleCompareLevel(shadowTex, shadowSampler, suv, slot, refZ);
904
+ }
905
+ let ang = fract(52.9829189 * fract(dot(fragXY, vec2<f32>(0.06711056, 0.00583715)))) * 6.2831853;
906
+ let ca = cos(ang);
907
+ let sa = sin(ang);
908
+ var sum = 0.0;
909
+ for (var k = 0; k < 8; k = k + 1) {
910
+ let t = VOGEL_DISK[k];
911
+ let rot = vec2<f32>(ca * t.x - sa * t.y, sa * t.x + ca * t.y) * sp.z;
912
+ sum += textureSampleCompareLevel(shadowTex, shadowSampler, suv + rot, slot, refZ);
913
+ }
914
+ return sum * 0.125;
915
+ }
916
+
917
+ @fragment
918
+ fn fsMain(in: VsOut, @builtin(front_facing) frontFacing: bool) -> @location(0) vec4<f32> {
919
+ let p1 = dpdx(in.worldPos);
920
+ let p2 = -dpdy(in.worldPos);
921
+ let u1 = dpdx(in.uv);
922
+ let u2 = -dpdy(in.uv);
923
+ let baseTexel = textureSample(baseTex, linSampler, in.uv);
924
+ let mrTexel = textureSample(mrTex, linSampler, in.uv);
925
+ let normTexel = textureSample(normTex, linSampler, in.uv);
926
+ let occTexel = textureSample(occTex, linSampler, in.uv);
927
+ let emTexel = textureSample(emTex, linSampler, in.uv);
928
+
929
+ let p = parts[in.instIdx];
930
+ let pFlags = p.flags;
931
+ let secOn = (sc.flags.w & 2u) != 0u && (pFlags & 64u) == 0u;
932
+ if (secOn && dot(in.worldPos, sc.sectionPlane.xyz) > sc.sectionPlane.w) {
933
+ discard;
934
+ }
935
+
936
+ var base = p.baseColor;
937
+ if ((pFlags & 2u) != 0u) {
938
+ base *= baseTexel;
939
+ }
940
+ if (base.a < 0.004) {
941
+ discard;
942
+ }
943
+
944
+ var em = p.emissive.xyz;
945
+ if ((pFlags & 32u) != 0u) {
946
+ em *= emTexel.rgb;
947
+ }
948
+ let selGlow = vec3<f32>(p.emissive.w * 0.35, p.emissive.w * 0.5, p.emissive.w * 0.7);
949
+
950
+ let nInLen = length(in.normal);
951
+ if (nInLen < 1e-4 && (pFlags & 2u) != 0u) {
952
+ let unlit = clamp(base.rgb + em + selGlow, vec3<f32>(0.0), vec3<f32>(1.0));
953
+ return vec4<f32>(unlit * base.a, base.a);
954
+ }
955
+
956
+ var N: vec3<f32>;
957
+ if (nInLen < 1e-4) {
958
+ let flatCross = cross(p1, p2);
959
+ let fLen = length(flatCross);
960
+ N = select(vec3<f32>(0.0, 1.0, 0.0), flatCross / fLen, fLen > 1e-8);
961
+ } else {
962
+ N = in.normal / nInLen;
963
+ }
964
+ if (!frontFacing) {
965
+ N = -N;
966
+ }
967
+
968
+ let toCam = sc.camAndExp.xyz - in.worldPos;
969
+ let camDist = length(toCam);
970
+ let V = select(vec3<f32>(0.0, 0.0, 1.0), toCam / camDist, camDist > 1e-6);
971
+
972
+ if ((pFlags & 8u) != 0u) {
973
+ var q = normTexel.xyz * 2.0 - 1.0;
974
+ q = vec3<f32>(q.xy * p.aux.x, q.z);
975
+ let c2 = cross(p2, N);
976
+ let c1 = cross(N, p1);
977
+ let T = c2 * u1.x + c1 * u2.x;
978
+ let B = c2 * u1.y + c1 * u2.y;
979
+ let maxTB = max(dot(T, T), dot(B, B));
980
+ if (maxTB > 1e-12 && length(q) > 1e-5) {
981
+ let k = inverseSqrt(maxTB);
982
+ N = normalize(mat3x3<f32>(T * k, B * k, N) * normalize(q));
983
+ }
984
+ }
985
+
986
+ var metallic = p.pbr.x;
987
+ var roughness = p.pbr.y;
988
+ if ((pFlags & 4u) != 0u) {
989
+ roughness *= mrTexel.g;
990
+ metallic *= mrTexel.b;
991
+ }
992
+ roughness = clamp(roughness, 0.04, 1.0);
993
+ metallic = clamp(metallic, 0.0, 1.0);
994
+
995
+ var occ = 1.0;
996
+ if ((pFlags & 16u) != 0u) {
997
+ occ = mix(1.0, occTexel.r, p.aux.y);
998
+ }
999
+
1000
+ let gloss = 1.0 - roughness;
1001
+ let specExp = mix(16.0, 256.0, gloss * gloss);
1002
+ let specWeight = mix(0.22 * gloss, 1.0, metallic);
1003
+ let cc = p.pbr.zw;
1004
+
1005
+ let recvShd = (pFlags & 2048u) != 0u;
1006
+ var directLight = vec3<f32>(0.0);
1007
+ let numDir = sc.flags.y;
1008
+ if (numDir > 0u) {
1009
+ let dL0 = normalize(sc.dirDir0.xyz);
1010
+ let sh0 = evalShadow(sc.shdSlots.x, recvShd, in.worldPos, N, dL0, in.clipPos.xy);
1011
+ directLight += evalLight(dL0, V, N, base.rgb, specExp, specWeight, cc) * sc.dirCol0.xyz * sh0;
1012
+ }
1013
+ if (numDir > 1u) {
1014
+ let dL1 = normalize(sc.dirDir1.xyz);
1015
+ let sh1 = evalShadow(sc.shdSlots.y, recvShd, in.worldPos, N, dL1, in.clipPos.xy);
1016
+ directLight += evalLight(dL1, V, N, base.rgb, specExp, specWeight, cc) * sc.dirCol1.xyz * sh1;
1017
+ }
1018
+
1019
+ let numPt = sc.flags.z;
1020
+ if (numPt > 0u) {
1021
+ let toL = sc.ptPos0.xyz - in.worldPos;
1022
+ let dist = length(toL);
1023
+ let L = toL / max(dist, 0.0001);
1024
+ var spotAtt = clamp((dot(-L, sc.ptSpotDir0.xyz) - sc.ptSpotCone0.y) / max(sc.ptSpotCone0.x - sc.ptSpotCone0.y, 0.0001), 0.0, 1.0);
1025
+ spotAtt *= spotAtt;
1026
+ let shP0 = evalShadow(sc.shdSlots.z, recvShd, in.worldPos, N, L, in.clipPos.xy);
1027
+ directLight += evalLight(L, V, N, base.rgb, specExp, specWeight, cc) * sc.ptCol0.xyz * spotAtt / (1.0 + 0.09 * dist + 0.032 * dist * dist) * shP0;
1028
+ }
1029
+ if (numPt > 1u) {
1030
+ let toL = sc.ptPos1.xyz - in.worldPos;
1031
+ let dist = length(toL);
1032
+ let L = toL / max(dist, 0.0001);
1033
+ var spotAtt = clamp((dot(-L, sc.ptSpotDir1.xyz) - sc.ptSpotCone1.y) / max(sc.ptSpotCone1.x - sc.ptSpotCone1.y, 0.0001), 0.0, 1.0);
1034
+ spotAtt *= spotAtt;
1035
+ let shP1 = evalShadow(sc.shdSlots.w, recvShd, in.worldPos, N, L, in.clipPos.xy);
1036
+ directLight += evalLight(L, V, N, base.rgb, specExp, specWeight, cc) * sc.ptCol1.xyz * spotAtt / (1.0 + 0.09 * dist + 0.032 * dist * dist) * shP1;
1037
+ }
1038
+
1039
+ let R = reflect(-V, N);
1040
+ let NoV = clamp(dot(N, V), 0.001, 1.0);
1041
+ let F0 = mix(vec3<f32>(0.04), base.rgb, metallic);
1042
+ let F = fSchlickRoughness(F0, roughness, NoV);
1043
+ let brdf = envBRDF(roughness, NoV);
1044
+
1045
+ var specularIBL: vec3<f32>;
1046
+ var envDiffuse: vec3<f32>;
1047
+ if ((sc.flags.w & 1u) != 0u) {
1048
+ specularIBL = textureSampleLevel(envTex, linSampler, equirectangularUV(R), 0.0).rgb * (F * brdf.x + brdf.y);
1049
+ envDiffuse = textureSampleLevel(envTex, linSampler, equirectangularUV(N), 0.0).rgb;
1050
+ } else {
1051
+ specularIBL = getStudioRadiance(R, roughness) * (F * brdf.x + brdf.y);
1052
+ envDiffuse = mix(vec3<f32>(0.10, 0.10, 0.12), vec3<f32>(0.52, 0.54, 0.58), N.y * 0.5 + 0.5);
1053
+ }
1054
+
1055
+ let kD = (vec3<f32>(1.0) - F) * (1.0 - metallic);
1056
+ directLight += kD * base.rgb * mix(sc.hemiGround.xyz, sc.hemiSky.xyz, dot(N, sc.hemiAxis.xyz) * 0.5 + 0.5) * occ;
1057
+ let diffuseIBL = kD * base.rgb * (sc.ambAndEnv.xyz + envDiffuse * 0.5) * occ;
1058
+ var color = directLight + (diffuseIBL + specularIBL) * sc.ambAndEnv.w + em + selGlow;
1059
+ if (cc.x > 0.0) {
1060
+ let ccF = fSchlickRoughness(vec3<f32>(0.04), cc.y, NoV) * cc.x;
1061
+ color = color * (vec3<f32>(1.0) - ccF) + getStudioRadiance(R, cc.y) * ccF * sc.ambAndEnv.w;
1062
+ }
1063
+ color = applyToneMapping(color * sc.camAndExp.w, sc.flags.x);
1064
+ return vec4<f32>(color * base.a, base.a);
1065
+ }
1066
+ `,Mc=wc+`
1067
+ struct ShadowVsOut {
1068
+ @builtin(position) clipPos: vec4<f32>,
1069
+ @location(0) localUv: vec2<f32>,
1070
+ };
1071
+
1072
+ @vertex
1073
+ fn vsShadow(@builtin(vertex_index) vid: u32) -> ShadowVsOut {
1074
+ let sx = select(-1.0, 1.0, (vid & 1u) != 0u);
1075
+ let sz = select(-1.0, 1.0, (vid & 2u) != 0u);
1076
+ let world = vec4<f32>(
1077
+ sc.shadowBox.x + sx * sc.shadowBox.w,
1078
+ sc.shadowBox.y,
1079
+ sc.shadowBox.z + sz * sc.shadowParams.x,
1080
+ 1.0,
1081
+ );
1082
+ var out: ShadowVsOut;
1083
+ out.clipPos = sc.viewProj * world;
1084
+ out.localUv = vec2<f32>(sx, sz);
1085
+ return out;
1086
+ }
1087
+
1088
+ @fragment
1089
+ fn fsShadow(in: ShadowVsOut) -> @location(0) vec4<f32> {
1090
+ let r2 = dot(in.localUv, in.localUv);
1091
+ if (r2 >= 1.0) {
1092
+ discard;
1093
+ }
1094
+ let softness = sc.shadowParams.z;
1095
+ let falloff = mix(6.5, 2.2, softness);
1096
+ let edgeFade = 1.0 - smoothstep(0.55, 1.0, sqrt(r2));
1097
+ let alpha = clamp(exp(-r2 * falloff) * edgeFade * sc.shadowParams.y * 0.72, 0.0, 1.0);
1098
+ return vec4<f32>(0.0, 0.0, 0.0, alpha);
1099
+ }
1100
+ `,_c=wc+`
1101
+ struct PickVsOut {
1102
+ @builtin(position) clipPos: vec4<f32>,
1103
+ @location(0) worldPos: vec3<f32>,
1104
+ @location(1) @interpolate(flat) instIdx: u32,
1105
+ };
1106
+
1107
+ @vertex
1108
+ fn vsPick(
1109
+ @location(0) aPos: vec3<f32>,
1110
+ @builtin(instance_index) instIdx: u32,
1111
+ ) -> PickVsOut {
1112
+ let p = parts[instIdx];
1113
+ var out: PickVsOut;
1114
+ if (p.pickId == 0u || (p.flags & 128u) != 0u) {
1115
+ out.clipPos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
1116
+ out.worldPos = vec3<f32>(0.0);
1117
+ out.instIdx = instIdx;
1118
+ return out;
1119
+ }
1120
+ var m: mat4x4<f32>;
1121
+ if ((p.flags & 1u) != 0u) {
1122
+ m = p.model;
1123
+ } else {
1124
+ m = sc.modelRoot * p.model;
1125
+ }
1126
+ let world = m * vec4<f32>(aPos, 1.0);
1127
+ out.clipPos = sc.viewProj * world;
1128
+ out.worldPos = world.xyz;
1129
+ out.instIdx = instIdx;
1130
+ return out;
1131
+ }
1132
+
1133
+ @fragment
1134
+ fn fsPick(in: PickVsOut) -> @location(0) vec4<f32> {
1135
+ let p = parts[in.instIdx];
1136
+ let secOn = (sc.flags.w & 2u) != 0u && (p.flags & 64u) == 0u;
1137
+ if (secOn && dot(in.worldPos, sc.sectionPlane.xyz) > sc.sectionPlane.w) {
1138
+ discard;
1139
+ }
1140
+ let id = p.pickId;
1141
+ return vec4<f32>(
1142
+ f32(id & 255u) / 255.0,
1143
+ f32((id >> 8u) & 255u) / 255.0,
1144
+ f32((id >> 16u) & 255u) / 255.0,
1145
+ 1.0,
1146
+ );
1147
+ }
1148
+ `,Qm=`
1149
+ struct ShadowSliceUniforms {
1150
+ lightVP: mat4x4<f32>,
1151
+ modelRoot: mat4x4<f32>,
1152
+ biasRay: vec4<f32>,
1153
+ sectionPlane: vec4<f32>,
1154
+ flags: vec4<u32>,
1155
+ };
1156
+
1157
+ struct PartInstance {
1158
+ model: mat4x4<f32>,
1159
+ baseColor: vec4<f32>,
1160
+ pbr: vec4<f32>,
1161
+ emissive: vec4<f32>,
1162
+ aux: vec2<f32>,
1163
+ flags: u32,
1164
+ pickId: u32,
1165
+ };
1166
+
1167
+ @group(0) @binding(0) var<uniform> shd: ShadowSliceUniforms;
1168
+ @group(0) @binding(1) var<storage, read> parts: array<PartInstance>;
1169
+
1170
+ struct ShadowDepthOut {
1171
+ @builtin(position) clipPos: vec4<f32>,
1172
+ @location(0) worldPos: vec3<f32>,
1173
+ @location(1) @interpolate(flat) instIdx: u32,
1174
+ };
1175
+
1176
+ @vertex
1177
+ fn vsShadowDepth(
1178
+ @location(0) aPos: vec3<f32>,
1179
+ @location(1) aNormal: vec3<f32>,
1180
+ @builtin(instance_index) instIdx: u32,
1181
+ ) -> ShadowDepthOut {
1182
+ let p = parts[instIdx];
1183
+ var out: ShadowDepthOut;
1184
+ if ((p.flags & 128u) != 0u || (p.flags & 1024u) == 0u) {
1185
+ out.clipPos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
1186
+ out.worldPos = vec3<f32>(0.0);
1187
+ out.instIdx = instIdx;
1188
+ return out;
1189
+ }
1190
+ var m: mat4x4<f32>;
1191
+ if ((p.flags & 1u) != 0u) {
1192
+ m = p.model;
1193
+ } else {
1194
+ m = shd.modelRoot * p.model;
1195
+ }
1196
+ var wp = m * vec4<f32>(aPos, 1.0);
1197
+ let wn = m[0].xyz * aNormal.x + m[1].xyz * aNormal.y + m[2].xyz * aNormal.z;
1198
+ let nl = length(wn);
1199
+ if (nl > 1e-5 && shd.biasRay.w > 0.0) {
1200
+ let un = wn / nl;
1201
+ wp = vec4<f32>(
1202
+ wp.xyz + un * (shd.biasRay.w * max(1.0 - abs(dot(un, shd.biasRay.xyz)), 0.15)),
1203
+ 1.0,
1204
+ );
1205
+ }
1206
+ out.clipPos = shd.lightVP * wp;
1207
+ out.worldPos = wp.xyz;
1208
+ out.instIdx = instIdx;
1209
+ return out;
1210
+ }
1211
+
1212
+ @fragment
1213
+ fn fsShadowDepth(in: ShadowDepthOut) {
1214
+ let p = parts[in.instIdx];
1215
+ if (shd.flags.x != 0u && (p.flags & 64u) == 0u && dot(in.worldPos, shd.sectionPlane.xyz) > shd.sectionPlane.w) {
1216
+ discard;
1217
+ }
1218
+ }
1219
+ `,Zm=1,si=8,pg=16,dg=32,Ks=64,gg=128,yg=1,Jm=2,Xs=4,gi=16,bg=1,sa=1,jr=2,Sc=4,yi=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),jt=null,Wt=null,Gr=!1,Kt="bgra8unorm",Ys=null,Qs=new WeakMap;function xt(e){try{e()}catch{}}function e0(e){return Math.max(16,e+3&-4)}function Zs(){let e=globalThis.navigator?.gpu;return e&&typeof e.requestAdapter=="function"?e:null}function t0(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.createBuffer=="function"&&typeof t.createTexture=="function"&&typeof t.createSampler=="function"&&typeof t.createRenderBundleEncoder=="function"&&typeof t.createRenderPipeline=="function"}function Ri(){if(jt)return Promise.resolve(jt);let e=We(),t=e.webgpuDeviceProvider?.peekDevice?.();return t0(t)?(jt=t,Kt=e.webgpuDeviceProvider?.getCanvasFormat?.()||Kt,Promise.resolve(t)):Gr?Promise.resolve(null):Wt||(e.webgpuDeviceProvider&&e.webgpuDeviceProvider!==r0?(Wt=e.webgpuDeviceProvider.acquireDevice().then(r=>(Wt=null,t0(r)?(jt=r,Kt=e.webgpuDeviceProvider?.getCanvasFormat?.()||Kt,r):Ac())).catch(()=>(Wt=null,Ac())),Wt):Ac())}function Ac(){let e=Zs();if(!e)return Gr=!0,Promise.resolve(null);try{Kt=e.getPreferredCanvasFormat?.()||"bgra8unorm"}catch{Kt="bgra8unorm"}return Wt=e.requestAdapter({powerPreference:"high-performance"}).then(async t=>{if(!t)return Gr=!0,Wt=null,null;let r=t.limits,i={};for(let[a,s]of[["maxStorageBufferBindingSize",134217728],["maxBufferSize",268435456]])(r?.[a]??0)>s&&(i[a]=r[a]);let n=await(i.maxBufferSize||i.maxStorageBufferBindingSize?t.requestDevice({requiredLimits:i}).catch(()=>t.requestDevice()):t.requestDevice());return jt=n,Wt=null,n.lost?.then?.(()=>{jt===n&&(jt=null,Wt=null,Gr=!1,Ys?.onDeviceLost(n))}),n}).catch(()=>(Gr=!0,Wt=null,null)),Wt}var r0={acquireDevice:()=>Ri(),peekDevice:()=>jt,getCanvasFormat:()=>Kt};function i0(e,t="bgra8unorm"){jt=e,Wt=null,Gr=e===null,Kt=t}function n0(){jt=null,Wt=null,Gr=!1,Kt="bgra8unorm"}function Tc(e){let t=String(e??"").trim().toLowerCase();return t==="webgpu"||t==="webgl2"?t:"auto"}function xg(e){let t=e.container?.getAttribute?.("renderer")??e.renderer??"auto";return Tc(t)}function vg(e){let t=e.container,r=t?.hasAttribute?.("bloom")?t.getAttribute?.("bloom")??"":t?.getAttribute?.("bloom")??null;if(r!==null&&!e.stereoSBS){let s=r.trim().toLowerCase();if(s===""||s==="true"||s!=="false"&&s!=="0"&&s!=="none"&&Number(s)>0)return!0}let i=t?.hasAttribute?.("outline")?t.getAttribute?.("outline")??"":t?.getAttribute?.("outline")??null;if(i!==null){let s=i.trim().toLowerCase();if(s!=="false"&&s!=="0"&&s!=="none")return!0}let n=t?.hasAttribute?.("outline-selected")?t.getAttribute?.("outline-selected"):null;if(n!==null&&n!=="false"&&e.selectedMeshName||e.skyboxTexture)return!0;let a=[e.backdropMeshes??[],e.meshes??[]];for(let s of a)for(let o of s){if(o.visible===!1)continue;let l=o.extras?.xr??o.userData?.xr;if(l&&(l.bloom||l.outline||l.splatUrl||l.splat))return!0;for(let c of o.primitives??[])if(c.isTransmissive||c.customProgram&&e.renderProg&&c.customProgram!==e.renderProg&&!(We().tslWgslCompiler&&We().tslMaterialResolver?.(e,c.materialIndex))||c.pluginData?.morph||c.pluginData?.skinning||c.instanceCount!==void 0)return!0}return!1}function Js(e,t=!!(jt||Zs())){let r=e;if(!r||r.xrSessionActive)return"webgl2";let i=xg(r);if(i==="webgl2"||!t)return"webgl2";let n=!1;for(let a of[r.backdropMeshes??[],r.meshes??[]]){for(let s of a){if(s.visible===!1)continue;let o=s.extras?.xr??s.userData?.xr;if(!(o?.splatUrl||o?.splat)){for(let l of s.primitives??[])if(l.positions&&l.positions.length>=3){n=!0;break}if(n)break}}if(n)break}return!n||i==="auto"&&vg(r)?"webgl2":"webgpu"}function a0(e){let t=Qs.get(e);if(t)return t;let r=e.createBindGroupLayout({entries:[{binding:0,visibility:sa|jr,buffer:{type:"uniform"}},{binding:1,visibility:sa|jr,buffer:{type:"read-only-storage"}},{binding:2,visibility:jr,sampler:{type:"filtering"}},{binding:3,visibility:jr,texture:{sampleType:"float"}},{binding:4,visibility:jr,sampler:{type:"comparison"}},{binding:5,visibility:jr,texture:{sampleType:"depth",viewDimension:"2d-array"}}]}),i=e.createBindGroupLayout({entries:[0,1,2,3,4].map(C=>({binding:C,visibility:jr,texture:{sampleType:"float"}}))}),n=e.createBindGroupLayout({entries:[{binding:0,visibility:sa|jr,buffer:{type:"uniform"}}]}),a=e.createBindGroupLayout({entries:[{binding:0,visibility:sa|jr,buffer:{type:"uniform"}},{binding:1,visibility:sa|jr,buffer:{type:"read-only-storage"}}]}),s=e.createPipelineLayout({bindGroupLayouts:[r,i]}),o=e.createPipelineLayout({bindGroupLayouts:[r,i,n]}),l=e.createPipelineLayout({bindGroupLayouts:[r]}),c=e.createPipelineLayout({bindGroupLayouts:[a]}),f=e.createPipelineLayout({bindGroupLayouts:[a,n]}),m=e.createShaderModule({code:Ws}),h=e.createShaderModule({code:Mc}),p=e.createShaderModule({code:Qm}),g=e.createShaderModule({code:_c}),x=e.createSampler({magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat"}),v=e.createSampler({compare:"less-equal",magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),y=e.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"rgba8unorm",usage:Xs|Jm|gi});xt(()=>e.queue.writeTexture?.({texture:y},new Uint8Array([255,255,255,255]),{bytesPerRow:256,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:1}));let A=y.createView(),b=e.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"depth24plus",usage:Xs|gi}),w=b.createView({dimension:"2d-array",baseArrayLayer:0,arrayLayerCount:1}),S=e.createBindGroup({layout:i,entries:[0,1,2,3,4].map(C=>({binding:C,resource:A}))}),E=e.createRenderPipeline({layout:l,vertex:{module:g,entryPoint:"vsPick",buffers:[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},fragment:{module:g,entryPoint:"fsPick",targets:[{format:"rgba8unorm"}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!0,depthCompare:"less-equal"},multisample:{count:1}}),N=e.createRenderPipeline({layout:c,vertex:{module:p,entryPoint:"vsShadowDepth",buffers:[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"}]}]},fragment:{module:p,entryPoint:"fsShadowDepth",targets:[]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!0,depthCompare:"less-equal",depthBias:2,depthBiasSlopeScale:1.5},multisample:{count:1}});return t={sceneBgl:r,matBgl:i,tslBgl:n,shadowSliceBgl:a,scenePipeLayout:s,tslScenePipeLayout:o,auxPipeLayout:l,shadowDepthPipeLayout:c,tslShadowDepthPipeLayout:f,shaderMod:m,shadowMod:h,shadowDepthMod:p,pickMod:g,pickPipeline:E,shadowDepthPipeline:N,sampler:x,shadowSampler:v,whiteTex:y,whiteView:A,dummyShadowTex:b,dummyShadowView:w,defaultMatBg:S,byFormat:new Map,tslShaders:new Map,tslPipelinesByFormat:new Map,texCache:new WeakMap,ownedTextures:new Set([y,b])},Qs.set(e,t),t}function wg(e,t,r,i){let n=t.tslShaders.get(r);if(n)return n;let a=We().tslWgslCompiler;if(!a)return null;let s=a(i,Ws,Qm);if(!s)return null;let o=e.createShaderModule({code:s.pbrWgsl}),l=null,c=null;return s.shadowDepthWgsl&&(l=e.createShaderModule({code:s.shadowDepthWgsl}),c=e.createRenderPipeline({layout:t.tslShadowDepthPipeLayout,vertex:{module:l,entryPoint:"vsShadowDepth",buffers:[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"}]}]},fragment:{module:l,entryPoint:"fsShadowDepth",targets:[]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!0,depthCompare:"less-equal",depthBias:2,depthBiasSlopeScale:1.5},multisample:{count:1}})),n={pbrMod:o,shadowDepthMod:l,shadowDepthPipe:c},t.tslShaders.set(r,n),n}var Mg=[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"}]}];function s0(e,t,r,i,n){let a=s=>e.createRenderPipeline({layout:t,vertex:{module:r,entryPoint:"vsMain",buffers:Mg},fragment:{module:r,entryPoint:"fsMain",targets:[s?{format:i,blend:{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}:{format:i}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!s,depthCompare:"less-equal"},multisample:{count:n}});return{opaque:a(!1),blend:a(!0)}}function _g(e,t,r,i,n,a){let s=t.tslShaders.get(r);if(!s)return null;let o=`${r}:${i}:${n}`,l=t.tslPipelinesByFormat.get(o);return l||(l=s0(e,t.tslScenePipeLayout,s.pbrMod,i,n),t.tslPipelinesByFormat.set(o,l)),a?l.blend:l.opaque}function o0(e,t,r,i){let n=`${r}:${i}`,a=t.byFormat.get(n);if(a)return a;let{opaque:s,blend:o}=s0(e,t.scenePipeLayout,t.shaderMod,r,i),l=e.createRenderPipeline({layout:t.auxPipeLayout,vertex:{module:t.shadowMod,entryPoint:"vsShadow"},fragment:{module:t.shadowMod,entryPoint:"fsShadow",targets:[{format:r,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-strip",cullMode:"none"},depthStencil:{format:"depth24plus",depthWriteEnabled:!1,depthCompare:"less-equal"},multisample:{count:i}});return a={opaque:s,blend:o,shadow:l},t.byFormat.set(n,a),a}function l0(e){if(!e||typeof e!="object")return null;let t=e,r=Math.floor(t.naturalWidth||t.videoWidth||t.width||0),i=Math.floor(t.naturalHeight||t.videoHeight||t.height||0);return r>0&&i>0?[r,i]:null}function bi(e){return!e||typeof e!="object"?null:e.__gpuImageSource||(l0(e)?e:null)}function Ii(e,t,r){if(!r)return{view:t.whiteView,src:null,valid:!1};let i=bi(r),n=t.texCache.get(r);if(n&&n.src===i)return{view:n.view,src:i,valid:i!==null};if(!i)return{view:t.whiteView,src:null,valid:!1};let a=l0(i);if(!a)return{view:t.whiteView,src:null,valid:!1};n&&(t.ownedTextures.delete(n.tex),xt(()=>n.tex.destroy()));let[s,o]=a,l=e.createTexture({size:{width:s,height:o,depthOrArrayLayers:1},format:"rgba8unorm",usage:Xs|Jm|gi}),c=!1;if(typeof e.queue.copyExternalImageToTexture=="function"&&xt(()=>{e.queue.copyExternalImageToTexture({source:i},{texture:l},{width:s,height:o,depthOrArrayLayers:1}),c=!0}),!c&&typeof e.queue.writeTexture=="function"&&i.data){let m=i.data,h=Math.ceil(s*4/256)*256,p=new Uint8Array(h*o);for(let g=0;g<o;g++)p.set(m.subarray(g*s*4,(g+1)*s*4),g*h);xt(()=>{e.queue.writeTexture({texture:l},p,{bytesPerRow:h,rowsPerImage:o},{width:s,height:o,depthOrArrayLayers:1}),c=!0})}if(!c)return xt(()=>l.destroy()),{view:t.whiteView,src:null,valid:!1};let f=l.createView();return t.ownedTextures.add(l),t.texCache.set(r,{tex:l,view:f,src:i}),{view:f,src:i,valid:!0}}function u0(e,t,r){let i=Ii(e,t,r.texture),n=Ii(e,t,r.metallicRoughnessTexture),a=Ii(e,t,r.normalTexture),s=Ii(e,t,r.occlusionTexture),o=Ii(e,t,r.emissiveTexture),l=0;return i.valid&&(l|=2),n.valid&&(l|=4),a.valid&&(l|=8),s.valid&&(l|=16),o.valid&&(l|=32),l===0?{bg:t.defaultMatBg,texFlags:0,src0:i.src,src1:n.src,src2:a.src,src3:s.src,src4:o.src}:{bg:e.createBindGroup({layout:t.matBgl,entries:[{binding:0,resource:i.view},{binding:1,resource:n.view},{binding:2,resource:a.view},{binding:3,resource:s.view},{binding:4,resource:o.view}]}),texFlags:l,src0:i.src,src1:n.src,src2:a.src,src3:s.src,src4:o.src}}function Sg(e,t){let r=e,i=[],n=()=>{if(!t.visible||!t.canvas)return null;try{let s=document.createElement("canvas"),o=s.width=t.canvas.width||e.width||1,l=s.height=t.canvas.height||e.height||1,c=s.getContext?.("2d");if(!c)return null;c.drawImage(e,0,0,o,l),c.drawImage(t.canvas,0,0,o,l);let f=e.parentElement?.querySelector?.("canvas.xr-live-webgpu-splat");return f&&f.style?.display!=="none"&&c.drawImage(f,0,0,o,l),s}catch{return null}},a=(s,o)=>{let l=r[s];if(typeof l!="function")return;let c=Object.prototype.hasOwnProperty.call(e,s);r[s]=o(l.bind(e)),i.push(()=>{c?r[s]=l:delete r[s]})};return a("toDataURL",s=>(o,l)=>{let c=n();return c?c.toDataURL(o,l):s(o,l)}),a("toBlob",s=>(o,l,c)=>{let f=n();f&&typeof f.toBlob=="function"?f.toBlob(o,l,c):s(o,l,c)}),()=>i.forEach(s=>s())}function c0(e){return Rm(e)}function Ag(e,t){let r=Number(e.shadowIntensity??0);if(!(r>0)||t||!e.bounds)return null;let i=e.bounds,n=Math.max(0,Math.min(1,Number(e.shadowSoftness??.5))),a=e.modelRootMatrix??yi,s=i.center[0],o=i.center[1],l=i.center[2],c=Math.max(.02,(i.max[0]-i.min[0])*.5),f=Math.max(.02,(i.max[1]-i.min[1])*.5),m=Math.max(.02,(i.max[2]-i.min[2])*.5),h=a[0]*s+a[4]*o+a[8]*l+a[12],p=a[1]*s+a[5]*o+a[9]*l+a[13],g=a[2]*s+a[6]*o+a[10]*l+a[14],x=Math.abs(a[0])*c+Math.abs(a[4])*f+Math.abs(a[8])*m,v=Math.abs(a[1])*c+Math.abs(a[5])*f+Math.abs(a[9])*m,y=Math.abs(a[2])*c+Math.abs(a[6])*f+Math.abs(a[10])*m,A=1.35+n*.5;return{centerX:h,floorY:p-v-5e-4,centerZ:g,halfExtentX:Math.max(.05,x*A),halfExtentZ:Math.max(.05,y*A),intensity:Math.min(1,r),softness:n}}function h0(e){return e.environmentTexture&&typeof e.environmentTexture=="object"?e.environmentTexture:e.environmentSource&&typeof e.environmentSource=="object"?e.environmentSource:null}function cn(e){if(e){xt(()=>e.vertexBuf.destroy()),xt(()=>e.indexBuf?.destroy()),xt(()=>e.partBuf.destroy()),xt(()=>e.uniformBuf.destroy()),xt(()=>e.pickUniformBuf?.destroy());for(let t of e.shadowSliceBufs)xt(()=>t?.destroy());for(let t of e.tslSlots.values())xt(()=>t.buf.destroy())}}function f0(e,t,r,i,n){let a=We().tslMaterialResolver;if(!a||n===void 0||n<0)return{tslHash:null,tslBg:null,tslShadowPipe:null};let s=a(r,n);if(!s)return{tslHash:null,tslBg:null,tslShadowPipe:null};let o=wg(e,t,s.hash,s.graph);if(!o)return{tslHash:null,tslBg:null,tslShadowPipe:null};let l=i.get(n);if(!l||l.hash!==s.hash){xt(()=>l?.buf.destroy());let c=e.createBuffer({size:s.buf68.byteLength,usage:Ks|si});e.queue.writeBuffer(c,0,s.buf68);let f=e.createBindGroup({layout:t.tslBgl,entries:[{binding:0,resource:{buffer:c}}]});l={buf:c,bg:f,hash:s.hash,usesVertexPosition:s.usesVertexPosition,uploadedVersion:s.version},i.set(n,l)}return{tslHash:s.hash,tslBg:l.bg,tslShadowPipe:o.shadowDepthPipe}}function Pc(e){xt(()=>e.shadowTex?.destroy()),e.shadowTex=null,e.shadowArrayView=null,e.shadowLayerViews=[],e.shadowSize=0,e.shadowLayers=0,e.lastShadowDigest=0}function eo(e){xt(()=>e.msaaTex?.destroy()),xt(()=>e.depthTex?.destroy()),e.msaaTex=null,e.msaaView=null,e.depthTex=null,e.depthView=null,e.width=0,e.height=0}function to(e){xt(()=>e.pickColorTex?.destroy()),xt(()=>e.pickDepthTex?.destroy()),xt(()=>e.pickReadBuf?.destroy()),e.pickColorTex=null,e.pickColorView=null,e.pickDepthTex=null,e.pickDepthView=null,e.pickReadBuf=null,e.pickBusy=!1}function m0(e,t,r){if(e.backdropCount!==t.length||e.meshRefs.length!==t.length+r.length)return!1;for(let i=0;i<t.length;i++)if(e.meshRefs[i]!==t[i])return!1;for(let i=0;i<r.length;i++)if(e.meshRefs[t.length+i]!==r[i])return!1;for(let i of e.groups){if(i.prim.positions!==i.posRef||(i.prim.indices??null)!==i.idxRef)return!1;let n=i.mesh.instanceMatrices;if((n&&n.length>=16?n.length>>4:i.prim.instanceCount!==void 0&&i.prim.translations?i.prim.instanceCount:1)!==i.instanceCount)return!1}return!0}function p0(e,t,r,i){let n=i?r.backdropMeshes??[]:[],a=r.meshes??[],s=[...n,...a],o=0,l=0,c=0,f=[],m=new Map;for(let N=0;N<s.length;N++){let C=s[N],_=C.extras?.xr??C.userData?.xr;if(_?.splatUrl||_?.splat)continue;let P=N<n.length,R=P||C.isPluginMesh||_?.pointerEvents==="none"?-1:N-n.length,I=C.instanceMatrices;for(let F of C.primitives??[]){let V=F.positions;if(!V||V.length<3)continue;let Y=Math.floor(V.length/3);if(Y<=0)continue;let J=F.indices??null,re=!!(J&&J.length>0),Q=re?J.length:Math.min(Y,F.indexCount??Y);if(Q<=0)continue;let ee=I&&I.length>=16?I.length>>4:F.instanceCount!==void 0&&F.translations?Math.max(1,F.instanceCount|0):1,k=u0(e,t,F),G=f0(e,t,r,m,F.materialIndex);f.push({mesh:C,prim:F,posRef:V,idxRef:J,meshIndex:R,isBackdrop:P,firstVertex:o,vertexCount:Y,indexed:re,firstIndex:l,indexCount:Q,firstInstance:c,instanceCount:ee,isBlend:F.alphaMode==="BLEND"||(F.baseColor?.[3]??1)<.999,matIndex:F.materialIndex,tslHash:G.tslHash,tslBg:G.tslBg,tslShadowPipe:G.tslShadowPipe,tex0:F.texture??null,tex1:F.metallicRoughnessTexture??null,tex2:F.normalTexture??null,tex3:F.occlusionTexture??null,tex4:F.emissiveTexture??null,src0:k.src0,src1:k.src1,src2:k.src2,src3:k.src3,src4:k.src4,matBg:k.bg}),o+=Y,re&&(l+=Q),c+=ee}}if(f.length===0||o===0||c===0)return null;let h=new Float32Array(o*8),p=l>0?new Uint32Array(l):null;for(let N of f){let C=N.posRef,_=N.prim.normals,P=N.prim.uvs,R=N.vertexCount,I=N.firstVertex*8;for(let F=0;F<R;F++){let V=F*3,Y=F*2;h[I]=C[V],h[I+1]=C[V+1],h[I+2]=C[V+2],_&&V+2<_.length&&(h[I+3]=_[V],h[I+4]=_[V+1],h[I+5]=_[V+2]),P&&Y+1<P.length&&(h[I+6]=P[Y],h[I+7]=P[Y+1]),I+=8}if(N.indexed&&p&&N.idxRef){let F=N.idxRef,V=N.firstIndex;for(let Y=0;Y<N.indexCount;Y++)p[V+Y]=F[Y]}}let g=e.createBuffer({size:e0(h.byteLength),usage:dg|si});e.queue.writeBuffer(g,0,h);let x=null;p&&(x=e.createBuffer({size:e0(p.byteLength),usage:pg|si}),e.queue.writeBuffer(x,0,p));let v=Math.max(128,c*128),y=e.createBuffer({size:v,usage:gg|si}),A=e.createBuffer({size:800,usage:Ks|si}),b=h0(r),w=Ii(e,t,b),S=e.createBindGroup({layout:t.sceneBgl,entries:[{binding:0,resource:{buffer:A}},{binding:1,resource:{buffer:y}},{binding:2,resource:t.sampler},{binding:3,resource:w.view},{binding:4,resource:t.shadowSampler},{binding:5,resource:t.dummyShadowView}]}),E=new ArrayBuffer(v);return{meshRefs:s,backdropCount:n.length,groups:f,totalVertices:o,totalIndices:l,totalInstances:c,vertexBuf:g,indexBuf:x,partBuf:y,uniformBuf:A,pickUniformBuf:null,pickSceneBg:null,cpuPartBuf:E,cpuPartF32:new Float32Array(E),cpuPartU32:new Uint32Array(E),gpuPartU32:new Uint32Array(v>>>2),partsUploadedOnce:!1,envSourceRef:bi(b),envView:w.view,shadowViewRef:t.dummyShadowView,sceneBg:S,tslSlots:m,tslVertexDirty:!1,shadowSliceBufs:[null,null,null,null],shadowSliceBgs:[null,null,null,null],shadowBundles:[null,null,null,null],opaqueBundle:null,blendBundle:null,pickBundle:null,bundleFormat:"",bundleSamples:0,bundlesDirty:!0}}function Tg(e,t,r,i,n){let a=o0(e,t,i,n),s=(o,l)=>{let c=r.groups.filter(x=>x.isBlend===o);if(c.length===0)return null;let f=o?c:[...c.filter(x=>x.isBackdrop),...c.filter(x=>!x.isBackdrop&&x.matBg===t.defaultMatBg),...c.filter(x=>!x.isBackdrop&&x.matBg!==t.defaultMatBg)],m=e.createRenderBundleEncoder({colorFormats:[i],depthStencilFormat:"depth24plus",sampleCount:n});m.setPipeline(l),m.setBindGroup(0,r.sceneBg),m.setVertexBuffer(0,r.vertexBuf),r.indexBuf&&m.setIndexBuffer(r.indexBuf,"uint32");let h=l,p=null,g=null;for(let x of f){let v=x.tslHash?_g(e,t,x.tslHash,i,n,o)??l:l;v!==h&&(m.setPipeline(v),h=v),x.matBg!==p&&(m.setBindGroup(1,x.matBg),p=x.matBg),x.tslBg&&x.tslBg!==g&&(m.setBindGroup(2,x.tslBg),g=x.tslBg),x.indexed?m.drawIndexed(x.indexCount,x.instanceCount,x.firstIndex,x.firstVertex,x.firstInstance):m.draw(x.indexCount,x.instanceCount,x.firstVertex,x.firstInstance)}return m.finish()};r.opaqueBundle=s(!1,a.opaque),r.blendBundle=s(!0,a.blend),r.pickBundle=null,r.bundleFormat=i,r.bundleSamples=n,r.bundlesDirty=!1}function Pg(e,t,r){if(r.pickUniformBuf||(r.pickUniformBuf=e.createBuffer({size:800,usage:Ks|si})),r.pickSceneBg||(r.pickSceneBg=e.createBindGroup({layout:t.sceneBgl,entries:[{binding:0,resource:{buffer:r.pickUniformBuf}},{binding:1,resource:{buffer:r.partBuf}},{binding:2,resource:t.sampler},{binding:3,resource:t.whiteView},{binding:4,resource:t.shadowSampler},{binding:5,resource:t.dummyShadowView}]})),r.pickBundle)return r.pickBundle;let i=e.createRenderBundleEncoder({colorFormats:["rgba8unorm"],depthStencilFormat:"depth24plus",sampleCount:1});i.setPipeline(t.pickPipeline),i.setBindGroup(0,r.pickSceneBg),i.setVertexBuffer(0,r.vertexBuf),r.indexBuf&&i.setIndexBuffer(r.indexBuf,"uint32");for(let n of r.groups)n.meshIndex<0||(n.indexed?i.drawIndexed(n.indexCount,n.instanceCount,n.firstIndex,n.firstVertex,n.firstInstance):i.draw(n.indexCount,n.instanceCount,n.firstVertex,n.firstInstance));return r.pickBundle=i.finish(),r.pickBundle}function Ng(e,t,r,i){if(i<0||i>=Jn)return null;if(r.shadowSliceBufs[i]||(r.shadowSliceBufs[i]=e.createBuffer({size:176,usage:Ks|si})),r.shadowSliceBgs[i]||(r.shadowSliceBgs[i]=e.createBindGroup({layout:t.shadowSliceBgl,entries:[{binding:0,resource:{buffer:r.shadowSliceBufs[i]}},{binding:1,resource:{buffer:r.partBuf}}]})),r.shadowBundles[i])return r.shadowBundles[i];let n=e.createRenderBundleEncoder({colorFormats:[],depthStencilFormat:"depth24plus",sampleCount:1});n.setPipeline(t.shadowDepthPipeline),n.setBindGroup(0,r.shadowSliceBgs[i]),n.setVertexBuffer(0,r.vertexBuf),r.indexBuf&&n.setIndexBuffer(r.indexBuf,"uint32");let a=t.shadowDepthPipeline,s=null;for(let l of r.groups){if(l.isBackdrop||l.isBlend||l.prim.isTransmissive)continue;let c=l.tslShadowPipe??t.shadowDepthPipeline;c!==a&&(n.setPipeline(c),a=c),l.tslShadowPipe&&l.tslBg&&l.tslBg!==s&&(n.setBindGroup(1,l.tslBg),s=l.tslBg),l.indexed?n.drawIndexed(l.indexCount,l.instanceCount,l.firstIndex,l.firstVertex,l.firstInstance):n.draw(l.indexCount,l.instanceCount,l.firstVertex,l.firstInstance)}let o=n.finish();return r.shadowBundles[i]=o,o}var Nc=lt(),$i=lt();function d0(e,t,r,i,n,a,s){let o=h0(r),l=bi(o),c=i.envView;if(l!==i.envSourceRef){let b=Ii(e,t,o);i.envSourceRef=b.src,c=b.view}let f=s??i.shadowViewRef;(c!==i.envView||f!==i.shadowViewRef)&&(i.envView=c,i.shadowViewRef=f,i.sceneBg=e.createBindGroup({layout:t.sceneBgl,entries:[{binding:0,resource:{buffer:i.uniformBuf}},{binding:1,resource:{buffer:i.partBuf}},{binding:2,resource:t.sampler},{binding:3,resource:c},{binding:4,resource:t.shadowSampler},{binding:5,resource:f}]}),i.bundlesDirty=!0);let m=i.cpuPartF32,h=i.cpuPartU32,p=r.selectedMeshNames,g=r.selectedMeshName||"",x=r.modelRootMatrix??yi,v=n.eye==="none"&&!r.stereoSBS;i.tslVertexDirty=!1;let y=We().tslMaterialResolver;if(y)for(let[b,w]of i.tslSlots.entries()){let S=y(r,b);S&&S.hash===w.hash&&S.version!==w.uploadedVersion&&(e.queue.writeBuffer(w.buf,0,S.buf68),w.uploadedVersion=S.version,w.usesVertexPosition&&(i.tslVertexDirty=!0))}for(let b of i.groups){let w=b.mesh,S=b.prim;if(S.materialIndex!==b.matIndex){b.matIndex=S.materialIndex;let D=f0(e,t,r,i.tslSlots,S.materialIndex);(D.tslHash!==b.tslHash||D.tslBg!==b.tslBg||D.tslShadowPipe!==b.tslShadowPipe)&&(D.tslShadowPipe!==b.tslShadowPipe&&(i.tslVertexDirty=!0),b.tslHash=D.tslHash,b.tslBg=D.tslBg,b.tslShadowPipe=D.tslShadowPipe,i.bundlesDirty=!0,i.shadowBundles=[null,null,null,null])}let E=S.texture??null,N=S.metallicRoughnessTexture??null,C=S.normalTexture??null,_=S.occlusionTexture??null,P=S.emissiveTexture??null;if(E!==b.tex0||N!==b.tex1||C!==b.tex2||_!==b.tex3||P!==b.tex4||bi(E)!==b.src0||bi(N)!==b.src1||bi(C)!==b.src2||bi(_)!==b.src3||bi(P)!==b.src4){let D=u0(e,t,S);b.tex0=E,b.tex1=N,b.tex2=C,b.tex3=_,b.tex4=P,b.src0=D.src0,b.src1=D.src1,b.src2=D.src2,b.src3=D.src3,b.src4=D.src4,b.matBg!==D.bg&&(b.matBg=D.bg,i.bundlesDirty=!0)}let R=S.baseColor??[1,1,1,1],I=R[0]??1,F=R[1]??1,V=R[2]??1,Y=R[3]??1,J=S.alphaMode==="BLEND"||Y<.999;J!==b.isBlend&&(b.isBlend=J,i.bundlesDirty=!0,i.shadowBundles=[null,null,null,null]);let re=0;b.src0&&(re|=2),b.src1&&(re|=4),b.src2&&(re|=8),b.src3&&(re|=16),b.src4&&(re|=32),(b.isBackdrop||w.isPluginMesh)&&(re|=64),w.visible===!1&&(re|=128),a&&a.slices.length>0&&!b.isBackdrop&&!J&&!S.isTransmissive&&on(w,a.promoteAllCasters)&&(re|=1024),a&&a.slices.length>0&&!b.isBackdrop&&js(w,a.promoteAllReceivers)&&(re|=2048);let Q=w.extras?.xr??w.userData?.xr,ee=Q?.stereo;ee==="sbs"?re|=256:ee==="ou"&&(re|=512);let k=v?Q?.billboard:void 0;(b.isBackdrop||w.worldSpace===!0||w.name==="__xr_reticle__"||k)&&(re|=1);let G=w.transform;if(k){b.isBackdrop||w.worldSpace===!0||w.name==="__xr_reticle__"?Nc.set(w.transform):ft(Nc,x,w.transform);let D=Nc,z=Math.hypot(D[0],D[1],D[2])||1,O=Math.hypot(D[4],D[5],D[6])||1,X=Math.hypot(D[8],D[9],D[10])||1,se=k==="y"||k==="cylindrical"||k==="capsule",ce=n.eyePos[0]-D[12],pe=n.eyePos[2]-D[14],xe=Math.hypot(ce,pe),he=xe>1e-5?ce/xe:0,Ne=xe>1e-5?pe/xe:1;if(se)D[0]=Ne*z,D[1]=0,D[2]=-he*z,D[3]=0,D[4]=0,D[5]=O,D[6]=0,D[7]=0,D[8]=he*X,D[9]=0,D[10]=Ne*X,D[11]=0;else{let ge=n.view;D[0]=ge[0]*z,D[1]=ge[4]*z,D[2]=ge[8]*z,D[3]=0,D[4]=ge[1]*O,D[5]=ge[5]*O,D[6]=ge[9]*O,D[7]=0,D[8]=ge[2]*X,D[9]=ge[6]*X,D[10]=ge[10]*X,D[11]=0}G=D}let q=S.metallic??0,H=S.roughness??.5,te=S.clearcoat??0,Z=S.clearcoatRoughness??.04,ae=S.emissiveFactor,ie=ae?.[0]??0,de=ae?.[1]??0,me=ae?.[2]??0,Se=(p?p.has(w.name):g!==""&&w.name===g)?1:0,ke=S.normalScale??1,_e=S.occlusionStrength??1,Le=b.meshIndex>=0?b.meshIndex+1>>>0:0,ne=w.instanceMatrices,Re=w.instanceColors,W=S.translations;for(let D=0;D<b.instanceCount;D++){let z=(b.firstInstance+D)*32,O=G;if(ne&&ne.length>=(D+1)*16)ft($i,G,ne.subarray(D*16,D*16+16)),O=$i;else if(W&&W.length>=(D+1)*3){$i.set(G);let X=W[D*3],se=W[D*3+1],ce=W[D*3+2];$i[12]+=G[0]*X+G[4]*se+G[8]*ce,$i[13]+=G[1]*X+G[5]*se+G[9]*ce,$i[14]+=G[2]*X+G[6]*se+G[10]*ce,O=$i}for(let X=0;X<16;X++)m[z+X]=O[X];Re&&Re.length>=(D+1)*3?(m[z+16]=I*Re[D*3],m[z+17]=F*Re[D*3+1],m[z+18]=V*Re[D*3+2]):(m[z+16]=I,m[z+17]=F,m[z+18]=V),m[z+19]=Y,m[z+20]=q,m[z+21]=H,m[z+22]=te,m[z+23]=Z,m[z+24]=ie,m[z+25]=de,m[z+26]=me,m[z+27]=Se,m[z+28]=ke,m[z+29]=_e,h[z+30]=re>>>0,h[z+31]=Le}}let A=i.totalInstances*32;if(!i.partsUploadedOnce)e.queue.writeBuffer(i.partBuf,0,h,0,A),i.gpuPartU32.set(h.subarray(0,A)),i.partsUploadedOnce=!0;else{let b=i.gpuPartU32,w=-1,S=-1;for(let E=0;E<A;E++)h[E]!==b[E]&&(w<0&&(w=E),S=E,b[E]=h[E]);if(w>=0){let E=S-w+1;e.queue.writeBuffer(i.partBuf,w*4,h,w,E)}}}function Cg(e,t,r,i,n,a){let s=Math.max(1,n),o=Math.max(1,a),l=(r+.5)/s*2-1,c=1-(i+.5)/o*2;for(let f=0;f<4;f++){let m=f*4,h=t[m],p=t[m+1],g=t[m+2],x=t[m+3];e[m]=s*(h-l*x),e[m+1]=o*(p-c*x),e[m+2]=g,e[m+3]=x}return e}var Cc=class{constructor(){this.states=new WeakMap,this.trackedViewers=new Set,this.renderedFrames=0,this.bundleRecordCount=0,this.shadowPassCount=0,this.shadowCacheHits=0}getState(e){let t=this.states.get(e);return t||(t={dev:null,canvas:null,ctx:null,configuredFormat:"",visible:!1,width:0,height:0,sampleCount:Sc,msaaTex:null,msaaView:null,depthTex:null,depthView:null,shadowTex:null,shadowArrayView:null,shadowLayerViews:[],shadowSize:0,shadowLayers:0,lastShadowDigest:0,pickColorTex:null,pickColorView:null,pickDepthTex:null,pickDepthView:null,pickReadBuf:null,pickBusy:!1,scene:null,unhookSnapshot:null,gen:0,uniformScratch:new ArrayBuffer(800),shadowSliceScratch:new ArrayBuffer(176)},this.states.set(e,t),this.trackedViewers.add(e)),t}ensureCanvas(e,t,r){let i=e.canvas??e.gl?.canvas;if(!i||typeof document>"u")return null;if(!t.canvas){let o=i.parentElement;if(!o||typeof o.insertBefore!="function")return null;let l=document.createElement("canvas");l.className="three-live-webgpu-scene",l.style&&(l.style.cssText="position:absolute;inset:0;width:100%;height:100%;display:block;pointer-events:none;z-index:0"),o.insertBefore(l,i.nextSibling);let c=l.getContext?.("webgpu");if(!c||typeof c.configure!="function")return xt(()=>l.remove?.()),null;t.canvas=l,t.ctx=c,t.visible=!0,t.unhookSnapshot=Sg(i,t)}let n=Math.max(1,i.width||1),a=Math.max(1,i.height||1),s=t.canvas.width!==n||t.canvas.height!==a;if(s&&(t.canvas.width=n,t.canvas.height=a),(t.dev!==r||t.configuredFormat!==Kt||s)&&(t.ctx.configure({device:r,format:Kt,alphaMode:"premultiplied"}),t.dev=r,t.configuredFormat=Kt),t.width!==n||t.height!==a||!t.depthTex){eo(t),t.width=n,t.height=a;let o=Sc,l=null;xt(()=>{l=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:Kt,sampleCount:Sc,usage:gi})}),l||(o=1);let c=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:"depth24plus",sampleCount:o,usage:gi});t.sampleCount=o,t.msaaTex=l,t.msaaView=l?l.createView():null,t.depthTex=c,t.depthView=c.createView()}return!t.visible&&t.canvas?.style&&(t.canvas.style.display="block",t.visible=!0),t.ctx}renderScene(e,t,r,i,n,a,s,o,l,c){let f={viewer:e,vp:t,proj:r,view:i,eyePos:n,toneMappingIndex:a,viewport:s,eye:o,clear:l,isAR:c},m=f.viewer,h=this.getState(f.viewer);if(!jt){if(!Gr&&!Wt){let G=h.gen;Ri().then(q=>{q&&h.gen===G&&this.trackedViewers.has(f.viewer)&&xt(()=>f.viewer.render?.())})}return this.hideLayer(f.viewer),!1}let p=jt;if(Js(m,!0)!=="webgpu")return this.hideLayer(f.viewer),!1;h.dev&&h.dev!==p&&(cn(h.scene),h.scene=null,eo(h),Pc(h),to(h));let g=this.ensureCanvas(m,h,p);if(!g)return!1;let x=a0(p),v=!f.isAR,y=v?m.backdropMeshes??[]:[],A=m.meshes??[];if((!h.scene||!m0(h.scene,y,A))&&(cn(h.scene),h.scene=p0(p,x,m,v),h.lastShadowDigest=0,!h.scene))return this.hideLayer(f.viewer),!1;let b=h.scene,w=Gs(m),S=x.dummyShadowView,E=w.slices.length;if(E>0){if(!h.shadowTex||h.shadowSize!==w.mapSize||h.shadowLayers<E){xt(()=>h.shadowTex?.destroy());let G=Math.max(h.shadowLayers,E),q=p.createTexture({size:{width:w.mapSize,height:w.mapSize,depthOrArrayLayers:G},format:"depth24plus",usage:gi|Xs});h.shadowTex=q,h.shadowSize=w.mapSize,h.shadowLayers=G,h.shadowArrayView=q.createView({dimension:"2d-array",baseArrayLayer:0,arrayLayerCount:G}),h.shadowLayerViews=[];for(let H=0;H<G;H++)h.shadowLayerViews.push(q.createView({dimension:"2d",baseArrayLayer:H,arrayLayerCount:1}));h.lastShadowDigest=0}S=h.shadowArrayView}d0(p,x,m,b,f,w,S),(b.bundlesDirty||b.bundleFormat!==Kt||b.bundleSamples!==h.sampleCount)&&(Tg(p,x,b,Kt,h.sampleCount),this.bundleRecordCount++);let N=w.sectionPlane??c0(m),C=Ag(m,f.isAR);qs(h.uniformScratch,{vp:f.vp,modelRoot:m.modelRootMatrix??yi,eyePos:f.eyePos,exposure:m.exposure??1,envIntensity:m.envIntensity??1,toneMappingIndex:f.toneMappingIndex,lights:m.lights??[],hasEnvMap:b.envSourceRef!==null,isRightEye:f.eye==="right",sectionPlane:N,contactShadow:C,shadowMap:E>0?{slices:w.slices,dirSlots:w.dirSlots,ptSlots:w.ptSlots}:null}),p.queue.writeBuffer(b.uniformBuf,0,h.uniformScratch);let _=g.getCurrentTexture().createView(),P=f.isAR?[0,0,0,0]:m.clearColor??[0,0,0,0],R=P[3]??0,I={r:(P[0]??0)*R,g:(P[1]??0)*R,b:(P[2]??0)*R,a:R},F=!!m.stereoSBS,V=h.sampleCount>1&&!!h.msaaView,Y=p.createCommandEncoder();if(E>0&&h.shadowTex)if(!b.tslVertexDirty&&h.lastShadowDigest===w.digest)this.shadowCacheHits++;else{h.lastShadowDigest=w.digest;let G=m.modelRootMatrix??yi;for(let q of w.slices){let H=Ng(p,x,b,q.slot),te=b.shadowSliceBufs[q.slot],Z=h.shadowLayerViews[q.slot];if(!te||!Z)continue;mg(h.shadowSliceScratch,q.viewProj,G,q.rayDir,q.normalBiasWorld,N),p.queue.writeBuffer(te,0,h.shadowSliceScratch);let ae=Y.beginRenderPass({colorAttachments:[],depthStencilAttachment:{view:Z,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});H&&ae.executeBundles([H]),ae.end(),this.shadowPassCount++}}let J=Y.beginRenderPass({colorAttachments:[V?{view:h.msaaView,resolveTarget:_,loadOp:f.clear?"clear":"load",storeOp:F?"store":"discard",clearValue:I}:{view:_,loadOp:f.clear?"clear":"load",storeOp:"store",clearValue:I}],depthStencilAttachment:{view:h.depthView,depthClearValue:1,depthLoadOp:f.clear?"clear":"load",depthStoreOp:F?"store":"discard"}}),[re,Q,ee,k]=f.viewport;if(J.setViewport&&(re!==0||Q!==0||ee!==h.width||k!==h.height)){let G=Math.max(0,Math.min(h.width-1,re)),q=Math.max(0,Math.min(h.height-1,h.height-Q-k));J.setViewport(G,q,Math.max(1,Math.min(h.width-G,ee)),Math.max(1,Math.min(h.height-q,k)),0,1)}if(b.opaqueBundle&&J.executeBundles([b.opaqueBundle]),C){let G=o0(p,x,Kt,h.sampleCount);J.setPipeline(G.shadow),J.setBindGroup(0,b.sceneBg),J.draw(4,1,0,0)}return b.blendBundle&&J.executeBundles([b.blendBundle]),J.end(),p.queue.submit([Y.finish()]),this.renderedFrames++,!0}async pickMeshGPU(e,t,r,i){let n=e,a=n.meshes??[];if(a.length===0)return-1;let s=jt??await Ri();if(!s||typeof s.createCommandEncoder!="function")return-1;let o=this.getState(e),l=o.gen,c=a0(s),f=n.backdropMeshes??[];if((!o.scene||!m0(o.scene,f,a))&&(cn(o.scene),o.scene=p0(s,c,n,!0),!o.scene))return-1;let m=o.scene,h=Math.max(1,n.canvas?.width||o.width||300),p=Math.max(1,n.canvas?.height||o.height||300),g=t;if(n.stereoSBS&&!n.xrSessionActive&&h>=2){let N=Math.max(1,Math.floor(h*.5)),C=t>=N,_=C?t-N:t,P=C?Math.max(1,h-N):N,R=(_+.5)/P*2-1;g=Math.floor((R*.5+1)*.5*h)}let x=Math.max(0,Math.min(h-1,Math.floor(g))),v=Math.max(0,Math.min(p-1,Math.floor(r))),y=lt();i?y.set(i):n.projMatrix&&n.viewMatrix?ft(y,n.projMatrix,n.viewMatrix):y.set(yi),d0(s,c,n,m,{viewer:e,vp:y,proj:n.projMatrix??yi,view:n.viewMatrix??yi,eyePos:[0,0,3],toneMappingIndex:0,viewport:[0,0,h,p],eye:"none",clear:!0,isAR:!1}),(!o.pickColorTex||!o.pickDepthTex)&&(to(o),o.pickColorTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"rgba8unorm",usage:gi|yg}),o.pickColorView=o.pickColorTex.createView(),o.pickDepthTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"depth24plus",usage:gi}),o.pickDepthView=o.pickDepthTex.createView(),o.pickReadBuf=s.createBuffer({size:256,usage:si|Zm}));let A=Cg(lt(),y,x,v,h,p),b=Pg(s,c,m),w=new ArrayBuffer(800);qs(w,{vp:A,modelRoot:n.modelRootMatrix??yi,eyePos:[0,0,0],exposure:1,envIntensity:1,toneMappingIndex:2,lights:[],hasEnvMap:!1,sectionPlane:c0(n)}),s.queue.writeBuffer(m.pickUniformBuf,0,w);let S=!!(o.pickReadBuf&&!o.pickBusy),E=S?o.pickReadBuf:s.createBuffer({size:256,usage:si|Zm});S&&(o.pickBusy=!0);try{let N=s.createCommandEncoder(),C=N.beginRenderPass({colorAttachments:[{view:o.pickColorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}],depthStencilAttachment:{view:o.pickDepthView,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"discard"}});if(C.executeBundles([b]),C.end(),N.copyTextureToBuffer?.({texture:o.pickColorTex},{buffer:E,bytesPerRow:256,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:1}),s.queue.submit([N.finish()]),await E.mapAsync(bg,0,4),o.gen!==l)return xt(()=>E.unmap()),-1;let _=new Uint8Array(E.getMappedRange(0,4)),P=_[0],R=_[1],I=_[2];E.unmap();let F=P+(R<<8)+(I<<16);return F>0&&F<=a.length?F-1:-1}finally{S?o.pickBusy=!1:xt(()=>E.destroy())}}willRenderScene(e){if(!jt)return!1;let t=e;if(t.xrSessionActive||Js(t,!0)!=="webgpu")return!1;if(this.states.get(e)?.ctx)return!0;let r=t.canvas??t.gl?.canvas;return!!(r&&typeof document<"u"&&typeof r.parentElement?.insertBefore=="function")}hideLayer(e){let t=this.states.get(e);t&&t.canvas&&t.visible&&(t.canvas.style&&(t.canvas.style.display="none"),t.visible=!1)}clearViewerScene(e){let t=this.states.get(e);t&&(t.gen++,cn(t.scene),t.scene=null,t.lastShadowDigest=0,this.hideLayer(e))}disposeViewer(e){let t=this.states.get(e);t&&(t.gen++,this.trackedViewers.delete(e),this.states.delete(e),t.unhookSnapshot?.(),t.unhookSnapshot=null,cn(t.scene),t.scene=null,eo(t),Pc(t),to(t),xt(()=>t.ctx?.unconfigure?.()),xt(()=>t.canvas?.remove?.()),t.ctx=null,t.canvas=null,t.dev=null,t.visible=!1)}onDeviceLost(e){let t=Qs.get(e);if(t){for(let r of t.ownedTextures)xt(()=>r.destroy());t.ownedTextures.clear(),Qs.delete(e)}for(let r of this.trackedViewers){let i=this.states.get(r);i&&i.dev===e&&(i.gen++,cn(i.scene),i.scene=null,eo(i),Pc(i),to(i),i.dev=null,i.configuredFormat="")}}};function hn(){return Ys||(Ys=new Cc),Ys}var Ec={name:"three-live-webgpu-scene",onRegister(){let e=We();e.gpuSceneAccelerator=hn(),e.webgpuDeviceProvider||(e.webgpuDeviceProvider=r0),!jt&&!Gr&&!Wt&&Zs()&&Ri()},onElementConnected(e){let t=e;!jt&&!Gr&&!Wt&&Zs()&&Ri().then(r=>{r&&t?.viewer&&xt(()=>t.viewer.render?.())})},onAttributeChanged(e,t){(t==="renderer"||t==="section-plane"||t==="shadow-maps")&&e?.viewer?.render?.()},onLoadModel(e){e&&typeof e=="object"&&hn().clearViewerScene(e)},onClearScene(e){e&&typeof e=="object"&&hn().clearViewerScene(e)},onXRSessionEnd(e){e&&typeof e=="object"&&xt(()=>e.render?.())},onDestroy(e,t){t&&typeof t=="object"&&hn().disposeViewer(t)}};Rt(Ec),di.registerScriptRunner(Bn),typeof window<"u"&&(window.ThreeLiveBundle=Gc);export{vu as AIVoiceSession,Fa as AmbientLight,La as BoxGeometry,zt as BufferAttribute,$t as BufferGeometry,za as Camera,Tl as CapsuleGeometry,Jo as CatmullRomCurve3,Pl as CircleGeometry,ml as Clock,Br as Color,Wo as ConeGeometry,Zo as CubicBezierCurve3,hi as Curve3,Ra as CylinderGeometry,tl as DataTexture,ul as DirectionalLight,Al as DodecahedronGeometry,El as EdgesGeometry,Ca as Euler,Oo as Float32BufferAttribute,ll as Group,Za as HemisphereLight,eh as IKSolver,eu as IMAGE_SYSTEM_PROMPT,Sl as IcosahedronGeometry,Da as InstancedMesh,Qu as InteractivityVM,ah as LOD,Ia as LatheGeometry,fi as Light,ka as LightShadow,Pi as Line,zn as LineBasicMaterial,Yo as LineCurve3,Nl as LineDashedMaterial,Ll as LineLoop,Rl as LineSegments,wo as LodController,Xc as MAX_BSP_DEPTH,Kc as MAX_CSG_TRIANGLES,Hi as MAX_INSTANCES_PER_MESH,Jn as MAX_SHADOW_LIGHTS,Qc as MAX_SHAPE_POINTS,Yc as MAX_TEXT_GEOMETRY_CHARS,Ah as MAX_TSL_NODES,Th as MAX_TSL_UNIFORMS,_r as Material,Uo as MathUtils,zo as Matrix3,Ai as Matrix4,Yr as Mesh,nl as MeshBasicMaterial,al as MeshLambertMaterial,sl as MeshPhongMaterial,ol as MeshPhysicalMaterial,Gi as MeshStandardMaterial,zr as Object3D,_l as OctahedronGeometry,Km as PART_STRIDE_BYTES,Wm as PART_STRIDE_WORDS,cl as PerspectiveCamera,Ho as PlaneGeometry,Ba as PointLight,Il as Points,Qa as PointsMaterial,Qh as PolyhedronFallbackGeometry,pi as PolyhedronGeometry,Qo as QuadraticBezierCurve3,Dn as Quaternion,vl as RawShaderMaterial,Dl as RectAreaLight,Ya as RingGeometry,Ws as SCENE_PBR_WGSL,_c as SCENE_PICK_WGSL,Mc as SCENE_SHADOW_WGSL,qm as SCENE_UNIFORM_BYTES,sc as SHADOW_MAP_TEXTURE_UNIT,Va as Scene,Qr as SceneQuotaValidator,Ka as ShaderMaterial,qo as SphereGeometry,$l as SpotLight,lu as TEXTURE_PROMPT_SUFFIX,Ni as THREE,Ui as TSL_EXTENSION_NAME,Ph as TSL_TIME_PERIOD_SEC,Um as TSL_WGSL_UNIFORM_BYTES,wl as TetrahedronGeometry,kn as Texture,rl as TextureLoader,di as ThreeLiveElement,ir as ThreeView,Ko as TorusGeometry,Xo as TorusKnotGeometry,el as TubeGeometry,jo as Uint16BufferAttribute,Go as Uint32BufferAttribute,Ym as VERTEX_STRIDE_BYTES,Xm as VERTEX_STRIDE_FLOATS,ar as Vector2,Ze as Vector3,Bo as Vector4,fl as WebGLRenderer,Cc as WebGPUSceneAccelerator,Cl as WireframeGeometry,Ri as acquireSceneWebGPUDevice,Uu as activateAR,Ts as aiPlugin,tc as applyMeshoptFilter,Bn as authorScriptRunner,On as browserImageCodec,ru as buildImageMessages,tu as buildImageUserText,Ha as buildSandboxWorkerSource,ns as buildSelectIndex,lo as cadPlugin,xl as clearAuthorWarnings,au as compileFromImage,$o as compileTslToGlsl,bc as compileTslToWgsl,Tm as computeOutlineClipOffset,uc as computeWorldSceneBounds,xs as connectVoice,Ps as contactShadowPlugin,_u as createAIChatProvider,uu as createAIImageProvider,Aa as createUSDZBlob,wu as createWebSpeechRecognizer,Eu as crossFadeTo,nh as decimateGeometry,rc as decodeMeshoptBuffer,Fs as decodeMeshoptGLB,rf as defineModelViewer,Ms as describeEditResult,ss as describeSelection,Ji as describeVoiceSelection,nu as detectImageMime,on as doesMeshCastShadow,js as doesMeshReceiveShadow,Tu as editScene,_m as encodeMeshoptBuffer,Hu as environmentMapPlugin,Am as evaluateKawaseBloom,fh as evaluateToneMapping,Ua as exportSceneToCanvas3D,Oa as exportSceneToGLB,hl as exportSceneToUSDZ,pc as extractMaterialVariants,Bm as extractPrimitiveVariantMappings,As as extractScript,cc as fitDirectionalShadowMatrix,Os as fitSpotShadowMatrix,Xr as fmtShaderFloat,us as formatSpatialPriors,xu as geminiLiveAdapter,Sa as generateUSDZ,Ns as getARCapabilities,yl as getAllowClientScripts,bl as getAuthorWarnings,Qf as getBestARMode,em as getEnvironmentSH,$s as getInteractivityVM,sh as getLodController,Ga as getSandboxEngineSrc,gl as getSandboxIframeSrc,yr as getSelection,Im as getShadowMapStats,hn as getWebGPUSceneAccelerator,_a as glbToUSDZ,Hn as hideSelectionChips,Ku as hotspotPlugin,vo as ikPlugin,iu as imageRepairMessage,mu as indexedDbTextureCache,ha as installCadExtension,Tn as installLodExtension,ga as installProceduralExtension,Ta as installTslExtension,Ju as interactivityPlugin,$r as isAllowedImageUrl,Ti as isAllowedSandboxEngineUrl,Bu as isQuickLookSupported,zu as isSceneViewerSupported,Vu as isWebXRSupported,Iu as keyframeAnimationPlugin,Mo as lodPlugin,Ol as matchSelection,ec as materialsPlugin,Bs as meshoptDecoder,ic as meshoptPlugin,$u as morphPlugin,qi as noopProxy,hs as normalizeImageInput,Tc as normalizeRendererPreference,lc as normalizeShadowMapsMode,Pa as packUniformVec4,Cu as parseAnimations,nc as parseHexRgb,da as parseLod,Yn as parseSafeGltfPointer,Zl as parseSelectReply,hu as parseTexturePack,Wl as parseVoiceCommand,ac as postprocessingPlugin,cu as prepareAlbedo,_o as proceduralPlugin,fa as quatFromUnitVectors,bu as realtimeAdapter,cm as registerMaterialShader,aa as remapClipDepthToZeroOne,n0 as resetSceneWebGPUDevice,Gs as resolveActiveShadowLights,Js as resolveSceneRenderBackend,Yl as resolveSelection,Jl as resolveSelectionWithModel,en as sampleChannel,Vn as sceneSelectEntries,Vi as sceneToCanvas3D,En as sceneToGLB,In as sceneToUSDZ,qn as selectByVoice,os as selectCamera,pa as selectLodLevelIndex,zm as selectMaterialVariant,Ql as selectMessages,Mu as selectNamesByVoice,Zu as sendInteractivityEvent,fu as serializeTexturePack,Do as serializeTslToUsda,jh as setAllowClientScripts,ju as setEnvironmentSH,xc as setMaterialUniform,Xf as setMorphTargetWeight,Uh as setSandboxEngineSrc,Oh as setSandboxIframeSrc,i0 as setSceneWebGPUDeviceForTests,Ss as setSelectOnTap,Ar as setSelection,mc as shadowMapsPlugin,gu as showSelectionChips,ku as skinningPlugin,mo as solveFABRIK,fo as solveTwoBoneIK,ws as speakableName,_s as startVoiceEdit,ps as textureRequests,Wi as threeAuthorPlugin,tf as threeMicroPlugin,zi as toGLBData,pl as toTrustedWorkerScriptURL,vc as tslPlugin,Lo as tslSafeMod,nr as tslTypeArity,Ro as tslTypeFromArity,Pu as undoEdit,qa as validateSandboxWorkerMessage,Oi as validateTslGraph,dc as variantsPlugin,Zr as warnUnsupported,Ec as webgpuScenePlugin,gc as webxrPlugin,qs as writeSceneUniforms};