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 ThreeLiveBundle=(()=>{var Zr=Object.defineProperty,co=Object.getOwnPropertyDescriptor,mo=Object.getOwnPropertyNames,fo=Object.prototype.hasOwnProperty,po=(e,t)=>{for(var r in t)Zr(e,r,{get:t[r],enumerable:!0})},go=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of mo(t))!fo.call(e,n)&&n!==r&&Zr(e,n,{get:()=>t[n],enumerable:!(i=co(t,n))||i.enumerable});return e},yo=e=>go(Zr({},"__esModule",{value:!0}),e),Qr={};po(Qr,{AmbientLight:()=>Ei,BoxGeometry:()=>Ai,BufferAttribute:()=>He,BufferGeometry:()=>Ue,Camera:()=>Ci,CapsuleGeometry:()=>Os,CatmullRomCurve3:()=>is,CircleGeometry:()=>Bs,Clock:()=>bs,Color:()=>gt,ConeGeometry:()=>Yn,CubicBezierCurve3:()=>rs,Curve3:()=>Rt,CylinderGeometry:()=>Ti,DataTexture:()=>ss,DirectionalLight:()=>fs,DodecahedronGeometry:()=>Us,EdgesGeometry:()=>Ws,Euler:()=>wi,Float32BufferAttribute:()=>Gn,Group:()=>cs,HemisphereLight:()=>zi,IKSolver:()=>So,IcosahedronGeometry:()=>Vs,InstancedMesh:()=>Pi,InteractivityVM:()=>Aa,LOD:()=>Vo,LatheGeometry:()=>Si,Light:()=>ar,Line:()=>zt,LineBasicMaterial:()=>Ur,LineCurve3:()=>es,LineDashedMaterial:()=>zs,LineLoop:()=>Gs,LineSegments:()=>js,LodController:()=>xn,MAX_BSP_DEPTH:()=>vo,MAX_CSG_TRIANGLES:()=>xo,MAX_INSTANCES_PER_MESH:()=>sr,MAX_SHAPE_POINTS:()=>wo,MAX_TEXT_GEOMETRY_CHARS:()=>Mo,Material:()=>it,MathUtils:()=>Wn,Matrix3:()=>$n,Matrix4:()=>Ot,Mesh:()=>At,MeshBasicMaterial:()=>os,MeshLambertMaterial:()=>ls,MeshPhongMaterial:()=>us,MeshPhysicalMaterial:()=>hs,MeshStandardMaterial:()=>nr,Object3D:()=>yt,OctahedronGeometry:()=>Fs,PerspectiveCamera:()=>ps,PlaneGeometry:()=>Xn,PointLight:()=>Ni,Points:()=>qs,PointsMaterial:()=>Bi,PolyhedronFallbackGeometry:()=>Rl,PolyhedronGeometry:()=>Et,QuadraticBezierCurve3:()=>ts,Quaternion:()=>Cr,RawShaderMaterial:()=>Is,RectAreaLight:()=>Ks,RingGeometry:()=>Oi,Scene:()=>Li,SceneQuotaValidator:()=>Tt,ShaderMaterial:()=>Ui,SphereGeometry:()=>Kn,SpotLight:()=>Xs,THREE:()=>$t,TetrahedronGeometry:()=>Ds,Texture:()=>Ir,TextureLoader:()=>as,ThreeLiveElement:()=>Ht,ThreeView:()=>Qe,TorusGeometry:()=>Zn,TorusKnotGeometry:()=>Jn,TubeGeometry:()=>ns,Uint16BufferAttribute:()=>jn,Uint32BufferAttribute:()=>qn,Vector2:()=>ut,Vector3:()=>xe,Vector4:()=>zn,WebGLRenderer:()=>gs,WireframeGeometry:()=>Hs,activateAR:()=>ha,applyMeshoptFilter:()=>La,authorScriptRunner:()=>kr,buildSandboxWorkerSource:()=>Fi,cadPlugin:()=>hn,clearAuthorWarnings:()=>_s,computeOutlineClipOffset:()=>yu,contactShadowPlugin:()=>Xi,createUSDZBlob:()=>xi,crossFadeTo:()=>ea,decimateGeometry:()=>Fo,decodeMeshoptBuffer:()=>Oa,decodeMeshoptGLB:()=>nn,defineModelViewer:()=>Ll,encodeMeshoptBuffer:()=>cu,environmentMapPlugin:()=>pa,evaluateKawaseBloom:()=>gu,evaluateToneMapping:()=>jo,exportSceneToCanvas3D:()=>_i,exportSceneToGLB:()=>Ii,exportSceneToUSDZ:()=>ds,extractMaterialVariants:()=>qa,extractPrimitiveVariantMappings:()=>Tu,generateUSDZ:()=>bi,getARCapabilities:()=>Ki,getAllowClientScripts:()=>As,getAuthorWarnings:()=>Ls,getBestARMode:()=>Vl,getEnvironmentSH:()=>Hl,getInteractivityVM:()=>rn,getLodController:()=>Uo,getSandboxEngineSrc:()=>Di,getSandboxIframeSrc:()=>ws,glbToUSDZ:()=>yi,hotspotPlugin:()=>da,ikPlugin:()=>bn,installCadExtension:()=>ei,installLodExtension:()=>wr,interactivityPlugin:()=>Sa,isAllowedSandboxEngineUrl:()=>Bt,isQuickLookSupported:()=>sa,isSceneViewerSupported:()=>aa,isWebXRSupported:()=>oa,keyframeAnimationPlugin:()=>ta,lodPlugin:()=>vn,materialsPlugin:()=>Ra,meshoptDecoder:()=>sn,meshoptPlugin:()=>za,morphPlugin:()=>ra,noopProxy:()=>or,parseAnimations:()=>Js,parseHexRgb:()=>Ha,parseLod:()=>ci,parseSafeGltfPointer:()=>jr,postprocessingPlugin:()=>ja,quatFromUnitVectors:()=>ni,registerMaterialShader:()=>Ql,sampleChannel:()=>hr,sceneToCanvas3D:()=>ir,sceneToGLB:()=>Tr,sceneToUSDZ:()=>Nr,selectLodLevelIndex:()=>hi,selectMaterialVariant:()=>Su,sendInteractivityEvent:()=>Ta,setAllowClientScripts:()=>yl,setEnvironmentSH:()=>ca,setMorphTargetWeight:()=>_l,setSandboxEngineSrc:()=>fl,setSandboxIframeSrc:()=>dl,skinningPlugin:()=>ia,solveFABRIK:()=>pn,solveTwoBoneIK:()=>fn,threeAuthorPlugin:()=>ur,threeMicroPlugin:()=>Nl,toGLBData:()=>tr,toTrustedWorkerScriptURL:()=>Ms,validateSandboxWorkerMessage:()=>Vi,variantsPlugin:()=>Xa,warnUnsupported:()=>Pt,webxrPlugin:()=>Ya});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],N=`/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)}}),B=m("variable/set",{configuration:{variable:z},values:{value:d(he)}}),$=m("pointer/interpolate",{configuration:{pointer:N},values:{value:{value:Array.isArray(w.to)?w.to:H},duration:{value:oe}}}),_=m("pointer/interpolate",{configuration:{pointer:N},values:{value:{value:Array.isArray(w.from)?w.from:H},duration:{value:oe}}});s[B].flows={out:{node:m("flow/branch",{values:{condition:d(ue)},flows:{true:{node:$},false:{node:_}}})}},S.push(B)}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),N=m("variable/get",{configuration:{variable:H}}),z=m("math/not",{values:{a:d(N)}}),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(N)}})}},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`,N=c(`__color_idx_${p}_${k}`,"int",0),z=m("variable/get",{configuration:{variable:N}}),ue=m("math/add",{values:{a:d(z),b:{value:1}}}),he=m("math/rem",{values:{a:d(ue),b:{value:w.colors.length}}}),B=m("variable/set",{configuration:{variable:N},values:{value:d(he)}}),$={};for(let _=0;_<w.colors.length;_++){let G=w.colors[_],j=Array.isArray(G)&&G.length>=3?[G[0],G[1],G[2],G[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[B].flows={out:{node:m("flow/switch",{values:{selection:d(z)},flows:$})}},S.push(B)}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,N]of Object.entries(w.values||{}))I[H]={value:N};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 O={};return S.forEach((k,w)=>{O[String(w)]={node:k}}),m("flow/sequence",{flows:O})},W=(T,E,S)=>{let O=F(E);O!==null&&m(T,{...S?{configuration:S}:{},flows:{out:{node:O}}})};if(M.onSelect&&W("pointer/onSelect",M.onSelect,{nodeIndex:p}),M.onHoverIn&&W("pointer/onHoverIn",M.onHoverIn,{nodeIndex:p}),M.onHoverOut&&W("pointer/onHoverOut",M.onHoverOut,{nodeIndex:p}),M.onStart&&W("event/onStart",M.onStart),M.onReceive&&typeof M.onReceive=="object")for(let[T,E]of Object.entries(M.onReceive))W("event/receive",E,{event:h(T)})}return s.length?{graphs:[{declarations:i,nodes:s,variables:l,events:o}],graph:0}:null}var on='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).',ln="Security Error: client-side scripts require allow-client-scripts opt-in.",br="__THREE_LIVE_REGISTRY__";function Ae(){let e=typeof globalThis<"u"?globalThis:{};if(!e[br]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,br,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[br]=t}}return e[br]}var Fe=Ae().plugins;function Jr(e){let t=Ae();t.workerExtensionInstallers||(t.workerExtensionInstallers=[]),t.workerExtensionInstallers.includes(e)||t.workerExtensionInstallers.push(e)}function Ge(e){let t=Ae().plugins;t.some(r=>r.name===e.name)||t.push(e),e.onRegister?.()}function un(){return Ae().plugins}var xo=8192,vo=2048,Mo=128,wo=4096;function ei(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 C=Number(A)||0,U=Number(L)||0;return this.currentPoint.set(C,U),this.segments.push({type:"move",pts:[C,U]}),this}lineTo(A,L){let C=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(C,U),this.segments.push({type:"line",pts:[C,U]}),this}quadraticCurveTo(A,L,C,U){let Q=this.currentPoint.x,X=this.currentPoint.y,Z=Number(A)||0,J=Number(L)||0,K=Number(C)||0,ae=Number(U)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[Q,X]}),this.currentPoint.set(K,ae),this.segments.push({type:"quad",pts:[Q,X,Z,J,K,ae]}),this}bezierCurveTo(A,L,C,U,Q,X){let Z=this.currentPoint.x,J=this.currentPoint.y,K=Number(A)||0,ae=Number(L)||0,ne=Number(C)||0,re=Number(U)||0,ce=Number(Q)||0,me=Number(X)||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,C,U,Q,X=!1){return this.absellipse(A,L,C,C,U,Q,X,0)}arc(A,L,C,U,Q,X=!1){return this.absarc(this.currentPoint.x+(Number(A)||0),this.currentPoint.y+(Number(L)||0),C,U,Q,X)}absellipse(A,L,C,U,Q,X,Z=!1,J=0){let K=Number(A)||0,ae=Number(L)||0,ne=Math.max(0,Number(C)||0),re=Math.max(0,Number(U)||0),ce=Number(Q)||0,me=Number(X)||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),Me=ne*Math.cos(me),be=re*Math.sin(me);return this.currentPoint.set(K+Me*pe-be*ye,ae+Me*ye+be*pe),this}ellipse(A,L,C,U,Q,X,Z=!1,J=0){return this.absellipse(this.currentPoint.x+(Number(A)||0),this.currentPoint.y+(Number(L)||0),C,U,Q,X,Z,J)}closePath(){if(this.segments.length>0){let A=this.segments[0],L=0,C=0;if(A.type==="arc"){let U=A.pts[0],Q=A.pts[1],X=A.pts[2],Z=A.pts[3],J=A.pts[4],K=A.pts[7],ae=Math.cos(K),ne=Math.sin(K),re=X*Math.cos(J),ce=Z*Math.sin(J);L=U+re*ae-ce*ne,C=Q+re*ne+ce*ae}else L=A.pts[0],C=A.pts[1];Math.hypot(this.currentPoint.x-L,this.currentPoint.y-C)>1e-6&&this.lineTo(L,C)}return this}getPoints(A=12){let L=Math.max(1,Math.min(128,Math.floor(Number(A)||12))),C=[],U=(Q,X)=>{if(C.length>0){let Z=C[C.length-1];if(Math.hypot(Z.x-Q,Z.y-X)<1e-6)return}C.push(new r(Q,X))};for(let Q of this.segments){let X=Q.pts;if(Q.type==="move"||Q.type==="line")U(X[0],X[1]);else if(Q.type==="quad"){let Z=X[0],J=X[1],K=X[2],ae=X[3],ne=X[4],re=X[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=X[0],J=X[1],K=X[2],ae=X[3],ne=X[4],re=X[5],ce=X[6],me=X[7];U(Z,J);for(let ge=1;ge<=L;ge++){let de=ge/L,pe=1-de,ye=pe*pe,Me=de*de;U(ye*pe*Z+3*ye*de*K+3*pe*Me*ne+Me*de*ce,ye*pe*J+3*ye*de*ae+3*pe*Me*re+Me*de*me)}}else if(Q.type==="arc"){let Z=X[0],J=X[1],K=X[2],ae=X[3],ne=X[4],re=X[5],ce=X[6]!==0,me=X[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),Me=Math.sin(me),be=Math.max(2,L);for(let Ee=0;Ee<=be;Ee++){let Se=Ee/be,Re=ne+Se*de,Ne=K*Math.cos(Re),De=ae*Math.sin(Re);U(Z+Ne*ye-De*Me,J+Ne*Me+De*ye)}}}if(C.length>2){let Q=C[0],X=C[C.length-1];Math.hypot(Q.x-X.x,Q.y-X.y)<1e-6&&C.pop()}return C}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 C=0,U=L-1;C<L;U=C++)A+=R[U].x*R[C].y-R[C].x*R[U].y;return A*.5}function M(R,A,L,C,U,Q,X,Z){let J=X-L,K=Z-C,ae=U-L,ne=Q-C,re=R-L,ce=A-C,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,Me=me*pe-ge*ge;if(Math.abs(Me)<1e-12)return!1;let be=1/Me,Ee=(pe*de-ge*ye)*be,Se=(me*ye-ge*de)*be;return Ee>=-1e-7&&Se>=-1e-7&&Ee+Se<=1.0000001}function P(R,A){let L=R.slice();y(L)<0&&L.reverse();let C=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=C.length;C.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 X=(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(X(J,K,re)*X(J,K,ce)<0&&X(re,ce,J)*X(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=>C[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],Me=re[(pe+ne-1)%ne],be=re[(pe+1)%ne],Ee=X(ye,be,K)>=0,Se=X(Me,ye,K)>=0;if((X(Me,ye,be)>=0?Ee&&Se:Ee||Se)&&!Z(K,ye,re)&&!Q.some(Re=>Z(K,ye,Re.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=>C[J]),mergedIndices:U,allVertices:C}}function F(R,A){let L=[],C=R.slice();if(C.length<3)return L;let U=C.length*C.length+64,Q=0;for(;C.length>2&&U-- >0;){let X=C.length,Z=C[(Q+X-1)%X],J=C[Q%X],K=C[(Q+1)%X],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<X;ye++){let Me=C[ye];if(Me===Z||Me===J||Me===K)continue;let be=A[Me];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]),C.splice(Q%X,1),Q=Math.max(0,Q%X-1);continue}}Q++,Q>=X*2&&(L.push([Z,J,K]),C.splice((Q-1)%X,1),Q=0)}return L}function W(R,A){let L=R instanceof p?R.extractPoints(A):{shape:R.getPoints(A),holes:[]},C=L.shape.length;for(let U of L.holes)C+=U.length;if(C>x)throw new RangeError(`SecurityError: shape point count (${C}) exceeds MAX_SHAPE_POINTS (${x})`);return L}function T(R){let A=1/0,L=1/0,C=-1/0,U=-1/0;for(let Q of R)Q.x<A&&(A=Q.x),Q.y<L&&(L=Q.y),Q.x>C&&(C=Q.x),Q.y>U&&(U=Q.y);return[A,L,Math.max(1e-6,C-A),Math.max(1e-6,U-L)]}class E extends u{constructor(A=new p,L=12){super();let C=Array.isArray(A)?A:[A],U=[],Q=[],X=[],Z=[];for(let J of C){if(!(J instanceof v))continue;let K=W(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),X.push((ye.x-me)/de,(ye.y-ge)/pe);for(let[ye,Me,be]of re)Z.push(ce+ye,ce+Me,ce+be)}S(this,U,Q,X,Z)}}function S(R,A,L,C,U){return R.setAttribute("position",new a(A,3)),R.setAttribute("normal",new a(L,3)),R.setAttribute("uv",new a(C,2)),R.setIndex(U),R}function O(R){let A=R.length,L=[];for(let C=0;C<A;C++){let U=R[(C+A-1)%A],Q=R[C],X=R[(C+1)%A],Z=Q.x-U.x,J=Q.y-U.y,K=Math.hypot(Z,J)||1;Z/=K,J/=K;let ae=X.x-Q.x,ne=X.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,Me=Math.hypot(pe,ye);if(Me>1e-6){pe/=Me,ye/=Me;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 C=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),X=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 C){if(!(de instanceof v))continue;let pe=W(de,U);if(pe.shape.length<3)continue;let ye=pe.shape.slice();y(ye)<0&&ye.reverse();let Me=[];for(let _e of pe.holes){if(_e.length<3)continue;let Ce=_e.slice();y(Ce)>0&&Ce.reverse(),Me.push(Ce)}let{mergedIndices:be,allVertices:Ee}=P(ye,Me),Se=F(be,Ee),Re=[ye,...Me],Ne=[];for(let _e of Re){let Ce=O(_e);for(let je of Ce)Ne.push(je)}let[De,Je,Xe,mt]=T(Ee);for(let[_e,Ce]of[[-J,-1],[Q+J,1]]){let je=re.length/3;for(let $e=0;$e<Ee.length;$e++){let Oe=Ee[$e],Be=Ne[$e]??new r(0,0),rt=Oe.x+Be.x*ae,Ze=Oe.y+Be.y*ae;re.push(rt,Ze,_e),ce.push(0,0,Ce),me.push((rt-De)/Xe,(Ze-Je)/mt)}for(let[$e,Oe,Be]of Se)ge.push(je+$e,je+(Ce<0?Be:Oe),je+(Ce<0?Oe:Be))}let Ve=[];if(Z&&ne>0)for(let _e=0;_e<ne;_e++){let Ce=_e/ne*Math.PI/2;Ve.push({z:-J*Math.cos(Ce),expand:ae+K*Math.sin(Ce)})}for(let _e=0;_e<=X;_e++){let Ce=_e/X;Ve.push({z:Ce*Q,expand:ae+K})}if(Z&&ne>0)for(let _e=1;_e<=ne;_e++){let Ce=_e/ne*Math.PI/2;Ve.push({z:Q+J*Math.sin(Ce),expand:ae+K*Math.cos(Ce)})}let st=0;for(let _e of Re){let Ce=_e.length;for(let je=0;je<Ve.length-1;je++){let $e=Ve[je],Oe=Ve[je+1];for(let Be=0;Be<Ce;Be++){let rt=(Be+1)%Ce,Ze=_e[Be],at=_e[rt],ot=Ne[st+Be],lt=Ne[st+rt],ft=Ze.x+ot.x*$e.expand,pt=Ze.y+ot.y*$e.expand,jt=at.x+lt.x*$e.expand,qt=at.y+lt.y*$e.expand,gr=at.x+lt.x*Oe.expand,yr=at.y+lt.y*Oe.expand,Lt=Ze.x+ot.x*Oe.expand,_t=Ze.y+ot.y*Oe.expand,It=jt-ft,vt=qt-pt,Ru=Lt-ft,Pu=_t-pt,Za=Oe.z-$e.z,Xt=vt*Za,Kt=-It*Za,Yt=It*Pu-vt*Ru,an=Math.hypot(Xt,Kt,Yt)||1;Xt/=an,Kt/=an,Yt/=an;let Zt=re.length/3;re.push(ft,pt,$e.z,jt,qt,$e.z,gr,yr,Oe.z,Lt,_t,Oe.z),ce.push(Xt,Kt,Yt,Xt,Kt,Yt,Xt,Kt,Yt,Xt,Kt,Yt);let Qa=Be/Ce,Ja=(Be+1)/Ce,eo=je/(Ve.length-1),to=(je+1)/(Ve.length-1);me.push(Qa,eo,Ja,eo,Ja,to,Qa,to),ge.push(Zt,Zt+1,Zt+2,Zt,Zt+2,Zt+3)}}st+=Ce}}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 C=R.nx+(A.nx-R.nx)*L,U=R.ny+(A.ny-R.ny)*L,Q=R.nz+(A.nz-R.nz)*L,X=Math.hypot(C,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:C/X,ny:U/X,nz:Q/X,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],C=R[2],U=L.x-A.x,Q=L.y-A.y,X=L.z-A.z,Z=C.x-A.x,J=C.y-A.y,K=C.z-A.z,ae=Q*K-X*J,ne=X*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 N=1e-5,z=0,ue=1,he=2,B=3;function $(R,A,L,C,U,Q,X,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-C,me=ce<-N?he:ce>N?ue:z;K|=me,ae.push(me)}switch(K){case z:{R*U.nx+A*U.ny+L*U.nz>0?Q.push(U):X.push(U);break}case ue:Z.push(U);break;case he:J.push(U);break;case B:{let ne=[],re=[],ce=U.vertices.length;for(let ye=0;ye<ce;ye++){let Me=(ye+1)%ce,be=ae[ye],Ee=ae[Me],Se=U.vertices[ye],Re=U.vertices[Me];if(be!==he&&ne.push(Se),be!==ue&&re.push(be!==he?w(Se):Se),(be|Ee)===B){let Ne=Re.x-Se.x,De=Re.y-Se.y,Je=Re.z-Se.z,Xe=R*Ne+A*De+L*Je,mt=Math.abs(Xe)>1e-12?(C-(R*Se.x+A*Se.y+L*Se.z))/Xe:.5,Ve=oe(Se,Re,Math.max(0,Math.min(1,mt)));ne.push(Ve),re.push(w(Ve))}}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 C=[],U=[];for(let Q=0;Q<A.length;Q++)$(this.nx,this.ny,this.nz,this.w,A[Q],C,U,C,U);return this.front&&C.length>0&&(C=this.front.clipPolygons(C,L+1)),this.back?U=U.length>0?this.back.clipPolygons(U,L+1):[]:U=[],C.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 C=[],U=[];for(let Q=0;Q<A.length;Q++)$(this.nx,this.ny,this.nz,this.w,A[Q],this.polygons,this.polygons,C,U);C.length>0&&(this.front||(this.front=new _),this.front.build(C,L+1)),U.length>0&&(this.back||(this.back=new _),this.back.build(U,L+1))}}function G(R,A){if(!A&&R._csgPolygons)return R._csgPolygons;let L=R.attributes.position;if(!L||L.count===0)return[];let C=R.attributes.normal,U=R.attributes.uv,Q=R.index?R.index.array:null,X=Math.floor(Q?Q.length/3:L.count/3);if(X>d)throw new RangeError(`SecurityError: CSG input triangle count (${X}) 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=C?C.getX(re):NaN,pe=C?C.getY(re):NaN,ye=C?C.getZ(re):NaN;if(Z&&K){let Ee=Z[0]*ce+Z[4]*me+Z[8]*ge+Z[12],Se=Z[1]*ce+Z[5]*me+Z[9]*ge+Z[13],Re=Z[2]*ce+Z[6]*me+Z[10]*ge+Z[14];ce=Ee,me=Se,ge=Re;let Ne=K[0]*de+K[3]*pe+K[6]*ye,De=K[1]*de+K[4]*pe+K[7]*ye,Je=K[2]*de+K[5]*pe+K[8]*ye,Xe=Math.hypot(Ne,De,Je)||1;de=Ne/Xe,pe=De/Xe,ye=Je/Xe}let Me=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:Me,v:be}},ne=[];for(let re=0;re<X;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=[],C=[],U=[];for(let X of R){let Z=X.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(X.nx,X.ny,X.nz),C.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,C,U);return Q._csgPolygons=R,Q}function q(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 C=1/0,U=1/0,Q=1/0,X=-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<C&&(C=de.x),de.y<U&&(U=de.y),de.z<Q&&(Q=de.z),de.x>X&&(X=de.x),de.y>Z&&(Z=de.y),de.z>J&&(J=de.z)}}C-=1e-4,U-=1e-4,Q-=1e-4,X+=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,Me=-1/0,be=-1/0,Ee=-1/0;for(let Se=0;Se<ge.length;Se++){let Re=ge[Se];Re.x<de&&(de=Re.x),Re.y<pe&&(pe=Re.y),Re.z<ye&&(ye=Re.z),Re.x>Me&&(Me=Re.x),Re.y>be&&(be=Re.y),Re.z>Ee&&(Ee=Re.z)}Me<C||de>X||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,C=null,U=null){let Q=G(R,C),X=G(A,U);return j(q(Q,X,L))}function Y(R,A,L){let C=R instanceof c||!!R?.isMesh,U=A instanceof c||!!A?.isMesh,Q=C?R.geometry:R,X=U?A.geometry:A,Z=null;if(U)if(A.updateMatrix(),C){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,X,L,null,Z),K=C?R.material:new m,ae=new c(J,K);return C&&(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 C=String(A??"").slice(0,g),U=Math.max(.005,Math.min(100,b(L.size,.2))),Q=!!(L.bevelEnabled??!1),X=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)))+X*2,K=U*.085+Z,ae=U*.68,ne=U*.82,re=[],ce=[],me=[],ge=[],de=(Me,be,Ee,Se,Re,Ne,De)=>{let Je=Ee-Me,Xe=Se-be,mt=Math.hypot(Je,Xe),Ve=1,st=0;mt>1e-6&&(Ve=Je/mt,st=Xe/mt);let _e=-st*Re,Ce=Ve*Re,je=Ve*Re*.6,$e=st*Re*.6,Oe=Me-je+_e,Be=be-$e+Ce,rt=Me-je-_e,Ze=be-$e-Ce,at=Ee+je-_e,ot=Se+$e-Ce,lt=Ee+je+_e,ft=Se+$e+Ce,pt=(jt,qt,gr,yr,Lt,_t,It)=>{let vt=re.length/3;re.push(jt[0],jt[1],jt[2],qt[0],qt[1],qt[2],gr[0],gr[1],gr[2],yr[0],yr[1],yr[2]),ce.push(Lt,_t,It,Lt,_t,It,Lt,_t,It,Lt,_t,It),me.push(0,0,1,0,1,1,0,1),ge.push(vt,vt+1,vt+2,vt,vt+2,vt+3)};pt([Oe,Be,De],[rt,Ze,De],[at,ot,De],[lt,ft,De],0,0,1),pt([rt,Ze,Ne],[Oe,Be,Ne],[lt,ft,Ne],[at,ot,Ne],0,0,-1),pt([Oe,Be,Ne],[rt,Ze,Ne],[rt,Ze,De],[Oe,Be,De],-Ve,-st,0),pt([at,ot,Ne],[lt,ft,Ne],[lt,ft,De],[at,ot,De],Ve,st,0),pt([rt,Ze,Ne],[at,ot,Ne],[at,ot,De],[rt,Ze,De],st,-Ve,0),pt([lt,ft,Ne],[Oe,Be,Ne],[Oe,Be,De],[lt,ft,De],-st,Ve,0)},pe=0,ye=0;for(let Me=0;Me<C.length;Me++){let be=C[Me];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(),Se=be!==Ee&&be>="a"&&be<="z",Re=se[Ee]??se["?"],Ne=Se?U*.76:U,De=Se?ae*.88:ae;for(let Je of Re)for(let Xe=0;Xe<Je.length-1;Xe++){let mt=Je[Xe],Ve=Je[Xe+1];de(pe+mt[0]*De,ye+mt[1]*Ne,pe+Ve[0]*De,ye+Ve[1]*Ne,K,-J*.5,J*.5)}pe+=Se?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="",X=.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&&(X=Number(K.size)||.08),(K.depth!==void 0||K.height!==void 0)&&(Z=Number(K.depth??K.height)||X*.2),(typeof K.color=="string"||typeof K.color=="number")&&(J=K.color)}Q.trim().length>0&&(A.geometry=new le(Q,{size:X,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 C=R.userData?.csg;if(C&&typeof C=="object"&&R.userData._csgApplied!==!0&&A.geometry instanceof u&&A.geometry.attributes.position?.count>0){R.userData._csgApplied=!0;let U=Array.isArray(C)?C:[C],Q=A.geometry;for(let X of U){if(!X||typeof X!="object")continue;let Z=X,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 hn={name:"cad",onRegister(){Jr(ei);let e=Ae(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&ei(t,e)}};function Pe(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function ti(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 xr(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 Qt(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 Ke(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 ri(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,W=h*g-m*f,T=h*x-c*f,E=h*b-d*f,S=m*x-c*g,O=m*b-d*g,k=c*b-d*x,w=v*k-p*O+y*S+M*E-P*T+F*W;return w?(w=1/w,e[0]=(o*k-a*O+u*S)*w,e[1]=(n*O-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*O-o*E+u*W)*w,e[9]=(i*E-r*O-s*W)*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*W)*w,e[13]=(r*S-i*T+n*W)*w,e[14]=(g*p-f*M-x*v)*w,e[15]=(h*M-m*p+c*v)*w,e):null}function cn(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 Ao(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,W=s*y-i*P,T=i*M-n*y,E=b*F+v*W+p*T;if(E>-1e-7&&E<1e-7)return!1;let S=1/E,O=e-l,k=t-o,w=r-a,ie=S*(O*F+k*W+w*T);if(ie<-x||ie>1+x)return!1;let oe=k*p-w*v,I=w*b-O*p,H=O*v-k*b,N=S*(i*oe+n*I+s*H);if(N<-x||ie+N>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,B=b*M-v*y,$=Math.hypot(ue,he,B)||1;return g.normal=[ue/$,he/$,B/$],!0}return!1}function vr(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];Qt(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 ii(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],W=m[1]-a[1],T=m[2]-a[2],E=Math.hypot(F,W,T),S=E>1e-6?[F/E,W/E,T/E]:M,O=Math.abs(x-y)+1e-5,k=Math.max(O,x+y-1e-5),w=Math.max(O,Math.min(k,E>1e-6?E:O)),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,N=c?c[2]-a[2]:g,z=I*S[0]+H*S[1]+N*S[2],ue=I-S[0]*z,he=H-S[1]*z,B=N-S[2]*z,$=Math.hypot(ue,he,B);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,B=S[0]*R-S[1]*ee,$=Math.hypot(ue,he,B)||1}let _=[ue/$,he/$,B/$],G=[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],q=j[0]-G[0],D=j[1]-G[1],Y=j[2]-G[2],te=Math.hypot(q,D,Y),se=te>1e-6?[q/te,D/te,Y/te]:S,le=[G[0]+se[0]*y,G[1]+se[1]*y,G[2]+se[2]*y],V=[(G[0]-a[0])/x,(G[1]-a[1])/x,(G[2]-a[2])/x];return{rootPos:[a[0],a[1],a[2]],midPos:G,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],O=d[E+1][1]-d[E][1],k=d[E+1][2]-d[E][2],w=Math.hypot(S,O,k);f.push(w),x+=w,g.push(w>1e-6?[S/w,O/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),W=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 O=f[S];d[S+1]=[d[S][0]+E[0]*O,d[S][1]+E[1]*O,d[S][2]+E[2]*O]}W=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;W=E;let O=(k,w,ie,oe,I)=>{let H=w[0]-k[0],N=w[1]-k[1],z=w[2]-k[2],ue=Math.hypot(H,N,z);if(ue>1e-6){let he=ie/ue;return[k[0]+H*he,k[1]+N*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]=O(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]=O(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],O=d[E+1][1]-d[E][1],k=d[E+1][2]-d[E][2],w=Math.hypot(S,O,k),ie=w>1e-6?[S/w,O/w,k/w]:g[E];T.push(i(g[E],ie))}return{positions:d,rotations:T,iterations:W}}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 Dt=ii(),mn=Dt.clampNum,To=Dt.parseIKTrait,ni=Dt.quatFromUnitVectors,fn=Dt.solveTwoBoneIK,pn=Dt.solveFABRIK,So=Dt.IKSolver;function si(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 Ro(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 Po(e,t,r,i,n){let s=mn(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 Eo(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return ri(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 ai(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 oi(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return si(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 Eo(r,[s[0],s[1],s[2]])}return null}function li(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 No(e){return[-e[0],-e[1],-e[2],e[3]]}function ui(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 Co(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 ui([r*a,i*a,n*a,Math.cos(l*t)])}function Lo(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 ui(f)}function _o(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 Mr(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 dn(e){e?.normalMatrix&&e?.transform&&Ke(e.normalMatrix,e.transform)}var gn=new WeakMap;function Io(e){let t=gn.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)}),gn.set(e,t)),t}function Do(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=Io(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 O of Array.isArray(S?.children)?S.children:[])typeof O=="number"&&d.push(O)}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 O=m.get(E);if(!O)return;let k=Pe();Qt(k,O.r,O.t,O.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 oi(T,r,e)},M=y(t.target);if(!M)return!0;let P=t.pole?y(t.pole)??void 0:void 0,F=yn(p,t,M,P),W=mn(t.weight,0,1,1);for(let T=0;T<o.length-1;T++){let E=Mr(v(o[T]),v(o[T+1])),S=Mr(F[T],F[T+1]);if(!E||!S)continue;let O=Co(ni(E,S),W),k=o[T],w=a[k],ie=w===f||w<0?g:x.get(w)??g,oe=Lo(ie),I=m.get(k);I.r=ui(li(No(oe),li(O,li(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),dn(T))}return!0}function yn(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let n=fn(e[0],e[1],e[2],r,i);return[e[0],n.midPos,n.effectorPos]}return pn(e,r,t.iterations,t.tolerance).positions}function ko(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=Mr([0,0,0],i[s]),u=Mr(r[s],r[s+1]);!l||l.length<16||!o||o.length<16||!a||!u||(_o(l,o,ni(a,u)),dn(t[s]))}}var bn={name:"ik",onRegister(){let e=Ae();Jr(ii),ii(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=To(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(Do(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||ai(i,s.root),o||ai(i,s.effector),s.mid&&!a&&ai(i,s.mid),!l||!o)continue;let u=oi(s.target,r,e);if(!u)continue;let h=s.pole?oi(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(si),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=[si(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=yn(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=Po(b,M,P,g[p-1],s.weight);Ro(m[p],F),b=F,v.push(F)}ko(i,m,v)}}};function wr(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),W=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,...W!==void 0?{hysteresis:W}:{},...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,W=-1/0,T=-1/0,E=-1/0;for(let $=0;$<g;$++){let _=f[$*3],G=f[$*3+1],j=f[$*3+2];_<M&&(M=_),G<P&&(P=G),j<F&&(F=j),_>W&&(W=_),G>T&&(T=G),j>E&&(E=j)}let S=Math.max(1e-5,W-M),O=Math.max(1e-5,T-P),k=Math.max(1e-5,E-F),w=Math.max(S,O,k),ie=$=>{let _=Math.max(1,Math.round(S/w*$)),G=Math.max(1,Math.round(O/w*$)),j=Math.max(1,Math.round(k/w*$)),q=new Map,D=new Int32Array(g),Y=[],te=[],se=[],le=[];for(let C=0;C<g;C++){let U=f[C*3],Q=f[C*3+1],X=f[C*3+2],Z=Math.min(_-1,Math.max(0,Math.floor((U-M)/S*_))),J=Math.min(G-1,Math.max(0,Math.floor((Q-P)/O*G))),K=Math.min(j-1,Math.max(0,Math.floor((X-F)/k*j))),ae=Z+J*_+K*_*G,ne=q.get(ae);ne===void 0?(ne=le.length,q.set(ae,ne),Y.push(U,Q,X),x&&te.push(x[C*3],x[C*3+1],x[C*3+2]),b&&se.push(b[C*2],b[C*2+1]),le.push(1)):(Y[ne*3]+=U,Y[ne*3+1]+=Q,Y[ne*3+2]+=X,x&&(te[ne*3]+=x[C*3],te[ne*3+1]+=x[C*3+1],te[ne*3+2]+=x[C*3+2]),le[ne]++),D[C]=ne}let V=[],ee=new Set;for(let C=0;C<p;C++){let U=v?v[C*3]:C*3,Q=v?v[C*3+1]:C*3+1,X=v?v[C*3+2]:C*3+2,Z=D[U],J=D[Q],K=D[X];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 C=0;C<R;C++){let U=1/le[C];if(A[C*3]=Y[C*3]*U,A[C*3+1]=Y[C*3+1]*U,A[C*3+2]=Y[C*3+2]*U,L){let Q=te[C*3],X=te[C*3+1],Z=te[C*3+2],J=Math.hypot(Q,X,Z)||1;L[C*3]=Q/J,L[C*3+1]=X/J,L[C*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 G=0;G<y;G++){let j=Math.min(I.triCount-1,Math.floor(G*_));$.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 N=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),z=N?.BufferGeometry??h.constructor,ue=N?.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 B=I.vertCount>65535?new Uint32Array(H):new Uint16Array(H);return typeof he.setIndex=="function"?he.setIndex(new ue(B,1)):he.index=new ue(B,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 Jt=wr(),Fo=Jt.decimateGeometry,hi=Jt.selectLodLevelIndex,ci=Jt.parseLod,Eu=Jt.materializeLodGeometry,Vo=Jt.LOD,er=new WeakMap;function Uo(e){return e&&typeof e=="object"?er.get(e):void 0}var xn=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=ci(s);if(!o&&l.length>0&&(o=ci({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=hi(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=hi(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})}}},vn={name:"lod",onRegister(){Jr(wr);let e=Ae(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);wr(t,e)},onLoadModel(e,t){!e||typeof e!="object"||er.set(e,new xn(e,t))},onUpdate(e){let t=er.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=er.get(e);n&&n.update(i)},onDestroy(e,t){t&&typeof t=="object"&&er.delete(t)}},Oo={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function kt(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=Oo[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 Bo(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 Ft(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 Mn=["neutral","reinhard","none","aces","agx"];function Vt(e){let t=String(e??"").trim().toLowerCase();return Mn.includes(t)?t:"neutral"}function zo(e){return Mn.indexOf(Vt(e))}function $o(e){return new TextDecoder().decode(e)}var wn=Ae().decoders;function Ho(e,t){wn.set(e.toLowerCase(),t)}function Ut(e){return wn.get(e.toLowerCase())}function An(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=$o(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")&&!Ut("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)&&!Ut("meshopt"))throw new Error(`Model requires ${c}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(u.includes("KHR_texture_basisu")&&!Ut("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 Fe)c.onParseGLB?.(m);return m}function Wo(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 tr(e){if(Wo(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return An(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Tn=`#version 300 es
16
+ */var ThreeLiveBundle=(()=>{var is=Object.defineProperty,Hm=Object.getOwnPropertyDescriptor,qm=Object.getOwnPropertyNames,Wm=Object.prototype.hasOwnProperty,Km=(e,t)=>{for(var r in t)is(e,r,{get:t[r],enumerable:!0})},Xm=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of qm(t))!Wm.call(e,n)&&n!==r&&is(e,n,{get:()=>t[n],enumerable:!(i=Hm(t,n))||i.enumerable});return e},Ym=e=>Xm(is({},"__esModule",{value:!0}),e),ns={};Km(ns,{AIVoiceSession:()=>Mh,AmbientLight:()=>Us,BoxGeometry:()=>Ds,BufferAttribute:()=>zt,BufferGeometry:()=>It,Camera:()=>js,CapsuleGeometry:()=>ac,CatmullRomCurve3:()=>_u,CircleGeometry:()=>sc,Clock:()=>Bu,Color:()=>jr,ConeGeometry:()=>gu,CubicBezierCurve3:()=>Mu,Curve3:()=>bi,CylinderGeometry:()=>ks,DataTexture:()=>Au,DirectionalLight:()=>$u,DodecahedronGeometry:()=>nc,EdgesGeometry:()=>cc,Euler:()=>$s,Float32BufferAttribute:()=>hu,Group:()=>Lu,HemisphereLight:()=>to,IKSolver:()=>a0,IMAGE_SYSTEM_PROMPT:()=>Uc,IcosahedronGeometry:()=>ic,InstancedMesh:()=>zs,InteractivityVM:()=>sf,LOD:()=>y0,LatheGeometry:()=>Fs,Light:()=>xi,LightShadow:()=>Vs,Line:()=>ki,LineBasicMaterial:()=>ma,LineCurve3:()=>vu,LineDashedMaterial:()=>oc,LineLoop:()=>hc,LineSegments:()=>fc,LodController:()=>El,MAX_BSP_DEPTH:()=>Jm,MAX_CSG_TRIANGLES:()=>Zm,MAX_INSTANCES_PER_MESH:()=>dn,MAX_SHADOW_LIGHTS:()=>Oa,MAX_SHAPE_POINTS:()=>t0,MAX_TEXT_GEOMETRY_CHARS:()=>e0,MAX_TSL_NODES:()=>j0,MAX_TSL_UNIFORMS:()=>G0,Material:()=>Nr,MathUtils:()=>cu,Matrix3:()=>lu,Matrix4:()=>Ii,Mesh:()=>si,MeshBasicMaterial:()=>Pu,MeshLambertMaterial:()=>Nu,MeshPhongMaterial:()=>Cu,MeshPhysicalMaterial:()=>Eu,MeshStandardMaterial:()=>pn,Object3D:()=>Gr,OctahedronGeometry:()=>rc,PART_STRIDE_BYTES:()=>Y1,PART_STRIDE_WORDS:()=>X1,PerspectiveCamera:()=>Iu,PlaneGeometry:()=>pu,PointLight:()=>Os,Points:()=>mc,PointsMaterial:()=>eo,PolyhedronFallbackGeometry:()=>_p,PolyhedronGeometry:()=>vi,QuadraticBezierCurve3:()=>wu,Quaternion:()=>aa,RawShaderMaterial:()=>Ju,RectAreaLight:()=>dc,RingGeometry:()=>Js,SCENE_PBR_WGSL:()=>sl,SCENE_PICK_WGSL:()=>tm,SCENE_SHADOW_WGSL:()=>em,SCENE_UNIFORM_BYTES:()=>K1,SHADOW_MAP_TEXTURE_UNIT:()=>Ef,Scene:()=>Gs,SceneQuotaValidator:()=>oi,ShaderMaterial:()=>Qs,SphereGeometry:()=>du,SpotLight:()=>pc,TEXTURE_PROMPT_SUFFIX:()=>Qc,THREE:()=>Fi,TSL_EXTENSION_NAME:()=>hn,TSL_TIME_PERIOD_SEC:()=>H0,TSL_WGSL_UNIFORM_BYTES:()=>V1,TetrahedronGeometry:()=>ec,Texture:()=>la,TextureLoader:()=>Tu,ThreeLiveElement:()=>wi,ThreeView:()=>ar,TorusGeometry:()=>yu,TorusKnotGeometry:()=>xu,TubeGeometry:()=>Su,Uint16BufferAttribute:()=>fu,Uint32BufferAttribute:()=>mu,VERTEX_STRIDE_BYTES:()=>Z1,VERTEX_STRIDE_FLOATS:()=>Q1,Vector2:()=>lr,Vector3:()=>Ze,Vector4:()=>ou,WebGLRenderer:()=>ku,WebGPUSceneAccelerator:()=>vm,WireframeGeometry:()=>uc,acquireSceneWebGPUDevice:()=>Yi,activateAR:()=>qh,aiPlugin:()=>Io,applyMeshoptFilter:()=>pf,authorScriptRunner:()=>ca,browserImageCodec:()=>Aa,buildImageMessages:()=>Hc,buildImageUserText:()=>Gc,buildSandboxWorkerSource:()=>Xs,buildSelectIndex:()=>oo,cadPlugin:()=>wl,clearAuthorWarnings:()=>Zu,compileFromImage:()=>Kc,compileTslToGlsl:()=>iu,compileTslToWgsl:()=>Xf,computeOutlineClipOffset:()=>M1,computeWorldSceneBounds:()=>Df,connectVoice:()=>To,contactShadowPlugin:()=>Vo,createAIChatProvider:()=>Nh,createAIImageProvider:()=>eh,createUSDZBlob:()=>Ps,createWebSpeechRecognizer:()=>_h,crossFadeTo:()=>kh,decimateGeometry:()=>g0,decodeMeshoptBuffer:()=>Mf,decodeMeshoptGLB:()=>Xo,defineModelViewer:()=>Np,describeEditResult:()=>No,describeSelection:()=>po,describeVoiceSelection:()=>Mn,detectImageMime:()=>Wc,doesMeshCastShadow:()=>En,doesMeshReceiveShadow:()=>el,editScene:()=>Lh,encodeMeshoptBuffer:()=>g1,environmentMapPlugin:()=>Yh,evaluateKawaseBloom:()=>w1,evaluateToneMapping:()=>T0,exportSceneToCanvas3D:()=>Hs,exportSceneToGLB:()=>qs,exportSceneToUSDZ:()=>Du,extractMaterialVariants:()=>jf,extractPrimitiveVariantMappings:()=>B1,extractScript:()=>Lo,fitDirectionalShadowMatrix:()=>kf,fitSpotShadowMatrix:()=>Zo,fmtShaderFloat:()=>ii,formatSpatialPriors:()=>bo,geminiLiveAdapter:()=>vh,generateUSDZ:()=>Ts,getARCapabilities:()=>Uo,getAllowClientScripts:()=>ju,getAuthorWarnings:()=>Qu,getBestARMode:()=>Od,getEnvironmentSH:()=>Kd,getInteractivityVM:()=>Ko,getLodController:()=>b0,getSandboxEngineSrc:()=>Ws,getSandboxIframeSrc:()=>Ou,getSelection:()=>br,getShadowMapStats:()=>R1,getWebGPUSceneAccelerator:()=>kn,glbToUSDZ:()=>As,hideSelectionChips:()=>Ca,hotspotPlugin:()=>Qh,ikPlugin:()=>Cl,imageRepairMessage:()=>qc,indexedDbTextureCache:()=>ah,installCadExtension:()=>as,installLodExtension:()=>Xn,installProceduralExtension:()=>ys,installTslExtension:()=>Ns,interactivityPlugin:()=>lf,isAllowedImageUrl:()=>Dr,isAllowedSandboxEngineUrl:()=>Di,isQuickLookSupported:()=>Uh,isSceneViewerSupported:()=>Oh,isWebXRSupported:()=>jh,keyframeAnimationPlugin:()=>Fh,lodPlugin:()=>Ll,matchSelection:()=>Ec,materialsPlugin:()=>uf,meshoptDecoder:()=>Yo,meshoptPlugin:()=>Sf,morphPlugin:()=>Bh,noopProxy:()=>gn,normalizeImageInput:()=>xo,normalizeRendererPreference:()=>lm,normalizeShadowMapsMode:()=>If,packUniformVec4:()=>Es,parseAnimations:()=>Dh,parseHexRgb:()=>Tf,parseLod:()=>gs,parseSafeGltfPointer:()=>Fa,parseSelectReply:()=>Bc,parseTexturePack:()=>ih,parseVoiceCommand:()=>Ic,postprocessingPlugin:()=>Cf,prepareAlbedo:()=>rh,proceduralPlugin:()=>Rl,quatFromUnitVectors:()=>us,realtimeAdapter:()=>xh,registerMaterialShader:()=>i1,remapClipDepthToZeroOne:()=>qa,resetSceneWebGPUDevice:()=>sg,resolveActiveShadowLights:()=>rl,resolveSceneRenderBackend:()=>ul,resolveSelection:()=>kc,resolveSelectionWithModel:()=>zc,sampleChannel:()=>_n,sceneSelectEntries:()=>va,sceneToCanvas3D:()=>ln,sceneToGLB:()=>ea,sceneToUSDZ:()=>ia,selectByVoice:()=>Ra,selectCamera:()=>yo,selectLodLevelIndex:()=>ds,selectMaterialVariant:()=>z1,selectMessages:()=>Fc,selectNamesByVoice:()=>Sh,sendInteractivityEvent:()=>of,serializeTexturePack:()=>nh,serializeTslToUsda:()=>nu,setAllowClientScripts:()=>pp,setEnvironmentSH:()=>Wh,setMaterialUniform:()=>Zf,setMorphTargetWeight:()=>Fd,setSandboxEngineSrc:()=>cp,setSandboxIframeSrc:()=>fp,setSceneWebGPUDeviceForTests:()=>ag,setSelectOnTap:()=>Eo,setSelection:()=>Er,shadowMapsPlugin:()=>Of,showSelectionChips:()=>yh,skinningPlugin:()=>zh,solveFABRIK:()=>Al,solveTwoBoneIK:()=>Sl,speakableName:()=>Po,startVoiceEdit:()=>Co,textureRequests:()=>Mo,threeAuthorPlugin:()=>bn,threeMicroPlugin:()=>Tp,toGLBData:()=>sn,toTrustedWorkerScriptURL:()=>Uu,tslPlugin:()=>Jf,tslSafeMod:()=>Ql,tslTypeArity:()=>sr,tslTypeFromArity:()=>Zl,undoEdit:()=>Rh,validateSandboxWorkerMessage:()=>Ys,validateTslGraph:()=>fn,variantsPlugin:()=>Gf,warnUnsupported:()=>ui,webgpuScenePlugin:()=>wm,webxrPlugin:()=>qf,writeSceneUniforms:()=>nl});function Qm(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 $={};return R.forEach((F,V)=>{$[String(V)]={node:F}}),m("flow/sequence",{flows:$})},C=(_,P,R)=>{let $=N(P);$!==null&&m(_,{...R?{configuration:R}:{},flows:{out:{node:$}}})};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 bl='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).',xl="Security Error: client-side scripts require allow-client-scripts opt-in.",Wn="__THREE_LIVE_REGISTRY__";function We(){let e=typeof globalThis<"u"?globalThis:{};if(!e[Wn]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,Wn,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[Wn]=t}}return e[Wn]}var Ct=We().plugins;function Ji(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 vl(){return We().plugins}var Zm=8192,Jm=2048,e0=128,t0=4096;function as(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,Ie=Number(ce)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[pe,xe]}),this.currentPoint.set(Ee,Ie),this.segments.push({type:"cubic",pts:[pe,xe,he,Ne,ge,Ae,Ee,Ie]}),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,Ie=Number(ce)||0,De=pe?1:0,Be=Number(xe)||0;this.segments.push({type:"arc",pts:[he,Ne,ge,Ae,Ee,Ie,De,Be]});let Fe=Math.cos(Be),Ve=Math.sin(Be),qe=ge*Math.cos(Ie),Ge=Ae*Math.sin(Ie);return this.currentPoint.set(he+qe*Fe-Ge*Ve,Ne+qe*Ve+Ge*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 Ie=Ee/z,De=1-Ie;X(De*De*pe+2*De*Ie*he+Ie*Ie*ge,De*De*xe+2*De*Ie*Ne+Ie*Ie*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],Ie=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*Ie)}}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,Ie=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(Ie),qe=Math.sin(Ie),Ge=Math.max(2,z);for(let ut=0;ut<=Ge;ut++){let it=ut/Ge,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,Ie=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=Ie*Fe-De*De;if(Math.abs(qe)<1e-12)return!1;let Ge=1/qe,ut=(Fe*Be-De*Ve)*Ge,it=(Ie*Ve-De*Be)*Ge;return ut>=-1e-7&&it>=-1e-7&&ut+it<=1.0000001}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 Ie=he[Ee],De=O.length;O.push(new r(Ie.x,Ie.y)),Ne.push(De),Ie.x>ge&&(ge=Ie.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),Ie=Ae.map((Fe,Ve)=>Ve).sort((Fe,Ve)=>+(Ae[Fe].x<Ne)-+(Ae[Ve].x<Ne)||Ee(Fe)-Ee(Ve)),De=Ie[0];for(let Fe of Ie){let Ve=Ae[Fe],qe=Ae[(Fe+ge-1)%ge],Ge=Ae[(Fe+1)%ge],ut=ce(Ve,Ge,he)>=0,it=ce(qe,Ve,he)>=0;if((ce(qe,Ve,Ge)>=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,Ie=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 Ge=D[qe];if(Ge.x>=Ie&&Ge.x<=De&&Ge.y>=Be&&Ge.y<=Fe&&S(Ge.x,Ge.y,Ne.x,Ne.y,ge.x,ge.y,Ae.x,Ae.y)&&(Ge.x-Ne.x)*(Ge.x-Ne.x)+(Ge.y-Ne.y)*(Ge.y-Ne.y)>=1e-12&&(Ge.x-ge.x)*(Ge.x-ge.x)+(Ge.y-ge.y)*(Ge.y-ge.y)>=1e-12&&(Ge.x-Ae.x)*(Ge.x-Ae.x)+(Ge.y-Ae.y)*(Ge.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,[Ie,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-Ie)/Be,(Ve.y-De)/Fe);for(let[Ve,qe,Ge]of Ae)pe.push(Ee+Ve,Ee+qe,Ee+Ge)}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 $(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,Ie=-pe,De=ge,Be=-Ne,Fe=Ee+De,Ve=Ie+Be,qe=Math.hypot(Fe,Ve);if(qe>1e-6){Fe/=qe,Ve/=qe;let Ge=Math.max(.35,Fe*Ee+Ve*Ie);z.push(new r(Fe/Ge,Ve/Ge))}else z.push(new r(Ee,Ie))}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=[],Ie=[],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 st=Pe.slice();w(st)>0&&st.reverse(),qe.push(st)}let{mergedIndices:Ge,allVertices:ut}=E(Ve,qe),it=N(Ge,ut),nt=[Ve,...qe],ct=[];for(let Pe of nt){let st=$(Pe);for(let vt of st)ct.push(vt)}let[Je,kt,Ft,ur]=_(ut);for(let[Pe,st]of[[-xe,-1],[se+xe,1]]){let vt=Ae.length/3;for(let _t=0;_t<ut.length;_t++){let Pt=ut[_t],Et=ct[_t]??new r(0,0),Xt=Pt.x+Et.x*Ne,jt=Pt.y+Et.y*Ne;Ae.push(Xt,jt,Pe),Ee.push(0,0,st),Ie.push((Xt-Je)/Ft,(jt-kt)/ur)}for(let[_t,Pt,Et]of it)De.push(vt+_t,vt+(st<0?Et:Pt),vt+(st<0?Pt:Et))}let wt=[];if(pe&&ge>0)for(let Pe=0;Pe<ge;Pe++){let st=Pe/ge*Math.PI/2;wt.push({z:-xe*Math.cos(st),expand:Ne+he*Math.sin(st)})}for(let Pe=0;Pe<=ce;Pe++){let st=Pe/ce;wt.push({z:st*se,expand:Ne+he})}if(pe&&ge>0)for(let Pe=1;Pe<=ge;Pe++){let st=Pe/ge*Math.PI/2;wt.push({z:se+xe*Math.sin(st),expand:Ne+he*Math.cos(st)})}let qt=0;for(let Pe of nt){let st=Pe.length;for(let vt=0;vt<wt.length-1;vt++){let _t=wt[vt],Pt=wt[vt+1];for(let Et=0;Et<st;Et++){let Xt=(Et+1)%st,jt=Pe[Et],Yt=Pe[Xt],er=ct[qt+Et],tr=ct[qt+Xt],cr=jt.x+er.x*_t.expand,wr=jt.y+er.y*_t.expand,mi=Yt.x+tr.x*_t.expand,rr=Yt.y+tr.y*_t.expand,ir=Yt.x+tr.x*Pt.expand,Pi=Yt.y+tr.y*Pt.expand,Jr=jt.x+er.x*Pt.expand,Mr=jt.y+er.y*Pt.expand,hr=mi-cr,Wt=rr-wr,fl=Jr-cr,Fn=Mr-wr,Ni=Pt.z-_t.z,Rr=Wt*Ni,$r=-hr*Ni,Ir=hr*Fn-Wt*fl,pi=Math.hypot(Rr,$r,Ir)||1;Rr/=pi,$r/=pi,Ir/=pi;let fr=Ae.length/3;Ae.push(cr,wr,_t.z,mi,rr,_t.z,ir,Pi,Pt.z,Jr,Mr,Pt.z),Ee.push(Rr,$r,Ir,Rr,$r,Ir,Rr,$r,Ir,Rr,$r,Ir);let Bn=Et/st,es=(Et+1)/st,_r=vt/(wt.length-1),mr=(vt+1)/(wt.length-1);Ie.push(Bn,_r,es,_r,es,mr,Bn,mr),De.push(fr,fr+1,fr+2,fr,fr+2,fr+3)}}qt+=st}}R(this,Ae,Ee,Ie,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 Ie=Ne*D.x+ge*D.y+Ae*D.z;return{vertices:W,nx:Ne,ny:ge,nz:Ae,w:Ie}}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,Ie=Ee<-ee?q:Ee>ee?G:k;he|=Ie,Ne.push(Ie)}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,Ge=Ne[Ve],ut=Ne[qe],it=X.vertices[Ve],nt=X.vertices[qe];if(Ge!==q&&ge.push(it),Ge!==G&&Ae.push(Ge!==q?V(it):it),(Ge|ut)===H){let ct=nt.x-it.x,Je=nt.y-it.y,kt=nt.z-it.z,Ft=W*ct+D*Je+z*kt,ur=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,ur)));ge.push(wt),Ae.push(V(wt))}}let{nx:Ie,ny:De,nz:Be,w:Fe}=X;ge.length>=3&&pe.push({vertices:ge,nx:Ie,ny:De,nz:Be,w:Fe}),Ae.length>=3&&xe.push({vertices:Ae,nx:Ie,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),Ie=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]*Ie+pe[8]*De+pe[12],it=pe[1]*Ee+pe[5]*Ie+pe[9]*De+pe[13],nt=pe[2]*Ee+pe[6]*Ie+pe[10]*De+pe[14];Ee=ut,Ie=it,De=nt;let ct=he[0]*Be+he[3]*Fe+he[6]*Ve,Je=he[1]*Be+he[4]*Fe+he[7]*Ve,kt=he[2]*Be+he[5]*Fe+he[8]*Ve,Ft=Math.hypot(ct,Je,kt)||1;Be=ct/Ft,Fe=Je/Ft,Ve=kt/Ft}let qe=X?X.getX(Ae):0,Ge=X?X.getY(Ae):0;return{x:Ee,y:Ie,z:De,nx:Be,ny:Fe,nz:Ve,u:qe,v:Ge}},ge=[];for(let Ae=0;Ae<ce;Ae++){let Ee=se?se[Ae*3]:Ae*3,Ie=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(Ie)]:[Ne(Ee),Ne(Ie),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 Ie=D[Ee].vertices;for(let De=0;De<Ie.length;De++){let Be=Ie[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 Ie=W[Ee],De=Ie.vertices,Be=1/0,Fe=1/0,Ve=1/0,qe=-1/0,Ge=-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>Ge&&(Ge=nt.y),nt.z>ut&&(ut=nt.z)}qe<O||Be>ce||Ge<X||Fe>pe||ut<se||Ve>xe?Ne.push(Ie):he.push(Ie)}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)),Ie=new a().makeTranslation(-W.position.x,-W.position.y,-W.position.z);pe=ge.multiply(Ee).multiply(Ie).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=[],Ie=[],De=[],Be=(qe,Ge,ut,it,nt,ct,Je)=>{let kt=ut-qe,Ft=it-Ge,ur=Math.hypot(kt,Ft),wt=1,qt=0;ur>1e-6&&(wt=kt/ur,qt=Ft/ur);let Pe=-qt*nt,st=wt*nt,vt=wt*nt*.6,_t=qt*nt*.6,Pt=qe-vt+Pe,Et=Ge-_t+st,Xt=qe-vt-Pe,jt=Ge-_t-st,Yt=ut+vt-Pe,er=it+_t-st,tr=ut+vt+Pe,cr=it+_t+st,wr=(mi,rr,ir,Pi,Jr,Mr,hr)=>{let Wt=Ae.length/3;Ae.push(mi[0],mi[1],mi[2],rr[0],rr[1],rr[2],ir[0],ir[1],ir[2],Pi[0],Pi[1],Pi[2]),Ee.push(Jr,Mr,hr,Jr,Mr,hr,Jr,Mr,hr,Jr,Mr,hr),Ie.push(0,0,1,0,1,1,0,1),De.push(Wt,Wt+1,Wt+2,Wt,Wt+2,Wt+3)};wr([Pt,Et,Je],[Xt,jt,Je],[Yt,er,Je],[tr,cr,Je],0,0,1),wr([Xt,jt,ct],[Pt,Et,ct],[tr,cr,ct],[Yt,er,ct],0,0,-1),wr([Pt,Et,ct],[Xt,jt,ct],[Xt,jt,Je],[Pt,Et,Je],-wt,-qt,0),wr([Yt,er,ct],[tr,cr,ct],[tr,cr,Je],[Yt,er,Je],wt,qt,0),wr([Xt,jt,ct],[Yt,er,ct],[Yt,er,Je],[Xt,jt,Je],qt,-wt,0),wr([tr,cr,ct],[Pt,Et,ct],[Pt,Et,Je],[tr,cr,Je],-qt,wt,0)},Fe=0,Ve=0;for(let qe=0;qe<O.length;qe++){let Ge=O[qe];if(Ge===`
17
+ `){Fe=0,Ve-=X*1.35;continue}if(Ge===" "||Ge===" "){Fe+=ge*(Ge===" "?.75:3);continue}if(Ge==="\r")continue;let ut=Ge.toUpperCase(),it=Ge!==ut&&Ge>="a"&&Ge<="z",nt=_e[ut]??_e["?"],ct=it?X*.76:X,Je=it?Ne*.88:Ne;for(let kt of nt)for(let Ft=0;Ft<kt.length-1;Ft++){let ur=kt[Ft],wt=kt[Ft+1];Be(Fe+ur[0]*Je,Ve+ur[1]*ct,Fe+wt[0]*Je,Ve+wt[1]*ct,he,-xe*.5,xe*.5)}Fe+=it?ge*.88:ge}R(this,Ae,Ee,Ie,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 wl={name:"cad",onRegister(){Ji(as);let e=We(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&as(t,e)}};function ot(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function ss(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 r0(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 en(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 tn(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 Qt(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 os(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,$=m*y-p*x,F=h*y-p*v,V=A*F-b*$+w*R+S*P-E*_+N*C;return V?(V=1/V,e[0]=(o*F-l*$+c*R)*V,e[1]=(n*$-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*$-o*P+c*C)*V,e[9]=(i*P-r*$-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 Ml(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 i0(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,$=e-s,F=t-o,V=r-l,Y=R*($*N+F*C+V*_);if(Y<-v||Y>1+v)return!1;let J=F*b-V*A,re=V*y-$*b,Q=$*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 rn(e,t){let r=Array.isArray(e?.nodes)?e.nodes.length:0,i=[];for(let f=0;f<r;f++)i.push(ot());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=ot();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];tn(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 ls(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,$=Math.abs(v-w)+1e-5,F=Math.max($,v+w-1e-5),V=Math.max($,Math.min(F,P>1e-6?P:$)),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],$=p[P+1][1]-p[P][1],F=p[P+1][2]-p[P][2],V=Math.hypot(R,$,F);g.push(V),v+=V,x.push(V>1e-6?[R/V,$/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 $=g[R];p[R+1]=[p[R][0]+P[0]*$,p[R][1]+P[1]*$,p[R][2]+P[2]*$]}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 $=(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]=$(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]=$(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],$=p[P+1][1]-p[P][1],F=p[P+1][2]-p[P][2],V=Math.hypot(R,$,F),Y=V>1e-6?[R/V,$/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 Ei=ls(),_l=Ei.clampNum,n0=Ei.parseIKTrait,us=Ei.quatFromUnitVectors,Sl=Ei.solveTwoBoneIK,Al=Ei.solveFABRIK,a0=Ei.IKSolver;function cs(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 s0(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 o0(e,t,r,i,n){let a=_l(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 l0(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return os(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 hs(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 fs(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return cs(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 l0(r,[a[0],a[1],a[2]])}return null}function ms(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 u0(e){return[-e[0],-e[1],-e[2],e[3]]}function ps(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 c0(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 ps([r*l,i*l,n*l,Math.cos(s*t)])}function h0(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 ps(g)}function f0(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 Kn(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 Tl(e){e?.normalMatrix&&e?.transform&&Qt(e.normalMatrix,e.transform)}var Pl=new WeakMap;function m0(e){let t=Pl.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)}),Pl.set(e,t)),t}function p0(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=m0(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 $ of Array.isArray(R?.children)?R.children:[])typeof $=="number"&&p.push($)}let g=l[c],x=g>=0&&e.worldMatrices?.[g]?.length===16?Float32Array.from(e.worldMatrices[g]):ot(),v=new Map,y=()=>{let _=(P,R)=>{let $=m.get(P);if(!$)return;let F=ot();tn(F,$.r,$.t,$.s);let V=ot();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 fs(_,r,e)},S=w(t.target);if(!S)return!0;let E=t.pole?w(t.pole)??void 0:void 0,N=Nl(b,t,S,E),C=_l(t.weight,0,1,1);for(let _=0;_<o.length-1;_++){let P=Kn(A(o[_]),A(o[_+1])),R=Kn(N[_],N[_+1]);if(!P||!R)continue;let $=c0(us(P,R),C),F=o[_],V=l[F],Y=V===g||V<0?x:v.get(V)??x,J=h0(Y),re=m.get(F);re.r=ps(ms(u0(J),ms($,ms(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),Tl(_))}return!0}function Nl(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let n=Sl(e[0],e[1],e[2],r,i);return[e[0],n.midPos,n.effectorPos]}return Al(e,r,t.iterations,t.tolerance).positions}function d0(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=Kn([0,0,0],i[a]),c=Kn(r[a],r[a+1]);!s||s.length<16||!o||o.length<16||!l||!c||(f0(s,o,us(l,c)),Tl(t[a]))}}var Cl={name:"ik",onRegister(){let e=We();Ji(ls),ls(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=n0(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(p0(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||hs(i,a.root),o||hs(i,a.effector),a.mid&&!l&&hs(i,a.mid),!s||!o)continue;let c=fs(a.target,r,e);if(!c)continue;let f=a.pole?fs(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(cs),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=[cs(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=Nl(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=o0(y,S,E,x[b-1],a.weight);s0(m[b],N),y=N,A.push(N)}d0(i,m,A)}}};function Xn(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),$=Math.max(1e-5,_-E),F=Math.max(1e-5,P-N),V=Math.max(R,$,F),Y=te=>{let Z=Math.max(1,Math.round(R/V*te)),ae=Math.max(1,Math.round($/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)/$*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 nn=Xn(),g0=nn.decimateGeometry,ds=nn.selectLodLevelIndex,gs=nn.parseLod,Dg=nn.materializeLodGeometry,y0=nn.LOD,an=new WeakMap;function b0(e){return e&&typeof e=="object"?an.get(e):void 0}var El=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=gs(a);if(!o&&s.length>0&&(o=gs({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=ds(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=ds(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})}}},Ll={name:"lod",onRegister(){Ji(Xn);let e=We(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);Xn(t,e)},onLoadModel(e,t){!e||typeof e!="object"||an.set(e,new El(e,t))},onUpdate(e){let t=an.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=an.get(e);n&&n.update(i)},onDestroy(e,t){t&&typeof t=="object"&&an.delete(t)}};function ys(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,I=Number(T?.y)||0,B=Number(T?.z)||0,U=T?.w===void 0?1:Number(T.w)||0,j=2*(I*M-B*d),K=2*(B*u-L*M),ue=2*(L*d-I*u);return this.set(u+U*j+(I*ue-B*K),d+U*K+(B*j-L*ue),M+U*ue+(L*K-I*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,I=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-I),this.max.set(B+M,U+L,j+I),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,I=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,I!==0?(u.z-this.min.z)/I: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,I=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<=-I&&U>=-I}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,I=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?I: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,I=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,I),B.multiplyMatrices(le.matrixWorld,I),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,I=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(I.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 I=0;I<T.count;I++){let B=T.getX(I),U=T.getY(I),j=T.getZ(I);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 I=p.charCodeAt(L);if(I===61)break;let B=I<128?g[I]:-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 I=L[1],B=L[2].replace(/\//g," ").split(/[\s,]+/).filter(Boolean);if(B.length<3)return u;if(I.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,I=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,I);if(Array.isArray(Oe)&&typeof Oe[0]=="string")return{uri:Oe[0],avgColor:[Oe[1],Oe[2],Oe[3],Oe[4]]}}let B=u>I||d>I?I/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,$e=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),bt=ze?Xe+1:Math.max(rt+1,Math.floor((Xe+1)*d/j));for(let pt=0;pt<U;pt++){let lt=0,xt=0,At=0,dt=0;if(ze){let gt=(rt*u+pt)*4;lt=T[gt]|0,xt=T[gt+1]|0,At=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 Ut=rt;Ut<bt&&Ut<d;Ut++)for(let Lt=gt;Lt<Bt&&Lt<u;Lt++){let Kt=(Ut*u+Lt)*4;lt+=T[Kt]|0,xt+=T[Kt+1]|0,At+=T[Kt+2]|0,dt+=T[Kt+3]|0,Nt++}Nt>1&&(lt=lt/Nt+.5|0,xt=xt/Nt+.5|0,At=At/Nt+.5|0,dt=dt/Nt+.5|0)}ye[ve++]=lt,we+=lt,Te+=we,ye[ve++]=xt,we+=xt,Te+=we,ye[ve++]=At,we+=At,Te+=we,ye[ve++]=dt,we+=dt,Te+=we,Me+=L?lt/255:A[lt],be+=L?xt/255:A[xt],Ce+=L?At/255:A[At],$e+=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,$e/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 I=L/255;if(I<=d[0].o){let B=d[0].c;u[L]=P(B[0],B[1],B[2],B[3])}else if(I>=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&&I>d[M+1].o;)M++;let B=d[M],U=d[M+1],j=U.o-B.o,K=j>1e-9?(I-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},$=(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 I=L<=0?0:L>=1?255:L*255+.5|0;return M[I]};class F{constructor(u,d,M,L,I,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(I)||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,I)=>L.o-I.o||L.i-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 I=(L||"repeat").toLowerCase();this.rx=I==="repeat"||I==="repeat-x",this.ry=I==="repeat"||I==="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 I=(L*T.w+M)*4;return P(T.d[I],T.d[I+1],T.d[I+2],T.d[I+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),I=(T-32)*5;for(let U=0;U<5;U++){let j=x[I+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]),I=M[2].toLowerCase();return I==="pt"?L*=4/3:(I==="em"||I==="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 I=1/L;return[M[3]*u*I,-M[2]*d*I,(-M[3]*M[4]+M[2]*M[5])*I,-M[1]*u*I,M[0]*d*I,(M[1]*M[4]-M[0]*M[5])*I]},H=(T,u,d)=>{let[M,L,I,B,U,j]=q(T);return[M*u+L*d+I,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 I=u?u._g:0;if(I===1||I===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=I===1?$(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 I=T.canvas._bw,B=T.canvas._bh;if(d<0||d>=I||M<0||M>=B)return;let U=M*I+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,I=T.canvas._bh,B=[],U=I,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,$e]=ve[(Te+1)%we];if(be===$e)continue;let ze=Math.min(be,$e),Ue=Math.max(be,$e);B.push([ze,Ue,$e>be?Me:Ce,($e>be?Ce-Me:Me-Ce)/(Ue-ze),$e>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(I-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,I)=>{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,I?T.strokeStyle:T.fillStyle),Ce=te(T),[$e,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,bt=1/ue;for(let pt=0;pt<U.length;pt++){let lt=J(U[pt].codePointAt(0)??32);if(lt===32)continue;let xt=we+pt*oe*ye,At=Q(lt,K),dt=G(T,xt,Te),gt=G(T,xt+Xe,Te),Bt=G(T,xt+Xe,Te+ue),Nt=G(T,xt,Te+ue),Ut=Math.max(0,Math.floor(Math.min(dt[0],gt[0],Bt[0],Nt[0]))),Lt=Math.min(Qe-1,Math.ceil(Math.max(dt[0],gt[0],Bt[0],Nt[0]))),Kt=Math.max(0,Math.floor(Math.min(dt[1],gt[1],Bt[1],Nt[1]))),nr=Math.min(tt-1,Math.ceil(Math.max(dt[1],gt[1],Bt[1],Nt[1])));for(let Ar=Kt;Ar<=nr;Ar++){let pr=Ar+.5;for(let ei=Ut;ei<=Lt;ei++){let Zi=Ar*Qe+ei;if(Oe[Zi])continue;let Ci=ei+.5,Vn=$e*Ci+ze*pr+Ue,Un=He*Ci+Ke*pr+et,ti=(Vn-xt)*rt,ri=(Un-Te)*bt;if(ti<0||ti>=1||ri<0||ri>=1)continue;let dr=Math.min(9,ti*10|0),gr=Math.min(13,ri*14|0);At[gr*10+dr]===1&&(I&&dr>0&&dr<9&&gr>0&&gr<13&&At[gr*10+dr-1]&&At[gr*10+dr+1]&&At[(gr-1)*10+dr]&&At[(gr+1)*10+dr]||(Oe[Zi]=1,ie(T,Ce,ei,Ar,be(Ci,pr))))}}}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,I,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(I??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,I,B){if(!Number.isFinite(u+d+M+L+I+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]*I+U[2]*B+U[4],U[1]*I+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,I,B){return new F(!0,u,d,M,L,I,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,I){if(!Number.isFinite(u+d+M+L))return;M<0&&(u+=M,M=-M),L<0&&(d+=L,L=-L);let B=Array.isArray(I)?I:I!==void 0?[I]:[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 I=this._cur.pts,[B,U]=I[I.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,I,B){if(!Number.isFinite(u+d+M+L+I+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,I,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,$e=Me*Me;Z(this,Ce*be*j+3*Ce*Me*ue+3*be*$e*oe+$e*Me*ye,Ce*be*K+3*Ce*Me*le+3*be*$e*fe+$e*Me*ve)}}ellipse(u,d,M,L,I=0,B=0,U=Math.PI*2,j=!1){if(!Number.isFinite(u+d+M+L+I+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(I),ye=Math.sin(I),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),$e=u+be*fe-Ce*ye,ze=d+be*ye+Ce*fe;Te===0&&(!this._cur||this._cur.pts.length===0)?this.moveTo($e,ze):this.lineTo($e,ze)}}arc(u,d,M,L,I,B=!1){this.ellipse(u,d,M,M,0,L,I,B)}arcTo(u,d,M,L,I){if(!Number.isFinite(u+d+M+L+I))return;let B=Math.max(0,I);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,$e=ve/Te,ze=Me*$e-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*$e)))*.5,He=B/Math.tan(Ue),Ke=Me+Ce,et=be+$e,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+$e*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,I)=>ie(this,M,L,I,d(L+.5,I+.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",(I,B)=>{L[B*d+I]=1}),this._clip)for(let I=0;I<L.length;I++)L[I]&=this._clip[I];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,I=Math.max(.5,L*d*.5),B=I*I,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,$e,ze,Ue)=>{let He=Me,Ke=be,et=Ce,Qe=$e,tt=et-He,Oe=Qe-Ke,Xe=Math.hypot(tt,Oe);if(U==="square"&&Xe>1e-6){let dt=tt/Xe*I,gt=Oe/Xe*I;ze&&(He-=dt,Ke-=gt),Ue&&(et+=dt,Qe+=gt),tt=et-He,Oe=Qe-Ke}let rt=tt*tt+Oe*Oe,bt=I+.5,pt=Math.max(0,Math.floor(Math.min(He,et)-bt)),lt=Math.min(j-1,Math.ceil(Math.max(He,et)+bt)),xt=Math.max(0,Math.floor(Math.min(Ke,Qe)-bt)),At=Math.min(K-1,Math.ceil(Math.max(Ke,Qe)+bt));for(let dt=xt;dt<=At;dt++){let gt=dt+.5;for(let Bt=pt;Bt<=lt;Bt++){let Nt=dt*j+Bt;if(oe[Nt])continue;let Ut=Bt+.5,Lt=rt>1e-9?((Ut-He)*tt+(gt-Ke)*Oe)/rt:0;if(U==="butt"&&(Lt<0&&ze||Lt>1&&Ue))continue;Lt=Math.max(0,Math.min(1,Lt));let Kt=He+Lt*tt,nr=Ke+Lt*Oe;(Ut-Kt)*(Ut-Kt)+(gt-nr)*(gt-nr)<=B&&(oe[Nt]=1,ie(this,le,Bt,dt,ue(Ut,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 $e=Me.closed?Ce:Ce-1,ze=fe>1e-6?(Te*d%fe+fe)%fe:0;for(let Ue=0;Ue<$e;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===$e-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 bt=Math.min(tt-Oe,rt<ye.length?Math.max(.25,ye[rt]-Xe):tt-Oe);if(rt%2===0){let pt=Oe/tt,lt=(Oe+bt)/tt;ve(He+(et-He)*pt,Ke+(Qe-Ke)*pt,He+(et-He)*lt,Ke+(Qe-Ke)*lt,!0,!0)}Oe+=bt,ze=(ze+bt)%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 I=this._m;if(I[0]===1&&I[1]===0&&I[2]===0&&I[3]===1&&I[4]===0&&I[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 I=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=I(0,0),Ce=be>>>24;if(B===0&&Ce>=255||B===1){let $e=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($e,we*j,(Te+1)*j);else for(let He=we;He<=Te;He++)Ue.fill($e,He*j+ye,He*j+ve+1);this.canvas._ver++;return}}let Me=be=>{let Ce=be+.5;for(let $e=ye;$e<=ve;$e++)ie(this,B,$e,be,I($e+.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,I(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 I=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=I,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))),I=Math.max(1,Math.min(f,Math.floor(Math.abs(Number(M?u.height:d))||1)));return{data:new Uint8ClampedArray(L*I*4),width:L,height:I}}getImageData(u,d,M,L){let I=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&&(I+=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=I+Me;if(be<0||be>=this.canvas.width)continue;let Ce=(Te*ue+Math.min(ue-1,Math.floor((be+.5)*oe)))*4,$e=(ve*U+Me)*4;K[$e]=ye[Ce],K[$e+1]=ye[Ce+1],K[$e+2]=ye[Ce+2],K[$e+3]=ye[Ce+3]}}return{data:K,width:U,height:j}}putImageData(u,d,M,L=0,I=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(I)||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,$e=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($e-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 bt=et;bt<=Qe;bt++){let pt=Math.floor((bt+.5)*ze)-Me;if(pt<ye||pt>=we)continue;let lt=(rt*j+pt)*4,xt=(Xe*Ce+bt)*4;He[xt]=Ke[lt]|0,He[xt+1]=Ke[lt+1]|0,He[xt+2]=Ke[lt+2]|0,He[xt+3]=Ke[lt+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,I=Number(u?.height)>0?Number(u.height):M.height,B=0,U=0,j=L,K=I,ue=0,le=0,oe=L,fe=I;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,$e,ze,Ue]=q(this),He=1/oe,Ke=1/fe,et=M.width/L,Qe=M.height/I;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,bt=Me*Xe+be*rt+Ce,pt=$e*Xe+ze*rt+Ue,lt=(bt-ue)*He,xt=(pt-le)*Ke;if(lt<0||lt>=1||xt<0||xt>=1)return;let At=Math.floor((B+lt*j)*et),dt=Math.floor((U+xt*K)*Qe);if(At<0||At>=M.width||dt<0||dt>=M.height)return;let gt=(dt*M.width+At)*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 I=d.getContext("2d")?.getImageData?.(0,0,M,L);if(I?.data)return{data:I.data instanceof Uint8ClampedArray?I.data:new Uint8ClampedArray(I.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,I=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(I)||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,I=L<8?u:d,B=L<4?d:L===12||L===14?u:M;return((L&1)===0?I:-I)+((L&2)===0?B:-B)};class pe{noise(u,d,M=0){let L=Number(u),I=Number(d),B=Number(M);if(!Number.isFinite(L)||!Number.isFinite(I)||!Number.isFinite(B))return 0;let U=Math.floor(L),j=Math.floor(I),K=Math.floor(B),ue=U&255,le=j&255,oe=K&255;L-=U,I-=j,B-=K;let fe=L-1,ye=I-1,ve=B-1,we=X(L),Te=X(I),Me=X(B),be=O[ue]+le,Ce=O[be]+oe,$e=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,I,B),ce(O[Ue],fe,I,B)),se(we,ce(O[$e],L,ye,B),ce(O[He],fe,ye,B))),se(Te,se(we,ce(O[Ce+1],L,I,ve),ce(O[Ue+1],fe,I,ve)),se(we,ce(O[$e+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,Ie=(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 Ge{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),I=new Uint8Array(512);for(let B=0;B<512;B++){let U=M[B&255];L[B]=U,I[B]=U%12}this.p=M,this.perm=L,this.permMod12=I}noise(u,d){let M=Number(u),L=Number(d);if(!Number.isFinite(M)||!Number.isFinite(L))return 0;let I=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,$e=j&255,ze=K&255,Ue=B[$e+I[ze]]*3,He=B[$e+ve+I[ze+we]]*3,Ke=B[$e+1+I[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),I=Number(d),B=Number(M);if(!Number.isFinite(L)||!Number.isFinite(I)||!Number.isFinite(B))return 0;let U=this.perm,j=this.permMod12,K=(L+I+B)*Ae,ue=Math.floor(L+K),le=Math.floor(I+K),oe=Math.floor(B+K),fe=(ue+le+oe)*Ee,ye=L-(ue-fe),ve=I-(le-fe),we=B-(oe-fe),Te,Me,be,Ce,$e,ze;ye>=ve?ve>=we?(Te=1,Me=0,be=0,Ce=1,$e=1,ze=0):ye>=we?(Te=1,Me=0,be=0,Ce=1,$e=0,ze=1):(Te=0,Me=0,be=1,Ce=1,$e=0,ze=1):ve<we?(Te=0,Me=0,be=1,Ce=0,$e=1,ze=1):ye<we?(Te=0,Me=1,be=0,Ce=0,$e=1,ze=1):(Te=0,Me=1,be=0,Ce=1,$e=1,ze=0);let Ue=ye-Te+Ee,He=ve-Me+Ee,Ke=we-be+Ee,et=ye-Ce+2*Ee,Qe=ve-$e+2*Ee,tt=we-ze+2*Ee,Oe=ye-1+3*Ee,Xe=ve-1+3*Ee,rt=we-1+3*Ee,bt=ue&255,pt=le&255,lt=oe&255,xt=j[bt+U[pt+U[lt]]]*3,At=j[bt+Te+U[pt+Me+U[lt+be]]]*3,dt=j[bt+Ce+U[pt+$e+U[lt+ze]]]*3,gt=j[bt+1+U[pt+1+U[lt+1]]]*3,Bt=0,Nt=.6-ye*ye-ve*ve-we*we;Nt>=0&&(Nt*=Nt,Bt=Nt*Nt*Fe(xt,ye,ve,we));let Ut=0,Lt=.6-Ue*Ue-He*He-Ke*Ke;Lt>=0&&(Lt*=Lt,Ut=Lt*Lt*Fe(At,Ue,He,Ke));let Kt=0,nr=.6-et*et-Qe*Qe-tt*tt;nr>=0&&(nr*=nr,Kt=nr*nr*Fe(dt,et,Qe,tt));let Ar=0,pr=.6-Oe*Oe-Xe*Xe-rt*rt;return pr>=0&&(pr*=pr,Ar=pr*pr*Fe(gt,Oe,Xe,rt)),32*(Bt+Ut+Kt+Ar)}noise4d(u,d,M,L){let I=Number(u),B=Number(d),U=Number(M),j=Number(L);if(!Number.isFinite(I)||!Number.isFinite(B)||!Number.isFinite(U)||!Number.isFinite(j))return 0;let K=this.perm,ue=(I+B+U+j)*Ie,le=Math.floor(I+ue),oe=Math.floor(B+ue),fe=Math.floor(U+ue),ye=Math.floor(j+ue),ve=(le+oe+fe+ye)*De,we=I-(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),$e=(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=$e>=3?1:0,et=ze>=3?1:0,Qe=Ue>=3?1:0,tt=Ce>=2?1:0,Oe=$e>=2?1:0,Xe=ze>=2?1:0,rt=Ue>=2?1:0,bt=Ce>=1?1:0,pt=$e>=1?1:0,lt=ze>=1?1:0,xt=Ue>=1?1:0,At=we-He+De,dt=Te-Ke+De,gt=Me-et+De,Bt=be-Qe+De,Nt=we-tt+2*De,Ut=Te-Oe+2*De,Lt=Me-Xe+2*De,Kt=be-rt+2*De,nr=we-bt+3*De,Ar=Te-pt+3*De,pr=Me-lt+3*De,ei=be-xt+3*De,Zi=we-1+4*De,Ci=Te-1+4*De,Vn=Me-1+4*De,Un=be-1+4*De,ti=le&255,ri=oe&255,dr=fe&255,gr=ye&255,Eg=(K[ti+K[ri+K[dr+K[gr]]]]&31)*4,Lg=(K[ti+He+K[ri+Ke+K[dr+et+K[gr+Qe]]]]&31)*4,Rg=(K[ti+tt+K[ri+Oe+K[dr+Xe+K[gr+rt]]]]&31)*4,$g=(K[ti+bt+K[ri+pt+K[dr+lt+K[gr+xt]]]]&31)*4,Ig=(K[ti+1+K[ri+1+K[dr+1+K[gr+1]]]]&31)*4,Em=0,On=.6-we*we-Te*Te-Me*Me-be*be;On>=0&&(On*=On,Em=On*On*Ve(Eg,we,Te,Me,be));let Lm=0,jn=.6-At*At-dt*dt-gt*gt-Bt*Bt;jn>=0&&(jn*=jn,Lm=jn*jn*Ve(Lg,At,dt,gt,Bt));let Rm=0,Gn=.6-Nt*Nt-Ut*Ut-Lt*Lt-Kt*Kt;Gn>=0&&(Gn*=Gn,Rm=Gn*Gn*Ve(Rg,Nt,Ut,Lt,Kt));let $m=0,Hn=.6-nr*nr-Ar*Ar-pr*pr-ei*ei;Hn>=0&&(Hn*=Hn,$m=Hn*Hn*Ve($g,nr,Ar,pr,ei));let Im=0,qn=.6-Zi*Zi-Ci*Ci-Vn*Vn-Un*Un;return qn>=0&&(qn*=qn,Im=qn*qn*Ve(Ig,Zi,Ci,Vn,Un)),27*(Em+Lm+Rm+$m+Im)}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(Ge.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,I=Number(d?.width??u.width)|0,B=Number(d?.height??u.height)|0;if(!L||!(I>0&&B>0)||!L.length)return null;let U=I*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:I,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)),I=Math.min(T.h-1,Math.max(0,d*T.h|0)),B=T.flipY?T.h-1-I:I,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 I=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(I*B*4);for(let j=0;j<B;j++){let K=(j+.5)/B;for(let ue=0;ue<I;ue++){let le=(ue+.5)/I,oe=(j*I+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,I,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,I=Math.min(128,M.w),B=Math.min(128,M.h),U=new Uint8ClampedArray(I*B*4),j=(K,ue)=>it(M,((K%I+I)%I+.5)/I,((ue%B+B)%B+.5)/B,0)/255;for(let K=0;K<B;K++)for(let ue=0;ue<I;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*I+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,I,B,!1,!0,128).uri,d=1}}return{mrUri:T,normUri:u,normScale:d}});let ct=0,Je=e.Vector2,kt=e.PlaneGeometry,Ft=e.Mesh,ur=e.Material;class wt extends ur{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 qt extends Ft{constructor(u){super(new kt(1,1),u instanceof ur?u:new wt(u||{})),this.isSprite=!0,this.center=new Je(.5,.5),this.userData={xr:{billboard:"spherical"}}}_cloneCustom(){let u=new qt(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),I=Number.isFinite(L)?L:0,B=`${d},${M},${I}`;if(this._bakedKey!==B&&(this._bakedKey!==void 0||d!==.5||M!==.5||I!==0)){let U=new kt(1,1),j=U.attributes.position?.array,K=.5-d,ue=.5-M,le=Math.cos(I),oe=Math.sin(I);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(qt.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 I=Number(L)||0,B=d?.x||0,U=d?.y||0;return this.set(B+((M?.x||0)-B)*I,U+((M?.y||0)-U)*I)}),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},st=T=>Math.max(0,Math.min(1,Pe(T,0))),vt=T=>new Je(Pe(T?.x),Pe(T?.y));class _t{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,I=this.getPoint(0);for(let B=1;B<=d;B++){let U=this.getPoint(B/d);L+=Math.hypot(Pe(U.x)-Pe(I.x),Pe(U.y)-Pe(I.y),Pe(U.z)-Pe(I.z)),M.push(L),I=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,I=M[L-1]||0;if(I<=0||L<2)return st(u);let B=d!==void 0&&Number.isFinite(Number(d))?Math.max(0,Math.min(I,Number(d))):st(u)*I,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]??I)-ue;return(K+(le>1e-12?(B-ue)/le:0))/(L-1)}getTangent(u,d){let M=st(u),L=this.getPoint(Math.max(0,M-1e-4)),I=this.getPoint(Math.min(1,M+1e-4)),B=Pe(I.x)-Pe(L.x),U=Pe(I.y)-Pe(L.y);if("z"in L||d?.isVector3){let K=Pe(I.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 I=d[L];Array.isArray(I)?M[L]=I.map(B=>B?.clone?B.clone():B&&typeof B=="object"&&"x"in B?vt(B):B):I?.clone?M[L]=I.clone():I&&typeof I=="object"&&"x"in I?M[L]=vt(I):M[L]=I}return this}}class Pt extends _t{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),I=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,I+(Pe(this.v2.y)-I)*M)}getPointAt(u,d=new Je){return this.getPoint(st(u),d)}}class Et extends _t{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=st(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 _t{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=st(u),L=1-M,I=L*L,B=M*M;return d.set(I*L*Pe(this.v0.x)+3*I*M*Pe(this.v1.x)+3*L*B*Pe(this.v2.x)+B*M*Pe(this.v3.x),I*L*Pe(this.v0.y)+3*I*M*Pe(this.v1.y)+3*L*B*Pe(this.v2.y)+B*M*Pe(this.v3.y))}}class jt extends _t{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 I=(L-1)*st(u),B=Math.floor(I),U=I-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 _t{constructor(u=0,d=0,M=1,L=1,I=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(I,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),I=Pe(this.aEndAngle,M)-L;Math.abs(I)>=1e-9?(I=(I%M+M)%M,I<1e-9&&(I=M),this.aClockwise&&(I=I===M?-M:I-M)):I=0;let B=L+st(u)*I,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 er extends Yt{constructor(u=0,d=0,M=1,L=0,I=Math.PI*2,B=!1){super(u,d,M,M,L,I,B,0),this.type="ArcCurve",this.isArcCurve=!0}}class tr extends _t{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 I=M.getPoints(32);for(let B=1;B<I.length;B++)L+=Math.hypot(Pe(I[B]?.x)-Pe(I[B-1]?.x),Pe(I[B]?.y)-Pe(I[B-1]?.y),Pe(I[B]?.z)-Pe(I[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 I=st(u)*L;for(let B=0;B<M.length;B++)if(I<=M[B]||B===M.length-1){let U=B>0?M[B-1]:0,j=M[B]-U,K=j>1e-12?(I-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 I of this.curves){let B=I?.isEllipseCurve?d*2:I?.isLineCurve||I instanceof(e.LineCurve3||Function)?1:I?.isSplineCurve&&Array.isArray(I.points)?d*Math.max(1,I.points.length):d;for(let U of I.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 I=M[0];Math.hypot(Pe(L.x)-Pe(I.x),Pe(L.y)-Pe(I.y),Pe(L.z)-Pe(I.z))>1e-6&&M.push(I.clone?I.clone():I)}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 cr=e.BufferAttribute,wr=e.Object3D,mi=e.Line,rr=e.LineSegments,ir=e.LineBasicMaterial,Pi=e.MeshBasicMaterial,Jr=e.ConeGeometry,Mr=e.Color,hr=(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},Wt=T=>{let u=new n;return u.setAttribute("position",new cr(new Float32Array(T),3)),u.__isSegmentPairs=!0,u},fl=[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,I)=>{if(!Number.isFinite(T+u+d+M+L+I)||M<T||L<u||I<d)return new n;let B=[];for(let U of fl)B.push(U&1?M:T,U&2?L:u,U&4?I:d);return Wt(B)};class Ni extends rr{constructor(u=10,d=10,M=4473924,L=8947848){let I=Math.max(1e-4,Math.abs(Pe(u,10))),B=Math.max(1,Math.min(256,Math.floor(Pe(d,10)))),U=new Mr(M??4473924),j=new Mr(L??8947848),K=I*.5,ue=I/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(Wt(oe.length?oe:fe),new ir({color:oe.length?j:U})),this.type="GridHelper",this.isGridHelper=!0,this._size=I,this._divisions=B,this._internalKids=0,fe.length&&oe.length){let ye=new rr(Wt(fe),new ir({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 Ni(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,hr(d,this,this._internalKids,u)}dispose(){}}class Rr extends rr{constructor(u=1){let d=Math.max(1e-4,Math.abs(Pe(u,1)));super(Wt([0,0,0,d,0,0]),new ir({color:16724736})),this.type="AxesHelper",this.isAxesHelper=!0,this._size=d,this._yAxis=new rr(Wt([0,0,0,0,d,0]),new ir({color:3407616})),this._zAxis=new rr(Wt([0,0,0,0,0,d]),new ir({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 Rr(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,hr(d,this,2,u)}dispose(){}}class $r extends wr{constructor(u=new r(0,0,1),d=new r(0,0,0),M=1,L=16776960,I,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 cr(new Float32Array([0,0,0,0,1,0]),3)),this.line=new mi(U,new ir({color:L})),this.cone=new Ft(new Jr(.5,1,8).translate(0,-.5,0),new Pi({color:L})),this.add(this.line),this.add(this.cone),this.setDirection(u).setLength(M,I,B)}setDirection(u){let d=Pe(u?.x,0),M=Pe(u?.y,0),L=Pe(u?.z,1),I=Math.hypot(d,M,L),B=I>1e-9?d/I:0,U=I>1e-9?M/I:1,j=I>1e-9?L/I: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))),I=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*I;return this.line.scale.set(1,Math.max(1e-4,L-I),1),this.line.updateMatrix?.(),this.cone.scale.set(B,I,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 $r;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,hr(d,this,2,u)}dispose(){}}class Ir extends rr{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 ir({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 Ir(this.box.clone(),this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,hr(d,this,0,u)}dispose(){}}class pi extends rr{constructor(u,d=16776960){super(new n,new ir({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 pi(this.object,this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,hr(d,this,0,u)}dispose(){}}for(let T of[_t,Pt,Et,Xt,jt,Yt,er,tr,Ni,Rr,$r,Ir,pi])Object.freeze(T.prototype);let fr=["checkerboard","grid","wood","marble","brushedMetal","carbonFiber","concrete","brick","fabric","leather","rust"],Bn=[[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]],es=(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},_r=(T,u,d)=>es(T,u,d)/4294967296,mr=(T,u)=>(T%u+u)%u,Mm=(T,u,d,M,L)=>{let I=Math.floor(T),B=Math.floor(u),U=T-I,j=u-B,K=mr(I,d),ue=mr(B,M),le=(K+1)%d,oe=(ue+1)%M,fe=U*U*(3-2*U),ye=j*j*(3-2*j),ve=_r(K,ue,L),we=_r(le,ue,L),Te=_r(K,oe,L),Me=_r(le,oe,L);return ve+(we-ve)*fe+(Te-ve)*ye+(ve-we-Te+Me)*fe*ye},Ur=(T,u,d,M,L,I)=>{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*Mm(T*le,u*oe,le,oe,I+ue>>>0),j+=U,U*=.5,K*=2}return B/j},ml=T=>T-Math.floor(T),pl=T=>Math.abs(ml(T)*2-1),zn=(T,u,d)=>{let M=(d-T)/(u-T);return M<0?M=0:M>1&&(M=1),M*M*(3-2*M)},Sr=(T,u,d)=>T+(u-T)*d,Or=T=>T<=0?0:T>=1?255:Math.floor(T*255+.5),bg=(T,u,d,M,L,I,B,U,j,K,ue)=>{let le=Me=>[L[0]*Me,L[1]*Me,L[2]*Me],oe=(Me,be,Ce)=>[Sr(Me[0],be[0],Ce),Sr(Me[1],be[1],Ce),Sr(Me[2],be[2],Ce)];if(T===0){let Me=mr(Math.floor(U*d)+Math.floor(j*d),2)===1?I:L;return[Me[0],Me[1],Me[2],.5,B,0]}if(T===1){let Me=ml(U*d),be=ml(j*d),Ce=Math.max(.035,d/u),$e=1-zn(Ce*.5,Ce,Math.min(Me,1-Me,be,1-be));return[...oe(L,I,$e),.3+.4*$e,B,0]}if(T===2){let Me=Ur(U,j,4,4,4,M),be=pl(j*d+Me*1.5),Ce=Ur(U,j,2,96,2,M+7>>>0),$e=be*.7+Ce*.3;return[...le(Sr(.55,1,$e)),$e,B+(1-$e)*.15,0]}if(T===3){let Me=Ur(U,j,3,3,5,M),be=pl((U+j)*d+Me*2.5),Ce=be*be,$e=Ce*Ce,ze=$e*$e,Ue=.92+.08*Me,He=oe(L,I,ze*.85);return[He[0]*Ue,He[1]*Ue,He[2]*Ue,.5-ze*.2,B+ze*.1,0]}if(T===4){let Me=Ur(U,j,2,192*d,2,M),be=_r(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,$e=be-Math.floor(be),ze=Ce-Math.floor(Ce),Ue=mr(Math.floor(be)+Math.floor(Ce),2)===0,He=Ue?ze*2-1:$e*2-1,Ke=1-He*He,et=.08*pl(Ue?ze*8:$e*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=Ur(U,j,d,d,5,M),be=_r(K,ue,M+31>>>0),Ce=d*16,$e=zn(.82,.9,Mm(U*Ce,j*Ce,Ce,Ce,M+17>>>0));return[...le((.82+.25*Me+.06*(be-.5))*(1-.35*$e)),.5+.25*(Me-.5)-.3*$e,B-.05*Me,0]}if(T===7){let Me=Math.floor(d/2),be=j*d,Ce=Math.floor(be),$e=be-Ce,ze=U*Me+(mr(Ce,2)===1?.5:0),Ue=Math.floor(ze),He=ze-Ue,Ke=Math.min(Math.min(He,1-He)*2,Math.min($e,1-$e)),et=Math.max(.06,1.5*d/u),Qe=1-zn(et*.5,et,Ke),tt=_r(mr(Ue,Me),mr(Ce,d),M),Oe=Ur(U,j,d,d,3,M+5>>>0),Xe=.8+.25*tt+.15*(Oe-.5),rt=.9+.1*Oe;return[Sr(L[0]*Xe,I[0]*rt,Qe),Sr(L[1]*Xe,I[1]*rt,Qe),Sr(L[2]*Xe,I[2]*rt,Qe),(1-Qe)*(.75+.1*Oe)+Qe*.2,Sr(B,.95,Qe),0]}if(T===8){let Me=U*d,be=j*d,Ce=(Me-Math.floor(Me))*2-1,$e=(be-Math.floor(be))*2-1,ze=mr(Math.floor(Me)+Math.floor(be),2)===0?1-Ce*Ce:1-$e*$e,Ue=Ur(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),$e=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=$e+et,Xe=mr(tt,d),rt=mr(Oe,d),bt=tt+_r(Xe,rt,M)-Me,pt=Oe+_r(Xe,rt,M+1>>>0)-be,lt=bt*bt+pt*pt;lt<ze?(Ue=ze,ze=lt):lt<Ue&&(Ue=lt)}let He=1-zn(0,.12,Math.sqrt(Ue)-Math.sqrt(ze)),Ke=Ur(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=Ur(U,j,d,d,5,M),ye=zn(.45,.6,fe),ve=Ur(U,j,d*8,d*8,3,M+9>>>0),we=.9+.1*ve,Te=.7+.5*ve;return[Sr(I[0]*we,L[0]*Te,ye),Sr(I[1]*we,L[1]*Te,ye),Sr(I[2]*we,L[2]*Te,ye),.4+.4*ye*ve+.1*ye,Sr(.35,B,ye),1-ye]},xg=(T,u,d,M,L,I,B,U)=>{let j=globalThis.__three_live_native_material_preset__;if(typeof j=="function"){let oe=j(T,u,d,M,...L,...I,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=bg(T,u,d,M,L,I,B,(ye+.5)/u,fe,ye,oe),we=(oe*u+ye)*4;K[we]=Or(ve[0]),K[we+1]=Or(ve[1]),K[we+2]=Or(ve[2]),K[we+3]=255,ue[we]=255,ue[we+1]=Or(ve[4]),ue[we+2]=Or(ve[5]),ue[we+3]=255,le[oe*u+ye]=ve[3]}}return[K,_m(le,u,U),ue]},_m=(T,u,d)=>{let M=new Uint8Array(u*u*4),L=d*u*.0625;for(let I=0;I<u;I++){let B=(I+u-1)%u,U=(I+1)%u;for(let j=0;j<u;j++){let K=-(T[I*u+(j+1)%u]-T[I*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=(I*u+j)*4;M[oe]=Or(K*le*.5+.5),M[oe+1]=Or(ue*le*.5+.5),M[oe+2]=Or(le*.5+.5),M[oe+3]=255}}return M},Sm=(T,u)=>{let d=u;try{T!=null&&(d=new Mr(T).getHex())}catch{}return[(d>>16&255)/255,(d>>8&255)/255,(d&255)/255]},ts=new Map,dl=(T,u={})=>{let d=fr.indexOf(T);if(d<0)throw new TypeError(`THREE.ProceduralTexture: unknown preset '${T}' (use ${fr.join(", ")})`);let M=u&&typeof u=="object"?u:{},L=Bn[d],I=Math.max(1,Math.min(256,Math.round(Pe(M.scale,L[0]))));(d===0||d===7||d===8)&&I%2===1&&I++;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=Sm(M.color,L[1]),K=Sm(M.color2,L[2]||L[1]),ue=st(Pe(M.roughness,L[3])),le=Math.max(0,Math.min(8,Pe(M.normalStrength,1))),oe=[d,B,I,U,...j,...K,ue,le].join(","),fe=ts.get(oe);if(fe)return{...fe};let[ye,ve,we]=xg(d,B,I,U,j,K,ue,le),Te=(Ce,$e)=>{let ze=new _e(B,B);ze._data.set(Ce),ze._ver++;let Ue=new W(ze);return Ue.flipY=!1,Ue.colorSpace=$e,Ue.name=`${T}_${$e==="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,ts.size>=64&&ts.clear(),ts.set(oe,be),{...be}},gl={presets:Object.freeze(fr.slice()),create:(T,u)=>dl(String(T),u)};for(let T of fr)gl[T]=u=>dl(T,u);Object.freeze(gl);let vg=500,wg=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>vg?null:u},Mg=T=>{let u=typeof T=="number"?T:NaN;return Number.isFinite(u)?u<=384?256:u<=768?512:1024:512},Am=T=>T>512&&T%2===0?T/2:T,_g=(T,u)=>{let d=u/2,M=new Uint8Array(d*d*4);for(let L=0;L<d;L++)for(let I=0;I<d;I++){let B=(2*L*u+2*I)*4,U=B+u*4,j=(L*d+I)*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},Sg=T=>{let u=typeof T=="number"?T:NaN,d=Number.isFinite(u)?Math.abs(u):1;return Math.floor(d+.5)%4294967296},Ag=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},Tg=(T,u,d)=>{let M=Ag(`three-live-texture1${T}${u}${d}`),L=3421674724,I=2216829733;for(let B of M){I=(I^B)>>>0;let U=I&65535,j=I>>>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+(I<<8>>>0)>>>0,I=le>>>0}return L.toString(16).padStart(8,"0")+I.toString(16).padStart(8,"0")},Tm=T=>{let u=wg(T?.prompt);if(u===null)return null;let d=Mg(T?.size),M=Sg(T?.seed);return{prompt:u,size:d,seed:M,key:Tg(u,d,M)}},yl=(T,u,d,M,L)=>{if(Am(u)!==u)return yl(_g(T,u),u/2,d,M,L);let I=new Float64Array(u*u);for(let be=0;be<u*u;be++){let Ce=be*4;I[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 $e=0;for(let ze=0;ze<=2*B;ze++)$e+=I[be*u+(Ce+u+ze-B)%u];U[be*u+Ce]=$e}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 $e=0;for(let Ue=0;Ue<=2*B;Ue++)$e+=U[(be+u+Ue-B)%u*u+Ce];let ze=j*I[be*u+Ce]-$e;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=_m(fe,u,ye),we=Number.isFinite(M)?Math.max(0,Math.min(1,M)):0,Te=Or(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]=Or(we+.35*(.5-fe[be])),Me[Ce+2]=Te,Me[Ce+3]=255}return[ve,Me]},rs=new Map,Pm=new WeakMap,Pg=0,Ng=(T,u)=>{let d=Tm(T);if(!d)return null;let{prompt:M,size:L,seed:I,key:B}=d,U=st(Pe(T.roughness,u>=0?Bn[u][3]:.8)),j=st(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 $e=ue.__three_live_native_texture_pack_token__;fe=typeof $e=="function"&&Number($e())||0}else oe&&typeof oe=="object"&&(fe=Pm.get(oe)??0,fe||Pm.set(oe,fe=++Pg));let ye=[fe,B,K,U,j].join(","),ve=fe?rs.get(ye):void 0;if(ve)return{...ve};let we=null;if(typeof le=="function"){let $e=le(M,L,I,K,U,j);Array.isArray($e)&&$e.length===3&&(we=$e)}else{let $e=oe&&typeof oe=="object"&&Object.prototype.hasOwnProperty.call(oe,B)?oe[B]:null;$e&&$e.size===L&&$e.rgba instanceof Uint8Array&&$e.rgba.length===L*L*4&&(we=[$e.rgba,...yl($e.rgba,L,K,U,j)])}if(!we)return null;let Te=($e,ze,Ue,He)=>{let Ke=new W({data:new Uint8ClampedArray($e.buffer,$e.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=Am(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&&(rs.size>=32&&rs.clear(),rs.set(ye,Ce)),{...Ce}},Nm=new Set,Cg=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??""),I=fr.indexOf(L),B=!!M&&M.prompt!==void 0&&M.prompt!==null,U=B?Ng(M,I):null;if(!M||I<0&&!U){!(B&&L==="")&&!Nm.has(L)&&(Nm.add(L),console.warn(`[three-live] userData.xr.material: unknown preset '${L}' (use ${fr.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 Mr(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??dl(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},Cm={Box3:a,Sphere:o,CanvasTexture:W,ImprovedNoise:pe,SimplexNoise:Ge,SpriteMaterial:wt,Sprite:qt,LineCurve:Pt,QuadraticBezierCurve:Et,CubicBezierCurve:Xt,SplineCurve:jt,EllipseCurve:Yt,ArcCurve:er,CurvePath:tr,GridHelper:Ni,AxesHelper:Rr,ArrowHelper:$r,Box3Helper:Ir,BoxHelper:pi,ProceduralTexture:gl};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,Cm),t.createCanvas=D,t._procMaterialize=Cg,t.canonicalTextureSpec=Tm,t.deriveTextureMaps=yl,t.encodeRgbaPngDataUri=(T,u,d)=>_(T,u,d,!1,!1,f).uri,t.materializeDeclarativeGeometry=T=>{t._cadMaterialize?.(T),t._lodMaterialize?.(T),t._procMaterialize?.(T)}),Cm}var Rl={name:"procedural",onRegister(){Ji(ys);let e=We(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&ys(t,e)}};function $l(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 $=Math.min(w,P-R);if(y+$>v.length)return null;v.set(h.subarray(R,R+$),y),y+=$,R+=$,w-=$,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 $=S[1]|S[2]<<8;if(($^(S[3]|S[4]<<8))!==65535)return null;w=$,$===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 $=R>=4?h[S+R-4]:0,F=w>0?h[E+R]:0,V=0;if(_===1)V=$;else if(_===2)V=F;else if(_===4){let J=R>=4&&w>0?h[E+R-4]:0,re=$+F-J,Q=Math.abs(re-$),ee=Math.abs(re-F),k=Math.abs(re-J);V=Q<=ee&&Q<=k?$: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,$)=>(R[$]|R[$+1]<<8|R[$+2]<<16|R[$+3]<<24)>>>0,g=(R,$,F)=>{R[$]=F&255,R[$+1]=F>>>8&255,R[$+2]=F>>>16&255,R[$+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)),$=p(h,12);if(p(h,16)!==1313821514||20+$>R)return Promise.resolve(h);x=JSON.parse(new TextDecoder().decode(h.subarray(20,20+$)));let F=20+$;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 $=A[R];if(!$||typeof $!="object")continue;let F=y[$.bufferView];if(typeof $.uri=="string"&&$.uri.indexOf(E)===0){let V=m($.uri.slice(E.length));V&&(w.push(R),S.push(V))}else $.mimeType==="image/png"&&F&&(F.buffer||0)===0&&b.indexOf($.bufferView)<0&&b.push($.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,$)=>(y[R].byteOffset||0)-(y[$].byteOffset||0));let C=0;for(let R=0;R<N.length;R++){let $=y[N[R]],F=$.byteOffset||0;if(typeof $.byteLength!="number"||($.buffer||0)!==0||F<C||F+$.byteLength>v.length)return Promise.resolve(h);C=F+$.byteLength}let _=R=>{let $=y[R].byteOffset||0;return v.subarray($,$+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 $=[];for(let k=0;k<y.length;k++){let G=b.indexOf(k);$.push(G>=0?R[G]:_(k))}let F=0;for(let k=0;k<N.length;k++)F=(F+3&-4)+$[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($[G],J),y[G].byteOffset=J,y[G].byteLength=$[G].length,J+=$[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 x0={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Li(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=x0[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 v0(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 gi(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 Il=["neutral","reinhard","none","aces","agx"];function Ri(e){let t=String(e??"").trim().toLowerCase();return Il.includes(t)?t:"neutral"}function w0(e){return Il.indexOf(Ri(e))}function M0(e){return new TextDecoder().decode(e)}var Dl=We().decoders;function _0(e,t){Dl.set(e.toLowerCase(),t)}function Yn(e){return Dl.get(e.toLowerCase())}function kl(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=M0(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)&&!Yn(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 Ct)h.onParseGLB?.(m);return m}function Fl(e,t=rn(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 S0(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 sn(e){if(S0(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return kl(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var bs=`#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
- }`,Go=`#version 300 es
52
+ }`,A0=`#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 jo(e,t,r=1){t=Vt(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 qo=`#version 300 es
208
+ }`;function T0(e,t,r=1){t=Ri(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 P0=`#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);}`,Xo=`#version 300 es
211
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,N0=`#version 300 es
247
212
  precision highp float;
248
213
  uniform vec4 uColorId;
249
214
  out vec4 fragColor;
250
- void main(){fragColor=uColorId;}`;function mi(e,t,r){let i={};for(let n of r)i[n]=e.getUniformLocation(t,n);return i}var Sn=["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 Rn(){let e=Ae().xrDepthShader;return{fs:Go.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...Sn,...e.uniformNames]:Sn}}function Ko(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 fi(e,t,r,i,n,s,l,o){if(i===void 0||!t.accessors?.[i])return null;let a=kt(t,r,t.accessors[i],s);if(!a)return null;o&&(a=a.slice(),Bo(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 pi(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function Pn(e,t,r){let i=Rn(),n=Tn,s=i.fs,l=!1;for(let a of Fe)if(a.onResolveShader){let u=a.onResolveShader(t,r,n,s);u&&(n=u.vs,s=u.fs,l=!0)}let o=l?Ft(e,n,s):null;return{program:o,uniforms:o?mi(e,o,i.uniforms):null}}function Yo(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 Zo(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 Qo=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),En=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Ar(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function Nn(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 Cn(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 Ln(e,t,r=En,i){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Jo(e,t,r,i,n)}catch(s){let l=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;Cn(e,l,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let o of n.buffers)e.deleteBuffer(o);throw s}}function Jo(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=Ut("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=vr(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],N=H.byteOffset||0,z=new Blob([o.slice(N,N+H.byteLength)],{type:ie.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(z).then(I).catch(()=>{})}else if(ie.uri){let H=Ko(ie.uri);if(H){let N=new Image;N.crossOrigin="anonymous",N.referrerPolicy="no-referrer",N.onload=()=>I(N),N.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);Ke(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 N=w.node?.extensions?.EXT_mesh_gpu_instancing;if(N&&N.attributes&&typeof N.attributes=="object"){let z=N.attributes,ue=z.TRANSLATION!==void 0?s.accessors?.[z.TRANSLATION]:null,he=z.ROTATION!==void 0?s.accessors?.[z.ROTATION]:null,B=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??B?.count??0);if(!Number.isFinite(_)||_<0||_>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${_}`);if(_>0){let G=(V,ee)=>{if(!V||V.bufferView===void 0||!s.bufferViews?.[V.bufferView])return null;let R=V.componentType??5126,A=C=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${C})`),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=kt(s,o,{...V,count:_},ee)}catch{return A("out of bounds")}return!L||!L.every(Number.isFinite)?A("non-finite value"):L},j=G(ue,3),q=G(he,4),D=G(B,3),Y=$?.type==="VEC4"?4:3,te=G($,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=q?[q[V*4],q[V*4+1],q[V*4+2],q[V*4+3]]:[0,0,0,1],A=D?[D[V*3],D[V*3+1],D[V*3+2]]:[1,1,1];Qt(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=Ut("draco");L&&L.decodePrimitive(s,z,o)}let ue=[],he=e.createVertexArray();n.vao=he,n.buffers=ue,e.bindVertexArray(he);let B=Yo(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=C=>{for(let U=0;U<3;U++){let Q=C[12+U],X=C[12+U];for(let Z=0;Z<3;Z++){let J=C[Z*4+U]*$.min[Z],K=C[Z*4+U]*$.max[Z];Q+=J<K?J:K,X+=J>K?J:K}Q<b[U]&&(b[U]=Q),X>v[U]&&(v[U]=X)}};if(H.instanceMatrices&&H.instanceMatrices.length>=16){let C=H.instanceMatrices.length>>4,U=Pe();for(let Q=0;Q<C;Q++){let X=H.instanceMatrices.subarray(Q*16,Q*16+16);ke(U,oe,X),L(U)}}else L(oe)}let G=fi(e,s,o,z.attributes.POSITION,0,3,ue);fi(e,s,o,z.attributes.NORMAL,1,3,ue),fi(e,s,o,z.attributes.TEXCOORD_0,2,2,ue,Zo(s,z));let j=0,q=5123,D=null;if(z.indices!==void 0){let L=s.accessors[z.indices],C=(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,q=L.componentType===5125?5125:5123;let U=e.createBuffer();ue.push(U),e.bindBuffer(34963,U),L.componentType===5125?D=new Uint32Array(o,C,L.count):L.componentType===5121?D=Uint16Array.from(new Uint8Array(o,C,L.count)):D=C%2===0?new Uint16Array(o,C,L.count):new Uint16Array(o.slice(C,C+L.count*2)),e.bufferData(34963,D,35044)}else j=$.count;let Y={};for(let L of Fe)if(L.onBuildPrimitiveVAO){let C=L.onBuildPrimitiveVAO(e,he,z,s,o);C&&(Y[L.name]=C)}e.bindVertexArray(null);let te=s.materials&&z.material!==void 0?s.materials[z.material]:null,{program:se,uniforms:le}=Pn(e,z,te),V=Nn(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(C=>Number(C)|0)})):void 0;H.primitives.push({vao:he,instanced:B,indexCount:j,indexType:q,...V,positions:G,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],W=v[2]-b[2],T=Math.max(Math.hypot(P,F,W)/2,.5),E=[b[0],b[1],b[2]],S=[v[0],v[1],v[2]],O=t.animations;if(!O){for(let k of Fe)if(k.onParseGLB?.(t),t.animations){O=t.animations;break}}return O||(O=[]),{meshes:a,bounds:{center:M,radius:T,min:E,max:S},lights:f,animations:O,worldMatrices:m,gpuTextures:x,availableVariants:u}}function rr(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 Qe=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=pi(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=Vt(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){Ho(e,t)}static getDecoder(e){return Ut(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=Rn();this.renderProg=Ft(e,Tn,t.fs),this.pickProg=Ft(e,qo,Xo),this.uRender=mi(e,this.renderProg,t.uniforms),this.uPick=mi(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of Fe)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}=Ln(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 Fe)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=pi(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(An(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of Fe)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(tr(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=tr(e),{meshes:i}=Ln(this.gl,r,En,()=>this.render());if(t)for(let n of i)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],Ke(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),Ke(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=pi(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=Vt(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of Fe)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of Fe)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,Nn(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=Pn(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 Fe)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,W,T]=rr(this),E=[i-F,n-W,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,W=(F&255)/255,T=(F>>8&255)/255,E=(F>>16&255)/255;i.uniform4f(this.uPick.uColorId,W,T,E,1),ke(this.modelMatrix,this.modelRootMatrix,P.transform);let S=P.instanceMatrices;if(S&&S.length>=16){let O=S.length>>4,k=Pe();for(let w of P.primitives){i.bindVertexArray(w.vao);for(let ie=0;ie<O;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),Ar(i,w)}}else{ke(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let O of P.primitives)i.bindVertexArray(O.vao),Ar(i,O)}}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]=rr(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(!ri(F,this.mvpMatrix))continue;let W=(a+.5)/n*2-1,T=(u+.5)/s*2-1,E=[0,0,0],S=[0,0,0];cn(E,W,T,-1,F),cn(S,W,T,1,F);let O=S[0]-E[0],k=S[1]-E[1],w=S[2]-E[2],ie=Math.hypot(O,k,w)||1,oe=O/ie,I=k/ie,H=w/ie,N={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,B=ue.indices,$=Math.floor(B?B.length/3:he.length/9);for(let _=0;_<$;_++){let G=B?B[_*3]:_*3,j=B?B[_*3+1]:_*3+1,q=B?B[_*3+2]:_*3+2;Ao(E[0],E[1],E[2],oe,I,H,he[G*3],he[G*3+1],he[G*3+2],he[j*3],he[j*3+1],he[j*3+2],he[q*3],he[q*3+1],he[q*3+2],N,z)}}})(1e-4),isFinite(N.distance)){let z=N.point[0],ue=N.point[1],he=N.point[2],B=this.modelMatrix,$=B[0]*z+B[4]*ue+B[8]*he+B[12],_=B[1]*z+B[5]*ue+B[9]*he+B[13],G=B[2]*z+B[6]*ue+B[10]*he+B[14],j=$-f,q=_-g,D=G-x,Y=Math.hypot(j,q,D);if(Y<m){Ke(this.normalMatrix,this.modelMatrix);let te=this.normalMatrix,se=N.normal[0],le=N.normal[1],V=N.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*q+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(G*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 Fe)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);ti(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;xr(this.viewMatrix,rr(this),r,[0,1,0]),ke(this.mvpMatrix,this.projMatrix,this.viewMatrix),Ke(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 Fe)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 Fe)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 Fe)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 Fe)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,[W,T,E]=rr(this),S=Math.cos(this.currTheta),O=-Math.sin(this.currTheta),k=.032,w=Pe(),ie=Pe(),oe=[W-S*k,T,E-O*k],I=[F[0]-S*k*.25,F[1],F[2]-O*k*.25];ti(w,this.fov,y/p,.1,P),xr(ie,oe,I,[0,1,0]);let H=Pe(),N=Pe(),z=[W+S*k,T,E+O*k],ue=[F[0]+S*k*.25,F[1],F[2]+O*k*.25];ti(H,this.fov,M/p,.1,P),xr(N,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:N,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=zo(this.toneMapping),[h,m,c]=e?e.eyePos:rr(this);for(let v of Fe)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),Ke(y.normalMatrix,this.modelMatrix);let P=y.extras?.xr?.stereo||y.userData?.xr?.stereo,F=0,W=0,T=1,E=1;P==="sbs"?(T=.5,F=f==="right"?.5:0):P==="ou"&&(E=.5,W=f==="right"?.5:0);for(let S of y.primitives){let O=!!S.isTransmissive;if(!v&&O){g=!0;continue}if(v&&!O)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,W,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 Fe)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(),N=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),Ke(N,H),t.uniformMatrix4fv(w.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(w.uModel,!1,H),t.uniformMatrix3fv(w.uNormalMatrix,!1,N),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)),Ar(t,S)}else Ar(t,S)}}};if(b(!1),g){for(let v of Fe)v.onBeforeTransmissivePass?.(t,this);b(!0)}for(let v of Fe)v.onAfterRender?.(t,this,l,e?.eye??"none",[r,i,n,s],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){Cn(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 Fe)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()}};Qe.registerPlugin=Ge,Qe.getRegisteredPlugins=un;function el(e){return e+3&-4}var ve=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function _n(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function In(e,t=0){let[r,i,n,,s,l,o,,a,u,h,,m,c,d]=Array.from({length:15},(N,z)=>ve(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,W=l*v,T=o*v,E=a*p,S=u*p,O=h*p,k=y+W+O,w=0,ie=0,oe=0,I=1;if(k>0){let N=.5/Math.sqrt(k+1);I=.25/N,w=(T-S)*N,ie=(E-P)*N,oe=(M-F)*N}else if(y>W&&y>O){let N=2*Math.sqrt(Math.max(0,1+y-W-O));N>1e-8&&(I=(T-S)/N,w=.25*N,ie=(F+M)/N,oe=(E+P)/N)}else if(W>O){let N=2*Math.sqrt(Math.max(0,1+W-y-O));N>1e-8&&(I=(E-P)/N,w=(F+M)/N,ie=.25*N,oe=(T+S)/N)}else{let N=2*Math.sqrt(Math.max(0,1+O-y-W));N>1e-8&&(I=(M-F)/N,w=(E+P)/N,ie=(T+S)/N,oe=.25*N)}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 tl(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 Mt=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function Dn(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:Mt(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function ir(e,t){return kn(e,t)[0]}function kn(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 N=I,z=N.color?.r??1,ue=N.color?.g??1,he=N.color?.b??1,B=N.opacity??1,$={baseColorFactor:[z,ue,he,B],metallicFactor:N.metalness??0,roughnessFactor:N.roughness??.5},_={},G=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=G(N.map);j&&($.baseColorTexture=j);let q=G(N.roughnessMap||N.metalnessMap);q&&($.metallicRoughnessTexture=q);let D=N.map?.avgColor;Array.isArray(D)&&D.length>=3&&(_.avgColor=[D[0],D[1],D[2]]);let Y=G(N.normalMap),te=G(N.emissiveMap),se=G(N.aoMap),le={name:N.name||"",pbrMetallicRoughness:$,doubleSided:N.side===2||!!N.doubleSided,...Y?{normalTexture:Y}:{},...te?{emissiveTexture:te}:{},...se?{occlusionTexture:se}:{},...Object.keys(_).length>0?{extras:_}:{}};if(N.emissive&&(N.emissive.r>0||N.emissive.g>0||N.emissive.b>0)){let ee=N.emissiveIntensity??1;le.emissiveFactor=[N.emissive.r*ee,N.emissive.g*ee,N.emissive.b*ee]}let V={};return N.clearcoat&&N.clearcoat>0&&(V.KHR_materials_clearcoat={clearcoatFactor:N.clearcoat,clearcoatRoughnessFactor:N.clearcoatRoughness||0}),N.sheen&&N.sheen>0&&(V.KHR_materials_sheen={sheenColorFactor:N.sheenColor?[N.sheenColor.r,N.sheenColor.g,N.sheenColor.b]:[1,1,1],sheenRoughnessFactor:N.sheenRoughness||0}),N.transmission&&N.transmission>0&&(V.KHR_materials_transmission={transmissionFactor:N.transmission}),N.thickness&&N.thickness>0&&(V.KHR_materials_volume={thicknessFactor:N.thickness,attenuationDistance:N.attenuationDistance??1/0,attenuationColor:N.attenuationColor?[N.attenuationColor.r,N.attenuationColor.g,N.attenuationColor.b]:[1,1,1]}),N.ior!==void 0&&N.ior!==1.5&&(V.KHR_materials_ior={ior:N.ior}),N.dispersion&&N.dispersion>0&&(V.KHR_materials_dispersion={dispersion:N.dispersion}),N.iridescence&&N.iridescence>0&&(V.KHR_materials_iridescence={iridescenceFactor:N.iridescence,iridescenceIor:N.iridescenceIOR??1.3}),Object.keys(V).length>0&&(le.extensions=V),h.push(le),H}function p(I,H){let N=new Uint8Array(I.buffer,I.byteOffset,I.byteLength),z=el(N.byteLength),ue=new Uint8Array(z);ue.set(N),r.push(ue);let he=n.length;return n.push({buffer:0,byteOffset:i,byteLength:N.byteLength,target:H}),i+=z,he}function y(I,H,N,z,ue,he,B){let $=p(I,N),_=s.length,G={bufferView:$,byteOffset:0,componentType:z,count:ue,type:H};return he&&(G.min=he),B&&(G.max=B),s.push(G),_}e.traverse(I=>{if(I.isLight||I.color&&I.intensity!==void 0){let H=I.matrixWorld?.elements,N=ve(H?H[12]:I.position?.x,0),z=ve(H?H[13]:I.position?.y,0),ue=ve(H?H[14]:I.position?.z,0),he=I.target,B=he?.parent?he?.matrixWorld?.elements:void 0,$=ve(B?B[12]:he?.position?.x,0),_=ve(B?B[13]:he?.position?.y,0),G=ve(B?B[14]:he?.position?.z,0),j=$-N,q=_-z,D=G-ue,Y=Math.hypot(j,q,D),te=Math.max(.01,Math.min(Math.PI/2,ve(I.angle,Math.PI/3))),se=Math.max(0,Math.min(1,ve(I.penumbra,0)));b.push({type:I.type,color:[I.color.r,I.color.g,I.color.b],intensity:I.intensity,position:[N,z,ue],...I.type==="spot"?{direction:Y>1e-6?[j/Y,q/Y,D/Y]:[0,-1,0],outerConeAngle:te,innerConeAngle:Math.max(0,te*(1-se)),range:Math.max(0,ve(I.distance,0))}:I.type==="point"?{range:Math.max(0,ve(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 N=!!(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||(N?`Node_${o.length}`:"")},ue=ve(I.position?.x,0),he=ve(I.position?.y,0),B=ve(I.position?.z,0),$=ve(I.quaternion?.x,0),_=ve(I.quaternion?.y,0),G=ve(I.quaternion?.z,0),j=ve(I.quaternion?.w,1),q=ve(I.scale?.x,1),D=ve(I.scale?.y,1),Y=ve(I.scale?.z,1);if((ue||he||B)&&(z.translation=[ue,he,B]),($||_||G||j!==1)&&(z.rotation=[$,_,G,j]),(q!==1||D!==1||Y!==1)&&(z.scale=[q,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=tl(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 X=0;X<V.count;X++){let Z=V.getX(X),J=V.getY(X),K=V.getZ(X);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 X=le.index.array instanceof Uint32Array;A.indices=y(le.index.array,"SCALAR",34963,X?5125:5123,le.index.count)}let L=Array.isArray(I.material)?I.material[0]:I.material;L&&(A.material=v(L));let C=I.userData?.variants;if(C&&typeof C=="object"){let X=new Map;for(let Z of Object.keys(C)){if(!Z||Z==="__proto__"||Z==="constructor"||Z==="prototype")continue;let J=C[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=X.get(ae);ne||(ne=[],X.set(ae,ne)),ne.push(K)}if(X.size>0){let Z=[];for(let[J,K]of X.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 X=Math.min(1e4,Math.floor(U.count)),Z=U.instanceMatrix.array,J=new Float32Array(X*3),K=new Float32Array(X*4),ae=new Float32Array(X*3);for(let re=0;re<X;re++){let{t:ce,r:me,s:ge}=In(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,X),ROTATION:y(K,"VEC4",0,5126,X),SCALE:y(ae,"VEC3",0,5126,X)};if(U.instanceColor?.array&&U.instanceColor.array.length>=X*3){let re=new Float32Array(U.instanceColor.array.subarray(0,X*3));ne._COLOR_0=y(re,"VEC3",0,5126,X)}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 W=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 W=="function"&&u.length>0){let I=t?.duration??4,H=t?.fps??15,N=Math.max(2,Math.round(I*H)+1),z=new Float32Array(N),ue=u.map(D=>[ve(D.position?.x,0),ve(D.position?.y,0),ve(D.position?.z,0),ve(D.quaternion?.x,0),ve(D.quaternion?.y,0),ve(D.quaternion?.z,0),ve(D.quaternion?.w,1),ve(D.scale?.x,1),ve(D.scale?.y,1),ve(D.scale?.z,1)]),he=u.map(()=>new Float32Array(N*3)),B=u.map(()=>new Float32Array(N*4)),$=u.map(()=>new Float32Array(N*3));for(let D=0;D<N;D++){let Y=D/(N-1)*I;z[D]=Y;try{W(Y)}catch{}for(let te=0;te<u.length;te++){let se=u[te];he[te][D*3]=ve(se.position?.x,0),he[te][D*3+1]=ve(se.position?.y,0),he[te][D*3+2]=ve(se.position?.z,0);let le=ve(se.quaternion?.x,0),V=ve(se.quaternion?.y,0),ee=ve(se.quaternion?.z,0),R=ve(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,C=B[te];C[L]*le+C[L+1]*V+C[L+2]*ee+C[L+3]*R<0&&(le=-le,V=-V,ee=-ee,R=-R)}B[te][D*4]=le,B[te][D*4+1]=V,B[te][D*4+2]=ee,B[te][D*4+3]=R,$[te][D*3]=ve(se.scale?.x,1),$[te][D*3+1]=ve(se.scale?.y,1),$[te][D*3+2]=ve(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,G=()=>(_===null&&(_=y(z,"SCALAR",0,5126,N,[0],[I])),_),j=[],q=[];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&&q.push({sampler:j.push({input:G(),interpolation:"LINEAR",output:y(V,ee,0,5126,N)})-1,target:{node:D,path:R}})};se(te(he[D],3,0),he[D],"VEC3","translation"),se(te(B[D],4,3),B[D],"VEC4","rotation"),se(te($[D],3,7),$[D],"VEC3","scale")}q.length>0&&T.push({name:"ProceduralLoop",samplers:j,channels:q})}let E=bo(o,l,e.userData),S=[],O=[],k=[];for(let I=0;I<o.length;I++){let H=o[I],N=Dn(H.extras?.xr);if(!N)continue;let{ae:z,src:ue,preset:he,volume:B,loop:$,isGlobal:_}=N,G=H.name||`Node_${I}`,j=O.length;O.push({name:`${G}_source`,gain:B,loop:$,autoPlay:typeof z.autoplay=="boolean"?z.autoplay:!0,...ue!==void 0?{audio:S.push({uri:ue})-1}:{},...he?{extras:{preset:he,pitch:Mt(z.pitch,.25,4,1)}}:{}});let q=k.length,D=Mt(z.refDistance,.05,100,1),Y=Mt(z.coneInnerAngle,0,360,360),te=Mt(z.coneOuterAngle,Y,360,360);k.push({name:`${G}_emitter`,type:_?"global":"positional",gain:B,sources:[j],..._?{}:{positional:{distanceModel:z.distanceModel==="linear"||z.distanceModel==="exponential"?z.distanceModel:"inverse",refDistance:D,maxDistance:Mt(z.maxDistance,D,500,Math.max(D,25)),rolloffFactor:Mt(z.rolloffFactor,0,10,1),coneInnerAngle:+(Y*Math.PI/180).toFixed(6),coneOuterAngle:+(te*Math.PI/180).toFixed(6),coneOuterGain:Mt(z.coneOuterGain,0,1,0)}}}),H.extensions={...H.extensions||{},KHR_audio_emitter:{emitter:q}},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:O,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 di(e){return new TextEncoder().encode(e)}function Tr(e,t){let{gltf:r,bin:i}=ir(e,t),n=JSON.stringify(r),s=di(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 rl(e,t){let[r,i]=kn(e,t);return Fn(r,i)}function Fn(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)=>_n(g,Sr(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 W=F[2].replace(/\s+/g,""),T=W.endsWith("==")?2:W.endsWith("=")?1:0,E=new Uint8Array((W.length*3>>2)-T),S=k=>{let w=W.charCodeAt(k);return w>96?w-71:w>64?w-65:w>47?w+4:w===43?62:w===47?63:0},O=0;for(let k=0;k<W.length;k+=4){let w=S(k)<<18|S(k+1)<<12|S(k+2)<<6|S(k+3);E[O++]=w>>16&255,O<E.length&&(E[O++]=w>>8&255),O<E.length&&(E[O++]=w&255)}return E}function p(P,F,W){let T=P?.index;if(typeof T!="number")return;let E=c[T],S=E?.source;if(typeof S!="number"||!d[S])return;let O=b.get(S);if(O===void 0){O=null;let ie=d[S],oe=null;if(typeof ie.bufferView=="number"){let I=a[ie.bufferView],H=I?.byteOffset||0,N=I?.byteLength||0;I&&N>0&&H>=0&&H+N<=l.byteLength&&(oe=new Uint8Array(l,H,N))}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||"");O={file:`texture_${S}.${I?"jpg":"png"}`,data:oe}}b.set(S,O)}if(!O)return;let k=typeof E.sampler=="number"?f[E.sampler]:void 0,w=ie=>ie===33071?"clamp":ie===33648?"mirror":"repeat";return{file:O.file,data:O.data,wrapS:w(k?.wrapS),wrapT:w(k?.wrapT),...F?{scale:F}:{},...W?{bias:W}:{}}}function y(P){let F=o[P];if(!F)throw new Error(`Accessor ${P} not found`);let W=a[F.bufferView||0],T=(W.byteOffset||0)+(F.byteOffset||0),E=W.byteLength||0;return{acc:F,buffer:l.slice(T,T+E)}}function M(P,F,W,T){let E=[],S=h[P];if(!S)return E;let O=S.primitives||[];for(let k=0;k<O.length;k++){let w=O[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),N,z=w.attributes?.NORMAL;if(z!==void 0){let{acc:V,buffer:ee}=y(z),R=new Float32Array(ee,0,V.count*3);N=new Float32Array(R.length);for(let A=0;A<V.count;A++){let L=R[A*3],C=R[A*3+1],U=R[A*3+2],Q=Math.hypot(L,C,U)||1;N[A*3]=L/Q,N[A*3+1]=C/Q,N[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 B;if(w.indices!==void 0){let{acc:V,buffer:ee}=y(w.indices);B=V.componentType===5125?new Uint32Array(ee,0,V.count):new Uint16Array(ee,0,V.count);let R=oe.count;for(let A of B)if(A>=R)throw new Error(`SecurityError: Index buffer value (${A}) out of vertex bounds [0, ${R}).`)}else{let V=oe.count;B=V>65535?new Uint32Array(V):new Uint16Array(V);for(let ee=0;ee<V;ee++)B[ee]=ee}let $="DefaultMaterial",_=[1,1,1],G=.5,j=0,q=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,C=p(ee.baseColorTexture,L?[_[0],_[1],_[2],A]:void 0),U=V.extras?.avgColor;!C&&Array.isArray(U)&&U.length>=3&&(_=[_[0]*U[0],_[1]*U[1],_[2]*U[2]]),typeof ee.roughnessFactor=="number"&&(G=ee.roughnessFactor),typeof ee.metallicFactor=="number"&&(j=ee.metallicFactor);let Q=typeof ee.roughnessFactor=="number"?ee.roughnessFactor:1,X=typeof ee.metallicFactor=="number"?ee.metallicFactor:1,Z=p(ee.metallicRoughnessTexture,Q!==1||X!==1?[1,Q,X,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);(C||Z||ae||K||ne)&&(le=[C,Z,ae,K,ne]);let re=V.extensions||{};re.KHR_materials_clearcoat&&(q=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:O.length>1?`${F}_p${k}`:F,positions:H,indices:B,normals:N,uvs:ue,materialName:$,color:_,roughness:G,metallic:j,clearcoat:q,clearcoatRoughness:D,ior:Y,opacity:te,emissiveColor:se,...le?{textures:le}:{},xrTraits:W||S.extras?.xr,...T?{invisible:!0}:{}})}return E}if(m.length>0){let P=new Float32Array(0),F=new Uint16Array(0),W=(H,N)=>{if(H===void 0)return null;let{acc:z,buffer:ue}=y(H);return new Float32Array(ue,0,z.count*N)},T=(H,N)=>Array.isArray(H)&&H.length>=3?[ve(H[0],N),ve(H[1],N),ve(H[2],N)]:[N,N,N],E=(H,N,z)=>H&&H.length>=(N+1)*3?[H[N*3],H[N*3+1],H[N*3+2]]:z,S=(H,N,z)=>H&&H.length>=(N+1)*4?[H[N*4],H[N*4+1],H[N*4+2],H[N*4+3]]:z,O=new Map,k=i.animations?.[0];if(k&&Array.isArray(k.channels)&&Array.isArray(k.samplers))for(let H of k.channels){let N=k.samplers[H?.sampler],z=H?.target?.node,ue=H?.target?.path;if(!N||typeof z!="number"||N.input===void 0)continue;let he=O.get(z);he||(he={input:N.input},O.set(z,he)),ue==="translation"?he.t=N.output:ue==="rotation"?he.r=N.output:ue==="scale"&&(he.s=N.output)}let w=i.scenes?.[i.scene??0]?.nodes??[];if(!Array.isArray(w)||w.length===0){let H=new Set;for(let N of m)if(Array.isArray(N?.children))for(let z of N.children)H.add(z);w=[];for(let N=0;N<m.length;N++)H.has(N)||w.push(N);w.length===0&&(w=[0])}let ie=new Set,oe=[],I=(H,N)=>{if(Array.isArray(H))for(let z=H.length-1;z>=0;z--)oe.push({idx:H[z],out:N})};for(I(w,r);oe.length>0;){let{idx:H,out:N}=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],B=[1,1,1];if(Array.isArray(z.matrix)&&z.matrix.length===16){let te=In(z.matrix);ue=te.t,he=te.r,B=te.s}else ue=T(z.translation,0),Array.isArray(z.rotation)&&z.rotation.length>=4&&(he=[ve(z.rotation[0],0),ve(z.rotation[1],0),ve(z.rotation[2],0),ve(z.rotation[3],1)]),B=T(z.scale,1);let $,_=O.get(H);if(_){let te=W(_.input,1);if(te&&te.length>0){let se=W(_.t,3),le=W(_.r,4),V=W(_.s,3),ee=Array.from(te),R=[],A=[],L=[];for(let C=0;C<te.length;C++)R.push(E(se,C,ue)),A.push(S(le,C,he)),L.push(E(V,C,B));$={times:ee,translations:R,rotations:A,scales:L}}}let G=Array.isArray(z.children)?z.children:[],j=typeof z.mesh=="number"&&z.mesh>=0&&z.mesh<h.length,q=t?.[H]?.userData?.xr??z.extras?.xr;if(!j&&G.length===0&&(z.camera!==void 0||z.extensions?.KHR_lights_punctual||!z.name&&!z.extras&&!q&&!$))continue;let D=(te,se,le)=>({name:te,positions:P,indices:F,isXform:!0,xrTraits:q,timeSamples:$,translation:ue,rotation:he,scale:B,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,q,Y),le=z.extensions?.EXT_mesh_gpu_instancing?.attributes;if(le&&typeof le=="object"&&se.length>0){let V=W(le.TRANSLATION,3),ee=W(le.ROTATION,4),R=W(le.SCALE,3),A=W(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 C=[];for(let U=0;U<L;U++){let Q=E(V,U,[0,0,0]),X=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;C.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:X,scale:Z})}}I(G,C),N.push(D(te,C,Y));continue}}if(se.length===1)se[0].translation=ue,se[0].rotation=he,se[0].scale=B,se[0].timeSamples=$,G.length>0&&(se[0].children=[],I(G,se[0].children)),N.push(se[0]);else{let V=[...se];I(G,V),N.push(D(te,V,Y))}}else{let te=[];I(G,te),N.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 Sr(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 Rr(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ze(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 dt=(e,t,r)=>`(${ze(e)}, ${ze(t)}, ${ze(r)})`,Pr=(e,t,r,i)=>`(${ze(e)}, ${ze(t)}, ${ze(r)}, ${ze(i)})`;function Vn(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=dt(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function il(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${ze(e[i*2])}, ${ze(1-e[i*2+1])})`;return r.join(", ")}function nl(e){return Array.from(e).join(", ")}function sl(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=Sr(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 = ${ze(r)}
215
+ void main(){fragColor=uColorId;}`;function Qn(e,t,r){let i={};for(let n of r)i[n]=e.getUniformLocation(t,n);return i}var C0="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 xs(){let e=We(),t=e.xrDepthShader,r=e.shadowMapShader;return{fs:A0.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:[...C0,...t?.uniformNames||[],...r?.uniformNames||[]]}}function E0(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 vs(e,t,r,i,n,a,s,o){if(i===void 0||!t.accessors?.[i])return null;let l=Li(t,r,t.accessors[i],a);if(!l)return null;o&&(l=l.slice(),v0(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 ws(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function Bl(e,t,r){let i=xs(),n=bs,a=i.fs,s=!1;for(let l of Ct)if(l.onResolveShader){let c=l.onResolveShader(t,r,n,a);c&&(n=c.vs,a=c.fs,s=!0)}let o=s?gi(e,n,a):null;return{program:o,uniforms:o?Qn(e,o,i.uniforms):null}}function L0(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 R0(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 $0=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),zl=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Zn(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function Vl(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 Ul(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 Ol(e,t,r=zl,i){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return I0(e,t,r,i,n)}catch(a){let s=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;Ul(e,s,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let o of n.buffers)e.deleteBuffer(o);throw a}}function I0(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=Yn("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=rn(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(...Fl(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],$=a.images[R.source];if($){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($.bufferView!==void 0){let Y=a.bufferViews[$.bufferView],J=Y.byteOffset||0,re=new Blob([o.slice(J,J+Y.byteLength)],{type:$.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(re).then(V).catch(()=>{})}else if($.uri){let Y=E0($.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:",$.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],$=a.meshes[R.meshIdx],F=R.nodeIdx>=0?m[R.nodeIdx]:ot(),V=new Float32Array(9);Qt(V,F);let Y=R.node?.extras?.shadow,J={name:R.node.name||$.name||`Mesh_${R.meshIdx}`,nodeIndex:R.nodeIdx,transform:F,normalMatrix:V,primitives:[],extras:R.node.extras||$.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=Li(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=ot();for(let _e=0;_e<H;_e++){let Le=_e*3,ne=_e*4;tn(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 $.primitives||[]){if(Q.extensions?.KHR_draco_mesh_compression){let z=Yn("draco");z&&z.decodePrimitive(a,Q,o)}let ee=[],k=e.createVertexArray();n.vao=k,n.buffers=ee,e.bindVertexArray(k);let G=L0(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=ot();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=vs(e,a,o,Q.attributes.POSITION,0,3,ee),Z=vs(e,a,o,Q.attributes.NORMAL,1,3,ee),ae=vs(e,a,o,Q.attributes.TEXCOORD_0,2,2,ee,R0(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 Ct)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}=Bl(e,Q,ke),ne=Vl(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 Ct)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 Jn(){return typeof performance<"u"?performance.now():Date.now()}function on(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 ar=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=ot(),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=ot(),this.viewMatrix=ot(),this.activeViewMatrix=null,this.modelMatrix=ot(),this.mvpMatrix=ot(),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:ot(),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=ws(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=Ri(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){_0(e,t)}static getDecoder(e){return Yn(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=xs();this.renderProg=gi(e,bs,t.fs),this.pickProg=gi(e,P0,N0),this.uRender=Qn(e,this.renderProg,t.uniforms),this.uPick=Qn(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}recompileRenderProgram(){if(this.contextLost)return;let e=this.gl,t=xs();this.renderProg&&e.deleteProgram(this.renderProg),this.renderProg=gi(e,bs,t.fs),this.uRender=Qn(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 Ct)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}=Ol(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 Ct)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=ws(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(kl(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of Ct)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(sn(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=sn(e),{meshes:i}=Ol(this.gl,r,zl,()=>this.render());if(t)for(let n of i)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],Qt(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),Qt(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=ws(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=Ri(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){this.environmentSource=e&&typeof e=="object"?e:null;for(let t of Ct)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e),this.render();return}this.render()}async setSkyboxImage(e){for(let t of Ct)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,Vl(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=Bl(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 Ct)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=ot();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]=on(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=Jn;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=ot();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 $=R.length>>4,F=ot();for(let V of E.primitives){i.bindVertexArray(V.vao);for(let Y=0;Y<$;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),Zn(i,V)}}else{ft(this.mvpMatrix,s,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let $ of E.primitives)i.bindVertexArray($.vao),Zn(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]=on(this),y=ot();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=ot();if(!os(N,this.mvpMatrix))continue;let C=(l+.5)/n*2-1,_=(c+.5)/a*2-1,P=[0,0,0],R=[0,0,0];Ml(P,C,_,-1,N),Ml(R,C,_,1,N);let $=R[0]-P[0],F=R[1]-P[1],V=R[2]-P[2],Y=Math.hypot($,F,V)||1,J=$/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;i0(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){Qt(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 Ct)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);ss(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;en(this.viewMatrix,on(this),r,[0,1,0]),ft(this.mvpMatrix,this.projMatrix,this.viewMatrix),Qt(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 Ct)r.onXRSessionEnd?.(this);if(this.lastTime=Jn(),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 Ct)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=Jn();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 Ct)a.onUpdate?.(this,e);let t=Jn();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let a of Ct)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,[$,F,V]=on(this),Y=Math.cos(this.currTheta),J=-Math.sin(this.currTheta),re=.032;for(let Q of[-1,1]){let ee=ot(),k=ot(),G=Q<0?C:_,q=[$+Q*Y*re,F,V+Q*J*re];ss(ee,this.fov,G/N,.1,P),en(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=ot(),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=w0(this.toneMapping),[h,p,g]=e?e.eyePos:on(this);for(let E of Ct)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 Ct)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),Qt(C.normalMatrix,this.modelMatrix);let P=C.extras?.xr?.stereo||C.userData?.xr?.stereo,R=0,$=0,F=1,V=1;P==="sbs"?(F=.5,R=v==="right"?.5:0):P==="ou"&&(V=.5,$=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,$,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 Ct)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=ot(),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),Qt(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]])}Zn(t,Y)}}else Zn(t,Y)}}};if(S(!1),A){for(let E of Ct)E.onBeforeTransmissivePass?.(t,this);S(!0)}for(let E of Ct)E.onAfterRender?.(t,this,s,v,[r,i,n,a],l)}disposeMeshListGpuResources(e,t){Ul(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 Ct)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()}};ar.registerPlugin=Rt,ar.getRegisteredPlugins=vl;function D0(e){return e+3&-4}var Ye=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function Ms(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function jl(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 Gl(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,$=f*b,F=w+C+$,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>$){let ee=2*Math.sqrt(Math.max(0,1+w-C-$));ee>1e-8&&(re=(_-R)/ee,V=.25*ee,Y=(N+S)/ee,J=(P+E)/ee)}else if(C>$){let ee=2*Math.sqrt(Math.max(0,1+C-w-$));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+$-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 k0(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 Tr=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function Hl(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:Tr(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function F0(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 ln(e,t){return ql(e,t)[0]}function ql(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=D0(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=k0(k.userData.xr);H.extensions={...H.extensions||{},MOZ_hubs_components:z,ANDROID_xr_scenecore:z},We().xrTraitSerializer?.gltfNode(H,k.userData.xr);let O=F0(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,Ie=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",Ge;if(k.castShadow&&qe){let Je=ne.shadow,kt=Math.max(256,Math.min(2048,Math.round(Ye(Je?.mapSize?.x??Je?.mapSize?.width,1024))));Ge={cast:!0,mapSize:kt<=384?256:kt<=768?512:kt<=1536?1024:2048,bias:Tr(Je?.bias,-.05,.05,-5e-4),normalBias:Tr(Je?.normalBias,0,.2,.015),radius:Tr(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:Ie>1e-6?[ge/Ie,Ae/Ie,Ee/Ie]:[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]}:{},...Ge?{shadow:Ge}:{}}),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:Ie,outerAngle:De,innerAngle:Fe,range:Ve,shadowSpec:Ge})}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),Ie=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),Ie<X[2]&&(X[2]=Ie),Ie>se[2]&&(se[2]=Ie)}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 Ie=v.indexOf(Ae);if(Ie===-1&&v.length<256&&(Ie=v.length,v.push(Ae)),Ie===-1)continue;let De=w(Ee),Be=ge.get(De);Be||(Be=[],ge.set(De,Be)),Be.push(Ie)}if(ge.size>0){let Ae=[];for(let[Ee,Ie]of ge.entries())Ae.push({material:Ee,variants:Ie});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),Ie=new Float32Array(ge*4),De=new Float32Array(ge*3);for(let Fe=0;Fe<ge;Fe++){let{t:Ve,r:qe,s:Ge}=Gl(Ae,Fe*16);Ee[Fe*3]=Ve[0],Ee[Fe*3+1]=Ve[1],Ee[Fe*3+2]=Ve[2],Ie[Fe*4]=qe[0],Ie[Fe*4+1]=qe[1],Ie[Fe*4+2]=qe[2],Ie[Fe*4+3]=qe[3],De[Fe*3]=Ge[0],De[Fe*3+1]=Ge[1],De[Fe*3+2]=Ge[2]}let Be={TRANSLATION:E(Ee,"VEC3",0,5126,ge),ROTATION:E(Ie,"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=jl(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),$=[];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&&$.push({name:"ProceduralLoop",samplers:Se,channels:ke})}let F=Qm(o,s,e.userData),V=[],Y=[],J=[];for(let k=0;k<o.length;k++){let G=o[k],q=Hl(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:Tr(H.pitch,.25,4,1)}}:{}});let ke=J.length,_e=Tr(H.refDistance,.05,100,1),Le=Tr(H.coneInnerAngle,0,360,360),ne=Tr(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:Tr(H.maxDistance,_e,500,Math.max(_e,25)),rolloffFactor:Tr(H.rolloffFactor,0,10,1),coneInnerAngle:+(Le*Math.PI/180).toFixed(6),coneOuterAngle:+(ne*Math.PI/180).toFixed(6),coneOuterGain:Tr(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}],...$.length>0?{animations:$}:{},...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 _s(e){return new TextEncoder().encode(e)}function ea(e,t){let{gltf:r,bin:i}=ln(e,t),n=JSON.stringify(r),a=_s(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 B0(e,t){let[r,i]=ql(e,t);return Wl(r,i)}function Wl(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,_)=>Ms(x,un(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,$=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);$[V++]=J>>16&255,V<$.length&&($[V++]=J>>8&255),V<$.length&&($[V++]=J&255)}return $}function b(C,_,P){let R=C?.index;if(typeof R!="number")return;let $=h[R],F=$?.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 $.sampler=="number"?g[$.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),$=P.byteLength||0;return{acc:_,buffer:s.slice(R,R+$)}}function S(C,_,P,R){let $=[],F=f[C];if(!F)return $;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,Ie=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||Ie||Ae||Be)&&(Re=[ce,Ne,Ie,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))}$.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 $}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],$=(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=Gl(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($(ne,se,H)),O.push(F(Re,se,te)),X.push($(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=$(O,he,[0,0,0]),ge=F(X,he,[0,0,0,1]),Ae=$(se,he,[1,1,1]);for(let Ee of ne){let Ie=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?[Ie[0]*ce[he*3],Ie[1]*ce[he*3+1],Ie[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)??Fl(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 un(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 ta(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function $t(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 Pr=(e,t,r)=>`(${$t(e)}, ${$t(t)}, ${$t(r)})`,cn=(e,t,r,i)=>`(${$t(e)}, ${$t(t)}, ${$t(r)}, ${$t(i)})`;function Kl(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=Pr(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function z0(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${$t(e[i*2])}, ${$t(1-e[i*2+1])})`;return r.join(", ")}function V0(e){return Array.from(e).join(", ")}function U0(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=un(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 = ${$t(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,W,T,E,S]=g.textures||[],O=(I,H)=>`.connect = <${P}/${I}.outputs:${H}>`,k=F?`color3f inputs:diffuseColor${O("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${dt(x,b,v)}`,w=W?`float inputs:metallic${O("MetallicRoughnessTexture","b")}
269
- float inputs:roughness${O("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${ze(g.metallic)}
270
- float inputs:roughness = ${ze(g.roughness)}`,ie="";g.clearcoat>0&&(ie+=`float inputs:clearcoat = ${ze(g.clearcoat)}
271
- `,ie+=`float inputs:clearcoatRoughness = ${ze(g.clearcoatRoughness)}
272
- `),g.ior!==1.5&&(ie+=`float inputs:ior = ${ze(g.ior)}
273
- `),g.opacity<1&&(ie+=`float inputs:opacity = ${ze(g.opacity)}
274
- `),E?ie+=`color3f inputs:emissiveColor${O("EmissiveTexture","rgb")}
275
- `:(p>0||y>0||M>0)&&(ie+=`color3f inputs:emissiveColor = ${dt(p,y,M)}
276
- `),T&&(ie+=`normal3f inputs:normal${O("NormalTexture","rgb")}
277
- `),S&&(ie+=`float inputs:occlusion${O("OcclusionTexture","r")}
278
- `);let oe="";if(F||W||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,$,F]=y.textures||[],V=(G,q)=>`.connect = <${C}/${G}.outputs:${q}>`,Y=_?`color3f inputs:diffuseColor${V("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${Pr(A,b,w)}`,J=P?`float inputs:metallic${V("MetallicRoughnessTexture","b")}
234
+ float inputs:roughness${V("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${$t(y.metallic)}
235
+ float inputs:roughness = ${$t(y.roughness)}`,re="";y.clearcoat>0&&(re+=`float inputs:clearcoat = ${$t(y.clearcoat)}
236
+ `,re+=`float inputs:clearcoatRoughness = ${$t(y.clearcoatRoughness)}
237
+ `),y.ior!==1.5&&(re+=`float inputs:ior = ${$t(y.ior)}
238
+ `),y.opacity<1&&(re+=`float inputs:opacity = ${$t(y.opacity)}
239
+ `),$?re+=`color3f inputs:emissiveColor${V("EmissiveTexture","rgb")}
240
+ `:(S>0||E>0||N>0)&&(re+=`color3f inputs:emissiveColor = ${Pr(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||$||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,N,z,ue)=>{if(!N)return;let he=N.scale?`float4 inputs:scale = ${Pr(N.scale[0],N.scale[1],N.scale[2],N.scale[3])}
285
- `:"",B=N.bias?`float4 inputs:bias = ${Pr(N.bias[0],N.bias[1],N.bias[2],N.bias[3])}
286
- `:"";oe+=`def Shader "${H}"
249
+ `;let G=(q,H,te,Z)=>{if(!H)return;let ae=H.scale?`float4 inputs:scale = ${cn(H.scale[0],H.scale[1],H.scale[2],H.scale[3])}
250
+ `:"",ie=H.bias?`float4 inputs:bias = ${cn(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 = @${Rr(N.file)}@
290
- float2 inputs:st${O("PrimvarReader","result")}
291
- token inputs:sourceColorSpace = "${z}"
292
- token inputs:wrapS = "${N.wrapS||"repeat"}"
293
- token inputs:wrapT = "${N.wrapT||"repeat"}"
294
- ${he}${B}${ue}}
295
- `};I("DiffuseTexture",F,"sRGB",`float3 outputs:rgb
296
- `),I("MetallicRoughnessTexture",W,"raw",`float outputs:g
254
+ asset inputs:file = @${ta(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",$,"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${O("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,Rr)??[];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} = "${Rr(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 $=N?.usdLines(v,ta)??[];if(!$.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&&$.push(`string ${F} = "${ta(V)}"`)}$.length>0&&E.push(`customData = {
316
281
  dictionary xr = {
317
- ${T.join(`
282
+ ${$.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 $=v?.rigidBody??v?.physics,F=$?.body??$?.mode??$;_+=`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 = ${ze(T.mass)}
328
- `)}let F=Dn(f),W=F?`def SpatialAudio "AudioEmitter"
292
+ `,$?.mass>0&&Number.isFinite($.mass)&&(_+=`float physics:mass = ${$t($.mass)}
293
+ `)}let P=Hl(v),R=(P?`def SpatialAudio "AudioEmitter"
329
294
  {
330
- ${F.src?`asset inputs:file = @${Rr(F.src)}@
331
- `:""}uniform token inputs:auralMode = "${F.isGlobal?"nonSpatial":"spatial"}"
332
- uniform token inputs:playbackMode = "${F.loop?"loopFromStart":"onceFromStart"}"
333
- double gain = ${ze(F.volume)}
334
- }
335
- `:"";return{header:M,body:P,tail:W}},u=f=>{if(f.timeSamples&&f.timeSamples.times.length>0){let y=f.timeSamples,M=(T,E,S)=>y.times.map((O,k)=>`${ze(O)}: ${S(T?.[k]||E)}`).join(", "),P=M(y.translations,[0,0,0],T=>dt(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 Pr(T[3]/E,T[0]/E,T[1]/E,T[2]/E)}),W=M(y.scales,[1,1,1],T=>dt(T[0],T[1],T[2]));return`double3 xformOp:translate.timeSamples = { ${P} }
336
- quatf xformOp:orient.timeSamples = { ${F} }
337
- double3 xformOp:scale.timeSamples = { ${W} }
295
+ ${P.src?`asset inputs:file = @${ta(P.src)}@
296
+ `:""}uniform token inputs:auralMode = "${P.isGlobal?"nonSpatial":"spatial"}"
297
+ uniform token inputs:playbackMode = "${P.loop?"loopFromStart":"onceFromStart"}"
298
+ double gain = ${$t(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,$,F)=>E.times.map((V,Y)=>`${$t(V)}: ${F(R?.[Y]||$)}`).join(", "),C=N(E.translations,[0,0,0],R=>Pr(R[0],R[1],R[2])),_=N(E.rotations,[0,0,0,1],R=>{let $=Math.hypot(R[0],R[1],R[2],R[3])||1;return cn(R[3]/$,R[0]/$,R[1]/$,R[2]/$)}),P=N(E.scales,[1,1,1],R=>Pr(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 = ${dt(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,W=v[3]/y;(1-Math.abs(W)>1e-7||Math.hypot(M,P,F)>1e-7)&&(x+=`quatf xformOp:orient = ${Pr(W,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 = ${dt(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],O=f.positions[E*3+1],k=f.positions[E*3+2];S<x&&(x=S),S>p&&(p=S),O<b&&(b=O),O>y&&(y=O),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=Sr(f.materialName,"DefaultMaterial"),W=P>0?P===1?"3":"3, ".repeat(P-1)+"3":"",T=`float3[] extent = [${dt(x,b,v)}, ${dt(p,y,M)}]
344
- int[] faceVertexCounts = [${W}]
345
- int[] faceVertexIndices = [${nl(f.indices)}]
346
- point3f[] points = [${Vn(f.positions)}]
347
- `;return f.normals&&f.normals.length===f.positions.length&&(T+=`normal3f[] normals = [${Vn(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 = ${Pr(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 = ${cn(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 = ${Pr(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 $=0;$<y;$++){let F=v.positions[$*3],V=v.positions[$*3+1],Y=v.positions[$*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),_=un(v.materialName,"DefaultMaterial"),P=C>0?C===1?"3":"3, ".repeat(C-1)+"3":"",R=`float3[] extent = [${Pr(A,b,w)}, ${Pr(S,E,N)}]
309
+ int[] faceVertexCounts = [${P}]
310
+ int[] faceVertexIndices = [${V0(v.indices)}]
311
+ point3f[] points = [${Kl(v.positions)}]
312
+ `;return v.normals&&v.normals.length===v.positions.length&&(R+=`normal3f[] normals = [${Kl(v.normals)}] (
348
313
  interpolation = "vertex"
349
314
  )
350
- `),f.uvs&&f.uvs.length===g*2&&(T+=`texCoord2f[] primvars:st = [${il(f.uvs,g)}] (
315
+ `),v.uvs&&v.uvs.length===y*2&&(R+=`texCoord2f[] primvars:st = [${z0(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=_n(x,Sr(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=Ms(A,un(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=Ms(v,un(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],$=-_,F=-P,V=-R;A.direction&&A.direction.length>=3&&(A.type==="directional"?($=-A.direction[0],F=-A.direction[1],V=-A.direction[2]):($=A.direction[0],F=A.direction[1],V=A.direction[2]));let[Y,J,re,Q]=jl($,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 = ${Pr(_,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 = ${cn(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 = ${$t(q)}
340
+ float inputs:shaping:cone:softness = ${$t(te)}
341
+ `}c+=`def ${w} "${b}" (
342
+ prepend apiSchemas = ${S}
343
+ )
344
+ {
345
+ color3f inputs:color = ${Pr(E,N,C)}
346
+ float inputs:intensity = ${$t(A.intensity??1)}
347
+ bool inputs:shadow:enable = 1
348
+ ${G}${ee}}
349
+ `}c+=`}
350
+ `}return c+=`}
351
+ `,c}var ra=null;function Ss(e){if(!ra){ra=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;ra[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=ra[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function O0(e){let t=[],r=0,i=[];for(let f of e){let m=_s(f.filename),h=Ss(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 Xl(e){let t=[{filename:"model.usda",data:_s(U0(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 O0(t)}function ia(e){return Xl(B0(e))}function As(e){return Xl(Wl(sn(e)))}function Ts(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():As(e)}function Ps(e){let t=Ts(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function Ns(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),$=s(P._type);if($>R)P=P.swizzle("xyzw".slice(0,R));else{let F=[P];for(let V=$;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 $=[_];for(let F=R;F<P;F++)$.push(new p("const","float",[],[F===3?1:0]));return new p("construct",C,$)};class p{constructor(C,_,P,R,$,F){this.isTSLNode=!0,this._op=C,this._type=_,this._args=P,R!==void 0&&(this._val=R),$!==void 0&&(this._name=$),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,$]=m(this,C),F=f(_);return F._type!=="float"&&F._type!==$&&(F=h(F,$)),new p("mix",$,[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,$=f(C);return(R._type!=="float"||$._type!=="float")&&(R=h(R,P._type),$=h($,P._type)),new p("smoothstep",P._type,[R,$,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 $=this.sub(C).div(f(_).sub(C)).clamp(0,1);return f(P).mix(R,$)}}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,$=[],F=0;for(let Y of P)if(F+=s(Y._type),Y._op==="const"&&Y._val)for(let J of Y._val)$.push(J);else R=!1;if(R&&$.length>=_)return new p("const",N,[],$.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={},$=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=$.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),$.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 hn="GOOGLE_material_tsl",j0=128,G0=16,H0=3600,q0={positionLocal:"vec3",positionWorld:"vec3",normalLocal:"vec3",normalWorld:"vec3",viewDirection:"vec3",uv:"vec2",vertexColor:"vec4",instanceIndex:"float",time:"float"},W0={color:"vec3",opacity:"float",emissive:"vec3",roughness:"float",metalness:"float",normalScale:"float",bump:"vec3",position:"vec3"},K0=new Set(["neg","abs","sign","floor","ceil","fract","sqrt","exp","log","sin","cos","normalize"]),X0=new Set(["add","sub","mul","div","mod","pow","atan2","min","max"]),Yl={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"]},Y0=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,Q0=new Set(["__proto__","constructor","prototype"]);function Ql(e,t){let r=Math.abs(t)<1e-6?t<0?-1e-6:1e-6:t;return e-r*Math.floor(e/r)}function sr(e){return e==="vec4"?4:e==="vec3"?3:e==="vec2"?2:1}function Zl(e){return e===1?"float":e===2?"vec2":e===3?"vec3":e===4?"vec4":null}function Cs(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 yi(e,t){for(let r=0;r<t.length;r++)e=Math.imul((e^t.charCodeAt(r))>>>0,16777619)>>>0;return e}var Jl=new Float32Array(1),Z0=new Uint32Array(Jl.buffer);function J0(e,t){return Jl[0]=t,Math.imul((e^Z0[0])>>>0,16777619)>>>0}function Es(e,t){let r=sr(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 fn(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=Cs(E)?Es(E,S.value):null;if(Q0.has(w)||!Y0.test(w)||!Cs(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=yi(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"||!Cs(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=yi(l,`N${y}:${E}:${S}:`);for(let P of C)l=yi(l,`${P},`);let _=C.map(P=>o[P].type);if(E==="const"){let P=sr(S),R=b.value;if(C.length!==0||!Array.isArray(R)||R.length!==P)return ht("TL501",`Invalid const node ${y} on '${t}'.`);let $=[];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);$.push(Y),l=J0(l,Y)}o.push({op:E,type:S,args:[],value:$})}else if(E==="builtin"){let P=b.name;if(C.length!==0||typeof P!="string"||q0[P]!==S)return ht("TL501",`Invalid builtin at node ${y}.`);l=yi(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=yi(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)||Zl(P.length)!==S)return ht("TL501",`Invalid swizzle at node ${y}.`);let R=sr(_[0]);for(let $=0;$<P.length;$++)if("xyzw".indexOf(P[$])>=R)return ht("TL501",`Swizzle '.${P}' out of bounds at node ${y}.`);l=yi(l,P),o.push({op:E,type:S,args:C,mask:P})}else if(E==="construct"){let P=sr(S),R=_.reduce(($,F)=>$+sr(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(K0.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(X0.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 Yl){let[P,R]=Yl[E];if(C.length!==P.length||S!==R||P.some(($,F)=>_[F]!==$))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=W0[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=yi(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 ii(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 ep=["x","y","z","w"],eu=[[2,"vec2"],[3,"vec3"],[4,"vec4"]];function $i(e,t){return eu.map(([r,i])=>{let n=ep.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 tu(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);}",...$i("_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);}",...$i("_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));}",...$i("_tslPow",2)),e.clamp&&r.push("float _tslClamp(float a,float b,float c){return clamp(a,min(b,c),max(b,c));}",...$i("_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);}",...$i("_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);}",...$i("_tslAtan2",2)),e.norm&&r.push("float _tslNorm(float v){return abs(v)>1e-6?sign(v):0.0;}",...eu.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 tp={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function ru(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(ii);g=o==="float"?x[0]:`${o}(${x.join(",")})`;break}case"builtin":g=s.builtin==="time"?`_tslMod(uTslTime,${ii(3600)})`:tp[s.builtin]??"0.0";break;case"uniform":{let x=`uTslParams[${s.uniformSlot??0}]`,v=sr(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 iu(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=tu(na(e.nodes,e.vertexReachable,e.usesTime),!1),c=ru(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=tu(na(e.nodes,e.fragmentReachable,e.usesTime),!0),c=ru(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 rp={float:"float",vec2:"float2",vec3:"float3",vec4:"float4"},ip={float:"float",vec2:"vector2",vec3:"vector3",vec4:"vector4"};function or(e){return rp[e]||"float"}function ni(e){return ip[e]||"float"}function mn(e,t){if(t===1)return ii(e[0]??0);let r=[];for(let i=0;i<t;i++)r.push(ii(e[i]??0));return`(${r.join(", ")})`}function nu(e,t,r=""){let i;if(e&&typeof e=="object"&&"fragmentReachable"in e)i=e;else{let w=fn(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=or(w.type),E=sr(w.type);s.push(`${S} inputs:u_${w.slot} = ${mn(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=sr(w),N=`C_${o++}`;return l(N,`ND_constant_${ni(w)}`,or(w),[`${or(w)} inputs:value = ${mn(S,E)}`])},f=(w,S)=>{if(S==="float")return w;let E=sr(S),N=`B_${o++}`,C=[];for(let _=1;_<=E;_++)C.push(`float inputs:in${_}.connect = <${w}>`);return l(N,`ND_combine${E}_${ni(S)}`,or(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_${ni(S)}`,"float",[`${or(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 = ${ii(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=or(E),C=ni(E),_=sr(E),P=S.args[0]!==void 0?x[S.args[0]]:"",R=S.args[1]!==void 0?x[S.args[1]]:"",$=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 = ${mn(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=sr(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 = ${mn([-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 = ${mn([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($,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($,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 = <${$}>`,`${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_${ni(F)}`,"float",[`${or(F)} inputs:in1.connect = <${P}>`,`${or(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_${ni(F)}`,"float",[`${or(F)} inputs:in.connect = <${P}>`]);break;case"distance":{let re=l(`D_${o++}`,`ND_subtract_${ni(F)}`,or(F),[`${or(F)} inputs:in1.connect = <${P}>`,`${or(F)} inputs:in2.connect = <${R}>`]);x[w]=F==="float"?l(J,"ND_absval_float","float",[`float inputs:in.connect = <${re}>`]):l(J,`ND_magnitude_${ni(F)}`,"float",[`${or(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 Er=null;function gi(e){if(!Er){Er=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;Er[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=Er[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function al(e){let t=[],r=0,i=[];for(let h of e){let m=di(h.filename),c=gi(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 Un(e){let t=[{filename:"model.usda",data:di(sl(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 al(t)}function Nr(e){return Un(rl(e))}function yi(e){return Un(Fn(tr(e)))}function bi(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():yi(e)}function xi(e){let t=bi(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function wt(e,t,r,i){let n=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,n))}function ol(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function vi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ll(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function ul(e){let t=vi(e);if(!t)return null;let r=t.target;return{target:ol(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:wt(t.radius,.01,50,.5),speed:wt(t.speed,-20,20,.5),height:wt(t.height,-10,10,0),phase:wt(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var hl=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],cl=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],Nu=new Set(hl),Cu=new Set(cl);function On(e,t){let r=ll(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 Bn(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:vi(e);if(!t||t.enabled===!1)return null;let r=wt(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:wt(t.threshold,0,4,.8),radius:wt(t.radius,0,2,.5)}:null}function Mi(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:vi(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:On(t.color,"#38bdf8"),thickness:wt(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var ut=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 io{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 io(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}},zn=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}},wi=class no{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 no(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},Cr=class so{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 so(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}},Ot=class ao{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 ao;return t.copy(this),t}compose(t,r,i){return Qt(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 xr(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}},$n=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 Ke(this.elements,e.elements),this}},Ye=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,Lr=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,Hn={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},gt=class oo{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 Hn)this.setHex(Hn[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=>Ye(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=Ye(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(Ye(l(t+1/3)),Ye(l(t)),Ye(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(Ye((r>>16&255)/255),Ye((r>>8&255)/255),Ye((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(Ye(this.r),Ye(this.g),Ye(this.b))}convertLinearToSRGB(){return this.setRGB(Lr(this.r),Lr(this.g),Lr(this.b))}getHex(){let t=r=>Math.round(Lr(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 oo(this.r,this.g,this.b)}},Wn={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 lo{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 lo(new t(this.array),this.itemSize)}},Gn=class extends He{constructor(e,t){super(e instanceof Float32Array||Array.isArray(e)?e:new Float32Array(e),t)}},jn=class extends He{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},qn=class extends He{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},Ue=class uo{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 uo;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(){}},Ai=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)}},Xn=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)}},Kn=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,W=M-1;(c!==1||s>0)&&h.push(P,F,M),(c!==r||m<Math.PI)&&h.push(F,W,M)}}}this.setFromBuffers(o,a,u,h)}},Ti=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),W=Math.cos(P),T=Math.hypot(F,d,W)||1;if(a.push(v*F,p,v*W),u.push(F/T,d/T,W/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),W=Math.cos(P);a.push(x*F,v,x*W),u.push(0,b,0),h.push(W*.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)}},Yn=class extends Ti{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)}},Zn=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 Qn(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),W=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*W,p.y+o*T,p.z+o*E),u.push(W,T,E),h.push(v,y/l),b>0&&y>0){let S=x*(b-1)+y-1,O=S+x;m.push(S,O,S+1,O,O+1,S+1)}}}e.setFromBuffers(a,u,h,m)}var Jn=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),Qn(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)})}},Rt=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)}},es=class extends Rt{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)}},ts=class extends Rt{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)}},rs=class extends Rt{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)}},is=class extends Rt{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))}},Si=class extends Ue{constructor(e=[new ut(0,-.5),new ut(.5,0),new ut(0,.5)],t=12,r=0,i=Math.PI*2){super();let n=Array.isArray(e)&&e.length>=2?e:[new ut(.2,0),new ut(.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),W=(Number(P?.y)||0)-(Number(M?.y)||0),T=Math.hypot(W,F)||1;if(o.push(W/T*f,-F/T,W/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)}},ns=class extends Ue{constructor(e,t=64,r=1,i=8,n=!1){super(),Qn(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)})}},_r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ir=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new ut(1,1),this.offset=new ut(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},ss=class extends Ir{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 O=0;O<t.length;O+=d)c=Math.imul(c^(t[O]*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,gi(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,W=O=>{if(!Number.isFinite(O))return 0;let k=u&&O<=1?O*255:O;return k>0?k<255?k+.5|0:255:0};for(let O=0;O<m;O++){let k=O*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:W(t[oe]??0),H=a>=3||o===1030?W(t[oe+1]??0):I,N=a>=3?W(t[oe+2]??0):o===1030?0:I,z=a===4?W(t[oe+3]??255):o===1021?W(t[oe]??255):o===1025?W(t[oe+1]??255):255;g[b++]=I,v+=I,p+=v,g[b++]=H,v+=H,p+=v,g[b++]=N,v+=N,p+=v,g[b++]=z,v+=z,p+=v,y+=I,M+=H,P+=N,F+=z}v%=65521,p%=65521}x.setUint32(b,(p<<16|v)>>>0),x.setUint32(b+4,gi(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:Ye(y/T),E?M/T:Ye(M/T),E?P/T:Ye(P/T),F/T];let S=["data:image/png;base64,"];for(let O=0;O<g.length;O+=3){let k=g[O]<<16|(g[O+1]??0)<<8|(g[O+2]??0);S.push(_r[k>>18&63]+_r[k>>12&63]+(O+1<g.length?_r[k>>6&63]:"=")+(O+2<g.length?_r[k&63]:"="))}this.source=S.join("")}},as=class{load(e,t){let r=new Ir(e);return t?.(r),r}};function qe(e,t){return e!==void 0?Number(e):t}function Ri(e,t){return e!==void 0?!!e:t}var it=class{constructor(e={}){this.name=e.name||"",this.color=new gt(e.color??16777215),this.emissive=new gt(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=Ri(e.transparent,!1),this.wireframe=Ri(e.wireframe,!1),this.side=qe(e.side,2),this.doubleSided=Ri(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 gt(e.sheenColor??0),this.sheenRoughness=qe(e.sheenRoughness,0),this.transmission=qe(e.transmission,0),this.thickness=qe(e.thickness,0),this.attenuationColor=new gt(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(){}},nr=class extends it{},os=class extends it{},ls=class extends it{},us=class extends it{},hs=class extends it{},yt=class ho{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 wi,this.quaternion=new Cr,this.scale=new xe(1,1,1),this.matrix=new Ot,this.matrixWorld=new Ot,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 ho&&(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=>{ms(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 Ot;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 Ot().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 Cr){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 zt?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof At?new At(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}},cs=class extends yt{},At=class extends yt{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 Ai(.5,.5,.5)):new Ue,this.material=r instanceof it?r:r?(Pt("unsupported material","MeshStandardMaterial"),new nr({color:13421772})):new nr}};function ms(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=Ae().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var sr=1e4,Pi=class extends At{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>sr)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${sr})`);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(){}},ar=class extends yt{constructor(e=16777215,t=1){super(),this.color=new gt(e),this.intensity=Number(t),this.type="directional"}},Ei=class extends ar{constructor(e,t){super(e,t),this.type="ambient"}},fs=class extends ar{constructor(e,t){super(e,t),this.target=new yt,this.type="directional"}},Ni=class extends ar{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},Ci=class extends yt{},ps=class extends Ci{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)}},Li=class extends yt{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return Tt.validate(this),ir(this)}toGLB(){return Tt.validate(this),Tr(this)}toUSDZ(){return Tt.validate(this),Nr(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof At){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},_i=ir,Ii=Tr,ds=Nr,Tt=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(ms(o),o instanceof At||o.geometry?.attributes?.position?.count){if(i++,i>1e3&&s("MESHES",1e3,i),o instanceof Pi){let u=l("instance",o.count);(u<0||u>sr)&&s("INSTANCES",sr,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))}}},gs=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 gt(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){Tt.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=_i(e),s=Ii(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 ys(){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 bs=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=ys(),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=ys();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function ml(){}var or=new Proxy(ml,{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:or},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>or,construct:()=>or}),xs=(()=>{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 Dr(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Bt(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,Dr());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 vs,lr;function Ms(e){if(!Bt(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(lr===void 0||vs!==t){vs=t;try{lr=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!Bt(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{lr=null}}return lr?lr.createScriptURL(e):e}function fl(e){Ae().sandboxEngineSrc=e}function Di(){let e=Ae().sandboxEngineSrc;if(e)return e;if(xs)return xs;try{if(typeof document>"u")return null;let t=Dr(),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)&&Bt(n,{requireSameOrigin:!0}))return n}}catch{}return null}function ki(e,t){if(!Bt(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,Dr()).href}function pl(){let e=Di();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 ki(e,"sandbox engine")}function dl(e){Ae().sandboxIframeSrc=e}function ws(){let e=Ae().sandboxIframeSrc;if(e)return e;let t=Di();if(!t||!Bt(t))return null;let r=new URL(t,Dr());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function gl(){let e=ws();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 ki(e,"sandbox iframe")}function yl(e){Ae().allowClientScripts=e}function As(){return!!Ae().allowClientScripts}function bl(e){return ki(e,"procedural scene script")}var xl=["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 vl(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 W=m||s,T=h;if(h=null,m=null,r.THREE=d,r.scene=M,r.camera=P,r.renderer=F,T(W),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 W=c?(0,eval)(c(`(function (THREE, scene, camera, renderer) {
392
+ `,surfaceConnections:y,surfaceInputsUsda:b,usesTime:i.usesTime}}function ai(e,t,r,i){let n=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,n))}function np(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function Ls(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ap(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function sp(e){let t=Ls(e);if(!t)return null;let r=t.target;return{target:np(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:ai(t.radius,.01,50,.5),speed:ai(t.speed,-20,20,.5),height:ai(t.height,-10,10,0),phase:ai(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var op=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],lp=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],kg=new Set(op),Fg=new Set(lp);function au(e,t){let r=ap(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 su(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:Ls(e);if(!t||t.enabled===!1)return null;let r=ai(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:ai(t.threshold,0,4,.8),radius:ai(t.radius,0,2,.5)}:null}function Rs(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:Ls(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:au(t.color,"#38bdf8"),thickness:ai(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var lr=class Dm{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 Dm(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 km{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 km(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}},ou=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}},$s=class Fm{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 Fm(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},aa=class Bm{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 Bm(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}},Ii=class zm{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 zm;return t.copy(this),t}compose(t,r,i){return tn(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 en(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}},lu=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 Qt(this.elements,e.elements),this}},Zt=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,sa=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,uu={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},jr=class Vm{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 uu)this.setHex(uu[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=>Zt(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=Zt(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(Zt(s(t+1/3)),Zt(s(t)),Zt(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(Zt((r>>16&255)/255),Zt((r>>8&255)/255),Zt((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(Zt(this.r),Zt(this.g),Zt(this.b))}convertLinearToSRGB(){return this.setRGB(sa(this.r),sa(this.g),sa(this.b))}getHex(){let t=r=>Math.round(sa(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 Vm(this.r,this.g,this.b)}},Is=1234567,cu={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&&(Is=Number.isFinite(e)?e|0:0);let t=Is=Is+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 Um{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 Um(new t(this.array),this.itemSize)}},hu=class extends zt{constructor(e,t){super(e instanceof Float32Array||Array.isArray(e)?e:new Float32Array(e),t)}},fu=class extends zt{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},mu=class extends zt{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},It=class Om{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 Om;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(){}},Ds=class extends It{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)}},pu=class extends It{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)}},du=class extends It{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)}},ks=class extends It{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)}},gu=class extends ks{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)}},yu=class extends It{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 bu(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,$=R+v;m.push(R,$,R+1,$,$+1,R+1)}}}e.setFromBuffers(l,c,f,m)}var xu=class extends It{constructor(e=1,t=.4,r=64,i=8,n=2,a=3){super(),r=Math.floor(r),i=Math.floor(i),bu(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)})}},bi=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)}},vu=class extends bi{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)}},wu=class extends bi{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)}},Mu=class extends bi{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)}},_u=class extends bi{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))}},Fs=class extends It{constructor(e=[new lr(0,-.5),new lr(.5,0),new lr(0,.5)],t=12,r=0,i=Math.PI*2){super();let n=Array.isArray(e)&&e.length>=2?e:[new lr(.2,0),new lr(.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)}},Su=class extends It{constructor(e,t=64,r=1,i=8,n=!1){super(),bu(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)})}},oa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",la=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new lr(1,1),this.offset=new lr(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},Au=class extends la{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 $=0;$<t.length;$+=p)h=Math.imul(h^(t[$]*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,Ss(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=$=>{if(!Number.isFinite($))return 0;let F=c&&$<=1?$*255:$;return F>0?F<255?F+.5|0:255:0};for(let $=0;$<m;$++){let F=$*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,Ss(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/_:Zt(w/_),P?S/_:Zt(S/_),P?E/_:Zt(E/_),N/_];let R=["data:image/png;base64,"];for(let $=0;$<x.length;$+=3){let F=x[$]<<16|(x[$+1]??0)<<8|(x[$+2]??0);R.push(oa[F>>18&63]+oa[F>>12&63]+($+1<x.length?oa[F>>6&63]:"=")+($+2<x.length?oa[F&63]:"="))}this.source=R.join("")}},Tu=class{load(e,t){let r=new la(e);return t?.(r),r}};function Dt(e,t){return e!==void 0?Number(e):t}function Bs(e,t){return e!==void 0?!!e:t}var Nr=class{constructor(e={}){this.name=e.name||"",this.color=new jr(e.color??16777215),this._em=e.emissive!==void 0,this.emissive=new jr(e.emissive??0),this.emissiveIntensity=Dt(e.emissiveIntensity,1),this.roughness=Dt(e.roughness,e.roughnessMap?1:.5),this.metalness=Dt(e.metalness,e.metalnessMap?1:0),this.opacity=Dt(e.opacity,1),this.transparent=Bs(e.transparent,!1),this.wireframe=Bs(e.wireframe,!1),this.side=Dt(e.side,2),this.doubleSided=Bs(e.doubleSided,!0),this.map=e.map||null,this.normalMap=e.normalMap||null;let t=e.normalScale;this.normalScale=typeof t=="number"?new lr(t,t):new lr(Dt(t?.x,1),Dt(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=Dt(e.aoMapIntensity,1),this.bumpMap=e.bumpMap||null,this.bumpScale=Dt(e.bumpScale,1),this.clearcoat=Dt(e.clearcoat,0),this.clearcoatRoughness=Dt(e.clearcoatRoughness,0),this.sheen=Dt(e.sheen,0),this.sheenColor=new jr(e.sheenColor??0),this.sheenRoughness=Dt(e.sheenRoughness,0),this.transmission=Dt(e.transmission,0),this.thickness=Dt(e.thickness,0),this.attenuationColor=new jr(e.attenuationColor??16777215),this.attenuationDistance=Dt(e.attenuationDistance,1/0),this.ior=Dt(e.ior,1.5),this.dispersion=Dt(e.dispersion,0),this.iridescence=Dt(e.iridescence,0),this.iridescenceIOR=Dt(e.iridescenceIOR,1.3)}dispose(){}},pn=class extends Nr{},Pu=class extends Nr{},Nu=class extends Nr{},Cu=class extends Nr{},Eu=class extends Nr{},Gr=class jm{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 $s,this.quaternion=new aa,this.scale=new Ze(1,1,1),this.matrix=new Ii,this.matrixWorld=new Ii,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 jm&&(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=>{Ru(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 Ii;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 Ii().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 aa){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 ki?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof si?new si(this.geometry,this.material):new this.constructor;if(this instanceof xi){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 to&&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}},Lu=class extends Gr{},si=class extends Gr{constructor(e,t){super(),this.isMesh=!0;let r=Array.isArray(t)?t[0]:t;this.geometry=e instanceof It?e:e?(ui("unsupported geometry","BoxGeometry"),new Ds(.5,.5,.5)):new It,this.material=r instanceof Nr?r:r?(ui("unsupported material","MeshStandardMaterial"),new pn({color:13421772})):new pn}};function Ru(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=We().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var dn=1e4,zs=class extends si{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>dn)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${dn})`);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(){}},Vs=class Gm{constructor(){this.mapSize=new lr(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 Gm().copy(this)}},xi=class extends Gr{constructor(e=16777215,t=1){super(),this.isLight=!0,this.shadow=new Vs,this.color=new jr(e),this.intensity=Number(t),this.type="directional"}},Us=class extends xi{constructor(e,t){super(e,t),this.type="ambient"}},$u=class extends xi{constructor(e,t){super(e,t),this.target=new Gr,this.type="directional"}},Os=class extends xi{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},js=class extends Gr{},Iu=class extends js{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)}},Gs=class extends Gr{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return oi.validate(this),ln(this)}toGLB(){return oi.validate(this),ea(this)}toUSDZ(){return oi.validate(this),ia(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof si){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},Hs=ln,qs=ea,Du=ia;We().makePngDeflater=$l;var oi=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(Ru(o),o instanceof si||o.geometry?.attributes?.position?.count){if(i++,i>1e3&&a("MESHES",1e3,i),o instanceof zs){let c=s("instance",o.count);(c<0||c>dn)&&a("INSTANCES",dn,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))}}},ku=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 jr(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){oi.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=Hs(e),a=qs(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 Fu(){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 Bu=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=Fu(),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=Fu();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function up(){}var gn=new Proxy(up,{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:gn},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>gn,construct:()=>gn}),zu=(()=>{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 ua(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Di(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,ua());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 Vu,yn;function Uu(e){if(!Di(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(yn===void 0||Vu!==t){Vu=t;try{yn=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!Di(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{yn=null}}return yn?yn.createScriptURL(e):e}function cp(e){We().sandboxEngineSrc=e}function Ws(){let e=We().sandboxEngineSrc;if(e)return e;if(zu)return zu;try{if(typeof document>"u")return null;let t=ua(),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)&&Di(n,{requireSameOrigin:!0}))return n}}catch{}return null}function Ks(e,t){if(!Di(e))throw new Error(`SecurityError: Disallowed ${t} URL "${e}" (http:, https:, or blob: required).`);return new URL(e,ua()).href}function hp(){let e=Ws();if(!e)throw new Error("SecurityError: Could not locate Three-Live bundle URL for worker sandbox; set ThreeLiveElement.sandboxEngineSrc explicitly.");return Ks(e,"sandbox engine")}function fp(e){We().sandboxIframeSrc=e}function Ou(){let e=We().sandboxIframeSrc;if(e)return e;let t=Ws();if(!t||!Di(t))return null;let r=new URL(t,ua());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function mp(){let e=Ou();if(!e)throw new Error("SecurityError: Could not locate three-live-sandbox.html; set ThreeLiveElement.sandboxIframeSrc explicitly.");return Ks(e,"sandbox iframe")}function pp(e){We().allowClientScripts=e}function ju(){return!!We().allowClientScripts}function dp(e){return Ks(e,"procedural scene script")}var gp="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 $ of Object.keys(_)){let F=_[$],V=F&&F.size;R<64&&/^[0-9a-f]{16}$/.test($)&&(V===256||V===512||V===1024)&&F.rgba instanceof Uint8Array&&F.rgba.length===V*V*4&&(P[$]=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),$=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=$,V(F),typeof i.__THREE_LIVE_SCENE__=="function"){let Y=i.__THREE_LIVE_SCENE__(y,P,R,$);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=W(d,M,P,F);T&&typeof T.toGLB=="function"&&(M=T)}if(!x){d.SceneQuotaValidator&&d.SceneQuotaValidator.validate(M);let W=M.toGLB(),T=W instanceof ArrayBuffer?W:W.buffer.slice(W.byteOffset,W.byteOffset+W.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 Fi(e,t,r){let i=r?.allowedScriptUrl??null,n=r?.allowClientScripts??i===null,s={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:n,revoked:xl},l=(Ae().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${vl.toString()})(${JSON.stringify(s)},[${l}]);`}function Ts(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 St=0;function Ss(){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 Ml(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var wl=1024,Al=256;function Rs(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 Vi(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,wl)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let n of i)if(!Rs(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>Al||o==="__proto__"||o==="constructor"||o==="prototype")return null;let a=l[o];if(!Rs(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 Tl(e){let t=Ml(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Ps(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 Sl(e,t,r,i){let n=Ss(),s=Fi(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,St++;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=Vi(x,n);b&&Ps(b,i,c,u)};c=()=>{o||(o=!0,h!==void 0&&clearTimeout(h),St=Math.max(0,St-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(),Ts(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 Es(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(St>=32)return i(`SecurityError: ${St} 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=pl()}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=gl()}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(Sl(e,n,c,r))}catch(d){return Promise.reject(d)}}let s=Ss(),l=Fi(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=Ms(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.")}St++;let a=!1,u={modelDispatched:!1},h,m=()=>{a||(a=!0,h!==void 0&&clearTimeout(h),St=Math.max(0,St-1),o.terminate())};return h=setTimeout(()=>{a||(m(),Ts(r))},3e3),o.onmessage=c=>{let d=Vi(c.data,s);d&&Ps(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 Ns(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 Cs=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},kr={execute(e,t,r,i){let n=Cs(r),s=Ns(t,n);if(s)return s;try{Tl(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??As()?Es({kind:"script",script:e},t,r,n):n(on,ln)},executeUrl(e,t,r){let i=Cs(r),n=Ns(t,i);if(n)return n;let s;try{s=bl(e)}catch(l){let o=l instanceof Error?l.message:String(l);return i(o,"Security Error: disallowed scene script URL.")}return Es({kind:"url",scriptUrl:s},t,r,i)}},Fr=new Set;function Pt(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;Fr.has(r)||(Fr.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function Ls(){return Array.from(Fr)}function _s(){Fr.clear()}var Ui=class extends nr{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}},Is=Ui,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)}},Rl=Et,Ds=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)}},Vr=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],ks=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],Fs=class extends Et{constructor(e=1,t=0){super(Vr,ks,e,t)}},Ie=(1+Math.sqrt(5))/2,Vs=class extends Et{constructor(e=1,t=0){super([-1,Ie,0,1,Ie,0,-1,-Ie,0,1,-Ie,0,0,-1,Ie,0,1,Ie,0,-1,-Ie,0,1,-Ie,Ie,0,-1,Ie,0,1,-Ie,0,-1,-Ie,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)}},et=1/Ie,Us=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,-et,-Ie,0,-et,Ie,0,et,-Ie,0,et,Ie,-et,-Ie,0,-et,Ie,0,et,-Ie,0,et,Ie,0,-Ie,0,-et,Ie,0,-et,-Ie,0,et,Ie,0,et],[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)}},Os=class extends Si{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 ut(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))))}},Oi=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),W=Math.sin(P);if(g.push(y*F,y*W,0),x.push(0,0,1),b.push(y/u*F*.5+.5,y/u*W*.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)}},Bs=class extends Oi{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},Bi=class extends it{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)}},Ur=class extends it{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)}},zs=class extends Ur{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function $s(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,W=(i[g*3+2]||0)-v,T=y*W-M*F,E=M*P-p*W,S=p*F-y*P,O=Math.hypot(T,E,S);if(!o&&O<1e-8)continue;O>0&&(T/=O,E/=O,S/=O);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 N=I<H?`${I}|${H}`:`${H}|${I}`,z=u[N];z?z.m||(z.m=1,z.nx*T+z.ny*E+z.nz*S<=a&&m(ie,oe)):(u[N]={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 Hs=class extends Ue{constructor(e){super(),this.setAttribute("position",new He($s(e),3)),this.__isSegmentPairs=!0}},Ws=class extends Ue{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new He($s(e,r),3)),this.__isSegmentPairs=!0}};function Pl(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,W=s[y*3+2]||0,T=(s[M*3]||0)-P,E=(s[M*3+1]||0)-F,S=(s[M*3+2]||0)-W,O=Math.hypot(T,E,S);if(O<1e-6)continue;let k=T/O,w=E/O,ie=S/O,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,N=Math.abs(w)<.9?-k/oe:w/oe,z=w*N-ie*H,ue=ie*I-k*N,he=k*H-w*I,B=d.length/3,$=[[I,H,N],[z,ue,he],[-I,-H,-N],[-z,-ue,-he]];for(let _=0;_<2;_++){let G=P+_*T,j=F+_*E,q=W+_*S;for(let D=0;D<4;D++){let Y=$[D];d.push(G+Y[0]*c,j+Y[1]*c,q+Y[2]*c),f.push(Y[0],Y[1],Y[2]),g.push(D/4,_)}}for(let _=0;_<4;_++){let G=(_+1)%4;x.push(B+_,B+G,B+4+G,B+_,B+4+G,B+4+_)}}return d.length>0&&i.setFromBuffers(d,f,g,x),i}function El(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=Vr[v*3],y=Vr[v*3+1],M=Vr[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+ks[v])}return r.setFromBuffers(a,u,h,m),r}var zt=class extends At{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},n=t instanceof it?t:r==="points"?new Bi(i):new Ur(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?El(this._sourceGeo,this.material?.size??.05):Pl(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},Gs=class extends zt{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},js=class extends zt{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},qs=class extends zt{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},Xs=class extends Ni{constructor(e,t,r=0,i=Math.PI/3,n=0,s=2){super(e,t,r,s),this.target=new yt,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}},zi=class extends Ei{constructor(e,t,r){Pt("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new gt(t??4473924)}},Ks=zi,Ys={Vector2:ut,Vector3:xe,Vector4:zn,Euler:wi,Quaternion:Cr,Matrix4:Ot,Matrix3:$n,Color:gt,MathUtils:Wn,BufferAttribute:He,Float32BufferAttribute:Gn,Uint16BufferAttribute:jn,Uint32BufferAttribute:qn,BufferGeometry:Ue,BoxGeometry:Ai,PlaneGeometry:Xn,SphereGeometry:Kn,CylinderGeometry:Ti,ConeGeometry:Yn,TorusGeometry:Zn,TorusKnotGeometry:Jn,Curve:Rt,Curve3:Rt,LineCurve3:es,QuadraticBezierCurve3:ts,CubicBezierCurve3:rs,CatmullRomCurve3:is,LatheGeometry:Si,TubeGeometry:ns,PolyhedronGeometry:Et,IcosahedronGeometry:Vs,OctahedronGeometry:Fs,DodecahedronGeometry:Us,TetrahedronGeometry:Ds,CapsuleGeometry:Os,RingGeometry:Oi,CircleGeometry:Bs,WireframeGeometry:Hs,EdgesGeometry:Ws,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:Ir,DataTexture:ss,TextureLoader:as,Material:it,MeshStandardMaterial:nr,MeshBasicMaterial:os,MeshLambertMaterial:ls,MeshPhongMaterial:us,MeshPhysicalMaterial:hs,PointsMaterial:Bi,LineBasicMaterial:Ur,LineDashedMaterial:zs,ShaderMaterial:Ui,RawShaderMaterial:Is,Object3D:yt,Group:cs,Mesh:At,InstancedMesh:Pi,Line:zt,LineLoop:Gs,LineSegments:js,Points:qs,Light:ar,AmbientLight:Ei,DirectionalLight:fs,PointLight:Ni,SpotLight:Xs,HemisphereLight:zi,RectAreaLight:Ks,Camera:Ci,PerspectiveCamera:ps,Scene:Li,WebGLRenderer:gs,Clock:bs,SceneQuotaValidator:Tt,exportSceneToCanvas3D:_i,exportSceneToGLB:Ii,exportSceneToUSDZ:ds,generateUSDZ:bi,glbToUSDZ:yi,sceneToCanvas3D:ir,sceneToGLB:Tr,sceneToUSDZ:Nr,authorScriptRunner:kr,getAuthorWarnings:Ls,clearAuthorWarnings:_s};Object.freeze(Tt),Object.freeze(Tt.prototype),Object.freeze(Li.prototype),Object.freeze(Ys);var $t=new Proxy(Ys,{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"),or)},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")}}),Or=Ae();if(Or.threeNamespace=$t,Or.workerExtensionInstallers)for(let e of Or.workerExtensionInstallers)e($t,Or);var ur={name:"three_author",THREE:$t},Nl=ur,bt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof bt.THREE>"u"&&(bt.THREE=$t),typeof bt.requestAnimationFrame!="function"&&(bt.requestAnimationFrame=e=>(typeof e=="function"&&typeof bt.__three_live_raf_cb__!="function"&&(bt.__three_live_raf_cb__=e),bt.__three_live_in_step__||Pt("requestAnimationFrame","single-frame static evaluation"),0)),typeof bt.cancelAnimationFrame!="function"&&(bt.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=$t,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=ur,e.ThreeLivePlugins.three_author=ur,e.ThreeLivePlugins["three-author"]=ur}function Br(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var $i=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),Cl=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 zr=class We extends Cl{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){We.scriptRunner=t}static defineModelViewer(t="model-viewer"){if(typeof customElements>"u")return!1;let r=customElements.get(t);if(r!=null)return r===We||r.prototype instanceof We;class i extends We{}return customElements.define(t,i),!0}static registerDecoder(t,r){Qe.registerDecoder(t,r)}static getDecoder(t){return Qe.getDecoder(t)}static registerAR(t){typeof t=="function"?We.arProvider={activateAR:t}:We.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof We&&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");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 Qe.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of Qe.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(Vt(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 Qe.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")||We.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 We.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 Vt(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 Br(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return Br(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():$i(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:$i(n,s,l),normal:$i(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=tr(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>.")),We.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 We.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&&We.arProvider.createUSDZBlob)try{let l=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:We.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 Qe(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 Qe.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")&&!!We.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 Qe.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=We.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,Qo,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(!We.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(on);return this.showToast(ln),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};zr.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"],zr.registerPlugin=Qe.registerPlugin,zr.getRegisteredPlugins=Qe.getRegisteredPlugins;var Ht=zr;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",Ht);function Ll(e="model-viewer"){return Ht.defineModelViewer(e)}function Zs(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function Hi(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 Qs(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 Js(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=kt(e,t,h,1)??Zs(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=kt(e,t,m,v)??Zs(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 hr(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]];Hi(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 cr=new WeakMap;function ea(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(o=>o.name===t);if(!i)return;let n=cr.get(e);n||(n=[],e.currentClip&&n.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),cr.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 Wi(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=cr.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")hr(d,m.time,s),Qs(f.t,f.t,s,c);else if(d.path==="rotation")hr(d,m.time,l),Hi(f.r,f.r,l,c);else if(d.path==="scale")hr(d,m.time,o),Qs(f.s,f.s,o,c);else if(d.path==="weights"&&(hr(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];Qt(c,f,d,g),u.push(c)}let h=vr(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]),Ke(m.normalMatrix,m.transform))}var Gi=e=>{cr.delete(e)},ta={name:"keyframes",evaluateAnimation:Wi,crossFadeTo:ea,onParseGLB(e){!e.animations&&e.gltf?.animations&&(e.animations=Js(e.gltf,e.bin))},onLoadModel:Gi,onClearScene:Gi,onDestroy:(e,t)=>Gi(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=cr.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),Wi(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),Wi(e,e.animationTime))}},mr=64;function _l(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 ra={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,$);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 Xs(e,t,r){let i=r?.allowedScriptUrl??null,n=r?.allowClientScripts??i===null,a={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:n,revoked:gp},s=(We().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${yp.toString()})(${JSON.stringify(a)},[${s}],(${$l.toString()}));`}function Gu(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 li=0;function Hu(){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 bp(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var xp=1024,vp=256;function qu(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 Ys(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,xp)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let n of i)if(!qu(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>vp||o==="__proto__"||o==="constructor"||o==="prototype")return null;let l=s[o];if(!qu(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 wp(e){let t=bp(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Wu(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 Mp(e,t,r,i){let n=Hu(),a=Xs(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,li++;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=Ys(v,n);y&&Wu(y,i,h,c)};h=()=>{o||(o=!0,f!==void 0&&clearTimeout(f),li=Math.max(0,li-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(),Gu(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 Ku(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(li>=32)return i(`SecurityError: ${li} workers running, meeting SECURITY_3D_MAX_CONCURRENT_TASKS (32).`,"Security Error: too many concurrent sandboxed scripts.");let n;try{n=hp()}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=mp()}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(Mp(e,n,h,r))}catch(p){return Promise.reject(p)}}let a=Hu(),s=Xs(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=Uu(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.")}li++;let l=!1,c={modelDispatched:!1},f,m=()=>{l||(l=!0,f!==void 0&&clearTimeout(f),li=Math.max(0,li-1),o.terminate())};return f=setTimeout(()=>{l||(m(),Gu(r))},3e3),o.onmessage=h=>{let p=Ys(h.data,a);p&&Wu(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 Xu(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 Yu=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},ca={execute(e,t,r,i){let n=Yu(r),a=Xu(t,n);if(a)return a;try{wp(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??ju()?Ku({kind:"script",script:e,texturePack:i?.texturePack},t,r,n):n(bl,xl)},executeUrl(e,t,r,i){let n=Yu(r),a=Xu(t,n);if(a)return a;let s;try{s=dp(e)}catch(o){let l=o instanceof Error?o.message:String(o);return n(l,"Security Error: disallowed scene script URL.")}return Ku({kind:"url",scriptUrl:s,texturePack:i?.texturePack},t,r,n)}},ha=new Set;function ui(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;ha.has(r)||(ha.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function Qu(){return Array.from(ha)}function Zu(){ha.clear()}var Qs=class extends pn{constructor(e={}){ui("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}},Ju=Qs,vi=class extends It{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)}},_p=vi,ec=class extends vi{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)}},Zs=e=>Array.from(e,t=>parseInt(t,36)),fa=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],tc=Zs("024043035052125153134142"),rc=class extends vi{constructor(e=1,t=0){super(fa,tc,e,t)}},Tt=(1+Math.sqrt(5))/2,ic=class extends vi{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],Zs("0b505101707a0ab1595b4ba2a7671839434232636838949524b62a867981"),e,t)}},yr=1/Tt,nc=class extends vi{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,-yr,-Tt,0,-yr,Tt,0,yr,-Tt,0,yr,Tt,-yr,-Tt,0,-yr,Tt,0,yr,-Tt,0,yr,Tt,0,-Tt,0,-yr,Tt,0,-yr,-Tt,0,yr,Tt,0,yr],Zs("3b737f3fd7jh7h676fh48h8aha680g8g282a0c101i0ig6a262d6df2gi2i323di19i9bib34ec4c0408b95b5jbj7j5eje4j4h1ce1e5159"),e,t)}},ac=class extends Fs{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 lr(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))))}},Js=class extends It{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)}},sc=class extends Js{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},eo=class extends Nr{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)}},ma=class extends Nr{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)}},oc=class extends ma{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function lc(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,$=Math.hypot(_,P,R);if(!o&&$<1e-8)continue;$>0&&(_/=$,P/=$,R/=$);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 uc=class extends It{constructor(e){super(),this.setAttribute("position",new zt(lc(e),3)),this.__isSegmentPairs=!0}},cc=class extends It{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new zt(lc(e,r),3)),this.__isSegmentPairs=!0}};function Sp(e,t,r=1){let i=new It;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,$=Math.hypot(_,P,R);if($<1e-6)continue;let F=_/$,V=P/$,Y=R/$,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 Ap(e,t=.05){let r=new It;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=fa[A*3],w=fa[A*3+1],S=fa[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+tc[A])}return r.setFromBuffers(l,c,f,m),r}var ki=class extends si{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},n=t instanceof Nr?t:r==="points"?new eo(i):new ma(i),a=e instanceof It?e:new It;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?Ap(this._sourceGeo,this.material?.size??.05):Sp(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},hc=class extends ki{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},fc=class extends ki{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},mc=class extends ki{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},pc=class extends Os{constructor(e,t,r=0,i=Math.PI/3,n=0,a=2){super(e,t,r,a),this.target=new Gr,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}},to=class extends xi{constructor(e,t,r){super(e,r),this.type="hemisphere",this.groundColor=new jr(t??4473924),this.position.set(0,1,0)}},dc=class extends Us{constructor(e,t){ui("RectAreaLight","AmbientLight"),super(e,t)}},gc={Vector2:lr,Vector3:Ze,Vector4:ou,Euler:$s,Quaternion:aa,Matrix4:Ii,Matrix3:lu,Color:jr,MathUtils:cu,BufferAttribute:zt,Float32BufferAttribute:hu,Uint16BufferAttribute:fu,Uint32BufferAttribute:mu,BufferGeometry:It,BoxGeometry:Ds,PlaneGeometry:pu,SphereGeometry:du,CylinderGeometry:ks,ConeGeometry:gu,TorusGeometry:yu,TorusKnotGeometry:xu,Curve:bi,Curve3:bi,LineCurve3:vu,QuadraticBezierCurve3:wu,CubicBezierCurve3:Mu,CatmullRomCurve3:_u,LatheGeometry:Fs,TubeGeometry:Su,PolyhedronGeometry:vi,IcosahedronGeometry:ic,OctahedronGeometry:rc,DodecahedronGeometry:nc,TetrahedronGeometry:ec,CapsuleGeometry:ac,RingGeometry:Js,CircleGeometry:sc,WireframeGeometry:uc,EdgesGeometry:cc,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:la,DataTexture:Au,TextureLoader:Tu,Material:Nr,MeshStandardMaterial:pn,MeshBasicMaterial:Pu,MeshLambertMaterial:Nu,MeshPhongMaterial:Cu,MeshPhysicalMaterial:Eu,PointsMaterial:eo,LineBasicMaterial:ma,LineDashedMaterial:oc,ShaderMaterial:Qs,RawShaderMaterial:Ju,Object3D:Gr,Group:Lu,Mesh:si,InstancedMesh:zs,Line:ki,LineLoop:hc,LineSegments:fc,Points:mc,LightShadow:Vs,Light:xi,AmbientLight:Us,DirectionalLight:$u,PointLight:Os,SpotLight:pc,HemisphereLight:to,RectAreaLight:dc,Camera:js,PerspectiveCamera:Iu,Scene:Gs,WebGLRenderer:ku,Clock:Bu,SceneQuotaValidator:oi,exportSceneToCanvas3D:Hs,exportSceneToGLB:qs,exportSceneToUSDZ:Du,generateUSDZ:Ts,glbToUSDZ:As,sceneToCanvas3D:ln,sceneToGLB:ea,sceneToUSDZ:ia,authorScriptRunner:ca,warnUnsupported:ui,getAuthorWarnings:Qu,clearAuthorWarnings:Zu};Object.freeze(oi),Object.freeze(oi.prototype),Object.freeze(Gs.prototype),Object.freeze(gc);var Fi=new Proxy(gc,{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("__")&&ui(`THREE.${t}`,"no-op proxy"),gn)},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")}}),pa=We();if(pa.threeNamespace=Fi,pa.workerExtensionInstallers)for(let e of pa.workerExtensionInstallers)e(Fi,pa);var bn={name:"three_author",THREE:Fi},Tp=bn,Hr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof Hr.THREE>"u"&&(Hr.THREE=Fi),typeof Hr.requestAnimationFrame!="function"&&(Hr.requestAnimationFrame=e=>(typeof e=="function"&&typeof Hr.__three_live_raf_cb__!="function"&&(Hr.__three_live_raf_cb__=e),Hr.__three_live_in_step__||ui("requestAnimationFrame","single-frame static evaluation"),0)),typeof Hr.cancelAnimationFrame!="function"&&(Hr.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=Fi,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=bn,e.ThreeLivePlugins.three_author=bn,e.ThreeLivePlugins["three-author"]=bn}function da(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var ro=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),Pp=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 ga=class di extends Pp{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===di||r.prototype instanceof di:(customElements.define(t,class extends di{}),!0)}static registerDecoder(t,r){ar.registerDecoder(t,r)}static getDecoder(t){return ar.getDecoder(t)}static registerAR(t){We().arProvider=typeof t=="function"?{activateAR:t}:t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof di&&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 ar.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 ar.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(Ri(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 ar.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")||di.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 di.isARSupported()}get toneMapping(){return Ri(this.getAttr("tone-mapping"))}set toneMapping(t){this.setAttr("tone-mapping",t)}get bloomThreshold(){return da(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return da(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():ro(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:ro(n,a,s),normal:ro(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=sn(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 ar(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 ar.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")&&di.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 ar.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,$0,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(bl);return this.showToast(xl),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};ga.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(" "),ga.registerPlugin=ar.registerPlugin,ga.getRegisteredPlugins=ar.getRegisteredPlugins;var wi=ga;{let e=wi.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",wi);function Np(e="model-viewer"){return wi.defineModelViewer(e)}var yc={eye:[0,1.6,5],target:[0,.8,0]},bc=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(" ")),Cp=["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(" ")),ya=[["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"]],xc={grey:"gray",golden:"gold",crimson:"red",maroon:"red",violet:"purple",aqua:"cyan",turquoise:"cyan",tan:"beige"},io={};function Cr(e,t){for(let r of e.split(" "))io[r]=t}Cr("left leftmost",["right",!1]),Cr("right rightmost",["right",!0]),Cr("front nearest closest frontmost",["depth",!1]),Cr("back farthest furthest rear far backmost",["depth",!0]),Cr("top highest upper topmost",["up",!0]),Cr("bottom lowest lower bottommost",["up",!1]),Cr("biggest largest big large huge bigger larger",["size",!0]),Cr("smallest small tiny little smaller",["size",!1]),Cr("tallest tall taller",["height",!0]),Cr("shortest short shorter",["height",!1]),Cr("middle center centre central","middle");var vc={first:0,second:1,third:2,fourth:3,fifth:4,last:-1},wc={two:2,pair:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10},Mc=new Set(["all","every","everything","each","everybody"]),no=e=>/^[0-9]+$/.test(e),ba=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ao=e=>ba(io,e)?io[e]:null,_c=e=>ba(vc,e)?vc[e]:null;function Sc(e){let t;if(ba(wc,e))t=wc[e];else if(/^[0-9]{1,3}$/.test(e))t=Number(e);else return null;return t>=1&&t<=50?t:null}function Ac(e){return ba(xc,e)?xc[e]:ya.some(t=>t[0]===e)?e:null}function Ep(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&&!ao(a)&&a!=="side"&&a!=="end")return!0}}return!1}function Lp(e){return String(e??"").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function Tc(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 Rp(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(Tc)}var $p=e=>e.replace(/[^A-Za-z0-9]/g,"").toLowerCase(),Ip=(e,t)=>Cp.some(r=>r.includes(e)&&r.includes(t));function Pc(e,t){return e===t||Ip(e,t)||t.length>=4&&e.length>=4&&(e.startsWith(t)||t.startsWith(e))}function so(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,.4166666666666667)-.055)*255}function Dp(e){let t=[so(e[0]),so(e[1]),so(e[2])],r=ya[0][0],i=1/0;for(let[n,a]of ya){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 kp=e=>ya.find(t=>t[0]===e)?.[2]??"";function Fp(e,t){return e.words.includes(t)?!0:e.colorName!=null&&(e.colorName===t||kp(e.colorName)===t)}function oo(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:Rp(t.name),colorName:t.color?Dp(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 Bp(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 Bi(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 Nc=e=>e.length?e.reduce((t,r)=>t+r,0)/e.length:0;function lo(e,t,r){let i;if(t==="middle"){if(e.length<3)return e;let n=e.map(o=>Bi(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=>Bi(s,t[0],r)),a=Nc(n);i=e.filter((s,o)=>t[1]?n[o]>a+1e-6:n[o]<a-1e-6)}return i.length?i:e}function Cc(e,t,r){let i;if(t==="middle"){let n=Nc(e.map(a=>Bi(a,"right",r)));i=e.map(a=>[a,Math.abs(Bi(a,"right",r)-n)])}else i=e.map(n=>[n,t[1]?-Bi(n,t[0],r):Bi(n,t[0],r)]);return i.sort((n,a)=>n[1]-a[1])}function Jt(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 Mi=e=>Jt([],"none",e);function Ec(e,t,r=yc,i){let n=i?e.filter(s=>i.includes(s.name)):[...e],a=Lp(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=uo(n,a.slice(0,s),r);if(f.confidence!=="high")return f;let m=n.filter(g=>f.ids.includes(g.id)),h=uo(m,a.slice(s+(c?1:2)),r);if(h.confidence!=="high")return Jt(m,"ambiguous","except");let p=m.filter(g=>!h.ids.includes(g.id));return p.length?Jt(p,"high","match"):Mi("no_match")}return uo(n,a,r)}function zp(e){return!(bc.has(e)||Mc.has(e)||e==="both"||Sc(e)!==null||_c(e)!==null||Ac(e)!==null||ao(e)!==null||no(e))}function uo(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(zp)))return Lc(e,t,r);let a=[],s=!1;for(let l of n){let c=Lc(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?Jt(o,"ambiguous","multiple"):Jt(o,"high","match")}function Lc(e,t,r){if(!e.length)return Mi("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=>$p(A.name)===n);if(y.length)return Jt(y,"high","exact")}if(Ep(t))return Mi("relation");let a=[],s=!1,o=!1,l=null,c=null,f=[],m=[],h=!1;for(let y of t){if(h&&no(y)){a.push(y);continue}h=!1;let A,b,w;if(Mc.has(y))o=!0,s=!0;else if(y==="both")l=2,s=!0;else if((A=Sc(y))!==null)l=A,s=s||A>1;else if((A=_c(y))!==null)c=A;else if((b=Ac(y))!==null)f.push(b);else if((w=ao(y))!==null)m.push(w);else if(!bc.has(y)){let S=Tc(y);S!==y&&(s=!0),a.push(S),h=!0}}if(!a.length&&!f.length&&!m.length&&c===null&&!o&&l===null)return Mi("empty");let p=Bp(r),g=e;if(a.length){let y=g.map(S=>({e:S,n:a.filter(E=>S.words.some(N=>Pc(N,E))).length})),A=Math.max(0,...y.map(S=>S.n));if(A===0)return Mi("no_match");g=y.filter(S=>S.n===A).map(S=>S.e);let b=S=>S.words.filter(E=>!no(E)&&!a.some(N=>Pc(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=>Fp(y,A)))),!g.length)return Mi("no_match");if(c!==null){for(let w of m)g=lo(g,w,p);let y=Cc(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 Mi("no_match");b=y.slice(w,w+A)}return Jt(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=lo(g,b,p);let y=Cc(g,m[m.length-1],p),A=v;if(y.length<A)return Jt(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 Jt(y.filter(w=>Math.abs(w[1]-b)<=1e-6).map(w=>w[0]),"ambiguous","multiple")}return Jt(y.slice(0,A).map(b=>b[0]),"high","match")}for(let y of m)g=lo(g,y,p);return x?g.length===1?Jt(g,"high","match"):Jt(g,"ambiguous","multiple"):l!==null&&g.length!==l?Jt(g,"ambiguous","count_mismatch"):Jt(g,"high","match")}var Rc="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(" "),xa=(e,t)=>{for(let r of t)if(e.startsWith(r))return e.slice(r.length).trim()||null;return null},co=(e,t)=>{for(let r of t)if(e.endsWith(r))return e.slice(0,-r.length).trim()||null;return null},ho=e=>e.replace(/[.!?,]+$/,"");function Vp(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||!Rc.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 $c(e,t){let r=e.split(/\s+/).filter(Boolean);return r.length&&ho(r[r.length-1]).toLowerCase()==="please"&&r.pop(),ho(r.slice(Math.max(0,r.length-t)).join(" "))}function fo(e,t,r){let[i,n]=Vp(t),a=co(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:$c(r,s)}}return{kind:"select",mode:e,query:i}}var Up=["please ","ok ","ok, ","okay ","okay, ","now ","now, ","hey ","um ","um, ","uh ","uh, ","so ","so, ","and "],Op=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"]),jp=["select only ","select just ","only select ","just select ","select ","pick ","choose ","highlight ","grab ","focus on "];function Ic(e){let t=String(e??"").trim(),r=t.toLowerCase().replace(/[\u2018\u2019]/g,"'").split(/\s+/).filter(Boolean).join(" ");for(r=ho(r);;){let n=r.length;for(let a of Up)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(),Op.has(r))return{kind:"clear",mode:"clear"};let i=xa(r,["deselect ","unselect ","don't select ","do not select "]);if(i!==null)return fo("remove",i,t);for(let n of["remove ","take "])if(r.startsWith(n)){let a=co(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=xa(r,["also select ","also pick ","also choose ","also add "]),i!==null)return fo("add",i,t);if(r.startsWith("add ")){let n=co(r.slice(4),[" to the selection"," to selection"]);if(n!==null)return{kind:"select",mode:"add",query:n}}return i=xa(r,jp),i!==null||(i=xa(r,["just ","only "]),i!==null&&!Rc.includes(i.split(" ")[0]))?fo("replace",i,t):{kind:"edit",instruction:$c(t,1/0)}}var Dc=50;function mo(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>=Dc)break}return t}function br(e){let t=e.__tlSelection??[],r=e.selectedMesh||null;return(t[0]??null)!==r?r?[r]:[]:[...t]}function Er(e,t,r={}){let i=r.mode??"replace",n=br(e),a=mo(typeof t=="string"?[t]:t??[]),s;switch(i){case"clear":s=[];break;case"add":s=mo([...n,...a]);break;case"remove":s=n.filter(f=>!a.includes(f));break;case"toggle":s=mo([...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 Gp(e){!e||e.__tlSelectionInstalled||(e.__tlSelectionInstalled=!0,"selectedMeshes"in e||Object.defineProperty(e,"selectedMeshes",{get:()=>br(e),set:t=>{Er(e,t??[],{mode:"replace",source:"api"})},configurable:!0}),e.addEventListener?.("three-load",()=>{let t=br(e);t.length>1&&e.viewer?.setSelectedMeshes?.(t)}))}function po(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 go=new WeakMap;function Hp(e){let t=e;if(go.has(t))return go.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 go.set(t,n),n}function va(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?Hp(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 yo(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 yc;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 kc(e,t,r={}){let i=oo(va(e));return Ec(i,t,yo(e),r.within??null)}var qp=["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(" "),zi=e=>Math.round(e*100)/100;function Fc(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(zi),target:r.target.map(zi),right:[zi(-n[2]/a),0,zi(n[0]/a)]},objects:e.slice(0,300).map(o=>({id:o.id,name:o.name,color:o.colorName,center:o.center.map(zi),size:zi(Math.cbrt(o.size))})),selected:i.slice(0,50),request:String(t).slice(0,500)};return[{role:"system",content:qp},{role:"user",content:JSON.stringify(s)}]}function Bc(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<Dc&&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 zc(e,t,r,i={}){let n=va(e);i.within&&(n=n.filter(o=>i.within.includes(o.name)));let a=oo(n);if(!a.length)return{names:[],confidence:"low",question:""};let s=await r.complete({messages:Fc(a,t,yo(e),br(e)),signal:i.signal});return Bc(s,a)}var Wp=32,Kp=32,Xp=80,Vc=2e3,wa=32*1024*1024,Yp=1024,Qp=256,Zp=2048,Uc=["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 Oc(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,Xp).join("")}function qr(e){let t=Math.round(e*100)/100;return(Object.is(t,-0)||Math.abs(t)<1e-9?0:t).toFixed(2)}function jc(e){let t=Math.round(e),r=Object.is(t,-0)?0:t;return String(r)}function Vi(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 Jp(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=Vi(e);return!t||t[0]<=0||t[1]<=0||t[2]<=0?null:t}function xn(e){return`[${qr(e[0])}, ${qr(e[1])}, ${qr(e[2])}]`}function bo(e){if(!e||typeof e!="object")return"";let t=[];if(typeof e.floorY=="number"&&Number.isFinite(e.floorY)&&t.push(`- Floor height: y = ${qr(e.floorY)} m`),e.camera&&typeof e.camera=="object"){let r=Vi(e.camera.eye),i=Vi(e.camera.target);if(r&&i){let n=`- Camera: eye ${xn(r)}, target ${xn(i)}`,a=Number(e.camera.fovDeg);Number.isFinite(a)&&a>=1&&a<=179&&(n+=`, fov ${jc(a)} deg`),t.push(n)}}if(Array.isArray(e.planes)){let r=[];for(let i of e.planes){if(r.length>=Wp)break;if(!i||typeof i!="object")continue;let n=Vi(i.center);if(!n)continue;let a=String(i.orientation??"").toLowerCase()==="vertical"?"vertical":"horizontal",s=Oc(i.label),o=Jp(i.extent),l=Vi(i.normal),c=` ${r.length+1}. ${a}`;s&&(c+=` "${s}"`),c+=` at ${xn(n)}`,o&&(c+=`, extent ${qr(o[0])}m x ${qr(o[1])}m`),l&&(c+=`, normal ${xn(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>=Kp)break;if(!i||typeof i!="object")continue;let n=Oc(i.label),a=Vi(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 ${xn(a)}`;s&&(l+=`, size ${qr(s[0])}m x ${qr(s[1])}m x ${qr(s[2])}m`),o!==null&&(l+=`, yaw ${jc(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 Dr(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 Gc(e,t){let r=`Reconstruct the 3D scene shown in this reference image as a complete Three-Live script.
409
+ `;r+=bo(t);let i=Array.from(String(e??"").trim()).slice(0,Vc).join("");return i&&(r+=`Additional instructions: ${i}
410
+ `),r+="Return only the complete script in a single ```js code block.",r}function Hc(e,t,r){let i=String(e??"").trim();if(!Dr(i))throw new Error("compileFromImage: imageUrl must be a base64 data:image/(png|jpeg|webp) URI or an https:// URL.");let n=Gc(t,r);return[{role:"system",content:Uc},{role:"user",content:[{type:"image_url",image_url:{url:i}},{type:"text",text:n}]}]}function qc(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 Wc(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 td(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(Qp,Math.min(Zp,Math.round(t))):Yp}function Ma(e){if(e.byteLength===0)throw new Error("compileFromImage: image buffer is empty.");if(e.byteLength>wa)throw new Error("compileFromImage: image exceeds the 32 MB limit.");let t=Wc(e);if(!t)throw new Error("compileFromImage: unsupported image format (expected PNG, JPEG, or WebP magic bytes).");return`data:${t};base64,${td(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(Dr(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(Dr(m))return m}}}catch{}if(typeof l.toDataURL=="function")try{let c=l.toDataURL("image/jpeg",.88);if(Dr(c))return c}catch{}return null}async function xo(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(!Dr(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)>wa)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)&&!Dr(s))throw new Error("compileFromImage: remote image URLs must use https:// (or http:// on localhost).");let o=/^https?:/i.test(s)&&Dr(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)&&!Dr(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>wa)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 Ma(new Uint8Array(h))}if(e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]")return Ma(new Uint8Array(e));if(ArrayBuffer.isView(e))return Ma(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>wa)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 Ma(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(Dr(s))return s}if(typeof i.src=="string"&&i.src.trim())return xo(i.src,t);throw new Error("compileFromImage: unsupported or unloaded image source.")}async function Kc(e,t,r={}){if(!e?.allowClientScripts)throw new Error("compileFromImage requires client scripts: add the allow-client-scripts attribute.");let i=Ro(e,r,"compileFromImage"),n=$o(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,Vc).join(""),c=bo(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 xo(t,{maxEdge:r.maxEdge,signal:o,fetch:r.fetch});if(o.aborted)throw o.reason;let A=Hc(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=Lo(w),p=[],!m)h="The model reply did not contain a scene script.";else if(new TextEncoder().encode(m).length>Ah)h="The generated script exceeds the 1 MB script limit.";else try{let S=await Eh(e,m,o,"compileFromImage");p=[...S.warnings];let E=Ch(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:qc(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>Th&&y.shift()}e.__tlAiSource=m,Er(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 vo="three-live-texture-pack",wo=1,Xc=64,Yc=6*1024*1024,_a=16*1024*1024,nd=64*1024*1024,Qc=" Seamless tileable PBR albedo texture, flat even lighting, orthographic top-down view, no perspective, no shadows, no text.";function Zc(){return We()}function Jc(e){let t=Zc().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 ad(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 Sa(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 sd(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 od(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 eh(e){let t=String(e?.endpoint??"");if(!ad(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+Qc,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 Sa(g.b64_json,_a);let x=typeof g?.url=="string"?g.url:"";if(x.startsWith("data:image/"))return Sa(x.slice(x.indexOf(",")+1),_a);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>_a)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 th(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 Aa={async decode(e){let t=th(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=Zc().encodeRgbaPngDataUri;if(typeof r=="function"){let i=r(e,t,t),n=Sa(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 ld(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 ud(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 rh(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:ld(a,r,r,t,t);for(let o=3;o<s.length;o+=4)s[o]=255;return ud(s,t)}async function ih(e,t=Aa){let r=typeof e=="string"?JSON.parse(e):e;if(!r||r.format!==vo)throw new Error(`texture pack: format must be "${vo}"`);if(r.version!==wo)throw new Error(`texture pack: version must be ${wo}`);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>Xc)throw new Error(`texture pack: more than ${Xc} 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=Jc(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=Sa(l.slice(c.length),Yc);if(f.length>Yc||th(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 nh(e,t=Aa){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,${sd(a)}`,...n.provenance?{provenance:n.provenance}:{}}}return{format:vo,version:wo,entries:r}}function cd(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 Mo(e){let t=new Map;for(let r of cd(e)?.nodes??[]){let i=r?.extras?.xr?.material;if(!i||typeof i!="object"||i.prompt==null)continue;let n=Jc(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 ah(e=nd){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 vn=null,sh=!1;function kr(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 hd(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 fd(){let e=We(),t=e.scriptRunner;if(!t||t.__tlTexWrapped)return;let r=i=>vn&&!i?.texturePack?{...i,texturePack:vn}: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 oh(e,t){fd();let r=vn;vn=hd(e);try{return t()}finally{vn=r}}function lh(e,t){let r=t??e.aiImageProvider;if(r&&typeof r.generateImage=="function")return r;let i=e.getAttribute?.("ai-image-endpoint");return i?eh({endpoint:i,model:e.getAttribute?.("ai-image-model")||void 0}):null}function uh(e){if(e.textureCache!==void 0)return e.textureCache;let t=kr(e);return t.cache===void 0&&(t.cache=ah()),t.cache}function _o(e){return e.textureCodec??Aa}function wn(e){let t=e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent,r=kr(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 ch(e,t){let r=kr(e);r.pack.set(t.key,t),r.packJson=null,r.failed.delete(t.key)}async function hh(e,t){let r=uh(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&&(ch(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 fh(e,t,r,i){let n=kr(e),a=n.inflight.get(r.key);if(a)return a;let s=(async()=>{try{let o=await od(await t.generateImage({...r.spec,signal:i}));if(o.length>_a)throw new Error("generated image exceeds 16 MB");let l=rh(await _o(e).decode(o),r.spec.size),c={provider:t.name??"custom",...t.model?{model:t.model}:{},createdAt:new Date().toISOString()};return ch(e,{key:r.key,spec:r.spec,rgba:l,provenance:c}),uh(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 md(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 mh(e,t){let r=kr(e);r.lastModel=t;let i;try{i=Mo(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 hh(e,n)).length){await wn(e).catch(()=>{});return}if((e.getAttribute?.("ai-textures")||"auto").toLowerCase()==="manual")return;let a=lh(e);if(!a)return;e.fireEvent?.("three-live-texture-start",{keys:n.map(o=>o.key)});let s=(await Promise.all(n.map(o=>fh(e,a,o)))).filter(Boolean).length;s&&(sh||(sh=!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 wn(e).catch(()=>{}))})()}function ph(e,t){kr(e).lastRun=t}async function So(e,t){let r=kr(e),i=++r.loadSeq;if(t==null){r.pack=new Map,r.packJson=null,await wn(e).catch(()=>{});return}try{let n=await ih(t,_o(e));if(i!==r.loadSeq)return;r.pack=n,r.packJson=typeof t=="string"?JSON.parse(t):t,r.failed.clear(),await wn(e).catch(()=>{})}catch(n){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(n?.message||n)})}}async function dh(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 So(e,await i.json())}catch(r){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(r?.message||r)})}}async function pd(e,t={}){let r=kr(e),i=t.meshes?new Set(t.meshes):null,n=Mo(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 hh(e,n));a.push(...c),l=n.filter(f=>!c.has(f.key))}if(l.length){let c=lh(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 md(l,f,async h=>{r.failed.delete(h.key),t.force&&r.pack.delete(h.key),await fh(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 wn(e).catch(()=>{}),{generated:s,cached:a,failed:o,pack:await gh(e)}}async function gh(e){let t=kr(e);return t.packJson??(t.packJson=await nh(t.pack,_o(e)))}function dd(e){if(!e||e.__tlTexInstalled)return;e.__tlTexInstalled=!0,kr(e),Object.defineProperty(e,"texturePack",{get:()=>e.__tlTex?.packJson??null,set:n=>{So(e,n)},configurable:!0}),e.generateTextures=n=>pd(e,n),e.exportTexturePack=()=>gh(e);let t=e.querySelector?.('script[type="application/three-live-texture-pack"]');t?.textContent?.trim()&&So(e,t.textContent);let r=e.getAttribute?.("texture-pack");r&&dh(e,r);let i=e;typeof MutationObserver<"u"&&i&&typeof i.nodeType=="number"&&new MutationObserver(()=>{let n=e.getAttribute?.("texture-pack");n&&dh(e,n)}).observe(i,{attributes:!0,attributeFilter:["texture-pack"]})}var Ta=12;function Pa(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 gd(e){if(typeof document>"u")return!1;let t=(e.getAttribute?.("ai-select-chips")??"").toLowerCase();return t!=="off"&&t!=="false"}function Na(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 Ca(e){let t=e.__tlChips;t&&(t.off(),t.root.remove(),e.__tlChips=null)}function yh(e,t,r){if(!gd(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&&Ea(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 Ea(e,t,r),i.root}function Ea(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,Ta))n.appendChild(Na(Pa(s),`Select ${Pa(s)}`,()=>{Er(e,[s],{mode:t.mode==="add"||t.mode==="remove"?t.mode:"replace",source:"tap",query:t.query}),Ea(e,{pending:t.pending},r)}))}else{let s=br(e);if(!s.length&&!t.pending){Ca(e);return}a(s.length?"Selected:":"Nothing selected");for(let o of s.slice(0,Ta))n.appendChild(Na(`${Pa(o)} \xD7`,`Remove ${Pa(o)} from the selection`,()=>Er(e,[o],{mode:"remove",source:"tap"})));if(s.length>Ta&&a(`+${s.length-Ta} more`),t.pending&&r&&s.length){let o=t.pending;n.appendChild(Na(`Apply: ${o.slice(0,40)}`,`Apply: ${o.slice(0,200)}`,()=>{Ea(e,{},r),r(o)},!0))}}n.appendChild(Na("\u2715","Dismiss",()=>Ca(e)))}var yd=500,Ui=2e3,bd=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."}}}}],vd=["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 wd(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 Md(e){if(!wd(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 St(e){return typeof e=="string"?e:""}function xr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ao(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)?Ao(a,n):n}return r}function bh(e){if(e&&typeof e=="object")return xr(e);try{return xr(JSON.parse(St(e)||"{}"))}catch{return{}}}var xh={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:Ao(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(St(e.type)){case"response.output_audio.delta":case"response.audio.delta":return St(e.delta)?[{type:"audio",base64:St(e.delta),rate:24e3}]:[];case"response.output_audio_transcript.delta":case"response.audio_transcript.delta":return[{type:"transcript",speaker:"model",text:St(e.delta),isFinal:!1}];case"response.output_audio_transcript.done":case"response.audio_transcript.done":return[{type:"transcript",speaker:"model",text:St(e.transcript),isFinal:!0}];case"conversation.item.input_audio_transcription.delta":return[{type:"transcript",speaker:"user",text:St(e.delta),isFinal:!1}];case"conversation.item.input_audio_transcription.completed":return[{type:"transcript",speaker:"user",text:St(e.transcript),isFinal:!0}];case"response.function_call_arguments.done":return[{type:"toolCall",id:St(e.call_id)||St(e.item_id),name:St(e.name),args:bh(e.arguments)}];case"input_audio_buffer.speech_started":return[{type:"interrupted"}];case"response.done":return[{type:"turnComplete"}];case"error":return[{type:"error",message:St(xr(e.error).message)||"Realtime server error"}];default:return[]}}},vh={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:Ao(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=xr(e.serverContent);r.interrupted&&t.push({type:"interrupted"});let i=xr(r.inputTranscription);St(i.text)&&t.push({type:"transcript",speaker:"user",text:St(i.text),isFinal:!1});let n=xr(r.outputTranscription);St(n.text)&&t.push({type:"transcript",speaker:"model",text:St(n.text),isFinal:!1});let a=xr(r.modelTurn).parts;for(let l of Array.isArray(a)?a:[]){let c=xr(xr(l).inlineData),f=St(c.mimeType);if(f.startsWith("audio/pcm")&&St(c.data)){let m=Number(/rate=(\d+)/.exec(f)?.[1])||24e3;t.push({type:"audio",base64:St(c.data),rate:m})}}r.turnComplete&&t.push({type:"turnComplete"});let s=xr(e.toolCall).functionCalls;for(let l of Array.isArray(s)?s:[]){let c=xr(l);t.push({type:"toolCall",id:St(c.id),name:St(c.name),args:bh(c.args)})}let o=xr(e.error);return St(o.message)&&t.push({type:"error",message:St(o.message)}),t}},_d={"ai-realtime":xh,"gemini-live":vh};function Sd(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 Ad(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 Td(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 wh(){let e=globalThis;return e.AudioContext??e.webkitAudioContext}function Pd(){let e=null,t=null,r=null;return{async start(i,n){let a=wh(),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=Ad(c.inputBuffer.getChannelData(0),l,i);f.length&&n(Sd(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 Nd(){let e=null,t=0,r=new Set,i={play(n,a){let s=wh();if(!e&&s)try{e=new s}catch{return}if(!e)return;e.state==="suspended"&&e.resume?.();let o=Td(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 Vt(e,t){e.fireEvent?.("three-live-voice",t)}var Mh=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(po(s))};let r=t.provider??"ai-realtime",i=_d[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=Md(t.url);else throw new Error("connectVoice: pass a wss:// url or a transport.");this.mic=t.microphone===!1?null:t.microphoneSource??Pd(),this.sink=t.playAudio===!1?null:t.audioSink??Nd()}async start(){this.transport.onMessage=r=>this.handle(r),this.transport.onClose=()=>this.shutdown();let e=[vd,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=br(this.el);t.length&&this.sendContext(po(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,Ui);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,Vt(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(-Ui),Vt(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(-Ui),Vt(this.el,{state:this.state,reply:this.modelText,isFinal:r.isFinal}),r.isFinal&&(this.modelText=""));break;case"turnComplete":this.userText&&(Vt(this.el,{state:this.state,transcript:this.userText,isFinal:!0}),this.userText=""),this.modelText&&(Vt(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<=bd&&this.runTool(r.id,r.name,r.args);break;case"error":Vt(this.el,{state:this.state,error:r.message});break}}async runTool(e,t,r){let i;try{if(t==="edit_scene"){let n=St(r.instruction).trim().slice(0,Ui);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=St(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"?Sh(this.el,s,a):await Ra(this.el,St(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 To(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 Mh(e,t??{});return e.__tlVoiceSession=r,Vt(e,{state:"connecting"}),r.start()}function _h(){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 La(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 Po(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 Oi(e,t="and"){let r=e.slice(0,5).map(Po),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 Mn(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 ${Oi(t.names)}. ${r.length} selected.`:`Removed ${Oi(t.names)}. Nothing is selected.`:e==="add"?`Added ${Oi(t.names)}. ${r.length} selected.`:t.names.length===1?`Selected ${Po(t.names[0])}.`:`Selected ${t.names.length}: ${Oi(t.names)}.`;if(t.confidence==="ambiguous")return t.reason==="count_mismatch"?`I found ${t.candidates.length}: ${Oi(t.candidates)}. Which ones?`:`Which one: ${Oi(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 Ra(e,t,r={}){let i=r.mode??"replace",n=String(t??"").slice(0,Ui);if(i==="clear")return Er(e,[],{mode:"clear",source:"voice",query:n||"clear"}),{mode:i,query:n,match:null,applied:!0,tier:1,meshes:[],say:Mn(i,null,[],n)};let a=i==="remove"?br(e):null;if(a&&!a.length)return{mode:i,query:n,match:null,applied:!1,tier:1,meshes:[],say:"Nothing is selected."};let s=kc(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 zc(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&&(Er(e,s.names,{mode:i,source:"voice",query:n}),f=!0);let m=br(e),h=!f&&l?l:Mn(i,s,m,n);return{mode:i,query:n,match:s,applied:f,tier:o,meshes:m,say:h}}function Sh(e,t,r="replace"){let i=new Set(va(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=br(e);return{mode:r,query:a,match:l,applied:!1,tier:1,meshes:c,say:Mn(r,l,c,a)}}Er(e,n,{mode:r,source:"voice",query:a});let s={ids:[],names:n,confidence:"high",candidates:[],reason:"exact"},o=br(e);return{mode:r,query:a,match:s,applied:!0,tier:1,meshes:o,say:Mn(r,s,o,a)}}function No(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 Cd(e,t,r){if(typeof e.editScene!="function")return;Vt(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)}}Vt(e,{state:"idle",transcript:t,isFinal:!0,result:i}),r.speak!==!1&&La(No(i),r.lang)}async function Co(e,t={}){if(typeof e.editScene!="function")throw new Error("startVoiceEdit needs three-live-ai.min.js (el.editScene).");let r=t.recognizer??_h();if(!r)throw new Error("startVoiceEdit: this browser has no speech recognition; use el.connectVoice() (ai-realtime or gemini-live) instead.");Vt(e,{state:"listening"});let i="";try{i=(await r.listen({lang:t.lang,signal:t.signal,onPartial:l=>Vt(e,{state:"listening",transcript:l,isFinal:!1})})).trim().slice(0,Ui)}catch(l){throw Vt(e,{state:"error",error:l?.message||String(l)}),l}if(!i){let l="I didn't catch that.";throw Vt(e,{state:"idle",transcript:i,isFinal:!0,error:l}),t.speak!==!1&&La(l,t.lang),new Error(`startVoiceEdit: ${l}`)}let n=i,a,s=t.talkToSelect===!1?null:Ic(i);if(s&&s.kind!=="edit"){Vt(e,{state:"thinking",transcript:i,isFinal:!0});try{a=await Ra(e,s.kind==="clear"?"":s.query,{mode:s.mode,signal:t.signal})}catch(m){throw Vt(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;yh(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=>Cd(e,h,t))}if(!c){if(Vt(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.":"";La(a.say+m,t.lang)}return{transcript:i,result:null,selection:a}}n=l}else t.chips!==!1&&e.__tlChips&&Ca(e);Vt(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(Vt(e,{state:"idle",transcript:i,isFinal:!0,result:o,...a?{selection:a}:{}}),t.speak!==!1){let l=No(o);La(a?`${a.say} ${l}`:l,t.lang)}return{transcript:i,result:o,...a?{selection:a}:{}}}function Eo(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>=yd,l=br(e);r||o?Er(e,[s],{mode:"toggle",source:"tap"}):l.length===1&&l[0]===s?Er(e,[],{mode:"clear",source:"tap"}):Er(e,[s],{mode:"replace",source:"tap"}),r=!1,i=0},e.addEventListener?.("meshclick",e.__tlTapHandler)}var Ed='<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 Ld(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=Ed,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";To(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),Co(e,{signal:i.signal}).catch(()=>{}).finally(()=>{i=null,n(!1)})})}var Ah=1048576,Th=20,Ph=15e3,Rd=["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 $d(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 Nh(e){let t=String(e?.endpoint??"");if(!$d(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 Lo(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 Ch(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 Eh(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 ${Ph} ms.`))),Ph);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 Id=50;function Dd(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>=Id)break}return r}function kd(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 Ro(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 Nh({endpoint:n,model:e.getAttribute?.("ai-model")||void 0})}function $o(e){return typeof e.__tlAiSource=="string"?e.__tlAiSource:e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent??""}async function Lh(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??$o(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=Ro(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=Dd(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:Rd},{role:"user",content:`Current scene script:
423
+ \`\`\`js
424
+ ${n}
425
+ \`\`\`
426
+ `+kd(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=Lo(b),!p)g="The model reply did not contain a scene script.";else if(new TextEncoder().encode(p).length>Ah)g="The generated script exceeds the 1 MB script limit.";else try{let w=await Eh(e,p,l);x=w.warnings;let S=Ch(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>Th&&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 Rh(e){let t=e?.__tlAiHistory?.pop();return typeof t!="string"?!1:(e.__tlAiSource=t,await e.executeScript(t),!0)}var Io={name:"ai",onRegister(){typeof document>"u"||document.querySelectorAll?.("three-live, xr-live").forEach(e=>Io.onElementConnected?.(e))},onElementConnected(e){let t=e;if(!t||t.__tlAiInstalled)return;t.__tlAiInstalled=!0,t.editScene=(s,o)=>Lh(t,s,o),t.compileFromImage=(s,o)=>Kc(t,s,o),t.undoEdit=()=>Rh(t),Gp(t);let r=t;t.startVoiceEdit=s=>Co(r,s),r.__tlSelectProvider=()=>{try{return Ro(t,{})}catch{return null}},t.selectByVoice=(s,o)=>Ra(r,s,o),t.connectVoice=s=>To(r,s),t.setSelectOnTap=s=>Eo(r,s),t.hasAttribute?.("ai-select-on-tap")&&Eo(r,!0),t.hasAttribute?.("ai-voice-button")&&Ld(r),"sceneSource"in t||Object.defineProperty(t,"sceneSource",{get:()=>$o(t),configurable:!0});let i=t;dd(i);let n=t.executeScript;typeof n=="function"&&(t.executeScript=s=>(ph(i,{kind:"script",value:String(s)}),oh(i,()=>n.call(t,s)).then(o=>(t.__tlAiSource=String(s),mh(i,o),o))));let a=i.loadScriptFromSrc;typeof a=="function"&&(i.loadScriptFromSrc=s=>(ph(i,{kind:"url",value:String(s)}),oh(i,()=>a.call(t,s)).then(o=>(mh(i,o),o))))}};Rt(Io);function $h(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function Do(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 Ih(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 Dh(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=Li(e,t,f,1)??$h(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=Li(e,t,m,A)??$h(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 _n(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]];Do(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 Sn=new WeakMap;function kh(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(o=>o.name===t);if(!i)return;let n=Sn.get(e);n||(n=[],e.currentClip&&n.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),Sn.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 ko(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=Sn.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")_n(p,m.time,a),Ih(g.t,g.t,a,h);else if(p.path==="rotation")_n(p,m.time,s),Do(g.r,g.r,s,h);else if(p.path==="scale")_n(p,m.time,o),Ih(g.s,g.s,o,h);else if(p.path==="weights"&&(_n(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=ot(),{t:p,r:g,s:x}=n[m];tn(h,g,p,x),c.push(h)}let f=rn(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]),Qt(m.normalMatrix,m.transform))}var Fo=e=>{Sn.delete(e)},Fh={name:"keyframes",evaluateAnimation:ko,crossFadeTo:kh,onParseGLB(e){(e.animationsParsed===!1||!e.animations)&&(e.animations=Dh(e.gltf,e.bin),e.animationsParsed=!0)},onLoadModel:Fo,onClearScene:Fo,onDestroy:(e,t)=>Fo(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=Sn.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),ko(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),ko(e,e.animationTime))}},An=64;function Fd(e,t,r){if(!(!e?.meshes||t<0||t>=An))for(let i of e.meshes)for(let n of i.primitives){let a=n.pluginData?.morph;a?.weights&&(a.weights[t]=r)}}var Bh={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[${An}];
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 < ${An}; 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=kt(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)}},ji=64,ia={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,An),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=Li(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(An);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)}},Bo=64,zh={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[${ji}];`),s=n.includes("morphedPos")?"morphedPos":"aPosition";return n=n.replace(`vec4 world=uModel*vec4(${s},1.0);`,`mat4 skinMatrix =
441
+ uniform mat4 uJointMatrix[${Bo}];`),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=kt(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(ji*16);for(let h=0;h<o.length&&h<ji;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)}};Ge(ra),Ge(ta),Ge(ia),Ge(bn),Ge(hn);var Il=`#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.);}`,Dl=`#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);}`,fr=new WeakMap,na=new Float32Array(20);function qi(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 kl(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 Fl(e){let t=fr.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,Il)),e.attachShader(i,r(35632,Dl)),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")},fr.set(e,t),t}var Xi={name:"contact-shadow",onContextRestored(e){fr.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let n=Fl(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=kl(f);if(!g)continue;f.transform&&(g=qi(f.transform,g)),t.modelRootMatrix&&(g=qi(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=qi(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,W,,T]of o)v>=T-.08&&Math.abs(f-M)<=F&&Math.abs(g-P)<=W&&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),W=Math.max(.045,b*1.45*P);na.set([f-F,p,g-W,0,0,f+F,p,g-W,1,0,f+F,p,g+W,1,1,f-F,p,g+W,0,1]),e.bufferSubData(34962,0,na),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=fr.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),fr.delete(e))}};function sa(){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 aa(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function oa(){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 Vl(){return(await Ki()).bestMode}async function Ki(){let[e,t,r]=await Promise.all([oa(),Promise.resolve(sa()),Promise.resolve(aa())]),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 la(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=Ul(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=$r(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 $r(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 Ul(e){try{return $r(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function Ol(e,t={}){let r=$r(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",$r(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 Bl(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=Ol(e,t);window.location.href=r}var Nt=null;function zl(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 ua(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 $l=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.");Nt&&Nt!==this&&Nt.isSessionActive()&&await Nt.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 G=document.createElement("button");G.type="button",G.textContent="\u2715 Exit AR",G.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",G.addEventListener("beforexrselect",j=>j.preventDefault()),G.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(G),_.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 Fe)_.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 G=String(_?.name||"");return G==="NotAllowedError"||G==="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(G){if(M(G))throw i.onError?.(G),G;try{this.s=await r.requestSession(f)}catch(j){throw i.onError?.(j),j}}}let P=this.s;Nt=this,this.placed=!1;let F=null,W=null,T=null,E=null,S=null,O=[0,-.25,-1.2],k=[0,-.25,-1.2],w=new Float32Array(16),ie=new Float32Array(16),oe=!1,I=1,H=0,N=!1,z=null,ue=null,he=0,B=null,$=()=>{Nt===this&&(Nt=null),B?.(),B=null;try{W?.cancel?.()}catch{}if(W=null,T){let _=e?.meshes;if(Array.isArray(_)){let j=_.indexOf(T);j!==-1&&_.splice(j,1)}let G=e.getGLContext?.()||e?.gl;if(G)for(let j of T.primitives||[]){G.deleteVertexArray?.(j.vao);for(let q of j.buffers||[])G.deleteBuffer?.(q)}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||O;k=[_[0],_[1],_[2]],ua(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 G=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;_&&typeof G=="function"&&typeof P.updateRenderState=="function"&&P.updateRenderState({baseLayer:new G(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&&(W=await P.requestHitTestSource({space:j}).catch(()=>null)),f==="immersive-ar"&&_&&typeof _.createVertexArray=="function"&&Array.isArray(e.meshes)&&(T=zl(_,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?N=!0:V.touches.length>=2&&(N=!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)&&(N=!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}),B=()=>{window.removeEventListener("touchstart",te),window.removeEventListener("touchmove",se),window.removeEventListener("touchend",le),window.removeEventListener("touchcancel",le)}}e.setXRSessionActive?.(!0);let q=(D,Y)=>{if(this.s!==P)return;P.requestAnimationFrame(q);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 C=le.transform.position,U=le.transform.matrix,Q=C?.x??(U?U[12]:0),X=C?.y??(U?U[13]:0),Z=C?.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),O=[Q+J*1.2,X-.25,Z+K*1.2],H=Math.atan2(-J,-K),oe=!0}if(W&&typeof Y.getHitTestResults=="function"&&(!this.placed||N)){let C=Y.getHitTestResults(W)||[],U=!1;for(let Q of C){let X=Q.getPose(F);if(X?.transform?.matrix){let Z=X.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&&N&&(k=[Z[12],Z[13],Z[14]]),T&&(T.visible=!this.placed||N,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)}ua(w,this.placed?k:S||O,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 C of Fe)C.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 C=0;C<L.length;C++){let U=L[C];if(typeof e.renderXRView=="function"){let Q;if(R&&typeof R.getViewport=="function"){let X=R.getViewport(U);X&&X.width>0&&X.height>0&&(Q=[X.x,X.y,X.width,X.height])}else R?.framebufferWidth>0&&R?.framebufferHeight>0&&(Q=[0,0,R.framebufferWidth,R.framebufferHeight]);e.renderXRView(U,ie,this.placed,Q,A,C)}}ee&&R&&R.framebuffer&&ee.bindFramebuffer(36160,null)};P.requestAnimationFrame(q)}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 ha(e){let t=await Ki(),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 la(e.model,n),{mode:"quick-look",success:!0};o=xi(e.model)}return la(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 Bl(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 $l(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}`)}}Ht.registerAR({activateAR:ha,createUSDZBlob:xi}),Ht.registerScriptRunner(kr),Ge(Xi);var Yi=new WeakMap;function ca(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);Yi.set(e,r)}function Hl(e){return Yi.get(e)}async function Wl(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 Zi=new WeakMap,ma=new Float32Array(16);async function fa(e,t,r){let i=r?await Wl(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var pa={name:"environment-map",onContextRestored(e){Zi.delete(e)},setEnvironmentImage(e,t){return fa(e,"environmentTexture",t)},setSkyboxImage(e,t){return fa(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,n){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let s=Zi.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},Zi.set(t,s)}let l=ri(ma,r)||ma;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=Li(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(Bo*16);for(let f=0;f<o.length&&f<Bo;f++){let m=o[f],h=n[m]||ot();l.subarray(f*16,(f+1)*16).set(h)}let c=e.getUniformLocation(t,"uJointMatrix[0]");c&&e.uniformMatrix4fv(c,!1,l)}};Rt(Bh),Rt(Fh),Rt(zh),Rt(Cl),Rt(wl);var Bd=`#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.);}`,zd=`#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);}`,Tn=new WeakMap,Vh=new Float32Array(20);function zo(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 Vd(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 Ud(e){let t=Tn.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,Bd)),e.attachShader(i,r(35632,zd)),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")},Tn.set(e,t),t}var Vo={name:"contact-shadow",onContextRestored(e){Tn.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let n=Ud(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=Vd(g);if(!x)continue;g.transform&&(x=zo(g.transform,x)),t.modelRootMatrix&&(x=zo(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=zo(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);Vh.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,Vh),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=Tn.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),Tn.delete(e))}};function Uh(){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 Oh(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function jh(){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 Od(){return(await Uo()).bestMode}async function Uo(){let[e,t,r]=await Promise.all([jh(),Promise.resolve(Uh()),Promise.resolve(Oh())]),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 Gh(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=jd(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=$a(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 $a(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 jd(e){try{return $a(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function Gd(e,t={}){let r=$a(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",$a(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 Hd(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=Gd(e,t);window.location.href=r}var _i=null;function qd(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 Hh(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 Wd=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.");_i&&_i!==this&&_i.isSessionActive()&&await _i.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 Ct)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;_i=this,this.placed=!1;let N=null,C=null,_=null,P=null,R=null,$=[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=()=>{_i===this&&(_i=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||$;F=[Z[0],Z[1],Z[2]],Hh(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)&&(_=qd(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),$=[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)}Hh(V,this.placed?F:R||$,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 Ct)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 qh(e){let t=await Uo(),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 Gh(e.model,n),{mode:"quick-look",success:!0};o=Ps(e.model)}return Gh(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 Hd(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 Wd(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}`)}}wi.registerAR({activateAR:qh,createUSDZBlob:Ps}),wi.registerScriptRunner(ca),Rt(Vo),Rt(Rl);var Oo=new WeakMap;function Wh(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);Oo.set(e,r)}function Kd(e){return Oo.get(e)}async function Xd(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 jo=new WeakMap,Kh=new Float32Array(16);async function Xh(e,t,r){let i=r?await Xd(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var Yh={name:"environment-map",onContextRestored(e){jo.delete(e)},setEnvironmentImage(e,t){return Xh(e,"environmentTexture",t)},setSkyboxImage(e,t){return Xh(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,n){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let a=jo.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},jo.set(t,a)}let s=os(Kh,r)||Kh;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=Yi.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)}},Qi=new WeakMap;function Ji(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 da={name:"hotspots",updateHotspotsForElement:Ji,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{Ji(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),Qi.set(e,t)},onCameraChange(e,t){t&&Ji(t,e)},onElementDisconnected(e){let t=Qi.get(e);t&&(t.disconnect(),Qi.delete(e))}},ga=1024,en=256,Hr=2048,Gl=128,jl=64,ql=16,Xl=1e4,Kl=8,xt=new Set(["__proto__","constructor","prototype"]),ya={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))},ba={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},Wr={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},Gr=(e,t)=>e!==null&&typeof e=="object"&&!xt.has(t)&&Object.prototype.hasOwnProperty.call(e,t),tt=e=>Array.isArray(e)?[...e]:e,xa=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&Gr(e,"value")?e.value:e,Le=(e,t)=>Gr(e.configuration,t)?xa(e.configuration[t]):void 0,fe=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},Ct=e=>Math.max(0,Math.min(1,e)),nt=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function jr(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||xt.has(i)||xt.has(r))return null;t.push(i)}return{segments:t}}var Wt=(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},va=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]},Ma=(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 Hi(n,va(e),va(t),r),n}return e.slice(0,t.length).map((n,s)=>n+(t[s]-n)*r)}return r>=.5?t:e},tn=(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)),Yl=(e,t)=>Array.isArray(e)?e.map(r=>t(fe(r))):t(fe(e)),wa=(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,Aa=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>ga)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${ga})`);let n=Array.isArray(r.variables)?r.variables:[];if(n.length>en)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${en})`);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((B,$)=>{if(!B||typeof B!="object")return;let _=tt(xa(B.value));o.set($,_);let G=B.id??B.name;typeof G=="string"&&G&&!xt.has(G)&&o.set(G,_)}),(t?.nodes||[]).forEach((B,$)=>{for(let _ of B?.children||[])typeof _=="number"&&g.set(_,$)});let W=B=>B.op||typeof B.declaration=="number"&&s[B.declaration]?.op||"",T=(B,$,_)=>{if(xt.has($))return;let G=a.get(B);G||a.set(B,G=Object.create(null)),G[$]=_},E=(B,$)=>{if(typeof B!="number"&&typeof B!="string"||typeof B=="string"&&xt.has(B)||!o.has(B)&&o.size>=en*2)return;let _=tt($);if(o.set(B,_),typeof B=="number"){let G=n[B]?.id??n[B]?.name;typeof G=="string"&&!xt.has(G)&&o.set(G,_)}},S=B=>typeof B=="number"?l[B]?.id??String(B):typeof B=="string"?/^\d+$/.test(B)&&l[Number(B)]?.id?l[Number(B)].id:B:"",O=(B,$)=>{for(let _=B,G=0;_!==void 0&&_>=0&&G<128;_=g.get(_),G++)if(_===$)return!0;return!1},k=B=>{for(let $=d.length-1;$>=0;$--)d[$].key===B&&d.splice($,1)},w=B=>{k(B.key),d.length>=Gl&&d.shift(),d.push(B)},ie=B=>{let $=jr(B)?.segments;if($){if($[0]==="nodes"&&Array.isArray(t?.nodes)){let _=t.nodes[Wt($[1],t.nodes.length)];if(!_)return;let G=$[2];if(G in Wr){let j=Wr[G],q=_[G]||j;return j.map((D,Y)=>fe(q[Y],D))}if(G==="weights"){let j=Array.isArray(_.weights)?_.weights:[0],q=$.length===4?Wt($[3],64):-2;return q===-2?j.map(D=>fe(D)):q>=0?fe(j[q]):void 0}if(G==="visible"||G==="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[Wt($[1],t.materials.length)];if(!_)return;let G=_.pbrMetallicRoughness||{};if($[2]==="pbrMetallicRoughness"){if($[3]==="baseColorFactor"){let j=G.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(G[$[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=(B,$)=>{let _=jr(B)?.segments;if(!_)return!1;if(_[0]==="nodes"&&Array.isArray(t?.nodes)){let G=Wt(_[1],t.nodes.length),j=t.nodes[G];if(!j)return!1;let q=_[2];if(q in Wr&&Array.isArray($)){let D=Wr[q];if($.length<D.length)return!1;let Y=D.map((se,le)=>fe($[le],se));if(q==="rotation"){let se=Math.hypot(...Y);Y=se>1e-8?Y.map(le=>le/se):[0,0,0,1]}j[q]=Y,delete j.matrix;let te=e?.initialNodeTransforms?.[G];return te&&(te[q[0]]=[...Y]),M=!0,!0}if(q==="weights"){Array.isArray(j.weights)||(j.weights=[]);let D=(Y,te)=>{for(let se of e?.meshes||[])if(se.nodeIndex===G)for(let le of se.primitives||[])le.pluginData?.morph?.weights&&(le.pluginData.morph.weights[Y]=te)};if(_.length===4){let Y=Wt(_[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(q==="visible"||q==="extensions"&&_[3]==="KHR_node_visibility"&&_[4]==="visible"){let D=nt($);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 G=Wt(_[1],t.materials.length),j=t.materials[G];if(!j)return!1;let q=j.pbrMetallicRoughness||(j.pbrMetallicRoughness={}),D=Y=>{for(let te of e?.meshes||[])for(let se of te.primitives||[])(se.materialIndex??0)===G&&Y(se)};if(_[2]==="pbrMetallicRoughness"){if(_[3]==="baseColorFactor"&&Array.isArray($)&&$.length>=3){let Y=[Ct(fe($[0],1)),Ct(fe($[1],1)),Ct(fe($[2],1)),$[3]!==void 0?Ct(fe($[3],1)):q.baseColorFactor?.[3]??1];return q.baseColorFactor=Y,D(te=>te.baseColor=[...Y]),F=!0}if(_[3]==="metallicFactor"||_[3]==="roughnessFactor"){let Y=_[3]==="metallicFactor",te=Ct(fe($,Y?0:.5));return q[_[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=Ct(fe($,.5)),F=!0}return!1},I=(B,$,_=new Set)=>{let G=Le($,"pointer");if(typeof G!="string"||!G.startsWith("/"))return null;let j=G.replace(/\{([a-zA-Z0-9_]+)\}/g,(q,D)=>{let Y=Math.trunc(Number(H(B,D,void 0,_)??Le($,D)));return Number.isSafeInteger(Y)&&Y>=0?String(Y):"-1"});return jr(j)?j:null},H=(B,$,_,G)=>{let j=i[B]?.values;if(!Gr(j,$))return _;let q=j[$];if(q==null)return _;if(typeof q!="object"||Array.isArray(q))return tt(q);let D=q;return typeof D.node=="number"?N(D.node,D.socket||"value",G):Gr(D,"value")?tt(D.value):_},N=(B,$,_)=>{if(B<0||B>=i.length||_.has(B)||_.size>128||++p>Xl)return;let G=i[B],j=W(G);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(j))return tt(a.get(B)?.[$]);_.add(B);try{let q=(D,Y=0)=>H(B,D,Y,_);if(j==="variable/get"){let D=Le(G,"variable")??Le(G,"id");return typeof D=="number"||typeof D=="string"?tt(o.get(D)):void 0}if(j==="pointer/get"){let D=I(B,G,_);return D?ie(D):void 0}if(j.startsWith("math/")){let D=j.slice(5);if(D in ya)return Yl(q("a"),ya[D]);if(D in ba){let Y=/^(mul|div|rem|mod|pow)$/.test(D)?1:0;return tn(q("a",D==="mul"?1:0),q("b",Y),ba[D])}if(D==="pi")return Math.PI;if(D==="e")return Math.E;if(D==="random")return Math.random();if(D==="clamp")return tn(tn(q("a"),q("b",q("min",0)),Math.max),q("c",q("max",1)),Math.min);if(D==="mix"||D==="quatSlerp")return Ma(q("a",0),q("b",1),fe(q("c",q("t",.5)),.5),D==="quatSlerp");if(D==="dot"){let Y=q("a"),te=q("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=q("a",[0,0,0]),te=q("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=q("a");return Array.isArray(Y)?Math.hypot(...Y):Math.abs(fe(Y))}if(D==="distance"){let Y=q("a"),te=q("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=q("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(q(Y)));if(D.startsWith("extract")){let Y=q("a");return Array.isArray(Y)?Y[$==="0"||$==="x"?0:$==="1"||$==="y"?1:$==="2"||$==="z"?2:3]??0:0}if(D==="eq")return wa(q("a"),q("b"));if(D==="ne")return!wa(q("a"),q("b"));if(D==="lt")return fe(q("a"))<fe(q("b"));if(D==="le")return fe(q("a"))<=fe(q("b"));if(D==="gt")return fe(q("a"))>fe(q("b"));if(D==="ge")return fe(q("a"))>=fe(q("b"));if(D==="isNaN")return Number.isNaN(Number(q("a")));if(D==="isInf"){let Y=Number(q("a"));return!Number.isFinite(Y)&&!Number.isNaN(Y)}return D==="and"?nt(q("a",!1))&&nt(q("b",!1)):D==="or"?nt(q("a",!1))||nt(q("b",!1)):D==="xor"?nt(q("a",!1))!==nt(q("b",!1)):D==="not"?!nt(q("a",!1)):D==="select"?tt(nt(q("condition",!1))?q("a"):q("b")):void 0}return j==="type/boolToInt"||j==="type/boolToFloat"?nt(q("a",!1))?1:0:j==="type/intToBool"||j==="type/floatToBool"?fe(q("a",0))!==0:j==="type/intToFloat"?fe(q("a",0)):j==="type/floatToInt"?Math.trunc(fe(q("a",0))):void 0}finally{_.delete(B)}},z=()=>{if(M){M=!1,F=!0;let B=vr(t);if(e){e.worldMatrices=B;for(let $ of e.meshes||[])$.nodeIndex>=0&&$.nodeIndex<B.length&&($.transform.set(B[$.nodeIndex]),Ke($.normalMatrix,$.transform))}}if(P){P=!1,F=!0;let B=t?.nodes;if(Array.isArray(e?.meshes)&&Array.isArray(B))for(let $ of e.meshes){let _=!0;for(let G=$.nodeIndex,j=0;G!==void 0&&G>=0&&j<128;G=g.get(G),j++){let q=B[G];if(q?.visible===!1||q?.extensions?.KHR_node_visibility?.visible===!1){_=!1;break}}$.visible=_}}F&&(F=!1,e?.render?.())},ue=(B,$={steps:0})=>{if(!B||typeof B.node!="number")return;$.steps===0&&(p=0);let _=[B],G=j=>{_.length+$.steps<Hr&&_.push(j)};for(;_.length>0&&$.steps<Hr;){$.steps++;let j=_.shift();if(!j||j.node<0||j.node>=i.length)continue;let q=j.node,D=i[q];if(!D)continue;let Y=j.socket||"in",te=W(D),se=(V,ee=void 0)=>H(q,V,ee,new Set),le=(V="out")=>{let ee=D.flows?.[V];ee&&G(ee)};switch(te){case"flow/branch":le(nt(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&&G(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<Kl){let C=Math.min(Math.ceil((ee-V)/R),Hr);y++;try{for(let U=0;U<C&&$.steps<Hr;U++)T(q,"index",V+U*R),ue(A,$)}finally{y--}}let L=D.flows?.completed??D.flows?.out;L&&G(L);break}case"flow/doN":{let V=Y==="reset"?0:(u.get(q)||0)+1;if(u.set(q,V),T(q,"currentCount",V),T(q,"count",V),Y!=="reset"){let ee=Math.trunc(fe(se("n",Le(D,"stopIterations")??Le(D,"n")??1),1));V<=ee&&le()}break}case"flow/multiGate":{if(Y==="reset"){c.set(q,0);break}let V=Object.keys(D.flows||{}).sort();if(!V.length)break;let ee=Le(D,"isRandom")?Math.floor(Math.random()*V.length):c.get(q)||0;ee<V.length&&(le(V[ee]),c.set(q,Le(D,"isLoop")!==!1?(ee+1)%V.length:ee+1));break}case"flow/waitAll":{if(Y==="reset"){h.delete(q);break}let V=h.get(q);V||h.set(q,V=new Set),V.add(Y),V.size>=Math.max(1,Math.trunc(Number(Le(D,"inputFlows")??2)||2))&&(V.clear(),le("out"),le("completed"));break}case"flow/throttle":{if(Y==="reset"){m.delete(q);break}let V=Math.max(0,fe(se("duration",0))),ee=m.get(q);ee===void 0||b-ee>=V?(m.set(q,b),T(q,"lastRemainingTime",0),le()):T(q,"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===q&&f.splice(A,1);T(q,"lastDelayIndex",-1);break}let V=Math.max(0,fe(se("duration",Le(D,"duration")??0))),ee=D.flows?.done??D.flows?.out;if(V<=0){T(q,"lastDelayIndex",-1),ee&&G(ee);break}f.length>=jl&&f.shift();let R=x++;T(q,"lastDelayIndex",R),f.push({id:R,nodeIdx:q,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(Le(D,"variable")??Le(D,"id"),se("value")),le();break;case"variable/interpolate":{let V=Le(D,"variable")??Le(D,"id"),ee=se("value",se("target")),R=Math.max(0,fe(se("duration",Le(D,"duration")??.3),.3));V!==void 0&&ee!==void 0&&w({key:`var:${String(V)}`,varKey:V,from:tt(se("from")??o.get(V)??0),to:tt(ee),dur:R,elapsed:0,quat:!1,linear:Le(D,"easing")==="linear",done:D.flows?.done}),le();break}case"pointer/set":{let V=I(q,D),ee=se("value");V&&ee!==void 0&&(k(`ptr:${V}`),oe(V,ee)),le();break}case"pointer/interpolate":{let V=I(q,D),ee=se("value",se("target")),R=Math.max(0,fe(se("duration",Le(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:tt(A),to:tt(ee),dur:R,elapsed:0,quat:V.endsWith("/rotation"),linear:Le(D,"easing")==="linear",done:D.flows?.done}))}le();break}case"animation/start":{let V=se("animation")??Le(D,"animation")??Le(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(Le(D,"event")??Le(D,"id")),ee={};for(let R of Object.keys(D.values||{}))xt.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(B=>{W(B)==="event/onStart"&&ue(B.flows?.out)}),z()},this.fireOnSelect=B=>{if(!B)return;let $=typeof B.meshIndex=="number"?B.meshIndex:-1,_=typeof B.nodeIndex=="number"?B.nodeIndex:e?.meshes?.[$]?.nodeIndex??-1;i.forEach((G,j)=>{if(!/^(pointer|event|scene)\/onSelect$/.test(W(G)))return;let q=Le(G,"nodeIndex")??Le(G,"node")??H(j,"nodeIndex",void 0,new Set),D=Le(G,"meshName");if(typeof D=="string"&&D?B.meshName===D:q==null||Number(q)<0||Number.isNaN(Number(q))||O(_,Math.trunc(Number(q)))){if(T(j,"nodeIndex",_),T(j,"meshIndex",$),Array.isArray(B.hitPoint)){let Y=[fe(B.hitPoint[0]),fe(B.hitPoint[1]),fe(B.hitPoint[2])];T(j,"hitPoint",Y),T(j,"point",Y),T(j,"intersectionPoint",Y)}if(Array.isArray(B.normal)){let Y=[fe(B.normal[0]),fe(B.normal[1],1),fe(B.normal[2])];T(j,"normal",Y),T(j,"hitNormal",Y)}typeof B.distance=="number"&&T(j,"distance",B.distance),ue(G.flows?.out)}}),z()},this.receiveCustomEvent=(B,$={})=>he(B,$,{steps:0});function he(B,$,_){if(!(v>=ql)){v++;try{let G=S(B);i.forEach((j,q)=>{if(!/^(customE|e)vent\/receive$/.test(W(j)))return;let D=Le(j,"event")??Le(j,"id");if(!(S(D)!==G&&String(D)!==String(B))){for(let[Y,te]of Object.entries($))xt.has(Y)||T(q,Y,tt(te));ue(j.flows?.out,_)}}),z()}finally{v--}}}this.tick=B=>{if(!Number.isFinite(B)||B<0)return;let $=Math.min(B,.25);b+=$,i.forEach((G,j)=>{W(G)==="event/onTick"&&(T(j,"timeDelta",$),T(j,"dt",$),T(j,"timeElapsed",b),ue(G.flows?.out))});let _=[];for(let G=d.length-1;G>=0;G--){let j=d[G];j.elapsed+=$;let q=j.dur>1e-6?Ct(j.elapsed/j.dur):1,D=j.linear?q:q*q*(3-2*q),Y=Ma(j.from,j.to,D,j.quat);j.ptr?oe(j.ptr,Y):j.varKey!==void 0&&E(j.varKey,Y),q>=1&&(d.splice(G,1),j.done&&_.push(j.done))}for(let G=f.length-1;G>=0;G--){let j=f[G];j.rem-=$,j.rem<=0&&(f.splice(G,1),j.done&&_.push(j.done))}for(let G of _)ue(G);z()},this.dispose=()=>{d.length=0,f.length=0,o.clear(),a.clear(),u.clear(),h.clear(),m.clear(),c.clear()}}},ht=new WeakMap,qr=new WeakMap;function Zl(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||un().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=(qr.get(e)||0)+n,l=!1;for(let o=0;o<i.length;o++){let a=i[o],u=ul(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){qr.set(e,s);let o=vr(r);e.worldMatrices=o;for(let a of e.meshes||[])a.nodeIndex>=0&&a.nodeIndex<o.length&&(a.transform.set(o[a.nodeIndex]),Ke(a.normalMatrix,a.transform))}}function rn(e){if(!(!e||typeof e!="object"))return ht.get(e)||ht.get(e.viewer)||ht.get(e._view)}function Ta(e,t,r){let i=rn(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var Sa={name:"khr-interactivity",sendInteractivityEvent:Ta,getInteractivityVM:rn,onLoadModel(e,t){if(!e||typeof e!="object")return;ht.get(e)?.dispose(),ht.delete(e),qr.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 Aa(e,t,i);ht.set(e,n),n.fireOnStart()},onMeshSelect(e,t){ht.get(e)?.fireOnSelect(t)},onUpdate(e,t){ht.get(e)?.tick(t),Zl(e,t)},onDestroy(e,t){ht.get(t)?.dispose(),ht.delete(t),qr.delete(t)}},pr=new Map,Xr=new WeakMap;function Ql(e,t){pr.set(e,t)}var Ra={name:"materials",onContextRestored(e){Xr.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=Xr.get(e);r||(r=e.createTexture(),Xr.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&&pr.has(t.name)){let f=pr.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=Oo.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)}},Go=new WeakMap;function Ho(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 Qh={name:"hotspots",updateHotspotsForElement:Ho,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{Ho(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),Go.set(e,t)},onCameraChange(e,t){t&&Ho(t,e)},onElementDisconnected(e){let t=Go.get(e);t&&(t.disconnect(),Go.delete(e))}},Zh=1024,qo=256,Ia=2048,Yd=128,Qd=64,Zd=16,Jd=1e4,e1=8,Wr=new Set(["__proto__","constructor","prototype"]),Jh={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))},ef={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},Da={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},ka=(e,t)=>e!==null&&typeof e=="object"&&!Wr.has(t)&&Object.prototype.hasOwnProperty.call(e,t),vr=e=>Array.isArray(e)?[...e]:e,tf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&ka(e,"value")?e.value:e,Mt=(e,t)=>ka(e.configuration,t)?tf(e.configuration[t]):void 0,je=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},Si=e=>Math.max(0,Math.min(1,e)),Lr=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function Fa(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||Wr.has(i)||Wr.has(r))return null;t.push(i)}return{segments:t}}var ji=(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},rf=e=>{let t=je(e[0]),r=je(e[1]),i=je(e[2]),n=je(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]},nf=(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 Do(n,rf(e),rf(t),r),n}return e.slice(0,t.length).map((n,a)=>n+(t[a]-n)*r)}return r>=.5?t:e},Wo=(e,t,r)=>Array.isArray(e)&&Array.isArray(t)?e.slice(0,t.length).map((i,n)=>r(je(i),je(t[n]))):Array.isArray(e)?e.map(i=>r(je(i),je(t))):Array.isArray(t)?t.map(i=>r(je(e),je(i))):r(je(e),je(t)),t1=(e,t)=>Array.isArray(e)?e.map(r=>t(je(r))):t(je(e)),af=(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,sf=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>Zh)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${Zh})`);let n=Array.isArray(r.variables)?r.variables:[];if(n.length>qo)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${qo})`);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=vr(tf(H.value));o.set(te,Z);let ae=H.id??H.name;typeof ae=="string"&&ae&&!Wr.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(Wr.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"&&Wr.has(H)||!o.has(H)&&o.size>=qo*2)return;let Z=vr(te);if(o.set(H,Z),typeof H=="number"){let ae=n[H]?.id??n[H]?.name;typeof ae=="string"&&!Wr.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:"",$=(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>=Yd&&p.shift(),p.push(H)},Y=H=>{let te=Fa(H)?.segments;if(te){if(te[0]==="nodes"&&Array.isArray(t?.nodes)){let Z=t.nodes[ji(te[1],t.nodes.length)];if(!Z)return;let ae=te[2];if(ae in Da){let ie=Da[ae],de=Z[ae]||ie;return ie.map((me,Se)=>je(de[Se],me))}if(ae==="weights"){let ie=Array.isArray(Z.weights)?Z.weights:[0],de=te.length===4?ji(te[3],64):-2;return de===-2?ie.map(me=>je(me)):de>=0?je(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[ji(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[je(ie[0],1),je(ie[1],1),je(ie[2],1),je(ie[3],1)]}if(te[3]==="metallicFactor"||te[3]==="roughnessFactor")return je(ae[te[3]],1)}if(te[2]==="emissiveFactor"){let ie=Z.emissiveFactor||[0,0,0];return[je(ie[0]),je(ie[1]),je(ie[2])]}if(te[2]==="alphaCutoff")return je(Z.alphaCutoff,.5)}}},J=(H,te)=>{let Z=Fa(H)?.segments;if(!Z)return!1;if(Z[0]==="nodes"&&Array.isArray(t?.nodes)){let ae=ji(Z[1],t.nodes.length),ie=t.nodes[ae];if(!ie)return!1;let de=Z[2];if(de in Da&&Array.isArray(te)){let me=Da[de];if(te.length<me.length)return!1;let Se=me.map((_e,Le)=>je(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=ji(Z[3],64);if(Se<0)return!1;me(Se,ie.weights[Se]=je(te))}else if(Array.isArray(te))ie.weights=te.slice(0,64).map(Se=>je(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=Lr(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=ji(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=[Si(je(te[0],1)),Si(je(te[1],1)),Si(je(te[2],1)),te[3]!==void 0?Si(je(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=Si(je(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,je(te[Se]))),N=!0;if(Z[2]==="alphaCutoff")return ie.alphaCutoff=Si(je(te,.5)),N=!0}return!1},re=(H,te,Z=new Set)=>{let ae=Mt(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)??Mt(te,me)));return Number.isSafeInteger(Se)&&Se>=0?String(Se):"-1"});return Fa(ie)?ie:null},Q=(H,te,Z,ae)=>{let ie=i[H]?.values;if(!ka(ie,te))return Z;let de=ie[te];if(de==null)return Z;if(typeof de!="object"||Array.isArray(de))return vr(de);let me=de;return typeof me.node=="number"?ee(me.node,me.socket||"value",ae):ka(me,"value")?vr(me.value):Z},ee=(H,te,Z)=>{if(H<0||H>=i.length||Z.has(H)||Z.size>128||++b>Jd)return;let ae=i[H],ie=C(ae);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(ie))return vr(l.get(H)?.[te]);Z.add(H);try{let de=(me,Se=0)=>Q(H,me,Se,Z);if(ie==="variable/get"){let me=Mt(ae,"variable")??Mt(ae,"id");return typeof me=="number"||typeof me=="string"?vr(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 Jh)return t1(de("a"),Jh[me]);if(me in ef){let Se=/^(mul|div|rem|mod|pow)$/.test(me)?1:0;return Wo(de("a",me==="mul"?1:0),de("b",Se),ef[me])}if(me==="pi")return Math.PI;if(me==="e")return Math.E;if(me==="random")return Math.random();if(me==="clamp")return Wo(Wo(de("a"),de("b",de("min",0)),Math.max),de("c",de("max",1)),Math.min);if(me==="mix"||me==="quatSlerp")return nf(de("a",0),de("b",1),je(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):je(Se)*je(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(je(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(je(Se)-je(ke))}if(me==="normalize"){let Se=de("a");if(!Array.isArray(Se))return je(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=>je(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 af(de("a"),de("b"));if(me==="ne")return!af(de("a"),de("b"));if(me==="lt")return je(de("a"))<je(de("b"));if(me==="le")return je(de("a"))<=je(de("b"));if(me==="gt")return je(de("a"))>je(de("b"));if(me==="ge")return je(de("a"))>=je(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"?Lr(de("a",!1))&&Lr(de("b",!1)):me==="or"?Lr(de("a",!1))||Lr(de("b",!1)):me==="xor"?Lr(de("a",!1))!==Lr(de("b",!1)):me==="not"?!Lr(de("a",!1)):me==="select"?vr(Lr(de("condition",!1))?de("a"):de("b")):void 0}return ie==="type/boolToInt"||ie==="type/boolToFloat"?Lr(de("a",!1))?1:0:ie==="type/intToBool"||ie==="type/floatToBool"?je(de("a",0))!==0:ie==="type/intToFloat"?je(de("a",0)):ie==="type/floatToInt"?Math.trunc(je(de("a",0))):void 0}finally{Z.delete(H)}},k=()=>{if(S){S=!1,N=!0;let H=rn(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]),Qt(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<Ia&&Z.push(ie)};for(;Z.length>0&&te.steps<Ia;){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(Lr(_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(je(_e("startIndex",0))),Re=Math.trunc(je(_e("endIndex",0))),W=Math.max(1,Math.trunc(je(_e("step",1),1))),D=me.flows?.body;if(D&&Re>ne&&w<e1){let O=Math.min(Math.ceil((Re-ne)/W),Ia);w++;try{for(let X=0;X<O&&te.steps<Ia;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(je(_e("n",Mt(me,"stopIterations")??Mt(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=Mt(me,"isRandom")?Math.floor(Math.random()*ne.length):h.get(de)||0;Re<ne.length&&(Le(ne[Re]),h.set(de,Mt(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(Mt(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,je(_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,je(_e("duration",Mt(me,"duration")??0))),Re=me.flows?.done??me.flows?.out;if(ne<=0){_(de,"lastDelayIndex",-1),Re&&ae(Re);break}g.length>=Qd&&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(je(_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(Mt(me,"variable")??Mt(me,"id"),_e("value")),Le();break;case"variable/interpolate":{let ne=Mt(me,"variable")??Mt(me,"id"),Re=_e("value",_e("target")),W=Math.max(0,je(_e("duration",Mt(me,"duration")??.3),.3));ne!==void 0&&Re!==void 0&&V({key:`var:${String(ne)}`,varKey:ne,from:vr(_e("from")??o.get(ne)??0),to:vr(Re),dur:W,elapsed:0,quat:!1,linear:Mt(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,je(_e("duration",Mt(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:vr(D),to:vr(Re),dur:W,elapsed:0,quat:ne.endsWith("/rotation"),linear:Mt(me,"easing")==="linear",done:me.flows?.done}))}Le();break}case"animation/start":{let ne=_e("animation")??Mt(me,"animation")??Mt(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?.(je(_e("time",0))),N=!0,Le();break;case"event/send":case"customEvent/send":{let ne=R(Mt(me,"event")??Mt(me,"id")),Re={};for(let W of Object.keys(me.values||{}))Wr.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=Mt(ae,"nodeIndex")??Mt(ae,"node")??Q(ie,"nodeIndex",void 0,new Set),me=Mt(ae,"meshName");if(typeof me=="string"&&me?H.meshName===me:de==null||Number(de)<0||Number.isNaN(Number(de))||$(Z,Math.trunc(Number(de)))){if(_(ie,"nodeIndex",Z),_(ie,"meshIndex",te),Array.isArray(H.hitPoint)){let Se=[je(H.hitPoint[0]),je(H.hitPoint[1]),je(H.hitPoint[2])];_(ie,"hitPoint",Se),_(ie,"point",Se),_(ie,"intersectionPoint",Se)}if(Array.isArray(H.normal)){let Se=[je(H.normal[0]),je(H.normal[1],1),je(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>=Zd)){A++;try{let ae=R(H);i.forEach((ie,de)=>{if(!/^(customE|e)vent\/receive$/.test(C(ie)))return;let me=Mt(ie,"event")??Mt(ie,"id");if(!(R(me)!==ae&&String(me)!==String(H))){for(let[Se,ke]of Object.entries(te))Wr.has(Se)||_(de,Se,vr(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?Si(ie.elapsed/ie.dur):1,me=ie.linear?de:de*de*(3-2*de),Se=nf(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()}}},Fr=new WeakMap,Ba=new WeakMap;function r1(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||vl().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=(Ba.get(e)||0)+n,s=!1;for(let o=0;o<i.length;o++){let l=i[o],c=sp(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=je(y.translation[0]),m=je(y.translation[1]),h=je(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){Ba.set(e,a);let o=rn(r);e.worldMatrices=o;for(let l of e.meshes||[])l.nodeIndex>=0&&l.nodeIndex<o.length&&(l.transform.set(o[l.nodeIndex]),Qt(l.normalMatrix,l.transform))}}function Ko(e){if(!(!e||typeof e!="object"))return Fr.get(e)||Fr.get(e.viewer)||Fr.get(e._view)}function of(e,t,r){let i=Ko(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var lf={name:"khr-interactivity",sendInteractivityEvent:of,getInteractivityVM:Ko,onLoadModel(e,t){if(!e||typeof e!="object")return;Fr.get(e)?.dispose(),Fr.delete(e),Ba.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 sf(e,t,i);Fr.set(e,n),n.fireOnStart()},onMeshSelect(e,t){Fr.get(e)?.fireOnSelect(t)},onUpdate(e,t){Fr.get(e)?.tick(t),r1(e,t)},onDestroy(e,t){Fr.get(t)?.dispose(),Fr.delete(t),Ba.delete(t)}},Pn=new Map,za=new WeakMap;function i1(e,t){Pn.set(e,t)}var uf={name:"materials",onContextRestored(e){za.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=za.get(e);r||(r=e.createTexture(),za.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&&Pn.has(t.name)){let g=Pn.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&&pr.has(o.name)&&pr.get(o.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let o=Xr.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)}}}},Pa=64*1024*1024,Ea=128*1024*1024,Jl=16777216;function eu(e){return(e>>>1^-(e&1))&255}function tu(e){return(e>>>1^-(e&1))&65535}function ru(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function Na(e){return(e<<1^e>>31)>>>0}function Ca(e){if(e!==void 0&&e!=="NONE"&&e!=="OCTAHEDRAL"&&e!=="QUATERNION"&&e!=="EXPONENTIAL"&&e!=="COLOR")throw Te(`unknown filter "${String(e)}"`)}var we=Math.fround;function Gt(e){return Math.trunc(we(e+(e>=0?.5:-.5)))}function La(e,t,r,i="NONE"){if(Ca(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 Te(`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,Gt(we(v*F))),f(b+g,Gt(we(p*F))),f(b+2*g,Gt(we(y*F)))}return}if(i==="QUATERNION"){if(r!==8)throw Te(`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,W=[0,0,0,0];W[F+1&3]=Gt(we(x*P)),W[F+2&3]=Gt(we(b*P)),W[F+3&3]=Gt(we(v*P)),W[F]=Math.trunc(we(we(M*P)+.5));for(let T=0;T<4;T++)n.setInt16(d+T*2,W[T]<<16>>16,!0)}return}if(i==="EXPONENTIAL"){if(r<4||r%4!==0)throw Te(`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 _a=160,ct=16,iu=24,Ia=32,nu=24,su=[0,2,4,8],au=[0,1,2,4,8];function Da(e){let t=Math.floor(8192/e)&~(ct-1);return t<256?t:256}function Te(e){return new Error(`EXT_meshopt_compression: ${e}`)}function ou(e,t,r,i,n){if(n===0)return r.fill(0,i,i+ct),t;if(n===8)return r.set(e.subarray(t,t+ct),i),t+ct;let s=(1<<n)-1,l=8/n,o=t+ct*n/8;for(let a=0;a<ct;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 ka(e,t,r,i,n,s,l,o){let a=s/ct,u=a+3>>2;if(r-t<u)throw Te("truncated ATTRIBUTES stream");let h=t;t+=u;for(let m=0;m<a;m++){if(r-t<iu)throw Te("truncated ATTRIBUTES stream");let c=e[h+(m>>2)]>>(m&3)*2&3;t=ou(e,t,i,n+m*ct,l[o+c])}return t}function lu(e,t,r,i){if(r%4!==0||r>256)throw Te(`ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let n=e.byteLength;if(n<1)throw Te("truncated ATTRIBUTES stream");let s=e[0];if((s&240)!==_a)throw Te(`unsupported ATTRIBUTES header 0x${s.toString(16)}`);let l=s&15;if(l>1)throw Te(`unsupported ATTRIBUTES codec version ${l}`);let o=r+(l===0?0:r/4),a=l===0?Ia:nu,u=o<a?a:o;if(n-1<u)throw Te("truncated ATTRIBUTES stream");let h=n-o,m=e.slice(h,h+r),c=h+r,d=Da(r),f=new Uint8Array(256*4),g=1;for(let x=0;x<t;){let b=Math.min(d,t-x),v=b+ct-1&~(ct-1),p=l===0?0:r/4;if(n-g<p)throw Te("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 Te("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?ka(e,g,n,f,T*b,v,su,0):ka(e,g,n,f,T*b,v,au,E)}let F=l===0?0:e[c+M/4],W=F&3;if(W===0)for(let T=0;T<4;T++){let E=m[M+T];for(let S=0;S<b;S++)E=eu(f[T*b+S])+E&255,i[(x+S)*r+M+T]=E}else if(W===1)for(let T=0;T<4;T+=2){let E=m[M+T]|m[M+T+1]<<8,S=T*b;for(let O=0;O<b;O++){let k=f[S+O]|f[S+b+O]<<8;E=tu(k)+E&65535;let w=(x+O)*r+M+T;i[w]=E&255,i[w+1]=E>>8}}else if(W===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 O=(f[S]|f[b+S]<<8|f[2*b+S]<<16|f[3*b+S]<<24)>>>0;O=((O<<T|O>>>(32-T&31))^E)>>>0,E=O;let k=(x+S)*r+M;i[k]=O&255,i[k+1]=O>>>8&255,i[k+2]=O>>>16&255,i[k+3]=O>>>24}}else throw Te(`invalid ATTRIBUTES channel ${F}`)}m.set(i.subarray((x+b-1)*r,(x+b)*r)),x+=b}if(n-g!==u)throw Te("ATTRIBUTES trailing data")}var Fa=224,Va=208;function Ua(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 Kr(e,t,r){let i=Ua(e,t),n=i>>>1^-(i&1);return r+n>>>0}function uu(e,t,r){if(t%3!==0)throw Te(`TRIANGLES count must be divisible by 3 (got ${t})`);let i=t/3;if(e.byteLength<1+i+16)throw Te("truncated TRIANGLES stream");let n=e[0];if((n&240)!==Fa)throw Te(`unsupported TRIANGLES header 0x${n.toString(16)}`);let s=n&15;if(s>1)throw Te(`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,W)=>{r(y++,P),r(y++,F),r(y++,W)};for(let P=1;P<x;P++){let F=e[P];if(F<240){let W=F>>4,T=u-1-W&15,E=l[T],S=o[T],O=0,k=F&15;if(k<g){let w=a[h-1-k&15];O=k===0?d:w;let ie=k===0?1:0;d=d+ie>>>0,c(O,ie)}else{if(p.pos>b)throw Te("truncated TRIANGLES stream");O=k!==15?f+(k*2-27)>>>0:Kr(e,p,f),f=O,c(O)}m(O,S),m(E,O),M(E,S,O)}else if(F<254){let W=e[v+(F&15)],T=W>>4,E=W&15,S=d;d=d+1>>>0;let O=a[h-T&15],k=T===0?d:O,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 Te("truncated TRIANGLES stream");let W=e[p.pos++],T=F===254?0:15,E=W>>4,S=W&15;W===0&&(d=0);let O=0;T===0&&(O=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=O=Kr(e,p,f)),E===15&&(f=k=Kr(e,p,f)),S===15&&(f=w=Kr(e,p,f)),M(O,k,w),c(O),c(k,E===0||E===15?1:0),c(w,S===0||S===15?1:0),m(k,O),m(w,k),m(O,w)}}if(p.pos!==b)throw Te("TRIANGLES trailing data")}function hu(e,t,r){if(e.byteLength<1+t+4)throw Te("truncated INDICES stream");let i=e[0];if((i&240)!==Va)throw Te(`unsupported INDICES header 0x${i.toString(16)}`);let n=i&15;if(n>1)throw Te(`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 Te("truncated INDICES stream");let u=Ua(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 Te("INDICES trailing data")}function Oa(e,t,r,i,n="NONE"){if(Ca(n),!Number.isInteger(t)||t<0||t>Jl||!Number.isInteger(r)||r<=0||r>256)throw Te(`invalid count (${t}) or byteStride (${r})`);let s=t*r;if(s>Pa)throw Te(`decompressed size (${s}) exceeds MAX_MESHOPT_BUFFER_BYTES (${Pa})`);if(t===0)return new Uint8Array(0);let l=new Uint8Array(s);if(i==="ATTRIBUTES")return lu(e,t,r,l),La(l,t,r,n),l;if(i==="TRIANGLES"||i==="INDICES"){if(r!==2&&r!==4)throw Te(`${i} byteStride must be 2 or 4 (got ${r})`);if(n&&n!=="NONE")throw Te(`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"?uu(e,t,a):hu(e,t,a),l}throw Te(`unknown mode "${String(i)}"`)}function Ba(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function cu(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=[_a],a=Da(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]=ru(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<Ia;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=[Va|1],a=0;for(let u=0;u<t;u++){let h=l(u),m=h-a|0;a=h,Ba(o,Na(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=[Fa|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);Ba(a,Na(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 nn(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 Te(`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>Ea)throw Te(`total decompressed size (${l}) exceeds MAX_MESHOPT_TOTAL_BYTES (${Ea})`);let F=n.subarray(v,v+p),W=Oa(F,x,b,y,M);s.push({index:m,bytes:W,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 sn={decodeBufferViews(e,t){nn(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",sn);var za={name:"meshopt",onParseGLB(e){Ae().decoders.set("meshopt",sn),nn(e)}},mu=`#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&&Pn.has(o.name)&&Pn.get(o.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let o=za.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)}}}},cf=64*1024*1024,hf=128*1024*1024,n1=16777216;function a1(e){return(e>>>1^-(e&1))&255}function s1(e){return(e>>>1^-(e&1))&65535}function o1(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function ff(e){return(e<<1^e>>31)>>>0}function mf(e){if(e!==void 0&&e!=="NONE"&&e!=="OCTAHEDRAL"&&e!=="QUATERNION"&&e!=="EXPONENTIAL"&&e!=="COLOR")throw mt(`unknown filter "${String(e)}"`)}var at=Math.fround;function Gi(e){return Math.trunc(at(e+(e>=0?.5:-.5)))}function pf(e,t,r,i="NONE"){if(mf(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=at(p(y+2*x)-Math.abs(A)-Math.abs(b)),S=w>=0?0:w;A=at(A+(A>=0?S:-S)),b=at(b+(b>=0?S:-S));let E=at(Math.sqrt(at(at(at(A*A)+at(b*b))+at(w*w))));if(E===0){g(y,0),g(y+x,0),g(y+2*x,h);continue}let N=at(h/E);g(y,Gi(at(A*N))),g(y+x,Gi(at(b*N))),g(y+2*x,Gi(at(w*N)))}return}if(i==="QUATERNION"){if(r!==8)throw mt(`QUATERNION filter requires byteStride 8 (got ${r})`);let m=at(32767/at(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=at(x*x),w=at(at(at(at(b*2)-at(v*v))-at(y*y))-at(A*A)),S=at(Math.sqrt(w>=0?w:0)),E=at(m/x),N=g&3,C=[0,0,0,0];C[N+1&3]=Gi(at(v*E)),C[N+2&3]=Gi(at(y*E)),C[N+3&3]=Gi(at(A*E)),C[N]=Math.trunc(at(at(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,at(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:at(s/p);c(h,Math.trunc(at(at(y*S)+.5))),c(h+f,Math.trunc(at(at(A*S)+.5))),c(h+2*f,Math.trunc(at(at(b*S)+.5))),c(h+3*f,Math.trunc(at(at(w*S)+.5)))}}var df=160,Br=16,l1=24,gf=32,u1=24,c1=[0,2,4,8],h1=[0,1,2,4,8];function yf(e){let t=Math.floor(8192/e)&~(Br-1);return t<256?t:256}function mt(e){return new Error(`EXT_meshopt_compression: ${e}`)}function f1(e,t,r,i,n){if(n===0)return r.fill(0,i,i+Br),t;if(n===8)return r.set(e.subarray(t,t+Br),i),t+Br;let a=(1<<n)-1,s=8/n,o=t+Br*n/8;for(let l=0;l<Br;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 bf(e,t,r,i,n,a,s,o){let l=a/Br,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<l1)throw mt("truncated ATTRIBUTES stream");let h=e[f+(m>>2)]>>(m&3)*2&3;t=f1(e,t,i,n+m*Br,s[o+h])}return t}function m1(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)!==df)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?gf:u1,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=yf(r),g=new Uint8Array(256*4),x=1;for(let v=0;v<t;){let y=Math.min(p,t-v),A=y+Br-1&~(Br-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?bf(e,x,n,g,_*y,A,c1,0):bf(e,x,n,g,_*y,A,h1,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=a1(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 $=0;$<y;$++){let F=g[R+$]|g[R+y+$]<<8;P=s1(F)+P&65535;let V=(v+$)*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 $=(g[R]|g[y+R]<<8|g[2*y+R]<<16|g[3*y+R]<<24)>>>0;$=(($<<_|$>>>(32-_&31))^P)>>>0,P=$;let F=(v+R)*r+S;i[F]=$&255,i[F+1]=$>>>8&255,i[F+2]=$>>>16&255,i[F+3]=$>>>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 xf=224,vf=208;function wf(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 Va(e,t,r){let i=wf(e,t),n=i>>>1^-(i&1);return r+n>>>0}function p1(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)!==xf)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[_],$=0,F=N&15;if(F<x){let V=l[f-1-F&15];$=F===0?p:V;let Y=F===0?1:0;p=p+Y>>>0,h($,Y)}else{if(b.pos>y)throw mt("truncated TRIANGLES stream");$=F!==15?g+(F*2-27)>>>0:Va(e,b,g),g=$,h($)}m($,R),m(P,$),S(P,R,$)}else if(N<254){let C=e[A+(N&15)],_=C>>4,P=C&15,R=p;p=p+1>>>0;let $=l[f-_&15],F=_===0?p:$,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 $=0;_===0&&($=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=$=Va(e,b,g)),P===15&&(g=F=Va(e,b,g)),R===15&&(g=V=Va(e,b,g)),S($,F,V),h($),h(F,P===0||P===15?1:0),h(V,R===0||R===15?1:0),m(F,$),m(V,F),m($,V)}}if(b.pos!==y)throw mt("TRIANGLES trailing data")}function d1(e,t,r){if(e.byteLength<1+t+4)throw mt("truncated INDICES stream");let i=e[0];if((i&240)!==vf)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=wf(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 Mf(e,t,r,i,n="NONE"){if(mf(n),!Number.isInteger(t)||t<0||t>n1||!Number.isInteger(r)||r<=0||r>256)throw mt(`invalid count (${t}) or byteStride (${r})`);let a=t*r;if(a>cf)throw mt(`decompressed size (${a}) exceeds MAX_MESHOPT_BUFFER_BYTES (${cf})`);if(t===0)return new Uint8Array(0);let s=new Uint8Array(a);if(i==="ATTRIBUTES")return m1(e,t,r,s),pf(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"?p1(e,t,l):d1(e,t,l),s}throw mt(`unknown mode "${String(i)}"`)}function _f(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function g1(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=[df],l=yf(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]=o1(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<gf;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=[vf|1],l=0;for(let c=0;c<t;c++){let f=s(c),m=f-l|0;l=f,_f(o,ff(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=[xf|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);_f(l,ff(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 Xo(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>hf)throw mt(`total decompressed size (${s}) exceeds MAX_MESHOPT_TOTAL_BYTES (${hf})`);let N=n.subarray(A,A+b),C=Mf(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 Yo={decodeBufferViews(e,t){Xo(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",Yo);var Sf={name:"meshopt",onParseGLB(e){We().decoders.set("meshopt",Yo),Xo(e)}},y1=`#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
- }`,fu=`#version 300 es
492
+ }`,b1=`#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
- }`,$a=`#version 300 es
498
+ }`,Af=`#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
- }`,pu=`#version 300 es
504
+ }`,x1=`#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
- }`,du=`#version 300 es
527
+ }`,v1=`#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
- }`,Yr=3,dr=new WeakMap;function Ha(e,t=[.22,.74,.97]){let r=On(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 gu(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 yu(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 Wa=new WeakSet;function Ga(e){let t=dr.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;dr.delete(e)}if(Wa.has(e)||e.isContextLost?.())return null;let r=Ft(e,mu,fu,!1),i=Ft(e,$a,pu,!1),n=Ft(e,$a,du,!1);if(!r||!i||!n){for(let l of[r,i,n])l&&e.deleteProgram(l);return Wa.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},dr.set(e,t),t}function bu(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===Yr&&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<Yr;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 xu(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=Bn({strength:s,threshold:Br(t.getAttribute("bloom-threshold"),.62),radius:Br(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=Bn(n);s&&(!r||s.strength>r.strength)&&(r=s)}return r}function vu(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 Mi({color:n,thickness:s,pulse:l})}var Mu=new Set(["floor","pedestal","ground","table","grid","pad"]);function wu(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>Mu.has(t))}function Au(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=Mi(n);if(s)return s;let l=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",o=vu(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?Mi({color:l,thickness:3,pulse:!1}):null);if(o){let h=t.name||"";return wu(h)?null:o}return null}var ja={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=Au(t,c);d&&s.push({mesh:c,trait:d})}let l=s.length>0?Ga(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,W]=Ha(M.color),T=M.pulse?.8+.25*Math.sin(x*4):1;c.uOutlineColor&&e.uniform4f(c.uOutlineColor,P,F,W,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 O=E.length>>4,k=Pe();for(let w=0;w<O;w++)ke(k,d,E.subarray(w*16,w*16+16)),ke(f,r,k),Ke(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),Ke(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=xu(t);if(!o||o.strength<=0)return;let a=Ga(e);if(!a||!bu(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<Yr;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=Yr-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=dr.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);dr.delete(e)}}};function qa(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 Tu(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 Su(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=qa(s).indexOf(o);if(a<0)return i;for(let u of l)if(u.variants.includes(a))return u.material;return i}var Xa={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},Ka=new WeakMap,Ya={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=Ka.get(t);if(n||(n={lightProbe:null},Ka.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&&ca(e.gl,s.sphericalHarmonicsCoefficients)}}}};return Ge(Xi),Ge(da),Ge(pa),Ge(Ra),Ge(Ya),Ge(Sa),Ge(za),Ge(Xa),Ge(ja),Ge(vn),Ht.registerScriptRunner(kr),typeof window<"u"&&(window.ThreeLiveBundle=Qr),yo(Qr)})();
549
+ }`,Ua=3,Nn=new WeakMap;function Tf(e,t=[.22,.74,.97]){let r=au(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 w1(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 M1(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 Pf=new WeakSet;function Nf(e){let t=Nn.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;Nn.delete(e)}if(Pf.has(e)||e.isContextLost?.())return null;let r=gi(e,y1,b1,!1),i=gi(e,Af,x1,!1),n=gi(e,Af,v1,!1);if(!r||!i||!n){for(let s of[r,i,n])s&&e.deleteProgram(s);return Pf.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},Nn.set(e,t),t}function _1(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===Ua&&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<Ua;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 S1(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=su({strength:a,threshold:da(t.getAttribute("bloom-threshold"),.62),radius:da(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=su(n);a&&(!r||a.strength>r.strength)&&(r=a)}return r}function A1(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 Rs({color:n,thickness:a,pulse:s})}var T1=new Set(["floor","pedestal","ground","table","grid","pad"]);function P1(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>T1.has(t))}function N1(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=Rs(n);if(a)return a;let s=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",o=A1(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?Rs({color:s,thickness:3,pulse:!1}):null);if(o){let f=t.name||"";return P1(f)?null:o}return null}var Cf={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=N1(t,h);p&&a.push({mesh:h,trait:p})}let s=a.length>0?Nf(e):null;if(s){let h=s,p=ot(),g=ot(),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]=Tf(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 $=P.length>>4,F=ot();for(let V=0;V<$;V++)ft(F,p,P.subarray(V*16,V*16+16)),ft(g,r,F),Qt(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),Qt(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=S1(t);if(!o||o.strength<=0)return;let l=Nf(e);if(!l||!_1(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<Ua;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=Ua-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=Nn.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);Nn.delete(e)}}},Oa=4,Ef=9,C1=32*1024*1024,ja=ot(),Lf=new Int32Array([-1,-1]);function Qo(e,t,r,i){let n=Number(e);return Number.isFinite(n)?Math.max(t,Math.min(r,n)):i}var Rf=new WeakMap,Kr=new WeakMap,Cn=new WeakMap,Hi=ot(),Ga=ot(),Xr=ot(),qi=ot(),$f=new Float32Array(1),E1=new Uint32Array($f.buffer);function If(e){if(typeof e!="string")return"auto";let t=e.trim().toLowerCase();return t==="pcf"||t==="off"?t:"auto"}function L1(e){let t=Rf.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 Rf.set(e,l),l}function Wi(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 Df(e){let t=e||{},r=t.modelRootMatrix??ja,i=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let m of t.meshes??[]){if(!Jo(m))continue;m.worldSpace===!0?Xr.set(m.transform):ft(Xr,r,m.transform);let h=m.instanceMatrices;for(let p of m.primitives??[]){if(!p.positions||p.positions.length<3)continue;let g=L1(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(qi,Xr,h.subarray(y*16,y*16+16)),Wi(g,qi,i,n);if(v>1){let y=x-1;ft(qi,Xr,h.subarray(y*16,y*16+16)),Wi(g,qi,i,n)}}else Wi(g,Xr,i,n)}}if(!Number.isFinite(i[0])){let m=t.bounds;m&&Array.isArray(m.min)&&Array.isArray(m.max)&&Wi([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 kf(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];en(Hi,h,r.center,p);let g=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0];Wi([...r.min,...r.max],Hi,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 r0(Ga,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,Ga,Hi)}function Zo(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];en(Hi,[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];Wi([...a.min,...a.max],Hi,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 ss(Ga,C,1,N,Math.max(N+.1,S)),ft(e,Ga,Hi)}function Ff(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??ja,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 Jo(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 En(e,t){if(!Jo(e))return!1;let r=e.castShadow??e.extras?.shadow?.cast;return r===!1?!1:t?!0:r===!0}function el(e,t){if(!e||typeof e!="object")return!1;let r=e;if(!Jo(r))return!1;let i=r.receiveShadow??r.extras?.shadow?.receive;return i!==void 0?!!i:t}function tl(e){return!(e.isTransmissive||e.alphaMode==="BLEND"||(e.baseColor?.[3]??1)<.98)}function Yr(e,t){return Math.imul((e^t>>>0)>>>0,16777619)>>>0}function Qr(e,t){return $f[0]=t||0,Yr(e,E1[0])}function Ln(e,t,r=64){let i=t.length;if(e=Yr(e,i),i<=r)for(let n=0;n<i;n++)e=Qr(e,t[n]);else{let n=Math.max(1,Math.floor(i/r));for(let a=0;a<i;a+=n)e=Qr(e,t[a]);e=Qr(e,t[i-1])}return e}function rl(e){let t=e||{},r=t.shadowMaps??t.container?.getAttribute?.("shadow-maps")??"auto",i=If(r),n=[-1,-1],a=[-1,-1],s=($=!1)=>({mode:i,mapSize:0,slices:[],dirSlots:n,ptSlots:a,promoteAllCasters:$,promoteAllReceivers:$,digest:0,sectionPlane:null});if(i==="off")return s();let o=[],l=null,c=null,f=!1,m=0,h=0;for(let $ of t.lights??[])$.type==="hemisphere"?f=!0:$.type==="directional"&&m<2?(l||(l=$),$.shadow?.cast&&o.length<Oa&&o.push({kind:"directional",subIdx:m,light:$}),m++):($.type==="spot"||$.type==="point")&&h<2&&(c||(c={kind:$.type,light:$}),$.shadow?.cast&&o.length<Oa&&o.push({kind:$.type,subIdx:h,light:$}),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 $ of p)if($.castShadow!==void 0||$.receiveShadow!==void 0||$.extras?.shadow!==void 0){g=!0;break}let x=i==="pcf"||!g,v=x,y=!1;for(let $ of p)if(En($,x)){for(let F of $.primitives??[])if(tl(F)&&F.indexCount>0){y=!0;break}if(y)break}if(!y)return s(x);let A=1024;for(let $ of o){let F=$.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>C1;)b=Math.max(256,b>>1);let S=Df(t),E=S.radius*2.2/b,N=[];for(let $=0;$<o.length;$++){let F=o[$],V=F.light,Y=V.shadow,J=ot(),re;if(F.kind==="directional"){n[F.subIdx]=$;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],kf(J,G,S)}else{a[F.subIdx]=$;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));Zo(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],Zo(J,G,re,Math.PI/3,V.range,S)}}let Q=Qo(Y?.bias,-.05,.05,-5e-4),ee=Qo(Y?.normalBias,0,.5,.015),k=Qo(Y?.radius,0,16,1.5);N.push({slot:$,viewProj:J,rayDir:re,depthBias:Q,normalBiasWorld:ee/.015*1.75*E,uvRadius:k*1.35/b})}let C=Ff(t),_=2166136261;_=Yr(_,i==="pcf"?2:1),_=Yr(_,b),_=Yr(_,N.length);for(let $ of N)_=Ln(_,$.viewProj,16),_=Qr(_,$.depthBias),_=Qr(_,$.normalBiasWorld);C?.enabled?(_=Yr(_,1),_=Qr(_,C.normal[0]),_=Qr(_,C.normal[1]),_=Qr(_,C.normal[2]),_=Qr(_,C.constant)):_=Yr(_,0);let P=t.modelRootMatrix??ja;_=Ln(_,P,16);let R=0;for(let $ of p){if(!En($,x)){R++;continue}_=Yr(_,R++),_=Ln(_,$.transform,16),$.instanceMatrices&&(_=Ln(_,$.instanceMatrices,64));for(let F of $.primitives??[])tl(F)&&(_=Yr(_,F.indexCount),F.translations&&(_=Ln(_,F.translations,48)))}return _===0&&(_=1),{mode:i,mapSize:b,slices:N,dirSlots:n,ptSlots:a,promoteAllCasters:x,promoteAllReceivers:v,digest:_,sectionPlane:C}}function R1(e){let t=Kr.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 $1=`#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
+ }`,I1=`#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
+ }`,D1=`
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
+ }`,k1=["uShadowMap","uShadowVP","uShadowParams","uDirShdSlot","uPtShdSlot","uReceiveShadow"];function F1(e){let t=Kr.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},Kr.set(e,t)),t}function Bf(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 zf(e){let t=Cn.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,$1),e.compileShader(i),e.shaderSource(n,I1),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:Bf(e,1,1)},Cn.set(e,t),t}var Vf={uniformsGLSL:D1,dirGLSL:"*shdEval(uDirShdSlot[i],vWorldPos,N,normalize(uDirLightDir[i]))",ptGLSL:"*shdEval(uPtShdSlot[i],vWorldPos,N,L)",uniformNames:k1,bind(e,t,r,i){let n=t.uShadowMap;if(n===void 0)return;let a=r&&typeof r=="object"?Kr.get(r):void 0,s=zf(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,Ef);let c=t.uDirShdSlot,f=t.uPtShdSlot,m=t.uReceiveShadow;if(!o){c&&e.uniform1iv?.(c,Lf),f&&e.uniform1iv?.(f,Lf),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,el(i,a.promoteAllReceivers)?1:0)}};function Uf(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}var Of={name:"shadow-maps",onRegister(){We().shadowMapShader=Vf},onLoadModel(e){if(e&&typeof e=="object"){let t=Kr.get(e);t&&(t.lastDigest=0)}},onClearScene(e){if(e&&typeof e=="object"){let t=Kr.get(e);t&&(t.lastDigest=0,t.activeLights=0)}},onContextRestored(e,t){if(Cn.delete(e),t&&typeof t=="object"){let r=Kr.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=Kr.get(t);r&&(r.texArray&&e.deleteTexture?.(r.texArray),r.fbo&&e.deleteFramebuffer?.(r.fbo),Kr.delete(t))}else if(e){let r=Cn.get(e);r&&(r.prog&&e.deleteProgram?.(r.prog),r.dummyArrayTex&&e.deleteTexture?.(r.dummyArrayTex),Cn.delete(e))}},onBeforeDrawScene(e,t){if(!e||typeof e!="object")return;let r=e,i=We();if(i.shadowMapShader||(i.shadowMapShader=Vf),r.uRender&&!("uShadowMap"in r.uRender)&&r.recompileRenderProgram?.(),i.gpuSceneAccelerator?.willRenderScene?.(e))return;let n=F1(e),a=rl(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=zf(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=Bf(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??ja,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(!En(g,a.promoteAllCasters))continue;g.worldSpace===!0?Xr.set(g.transform):ft(Xr,m,g.transform);let x=g.instanceMatrices;for(let v of g.primitives??[])if(!(!v.vao||v.indexCount<=0||!tl(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,Xr),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(qi,Xr,x.subarray(A*16,A*16+16)),s.uModel&&t.uniformMatrix4fv(s.uModel,!1,qi),Uf(t,v)}else Uf(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 jf(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 B1(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 z1(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=jf(a).indexOf(o);if(l<0)return i;for(let c of s)if(c.variants.includes(l))return c.material;return i}var Gf={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},Hf=new WeakMap,qf={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=Hf.get(t);if(n||(n={lightProbe:null},Hf.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&&Wh(e.gl,a.sphericalHarmonicsCoefficients)}}}};Rt(Vo),Rt(Of),Rt(Qh),Rt(Yh),Rt(uf),Rt(qf),Rt(lf),Rt(Sf),Rt(Gf),Rt(Cf),Rt(Ll);var V1=272,U1=["x","y","z","w"],Wf=[[2,"vec2<f32>"],[3,"vec3<f32>"],[4,"vec4<f32>"]];function Ki(e,t){return Wf.map(([r,i])=>{let n=U1.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 Kf(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);}",...Ki("_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);}",...Ki("_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);}",...Ki("_tslPow",2)),e.clamp&&r.push("fn _tslClamp1(a:f32,b:f32,c:f32)->f32{return clamp(a,min(b,c),max(b,c));}",...Ki("_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);}",...Ki("_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);}",...Ki("_tslAtan",2)),e.norm&&r.push("fn _tslNorm1(v:f32)->f32{return select(0.0,sign(v),abs(v)>1e-6);}",...Wf.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 O1={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function il(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=sr(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(ii);v=l==="float"?y[0]:`${l}<f32>(${y.join(",")})`;break}case"builtin":v=o.builtin==="time"?`_tslMod1(tslU.timeAndPad.x,${ii(3600)})`:O1[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 Xf(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=Kf(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
+ ${il(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
+ ${il(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=Kf(na(e.nodes,e.vertexReachable,e.usesTime),!1),f=il(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 Rn=new WeakMap,Xi=new WeakMap,Yf=new WeakMap,$n=new Map,j1=128;function G1(e,t){let r=Yf.get(t);return r||(r={paramsLoc:e.getUniformLocation(t,"uTslParams[0]")??e.getUniformLocation(t,"uTslParams"),timeLoc:e.getUniformLocation(t,"uTslTime")},Yf.set(t,r)),r}function H1(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 In(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?.[hn];if(!f)continue;let m=typeof c.name=="string"&&c.name.length>0?c.name:`Material_${l}`,h=fn(f,m);if(!h.ok){console.warn(`[three-live] [${h.issue.code}] ${h.issue.message} Falling back to base PBR material.`);continue}let p=H1(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};Rn.set(e,s);let o=e.gl;return o&&typeof o=="object"&&Xi.set(o,s),s}function Qf(e,t){let r=Rn.get(e);if(!r){let i=t??e.gltf;if(!i)return null;r=In(e,i)}return r}function q1(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 Zf(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=Qf(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=q1(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=Es(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 Ha(e){if(!e||typeof e!="object")return;let t=e;typeof t.setMaterialUniform!="function"&&(t.setMaterialUniform=(r,i,n)=>Zf(e,r,i,n))}function W1(){let e=We();Ji(Ns);let t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t?Ns(t,e):e.authorNamespace||(e.authorNamespace={}),e.tslWgslCompiler=(r,i,n)=>!r||typeof r!="object"?null:Xf(r,i,n),e.tslMaterialResolver=(r,i)=>i===void 0||i<0?null:Qf(r)?.materialsByIndex.get(i)??null,e.tslUsdzSerializer=nu}var Jf={name:"tsl",onRegister(){W1()},onElementConnected(e){Ha(e),e?.viewer&&(Ha(e.viewer),e.viewer.gltf&&(In(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?.[hn];if(!a)return null;let s=fn(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?.[hn];if(!n)return null;let a=fn(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=$n.get(s);if(!o){if($n.size>=j1){let l=$n.keys().next().value;l!==void 0&&$n.delete(l)}o=iu(a.graph,r,i),$n.set(s,o)}return o},onLoadModel(e,t){Ha(e),e?.container&&Ha(e.container),In(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=Rn.get(e);if(!r||!r.hasAnimatedTsl)return;let i=Number.isFinite(t)&&t>0?Math.min(t,.25):0;r.elapsedSec=Ql(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?.[hn])return;let o=G1(e,t);if(!o.paramsLoc&&!o.timeLoc)return;let l=Xi.get(e);l||(l=In(e,a),Xi.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){Rn.delete(e),e?.gl&&typeof e.gl=="object"&&Xi.delete(e.gl)},onContextRestored(e,t){if(t?.gltf){let r=In(t,t.gltf);e&&typeof e=="object"&&Xi.set(e,r)}},onDestroy(e,t){Rn.delete(t),e&&typeof e=="object"&&Xi.delete(e)}};Rt(Jf);var K1=800,X1=32,Y1=128,Q1=8,Z1=32;function qa(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 nl(e,t){let r=new Float32Array(e,0,200),i=new Uint32Array(e,0,200),n=new Int32Array(e,0,200);r.fill(0),qa(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;qa(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 J1(e,t,r,i,n,a){let s=new Float32Array(e,0,44),o=new Uint32Array(e,0,44);s.fill(0),qa(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 al=`
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
+ `,sl=al+`
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
+ `,em=al+`
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
+ `,tm=al+`
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
+ `,rm=`
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
+ `,im=1,Zr=8,eg=16,tg=32,Wa=64,rg=128,ig=1,nm=2,Ka=4,ci=16,ng=1,Dn=1,zr=2,ol=4,hi=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),Ot=null,Gt=null,Vr=!1,Ht="bgra8unorm",Xa=null,Ya=new WeakMap;function yt(e){try{e()}catch{}}function am(e){return Math.max(16,e+3&-4)}function Qa(){let e=globalThis.navigator?.gpu;return e&&typeof e.requestAdapter=="function"?e:null}function sm(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 Yi(){if(Ot)return Promise.resolve(Ot);let e=We(),t=e.webgpuDeviceProvider?.peekDevice?.();return sm(t)?(Ot=t,Ht=e.webgpuDeviceProvider?.getCanvasFormat?.()||Ht,Promise.resolve(t)):Vr?Promise.resolve(null):Gt||(e.webgpuDeviceProvider&&e.webgpuDeviceProvider!==om?(Gt=e.webgpuDeviceProvider.acquireDevice().then(r=>(Gt=null,sm(r)?(Ot=r,Ht=e.webgpuDeviceProvider?.getCanvasFormat?.()||Ht,r):ll())).catch(()=>(Gt=null,ll())),Gt):ll())}function ll(){let e=Qa();if(!e)return Vr=!0,Promise.resolve(null);try{Ht=e.getPreferredCanvasFormat?.()||"bgra8unorm"}catch{Ht="bgra8unorm"}return Gt=e.requestAdapter({powerPreference:"high-performance"}).then(async t=>{if(!t)return Vr=!0,Gt=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 Ot=n,Gt=null,n.lost?.then?.(()=>{Ot===n&&(Ot=null,Gt=null,Vr=!1,Xa?.onDeviceLost(n))}),n}).catch(()=>(Vr=!0,Gt=null,null)),Gt}var om={acquireDevice:()=>Yi(),peekDevice:()=>Ot,getCanvasFormat:()=>Ht};function ag(e,t="bgra8unorm"){Ot=e,Gt=null,Vr=e===null,Ht=t}function sg(){Ot=null,Gt=null,Vr=!1,Ht="bgra8unorm"}function lm(e){let t=String(e??"").trim().toLowerCase();return t==="webgpu"||t==="webgl2"?t:"auto"}function og(e){let t=e.container?.getAttribute?.("renderer")??e.renderer??"auto";return lm(t)}function lg(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 ul(e,t=!!(Ot||Qa())){let r=e;if(!r||r.xrSessionActive)return"webgl2";let i=og(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"&&lg(r)?"webgl2":"webgpu"}function um(e){let t=Ya.get(e);if(t)return t;let r=e.createBindGroupLayout({entries:[{binding:0,visibility:Dn|zr,buffer:{type:"uniform"}},{binding:1,visibility:Dn|zr,buffer:{type:"read-only-storage"}},{binding:2,visibility:zr,sampler:{type:"filtering"}},{binding:3,visibility:zr,texture:{sampleType:"float"}},{binding:4,visibility:zr,sampler:{type:"comparison"}},{binding:5,visibility:zr,texture:{sampleType:"depth",viewDimension:"2d-array"}}]}),i=e.createBindGroupLayout({entries:[0,1,2,3,4].map(C=>({binding:C,visibility:zr,texture:{sampleType:"float"}}))}),n=e.createBindGroupLayout({entries:[{binding:0,visibility:Dn|zr,buffer:{type:"uniform"}}]}),a=e.createBindGroupLayout({entries:[{binding:0,visibility:Dn|zr,buffer:{type:"uniform"}},{binding:1,visibility:Dn|zr,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:sl}),h=e.createShaderModule({code:em}),p=e.createShaderModule({code:rm}),g=e.createShaderModule({code:tm}),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:Ka|nm|ci});yt(()=>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:Ka|ci}),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])},Ya.set(e,t),t}function ug(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,sl,rm);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 cg=[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"}]}];function cm(e,t,r,i,n){let a=s=>e.createRenderPipeline({layout:t,vertex:{module:r,entryPoint:"vsMain",buffers:cg},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 hg(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=cm(e,t.tslScenePipeLayout,s.pbrMod,i,n),t.tslPipelinesByFormat.set(o,l)),a?l.blend:l.opaque}function hm(e,t,r,i){let n=`${r}:${i}`,a=t.byFormat.get(n);if(a)return a;let{opaque:s,blend:o}=cm(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 fm(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 fi(e){return!e||typeof e!="object"?null:e.__gpuImageSource||(fm(e)?e:null)}function Ai(e,t,r){if(!r)return{view:t.whiteView,src:null,valid:!1};let i=fi(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=fm(i);if(!a)return{view:t.whiteView,src:null,valid:!1};n&&(t.ownedTextures.delete(n.tex),yt(()=>n.tex.destroy()));let[s,o]=a,l=e.createTexture({size:{width:s,height:o,depthOrArrayLayers:1},format:"rgba8unorm",usage:Ka|nm|ci}),c=!1;if(typeof e.queue.copyExternalImageToTexture=="function"&&yt(()=>{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);yt(()=>{e.queue.writeTexture({texture:l},p,{bytesPerRow:h,rowsPerImage:o},{width:s,height:o,depthOrArrayLayers:1}),c=!0})}if(!c)return yt(()=>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 mm(e,t,r){let i=Ai(e,t,r.texture),n=Ai(e,t,r.metallicRoughnessTexture),a=Ai(e,t,r.normalTexture),s=Ai(e,t,r.occlusionTexture),o=Ai(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 fg(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 pm(e){return Ff(e)}function mg(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??hi,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 dm(e){return e.environmentTexture&&typeof e.environmentTexture=="object"?e.environmentTexture:e.environmentSource&&typeof e.environmentSource=="object"?e.environmentSource:null}function Qi(e){if(e){yt(()=>e.vertexBuf.destroy()),yt(()=>e.indexBuf?.destroy()),yt(()=>e.partBuf.destroy()),yt(()=>e.uniformBuf.destroy()),yt(()=>e.pickUniformBuf?.destroy());for(let t of e.shadowSliceBufs)yt(()=>t?.destroy());for(let t of e.tslSlots.values())yt(()=>t.buf.destroy())}}function gm(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=ug(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){yt(()=>l?.buf.destroy());let c=e.createBuffer({size:s.buf68.byteLength,usage:Wa|Zr});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 cl(e){yt(()=>e.shadowTex?.destroy()),e.shadowTex=null,e.shadowArrayView=null,e.shadowLayerViews=[],e.shadowSize=0,e.shadowLayers=0,e.lastShadowDigest=0}function Za(e){yt(()=>e.msaaTex?.destroy()),yt(()=>e.depthTex?.destroy()),e.msaaTex=null,e.msaaView=null,e.depthTex=null,e.depthView=null,e.width=0,e.height=0}function Ja(e){yt(()=>e.pickColorTex?.destroy()),yt(()=>e.pickDepthTex?.destroy()),yt(()=>e.pickReadBuf?.destroy()),e.pickColorTex=null,e.pickColorView=null,e.pickDepthTex=null,e.pickDepthView=null,e.pickReadBuf=null,e.pickBusy=!1}function ym(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 bm(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,$=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=$&&$.length>=16?$.length>>4:F.instanceCount!==void 0&&F.translations?Math.max(1,F.instanceCount|0):1,k=mm(e,t,F),G=gm(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,$=N.firstVertex*8;for(let F=0;F<R;F++){let V=F*3,Y=F*2;h[$]=C[V],h[$+1]=C[V+1],h[$+2]=C[V+2],_&&V+2<_.length&&(h[$+3]=_[V],h[$+4]=_[V+1],h[$+5]=_[V+2]),P&&Y+1<P.length&&(h[$+6]=P[Y],h[$+7]=P[Y+1]),$+=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:am(h.byteLength),usage:tg|Zr});e.queue.writeBuffer(g,0,h);let x=null;p&&(x=e.createBuffer({size:am(p.byteLength),usage:eg|Zr}),e.queue.writeBuffer(x,0,p));let v=Math.max(128,c*128),y=e.createBuffer({size:v,usage:rg|Zr}),A=e.createBuffer({size:800,usage:Wa|Zr}),b=dm(r),w=Ai(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:fi(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 pg(e,t,r,i,n){let a=hm(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?hg(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 dg(e,t,r){if(r.pickUniformBuf||(r.pickUniformBuf=e.createBuffer({size:800,usage:Wa|Zr})),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 gg(e,t,r,i){if(i<0||i>=Oa)return null;if(r.shadowSliceBufs[i]||(r.shadowSliceBufs[i]=e.createBuffer({size:176,usage:Wa|Zr})),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 hl=ot(),Ti=ot();function xm(e,t,r,i,n,a,s){let o=dm(r),l=fi(o),c=i.envView;if(l!==i.envSourceRef){let b=Ai(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??hi,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=gm(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||fi(E)!==b.src0||fi(N)!==b.src1||fi(C)!==b.src2||fi(_)!==b.src3||fi(P)!==b.src4){let D=mm(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],$=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&&En(w,a.promoteAllCasters)&&(re|=1024),a&&a.slices.length>0&&!b.isBackdrop&&el(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__"?hl.set(w.transform):ft(hl,x,w.transform);let D=hl,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(Ti,G,ne.subarray(D*16,D*16+16)),O=Ti;else if(W&&W.length>=(D+1)*3){Ti.set(G);let X=W[D*3],se=W[D*3+1],ce=W[D*3+2];Ti[12]+=G[0]*X+G[4]*se+G[8]*ce,Ti[13]+=G[1]*X+G[5]*se+G[9]*ce,Ti[14]+=G[2]*X+G[6]*se+G[10]*ce,O=Ti}for(let X=0;X<16;X++)m[z+X]=O[X];Re&&Re.length>=(D+1)*3?(m[z+16]=$*Re[D*3],m[z+17]=F*Re[D*3+1],m[z+18]=V*Re[D*3+2]):(m[z+16]=$,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 yg(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 vm=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:ol,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 yt(()=>l.remove?.()),null;t.canvas=l,t.ctx=c,t.visible=!0,t.unhookSnapshot=fg(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!==Ht||s)&&(t.ctx.configure({device:r,format:Ht,alphaMode:"premultiplied"}),t.dev=r,t.configuredFormat=Ht),t.width!==n||t.height!==a||!t.depthTex){Za(t),t.width=n,t.height=a;let o=ol,l=null;yt(()=>{l=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:Ht,sampleCount:ol,usage:ci})}),l||(o=1);let c=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:"depth24plus",sampleCount:o,usage:ci});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(!Ot){if(!Vr&&!Gt){let G=h.gen;Yi().then(q=>{q&&h.gen===G&&this.trackedViewers.has(f.viewer)&&yt(()=>f.viewer.render?.())})}return this.hideLayer(f.viewer),!1}let p=Ot;if(ul(m,!0)!=="webgpu")return this.hideLayer(f.viewer),!1;h.dev&&h.dev!==p&&(Qi(h.scene),h.scene=null,Za(h),cl(h),Ja(h));let g=this.ensureCanvas(m,h,p);if(!g)return!1;let x=um(p),v=!f.isAR,y=v?m.backdropMeshes??[]:[],A=m.meshes??[];if((!h.scene||!ym(h.scene,y,A))&&(Qi(h.scene),h.scene=bm(p,x,m,v),h.lastShadowDigest=0,!h.scene))return this.hideLayer(f.viewer),!1;let b=h.scene,w=rl(m),S=x.dummyShadowView,E=w.slices.length;if(E>0){if(!h.shadowTex||h.shadowSize!==w.mapSize||h.shadowLayers<E){yt(()=>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:ci|Ka});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}xm(p,x,m,b,f,w,S),(b.bundlesDirty||b.bundleFormat!==Ht||b.bundleSamples!==h.sampleCount)&&(pg(p,x,b,Ht,h.sampleCount),this.bundleRecordCount++);let N=w.sectionPlane??pm(m),C=mg(m,f.isAR);nl(h.uniformScratch,{vp:f.vp,modelRoot:m.modelRootMatrix??hi,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,$={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??hi;for(let q of w.slices){let H=gg(p,x,b,q.slot),te=b.shadowSliceBufs[q.slot],Z=h.shadowLayerViews[q.slot];if(!te||!Z)continue;J1(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:$}:{view:_,loadOp:f.clear?"clear":"load",storeOp:"store",clearValue:$}],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=hm(p,x,Ht,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=Ot??await Yi();if(!s||typeof s.createCommandEncoder!="function")return-1;let o=this.getState(e),l=o.gen,c=um(s),f=n.backdropMeshes??[];if((!o.scene||!ym(o.scene,f,a))&&(Qi(o.scene),o.scene=bm(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=ot();i?y.set(i):n.projMatrix&&n.viewMatrix?ft(y,n.projMatrix,n.viewMatrix):y.set(hi),xm(s,c,n,m,{viewer:e,vp:y,proj:n.projMatrix??hi,view:n.viewMatrix??hi,eyePos:[0,0,3],toneMappingIndex:0,viewport:[0,0,h,p],eye:"none",clear:!0,isAR:!1}),(!o.pickColorTex||!o.pickDepthTex)&&(Ja(o),o.pickColorTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"rgba8unorm",usage:ci|ig}),o.pickColorView=o.pickColorTex.createView(),o.pickDepthTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"depth24plus",usage:ci}),o.pickDepthView=o.pickDepthTex.createView(),o.pickReadBuf=s.createBuffer({size:256,usage:Zr|im}));let A=yg(ot(),y,x,v,h,p),b=dg(s,c,m),w=new ArrayBuffer(800);nl(w,{vp:A,modelRoot:n.modelRootMatrix??hi,eyePos:[0,0,0],exposure:1,envIntensity:1,toneMappingIndex:2,lights:[],hasEnvMap:!1,sectionPlane:pm(n)}),s.queue.writeBuffer(m.pickUniformBuf,0,w);let S=!!(o.pickReadBuf&&!o.pickBusy),E=S?o.pickReadBuf:s.createBuffer({size:256,usage:Zr|im});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(ng,0,4),o.gen!==l)return yt(()=>E.unmap()),-1;let _=new Uint8Array(E.getMappedRange(0,4)),P=_[0],R=_[1],$=_[2];E.unmap();let F=P+(R<<8)+($<<16);return F>0&&F<=a.length?F-1:-1}finally{S?o.pickBusy=!1:yt(()=>E.destroy())}}willRenderScene(e){if(!Ot)return!1;let t=e;if(t.xrSessionActive||ul(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++,Qi(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,Qi(t.scene),t.scene=null,Za(t),cl(t),Ja(t),yt(()=>t.ctx?.unconfigure?.()),yt(()=>t.canvas?.remove?.()),t.ctx=null,t.canvas=null,t.dev=null,t.visible=!1)}onDeviceLost(e){let t=Ya.get(e);if(t){for(let r of t.ownedTextures)yt(()=>r.destroy());t.ownedTextures.clear(),Ya.delete(e)}for(let r of this.trackedViewers){let i=this.states.get(r);i&&i.dev===e&&(i.gen++,Qi(i.scene),i.scene=null,Za(i),cl(i),Ja(i),i.dev=null,i.configuredFormat="")}}};function kn(){return Xa||(Xa=new vm),Xa}var wm={name:"three-live-webgpu-scene",onRegister(){let e=We();e.gpuSceneAccelerator=kn(),e.webgpuDeviceProvider||(e.webgpuDeviceProvider=om),!Ot&&!Vr&&!Gt&&Qa()&&Yi()},onElementConnected(e){let t=e;!Ot&&!Vr&&!Gt&&Qa()&&Yi().then(r=>{r&&t?.viewer&&yt(()=>t.viewer.render?.())})},onAttributeChanged(e,t){(t==="renderer"||t==="section-plane"||t==="shadow-maps")&&e?.viewer?.render?.()},onLoadModel(e){e&&typeof e=="object"&&kn().clearViewerScene(e)},onClearScene(e){e&&typeof e=="object"&&kn().clearViewerScene(e)},onXRSessionEnd(e){e&&typeof e=="object"&&yt(()=>e.render?.())},onDestroy(e,t){t&&typeof t=="object"&&kn().disposeViewer(t)}};return Rt(wm),wi.registerScriptRunner(ca),typeof window<"u"&&(window.ThreeLiveBundle=ns),Ym(ns)})();