three-live 1.3.1 → 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 +191 -0
  3. package/dist/three-author-engine.js +179 -144
  4. package/dist/three-author.cjs +153 -144
  5. package/dist/three-author.d.ts +191 -0
  6. package/dist/three-author.js +153 -144
  7. package/dist/three-convert.cjs +150 -141
  8. package/dist/three-convert.d.ts +191 -0
  9. package/dist/three-convert.js +150 -141
  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 +191 -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 +191 -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 +191 -0
  24. package/dist/three-live-element.js +50 -85
  25. package/dist/three-live-full.cjs +915 -170
  26. package/dist/three-live-full.js +917 -172
  27. package/dist/three-live-full.min.js +915 -170
  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 +191 -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 +191 -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 +155 -146
  50. package/dist/three-live.js +155 -146
  51. package/dist/three-live.min.js +155 -146
  52. package/dist/three-view.cjs +49 -84
  53. package/dist/three-view.d.ts +191 -0
  54. package/dist/three-view.js +50 -85
  55. package/dist/three-xr.cjs +150 -141
  56. package/dist/three-xr.d.ts +191 -0
  57. package/dist/three-xr.js +150 -141
  58. package/package.json +39 -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 gi=Object.defineProperty,Ba=Object.getOwnPropertyDescriptor,za=Object.getOwnPropertyNames,Ga=Object.prototype.hasOwnProperty,Ha=(e,t)=>{for(var r in t)gi(e,r,{get:t[r],enumerable:!0})},Xa=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of za(t))!Ga.call(e,n)&&n!==r&&gi(e,n,{get:()=>t[n],enumerable:!(i=Ba(t,n))||i.enumerable});return e},$a=e=>Xa(gi({},"__esModule",{value:!0}),e),Co={};Ha(Co,{AmbientLight:()=>kn,BoxGeometry:()=>In,BufferAttribute:()=>He,BufferGeometry:()=>Fe,Camera:()=>Un,CapsuleGeometry:()=>Wr,CatmullRomCurve3:()=>_r,CircleGeometry:()=>jr,Clock:()=>Br,Color:()=>it,ConeGeometry:()=>Tr,CubicBezierCurve3:()=>Rr,Curve3:()=>Mt,CylinderGeometry:()=>Cn,DataTexture:()=>Ir,DirectionalLight:()=>Ur,DodecahedronGeometry:()=>$r,EdgesGeometry:()=>Yr,Euler:()=>_n,Float32BufferAttribute:()=>yr,Group:()=>Or,HemisphereLight:()=>Gn,IKSolver:()=>Qo,IcosahedronGeometry:()=>Xr,InstancedMesh:()=>Nn,InteractivityVM:()=>Kn,LOD:()=>ns,LatheGeometry:()=>Dn,Light:()=>Gt,Line:()=>Ut,LineBasicMaterial:()=>un,LineCurve3:()=>Sr,LineDashedMaterial:()=>Kr,LineLoop:()=>Zr,LineSegments:()=>Qr,LodController:()=>yn,MAX_BSP_DEPTH:()=>Wo,MAX_CSG_TRIANGLES:()=>$o,MAX_INSTANCES_PER_MESH:()=>Pn,MAX_SHAPE_POINTS:()=>Ko,MAX_TEXT_GEOMETRY_CHARS:()=>jo,Material:()=>Je,MathUtils:()=>Os,Matrix3:()=>br,Matrix4:()=>Ot,Mesh:()=>mt,MeshBasicMaterial:()=>Dr,MeshLambertMaterial:()=>Pr,MeshPhongMaterial:()=>Nr,MeshPhysicalMaterial:()=>kr,MeshStandardMaterial:()=>zt,Object3D:()=>ot,OctahedronGeometry:()=>Hr,PerspectiveCamera:()=>Fr,PlaneGeometry:()=>vr,PointLight:()=>On,Points:()=>Jr,PointsMaterial:()=>zn,PolyhedronFallbackGeometry:()=>Fc,PolyhedronGeometry:()=>Tt,QuadraticBezierCurve3:()=>Er,Quaternion:()=>Ln,RawShaderMaterial:()=>Ks,RectAreaLight:()=>Zs,RingGeometry:()=>Bn,Scene:()=>Fn,SceneQuotaValidator:()=>lt,ShaderMaterial:()=>Vn,SphereGeometry:()=>Mr,SpotLight:()=>ei,THREE:()=>Xt,TetrahedronGeometry:()=>Gr,Texture:()=>an,TextureLoader:()=>Cr,ThreeLiveElement:()=>ft,ThreeView:()=>je,TorusGeometry:()=>Ar,TorusKnotGeometry:()=>wr,TubeGeometry:()=>Lr,Uint16BufferAttribute:()=>gr,Uint32BufferAttribute:()=>xr,Vector2:()=>nt,Vector3:()=>ge,Vector4:()=>pr,WebGLRenderer:()=>Vr,WireframeGeometry:()=>qr,activateAR:()=>oi,applyMeshoptFilter:()=>Ao,authorScriptRunner:()=>ln,buildSandboxWorkerSource:()=>Wi,cadPlugin:()=>xi,clearAuthorWarnings:()=>js,computeOutlineClipOffset:()=>Na,contactShadowPlugin:()=>Wn,createUSDZBlob:()=>sn,crossFadeTo:()=>eo,decimateGeometry:()=>ts,decodeMeshoptBuffer:()=>wo,decodeMeshoptGLB:()=>hi,encodeMeshoptBuffer:()=>La,environmentMapPlugin:()=>ho,evaluateKawaseBloom:()=>Pa,evaluateToneMapping:()=>ms,exportSceneToCanvas3D:()=>Gi,exportSceneToGLB:()=>Hi,exportSceneToUSDZ:()=>Vs,extractMaterialVariants:()=>_o,extractPrimitiveVariantMappings:()=>ka,generateUSDZ:()=>wn,getARCapabilities:()=>ii,getAllowClientScripts:()=>Gs,getAuthorWarnings:()=>Ws,getBestARMode:()=>oa,getEnvironmentSH:()=>ca,getInteractivityVM:()=>mi,getLodController:()=>rs,getSandboxEngineSrc:()=>Xi,getSandboxIframeSrc:()=>zs,glbToUSDZ:()=>An,hotspotPlugin:()=>yo,ikPlugin:()=>Li,installCadExtension:()=>tr,installLodExtension:()=>bn,interactivityPlugin:()=>Mo,isAllowedSandboxEngineUrl:()=>cn,isQuickLookSupported:()=>co,isSceneViewerSupported:()=>uo,isWebXRSupported:()=>lo,keyframeAnimationPlugin:()=>to,lodPlugin:()=>Ii,materialsPlugin:()=>To,meshoptDecoder:()=>pi,meshoptPlugin:()=>So,morphPlugin:()=>no,noopProxy:()=>En,parseAnimations:()=>Ji,parseHexRgb:()=>Eo,parseLod:()=>sr,parseSafeGltfPointer:()=>jn,postprocessingPlugin:()=>Ro,quatFromUnitVectors:()=>ir,registerMaterialShader:()=>ba,sampleChannel:()=>fn,sceneToCanvas3D:()=>on,sceneToGLB:()=>vn,sceneToUSDZ:()=>Tn,selectLodLevelIndex:()=>or,selectMaterialVariant:()=>Oa,sendInteractivityEvent:()=>vo,setAllowClientScripts:()=>Lc,setEnvironmentSH:()=>si,setMorphTargetWeight:()=>ta,setSandboxEngineSrc:()=>Sc,setSandboxIframeSrc:()=>Rc,skinningPlugin:()=>io,solveFABRIK:()=>Ri,solveTwoBoneIK:()=>Ei,threeAuthorPlugin:()=>Rn,threeMicroPlugin:()=>zc,toGLBData:()=>gt,toTrustedWorkerScriptURL:()=>Bs,validateSandboxWorkerMessage:()=>ji,variantsPlugin:()=>Lo,warnUnsupported:()=>Ht,webxrPlugin:()=>Io}),module.exports=$a(Co);function Xo(e,t,r){let i=[],n=new Map,s=[],l=[],o=[],a=new Map,u=d=>{let y=n.get(d);return y===void 0&&(y=i.length,i.push({op:d}),n.set(d,y)),y},h=d=>{let y=a.get(d);return y===void 0&&(y=o.length,o.push({id:d}),a.set(d,y)),y},c=(d,y={})=>s.push({declaration:u(d),...y})-1,f=(d,y,M)=>l.push({id:d,type:y,value:M})-1,p=d=>({node:d,socket:"value"}),m=r?.interactivity??r?.gltfExtensions?.KHR_interactivity;if(m&&typeof m=="object"){let d=Array.isArray(m.graphs)?m.graphs[m.graph??0]:m;if(d&&Array.isArray(d.nodes)){let y=Array.isArray(d.declarations)?d.declarations:[];for(let M of y)M?.op&&u(M.op);Array.isArray(d.variables)&&l.push(...d.variables);for(let M of d.events||[])M?.id&&h(M.id);for(let M of d.nodes){if(!M||typeof M!="object")continue;let T=M.op||(typeof M.declaration=="number"?y[M.declaration]?.op:"");s.push(T?{...M,declaration:u(T)}:{...M})}}}let g=(d,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/${d}/extensions/KHR_node_visibility/visible`:`/nodes/${d}/${M}`,x=new Map;e.forEach((d,y)=>{typeof d?.name=="string"&&!x.has(d.name)&&x.set(d.name,y)});let b=(d,y)=>typeof d.target=="string"&&x.has(d.target)?x.get(d.target):typeof d.targetNode=="number"?d.targetNode:y,v=d=>{let y=e[d];return(typeof y?.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0};for(let d=0;d<e.length;d++){let y=e[d],M=y?.extras?.interactivity;if(!M||typeof M!="object")continue;let T=(typeof y.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0,V=P=>{let R=Array.isArray(P)?P:[P],C=[];for(let N=0;N<R.length;N++){let w=R[N];if(!w||typeof w!="object")continue;let ie=w.action||"interpolate",ae=typeof w.duration=="number"?w.duration:.35;if(ie==="toggleTransform"){let k=w.property==="rotation"||w.property==="scale"?w.property:"translation",J=k==="rotation"?y.rotation||[0,0,0,1]:k==="scale"?y.scale||[1,1,1]:y.translation||[0,0,0],z=`/nodes/${d}/${k}`,Y=f(`__toggle_${d}_${N}`,"bool",!1),le=c("variable/get",{configuration:{variable:Y}}),ce=c("math/not",{values:{a:p(le)}}),$=c("variable/set",{configuration:{variable:Y},values:{value:p(ce)}}),U=c("pointer/interpolate",{configuration:{pointer:z},values:{value:{value:Array.isArray(w.to)?w.to:J},duration:{value:ae}}}),_=c("pointer/interpolate",{configuration:{pointer:z},values:{value:{value:Array.isArray(w.from)?w.from:J},duration:{value:ae}}});s[$].flows={out:{node:c("flow/branch",{values:{condition:p(le)},flows:{true:{node:U},false:{node:_}}})}},C.push($)}else if(ie==="interpolate"){let k=w.to??w.value;if(k===void 0)continue;let J={value:{value:k},duration:{value:ae}};w.from!==void 0&&(J.from={value:w.from}),C.push(c("pointer/interpolate",{configuration:{pointer:typeof w.pointer=="string"?w.pointer:g(b(w,d),v(b(w,d)),w.property)},values:J}))}else if(ie==="setProperty"){if(w.value===void 0)continue;C.push(c("pointer/set",{configuration:{pointer:typeof w.pointer=="string"?w.pointer:g(b(w,d),v(b(w,d)),w.property)},values:{value:{value:w.value}}}))}else if(ie==="toggleVisibility"){let k=b(w,d),J=f(`__vis_${k}_${N}`,"bool",!0),z=c("variable/get",{configuration:{variable:J}}),Y=c("math/not",{values:{a:p(z)}}),le=c("variable/set",{configuration:{variable:J},values:{value:p(Y)}});s[le].flows={out:{node:c("pointer/set",{configuration:{pointer:`/nodes/${k}/extensions/KHR_node_visibility/visible`},values:{value:p(z)}})}},C.push(le)}else if(ie==="cycleMaterialColor"&&Array.isArray(w.colors)&&w.colors.length>0){let k=typeof w.duration=="number"?w.duration:.25,J=`/materials/${Math.max(0,T)}/pbrMetallicRoughness/baseColorFactor`,z=f(`__color_idx_${d}_${N}`,"int",0),Y=c("variable/get",{configuration:{variable:z}}),le=c("math/add",{values:{a:p(Y),b:{value:1}}}),ce=c("math/rem",{values:{a:p(le),b:{value:w.colors.length}}}),$=c("variable/set",{configuration:{variable:z},values:{value:p(ce)}}),U={};for(let _=0;_<w.colors.length;_++){let H=w.colors[_],D=Array.isArray(H)&&H.length>=3?[H[0],H[1],H[2],H[3]??1]:[1,1,1,1];U[String(_)]={node:k>0?c("pointer/interpolate",{configuration:{pointer:J},values:{value:{value:D},duration:{value:k}}}):c("pointer/set",{configuration:{pointer:J},values:{value:{value:D}}})}}s[$].flows={out:{node:c("flow/switch",{values:{selection:p(Y)},flows:U})}},C.push($)}else if(ie==="playAnimation")C.push(c("animation/start",{configuration:{animation:w.animation??w.clip??0}}));else if(ie==="stopAnimation")C.push(c("animation/stop"));else if(ie==="sendEvent"){let k={};for(let[J,z]of Object.entries(w.values||{}))k[J]={value:z};C.push(c("event/send",{configuration:{event:h(String(w.event??w.id??"custom"))},values:k}))}}if(!C.length)return null;if(C.length===1)return C[0];let B={};return C.forEach((N,w)=>{B[String(w)]={node:N}}),c("flow/sequence",{flows:B})},X=(P,R,C)=>{let B=V(R);B!==null&&c(P,{...C?{configuration:C}:{},flows:{out:{node:B}}})};if(M.onSelect&&X("pointer/onSelect",M.onSelect,{nodeIndex:d}),M.onHoverIn&&X("pointer/onHoverIn",M.onHoverIn,{nodeIndex:d}),M.onHoverOut&&X("pointer/onHoverOut",M.onHoverOut,{nodeIndex:d}),M.onStart&&X("event/onStart",M.onStart),M.onReceive&&typeof M.onReceive=="object")for(let[P,R]of Object.entries(M.onReceive))X("event/receive",R,{event:h(P)})}return s.length?{graphs:[{declarations:i,nodes:s,variables:l,events:o}],graph:0}:null}var Zn='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).',Qn="Security Error: client-side scripts require allow-client-scripts opt-in.",Jn="__THREE_LIVE_REGISTRY__";function Me(){let e=typeof globalThis<"u"?globalThis:{};if(!e[Jn]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,Jn,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[Jn]=t}}return e[Jn]}var Oe=Me().plugins;function Jt(e){let t=Me();t.workerExtensionInstallers||(t.workerExtensionInstallers=[]),t.workerExtensionInstallers.includes(e)||t.workerExtensionInstallers.push(e)}function Ue(e){let t=Me().plugins;t.some(r=>r.name===e.name)||t.push(e),e.onRegister?.()}function er(){return Me().plugins}var $o=8192,Wo=2048,jo=128,Ko=4096;function tr(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,c=e.MeshStandardMaterial,f=e.Mesh,p=8192,m=2048,g=128,x=4096,b=(A,S)=>{let L=A==null?NaN:Number(A);return Number.isFinite(L)?L:S};class v{constructor(S){this.currentPoint=new r(0,0),this.segments=[],Array.isArray(S)&&S.length>0&&this.fromPoints(S)}fromPoints(S){if(!S.length)return this;this.moveTo(S[0].x,S[0].y);for(let L=1;L<S.length;L++)this.lineTo(S[L].x,S[L].y);return this}moveTo(S,L){let O=Number(S)||0,I=Number(L)||0;return this.currentPoint.set(O,I),this.segments.push({type:"move",pts:[O,I]}),this}lineTo(S,L){let O=Number(S)||0,I=Number(L)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[this.currentPoint.x,this.currentPoint.y]}),this.currentPoint.set(O,I),this.segments.push({type:"line",pts:[O,I]}),this}quadraticCurveTo(S,L,O,I){let W=this.currentPoint.x,Q=this.currentPoint.y,K=Number(S)||0,Z=Number(L)||0,q=Number(O)||0,re=Number(I)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[W,Q]}),this.currentPoint.set(q,re),this.segments.push({type:"quad",pts:[W,Q,K,Z,q,re]}),this}bezierCurveTo(S,L,O,I,W,Q){let K=this.currentPoint.x,Z=this.currentPoint.y,q=Number(S)||0,re=Number(L)||0,ne=Number(O)||0,te=Number(I)||0,ue=Number(W)||0,me=Number(Q)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[K,Z]}),this.currentPoint.set(ue,me),this.segments.push({type:"cubic",pts:[K,Z,q,re,ne,te,ue,me]}),this}absarc(S,L,O,I,W,Q=!1){return this.absellipse(S,L,O,O,I,W,Q,0)}arc(S,L,O,I,W,Q=!1){return this.absarc(this.currentPoint.x+(Number(S)||0),this.currentPoint.y+(Number(L)||0),O,I,W,Q)}absellipse(S,L,O,I,W,Q,K=!1,Z=0){let q=Number(S)||0,re=Number(L)||0,ne=Math.max(0,Number(O)||0),te=Math.max(0,Number(I)||0),ue=Number(W)||0,me=Number(Q)||0,pe=K?1:0,fe=Number(Z)||0;this.segments.push({type:"arc",pts:[q,re,ne,te,ue,me,pe,fe]});let de=Math.cos(fe),ye=Math.sin(fe),we=ne*Math.cos(me),be=te*Math.sin(me);return this.currentPoint.set(q+we*de-be*ye,re+we*ye+be*de),this}ellipse(S,L,O,I,W,Q,K=!1,Z=0){return this.absellipse(this.currentPoint.x+(Number(S)||0),this.currentPoint.y+(Number(L)||0),O,I,W,Q,K,Z)}closePath(){if(this.segments.length>0){let S=this.segments[0],L=0,O=0;if(S.type==="arc"){let I=S.pts[0],W=S.pts[1],Q=S.pts[2],K=S.pts[3],Z=S.pts[4],q=S.pts[7],re=Math.cos(q),ne=Math.sin(q),te=Q*Math.cos(Z),ue=K*Math.sin(Z);L=I+te*re-ue*ne,O=W+te*ne+ue*re}else L=S.pts[0],O=S.pts[1];Math.hypot(this.currentPoint.x-L,this.currentPoint.y-O)>1e-6&&this.lineTo(L,O)}return this}getPoints(S=12){let L=Math.max(1,Math.min(128,Math.floor(Number(S)||12))),O=[],I=(W,Q)=>{if(O.length>0){let K=O[O.length-1];if(Math.hypot(K.x-W,K.y-Q)<1e-6)return}O.push(new r(W,Q))};for(let W of this.segments){let Q=W.pts;if(W.type==="move"||W.type==="line")I(Q[0],Q[1]);else if(W.type==="quad"){let K=Q[0],Z=Q[1],q=Q[2],re=Q[3],ne=Q[4],te=Q[5];I(K,Z);for(let ue=1;ue<=L;ue++){let me=ue/L,pe=1-me;I(pe*pe*K+2*pe*me*q+me*me*ne,pe*pe*Z+2*pe*me*re+me*me*te)}}else if(W.type==="cubic"){let K=Q[0],Z=Q[1],q=Q[2],re=Q[3],ne=Q[4],te=Q[5],ue=Q[6],me=Q[7];I(K,Z);for(let pe=1;pe<=L;pe++){let fe=pe/L,de=1-fe,ye=de*de,we=fe*fe;I(ye*de*K+3*ye*fe*q+3*de*we*ne+we*fe*ue,ye*de*Z+3*ye*fe*re+3*de*we*te+we*fe*me)}}else if(W.type==="arc"){let K=Q[0],Z=Q[1],q=Q[2],re=Q[3],ne=Q[4],te=Q[5],ue=Q[6]!==0,me=Q[7],pe=Math.PI*2,fe=te-ne,de=Math.abs(fe)<1e-9;for(;fe<0;)fe+=pe;for(;fe>pe;)fe-=pe;fe<1e-9&&(fe=de?0:pe),ue&&!de&&(fe=fe===pe?-pe:fe-pe);let ye=Math.cos(me),we=Math.sin(me),be=Math.max(2,L);for(let _e=0;_e<=be;_e++){let Te=_e/be,Ce=ne+Te*fe,Le=q*Math.cos(Ce),De=re*Math.sin(Ce);I(K+Le*ye-De*we,Z+Le*we+De*ye)}}}if(O.length>2){let W=O[0],Q=O[O.length-1];Math.hypot(W.x-Q.x,W.y-Q.y)<1e-6&&O.pop()}return O}getSpacedPoints(S=12){return this.getPoints(S)}clone(){let S=new this.constructor;return S.currentPoint.copy(this.currentPoint),S.segments=this.segments.map(L=>({type:L.type,pts:[...L.pts]})),Array.isArray(this.holes)&&(S.holes=this.holes.map(L=>L.clone())),S}}class d extends v{constructor(S){super(S),this.holes=[]}extractPoints(S=12){return{shape:this.getPoints(S),holes:this.holes.map(L=>L.getPoints(S))}}}function y(A){let S=0,L=A.length;for(let O=0,I=L-1;O<L;I=O++)S+=A[I].x*A[O].y-A[O].x*A[I].y;return S*.5}function M(A,S,L,O,I,W,Q,K){let Z=Q-L,q=K-O,re=I-L,ne=W-O,te=A-L,ue=S-O,me=Z*Z+q*q,pe=Z*re+q*ne,fe=Z*te+q*ue,de=re*re+ne*ne,ye=re*te+ne*ue,we=me*de-pe*pe;if(Math.abs(we)<1e-12)return!1;let be=1/we,_e=(de*fe-pe*ye)*be,Te=(me*ye-pe*fe)*be;return _e>=-1e-7&&Te>=-1e-7&&_e+Te<=1+1e-7}function T(A,S){let L=A.slice();y(L)<0&&L.reverse();let O=L.map(Z=>new r(Z.x,Z.y)),I=L.map((Z,q)=>q),W=[];for(let Z of S){if(!Z||Z.length<3)continue;let q=Z.slice();y(q)>0&&q.reverse();let re=[],ne=-1/0,te=0;for(let ue=0;ue<q.length;ue++){let me=q[ue],pe=O.length;O.push(new r(me.x,me.y)),re.push(pe),me.x>ne&&(ne=me.x,te=ue)}W.push({pts:q,indices:re,maxX:ne,maxIdx:te})}W.sort((Z,q)=>q.maxX-Z.maxX);let Q=(Z,q,re)=>(q.x-Z.x)*(re.y-Z.y)-(q.y-Z.y)*(re.x-Z.x),K=(Z,q,re)=>{for(let ne=0;ne<re.length;ne++){let te=re[ne],ue=re[(ne+1)%re.length];if(Q(Z,q,te)*Q(Z,q,ue)<0&&Q(te,ue,Z)*Q(te,ue,q)<0)return!0}return!1};for(let Z of W){let q=Z.pts[Z.maxIdx],re=q.x,ne=I.length,te=I.map(de=>O[de]),ue=de=>Math.hypot(te[de].x-re,te[de].y-q.y),me=te.map((de,ye)=>ye).sort((de,ye)=>+(te[de].x<re)-+(te[ye].x<re)||ue(de)-ue(ye)),pe=me[0];for(let de of me){let ye=te[de],we=te[(de+ne-1)%ne],be=te[(de+1)%ne],_e=Q(ye,be,q)>=0,Te=Q(we,ye,q)>=0;if((Q(we,ye,be)>=0?_e&&Te:_e||Te)&&!K(q,ye,te)&&!W.some(Ce=>K(q,ye,Ce.pts))){pe=de;break}}let fe=[];for(let de=0;de<=pe;de++)fe.push(I[de]);for(let de=0;de<=Z.indices.length;de++){let ye=Z.indices[(Z.maxIdx+de)%Z.indices.length];fe.push(ye)}for(let de=pe;de<I.length;de++)fe.push(I[de]);I=fe}return{merged:I.map(Z=>O[Z]),mergedIndices:I,allVertices:O}}function V(A,S){let L=[],O=A.slice();if(O.length<3)return L;let I=O.length*O.length+64,W=0;for(;O.length>2&&I-- >0;){let Q=O.length,K=O[(W+Q-1)%Q],Z=O[W%Q],q=O[(W+1)%Q],re=S[K],ne=S[Z],te=S[q];if((ne.x-re.x)*(te.y-re.y)-(ne.y-re.y)*(te.x-re.x)>1e-9){let ue=!0;for(let me=0;me<Q;me++){let pe=O[me];if(pe===K||pe===Z||pe===q)continue;let fe=S[pe];if(M(fe.x,fe.y,re.x,re.y,ne.x,ne.y,te.x,te.y)&&Math.hypot(fe.x-re.x,fe.y-re.y)>=1e-6&&Math.hypot(fe.x-ne.x,fe.y-ne.y)>=1e-6&&Math.hypot(fe.x-te.x,fe.y-te.y)>=1e-6){ue=!1;break}}if(ue){L.push([K,Z,q]),O.splice(W%Q,1),W=Math.max(0,W%Q-1);continue}}W++,W>=Q*2&&(L.push([K,Z,q]),O.splice((W-1)%Q,1),W=0)}return L}function X(A,S){let L=A instanceof d?A.extractPoints(S):{shape:A.getPoints(S),holes:[]},O=L.shape.length;for(let I of L.holes)O+=I.length;if(O>x)throw new RangeError(`SecurityError: shape point count (${O}) exceeds MAX_SHAPE_POINTS (${x})`);return L}class P extends u{constructor(S=new d,L=12){super();let O=Array.isArray(S)?S:[S],I=[],W=[],Q=[],K=[];for(let Z of O){if(!(Z instanceof v))continue;let q=X(Z,L);if(q.shape.length<3)continue;let{mergedIndices:re,allVertices:ne}=T(q.shape,q.holes),te=V(re,ne),ue=I.length/3,me=1/0,pe=1/0,fe=-1/0,de=-1/0;for(let be of ne)be.x<me&&(me=be.x),be.y<pe&&(pe=be.y),be.x>fe&&(fe=be.x),be.y>de&&(de=be.y);let ye=Math.max(1e-6,fe-me),we=Math.max(1e-6,de-pe);for(let be of ne)I.push(be.x,be.y,0),W.push(0,0,1),Q.push((be.x-me)/ye,(be.y-pe)/we);for(let[be,_e,Te]of te)K.push(ue+be,ue+_e,ue+Te)}R(this,I,W,Q,K)}}function R(A,S,L,O,I){return A.setAttribute("position",new a(S,3)),A.setAttribute("normal",new a(L,3)),A.setAttribute("uv",new a(O,2)),A.setIndex(I),A}function C(A){let S=A.length,L=[];for(let O=0;O<S;O++){let I=A[(O+S-1)%S],W=A[O],Q=A[(O+1)%S],K=W.x-I.x,Z=W.y-I.y,q=Math.hypot(K,Z)||1;K/=q,Z/=q;let re=Q.x-W.x,ne=Q.y-W.y,te=Math.hypot(re,ne)||1;re/=te,ne/=te;let ue=Z,me=-K,pe=ne,fe=-re,de=ue+pe,ye=me+fe,we=Math.hypot(de,ye);if(we>1e-6){de/=we,ye/=we;let be=Math.max(.35,de*ue+ye*me);L.push(new r(de/be,ye/be))}else L.push(new r(ue,me))}return L}class B extends u{constructor(S=new d,L={}){super();let O=Array.isArray(S)?S:[S],I=Math.max(1,Math.min(64,Math.floor(b(L.curveSegments,12)))),W=b(L.depth??L.amount,1),Q=Math.max(1,Math.min(32,Math.floor(b(L.steps,1)))),K=!!(L.bevelEnabled??!1),Z=K?Math.max(0,b(L.bevelThickness,.06)):0,q=K?Math.max(0,b(L.bevelSize,Z*.8)):0,re=K?b(L.bevelOffset,0):0,ne=K?Math.max(1,Math.min(8,Math.floor(b(L.bevelSegments,2)))):0,te=[],ue=[],me=[],pe=[];for(let fe of O){if(!(fe instanceof v))continue;let de=X(fe,I);if(de.shape.length<3)continue;let ye=de.shape.slice();y(ye)<0&&ye.reverse();let we=[];for(let xe of de.holes){if(xe.length<3)continue;let Re=xe.slice();y(Re)>0&&Re.reverse(),we.push(Re)}let{mergedIndices:be,allVertices:_e}=T(ye,we),Te=V(be,_e),Ce=[ye,...we],Le=[];for(let xe of Ce){let Re=C(xe);for(let Ie of Re)Le.push(Ie)}let De=1/0,We=1/0,$e=-1/0,at=-1/0;for(let xe of _e)xe.x<De&&(De=xe.x),xe.y<We&&(We=xe.y),xe.x>$e&&($e=xe.x),xe.y>at&&(at=xe.y);let Ke=Math.max(1e-6,$e-De),ct=Math.max(1e-6,at-We),qt=-Z,Kt=W+Z,St=te.length/3;for(let xe=0;xe<_e.length;xe++){let Re=_e[xe],Ie=Le[xe]??new r(0,0),Ve=Re.x+Ie.x*re,Be=Re.y+Ie.y*re;te.push(Ve,Be,qt),ue.push(0,0,-1),me.push((Ve-De)/Ke,(Be-We)/ct)}for(let[xe,Re,Ie]of Te)pe.push(St+xe,St+Ie,St+Re);let Rt=te.length/3;for(let xe=0;xe<_e.length;xe++){let Re=_e[xe],Ie=Le[xe]??new r(0,0),Ve=Re.x+Ie.x*re,Be=Re.y+Ie.y*re;te.push(Ve,Be,Kt),ue.push(0,0,1),me.push((Ve-De)/Ke,(Be-We)/ct)}for(let[xe,Re,Ie]of Te)pe.push(Rt+xe,Rt+Re,Rt+Ie);let Ye=[];if(K&&ne>0)for(let xe=0;xe<ne;xe++){let Re=xe/ne*Math.PI/2;Ye.push({z:-Z*Math.cos(Re),expand:re+q*Math.sin(Re)})}for(let xe=0;xe<=Q;xe++){let Re=xe/Q;Ye.push({z:Re*W,expand:re+q})}if(K&&ne>0)for(let xe=1;xe<=ne;xe++){let Re=xe/ne*Math.PI/2;Ye.push({z:W+Z*Math.sin(Re),expand:re+q*Math.cos(Re)})}let pt=0;for(let xe of Ce){let Re=xe.length;for(let Ie=0;Ie<Ye.length-1;Ie++){let Ve=Ye[Ie],Be=Ye[Ie+1];for(let et=0;et<Re;et++){let bt=(et+1)%Re,Ct=xe[et],Et=xe[bt],_t=Le[pt+et],Lt=Le[pt+bt],It=Ct.x+_t.x*Ve.expand,Ft=Ct.y+_t.y*Ve.expand,jt=Et.x+Lt.x*Ve.expand,wt=Et.y+Lt.y*Ve.expand,sl=Et.x+Lt.x*Be.expand,ol=Et.y+Lt.y*Be.expand,Yi=Ct.x+_t.x*Be.expand,so=Ct.y+_t.y*Be.expand,Po=jt-It,No=wt-Ft,Do=0,ko=Yi-It,Fo=so-Ft,Vo=Be.z-Ve.z,Yt=No*Vo-Do*Fo,Zt=Do*ko-Po*Vo,Qt=Po*Fo-No*ko,qi=Math.hypot(Yt,Zt,Qt)||1;Yt/=qi,Zt/=qi,Qt/=qi;let yi=te.length/3;te.push(It,Ft,Ve.z,jt,wt,Ve.z,sl,ol,Be.z,Yi,so,Be.z),ue.push(Yt,Zt,Qt,Yt,Zt,Qt,Yt,Zt,Qt,Yt,Zt,Qt);let Oo=et/Re,Uo=(et+1)/Re,Bo=Ie/(Ye.length-1),zo=(Ie+1)/(Ye.length-1);me.push(Oo,Bo,Uo,Bo,Uo,zo,Oo,zo),pe.push(yi,yi+1,yi+2,yi,yi+2,yi+3)}}pt+=Re}}R(this,te,ue,me,pe)}}function N(A){return{x:A.x,y:A.y,z:A.z,nx:A.nx,ny:A.ny,nz:A.nz,u:A.u,v:A.v}}function w(A){return{x:A.x,y:A.y,z:A.z,nx:-A.nx,ny:-A.ny,nz:-A.nz,u:A.u,v:A.v}}function ie(A,S,L){let O=A.nx+(S.nx-A.nx)*L,I=A.ny+(S.ny-A.ny)*L,W=A.nz+(S.nz-A.nz)*L,Q=Math.hypot(O,I,W)||1;return{x:A.x+(S.x-A.x)*L,y:A.y+(S.y-A.y)*L,z:A.z+(S.z-A.z)*L,nx:O/Q,ny:I/Q,nz:W/Q,u:A.u+(S.u-A.u)*L,v:A.v+(S.v-A.v)*L}}function ae(A){if(A.length<3)return null;let S=A[0],L=A[1],O=A[2],I=L.x-S.x,W=L.y-S.y,Q=L.z-S.z,K=O.x-S.x,Z=O.y-S.y,q=O.z-S.z,re=W*q-Q*Z,ne=Q*K-I*q,te=I*Z-W*K,ue=Math.hypot(re,ne,te);if(ue<1e-9)return null;re/=ue,ne/=ue,te/=ue;let me=re*S.x+ne*S.y+te*S.z;return{vertices:A,nx:re,ny:ne,nz:te,w:me}}function k(A){A.vertices.reverse();for(let S=0;S<A.vertices.length;S++)A.vertices[S]=w(A.vertices[S]);A.nx=-A.nx,A.ny=-A.ny,A.nz=-A.nz,A.w=-A.w}let J=1e-5,z=0,Y=1,le=2,ce=3;function $(A,S,L,O,I,W,Q,K,Z){let q=0,re=[];for(let ne=0;ne<I.vertices.length;ne++){let te=I.vertices[ne],ue=A*te.x+S*te.y+L*te.z-O,me=ue<-J?le:ue>J?Y:z;q|=me,re.push(me)}switch(q){case z:{A*I.nx+S*I.ny+L*I.nz>0?W.push(I):Q.push(I);break}case Y:K.push(I);break;case le:Z.push(I);break;case ce:{let ne=[],te=[],ue=I.vertices.length;for(let ye=0;ye<ue;ye++){let we=(ye+1)%ue,be=re[ye],_e=re[we],Te=I.vertices[ye],Ce=I.vertices[we];if(be!==le&&ne.push(Te),be!==Y&&te.push(be!==le?N(Te):Te),(be|_e)===ce){let Le=Ce.x-Te.x,De=Ce.y-Te.y,We=Ce.z-Te.z,$e=A*Le+S*De+L*We,at=Math.abs($e)>1e-12?(O-(A*Te.x+S*Te.y+L*Te.z))/$e:.5,Ke=ie(Te,Ce,Math.max(0,Math.min(1,at)));ne.push(Ke),te.push(N(Ke))}}let{nx:me,ny:pe,nz:fe,w:de}=I;ne.length>=3&&K.push({vertices:ne,nx:me,ny:pe,nz:fe,w:de}),te.length>=3&&Z.push({vertices:te,nx:me,ny:pe,nz:fe,w:de});break}default:break}}class U{constructor(S,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,S&&S.length>0&&this.build(S,L)}invert(){for(let L=0;L<this.polygons.length;L++)k(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 S=this.front;this.front=this.back,this.back=S}clipPolygons(S,L=0){if(!this.hasPlane||S.length===0)return S.slice();if(L>=m)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${m})`);let O=[],I=[];for(let W=0;W<S.length;W++)$(this.nx,this.ny,this.nz,this.w,S[W],O,I,O,I);return this.front&&O.length>0&&(O=this.front.clipPolygons(O,L+1)),this.back?I=I.length>0?this.back.clipPolygons(I,L+1):[]:I=[],O.concat(I)}clipTo(S,L=0){this.polygons.length>0&&(this.polygons=S.clipPolygons(this.polygons,0)),L<m&&(this.front&&this.front.clipTo(S,L+1),this.back&&this.back.clipTo(S,L+1))}allPolygons(S=[]){for(let L=0;L<this.polygons.length;L++)S.push(this.polygons[L]);return this.front&&this.front.allPolygons(S),this.back&&this.back.allPolygons(S),S}build(S,L=0){if(!S.length)return;if(!this.hasPlane){let W=S[S.length>>1];this.nx=W.nx,this.ny=W.ny,this.nz=W.nz,this.w=W.w,this.hasPlane=!0}if(L>=m)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${m})`);let O=[],I=[];for(let W=0;W<S.length;W++)$(this.nx,this.ny,this.nz,this.w,S[W],this.polygons,this.polygons,O,I);O.length>0&&(this.front||(this.front=new U),this.front.build(O,L+1)),I.length>0&&(this.back||(this.back=new U),this.back.build(I,L+1))}}function _(A,S){if(!S&&A._csgPolygons)return A._csgPolygons;let L=A.attributes.position;if(!L||L.count===0)return[];let O=A.attributes.normal,I=A.attributes.uv,W=A.index?A.index.array:null,Q=Math.floor(W?W.length/3:L.count/3);if(Q>p)throw new RangeError(`SecurityError: CSG input triangle count (${Q}) exceeds MAX_CSG_TRIANGLES (${p})`);let K=S?S.elements:null,Z=K?K[0]*(K[5]*K[10]-K[9]*K[6])-K[4]*(K[1]*K[10]-K[9]*K[2])+K[8]*(K[1]*K[6]-K[5]*K[2])<0:!1,q=K?new l().getNormalMatrix(S).elements:null,re=te=>{let ue=L.getX(te),me=L.getY(te),pe=L.getZ(te),fe=O?O.getX(te):NaN,de=O?O.getY(te):NaN,ye=O?O.getZ(te):NaN;if(K&&q){let _e=K[0]*ue+K[4]*me+K[8]*pe+K[12],Te=K[1]*ue+K[5]*me+K[9]*pe+K[13],Ce=K[2]*ue+K[6]*me+K[10]*pe+K[14];ue=_e,me=Te,pe=Ce;let Le=q[0]*fe+q[3]*de+q[6]*ye,De=q[1]*fe+q[4]*de+q[7]*ye,We=q[2]*fe+q[5]*de+q[8]*ye,$e=Math.hypot(Le,De,We)||1;fe=Le/$e,de=De/$e,ye=We/$e}let we=I?I.getX(te):0,be=I?I.getY(te):0;return{x:ue,y:me,z:pe,nx:fe,ny:de,nz:ye,u:we,v:be}},ne=[];for(let te=0;te<Q;te++){let ue=W?W[te*3]:te*3,me=W?W[te*3+1]:te*3+1,pe=W?W[te*3+2]:te*3+2,fe=ae(Z?[re(ue),re(pe),re(me)]:[re(ue),re(me),re(pe)]);fe&&ne.push(fe)}return ne}function H(A){let S=[],L=[],O=[],I=[];for(let Q of A){let K=Q.vertices;if(K.length<3)continue;let Z=S.length/3;for(let q of K)S.push(q.x,q.y,q.z),Number.isFinite(q.nx)&&q.nx*q.nx+q.ny*q.ny+q.nz*q.nz>.5?L.push(q.nx,q.ny,q.nz):L.push(Q.nx,Q.ny,Q.nz),O.push(q.u,q.v);for(let q=1;q<K.length-1;q++)I.push(Z,Z+q,Z+q+1)}let W=R(new u,S,L,O,I);return W._csgPolygons=A,W}function D(A,S,L){if(A.length+S.length>p)throw new RangeError(`SecurityError: Combined CSG triangle count (${A.length+S.length}) exceeds MAX_CSG_TRIANGLES (${p})`);if(A.length===0)return L==="union"?S:[];if(S.length===0)return L==="intersect"?[]:A;let O=1/0,I=1/0,W=1/0,Q=-1/0,K=-1/0,Z=-1/0;for(let ue=0;ue<S.length;ue++){let me=S[ue].vertices;for(let pe=0;pe<me.length;pe++){let fe=me[pe];fe.x<O&&(O=fe.x),fe.y<I&&(I=fe.y),fe.z<W&&(W=fe.z),fe.x>Q&&(Q=fe.x),fe.y>K&&(K=fe.y),fe.z>Z&&(Z=fe.z)}}O-=1e-4,I-=1e-4,W-=1e-4,Q+=1e-4,K+=1e-4,Z+=1e-4;let q=[],re=[];for(let ue=0;ue<A.length;ue++){let me=A[ue],pe=me.vertices,fe=1/0,de=1/0,ye=1/0,we=-1/0,be=-1/0,_e=-1/0;for(let Te=0;Te<pe.length;Te++){let Ce=pe[Te];Ce.x<fe&&(fe=Ce.x),Ce.y<de&&(de=Ce.y),Ce.z<ye&&(ye=Ce.z),Ce.x>we&&(we=Ce.x),Ce.y>be&&(be=Ce.y),Ce.z>_e&&(_e=Ce.z)}we<O||fe>Q||be<I||de>K||_e<W||ye>Z?re.push(me):q.push(me)}if(q.length===0)return L==="union"?A.concat(S):L==="subtract"?A:[];let ne=new U(q),te=new U(S);return L==="union"?(ne.clipTo(te),te.clipTo(ne),te.invert(),te.clipTo(ne),te.invert(),ne.build(te.allPolygons()),re.concat(ne.allPolygons())):L==="subtract"?(ne.invert(),ne.clipTo(te),te.clipTo(ne),te.invert(),te.clipTo(ne),te.invert(),ne.build(te.allPolygons()),ne.invert(),re.concat(ne.allPolygons())):(ne.invert(),te.clipTo(ne),te.invert(),ne.clipTo(te),te.clipTo(ne),ne.build(te.allPolygons()),ne.invert(),ne.allPolygons())}function F(A,S,L,O=null,I=null){let W=_(A,O),Q=_(S,I);return H(D(W,Q,L))}function E(A,S,L){let O=A instanceof f||!!A?.isMesh,I=S instanceof f||!!S?.isMesh,W=O?A.geometry:A,Q=I?S.geometry:S,K=null;if(I)if(S.updateMatrix(),O){A.updateMatrix();let ne=new s().makeScale(1/(A.scale.x||1),1/(A.scale.y||1),1/(A.scale.z||1)),te=Math.hypot(A.quaternion.x,A.quaternion.y,A.quaternion.z,A.quaternion.w)||1,ue=new s().compose(new i(0,0,0),new n(-A.quaternion.x/te,-A.quaternion.y/te,-A.quaternion.z/te,A.quaternion.w/te),new i(1,1,1)),me=new s().makeTranslation(-A.position.x,-A.position.y,-A.position.z);K=ne.multiply(ue).multiply(me).multiply(S.matrix)}else K=S.matrix;let Z=F(W,Q,L,null,K),q=O?A.material:new c,re=new f(Z,q);return O&&(re.position.copy(A.position),re.quaternion.copy(A.quaternion),re.scale.copy(A.scale),re.name=A.name),re}let G={toGeometry:F,subtract(A,S){return E(A,S,"subtract")},union(A,S){return E(A,S,"union")},intersect(A,S){return E(A,S,"intersect")}},ee={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 se extends u{constructor(S="",L={}){super();let O=String(S??"").slice(0,g),I=Math.max(.005,Math.min(100,b(L.size,.2))),W=!!(L.bevelEnabled??!1),Q=W?Math.max(0,Math.min(2,b(L.bevelThickness,I*.04))):0,K=W?Math.max(0,Math.min(2,b(L.bevelSize,I*.03))):0,Z=Math.max(.001,Math.min(20,b(L.depth??L.height,I*.2)))+Q*2,q=I*.085+K,re=I*.68,ne=I*.82,te=[],ue=[],me=[],pe=[],fe=(we,be,_e,Te,Ce,Le,De)=>{let We=_e-we,$e=Te-be,at=Math.hypot(We,$e),Ke=1,ct=0;at>1e-6&&(Ke=We/at,ct=$e/at);let qt=-ct*Ce,Kt=Ke*Ce,St=Ke*Ce*.6,Rt=ct*Ce*.6,Ye=we-St+qt,pt=be-Rt+Kt,xe=we-St-qt,Re=be-Rt-Kt,Ie=_e+St-qt,Ve=Te+Rt-Kt,Be=_e+St+qt,et=Te+Rt+Kt,bt=(Ct,Et,_t,Lt,It,Ft,jt)=>{let wt=te.length/3;te.push(Ct[0],Ct[1],Ct[2],Et[0],Et[1],Et[2],_t[0],_t[1],_t[2],Lt[0],Lt[1],Lt[2]),ue.push(It,Ft,jt,It,Ft,jt,It,Ft,jt,It,Ft,jt),me.push(0,0,1,0,1,1,0,1),pe.push(wt,wt+1,wt+2,wt,wt+2,wt+3)};bt([Ye,pt,De],[xe,Re,De],[Ie,Ve,De],[Be,et,De],0,0,1),bt([xe,Re,Le],[Ye,pt,Le],[Be,et,Le],[Ie,Ve,Le],0,0,-1),bt([Ye,pt,Le],[xe,Re,Le],[xe,Re,De],[Ye,pt,De],-Ke,-ct,0),bt([Ie,Ve,Le],[Be,et,Le],[Be,et,De],[Ie,Ve,De],Ke,ct,0),bt([xe,Re,Le],[Ie,Ve,Le],[Ie,Ve,De],[xe,Re,De],ct,-Ke,0),bt([Be,et,Le],[Ye,pt,Le],[Ye,pt,De],[Be,et,De],-ct,Ke,0)},de=0,ye=0;for(let we=0;we<O.length;we++){let be=O[we];if(be===`
17
- `){de=0,ye-=I*1.35;continue}if(be===" "||be===" "){de+=ne*(be===" "?.75:3);continue}if(be==="\r")continue;let _e=be.toUpperCase(),Te=be!==_e&&be>="a"&&be<="z",Ce=ee[_e]??ee["?"],Le=Te?I*.76:I,De=Te?re*.88:re;for(let We of Ce)for(let $e=0;$e<We.length-1;$e++){let at=We[$e],Ke=We[$e+1];fe(de+at[0]*De,ye+at[1]*Le,de+Ke[0]*De,ye+Ke[1]*Le,q,-Z*.5,Z*.5)}de+=Te?ne*.88:ne}R(this,te,ue,me,pe),L.center!==!1?this.center():this.computeBoundingBox()}}function oe(A){if(!A)return;let S=A,L=A.userData?.xr?.text??A.userData?.xr?.label??A.userData?.xr?.title??A.userData?.xr?.caption??A.userData?.xr?.spatialLabel;if(L!=null&&L!==!1){let I=S.geometry?.attributes?.position;if((!I||I.count===0)&&A.userData._textApplied!==!0){let W="",Q=.08,K=.015,Z;if(typeof L=="string"||typeof L=="number")W=String(L);else if(typeof L=="object"){let q=L;W=String(q.text??q.value??""),q.size!==void 0&&(Q=Number(q.size)||.08),(q.depth!==void 0||q.height!==void 0)&&(K=Number(q.depth??q.height)||Q*.2),(typeof q.color=="string"||typeof q.color=="number")&&(Z=q.color)}W.trim().length>0&&(S.geometry=new se(W,{size:Q,depth:K}),A.userData._textApplied=!0,S.material instanceof h?Z!==void 0&&A.userData._autoTextColorApplied!==!0&&(S.material.color=new o(Z),A.userData._autoTextColorApplied=!0):S.material=new c({color:Z??16317180}))}}let O=A.userData?.csg;if(O&&typeof O=="object"&&A.userData._csgApplied!==!0&&S.geometry instanceof u&&S.geometry.attributes.position?.count>0){A.userData._csgApplied=!0;let I=Array.isArray(O)?O:[O],W=S.geometry;for(let Q of I){if(!Q||typeof Q!="object")continue;let K=Q,Z=String(K.op??K.operation??"subtract"),q=Z==="union"||Z==="intersect"?Z:"subtract",re=K.target??K.mesh??K.geometry;if(re instanceof f||re instanceof u)try{let ne=q==="union"?G.union(S,re):q==="intersect"?G.intersect(S,re):G.subtract(S,re);S.geometry!==W&&S.geometry.dispose?.(),S.geometry=ne.geometry}catch(ne){typeof console<"u"&&console.warn("[three-live] userData.csg skipped:",ne)}}}}let j={Path:v,Shape:d,ShapeGeometry:P,ExtrudeGeometry:B,TextGeometry:se,CSG:G,MAX_CSG_TRIANGLES:p,MAX_BSP_DEPTH:m,MAX_TEXT_GEOMETRY_CHARS:g,MAX_SHAPE_POINTS:x,materializeDeclarativeGeometry:oe};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,j),t._cadMaterialize=oe,t.materializeDeclarativeGeometry=A=>{t._cadMaterialize?.(A),t._lodMaterialize?.(A)}),j}var xi={name:"cad",onRegister(){Jt(tr);let e=Me(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&tr(t,e)}};function Se(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function nr(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 en(e,t,r,i){let[n,s,l]=t,[o,a,u]=i,[h,c,f]=r,p=n-h,m=s-c,g=l-f,x=Math.hypot(p,m,g);x<=1e-5?(p=0,m=0,g=1):(p/=x,m/=x,g/=x);let b=a*g-u*m,v=u*p-o*g,d=o*m-a*p;x=Math.hypot(b,v,d),x<=1e-5?(b=0,v=0,d=0):(b/=x,v/=x,d/=x);let y=m*d-g*v,M=g*b-p*d,T=p*v-m*b;return x=Math.hypot(y,M,T),x<=1e-5?(y=0,M=0,T=0):(y/=x,M/=x,T/=x),e[0]=b,e[1]=y,e[2]=p,e[3]=0,e[4]=v,e[5]=M,e[6]=m,e[7]=0,e[8]=d,e[9]=T,e[10]=g,e[11]=0,e[12]=-(b*n+v*s+d*l),e[13]=-(y*n+M*s+T*l),e[14]=-(p*n+m*s+g*l),e[15]=1,e}function Pe(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],c=t[8],f=t[9],p=t[10],m=t[11],g=t[12],x=t[13],b=t[14],v=t[15],d=r[0],y=r[1],M=r[2],T=r[3];return e[0]=d*i+y*o+M*c+T*g,e[1]=d*n+y*a+M*f+T*x,e[2]=d*s+y*u+M*p+T*b,e[3]=d*l+y*h+M*m+T*v,d=r[4],y=r[5],M=r[6],T=r[7],e[4]=d*i+y*o+M*c+T*g,e[5]=d*n+y*a+M*f+T*x,e[6]=d*s+y*u+M*p+T*b,e[7]=d*l+y*h+M*m+T*v,d=r[8],y=r[9],M=r[10],T=r[11],e[8]=d*i+y*o+M*c+T*g,e[9]=d*n+y*a+M*f+T*x,e[10]=d*s+y*u+M*p+T*b,e[11]=d*l+y*h+M*m+T*v,d=r[12],y=r[13],M=r[14],T=r[15],e[12]=d*i+y*o+M*c+T*g,e[13]=d*n+y*a+M*f+T*x,e[14]=d*s+y*u+M*p+T*b,e[15]=d*l+y*h+M*m+T*v,e}function yt(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,c=n*a,f=n*u,p=n*h,m=s*u,g=s*h,x=l*h,b=o*a,v=o*u,d=o*h,y=i[0],M=i[1],T=i[2];return e[0]=(1-(m+x))*y,e[1]=(f+d)*y,e[2]=(p-v)*y,e[3]=0,e[4]=(f-d)*M,e[5]=(1-(c+x))*M,e[6]=(g+b)*M,e[7]=0,e[8]=(p+v)*T,e[9]=(g-b)*T,e[10]=(1-(c+m))*T,e[11]=0,e[12]=r[0],e[13]=r[1],e[14]=r[2],e[15]=1,e}function ze(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],c=t[10],f=c*o-a*h,p=-c*l+a*u,m=h*l-o*u,g=i*f+n*p+s*m;return!g||r>0&&(!Number.isFinite(g)||Math.abs(g)<=r)||(g=1/g,e[0]=f*g,e[1]=p*g,e[2]=m*g,e[3]=(-c*n+s*h)*g,e[4]=(c*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 tn(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],c=t[9],f=t[10],p=t[11],m=t[12],g=t[13],x=t[14],b=t[15],v=r*o-i*l,d=r*a-n*l,y=r*u-s*l,M=i*a-n*o,T=i*u-s*o,V=n*u-s*a,X=h*g-c*m,P=h*x-f*m,R=h*b-p*m,C=c*x-f*g,B=c*b-p*g,N=f*b-p*x,w=v*N-d*B+y*C+M*R-T*P+V*X;return w?(w=1/w,e[0]=(o*N-a*B+u*C)*w,e[1]=(n*B-i*N-s*C)*w,e[2]=(g*V-x*T+b*M)*w,e[3]=(f*T-c*V-p*M)*w,e[4]=(a*R-l*N-u*P)*w,e[5]=(r*N-n*R+s*P)*w,e[6]=(x*y-m*V-b*d)*w,e[7]=(h*V-f*y+p*d)*w,e[8]=(l*B-o*R+u*X)*w,e[9]=(i*R-r*B-s*X)*w,e[10]=(m*T-g*y+b*v)*w,e[11]=(c*y-h*T-p*v)*w,e[12]=(o*P-l*C-a*X)*w,e[13]=(r*C-i*P+n*X)*w,e[14]=(g*d-m*M-x*v)*w,e[15]=(h*M-c*d+f*v)*w,e):null}function vi(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 qo(e,t,r,i,n,s,l,o,a,u,h,c,f,p,m,g,x=0){let b=u-l,v=h-o,d=c-a,y=f-l,M=p-o,T=m-a,V=n*T-s*M,X=s*y-i*T,P=i*M-n*y,R=b*V+v*X+d*P;if(R>-1e-7&&R<1e-7)return!1;let C=1/R,B=e-l,N=t-o,w=r-a,ie=C*(B*V+N*X+w*P);if(ie<-x||ie>1+x)return!1;let ae=N*d-w*v,k=w*b-B*d,J=B*v-N*b,z=C*(i*ae+n*k+s*J);if(z<-x||ie+z>1+x)return!1;let Y=C*(y*ae+M*k+T*J);if(Y>1e-4&&Y<g.distance){g.distance=Y,g.point=[e+i*Y,t+n*Y,r+s*Y];let le=v*T-d*M,ce=d*y-b*T,$=b*M-v*y,U=Math.hypot(le,ce,$)||1;return g.normal=[le/U,ce/U,$/U],!0}return!1}function Vt(e,t){let r=Array.isArray(e?.nodes)?e.nodes.length:0,i=[];for(let h=0;h<r;h++)i.push(Se());if(r===0)return i;let n=new Set;for(let h of e.nodes)if(Array.isArray(h.children))for(let c of h.children)n.add(c);let s=new Set,l=128,o=(h,c,f=0)=>{if(f>l||h<0||h>=r||s.has(h))return;s.add(h);let p=e.nodes[h];if(!p)return;let m=Se();if(t&&t[h])m.set(t[h]);else if(p.matrix&&p.matrix.length===16)m.set(p.matrix);else{let x=p.translation||[0,0,0],b=p.rotation||[0,0,0,1],v=p.scale||[1,1,1];yt(m,b,x,v)}let g=i[h];if(c?Pe(g,c,m):g.set(m),Array.isArray(p.children))for(let x of p.children)typeof x=="number"&&o(x,g,f+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 Ai(e,t){function r(a,u,h,c){let f=typeof a=="number"?a:Number(a);return Number.isFinite(f)?Math.max(u,Math.min(h,f)):c}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 c=a[1]*u[2]-a[2]*u[1],f=a[2]*u[0]-a[0]*u[2],p=a[0]*u[1]-a[1]*u[0],m=Math.hypot(c,f,p,h)||1;return[c/m,f/m,p/m,h/m]}function n(a,u,h,c,f){let p=u[0]-a[0],m=u[1]-a[1],g=u[2]-a[2],x=Math.hypot(p,m,g),b=h[0]-u[0],v=h[1]-u[1],d=h[2]-u[2],y=Math.hypot(b,v,d);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=[p/x,m/x,g/x],T=[b/y,v/y,d/y],V=c[0]-a[0],X=c[1]-a[1],P=c[2]-a[2],R=Math.hypot(V,X,P),C=R>1e-6?[V/R,X/R,P/R]:M,B=Math.abs(x-y)+1e-5,N=Math.max(B,x+y-1e-5),w=Math.max(B,Math.min(N,R>1e-6?R:B)),ie=r((x*x+w*w-y*y)/(2*x*w),-1,1,1),ae=Math.sqrt(Math.max(0,1-ie*ie)),k=f?f[0]-a[0]:p,J=f?f[1]-a[1]:m,z=f?f[2]-a[2]:g,Y=k*C[0]+J*C[1]+z*C[2],le=k-C[0]*Y,ce=J-C[1]*Y,$=z-C[2]*Y,U=Math.hypot(le,ce,$);if(U<=1e-6){let A=Math.abs(C[1])<.99?0:1,S=Math.abs(C[1])<.99?1:0,L=0;le=C[1]*L-C[2]*S,ce=C[2]*A-C[0]*L,$=C[0]*S-C[1]*A,U=Math.hypot(le,ce,$)||1}let _=[le/U,ce/U,$/U],H=[a[0]+C[0]*(x*ie)+_[0]*(x*ae),a[1]+C[1]*(x*ie)+_[1]*(x*ae),a[2]+C[2]*(x*ie)+_[2]*(x*ae)],D=[a[0]+C[0]*w,a[1]+C[1]*w,a[2]+C[2]*w],F=D[0]-H[0],E=D[1]-H[1],G=D[2]-H[2],ee=Math.hypot(F,E,G),se=ee>1e-6?[F/ee,E/ee,G/ee]:C,oe=[H[0]+se[0]*y,H[1]+se[1]*y,H[2]+se[2]*y],j=[(H[0]-a[0])/x,(H[1]-a[1])/x,(H[2]-a[2])/x];return{rootPos:[a[0],a[1],a[2]],midPos:H,effectorPos:oe,rootRotation:i(M,j),midRotation:i(T,se)}}function s(a,u,h=8,c=.001){let f=a.length;if(f<2)return{positions:a.map(R=>[R[0],R[1],R[2]]),rotations:[],iterations:0};let p=a.map(R=>[R[0],R[1],R[2]]),m=[],g=[],x=0;for(let R=0;R<f-1;R++){let C=p[R+1][0]-p[R][0],B=p[R+1][1]-p[R][1],N=p[R+1][2]-p[R][2],w=Math.hypot(C,B,N);m.push(w),x+=w,g.push(w>1e-6?[C/w,B/w,N/w]:[0,1,0])}let b=[p[0][0],p[0][1],p[0][2]],v=Math.round(r(h,1,32,8)),d=r(c,1e-5,.1,.001),y=u[0]-b[0],M=u[1]-b[1],T=u[2]-b[2],V=Math.hypot(y,M,T),X=0;if(V>=x&&x>1e-6){let R=V>1e-6?[y/V,M/V,T/V]:g[0];p[0]=[b[0],b[1],b[2]];for(let C=0;C<f-1;C++){let B=m[C];p[C+1]=[p[C][0]+R[0]*B,p[C][1]+R[1]*B,p[C][2]+R[2]*B]}X=1}else for(let R=1;R<=v;R++){let C=p[f-1];if(Math.hypot(C[0]-u[0],C[1]-u[1],C[2]-u[2])<=d)break;X=R;let B=(N,w,ie,ae,k)=>{let J=w[0]-N[0],z=w[1]-N[1],Y=w[2]-N[2],le=Math.hypot(J,z,Y);if(le>1e-6){let ce=ie/le;return[N[0]+J*ce,N[1]+z*ce,N[2]+Y*ce]}return[N[0]+ae[0]*ie*k,N[1]+ae[1]*ie*k,N[2]+ae[2]*ie*k]};p[f-1]=[u[0],u[1],u[2]];for(let N=f-2;N>=0;N--)p[N]=B(p[N+1],p[N],m[N],g[N],-1);p[0]=[b[0],b[1],b[2]];for(let N=0;N<f-1;N++)p[N+1]=B(p[N],p[N+1],m[N],g[N],1)}let P=[];for(let R=0;R<f-1;R++){let C=p[R+1][0]-p[R][0],B=p[R+1][1]-p[R][1],N=p[R+1][2]-p[R][2],w=Math.hypot(C,B,N),ie=w>1e-6?[C/w,B/w,N/w]:g[R];P.push(i(g[R],ie))}return{positions:p,rotations:P,iterations:X}}function l(a){if(!a||typeof a!="object"||Array.isArray(a))return null;let u=a;if(u.enabled===!1)return null;let h=d=>{if(typeof d!="string")return;let y=d.trim().slice(0,64);return/^[A-Za-z0-9_.:-]+$/.test(y)?y:void 0},c=d=>Array.isArray(d)&&d.length===3&&d.every(y=>typeof y=="number"&&Number.isFinite(y))?[r(d[0],-1e3,1e3,0),r(d[1],-1e3,1e3,0),r(d[2],-1e3,1e3,0)]:void 0,f=h(u.root),p=h(u.effector);if(!f||!p)return null;let m=h(u.mid),g=c(u.target)??h(u.target);if(!g)return null;let x=u.pole??u.poleTarget,b=c(x)??h(x),v=u.solver==="fabrik"?"fabrik":u.solver==="two-bone"||m?"two-bone":"fabrik";return{root:f,...m?{mid:m}:{},effector:p,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 nn=Ai(),Zo=nn.clampNum,Wa=nn.parseIKTrait,ir=nn.quatFromUnitVectors,Ei=nn.solveTwoBoneIK,Ri=nn.solveFABRIK,Qo=nn.IKSolver;function wi(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 ja(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 Ka(e,t,r,i,n){let s=Zo(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],c=a-e[2],f=Math.hypot(u,h,c);if(f>1e-6&&i>1e-6){let b=i/f;return[e[0]+u*b,e[1]+h*b,e[2]+c*b]}let p=r[0]-e[0],m=r[1]-e[1],g=r[2]-e[2],x=Math.hypot(p,m,g);if(x>1e-6&&i>1e-6){let b=i/x;return[e[0]+p*b,e[1]+m*b,e[2]+g*b]}return[l,o,a]}function qa(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return tn(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 Mi(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 Si(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return wi(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 qa(r,[s[0],s[1],s[2]])}return null}function Ti(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 Ya(e){return[-e[0],-e[1],-e[2],e[3]]}function _i(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 Za(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 _i([r*a,i*a,n*a,Math.cos(l*t)])}function Qa(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,c=e[9]/i,f=e[10]/i,p=n+a+f,m;if(p>0){let g=Math.sqrt(p+1)*2;m=[(u-c)/g,(h-l)/g,(s-o)/g,.25*g]}else if(n>a&&n>f){let g=Math.sqrt(1+n-a-f)*2;m=[.25*g,(o+s)/g,(h+l)/g,(u-c)/g]}else if(a>f){let g=Math.sqrt(1+a-n-f)*2;m=[(o+s)/g,.25*g,(c+u)/g,(h-l)/g]}else{let g=Math.sqrt(1+f-n-a)*2;m=[(h+l)/g,(c+u)/g,.25*g,(s-o)/g]}return _i(m)}function Ja(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),c=1-2*(i*i+s*s),f=2*(n*s-i*l),p=2*(i*s-n*l),m=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],d=t[x*4+2];e[x*4]=o*b+a*v+u*d,e[x*4+1]=h*b+c*v+f*d,e[x*4+2]=p*b+m*v+g*d}}function rr(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 Jo(e){e?.normalMatrix&&e?.transform&&ze(e.normalMatrix,e.transform)}var Yo=new WeakMap;function ec(e){let t=Yo.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)}),Yo.set(e,t)),t}function tc(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((P,R)=>{typeof P?.name=="string"&&P.name&&!s.has(P.name)&&s.set(P.name,R)});let l=(t.mid?[t.root,t.mid,t.effector]:[t.root,t.effector]).map(P=>s.get(P));if(l.some(P=>P===void 0))return!1;let o=l,a=ec(i);for(let P=1;P<o.length;P++){let R=a[o[P]],C=0;for(;R>=0&&R!==o[P-1]&&C++<256;)R=a[R];if(R!==o[P-1])return!1}let u=o[0],h=e.initialNodeTransforms,c=new Map,f=[],p=[u];for(;p.length&&f.length<4096;){let P=p.pop();if(c.has(P))continue;let R=h?.[P],C=n[P];c.set(P,{t:R?[R.t[0],R.t[1],R.t[2]]:C?.translation?[...C.translation]:[0,0,0],r:R?[R.r[0],R.r[1],R.r[2],R.r[3]]:C?.rotation?[...C.rotation]:[0,0,0,1],s:R?[R.s[0],R.s[1],R.s[2]]:C?.scale?[...C.scale]:[1,1,1]}),f.push(P);for(let B of Array.isArray(C?.children)?C.children:[])typeof B=="number"&&p.push(B)}let m=a[u],g=m>=0&&e.worldMatrices?.[m]?.length===16?Float32Array.from(e.worldMatrices[m]):Se(),x=new Map,b=()=>{let P=(R,C)=>{let B=c.get(R);if(!B)return;let N=Se();yt(N,B.r,B.t,B.s);let w=Se();Pe(w,C,N),x.set(R,w);for(let ie of Array.isArray(n[R]?.children)?n[R].children:[])typeof ie=="number"&&P(ie,w)};P(u,g)},v=P=>{let R=x.get(P);return[R[12],R[13],R[14]]};b();let d=o.map(v),y=P=>{if(typeof P=="string"&&!r.has(P)){let R=s.get(P),C=R!==void 0?x.get(R)??e.worldMatrices?.[R]:void 0;if(C&&C.length===16)return[C[12],C[13],C[14]]}return Si(P,r,e)},M=y(t.target);if(!M)return!0;let T=t.pole?y(t.pole)??void 0:void 0,V=es(d,t,M,T),X=Zo(t.weight,0,1,1);for(let P=0;P<o.length-1;P++){let R=rr(v(o[P]),v(o[P+1])),C=rr(V[P],V[P+1]);if(!R||!C)continue;let B=Za(ir(R,C),X),N=o[P],w=a[N],ie=w===m||w<0?g:x.get(w)??g,ae=Qa(ie),k=c.get(N);k.r=_i(Ti(Ya(ae),Ti(B,Ti(ae,k.r)))),b()}if(Array.isArray(e.worldMatrices))for(let[P,R]of x)e.worldMatrices[P]?.set&&e.worldMatrices[P].set(R);for(let P of e.meshes??[]){let R=x.get(P?.nodeIndex);R&&P.transform?.set&&(P.transform.set(R),Jo(P))}return!0}function es(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let n=Ei(e[0],e[1],e[2],r,i);return[e[0],n.midPos,n.effectorPos]}return Ri(e,r,t.iterations,t.tolerance).positions}function nc(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=rr([0,0,0],i[s]),u=rr(r[s],r[s+1]);!l||l.length<16||!o||o.length<16||!a||!u||(Ja(l,o,ir(a,u)),Jo(t[s]))}}var Li={name:"ik",onRegister(){let e=Me();Jt(Ai),Ai(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=Wa(n);if(!s||s.weight<=0)continue;if(!r){r=new Map;for(let d of t)d&&typeof d.name=="string"&&d.name&&r.set(d.name,d)}if(tc(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||Mi(i,s.root),o||Mi(i,s.effector),s.mid&&!a&&Mi(i,s.mid),!l||!o)continue;let u=Si(s.target,r,e);if(!u)continue;let h=s.pole?Si(s.pole,r,e)??void 0:void 0,c=a?[l,a,o]:[l,o],f=c.map(d=>d.name||"").join(">");if(!i.__ikRestOffsets||i.__ikRestKey!==f){let d=c.map(wi),y=[];for(let M=0;M<d.length-1;M++)y.push([d[M+1][0]-d[M][0],d[M+1][1]-d[M][1],d[M+1][2]-d[M][2]]);i.__ikRestOffsets=y,i.__ikRestKey=f,i.__ikRestMats=c.map(M=>Array.from(M.transform??M.modelMatrix??[]))}let p=i.__ikRestOffsets,m=[wi(l)],g=[];for(let d=0;d<p.length;d++){let y=m[d],M=p[d];m.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=es(m,s,u,h),b=m[0],v=[m[0]];for(let d=1;d<c.length;d++){let y=p[d-1],M=[b[0]+y[0],b[1]+y[1],b[2]+y[2]],T=[b[0]+(x[d][0]-x[d-1][0]),b[1]+(x[d][1]-x[d-1][1]),b[2]+(x[d][2]-x[d-1][2])],V=Ka(b,M,T,g[d-1],s.weight);ja(c[d],V),b=V,v.push(V)}nc(i,c,v)}}};function bn(e,t){let r=(h,c,f,p)=>{let m=typeof h=="number"?h:Number(h);return Number.isFinite(m)?Math.max(c,Math.min(f,m)):p};function i(h,c,f=0,p=.05,m){if(!h||!h.length)return-1;let g=h[0]>0?[0,...h]:h,x=Number.isFinite(c)?Math.max(0,c):0,b=Number.isFinite(p)?Math.max(0,Math.min(.5,p)):.05;if(typeof m=="number"&&Number.isFinite(m)&&m>0){let y=f===-1?m*(1-b):m*(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(f<0||f>=g.length||f===v)return v;if(v>f){let y=f;for(let M=f+1;M<=v&&x>=g[M]*(1+b);M++)y=M;return y}let d=f;for(let y=f;y>v&&x<g[y]*(1-b);y--)d=y-1;return d}function n(h){if(!h)return null;let c=h===!0?{distances:[4,10],ratios:[.5,.25]}:Array.isArray(h)?{distances:h}:typeof h=="object"?h:null;if(!c||c.enabled===!1)return null;let f=r(c.hysteresis,0,.5,.05),p=[],m;if(Array.isArray(c.levels)&&c.levels.length>0){let v=c.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 T=M,V=r(T.distance,0,1e4,y===0?0:y*4),X=typeof T.hysteresis=="number"?r(T.hysteresis,0,.5,f):void 0,P=typeof T.ratio=="number"?r(T.ratio,.05,1,.5):void 0,R=typeof T.childIndex=="number"&&Number.isFinite(T.childIndex)?Math.max(0,Math.round(T.childIndex)):void 0,C=typeof T.node=="string"&&/^[A-Za-z0-9_.:-]+$/.test(T.node.trim())?T.node.trim().slice(0,64):void 0;p.push({distance:V,...X!==void 0?{hysteresis:X}:{},...P!==void 0?{ratio:P}:{},...R!==void 0?{childIndex:R}:{},...C?{node:C}:{}})}p.sort((y,M)=>y.distance-M.distance),p.length>0&&p[0].distance>0&&p.unshift({distance:0,childIndex:0});let d=0;p=p.slice(0,8).map((y,M)=>{let T=M===0?0:Math.max(d,y.distance);return d=T,{...y,distance:T,childIndex:y.childIndex??M}})}if(Array.isArray(c.ratios)&&c.ratios.length>0){let v=[];for(let d of c.ratios.slice(0,7))typeof d=="number"&&v.push(r(d,.05,1,.5));v.length>0&&(m=v)}if(p.length===0){let v=Array.isArray(c.distances)?c.distances:[],d=[];for(let M of v.slice(0,8))typeof M=="number"&&d.push(r(M,0,1e4,4));if(d.length===0&&m&&m.length>0)for(let M=0;M<m.length;M++)d.push((M+1)*4);if(d.length===0&&c.cullDistance===void 0)return null;d.length===0||d[0]>0?d.unshift(0):m&&m.length===d.length&&m[0]===1&&(m=m.slice(1));let y=0;for(let M=0;M<Math.min(8,d.length);M++){let T=M===0?0:Math.max(y,d[M]);y=T;let V=M>0&&m?m[M-1]:void 0;p.push({distance:T,childIndex:M,...V!==void 0?{ratio:V}:{}})}}else if(!m){let v=[];for(let d=1;d<p.length;d++)typeof p[d].ratio=="number"&&v.push(p[d].ratio);v.length>0&&(m=v)}let g=p.map(v=>v.distance),x=g[g.length-1]??0,b=c.cullDistance!==void 0&&c.cullDistance!==null&&c.cullDistance!==!1?r(c.cullDistance,Math.max(1,x),1e4,100):void 0;return{levels:p,distances:g,...m?{ratios:m}:{},hysteresis:f,...b!==void 0?{cullDistance:b}:{}}}function s(h,c){let f=h?.attributes?.position;if(!f||!f.array||f.count<3)return h;let p=r(c,.05,1,.5),m=f.array,g=f.count,x=h.attributes?.normal?.array,b=h.attributes?.uv?.array,v=h.index?.array,d=Math.floor((v?v.length:g)/3);if(d<1)return h;let y=Math.max(1,Math.min(d,Math.round(d*p))),M=1/0,T=1/0,V=1/0,X=-1/0,P=-1/0,R=-1/0;for(let U=0;U<g;U++){let _=m[U*3],H=m[U*3+1],D=m[U*3+2];_<M&&(M=_),H<T&&(T=H),D<V&&(V=D),_>X&&(X=_),H>P&&(P=H),D>R&&(R=D)}let C=Math.max(1e-5,X-M),B=Math.max(1e-5,P-T),N=Math.max(1e-5,R-V),w=Math.max(C,B,N),ie=U=>{let _=Math.max(1,Math.round(C/w*U)),H=Math.max(1,Math.round(B/w*U)),D=Math.max(1,Math.round(N/w*U)),F=new Map,E=new Int32Array(g),G=[],ee=[],se=[],oe=[];for(let I=0;I<g;I++){let W=m[I*3],Q=m[I*3+1],K=m[I*3+2],Z=Math.min(_-1,Math.max(0,Math.floor((W-M)/C*_))),q=Math.min(H-1,Math.max(0,Math.floor((Q-T)/B*H))),re=Math.min(D-1,Math.max(0,Math.floor((K-V)/N*D))),ne=Z+q*_+re*_*H,te=F.get(ne);te===void 0?(te=oe.length,F.set(ne,te),G.push(W,Q,K),x&&ee.push(x[I*3],x[I*3+1],x[I*3+2]),b&&se.push(b[I*2],b[I*2+1]),oe.push(1)):(G[te*3]+=W,G[te*3+1]+=Q,G[te*3+2]+=K,x&&(ee[te*3]+=x[I*3],ee[te*3+1]+=x[I*3+1],ee[te*3+2]+=x[I*3+2]),oe[te]++),E[I]=te}let j=[],A=new Set;for(let I=0;I<d;I++){let W=v?v[I*3]:I*3,Q=v?v[I*3+1]:I*3+1,K=v?v[I*3+2]:I*3+2,Z=E[W],q=E[Q],re=E[K];if(Z===q||q===re||re===Z)continue;let ne=Math.min(Z,q,re),te=Math.max(Z,q,re),ue=Z+q+re-ne-te,me=`${ne}_${ue}_${te}`;A.has(me)||(A.add(me),j.push(Z,q,re))}let S=oe.length,L=new Float32Array(S*3),O=x?new Float32Array(S*3):null;for(let I=0;I<S;I++){let W=1/oe[I];if(L[I*3]=G[I*3]*W,L[I*3+1]=G[I*3+1]*W,L[I*3+2]=G[I*3+2]*W,O){let Q=ee[I*3],K=ee[I*3+1],Z=ee[I*3+2],q=Math.hypot(Q,K,Z)||1;O[I*3]=Q/q,O[I*3+1]=K/q,O[I*3+2]=Z/q}}return{pos:L,norm:O,uv:b?new Float32Array(se):null,tris:j,triCount:j.length/3,vertCount:S}},ae=Math.max(2,Math.round(Math.sqrt(y/4))),k=ie(ae);if(k.triCount>y*1.25&&ae>2){let U=Math.max(2,Math.round(ae*Math.sqrt(y/k.triCount)));if(U!==ae){let _=ie(U);_.triCount>=Math.min(4,y)&&(k=_)}}else if(k.triCount<Math.min(4,y)){let U=ie(Math.max(ae*2,8));U.triCount>k.triCount&&(k=U)}let J=k.tris;if(p<1&&k.triCount>y){let U=[],_=k.triCount/y;for(let H=0;H<y;H++){let D=Math.min(k.triCount-1,Math.floor(H*_));U.push(k.tris[D*3],k.tris[D*3+1],k.tris[D*3+2])}J=U}if(J.length<3){J=[];for(let U=0;U<y*3;U++)J.push(v?v[U]:U);k={pos:m.slice(),norm:x?x.slice():null,uv:b?b.slice():null,tris:J,triCount:y,vertCount:g}}let z=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),Y=z?.BufferGeometry??h.constructor,le=z?.BufferAttribute??f.constructor,ce=new Y;ce.setAttribute("position",new le(k.pos,3)),k.norm&&ce.setAttribute("normal",new le(k.norm,3)),k.uv&&ce.setAttribute("uv",new le(k.uv,2));let $=k.vertCount>65535?new Uint32Array(J):new Uint16Array(J);return typeof ce.setIndex=="function"?ce.setIndex(new le($,1)):ce.index=new le($,1),ce}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 c of h)c&&(c.parent=this,this.children.push(c));return this}};class o extends l{constructor(){super(),this.isLOD=!0,this.type="LOD",this.autoUpdate=!0,this.levels=[],this._currentLevel=0}addLevel(c,f=0,p=.05){if(!c)return this;let m=Math.max(0,Number.isFinite(Number(f))?Number(f):0),g=r(p,0,.5,.05),x=this.levels.length;for(let d=0;d<this.levels.length;d++)if(m<this.levels[d].distance){x=d;break}this.levels.splice(x,0,{object:c,distance:m,hysteresis:g}),this.add(c);let b=this.levels.map(d=>d.object),v=this.children.filter(d=>!b.includes(d));this.children=[...b,...v];for(let d=0;d<this.levels.length;d++)this.levels[d].object.visible=d===this._currentLevel;return this.syncUserDataTrait(),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(c){if(!this.levels.length)return null;let f=i(this.levels.map(p=>p.distance),c,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);return f>=0&&f<this.levels.length?this.levels[f].object:null}update(c){if(this.levels.length===0||!c)return;let f=c.position??{x:0,y:0,z:0},p=this.position??{x:0,y:0,z:0},m=Math.hypot((Number(f.x)||0)-(Number(p.x)||0),(Number(f.y)||0)-(Number(p.y)||0),(Number(f.z)||0)-(Number(p.z)||0)),g=i(this.levels.map(x=>x.distance),m,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 c=this.userData.xr.lod?.cullDistance;this.userData.xr.lod={levels:this.levels.map((f,p)=>({distance:f.distance,hysteresis:f.hysteresis,childIndex:p,...f.object?.name?{node:f.object.name}:{}})),distances:this.levels.map(f=>f.distance),hysteresis:this.levels[0]?.hysteresis??.05,...c!==void 0?{cullDistance:c}:{}}}}function a(h){if(!h||h._lodMaterialized||!h.userData?.xr?.lod||h.isLOD||Array.isArray(h.children)&&h.children.length>0)return;let c=h.geometry?.attributes?.position;if(!c||!c.array||c.count<3)return;let f=n(h.userData.xr.lod);if(!f||f.levels.length<2)return;h._lodMaterialized=!0;let p=h.geometry;h._lodOriginalGeometry=p;let m=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),g=m?.Mesh??h.constructor,x=m?.BufferGeometry??p.constructor,b=typeof h.name=="string"&&h.name.trim()?h.name.trim():"Mesh",v=new g(p,h.material);v.name=`${b}_LOD0`,v.visible=!0,v.castShadow=!!h.castShadow,v.receiveShadow=!!h.receiveShadow,h.add(v);for(let d=1;d<f.levels.length;d++){let y=f.levels[d].ratio??f.ratios?.[d-1]??Math.max(.05,Math.pow(.5,d)),M=s(p,y),T=new g(M,h.material);T.name=`${b}_LOD${d}`,T.visible=!1,T.castShadow=!!h.castShadow,T.receiveShadow=!!h.receiveShadow,h.add(T)}h.geometry=new x,h.userData.xr.lod={...f,levels:f.levels.map((d,y)=>({...d,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 gn=bn(),ts=gn.decimateGeometry,or=gn.selectLodLevelIndex,sr=gn.parseLod,Vu=gn.materializeLodGeometry,ns=gn.LOD,pn=new WeakMap;function rs(e){return e&&typeof e=="object"?pn.get(e):void 0}var yn=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(p=>typeof p=="number"&&Number.isInteger(p)&&p>=0&&p<e.length):[],o=sr(s);if(!o&&l.length>0&&(o=sr({distances:l.map((p,m)=>m*4)})),!o)continue;let a=l.length>0?l:Array.isArray(n.children)?n.children.filter(p=>typeof p=="number"&&Number.isInteger(p)&&p>=0&&p<e.length):[],u=[],h=[];if(a.length>0){let p=Math.min(a.length,o.levels.length);for(let m=0;m<p;m++){let g=a[m];u.push(g),h.push(r(g))}}else{let p=t.get(i)??[];if(p.length===0)continue;u.push(i),h.push(p)}let c=o.distances.slice(0,h.length);c.length===0&&c.push(0);let f={nodeIndex:i,name:typeof n.name=="string"?n.name:`LOD_${i}`,distances:c,hysteresis:o.hysteresis,...o.cullDistance!==void 0?{cullDistance:o.cullDistance}:{},childNodeIndices:u,levelMeshes:h,activeLevelIndex:0,lastDistance:0};this.applyGroupVisibility(f,0),this.groups.push(f)}}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=or(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,c=Math.hypot((e[0]||0)-a,(e[1]||0)-u,(e[2]||0)-h);if(i.lastDistance=c,i.forcedLevelIndex!==void 0&&i.forcedLevelIndex!==null){i.activeLevelIndex!==i.forcedLevelIndex&&(i.activeLevelIndex=i.forcedLevelIndex,this.applyGroupVisibility(i,i.forcedLevelIndex));continue}let f=or(i.distances,c,i.activeLevelIndex,i.hysteresis,i.cullDistance);f!==i.activeLevelIndex&&(i.activeLevelIndex=f,this.applyGroupVisibility(i,f))}}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})}}},Ii={name:"lod",onRegister(){Jt(bn);let e=Me(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);bn(t,e)},onLoadModel(e,t){!e||typeof e!="object"||pn.set(e,new yn(e,t))},onUpdate(e){let t=pn.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=pn.get(e);n&&n.update(i)},onDestroy(e,t){t&&typeof t=="object"&&pn.delete(t)}},rc={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function ut(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=rc[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 c=new DataView(t),f=r.normalized===!0,p=new Float32Array(s*i);for(let m=0;m<s;m++){let g=h+m*u;for(let x=0;x<i;x++){let b=g+x*o,v;switch(l){case 5126:v=c.getFloat32(b,!0);break;case 5120:v=c.getInt8(b),f&&(v=Math.max(v/127,-1));break;case 5121:v=c.getUint8(b),f&&(v/=255);break;case 5122:v=c.getInt16(b,!0),f&&(v=Math.max(v/32767,-1));break;case 5123:v=c.getUint16(b,!0),f&&(v/=65535);break;default:v=c.getUint32(b,!0),f&&(v/=4294967295)}p[m*i+x]=v}}return p}function is(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,c=-(Number.isFinite(s)?s:1)*a,f=(Number.isFinite(s)?s:1)*o;for(let p=0;p+1<e.length;p+=2){let m=e[p],g=e[p+1];e[p]=u*m+h*g+r,e[p+1]=c*m+f*g+i}}function Dt(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 as=["neutral","reinhard","none","aces","agx"];function Bt(e){let t=String(e??"").trim().toLowerCase();return as.includes(t)?t:"neutral"}function ic(e){return as.indexOf(Bt(e))}function oc(e){return new TextDecoder().decode(e)}var cs=Me().decoders;function sc(e,t){cs.set(e.toLowerCase(),t)}function rn(e){return cs.get(e.toLowerCase())}function us(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 f=r.getUint8(0);throw f===123||f===32||f===10||f===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 f=r.getUint32(l,!0),p=r.getUint32(l+4,!0),m=l+8;if(m+f>t.byteLength)throw new Error(`Truncated GLB chunk: required ${m+f} bytes, buffer has ${t.byteLength}`);if(p===1313821514){let g=new Uint8Array(t,m,f),x=oc(g);o=JSON.parse(x,(b,v)=>b==="__proto__"||b==="constructor"||b==="prototype"?void 0:v)}else p===5130562&&(a=t.slice(m,m+f));l=m+f}if(!o)throw new Error("Missing JSON chunk in GLB");let u=o.extensionsRequired||[];if(u.includes("KHR_draco_mesh_compression")&&!rn("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let f of["EXT_meshopt_compression","KHR_meshopt_compression"])if(u.includes(f)&&!rn("meshopt"))throw new Error(`Model requires ${f}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(u.includes("KHR_texture_basisu")&&!rn("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let h=a||new ArrayBuffer(0),c={gltf:o,bin:h,animations:[]};for(let f of Oe)f.onParseGLB?.(c);return c}function ac(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 gt(e){if(ac(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return us(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var ls=`#version 300 es
16
+ */var Ec=Object.defineProperty,Kh=Object.getOwnPropertyDescriptor,Jh=Object.getOwnPropertyNames,Qh=Object.prototype.hasOwnProperty,Zh=(e,t)=>{for(var r in t)Ec(e,r,{get:t[r],enumerable:!0})},ep=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Jh(t))!Qh.call(e,n)&&n!==r&&Ec(e,n,{get:()=>t[n],enumerable:!(i=Kh(t,n))||i.enumerable});return e},tp=e=>ep(Ec({},"__esModule",{value:!0}),e),Qu={};Zh(Qu,{AIVoiceSession:()=>ki,AmbientLight:()=>mi,BoxGeometry:()=>ai,BufferAttribute:()=>Vt,BufferGeometry:()=>Nt,Camera:()=>pi,CapsuleGeometry:()=>ia,CatmullRomCurve3:()=>zs,CircleGeometry:()=>sa,Clock:()=>Zs,Color:()=>Bn,ConeGeometry:()=>Ds,CubicBezierCurve3:()=>Os,Curve3:()=>ar,CylinderGeometry:()=>ci,DataTexture:()=>Gs,DirectionalLight:()=>Ks,DodecahedronGeometry:()=>oa,EdgesGeometry:()=>la,Euler:()=>si,Float32BufferAttribute:()=>Ls,Group:()=>Ys,HemisphereLight:()=>vi,IKSolver:()=>wd,IMAGE_SYSTEM_PROMPT:()=>Tl,IcosahedronGeometry:()=>ra,InstancedMesh:()=>di,InteractivityVM:()=>Bi,LOD:()=>Td,LatheGeometry:()=>li,Light:()=>cr,LightShadow:()=>fi,Line:()=>kr,LineBasicMaterial:()=>io,LineCurve3:()=>Fs,LineDashedMaterial:()=>aa,LineLoop:()=>ua,LineSegments:()=>da,LodController:()=>Go,MAX_BSP_DEPTH:()=>hd,MAX_CSG_TRIANGLES:()=>md,MAX_INSTANCES_PER_MESH:()=>ui,MAX_SHADOW_LIGHTS:()=>Ao,MAX_SHAPE_POINTS:()=>bd,MAX_TEXT_GEOMETRY_CHARS:()=>pd,MAX_TSL_NODES:()=>Xd,MAX_TSL_UNIFORMS:()=>eo,Material:()=>vn,MathUtils:()=>cf,Matrix3:()=>Rs,Matrix4:()=>_r,Mesh:()=>qn,MeshBasicMaterial:()=>Hs,MeshLambertMaterial:()=>Ws,MeshPhongMaterial:()=>Xs,MeshPhysicalMaterial:()=>qs,MeshStandardMaterial:()=>Fr,Object3D:()=>Fn,OctahedronGeometry:()=>na,PART_STRIDE_BYTES:()=>Yi,PART_STRIDE_WORDS:()=>qi,PerspectiveCamera:()=>Js,PlaneGeometry:()=>Cs,PointLight:()=>hi,Points:()=>fa,PointsMaterial:()=>xi,PolyhedronFallbackGeometry:()=>l0,PolyhedronGeometry:()=>lr,QuadraticBezierCurve3:()=>Vs,Quaternion:()=>no,RawShaderMaterial:()=>vf,RectAreaLight:()=>ha,RingGeometry:()=>gi,SCENE_PBR_WGSL:()=>Ji,SCENE_PICK_WGSL:()=>fc,SCENE_SHADOW_WGSL:()=>dc,SCENE_UNIFORM_BYTES:()=>jr,SHADOW_MAP_TEXTURE_UNIT:()=>Cu,Scene:()=>bi,SceneQuotaValidator:()=>Xn,ShaderMaterial:()=>yi,SphereGeometry:()=>Ns,SpotLight:()=>ma,TEXTURE_PROMPT_SUFFIX:()=>Bl,THREE:()=>Vr,TSL_EXTENSION_NAME:()=>Br,TSL_TIME_PERIOD_SEC:()=>Wn,TSL_WGSL_UNIFORM_BYTES:()=>rh,TetrahedronGeometry:()=>ta,Texture:()=>ro,TextureLoader:()=>js,ThreeLiveElement:()=>kn,ThreeView:()=>Ht,TorusGeometry:()=>Us,TorusKnotGeometry:()=>Bs,TubeGeometry:()=>$s,Uint16BufferAttribute:()=>Ps,Uint32BufferAttribute:()=>Is,VERTEX_STRIDE_BYTES:()=>Hr,VERTEX_STRIDE_FLOATS:()=>Eo,Vector2:()=>tn,Vector3:()=>Ze,Vector4:()=>ks,WebGLRenderer:()=>Qs,WebGPUSceneAccelerator:()=>Zi,WireframeGeometry:()=>ca,acquireSceneWebGPUDevice:()=>qr,activateAR:()=>Xa,aiPlugin:()=>Ga,applyMeshoptFilter:()=>_u,authorScriptRunner:()=>so,browserImageCodec:()=>Ei,buildImageMessages:()=>El,buildImageUserText:()=>_l,buildSandboxWorkerSource:()=>sl,buildSelectIndex:()=>wi,cadPlugin:()=>kc,clearAuthorWarnings:()=>xf,compileFromImage:()=>Ra,compileTslToGlsl:()=>ws,compileTslToWgsl:()=>cc,computeOutlineClipOffset:()=>jm,computeWorldSceneBounds:()=>Du,connectVoice:()=>Ri,contactShadowPlugin:()=>Di,createAIChatProvider:()=>Ql,createAIImageProvider:()=>Fl,createUSDZBlob:()=>Zr,createWebSpeechRecognizer:()=>Kl,crossFadeTo:()=>ou,decimateGeometry:()=>Ad,decodeMeshoptBuffer:()=>Eu,decodeMeshoptGLB:()=>nc,defineModelViewer:()=>Af,describeEditResult:()=>$a,describeSelection:()=>Si,describeVoiceSelection:()=>bo,detectImageMime:()=>Rl,doesMeshCastShadow:()=>Gr,doesMeshReceiveShadow:()=>$i,editScene:()=>Zl,encodeMeshoptBuffer:()=>Vm,environmentMapPlugin:()=>yu,evaluateKawaseBloom:()=>Gm,evaluateToneMapping:()=>Id,exportSceneToCanvas3D:()=>nl,exportSceneToGLB:()=>rl,exportSceneToUSDZ:()=>df,extractMaterialVariants:()=>Ou,extractPrimitiveVariantMappings:()=>Zm,extractScript:()=>Ai,fitDirectionalShadowMatrix:()=>Uu,fitSpotShadowMatrix:()=>sc,fmtShaderFloat:()=>Un,formatSpatialPriors:()=>Ea,geminiLiveAdapter:()=>Yl,generateUSDZ:()=>Qo,getARCapabilities:()=>Wa,getAllowClientScripts:()=>hf,getAuthorWarnings:()=>gf,getBestARMode:()=>pm,getEnvironmentSH:()=>gm,getInteractivityVM:()=>Za,getLodController:()=>_d,getSandboxEngineSrc:()=>ol,getSandboxIframeSrc:()=>mf,getSelection:()=>nn,getShadowMapStats:()=>Km,getWebGPUSceneAccelerator:()=>Ro,glbToUSDZ:()=>Jo,hideSelectionChips:()=>mo,hotspotPlugin:()=>vu,ikPlugin:()=>Fc,imageRepairMessage:()=>kl,indexedDbTextureCache:()=>$l,installCadExtension:()=>cs,installLodExtension:()=>$o,installProceduralExtension:()=>ms,installTslExtension:()=>Zo,interactivityPlugin:()=>Au,isAllowedImageUrl:()=>On,isAllowedSandboxEngineUrl:()=>oo,isQuickLookSupported:()=>fu,isSceneViewerSupported:()=>mu,isWebXRSupported:()=>hu,keyframeAnimationPlugin:()=>iu,lodPlugin:()=>Vc,matchSelection:()=>va,materialsPlugin:()=>Tu,meshoptDecoder:()=>rc,meshoptPlugin:()=>ku,morphPlugin:()=>su,noopProxy:()=>oi,normalizeImageInput:()=>ka,normalizeRendererPreference:()=>Ju,normalizeShadowMapsMode:()=>Nu,packUniformVec4:()=>ei,parseAnimations:()=>ru,parseHexRgb:()=>Ru,parseLod:()=>fs,parseSafeGltfPointer:()=>Ui,parseSelectReply:()=>Al,parseTexturePack:()=>Ol,parseVoiceCommand:()=>wa,postprocessingPlugin:()=>Lu,prepareAlbedo:()=>Vl,proceduralPlugin:()=>Oc,quatFromUnitVectors:()=>us,realtimeAdapter:()=>ql,registerMaterialShader:()=>_m,remapClipDepthToZeroOne:()=>Xi,resetSceneWebGPUDevice:()=>_h,resolveActiveShadowLights:()=>Gi,resolveSceneRenderBackend:()=>xc,resolveSelection:()=>Ma,resolveSelectionWithModel:()=>Aa,sampleChannel:()=>go,sceneSelectEntries:()=>uo,sceneToCanvas3D:()=>Qr,sceneToGLB:()=>qo,sceneToUSDZ:()=>Ko,selectByVoice:()=>yo,selectCamera:()=>Sa,selectLodLevelIndex:()=>ds,selectMaterialVariant:()=>eh,selectMessages:()=>Ml,selectNamesByVoice:()=>Jl,sendInteractivityEvent:()=>Mu,serializeTexturePack:()=>zl,serializeTslToUsda:()=>Ss,setAllowClientScripts:()=>e0,setEnvironmentSH:()=>qa,setMaterialUniform:()=>ju,setMorphTargetWeight:()=>dm,setSandboxEngineSrc:()=>Kp,setSandboxIframeSrc:()=>Qp,setSceneWebGPUDeviceForTests:()=>Th,setSelectOnTap:()=>Pi,setSelection:()=>rn,shadowMapsPlugin:()=>Vu,showSelectionChips:()=>Va,skinningPlugin:()=>cu,solveFABRIK:()=>Uc,solveTwoBoneIK:()=>Dc,speakableName:()=>za,startVoiceEdit:()=>Li,textureRequests:()=>Na,threeAuthorPlugin:()=>ii,threeMicroPlugin:()=>f0,toGLBData:()=>wr,toTrustedWorkerScriptURL:()=>ff,tslPlugin:()=>uc,tslSafeMod:()=>vs,tslTypeArity:()=>Wt,tslTypeFromArity:()=>Kc,undoEdit:()=>eu,validateSandboxWorkerMessage:()=>al,validateTslGraph:()=>Sr,variantsPlugin:()=>zu,warnUnsupported:()=>Er,webgpuScenePlugin:()=>wc,webxrPlugin:()=>$u,writeSceneUniforms:()=>Ki}),module.exports=tp(Qu);function fd(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 os='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).',is="Security Error: client-side scripts require allow-client-scripts opt-in.",ss="__THREE_LIVE_REGISTRY__";function He(){let e=typeof globalThis<"u"?globalThis:{};if(!e[ss]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,ss,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[ss]=t}}return e[ss]}var kt=He().plugins;function jn(e){let t=He();t.workerExtensionInstallers||(t.workerExtensionInstallers=[]),t.workerExtensionInstallers.includes(e)||t.workerExtensionInstallers.push(e)}function gt(e){let t=He().plugins;t.some(r=>r.name===e.name)||t.push(e),e.onRegister?.()}function as(){return He().plugins}var md=8192,hd=2048,pd=128,bd=4096;function cs(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,De=Number(ce)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[pe,xe]}),this.currentPoint.set(Ee,De),this.segments.push({type:"cubic",pts:[pe,xe,he,Ne,ge,Ae,Ee,De]}),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,De=Number(ce)||0,ke=pe?1:0,ze=Number(xe)||0;this.segments.push({type:"arc",pts:[he,Ne,ge,Ae,Ee,De,ke,ze]});let Be=Math.cos(ze),Ue=Math.sin(ze),We=ge*Math.cos(De),Ge=Ae*Math.sin(De);return this.currentPoint.set(he+We*Be-Ge*Ue,Ne+We*Ue+Ge*Be),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 De=Ee/z,ke=1-De;X(ke*ke*pe+2*ke*De*he+De*De*ge,ke*ke*xe+2*ke*De*Ne+De*De*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],De=ce[7];X(pe,xe);for(let ke=1;ke<=z;ke++){let ze=ke/z,Be=1-ze,Ue=Be*Be,We=ze*ze;X(Ue*Be*pe+3*Ue*ze*he+3*Be*We*ge+We*ze*Ee,Ue*Be*xe+3*Ue*ze*Ne+3*Be*We*Ae+We*ze*De)}}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,De=ce[7],ke=Math.PI*2,ze=Ae-ge,Be=Math.abs(ze)<1e-9;for(;ze<0;)ze+=ke;for(;ze>ke;)ze-=ke;ze<1e-9&&(ze=Be?0:ke),Ee&&!Be&&(ze=ze===ke?-ke:ze-ke);let Ue=Math.cos(De),We=Math.sin(De),Ge=Math.max(2,z);for(let ut=0;ut<=Ge;ut++){let nt=ut/Ge,st=ge+nt*ze,ft=he*Math.cos(st),Qe=Ne*Math.sin(st);X(pe+ft*Ue-Qe*We,xe+ft*We+Qe*Ue)}}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,De=xe*xe+he*he,ke=xe*Ne+he*ge,ze=xe*Ae+he*Ee,Be=Ne*Ne+ge*ge,Ue=Ne*Ae+ge*Ee,We=De*Be-ke*ke;if(Math.abs(We)<1e-12)return!1;let Ge=1/We,ut=(Be*ze-ke*Ue)*Ge,nt=(De*Ue-ke*ze)*Ge;return ut>=-1e-7&&nt>=-1e-7&&ut+nt<=1+1e-7}function E(W,D){let z=W.slice();w(z)<0&&z.reverse();let O=z.map(xe=>new r(xe.x,xe.y)),X=z.map((xe,he)=>he),se=[];for(let xe of D){if(!xe||xe.length<3)continue;let he=xe.slice();w(he)>0&&he.reverse();let Ne=[],ge=-1/0,Ae=0;for(let Ee=0;Ee<he.length;Ee++){let De=he[Ee],ke=O.length;O.push(new r(De.x,De.y)),Ne.push(ke),De.x>ge&&(ge=De.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(Be=>O[Be]),Ee=Be=>Math.hypot(Ae[Be].x-Ne,Ae[Be].y-he.y),De=Ae.map((Be,Ue)=>Ue).sort((Be,Ue)=>+(Ae[Be].x<Ne)-+(Ae[Ue].x<Ne)||Ee(Be)-Ee(Ue)),ke=De[0];for(let Be of De){let Ue=Ae[Be],We=Ae[(Be+ge-1)%ge],Ge=Ae[(Be+1)%ge],ut=ce(Ue,Ge,he)>=0,nt=ce(We,Ue,he)>=0;if((ce(We,Ue,Ge)>=0?ut&&nt:ut||nt)&&!pe(he,Ue,Ae)&&!se.some(st=>pe(he,Ue,st.pts))){ke=Be;break}}let ze=[];for(let Be=0;Be<=ke;Be++)ze.push(X[Be]);for(let Be=0;Be<=xe.indices.length;Be++){let Ue=xe.indices[(xe.maxIdx+Be)%xe.indices.length];ze.push(Ue)}for(let Be=ke;Be<X.length;Be++)ze.push(X[Be]);X=ze}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,De=Math.min(Ne.x,ge.x,Ae.x)-1e-7,ke=Math.max(Ne.x,ge.x,Ae.x)+1e-7,ze=Math.min(Ne.y,ge.y,Ae.y)-1e-7,Be=Math.max(Ne.y,ge.y,Ae.y)+1e-7;for(let Ue=0;Ue<ce;Ue++){let We=O[Ue];if(We===pe||We===xe||We===he)continue;let Ge=D[We];if(Ge.x>=De&&Ge.x<=ke&&Ge.y>=ze&&Ge.y<=Be&&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,[De,ke,ze,Be]=_(ge);for(let Ue of ge)X.push(Ue.x,Ue.y,0),se.push(0,0,1),ce.push((Ue.x-De)/ze,(Ue.y-ke)/Be);for(let[Ue,We,Ge]of Ae)pe.push(Ee+Ue,Ee+We,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,De=-pe,ke=ge,ze=-Ne,Be=Ee+ke,Ue=De+ze,We=Math.hypot(Be,Ue);if(We>1e-6){Be/=We,Ue/=We;let Ge=Math.max(.35,Be*Ee+Ue*De);z.push(new r(Be/Ge,Ue/Ge))}else z.push(new r(Ee,De))}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=[],De=[],ke=[];for(let ze of O){if(!(ze instanceof A))continue;let Be=C(ze,X);if(Be.shape.length<3)continue;let Ue=Be.shape.slice();w(Ue)<0&&Ue.reverse();let We=[];for(let Pe of Be.holes){if(Pe.length<3)continue;let ot=Pe.slice();w(ot)>0&&ot.reverse(),We.push(ot)}let{mergedIndices:Ge,allVertices:ut}=E(Ue,We),nt=N(Ge,ut),st=[Ue,...We],ft=[];for(let Pe of st){let ot=$(Pe);for(let wt of ot)ft.push(wt)}let[Qe,It,Dt,yr]=_(ut);for(let[Pe,ot]of[[-xe,-1],[se+xe,1]]){let wt=Ae.length/3;for(let St=0;St<ut.length;St++){let Pt=ut[St],Lt=ft[St]??new r(0,0),Zt=Pt.x+Lt.x*Ne,Ot=Pt.y+Lt.y*Ne;Ae.push(Zt,Ot,Pe),Ee.push(0,0,ot),De.push((Zt-Qe)/Dt,(Ot-It)/yr)}for(let[St,Pt,Lt]of nt)ke.push(wt+St,wt+(ot<0?Lt:Pt),wt+(ot<0?Pt:Lt))}let Mt=[];if(pe&&ge>0)for(let Pe=0;Pe<ge;Pe++){let ot=Pe/ge*Math.PI/2;Mt.push({z:-xe*Math.cos(ot),expand:Ne+he*Math.sin(ot)})}for(let Pe=0;Pe<=ce;Pe++){let ot=Pe/ce;Mt.push({z:ot*se,expand:Ne+he})}if(pe&&ge>0)for(let Pe=1;Pe<=ge;Pe++){let ot=Pe/ge*Math.PI/2;Mt.push({z:se+xe*Math.sin(ot),expand:Ne+he*Math.cos(ot)})}let jt=0;for(let Pe of st){let ot=Pe.length;for(let wt=0;wt<Mt.length-1;wt++){let St=Mt[wt],Pt=Mt[wt+1];for(let Lt=0;Lt<ot;Lt++){let Zt=(Lt+1)%ot,Ot=Pe[Lt],Jt=Pe[Zt],er=ft[jt+Lt],tr=ft[jt+Zt],Nr=Ot.x+er.x*St.expand,on=Ot.y+er.y*St.expand,Tn=Jt.x+tr.x*St.expand,rr=Jt.y+tr.y*St.expand,nr=Jt.x+tr.x*Pt.expand,$n=Jt.y+tr.y*Pt.expand,wn=Ot.x+er.x*Pt.expand,cn=Ot.y+er.y*Pt.expand,Cr=Tn-Nr,Kt=rr-on,ul=wn-Nr,ts=cn-on,In=Pt.z-St.z,pn=Kt*In,dn=-Cr*In,gn=Cr*ts-Kt*ul,Pn=Math.hypot(pn,dn,gn)||1;pn/=Pn,dn/=Pn,gn/=Pn;let Ir=Ae.length/3;Ae.push(Nr,on,St.z,Tn,rr,St.z,nr,$n,Pt.z,wn,cn,Pt.z),Ee.push(pn,dn,gn,pn,dn,gn,pn,dn,gn,pn,dn,gn);let rs=Lt/ot,Bo=(Lt+1)/ot,hn=wt/(Mt.length-1),Yr=(wt+1)/(Mt.length-1);De.push(rs,hn,Bo,hn,Bo,Yr,rs,Yr),ke.push(Ir,Ir+1,Ir+2,Ir,Ir+2,Ir+3)}}jt+=ot}}R(this,Ae,Ee,De,ke)}}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 De=Ne*D.x+ge*D.y+Ae*D.z;return{vertices:W,nx:Ne,ny:ge,nz:Ae,w:De}}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,De=Ee<-ee?q:Ee>ee?G:k;he|=De,Ne.push(De)}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 Ue=0;Ue<Ee;Ue++){let We=(Ue+1)%Ee,Ge=Ne[Ue],ut=Ne[We],nt=X.vertices[Ue],st=X.vertices[We];if(Ge!==q&&ge.push(nt),Ge!==G&&Ae.push(Ge!==q?V(nt):nt),(Ge|ut)===H){let ft=st.x-nt.x,Qe=st.y-nt.y,It=st.z-nt.z,Dt=W*ft+D*Qe+z*It,yr=Math.abs(Dt)>1e-12?(O-(W*nt.x+D*nt.y+z*nt.z))/Dt:.5,Mt=J(nt,st,Math.max(0,Math.min(1,yr)));ge.push(Mt),Ae.push(V(Mt))}}let{nx:De,ny:ke,nz:ze,w:Be}=X;ge.length>=3&&pe.push({vertices:ge,nx:De,ny:ke,nz:ze,w:Be}),Ae.length>=3&&xe.push({vertices:Ae,nx:De,ny:ke,nz:ze,w:Be});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),De=z.getY(Ae),ke=z.getZ(Ae),ze=O?O.getX(Ae):NaN,Be=O?O.getY(Ae):NaN,Ue=O?O.getZ(Ae):NaN;if(pe&&he){let ut=pe[0]*Ee+pe[4]*De+pe[8]*ke+pe[12],nt=pe[1]*Ee+pe[5]*De+pe[9]*ke+pe[13],st=pe[2]*Ee+pe[6]*De+pe[10]*ke+pe[14];Ee=ut,De=nt,ke=st;let ft=he[0]*ze+he[3]*Be+he[6]*Ue,Qe=he[1]*ze+he[4]*Be+he[7]*Ue,It=he[2]*ze+he[5]*Be+he[8]*Ue,Dt=Math.hypot(ft,Qe,It)||1;ze=ft/Dt,Be=Qe/Dt,Ue=It/Dt}let We=X?X.getX(Ae):0,Ge=X?X.getY(Ae):0;return{x:Ee,y:De,z:ke,nx:ze,ny:Be,nz:Ue,u:We,v:Ge}},ge=[];for(let Ae=0;Ae<ce;Ae++){let Ee=se?se[Ae*3]:Ae*3,De=se?se[Ae*3+1]:Ae*3+1,ke=se?se[Ae*3+2]:Ae*3+2,ze=re(xe?[Ne(Ee),Ne(ke),Ne(De)]:[Ne(Ee),Ne(De),Ne(ke)]);ze&&ge.push(ze)}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 De=D[Ee].vertices;for(let ke=0;ke<De.length;ke++){let ze=De[ke];ze.x<O&&(O=ze.x),ze.y<X&&(X=ze.y),ze.z<se&&(se=ze.z),ze.x>ce&&(ce=ze.x),ze.y>pe&&(pe=ze.y),ze.z>xe&&(xe=ze.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 De=W[Ee],ke=De.vertices,ze=1/0,Be=1/0,Ue=1/0,We=-1/0,Ge=-1/0,ut=-1/0;for(let nt=0;nt<ke.length;nt++){let st=ke[nt];st.x<ze&&(ze=st.x),st.y<Be&&(Be=st.y),st.z<Ue&&(Ue=st.z),st.x>We&&(We=st.x),st.y>Ge&&(Ge=st.y),st.z>ut&&(ut=st.z)}We<O||ze>ce||Ge<X||Be>pe||ut<se||Ue>xe?Ne.push(De):he.push(De)}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)),De=new a().makeTranslation(-W.position.x,-W.position.y,-W.position.z);pe=ge.multiply(Ee).multiply(De).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 Fe={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=[],De=[],ke=[],ze=(We,Ge,ut,nt,st,ft,Qe)=>{let It=ut-We,Dt=nt-Ge,yr=Math.hypot(It,Dt),Mt=1,jt=0;yr>1e-6&&(Mt=It/yr,jt=Dt/yr);let Pe=-jt*st,ot=Mt*st,wt=Mt*st*.6,St=jt*st*.6,Pt=We-wt+Pe,Lt=Ge-St+ot,Zt=We-wt-Pe,Ot=Ge-St-ot,Jt=ut+wt-Pe,er=nt+St-ot,tr=ut+wt+Pe,Nr=nt+St+ot,on=(Tn,rr,nr,$n,wn,cn,Cr)=>{let Kt=Ae.length/3;Ae.push(Tn[0],Tn[1],Tn[2],rr[0],rr[1],rr[2],nr[0],nr[1],nr[2],$n[0],$n[1],$n[2]),Ee.push(wn,cn,Cr,wn,cn,Cr,wn,cn,Cr,wn,cn,Cr),De.push(0,0,1,0,1,1,0,1),ke.push(Kt,Kt+1,Kt+2,Kt,Kt+2,Kt+3)};on([Pt,Lt,Qe],[Zt,Ot,Qe],[Jt,er,Qe],[tr,Nr,Qe],0,0,1),on([Zt,Ot,ft],[Pt,Lt,ft],[tr,Nr,ft],[Jt,er,ft],0,0,-1),on([Pt,Lt,ft],[Zt,Ot,ft],[Zt,Ot,Qe],[Pt,Lt,Qe],-Mt,-jt,0),on([Jt,er,ft],[tr,Nr,ft],[tr,Nr,Qe],[Jt,er,Qe],Mt,jt,0),on([Zt,Ot,ft],[Jt,er,ft],[Jt,er,Qe],[Zt,Ot,Qe],jt,-Mt,0),on([tr,Nr,ft],[Pt,Lt,ft],[Pt,Lt,Qe],[tr,Nr,Qe],-jt,Mt,0)},Be=0,Ue=0;for(let We=0;We<O.length;We++){let Ge=O[We];if(Ge===`
17
+ `){Be=0,Ue-=X*1.35;continue}if(Ge===" "||Ge===" "){Be+=ge*(Ge===" "?.75:3);continue}if(Ge==="\r")continue;let ut=Ge.toUpperCase(),nt=Ge!==ut&&Ge>="a"&&Ge<="z",st=_e[ut]??_e["?"],ft=nt?X*.76:X,Qe=nt?Ne*.88:Ne;for(let It of st)for(let Dt=0;Dt<It.length-1;Dt++){let yr=It[Dt],Mt=It[Dt+1];ze(Be+yr[0]*Qe,Ue+yr[1]*ft,Be+Mt[0]*Qe,Ue+Mt[1]*ft,he,-xe*.5,xe*.5)}Be+=nt?ge*.88:ge}R(this,Ae,Ee,De,ke),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"?Fe.union(D,Ne):he==="intersect"?Fe.intersect(D,Ne):Fe.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:Fe,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 kc={name:"cad",onRegister(){jn(cs);let e=He(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&cs(t,e)}};function rt(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function Oo(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 yd(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 xr(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 at(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 or(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 Bt(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 Kr(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 Rc(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 gd(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 vr(e,t){let r=Array.isArray(e?.nodes)?e.nodes.length:0,i=[];for(let f=0;f<r;f++)i.push(rt());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=rt();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];or(g,y,v,A)}let x=i[f];if(m?at(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 Ic(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],Fe=Math.hypot(de,me,Se),_e=Fe>1e-6?[de/Fe,me/Fe,Se/Fe]: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 Jr=Ic(),vd=Jr.clampNum,np=Jr.parseIKTrait,us=Jr.quatFromUnitVectors,Dc=Jr.solveTwoBoneIK,Uc=Jr.solveFABRIK,wd=Jr.IKSolver;function Cc(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 rp(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 op(e,t,r,i,n){let a=vd(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 ip(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return Kr(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 Lc(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 Nc(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return Cc(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 ip(r,[a[0],a[1],a[2]])}return null}function Pc(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 sp(e){return[-e[0],-e[1],-e[2],e[3]]}function Bc(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 ap(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 Bc([r*l,i*l,n*l,Math.cos(s*t)])}function cp(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 Bc(g)}function lp(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 ls(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 Sd(e){e?.normalMatrix&&e?.transform&&Bt(e.normalMatrix,e.transform)}var xd=new WeakMap;function up(e){let t=xd.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)}),xd.set(e,t)),t}function dp(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=up(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]):rt(),v=new Map,y=()=>{let _=(P,R)=>{let $=m.get(P);if(!$)return;let F=rt();or(F,$.r,$.t,$.s);let V=rt();at(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 Nc(_,r,e)},S=w(t.target);if(!S)return!0;let E=t.pole?w(t.pole)??void 0:void 0,N=Md(b,t,S,E),C=vd(t.weight,0,1,1);for(let _=0;_<o.length-1;_++){let P=ls(A(o[_]),A(o[_+1])),R=ls(N[_],N[_+1]);if(!P||!R)continue;let $=ap(us(P,R),C),F=o[_],V=l[F],Y=V===g||V<0?x:v.get(V)??x,J=cp(Y),re=m.get(F);re.r=Bc(Pc(sp(J),Pc($,Pc(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),Sd(_))}return!0}function Md(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let n=Dc(e[0],e[1],e[2],r,i);return[e[0],n.midPos,n.effectorPos]}return Uc(e,r,t.iterations,t.tolerance).positions}function fp(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=ls([0,0,0],i[a]),c=ls(r[a],r[a+1]);!s||s.length<16||!o||o.length<16||!l||!c||(lp(s,o,us(l,c)),Sd(t[a]))}}var Fc={name:"ik",onRegister(){let e=He();jn(Ic),Ic(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=np(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(dp(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||Lc(i,a.root),o||Lc(i,a.effector),a.mid&&!l&&Lc(i,a.mid),!s||!o)continue;let c=Nc(a.target,r,e);if(!c)continue;let f=a.pole?Nc(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(Cc),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=[Cc(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=Md(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=op(y,S,E,x[b-1],a.weight);rp(m[b],N),y=N,A.push(N)}fp(i,m,A)}}};function $o(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=[],Fe=[],_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&&Fe.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&&(Fe[ge*3]+=v[O*3],Fe[ge*3+1]+=v[O*3+1],Fe[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=Fe[O*3],ce=Fe[O*3+1],pe=Fe[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 jo=$o(),Ad=jo.decimateGeometry,ds=jo.selectLodLevelIndex,fs=jo.parseLod,Jy=jo.materializeLodGeometry,Td=jo.LOD,zo=new WeakMap;function _d(e){return e&&typeof e=="object"?zo.get(e):void 0}var Go=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=fs(a);if(!o&&s.length>0&&(o=fs({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})}}},Vc={name:"lod",onRegister(){jn($o);let e=He(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);$o(t,e)},onLoadModel(e,t){!e||typeof e!="object"||zo.set(e,new Go(e,t))},onUpdate(e){let t=zo.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=zo.get(e);n&&n.update(i)},onDestroy(e,t){t&&typeof t=="object"&&zo.delete(t)}};function ms(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 je=b(T,u,d,M,L,I);if(Array.isArray(je)&&typeof je[0]=="string")return{uri:je[0],avgColor:[je[1],je[2],je[3],je[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,Ie=0,Ve=U===u&&j===d;for(let je=0;je<j;je++){ye[ve++]=0,Te=(Te+we)%65521;let Xe=M?j-1-je:je,it=Ve?Xe:Math.floor(Xe*d/j),bt=Ve?Xe+1:Math.max(it+1,Math.floor((Xe+1)*d/j));for(let pt=0;pt<U;pt++){let lt=0,xt=0,Tt=0,dt=0;if(Ve){let yt=(it*u+pt)*4;lt=T[yt]|0,xt=T[yt+1]|0,Tt=T[yt+2]|0,dt=T[yt+3]|0}else{let yt=Math.floor(pt*u/U),zt=Math.max(yt+1,Math.floor((pt+1)*u/U)),Et=0;for(let Ut=it;Ut<bt&&Ut<d;Ut++)for(let $t=yt;$t<zt&&$t<u;$t++){let Yt=(Ut*u+$t)*4;lt+=T[Yt]|0,xt+=T[Yt+1]|0,Tt+=T[Yt+2]|0,dt+=T[Yt+3]|0,Et++}Et>1&&(lt=lt/Et+.5|0,xt=xt/Et+.5|0,Tt=Tt/Et+.5|0,dt=dt/Et+.5|0)}ye[ve++]=lt,we+=lt,Te+=we,ye[ve++]=xt,we+=xt,Te+=we,ye[ve++]=Tt,we+=Tt,Te+=we,ye[ve++]=dt,we+=dt,Te+=we,Me+=L?lt/255:A[lt],be+=L?xt/255:A[xt],Ce+=L?Tt/255:A[Tt],Ie+=dt/255}we%=65521,Te%=65521}let Oe=43,qe=ue,Ke=0;for(;qe>0||Ke===0;){let je=Math.min(65535,qe),Xe=qe-je===0?1:0;if(oe[Oe++]=Xe,fe.setUint16(Oe,je,!0),fe.setUint16(Oe+2,~je&65535,!0),Oe+=4,je>0&&(oe.set(ye.subarray(Ke,Ke+je),Oe),Oe+=je,Ke+=je,qe-=je),Xe)break}fe.setUint32(Oe,(Te<<16|we)>>>0),Oe+=4,fe.setUint32(Oe,y(oe.subarray(37,Oe))),Oe+=4,fe.setUint32(Oe,0),fe.setUint32(Oe+4,1229278788),fe.setUint32(Oe+8,2923585666);let et=Math.max(1,U*j),Ye=[Me/et,be/et,Ce/et,Ie/et],tt=["data:image/png;base64,"];for(let je=0;je<oe.length;je+=3){let Xe=oe[je]<<16|(oe[je+1]??0)<<8|(oe[je+2]??0);tt.push(l[Xe>>18&63]+l[Xe>>12&63]+(je+1<oe.length?l[Xe>>6&63]:"=")+(je+2<oe.length?l[Xe&63]:"="))}return{uri:tt.join(""),avgColor:Ye}},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,Ie]=ve[(Te+1)%we];if(be===Ie)continue;let Ve=Math.min(be,Ie),Oe=Math.max(be,Ie);B.push([Ve,Oe,Ie>be?Me:Ce,(Ie>be?Ce-Me:Me-Ce)/(Oe-Ve),Ie>be?1:-1]),Ve<U&&(U=Ve),Oe>j&&(j=Oe)}}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),[Ie,Ve,Oe,qe,Ke,et]=q(T),Ye=T.canvas._bw,tt=T.canvas._bh,je=new Uint8Array(Ye*tt),Xe=le*ye;if(Xe<=1e-6||ue<=1e-6)return;let it=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,Tt=Q(lt,K),dt=G(T,xt,Te),yt=G(T,xt+Xe,Te),zt=G(T,xt+Xe,Te+ue),Et=G(T,xt,Te+ue),Ut=Math.max(0,Math.floor(Math.min(dt[0],yt[0],zt[0],Et[0]))),$t=Math.min(Ye-1,Math.ceil(Math.max(dt[0],yt[0],zt[0],Et[0]))),Yt=Math.max(0,Math.floor(Math.min(dt[1],yt[1],zt[1],Et[1]))),gr=Math.min(tt-1,Math.ceil(Math.max(dt[1],yt[1],zt[1],Et[1])));for(let mn=Yt;mn<=gr;mn++){let en=mn+.5;for(let Mn=Ut;Mn<=$t;Mn++){let es=mn*Ye+Mn;if(je[es])continue;let Gn=Mn+.5,Po=Ie*Gn+Ve*en+Oe,No=qe*Gn+Ke*en+et,Sn=(Po-xt)*it,An=(No-Te)*bt;if(Sn<0||Sn>=1||An<0||An>=1)continue;let an=Math.min(9,Sn*10|0),sn=Math.min(13,An*14|0);Tt[sn*10+an]===1&&(I&&an>0&&an<9&&sn>0&&sn<13&&Tt[sn*10+an-1]&&Tt[sn*10+an+1]&&Tt[(sn-1)*10+an]&&Tt[(sn+1)*10+an]||(je[es]=1,ie(T,Ce,Mn,mn,be(Gn,en))))}}}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,Ie=Me*Me;Z(this,Ce*be*j+3*Ce*Me*ue+3*be*Ie*oe+Ie*Me*ye,Ce*be*K+3*Ce*Me*le+3*be*Ie*fe+Ie*Me*ve)}}ellipse(u,d,M,L,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),Ie=u+be*fe-Ce*ye,Ve=d+be*ye+Ce*fe;Te===0&&(!this._cur||this._cur.pts.length===0)?this.moveTo(Ie,Ve):this.lineTo(Ie,Ve)}}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,Ie=ve/Te,Ve=Me*Ie-be*Ce;if(Math.abs(Ve)<1e-6){this.lineTo(u,d);return}let Oe=Math.acos(Math.max(-1,Math.min(1,Me*Ce+be*Ie)))*.5,qe=B/Math.tan(Oe),Ke=Me+Ce,et=be+Ie,Ye=Math.hypot(Ke,et)||1,tt=B/Math.sin(Oe),je=u+Ke/Ye*tt,Xe=d+et/Ye*tt;this.arc(je,Xe,B,Math.atan2(d+be*qe-Xe,u+Me*qe-je),Math.atan2(d+Ie*qe-Xe,u+Ce*qe-je),Ve>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,Ie,Ve,Oe)=>{let qe=Me,Ke=be,et=Ce,Ye=Ie,tt=et-qe,je=Ye-Ke,Xe=Math.hypot(tt,je);if(U==="square"&&Xe>1e-6){let dt=tt/Xe*I,yt=je/Xe*I;Ve&&(qe-=dt,Ke-=yt),Oe&&(et+=dt,Ye+=yt),tt=et-qe,je=Ye-Ke}let it=tt*tt+je*je,bt=I+.5,pt=Math.max(0,Math.floor(Math.min(qe,et)-bt)),lt=Math.min(j-1,Math.ceil(Math.max(qe,et)+bt)),xt=Math.max(0,Math.floor(Math.min(Ke,Ye)-bt)),Tt=Math.min(K-1,Math.ceil(Math.max(Ke,Ye)+bt));for(let dt=xt;dt<=Tt;dt++){let yt=dt+.5;for(let zt=pt;zt<=lt;zt++){let Et=dt*j+zt;if(oe[Et])continue;let Ut=zt+.5,$t=it>1e-9?((Ut-qe)*tt+(yt-Ke)*je)/it:0;if(U==="butt"&&($t<0&&Ve||$t>1&&Oe))continue;$t=Math.max(0,Math.min(1,$t));let Yt=qe+$t*tt,gr=Ke+$t*je;(Ut-Yt)*(Ut-Yt)+(yt-gr)*(yt-gr)<=B&&(oe[Et]=1,ie(this,le,zt,dt,ue(Ut,yt)))}}},we=Number(this.lineDashOffset),Te=Number.isFinite(we)?we:0;for(let Me of this._subs){let be=Me.pts,Ce=be.length;if(Ce<2)continue;let Ie=Me.closed?Ce:Ce-1,Ve=fe>1e-6?(Te*d%fe+fe)%fe:0;for(let Oe=0;Oe<Ie;Oe++){let[qe,Ke]=be[Oe],[et,Ye]=be[(Oe+1)%Ce];if(fe<=1e-6)ve(qe,Ke,et,Ye,!Me.closed&&Oe===0,!Me.closed&&Oe===Ie-1);else{let tt=Math.hypot(et-qe,Ye-Ke);if(tt<=1e-6)continue;let je=0;for(;je<tt;){let Xe=Ve,it=0;for(;it<ye.length&&Xe>=ye[it];)Xe-=ye[it],it++;let bt=Math.min(tt-je,it<ye.length?Math.max(.25,ye[it]-Xe):tt-je);if(it%2===0){let pt=je/tt,lt=(je+bt)/tt;ve(qe+(et-qe)*pt,Ke+(Ye-Ke)*pt,qe+(et-qe)*lt,Ke+(Ye-Ke)*lt,!0,!0)}je+=bt,Ve=(Ve+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 Ie=new Uint32Array(new Uint8Array([be&255,be>>>8&255,be>>>16&255,Ce]).buffer)[0],Ve=this.canvas._data,Oe=new Uint32Array(Ve.buffer,Ve.byteOffset,j*K);if(ye===0&&ve===j-1)Oe.fill(Ie,we*j,(Te+1)*j);else for(let qe=we;qe<=Te;qe++)Oe.fill(Ie,qe*j+ye,qe*j+ve+1);this.canvas._ver++;return}}let Me=be=>{let Ce=be+.5;for(let Ie=ye;Ie<=ve;Ie++)ie(this,B,Ie,be,I(Ie+.5,Ce))};for(let be=we;be<=Te;be++)Me(be)}this.canvas._ver++;return}de(this,[{pts:[G(this,u,d),G(this,u+M,d),G(this,u+M,d+L),G(this,u,d+L)],closed:!0}],"nonzero",(j,K)=>ie(this,B,j,K,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,Ie=(ve*U+Me)*4;K[Ie]=ye[Ce],K[Ie+1]=ye[Ce+1],K[Ie+2]=ye[Ce+2],K[Ie+3]=ye[Ce+3]}}return{data:K,width:U,height:j}}putImageData(u,d,M,L=0,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,Ie=this.canvas._bh,Ve=1/this.canvas._sx,Oe=1/this.canvas._sy,qe=this.canvas._data,Ke=u.data,et=Math.max(0,Math.floor((Me+ye)*this.canvas._sx)),Ye=Math.min(Ce-1,Math.ceil((Me+we)*this.canvas._sx)-1),tt=Math.max(0,Math.floor((be+ve)*this.canvas._sy)),je=Math.min(Ie-1,Math.ceil((be+Te)*this.canvas._sy)-1);for(let Xe=tt;Xe<=je;Xe++){let it=Math.floor((Xe+.5)*Oe)-be;if(!(it<ve||it>=Te))for(let bt=et;bt<=Ye;bt++){let pt=Math.floor((bt+.5)*Ve)-Me;if(pt<ye||pt>=we)continue;let lt=(it*j+pt)*4,xt=(Xe*Ce+bt)*4;qe[xt]=Ke[lt]|0,qe[xt+1]=Ke[lt+1]|0,qe[xt+2]=Ke[lt+2]|0,qe[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,Ie,Ve,Oe]=q(this),qe=1/oe,Ke=1/fe,et=M.width/L,Ye=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,je)=>{let Xe=tt+.5,it=je+.5,bt=Me*Xe+be*it+Ce,pt=Ie*Xe+Ve*it+Oe,lt=(bt-ue)*qe,xt=(pt-le)*Ke;if(lt<0||lt>=1||xt<0||xt>=1)return;let Tt=Math.floor((B+lt*j)*et),dt=Math.floor((U+xt*K)*Ye);if(Tt<0||Tt>=M.width||dt<0||dt>=M.height)return;let yt=(dt*M.width+Tt)*4;ie(this,Te,tt,je,P(M.data[yt],M.data[yt+1],M.data[yt+2],M.data[yt+3]*we+128>>8))}),this.canvas._ver++}}let Fe=(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={},Fe(this,u,d)}get width(){return this._w}set width(u){Fe(this,u,this._h)}get height(){return this._h}set height(u){Fe(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,Ie=O[be+1]+oe,Ve=O[ue+1]+le,Oe=O[Ve]+oe,qe=O[Ve+1]+oe;return se(Me,se(Te,se(we,ce(O[Ce],L,I,B),ce(O[Oe],fe,I,B)),se(we,ce(O[Ie],L,ye,B),ce(O[qe],fe,ye,B))),se(Te,se(we,ce(O[Ce+1],L,I,ve),ce(O[Oe+1],fe,I,ve)),se(we,ce(O[Ie+1],L,ye,ve),ce(O[qe+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,De=(Math.sqrt(5)-1)/4,ke=(5-Math.sqrt(5))/20,ze=(T,u,d)=>xe[T]*u+xe[T+1]*d,Be=(T,u,d,M)=>xe[T]*u+xe[T+1]*d+xe[T+2]*M,Ue=(T,u,d,M,L)=>he[T]*u+he[T+1]*d+he[T+2]*M+he[T+3]*L;function We(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=We(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,Ie=j&255,Ve=K&255,Oe=B[Ie+I[Ve]]*3,qe=B[Ie+ve+I[Ve+we]]*3,Ke=B[Ie+1+I[Ve+1]]*3,et=0,Ye=.5-fe*fe-ye*ye;Ye>=0&&(Ye*=Ye,et=Ye*Ye*ze(Oe,fe,ye));let tt=0,je=.5-Te*Te-Me*Me;je>=0&&(je*=je,tt=je*je*ze(qe,Te,Me));let Xe=0,it=.5-be*be-Ce*Ce;return it>=0&&(it*=it,Xe=it*it*ze(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,Ie,Ve;ye>=ve?ve>=we?(Te=1,Me=0,be=0,Ce=1,Ie=1,Ve=0):ye>=we?(Te=1,Me=0,be=0,Ce=1,Ie=0,Ve=1):(Te=0,Me=0,be=1,Ce=1,Ie=0,Ve=1):ve<we?(Te=0,Me=0,be=1,Ce=0,Ie=1,Ve=1):ye<we?(Te=0,Me=1,be=0,Ce=0,Ie=1,Ve=1):(Te=0,Me=1,be=0,Ce=1,Ie=1,Ve=0);let Oe=ye-Te+Ee,qe=ve-Me+Ee,Ke=we-be+Ee,et=ye-Ce+2*Ee,Ye=ve-Ie+2*Ee,tt=we-Ve+2*Ee,je=ye-1+3*Ee,Xe=ve-1+3*Ee,it=we-1+3*Ee,bt=ue&255,pt=le&255,lt=oe&255,xt=j[bt+U[pt+U[lt]]]*3,Tt=j[bt+Te+U[pt+Me+U[lt+be]]]*3,dt=j[bt+Ce+U[pt+Ie+U[lt+Ve]]]*3,yt=j[bt+1+U[pt+1+U[lt+1]]]*3,zt=0,Et=.6-ye*ye-ve*ve-we*we;Et>=0&&(Et*=Et,zt=Et*Et*Be(xt,ye,ve,we));let Ut=0,$t=.6-Oe*Oe-qe*qe-Ke*Ke;$t>=0&&($t*=$t,Ut=$t*$t*Be(Tt,Oe,qe,Ke));let Yt=0,gr=.6-et*et-Ye*Ye-tt*tt;gr>=0&&(gr*=gr,Yt=gr*gr*Be(dt,et,Ye,tt));let mn=0,en=.6-je*je-Xe*Xe-it*it;return en>=0&&(en*=en,mn=en*en*Be(yt,je,Xe,it)),32*(zt+Ut+Yt+mn)}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)*De,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)*ke,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),Ie=(we<=Te?1:0)+(Te>Me?1:0)+(Te>be?1:0),Ve=(we<=Me?1:0)+(Te<=Me?1:0)+(Me>be?1:0),Oe=(we<=be?1:0)+(Te<=be?1:0)+(Me<=be?1:0),qe=Ce>=3?1:0,Ke=Ie>=3?1:0,et=Ve>=3?1:0,Ye=Oe>=3?1:0,tt=Ce>=2?1:0,je=Ie>=2?1:0,Xe=Ve>=2?1:0,it=Oe>=2?1:0,bt=Ce>=1?1:0,pt=Ie>=1?1:0,lt=Ve>=1?1:0,xt=Oe>=1?1:0,Tt=we-qe+ke,dt=Te-Ke+ke,yt=Me-et+ke,zt=be-Ye+ke,Et=we-tt+2*ke,Ut=Te-je+2*ke,$t=Me-Xe+2*ke,Yt=be-it+2*ke,gr=we-bt+3*ke,mn=Te-pt+3*ke,en=Me-lt+3*ke,Mn=be-xt+3*ke,es=we-1+4*ke,Gn=Te-1+4*ke,Po=Me-1+4*ke,No=be-1+4*ke,Sn=le&255,An=oe&255,an=fe&255,sn=ye&255,ld=(K[Sn+K[An+K[an+K[sn]]]]&31)*4,ud=(K[Sn+qe+K[An+Ke+K[an+et+K[sn+Ye]]]]&31)*4,cd=(K[Sn+tt+K[An+je+K[an+Xe+K[sn+it]]]]&31)*4,dd=(K[Sn+bt+K[An+pt+K[an+lt+K[sn+xt]]]]&31)*4,e1=(K[Sn+1+K[An+1+K[an+1+K[sn+1]]]]&31)*4,wh=0,Co=.6-we*we-Te*Te-Me*Me-be*be;Co>=0&&(Co*=Co,wh=Co*Co*Ue(ld,we,Te,Me,be));let Sh=0,Lo=.6-Tt*Tt-dt*dt-yt*yt-zt*zt;Lo>=0&&(Lo*=Lo,Sh=Lo*Lo*Ue(ud,Tt,dt,yt,zt));let Nh=0,Io=.6-Et*Et-Ut*Ut-$t*$t-Yt*Yt;Io>=0&&(Io*=Io,Nh=Io*Io*Ue(cd,Et,Ut,$t,Yt));let Ch=0,Do=.6-gr*gr-mn*mn-en*en-Mn*Mn;Do>=0&&(Do*=Do,Ch=Do*Do*Ue(dd,gr,mn,en,Mn));let $h=0,Fo=.6-es*es-Gn*Gn-Po*Po-No*No;return Fo>=0&&(Fo*=Fo,$h=Fo*Fo*Ue(e1,es,Gn,Po,No)),27*(wh+Sh+Nh+Ch+$h)}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}},nt=(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},st=e.MeshStandardMaterial?.prototype&&(Object.getPrototypeOf(e.MeshStandardMaterial.prototype)||e.MeshStandardMaterial.prototype);st&&typeof st._packPbr!="function"&&(st._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?nt(M,le,K,1):255,U[oe+2]=L?nt(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)=>nt(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 ft=0,Qe=e.Vector2,It=e.PlaneGeometry,Dt=e.Mesh,yr=e.Material;class Mt extends yr{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 Mt({...this,emissive:this._em?this.emissive:void 0})}}class jt extends Dt{constructor(u){super(new It(1,1),u instanceof yr?u:new Mt(u||{})),this.isSprite=!0,this.center=new Qe(.5,.5),this.userData={xr:{billboard:"spherical"}}}_cloneCustom(){let u=new jt(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_${++ft}`,this._autoNamed=!0),this._bakedOwner=this):this.name||(this.name=`Sprite_${++ft}`,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 It(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(Mt.prototype),Object.freeze(jt.prototype),Qe?.prototype){let T=Qe.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},ot=T=>Math.max(0,Math.min(1,Pe(T,0))),wt=T=>new Qe(Pe(T?.x),Pe(T?.y));class St{constructor(u="Curve"){this.type=u,this.arcLengthDivisions=200,this._lenCache=null}getPoint(u,d=new Qe){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 ot(u);let B=d!==void 0&&Number.isFinite(Number(d))?Math.max(0,Math.min(I,Number(d))):ot(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=ot(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 Qe).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?wt(B):B):I?.clone?M[L]=I.clone():I&&typeof I=="object"&&"x"in I?M[L]=wt(I):M[L]=I}return this}}class Pt extends St{constructor(u,d){super("LineCurve"),this.isLineCurve=!0,this.v1=wt(u),this.v2=wt(d)}getPoint(u,d=new Qe){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 Qe){return this.getPoint(ot(u),d)}}class Lt extends St{constructor(u,d,M){super("QuadraticBezierCurve"),this.isQuadraticBezierCurve=!0,this.v0=wt(u),this.v1=wt(d),this.v2=wt(M)}getPoint(u,d=new Qe){let M=ot(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 Zt extends St{constructor(u,d,M,L){super("CubicBezierCurve"),this.isCubicBezierCurve=!0,this.v0=wt(u),this.v1=wt(d),this.v2=wt(M),this.v3=wt(L)}getPoint(u,d=new Qe){let M=ot(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 Ot extends St{constructor(u=[]){super("SplineCurve"),this.isSplineCurve=!0,this.points=Array.isArray(u)?u:[]}getPoint(u,d=new Qe){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)*ot(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 Jt extends St{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 Qe){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+ot(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 Jt{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 St{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 Qe).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=ot(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 Nr=e.BufferAttribute,on=e.Object3D,Tn=e.Line,rr=e.LineSegments,nr=e.LineBasicMaterial,$n=e.MeshBasicMaterial,wn=e.ConeGeometry,cn=e.Color,Cr=(T,u,d,M)=>{T.name=u.name,T.position.copy(u.position),T.quaternion.copy(u.quaternion),T.scale.copy(u.scale),T.visible=u.visible,T.castShadow=u.castShadow,T.receiveShadow=u.receiveShadow;try{T.userData=JSON.parse(JSON.stringify(u.userData||{}))}catch{T.userData={...u.userData||{}}}if(M&&Array.isArray(u.children))for(let L=d;L<u.children.length;L++)T.add(u.children[L].clone(!0));return T},Kt=T=>{let u=new n;return u.setAttribute("position",new Nr(new Float32Array(T),3)),u.__isSegmentPairs=!0,u},ul=[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,3,7,2,6],ts=(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 ul)B.push(U&1?M:T,U&2?L:u,U&4?I:d);return Kt(B)};class In 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 cn(M??4473924),j=new cn(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(Kt(oe.length?oe:fe),new nr({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(Kt(fe),new nr({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 In(this._size,this._divisions,this._centerLines?this._centerLines.material.color:this.material.color,this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,Cr(d,this,this._internalKids,u)}dispose(){}}class pn extends rr{constructor(u=1){let d=Math.max(1e-4,Math.abs(Pe(u,1)));super(Kt([0,0,0,d,0,0]),new nr({color:16724736})),this.type="AxesHelper",this.isAxesHelper=!0,this._size=d,this._yAxis=new rr(Kt([0,0,0,0,d,0]),new nr({color:3407616})),this._zAxis=new rr(Kt([0,0,0,0,0,d]),new nr({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 pn(this._size).setColors(this.material.color,this._yAxis.material.color,this._zAxis.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,Cr(d,this,2,u)}dispose(){}}class dn extends on{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 Nr(new Float32Array([0,0,0,0,1,0]),3)),this.line=new Tn(U,new nr({color:L})),this.cone=new Dt(new wn(.5,1,8).translate(0,-.5,0),new $n({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 dn;return d.line.scale.copy(this.line.scale),d.cone.scale.copy(this.cone.scale),d.cone.position.copy(this.cone.position),d.setColor(this.cone.material.color),d.line.material.transparent=this.line.material.transparent,d.line.material.opacity=this.line.material.opacity,d.cone.material.transparent=this.cone.material.transparent,d.cone.material.opacity=this.cone.material.opacity,Cr(d,this,2,u)}dispose(){}}class gn 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:ts(M.min.x,M.min.y,M.min.z,M.max.x,M.max.y,M.max.z),new nr({color:d})),this.type="Box3Helper",this.isBox3Helper=!0,this.box=M}_bakeAuthorGeometry(){let u=this.box,d=!u||u.isEmpty()?new n:ts(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 gn(this.box.clone(),this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,Cr(d,this,0,u)}dispose(){}}class Pn extends rr{constructor(u,d=16776960){super(new n,new nr({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:ts(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 Pn(this.object,this.material.color);return d.material.transparent=this.material.transparent,d.material.opacity=this.material.opacity,Cr(d,this,0,u)}dispose(){}}for(let T of[St,Pt,Lt,Zt,Ot,Jt,er,tr,In,pn,dn,gn,Pn])Object.freeze(T.prototype);let Ir=["checkerboard","grid","wood","marble","brushedMetal","carbonFiber","concrete","brick","fabric","leather","rust"],rs=[[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]],Bo=(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},hn=(T,u,d)=>Bo(T,u,d)/4294967296,Yr=(T,u)=>(T%u+u)%u,Sc=(T,u,d,M,L)=>{let I=Math.floor(T),B=Math.floor(u),U=T-I,j=u-B,K=Yr(I,d),ue=Yr(B,M),le=(K+1)%d,oe=(ue+1)%M,fe=U*U*(3-2*U),ye=j*j*(3-2*j),ve=hn(K,ue,L),we=hn(le,ue,L),Te=hn(K,oe,L),Me=hn(le,oe,L);return ve+(we-ve)*fe+(Te-ve)*ye+(ve-we-Te+Me)*fe*ye},yn=(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*Sc(T*le,u*oe,le,oe,I+ue>>>0),j+=U,U*=.5,K*=2}return B/j},dl=T=>T-Math.floor(T),uu=T=>Math.abs(dl(T)*2-1),ns=(T,u,d)=>{let M=(d-T)/(u-T);return M<0?M=0:M>1&&(M=1),M*M*(3-2*M)},fn=(T,u,d)=>T+(u-T)*d,bn=T=>T<=0?0:T>=1?255:Math.floor(T*255+.5),qh=(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)=>[fn(Me[0],be[0],Ce),fn(Me[1],be[1],Ce),fn(Me[2],be[2],Ce)];if(T===0){let Me=Yr(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=dl(U*d),be=dl(j*d),Ce=Math.max(.035,d/u),Ie=1-ns(Ce*.5,Ce,Math.min(Me,1-Me,be,1-be));return[...oe(L,I,Ie),.3+.4*Ie,B,0]}if(T===2){let Me=yn(U,j,4,4,4,M),be=uu(j*d+Me*1.5),Ce=yn(U,j,2,96,2,M+7>>>0),Ie=be*.7+Ce*.3;return[...le(fn(.55,1,Ie)),Ie,B+(1-Ie)*.15,0]}if(T===3){let Me=yn(U,j,3,3,5,M),be=uu((U+j)*d+Me*2.5),Ce=be*be,Ie=Ce*Ce,Ve=Ie*Ie,Oe=.92+.08*Me,qe=oe(L,I,Ve*.85);return[qe[0]*Oe,qe[1]*Oe,qe[2]*Oe,.5-Ve*.2,B+Ve*.1,0]}if(T===4){let Me=yn(U,j,2,192*d,2,M),be=hn(K,ue,M+3>>>0);return[...le(.85+.12*Me+.03*be),.35+Me*.3,B+(Me-.5)*.12,1]}if(T===5){let Me=d*2,be=U*Me,Ce=j*Me,Ie=be-Math.floor(be),Ve=Ce-Math.floor(Ce),Oe=Yr(Math.floor(be)+Math.floor(Ce),2)===0,qe=Oe?Ve*2-1:Ie*2-1,Ke=1-qe*qe,et=.08*uu(Oe?Ve*8:Ie*8),Ye=.6+.4*Ke;return[L[0]*Ye+et,L[1]*Ye+et,L[2]*Ye+et,Ke*.8,B+.1*(1-Ke),0]}if(T===6){let Me=yn(U,j,d,d,5,M),be=hn(K,ue,M+31>>>0),Ce=d*16,Ie=ns(.82,.9,Sc(U*Ce,j*Ce,Ce,Ce,M+17>>>0));return[...le((.82+.25*Me+.06*(be-.5))*(1-.35*Ie)),.5+.25*(Me-.5)-.3*Ie,B-.05*Me,0]}if(T===7){let Me=Math.floor(d/2),be=j*d,Ce=Math.floor(be),Ie=be-Ce,Ve=U*Me+(Yr(Ce,2)===1?.5:0),Oe=Math.floor(Ve),qe=Ve-Oe,Ke=Math.min(Math.min(qe,1-qe)*2,Math.min(Ie,1-Ie)),et=Math.max(.06,1.5*d/u),Ye=1-ns(et*.5,et,Ke),tt=hn(Yr(Oe,Me),Yr(Ce,d),M),je=yn(U,j,d,d,3,M+5>>>0),Xe=.8+.25*tt+.15*(je-.5),it=.9+.1*je;return[fn(L[0]*Xe,I[0]*it,Ye),fn(L[1]*Xe,I[1]*it,Ye),fn(L[2]*Xe,I[2]*it,Ye),(1-Ye)*(.75+.1*je)+Ye*.2,fn(B,.95,Ye),0]}if(T===8){let Me=U*d,be=j*d,Ce=(Me-Math.floor(Me))*2-1,Ie=(be-Math.floor(be))*2-1,Ve=Yr(Math.floor(Me)+Math.floor(be),2)===0?1-Ce*Ce:1-Ie*Ie,Oe=yn(U,j,4,4,2,M);return[...le((.75+.25*Ve)*(.95+.1*(Oe-.5))),Ve,B,0]}if(T===9){let Me=U*d,be=j*d,Ce=Math.floor(Me),Ie=Math.floor(be),Ve=1e9,Oe=1e9;for(let et=-1;et<=1;et++)for(let Ye=-1;Ye<=1;Ye++){let tt=Ce+Ye,je=Ie+et,Xe=Yr(tt,d),it=Yr(je,d),bt=tt+hn(Xe,it,M)-Me,pt=je+hn(Xe,it,M+1>>>0)-be,lt=bt*bt+pt*pt;lt<Ve?(Oe=Ve,Ve=lt):lt<Oe&&(Oe=lt)}let qe=1-ns(0,.12,Math.sqrt(Oe)-Math.sqrt(Ve)),Ke=yn(U,j,4,4,3,M+3>>>0);return[...le((.85+.2*(Ke-.5))*(1-.3*qe)),.6-.4*qe+.1*(Ke-.5),B+.15*qe,0]}let fe=yn(U,j,d,d,5,M),ye=ns(.45,.6,fe),ve=yn(U,j,d*8,d*8,3,M+9>>>0),we=.9+.1*ve,Te=.7+.5*ve;return[fn(I[0]*we,L[0]*Te,ye),fn(I[1]*we,L[1]*Te,ye),fn(I[2]*we,L[2]*Te,ye),.4+.4*ye*ve+.1*ye,fn(.35,B,ye),1-ye]},Wh=(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=qh(T,u,d,M,L,I,B,(ye+.5)/u,fe,ye,oe),we=(oe*u+ye)*4;K[we]=bn(ve[0]),K[we+1]=bn(ve[1]),K[we+2]=bn(ve[2]),K[we+3]=255,ue[we]=255,ue[we+1]=bn(ve[4]),ue[we+2]=bn(ve[5]),ue[we+3]=255,le[oe*u+ye]=ve[3]}}return[K,Ac(le,u,U),ue]},Ac=(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]=bn(K*le*.5+.5),M[oe+1]=bn(ue*le*.5+.5),M[oe+2]=bn(le*.5+.5),M[oe+3]=255}}return M},Tc=(T,u)=>{let d=u;try{T!=null&&(d=new cn(T).getHex())}catch{}return[(d>>16&255)/255,(d>>8&255)/255,(d&255)/255]},Vo=new Map,Zu=(T,u={})=>{let d=Ir.indexOf(T);if(d<0)throw new TypeError(`THREE.ProceduralTexture: unknown preset '${T}' (use ${Ir.join(", ")})`);let M=u&&typeof u=="object"?u:{},L=rs[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=Tc(M.color,L[1]),K=Tc(M.color2,L[2]||L[1]),ue=ot(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=Vo.get(oe);if(fe)return{...fe};let[ye,ve,we]=Wh(d,B,I,U,j,K,ue,le),Te=(Ce,Ie)=>{let Ve=new _e(B,B);Ve._data.set(Ce),Ve._ver++;let Oe=new W(Ve);return Oe.flipY=!1,Oe.colorSpace=Ie,Oe.name=`${T}_${Ie==="srgb"?"albedo":Ce===ve?"normal":"orm"}`,Oe},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,Vo.size>=64&&Vo.clear(),Vo.set(oe,be),{...be}},Mc={presets:Object.freeze(Ir.slice()),create:(T,u)=>Zu(String(T),u)};for(let T of Ir)Mc[T]=u=>Zu(T,u);Object.freeze(Mc);let Xh=500,Yh=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>Xh?null:u},ed=T=>{let u=typeof T=="number"?T:NaN;return Number.isFinite(u)?u<=384?256:u<=768?512:1024:512},ch=T=>T>512&&T%2===0?T/2:T,td=(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},rd=T=>{let u=typeof T=="number"?T:NaN,d=Number.isFinite(u)?Math.abs(u):1;return Math.floor(d+.5)%4294967296},id=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},nd=(T,u,d)=>{let M=id(`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")},gh=T=>{let u=Yh(T?.prompt);if(u===null)return null;let d=ed(T?.size),M=rd(T?.seed);return{prompt:u,size:d,seed:M,key:nd(u,d,M)}},_c=(T,u,d,M,L)=>{if(ch(u)!==u)return _c(td(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 Ie=0;for(let Ve=0;Ve<=2*B;Ve++)Ie+=I[be*u+(Ce+u+Ve-B)%u];U[be*u+Ce]=Ie}let j=(2*B+1)*(2*B+1),K=new Float64Array(u*u),ue=1/0,le=-1/0;for(let be=0;be<u;be++)for(let Ce=0;Ce<u;Ce++){let Ie=0;for(let Oe=0;Oe<=2*B;Oe++)Ie+=U[(be+u+Oe-B)%u*u+Ce];let Ve=j*I[be*u+Ce]-Ie;K[be*u+Ce]=Ve,Ve<ue&&(ue=Ve),Ve>le&&(le=Ve)}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=Ac(fe,u,ye),we=Number.isFinite(M)?Math.max(0,Math.min(1,M)):0,Te=bn(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]=bn(we+.35*(.5-fe[be])),Me[Ce+2]=Te,Me[Ce+3]=255}return[ve,Me]},Uo=new Map,yh=new WeakMap,ad=0,sd=(T,u)=>{let d=gh(T);if(!d)return null;let{prompt:M,size:L,seed:I,key:B}=d,U=ot(Pe(T.roughness,u>=0?rs[u][3]:.8)),j=ot(Pe(T.metalness,0)),K=Math.max(0,Math.min(8,Pe(T.normalStrength,1))),ue=globalThis,le=ue.__three_live_native_texture_pack__,oe=ue.__three_live_texture_pack__,fe=0;if(typeof le=="function"){let Ie=ue.__three_live_native_texture_pack_token__;fe=typeof Ie=="function"&&Number(Ie())||0}else oe&&typeof oe=="object"&&(fe=yh.get(oe)??0,fe||yh.set(oe,fe=++ad));let ye=[fe,B,K,U,j].join(","),ve=fe?Uo.get(ye):void 0;if(ve)return{...ve};let we=null;if(typeof le=="function"){let Ie=le(M,L,I,K,U,j);Array.isArray(Ie)&&Ie.length===3&&(we=Ie)}else{let Ie=oe&&typeof oe=="object"&&Object.prototype.hasOwnProperty.call(oe,B)?oe[B]:null;Ie&&Ie.size===L&&Ie.rgba instanceof Uint8Array&&Ie.rgba.length===L*L*4&&(we=[Ie.rgba,..._c(Ie.rgba,L,K,U,j)])}if(!we)return null;let Te=(Ie,Ve,Oe,qe)=>{let Ke=new W({data:new Uint8ClampedArray(Ie.buffer,Ie.byteOffset,Ve*Ve*4),width:Ve,height:Ve});return Ke.flipY=!1,Ke.colorSpace=Oe,Ke.name=`ai_${B}_${qe}`,Ke._pngDim=Ve,Ke},Me=ch(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&&(Uo.size>=32&&Uo.clear(),Uo.set(ye,Ce)),{...Ce}},xh=new Set,od=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=Ir.indexOf(L),B=!!M&&M.prompt!==void 0&&M.prompt!==null,U=B?sd(M,I):null;if(!M||I<0&&!U){!(B&&L==="")&&!xh.has(L)&&(xh.add(L),console.warn(`[three-live] userData.xr.material: unknown preset '${L}' (use ${Ir.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 cn(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??Zu(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},vh={Box3:a,Sphere:o,CanvasTexture:W,ImprovedNoise:pe,SimplexNoise:Ge,SpriteMaterial:Mt,Sprite:jt,LineCurve:Pt,QuadraticBezierCurve:Lt,CubicBezierCurve:Zt,SplineCurve:Ot,EllipseCurve:Jt,ArcCurve:er,CurvePath:tr,GridHelper:In,AxesHelper:pn,ArrowHelper:dn,Box3Helper:gn,BoxHelper:Pn,ProceduralTexture:Mc};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,vh),t.createCanvas=D,t._procMaterialize=od,t.canonicalTextureSpec=gh,t.deriveTextureMaps=_c,t.encodeRgbaPngDataUri=(T,u,d)=>_(T,u,d,!1,!1,f).uri,t.materializeDeclarativeGeometry=T=>{t._cadMaterialize?.(T),t._lodMaterialize?.(T),t._procMaterialize?.(T)}),vh}var Oc={name:"procedural",onRegister(){jn(ms);let e=He(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&ms(t,e)}};function zc(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 mp={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Hn(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=mp[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 Ed(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 ir(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 Rd=["neutral","reinhard","none","aces","agx"];function Dr(e){let t=String(e??"").trim().toLowerCase();return Rd.includes(t)?t:"neutral"}function hp(e){return Rd.indexOf(Dr(e))}function pp(e){return new TextDecoder().decode(e)}var Ld=He().decoders;function bp(e,t){Ld.set(e.toLowerCase(),t)}function ys(e){return Ld.get(e.toLowerCase())}function Pd(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=pp(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)&&!ys(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 kt)h.onParseGLB?.(m);return m}function Wc(e,t=vr(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 yp(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 wr(e){if(yp(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Pd(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var jc=`#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
- }`,cc=`#version 300 es
52
+ }`,gp=`#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 ms(e,t,r=1){t=Bt(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 d=o((Math.log2(Math.max(v,1e-6))+12.47393)/16.5),y=d*d,M=y*y;return 15.5*M*y-40.14*M*d+31.96*M-6.868*y*d+.4298*y+.1191*d-.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 c=Math.max(n,s,l);if(c<.76)return a(o);let f=1-.0576/(c-.52),p=f/c,m=1-1/(.15*(c-f)+1);return a(g=>o(g*p+(f-g*p)*m))}var uc=`#version 300 es
208
+ }`;function Id(e,t,r=1){t=Dr(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 xp=`#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);}`,lc=`#version 300 es
211
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,vp=`#version 300 es
247
212
  precision highp float;
248
213
  uniform vec4 uColorId;
249
214
  out vec4 fragColor;
250
- void main(){fragColor=uColorId;}`;function Pi(e,t,r){let i={};for(let n of r)i[n]=e.getUniformLocation(t,n);return i}var os=["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 fs(){let e=Me().xrDepthShader;return{fs:cc.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...os,...e.uniformNames]:os}}function mc(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 Ci(e,t,r,i,n,s,l,o){if(i===void 0||!t.accessors?.[i])return null;let a=ut(t,r,t.accessors[i],s);if(!a)return null;o&&(a=a.slice(),is(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 Di(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function ds(e,t,r){let i=fs(),n=ls,s=i.fs,l=!1;for(let a of Oe)if(a.onResolveShader){let u=a.onResolveShader(t,r,n,s);u&&(n=u.vs,s=u.fs,l=!0)}let o=l?Dt(e,n,s):null;return{program:o,uniforms:o?Pi(e,o,i.uniforms):null}}function fc(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 dc(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 hs=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),ps=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 bs(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 ys(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 ss(e,t,r=ps,i){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return hc(e,t,r,i,n)}catch(s){let l=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;ys(e,l,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let o of n.buffers)e.deleteBuffer(o);throw s}}function hc(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=rn("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((N,w)=>{u.push(typeof N?.name=="string"&&N.name?N.name:`Variant_${w}`)});let c=Vt(s),f=[];if(Array.isArray(s.nodes))for(let N=0;N<s.nodes.length;N++){let w=s.nodes[N];w.mesh!==void 0&&s.meshes&&s.meshes[w.mesh]&&f.push({node:w,nodeIdx:N,meshIdx:w.mesh})}let p=f.length>0?f:(s.meshes||[]).map((N,w)=>({node:N,nodeIdx:-1,meshIdx:w})),m=[],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 N of g)m.push({...N,type:N.type||N.light_type||"point",innerConeAngle:N.innerConeAngle??N.inner_cone_angle,outerConeAngle:N.outerConeAngle??N.outer_cone_angle});else if(s.extensions?.KHR_lights_punctual?.lights){let N=s.extensions.KHR_lights_punctual.lights;for(let w of N){let ie=w.type==="directional"?"directional":w.type==="point"?"point":w.type==="spot"?"spot":"ambient";m.push({type:ie,color:w.color||[1,1,1],intensity:w.intensity!==void 0?w.intensity:1})}}if(m.length===0&&(m.push({type:"ambient",color:[1,1,1],intensity:.35}),m.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 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 N=0;N<s.textures.length;N++){let w=s.textures[N],ie=s.images[w.source];if(ie){let ae=e.createTexture();e.bindTexture(3553,ae),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 k=J=>{e.bindTexture(3553,ae),e.texImage2D(3553,0,6408,6408,5121,J),e.generateMipmap(3553),i?.()};if(ie.bufferView!==void 0){let J=s.bufferViews[ie.bufferView],z=J.byteOffset||0,Y=new Blob([o.slice(z,z+J.byteLength)],{type:ie.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(Y).then(k).catch(()=>{})}else if(ie.uri){let J=mc(ie.uri);if(J){let z=new Image;z.crossOrigin="anonymous",z.referrerPolicy="no-referrer",z.onload=()=>k(z),z.src=J}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",ie.uri)}x.push(ae)}else x.push(null)}}let b=[1/0,1/0,1/0],v=[-1/0,-1/0,-1/0],d=0,y=0;for(let N=0;N<p.length;N++){let w=p[N],ie=s.meshes[w.meshIdx],ae=w.nodeIdx>=0?c[w.nodeIdx]:Se(),k=new Float32Array(9);ze(k,ae);let J={name:w.node.name||ie.name||`Mesh_${w.meshIdx}`,nodeIndex:w.nodeIdx,transform:ae,normalMatrix:k,primitives:[],extras:w.node.extras||ie.extras,...w.node?.visible===!1||w.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};n.mesh=J;let z=w.node?.extensions?.EXT_mesh_gpu_instancing;if(z&&z.attributes&&typeof z.attributes=="object"){let Y=z.attributes,le=Y.TRANSLATION!==void 0?s.accessors?.[Y.TRANSLATION]:null,ce=Y.ROTATION!==void 0?s.accessors?.[Y.ROTATION]:null,$=Y.SCALE!==void 0?s.accessors?.[Y.SCALE]:null,U=Y._COLOR_0!==void 0?s.accessors?.[Y._COLOR_0]:null,_=Number(le?.count??ce?.count??$?.count??0);if(!Number.isFinite(_)||_<0||_>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${_}`);if(_>0){let H=(j,A)=>{if(!j||j.bufferView===void 0||!s.bufferViews?.[j.bufferView])return null;let S=j.componentType??5126,L=I=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${I})`),null);if(S!==5120&&S!==5121&&S!==5122&&S!==5123&&S!==5126)return L(`componentType ${S}`);if(!(Number(j.count)>=_))return L(`count ${j.count} < ${_}`);let O=null;try{O=ut(s,o,{...j,count:_},A)}catch{return L("out of bounds")}return!O||!O.every(Number.isFinite)?L("non-finite value"):O},D=H(le,3),F=H(ce,4),E=H($,3),G=U?.type==="VEC4"?4:3,ee=H(U,G),se=new Float32Array(_*16),oe=Se();for(let j=0;j<_;j++){let A=D?[D[j*3],D[j*3+1],D[j*3+2]]:[0,0,0],S=F?[F[j*4],F[j*4+1],F[j*4+2],F[j*4+3]]:[0,0,0,1],L=E?[E[j*3],E[j*3+1],E[j*3+2]]:[1,1,1];yt(oe,S,A,L),se.set(oe,j*16)}if(J.instanceMatrices=se,ee){let j=new Float32Array(_*3);for(let A=0;A<_;A++)j[A*3]=ee[A*G],j[A*3+1]=ee[A*G+1],j[A*3+2]=ee[A*G+2];J.instanceColors=j}}}for(let Y of ie.primitives||[]){if(Y.extensions?.KHR_draco_mesh_compression){let O=rn("draco");O&&O.decodePrimitive(s,Y,o)}let le=[],ce=e.createVertexArray();n.vao=ce,n.buffers=le,e.bindVertexArray(ce);let $=fc(e,J,le),U=s.accessors[Y.attributes.POSITION],_=Number(U?.count??0);if(!Number.isFinite(_)||_<0||d+_>r.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${r.maxVertices}).`);if(d+=_,U?.min&&U?.max){let O=I=>{for(let W=0;W<3;W++){let Q=I[12+W],K=I[12+W];for(let Z=0;Z<3;Z++){let q=I[Z*4+W]*U.min[Z],re=I[Z*4+W]*U.max[Z];Q+=q<re?q:re,K+=q>re?q:re}Q<b[W]&&(b[W]=Q),K>v[W]&&(v[W]=K)}};if(J.instanceMatrices&&J.instanceMatrices.length>=16){let I=J.instanceMatrices.length>>4,W=Se();for(let Q=0;Q<I;Q++){let K=J.instanceMatrices.subarray(Q*16,Q*16+16);Pe(W,ae,K),O(W)}}else O(ae)}let H=Ci(e,s,o,Y.attributes.POSITION,0,3,le);Ci(e,s,o,Y.attributes.NORMAL,1,3,le),Ci(e,s,o,Y.attributes.TEXCOORD_0,2,2,le,dc(s,Y));let D=0,F=5123,E=null;if(Y.indices!==void 0){let O=s.accessors[Y.indices],I=(s.bufferViews[O.bufferView].byteOffset||0)+(O.byteOffset||0);if(D=Number(O.count??0),!Number.isFinite(D)||D<0||y+D>r.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${r.maxIndices}).`);y+=D,F=O.componentType===5125?5125:5123;let W=e.createBuffer();le.push(W),e.bindBuffer(34963,W),O.componentType===5125?E=new Uint32Array(o,I,O.count):O.componentType===5121?E=Uint16Array.from(new Uint8Array(o,I,O.count)):E=I%2===0?new Uint16Array(o,I,O.count):new Uint16Array(o.slice(I,I+O.count*2)),e.bufferData(34963,E,35044)}else D=U.count;let G={};for(let O of Oe)if(O.onBuildPrimitiveVAO){let I=O.onBuildPrimitiveVAO(e,ce,Y,s,o);I&&(G[O.name]=I)}e.bindVertexArray(null);let ee=s.materials&&Y.material!==void 0?s.materials[Y.material]:null,{program:se,uniforms:oe}=ds(e,Y,ee),j=bs(ee,x),A=!!(ee?.extensions?.KHR_materials_transmission||G.materials?.isTransmissive),S=Y.extensions?.KHR_materials_variants?.mappings,L=Array.isArray(S)?S.filter(O=>O&&typeof O.material=="number"&&Array.isArray(O.variants)).map(O=>({material:O.material|0,variants:O.variants.map(I=>Number(I)|0)})):void 0;J.primitives.push({vao:ce,instanced:$,indexCount:D,indexType:F,...j,positions:H,indices:E,buffers:le,materialIndex:Y.material,defaultMaterialIndex:Y.material,variantMappings:L,primitiveDef:Y,programCache:new Map([[Y.material??-1,{program:se,uniforms:oe}]]),pluginData:G,customProgram:se,customUniforms:oe,isTransmissive:A})}a.push(J)}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],T=v[0]-b[0],V=v[1]-b[1],X=v[2]-b[2],P=Math.max(Math.hypot(T,V,X)/2,.5),R=[b[0],b[1],b[2]],C=[v[0],v[1],v[2]],B=t.animations;if(!B){for(let N of Oe)if(N.onParseGLB?.(t),t.animations){B=t.animations;break}}return B||(B=[]),{meshes:a,bounds:{center:M,radius:P,min:R,max:C},lights:m,animations:B,worldMatrices:c,gpuTextures:x,availableVariants:u}}function xn(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 je=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=Se(),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=Se(),this.viewMatrix=Se(),this.activeViewMatrix=null,this.modelMatrix=Se(),this.mvpMatrix=Se(),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:Se(),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=Di(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=Bt(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){sc(e,t)}static getDecoder(e){return rn(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=fs();this.renderProg=Dt(e,ls,t.fs),this.pickProg=Dt(e,uc,lc),this.uRender=Pi(e,this.renderProg,t.uniforms),this.uPick=Pi(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of Oe)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}=ss(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 c of e.gltf.nodes)this.initialNodeTransforms.push({t:c.translation?[c.translation[0],c.translation[1],c.translation[2]]:[0,0,0],r:c.rotation?[c.rotation[0],c.rotation[1],c.rotation[2],c.rotation[3]]:[0,0,0,1],s:c.scale?[c.scale[0],c.scale[1],c.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let c of Oe)c.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=Di(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(us(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of Oe)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(gt(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=gt(e),{meshes:i}=ss(this.gl,r,ps,()=>this.render());if(t)for(let n of i)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],ze(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),ze(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],c=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")r=[h[0]*c,h[1]*c,h[2]*c];else if(u.type==="directional"&&i.length<6){let f=u.direction||[.5,1,.8];i.push(f[0],f[1],f[2]),n.push(h[0]*c,h[1]*c,h[2]*c)}else if((u.type==="point"||u.type==="spot")&&s.length<6){let f=u.position||[0,0,0];if(s.push(f[0],f[1],f[2]),l.push(h[0]*c,h[1]*c,h[2]*c),u.type==="spot"){let p=u.direction||[0,-1,0],m=Math.max(.01,Math.min(Math.PI/2,u.outerConeAngle??Math.PI/3)),g=Math.max(0,Math.min(m-1e-4,u.innerConeAngle??0));o.push(p[0],p[1],p[2]),a.push(Math.cos(g),Math.cos(m))}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=Di(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=Bt(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of Oe)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of Oe)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 c of i)c.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,bs(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=ds(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 Oe)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=Se();Pe(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],c=r[1]*i+r[5]*n+r[9]*s+r[13],f=r[2]*i+r[6]*n+r[10]*s+r[14],p=r[3]*i+r[7]*n+r[11]*s+r[15];if(p<=1e-4)return{x:0,y:0,z:1,visible:!1};let m=h/p,g=c/p,x=f/p,b=this.canvas.getBoundingClientRect(),v=b.width||this.canvas.clientWidth||this.canvas.width||300,d=b.height||this.canvas.clientHeight||this.canvas.height||150,y=(m*.5+.5)*v,M=(-g*.5+.5)*d,T=m>=-1.1&&m<=1.1&&g>=-1.1&&g<=1.1&&x>=-1&&x<=1;if(T&&t){let[V,X,P]=xn(this),R=[i-V,n-X,s-P];l*R[0]+o*R[1]+a*R[2]>.05&&(T=!1)}return{x:y,y:M,z:x,visible:T}}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=Se();Pe(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 T=this.meshes[M];if(T.visible===!1||T.isPluginMesh)continue;let V=M+1,X=(V&255)/255,P=(V>>8&255)/255,R=(V>>16&255)/255;i.uniform4f(this.uPick.uColorId,X,P,R,1),Pe(this.modelMatrix,this.modelRootMatrix,T.transform);let C=T.instanceMatrices;if(C&&C.length>=16){let B=C.length>>4,N=Se();for(let w of T.primitives){i.bindVertexArray(w.vao);for(let ie=0;ie<B;ie++)Pe(N,this.modelMatrix,C.subarray(ie*16,ie*16+16)),Pe(this.mvpMatrix,l,N),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),ar(i,w)}}else{Pe(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let B of T.primitives)i.bindVertexArray(B.vao),ar(i,B)}}let d=new Uint8Array(4);i.readPixels(a,u,1,1,6408,5121,d),i.bindFramebuffer(36160,null);let y=d[0]+(d[1]<<8)+(d[2]<<16);y>0&&y<=this.meshes.length&&(o=[this.meshes[y-1]])}o.length===0&&(o=this.meshes.filter(d=>d.visible!==!1));let h=null,c=1/0,f=[0,0,0],p=[0,1,0],[m,g,x]=xn(this),b=Se();for(let d of o){Pe(b,this.modelRootMatrix,d.transform);let y=d.instanceMatrices,M=y&&y.length>=16?y.length>>4:1;for(let T=0;T<M;T++){y&&y.length>=16?Pe(this.modelMatrix,b,y.subarray(T*16,T*16+16)):this.modelMatrix.set(b),Pe(this.mvpMatrix,l,this.modelMatrix);let V=Se();if(!tn(V,this.mvpMatrix))continue;let X=(a+.5)/n*2-1,P=(u+.5)/s*2-1,R=[0,0,0],C=[0,0,0];vi(R,X,P,-1,V),vi(C,X,P,1,V);let B=C[0]-R[0],N=C[1]-R[1],w=C[2]-R[2],ie=Math.hypot(B,N,w)||1,ae=B/ie,k=N/ie,J=w/ie,z={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((Y=>{for(let le of d.primitives){if(!le.positions)continue;let ce=le.positions,$=le.indices,U=Math.floor($?$.length/3:ce.length/9);for(let _=0;_<U;_++){let H=$?$[_*3]:_*3,D=$?$[_*3+1]:_*3+1,F=$?$[_*3+2]:_*3+2;qo(R[0],R[1],R[2],ae,k,J,ce[H*3],ce[H*3+1],ce[H*3+2],ce[D*3],ce[D*3+1],ce[D*3+2],ce[F*3],ce[F*3+1],ce[F*3+2],z,Y)}}})(1e-4),isFinite(z.distance)){let Y=z.point[0],le=z.point[1],ce=z.point[2],$=this.modelMatrix,U=$[0]*Y+$[4]*le+$[8]*ce+$[12],_=$[1]*Y+$[5]*le+$[9]*ce+$[13],H=$[2]*Y+$[6]*le+$[10]*ce+$[14],D=U-m,F=_-g,E=H-x,G=Math.hypot(D,F,E);if(G<c){ze(this.normalMatrix,this.modelMatrix);let ee=this.normalMatrix,se=z.normal[0],oe=z.normal[1],j=z.normal[2],A=ee[0]*se+ee[3]*oe+ee[6]*j,S=ee[1]*se+ee[4]*oe+ee[7]*j,L=ee[2]*se+ee[5]*oe+ee[8]*j,O=Math.hypot(A,S,L)||1;A/=O,S/=O,L/=O,A*D+S*F+L*E>0&&(A=-A,S=-S,L=-L),h=d,c=Math.round(G*1e3)/1e3,f=[Math.round(U*1e3)/1e3,Math.round(_*1e3)/1e3,Math.round(H*1e3)/1e3],p=[Math.round(A*1e3)/1e3,Math.round(S*1e3)/1e3,Math.round(L*1e3)/1e3]}}}}if(!h)return null;let v={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:c,hitPoint:f,normal:p,screenX:e,screenY:t};if(r){for(let d of Oe)d.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);nr(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;en(this.viewMatrix,xn(this),r,[0,1,0]),Pe(this.mvpMatrix,this.projMatrix,this.viewMatrix),ze(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 Oe)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 Oe)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 Oe)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 Oe)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),d=Math.max(1,this.canvas.height||1),y=Math.max(1,Math.floor(v*.5)),M=Math.max(1,v-y),T=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),V=this.customTarget||this.bounds.center,[X,P,R]=xn(this),C=Math.cos(this.currTheta),B=-Math.sin(this.currTheta),N=.032,w=Se(),ie=Se(),ae=[X-C*N,P,R-B*N],k=[V[0]-C*N*.25,V[1],V[2]-B*N*.25];nr(w,this.fov,y/d,.1,T),en(ie,ae,k,[0,1,0]);let J=Se(),z=Se(),Y=[X+C*N,P,R+B*N],le=[V[0]+C*N*.25,V[1],V[2]+B*N*.25];nr(J,this.fov,M/d,.1,T),en(z,Y,le,[0,1,0]),this.render({viewMatrix:ie,projMatrix:w,eyePos:ae,viewport:[0,0,y,d],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:z,projMatrix:J,eyePos:Y,viewport:[y,0,M,d],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,d);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=Se(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o,Pe(l,e?.projMatrix??this.projMatrix,o);let a=Me().xrDepthShader,u=ic(this.toneMapping),[h,c,f]=e?e.eyePos:xn(this);for(let v of Oe)v.onBeforeDrawScene?.(this,t,l,[h,c,f],u);let p=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&p===0)return;let m=e?.eye||"none",g=!1,x=p>0?[...this.backdropMeshes,...this.meshes]:this.meshes,b=v=>{for(let d=0;d<x.length;d++){let y=x[d];if(y.visible===!1)continue;let M=this.selectedMeshName!==""&&y.name===this.selectedMeshName;d<p||y.worldSpace===!0||y.name==="__xr_reticle__"?this.modelMatrix.set(y.transform):Pe(this.modelMatrix,this.modelRootMatrix,y.transform),Pe(this.mvpMatrix,l,this.modelMatrix),ze(y.normalMatrix,this.modelMatrix);let T=y.extras?.xr?.stereo||y.userData?.xr?.stereo,V=0,X=0,P=1,R=1;T==="sbs"?(P=.5,V=m==="right"?.5:0):T==="ou"&&(R=.5,X=m==="right"?.5:0);for(let C of y.primitives){let B=!!C.isTransmissive;if(!v&&B){g=!0;continue}if(v&&!B)continue;let N=C.customProgram||this.renderProg,w=C.customUniforms||this.uRender;t.useProgram(N),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,c,f),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,V,X,P,R),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 ae of Oe)ae.onBeforeDrawPrimitive?.(t,N,C,y,this.worldMatrices||[],this.gltf);t.uniform4fv(w.uBaseColor,C.baseColor),t.uniform1f(w.uMetallic,C.metallic),t.uniform1f(w.uRoughness,C.roughness),w.uClearcoat&&t.uniform2f(w.uClearcoat,C.clearcoat??0,C.clearcoatRoughness??.04),C.texture?(t.activeTexture(33984),t.bindTexture(3553,C.texture),t.uniform1i(w.uBaseColorTexture,0),t.uniform1i(w.uHasTexture,1)):t.uniform1i(w.uHasTexture,0),C.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,C.metallicRoughnessTexture),t.uniform1i(w.uMetallicRoughnessTexture,1),t.uniform1i(w.uHasMetallicRoughnessTexture,1)):t.uniform1i(w.uHasMetallicRoughnessTexture,0),C.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,C.normalTexture),t.uniform1i(w.uNormalTexture,2),t.uniform1i(w.uHasNormalTexture,1),t.uniform1f(w.uNormalScale,C.normalScale)):t.uniform1i(w.uHasNormalTexture,0),C.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,C.occlusionTexture),t.uniform1i(w.uOcclusionTexture,3),t.uniform1i(w.uHasOcclusionTexture,1),t.uniform1f(w.uOcclusionStrength,C.occlusionStrength)):t.uniform1i(w.uHasOcclusionTexture,0),t.bindVertexArray(C.vao);let ie=y.instanceMatrices;if(C.instanceCount!==void 0)t.drawElementsInstanced(4,C.indexCount,C.indexType,0,C.instanceCount);else if(ie&&ie.length>=16&&C.instanced&&w.uInstanced&&w.uViewProj){let ae=ie.length>>4;t.uniform1i(w.uInstanced,1),t.uniformMatrix4fv(w.uViewProj,!1,l),C.indices?t.drawElementsInstanced(4,C.indexCount,C.indexType,0,ae):t.drawArraysInstanced(4,0,C.indexCount,ae),t.uniform1i(w.uInstanced,0)}else if(ie&&ie.length>=16){let ae=ie.length>>4,k=y.instanceColors,J=Se(),z=new Float32Array(9),Y=[C.baseColor[0],C.baseColor[1],C.baseColor[2],C.baseColor[3]];for(let le=0;le<ae;le++)Pe(J,this.modelMatrix,ie.subarray(le*16,le*16+16)),Pe(this.mvpMatrix,l,J),ze(z,J),t.uniformMatrix4fv(w.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(w.uModel,!1,J),t.uniformMatrix3fv(w.uNormalMatrix,!1,z),k&&(Y[0]=C.baseColor[0]*k[le*3],Y[1]=C.baseColor[1]*k[le*3+1],Y[2]=C.baseColor[2]*k[le*3+2],Y[3]=C.baseColor[3],t.uniform4fv(w.uBaseColor,Y)),ar(t,C)}else ar(t,C)}}};if(b(!1),g){for(let v of Oe)v.onBeforeTransmissivePass?.(t,this);b(!0)}for(let v of Oe)v.onAfterRender?.(t,this,l,e?.eye??"none",[r,i,n,s],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){ys(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 Oe)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()}};je.registerPlugin=Ue,je.getRegisteredPlugins=er;function pc(e){return e+3&-4}var ve=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function vs(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function Ms(e,t=0){let[r,i,n,,s,l,o,,a,u,h,,c,f,p]=Array.from({length:15},(z,Y)=>ve(e[t+Y],Y%5===0?1:0)),m=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&&(m=-m);let b=Math.abs(m)>1e-8?1/m:0,v=Math.abs(g)>1e-8?1/g:0,d=Math.abs(x)>1e-8?1/x:0,y=r*b,M=i*b,T=n*b,V=s*v,X=l*v,P=o*v,R=a*d,C=u*d,B=h*d,N=y+X+B,w=0,ie=0,ae=0,k=1;if(N>0){let z=.5/Math.sqrt(N+1);k=.25/z,w=(P-C)*z,ie=(R-T)*z,ae=(M-V)*z}else if(y>X&&y>B){let z=2*Math.sqrt(Math.max(0,1+y-X-B));z>1e-8&&(k=(P-C)/z,w=.25*z,ie=(V+M)/z,ae=(R+T)/z)}else if(X>B){let z=2*Math.sqrt(Math.max(0,1+X-y-B));z>1e-8&&(k=(R-T)/z,w=(V+M)/z,ie=.25*z,ae=(P+C)/z)}else{let z=2*Math.sqrt(Math.max(0,1+B-y-X));z>1e-8&&(k=(M-V)/z,w=(R+T)/z,ie=(P+C)/z,ae=.25*z)}let J=Math.hypot(w,ie,ae,k);return J>1e-8&&Number.isFinite(J)?(w/=J,ie/=J,ae/=J,k/=J):(w=0,ie=0,ae=0,k=1),{t:[c,f,p],r:[w,ie,ae,k],s:[m,g,x]}}function bc(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 Pt=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function Ts(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:Pt(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function on(e,t){return As(e,t)[0]}function As(e,t){e.updateMatrixWorld(!0);let r=[],i=0,n=[],s=[],l=[],o=[],a=new Set,u=[],h=[],c=new Map,f=[],p=[],m=[],g=new Map,x=[],b=[];function v(k){let J=c.get(k);if(J!==void 0)return J;J=h.length,c.set(k,J);let z=k,Y=z.color?.r??.8,le=z.color?.g??.8,ce=z.color?.b??.8,$=z.opacity??1,U={baseColorFactor:[Y,le,ce,$],metallicFactor:z.metalness??0,roughnessFactor:z.roughness??.5},_={};if(z.map){let F="";typeof z.map=="string"?F=z.map:typeof z.map.source=="string"?F=z.map.source:typeof z.map.image=="string"&&(F=z.map.image);let E=F.trim(),G=E&&!/[\x00-\x1f\x7f\\]|\.\./.test(E)&&(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(E)||!E.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(E))?E:null;if(G){let se=g.get(G);if(se===void 0){let oe=f.length;f.push({uri:G}),p.length===0&&p.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),se=m.length,m.push({sampler:0,source:oe}),g.set(G,se)}U.baseColorTexture={index:se}}let ee=z.map.avgColor;Array.isArray(ee)&&ee.length>=3&&(_.avgColor=[ee[0],ee[1],ee[2]])}let H={name:z.name||"",pbrMetallicRoughness:U,doubleSided:z.side===2||!!z.doubleSided,...Object.keys(_).length>0?{extras:_}:{}};if(z.emissive&&(z.emissive.r>0||z.emissive.g>0||z.emissive.b>0)){let F=z.emissiveIntensity??1;H.emissiveFactor=[z.emissive.r*F,z.emissive.g*F,z.emissive.b*F]}let D={};return z.clearcoat&&z.clearcoat>0&&(D.KHR_materials_clearcoat={clearcoatFactor:z.clearcoat,clearcoatRoughnessFactor:z.clearcoatRoughness||0}),z.sheen&&z.sheen>0&&(D.KHR_materials_sheen={sheenColorFactor:z.sheenColor?[z.sheenColor.r,z.sheenColor.g,z.sheenColor.b]:[1,1,1],sheenRoughnessFactor:z.sheenRoughness||0}),z.transmission&&z.transmission>0&&(D.KHR_materials_transmission={transmissionFactor:z.transmission}),z.thickness&&z.thickness>0&&(D.KHR_materials_volume={thicknessFactor:z.thickness,attenuationDistance:z.attenuationDistance??1/0,attenuationColor:z.attenuationColor?[z.attenuationColor.r,z.attenuationColor.g,z.attenuationColor.b]:[1,1,1]}),z.ior!==void 0&&z.ior!==1.5&&(D.KHR_materials_ior={ior:z.ior}),z.dispersion&&z.dispersion>0&&(D.KHR_materials_dispersion={dispersion:z.dispersion}),z.iridescence&&z.iridescence>0&&(D.KHR_materials_iridescence={iridescenceFactor:z.iridescence,iridescenceIor:z.iridescenceIOR??1.3}),Object.keys(D).length>0&&(H.extensions=D),h.push(H),J}function d(k,J){let z=new Uint8Array(k.buffer,k.byteOffset,k.byteLength),Y=pc(z.byteLength),le=new Uint8Array(Y);le.set(z),r.push(le);let ce=n.length;return n.push({buffer:0,byteOffset:i,byteLength:z.byteLength,target:J}),i+=Y,ce}function y(k,J,z,Y,le,ce,$){let U=d(k,z),_=s.length,H={bufferView:U,byteOffset:0,componentType:Y,count:le,type:J};return ce&&(H.min=ce),$&&(H.max=$),s.push(H),_}e.traverse(k=>{if(k.isLight||k.color&&k.intensity!==void 0){let J=k.matrixWorld?.elements,z=ve(J?J[12]:k.position?.x,0),Y=ve(J?J[13]:k.position?.y,0),le=ve(J?J[14]:k.position?.z,0),ce=k.target,$=ce?.parent?ce?.matrixWorld?.elements:void 0,U=ve($?$[12]:ce?.position?.x,0),_=ve($?$[13]:ce?.position?.y,0),H=ve($?$[14]:ce?.position?.z,0),D=U-z,F=_-Y,E=H-le,G=Math.hypot(D,F,E),ee=Math.max(.01,Math.min(Math.PI/2,ve(k.angle,Math.PI/3))),se=Math.max(0,Math.min(1,ve(k.penumbra,0)));b.push({type:k.type,color:[k.color.r,k.color.g,k.color.b],intensity:k.intensity,position:[z,Y,le],...k.type==="spot"?{direction:G>1e-6?[D/G,F/G,E/G]:[0,-1,0],outerConeAngle:ee,innerConeAngle:Math.max(0,ee*(1-se)),range:Math.max(0,ve(k.distance,0))}:k.type==="point"?{range:Math.max(0,ve(k.distance,0))}:{}})}});let M=[],T=new Set([e]),V=[];if(Array.isArray(e.children))for(let k=e.children.length-1;k>=0;k--)V.push({obj:e.children[k],parentKids:M});for(;V.length>0;){let{obj:k,parentKids:J}=V.pop();if(!k||typeof k!="object"||T.has(k))continue;T.add(k),k._bakeAuthorGeometry?.(),Me().materializeDeclarativeGeometry?.(k);let z=!!(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)),Y={name:k.name||(z?`Node_${o.length}`:"")},le=ve(k.position?.x,0),ce=ve(k.position?.y,0),$=ve(k.position?.z,0),U=ve(k.quaternion?.x,0),_=ve(k.quaternion?.y,0),H=ve(k.quaternion?.z,0),D=ve(k.quaternion?.w,1),F=ve(k.scale?.x,1),E=ve(k.scale?.y,1),G=ve(k.scale?.z,1);if((le||ce||$)&&(Y.translation=[le,ce,$]),(U||_||H||D!==1)&&(Y.rotation=[U,_,H,D]),(F!==1||E!==1||G!==1)&&(Y.scale=[F,E,G]),k.visible===!1&&(Y.extensions={...Y.extensions||{},KHR_node_visibility:{visible:!1}},a.add("KHR_node_visibility")),k.userData&&Object.keys(k.userData).length>0&&(Y.extras=JSON.parse(JSON.stringify(k.userData,(oe,j)=>{if(!(oe==="__proto__"||oe==="prototype"||oe==="constructor"))return typeof j=="function"?void 0:j})),k.userData.xr)){let oe=bc(k.userData.xr);Y.extensions={...Y.extensions||{},MOZ_hubs_components:oe,ANDROID_xr_scenecore:oe},Me().xrTraitSerializer?.gltfNode(Y,k.userData.xr),a.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(k.geometry){let oe=k.geometry,j=oe.attributes.position;if(j&&j.count>0){let A=[1/0,1/0,1/0],S=[-1/0,-1/0,-1/0];for(let K=0;K<j.count;K++){let Z=j.getX(K),q=j.getY(K),re=j.getZ(K);Z<A[0]&&(A[0]=Z),Z>S[0]&&(S[0]=Z),q<A[1]&&(A[1]=q),q>S[1]&&(S[1]=q),re<A[2]&&(A[2]=re),re>S[2]&&(S[2]=re)}let L={attributes:{POSITION:y(j.array,"VEC3",34962,5126,j.count,A,S)}};if(oe.attributes.normal&&(L.attributes.NORMAL=y(oe.attributes.normal.array,"VEC3",34962,5126,oe.attributes.normal.count)),oe.attributes.uv&&(L.attributes.TEXCOORD_0=y(oe.attributes.uv.array,"VEC2",34962,5126,oe.attributes.uv.count)),oe.index){let K=oe.index.array instanceof Uint32Array;L.indices=y(oe.index.array,"SCALAR",34963,K?5125:5123,oe.index.count)}let O=Array.isArray(k.material)?k.material[0]:k.material;O&&(L.material=v(O));let I=k.userData?.variants;if(I&&typeof I=="object"){let K=new Map;for(let Z of Object.keys(I)){if(!Z||Z==="__proto__"||Z==="constructor"||Z==="prototype")continue;let q=I[Z];if(!q||typeof q!="object")continue;let re=x.indexOf(Z);if(re===-1&&x.length<256&&(re=x.length,x.push(Z)),re===-1)continue;let ne=v(q),te=K.get(ne);te||(te=[],K.set(ne,te)),te.push(re)}if(K.size>0){let Z=[];for(let[q,re]of K.entries())Z.push({material:q,variants:re});L.extensions={...L.extensions||{},KHR_materials_variants:{mappings:Z}},a.add("KHR_materials_variants")}}let W=k;if(W.isInstancedMesh&&typeof W.count=="number"&&W.count>0&&W.instanceMatrix?.array){let K=Math.min(1e4,Math.floor(W.count)),Z=W.instanceMatrix.array,q=new Float32Array(K*3),re=new Float32Array(K*4),ne=new Float32Array(K*3);for(let ue=0;ue<K;ue++){let{t:me,r:pe,s:fe}=Ms(Z,ue*16);q[ue*3]=me[0],q[ue*3+1]=me[1],q[ue*3+2]=me[2],re[ue*4]=pe[0],re[ue*4+1]=pe[1],re[ue*4+2]=pe[2],re[ue*4+3]=pe[3],ne[ue*3]=fe[0],ne[ue*3+1]=fe[1],ne[ue*3+2]=fe[2]}let te={TRANSLATION:y(q,"VEC3",0,5126,K),ROTATION:y(re,"VEC4",0,5126,K),SCALE:y(ne,"VEC3",0,5126,K)};if(W.instanceColor?.array&&W.instanceColor.array.length>=K*3){let ue=new Float32Array(W.instanceColor.array.subarray(0,K*3));te._COLOR_0=y(ue,"VEC3",0,5126,K)}Y.extensions={...Y.extensions||{},EXT_mesh_gpu_instancing:{attributes:te}},a.add("EXT_mesh_gpu_instancing")}let Q=l.length;l.push({primitives:[L],name:k.name,...Y.extras?{extras:Y.extras}:{}}),Y.mesh=Q}}let ee=o.length;o.push(Y),u.push(k),J.push(ee);let se=k.children;if(Array.isArray(se)&&se.length>0){let oe=[];Y.children=oe;for(let j=se.length-1;j>=0;j--)V.push({obj:se[j],parentKids:oe})}}for(let k=0;k<o.length;k++){let J=o[k];J.children&&J.children.length===0?delete J.children:J.children&&J.children.length>0&&(J.extras?.xr?.lod||J.extensions?.ANDROID_xr_scenecore?.lod||u[k]?.isLOD)&&(J.extensions={...J.extensions||{},MSFT_lod:{ids:[...J.children]}},a.add("MSFT_lod"))}let X=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),P=[];if(typeof X=="function"&&u.length>0){let k=t?.duration??4,J=t?.fps??15,z=Math.max(2,Math.round(k*J)+1),Y=new Float32Array(z),le=u.map(E=>[ve(E.position?.x,0),ve(E.position?.y,0),ve(E.position?.z,0),ve(E.quaternion?.x,0),ve(E.quaternion?.y,0),ve(E.quaternion?.z,0),ve(E.quaternion?.w,1),ve(E.scale?.x,1),ve(E.scale?.y,1),ve(E.scale?.z,1)]),ce=u.map(()=>new Float32Array(z*3)),$=u.map(()=>new Float32Array(z*4)),U=u.map(()=>new Float32Array(z*3));for(let E=0;E<z;E++){let G=E/(z-1)*k;Y[E]=G;try{X(G)}catch{}for(let ee=0;ee<u.length;ee++){let se=u[ee];ce[ee][E*3]=ve(se.position?.x,0),ce[ee][E*3+1]=ve(se.position?.y,0),ce[ee][E*3+2]=ve(se.position?.z,0);let oe=ve(se.quaternion?.x,0),j=ve(se.quaternion?.y,0),A=ve(se.quaternion?.z,0),S=ve(se.quaternion?.w,1),L=Math.hypot(oe,j,A,S)||1;if(oe/=L,j/=L,A/=L,S/=L,E>0){let O=(E-1)*4,I=$[ee];I[O]*oe+I[O+1]*j+I[O+2]*A+I[O+3]*S<0&&(oe=-oe,j=-j,A=-A,S=-S)}$[ee][E*4]=oe,$[ee][E*4+1]=j,$[ee][E*4+2]=A,$[ee][E*4+3]=S,U[ee][E*3]=ve(se.scale?.x,1),U[ee][E*3+1]=ve(se.scale?.y,1),U[ee][E*3+2]=ve(se.scale?.z,1)}}for(let E=0;E<u.length;E++){let G=u[E],ee=le[E];G.position?.set(ee[0],ee[1],ee[2]),G.quaternion?.set(ee[3],ee[4],ee[5],ee[6]),G.scale?.set(ee[7],ee[8],ee[9])}e.updateMatrixWorld(!0);let _=null,H=()=>(_===null&&(_=y(Y,"SCALAR",0,5126,z,[0],[k])),_),D=[],F=[];for(let E=0;E<u.length;E++){let G=le[E],ee=(oe,j,A)=>oe.some((S,L)=>Math.abs(S-G[A+L%j])>1e-4),se=(oe,j,A,S)=>{oe&&F.push({sampler:D.push({input:H(),interpolation:"LINEAR",output:y(j,A,0,5126,z)})-1,target:{node:E,path:S}})};se(ee(ce[E],3,0),ce[E],"VEC3","translation"),se(ee($[E],4,3),$[E],"VEC4","rotation"),se(ee(U[E],3,7),U[E],"VEC3","scale")}F.length>0&&P.push({name:"ProceduralLoop",samplers:D,channels:F})}let R=Xo(o,l,e.userData),C=[],B=[],N=[];for(let k=0;k<o.length;k++){let J=o[k],z=Ts(J.extras?.xr);if(!z)continue;let{ae:Y,src:le,preset:ce,volume:$,loop:U,isGlobal:_}=z,H=J.name||`Node_${k}`,D=B.length;B.push({name:`${H}_source`,gain:$,loop:U,autoPlay:typeof Y.autoplay=="boolean"?Y.autoplay:!0,...le!==void 0?{audio:C.push({uri:le})-1}:{},...ce?{extras:{preset:ce,pitch:Pt(Y.pitch,.25,4,1)}}:{}});let F=N.length,E=Pt(Y.refDistance,.05,100,1),G=Pt(Y.coneInnerAngle,0,360,360),ee=Pt(Y.coneOuterAngle,G,360,360);N.push({name:`${H}_emitter`,type:_?"global":"positional",gain:$,sources:[D],..._?{}:{positional:{distanceModel:Y.distanceModel==="linear"||Y.distanceModel==="exponential"?Y.distanceModel:"inverse",refDistance:E,maxDistance:Pt(Y.maxDistance,E,500,Math.max(E,25)),rolloffFactor:Pt(Y.rolloffFactor,0,10,1),coneInnerAngle:+(G*Math.PI/180).toFixed(6),coneOuterAngle:+(ee*Math.PI/180).toFixed(6),coneOuterGain:Pt(Y.coneOuterGain,0,1,0)}}}),J.extensions={...J.extensions||{},KHR_audio_emitter:{emitter:F}},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,...f.length>0?{images:f}:{},...p.length>0?{samplers:p}:{},...m.length>0?{textures:m}:{},accessors:s,bufferViews:n,buffers:[{byteLength:i}],...P.length>0?{animations:P}:{},...R||a.size>0?{extensionsUsed:[...R?["KHR_interactivity"]:[],...a]}:{},...R||x.length>0||N.length>0?{extensions:{...R?{KHR_interactivity:R}:{},...x.length>0?{KHR_materials_variants:{variants:x.map(k=>({name:k}))}}:{},...N.length>0?{KHR_audio_emitter:{...C.length>0?{audio:C}:{},sources:B,emitters:N}}:{}}}:{}},ie=new Uint8Array(i),ae=0;for(let k of r)ie.set(k,ae),ae+=k.byteLength;return[{gltf:w,bin:ie.buffer,lights:b,environmentIntensity:e.environmentIntensity},u]}function Oi(e){return new TextEncoder().encode(e)}function vn(e,t){let{gltf:r,bin:i}=on(e,t),n=JSON.stringify(r),s=Oi(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 f=0;f<l;f++)u[20+s.byteLength+f]=32;let c=20+o;return h.setUint32(c,i.byteLength,!0),h.setUint32(c+4,5130562,!0),u.set(new Uint8Array(i),c+8),u}function yc(e,t){let[r,i]=As(e,t);return Ui(r,i)}function Ui(e,t){let r=[],i=e.gltf,n=Me().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||[],c=i.nodes||[],f=new Set,p=u.map((x,b)=>vs(f,ur(x?.name,`Material_${b}`)));function m(x){let b=o[x];if(!b)throw new Error(`Accessor ${x} not found`);let v=a[b.bufferView||0],d=(v.byteOffset||0)+(b.byteOffset||0),y=v.byteLength||0;return{acc:b,buffer:l.slice(d,d+y)}}function g(x,b,v,d){let y=[],M=h[x];if(!M)return y;let T=M.primitives||[];for(let V=0;V<T.length;V++){let X=T[V],P=X.attributes?.POSITION;if(P===void 0)continue;let{acc:R,buffer:C}=m(P),B=new Float32Array(C,0,R.count*3),N,w=X.attributes?.NORMAL;if(w!==void 0){let{acc:D,buffer:F}=m(w),E=new Float32Array(F,0,D.count*3);N=new Float32Array(E.length);for(let G=0;G<D.count;G++){let ee=E[G*3],se=E[G*3+1],oe=E[G*3+2],j=Math.hypot(ee,se,oe)||1;N[G*3]=ee/j,N[G*3+1]=se/j,N[G*3+2]=oe/j}}let ie,ae=X.attributes?.TEXCOORD_0;if(ae!==void 0){let{acc:D,buffer:F}=m(ae);ie=new Float32Array(F,0,D.count*2)}let k;if(X.indices!==void 0){let{acc:D,buffer:F}=m(X.indices);k=D.componentType===5125?new Uint32Array(F,0,D.count):new Uint16Array(F,0,D.count);let E=R.count;for(let G of k)if(G>=E)throw new Error(`SecurityError: Index buffer value (${G}) out of vertex bounds [0, ${E}).`)}else{let D=R.count;k=D>65535?new Uint32Array(D):new Uint16Array(D);for(let F=0;F<D;F++)k[F]=F}let J="DefaultMaterial",z=[.8,.8,.8],Y=.5,le=0,ce=0,$=0,U=1.5,_=1,H=[0,0,0];if(X.material!==void 0&&u[X.material]){let D=u[X.material];J=p[X.material]||`Material_${X.material}`;let F=D.pbrMetallicRoughness||{},E=(oe,j)=>Array.isArray(oe)&&oe.length>=3?[oe[0],oe[1],oe[2]]:j;z=E(F.baseColorFactor,[1,1,1]);let G=D.extras?.avgColor;Array.isArray(G)&&G.length>=3&&(z=[z[0]*G[0],z[1]*G[1],z[2]*G[2]]);let ee=Array.isArray(F.baseColorFactor)&&typeof F.baseColorFactor[3]=="number"?F.baseColorFactor[3]:1;typeof F.roughnessFactor=="number"&&(Y=F.roughnessFactor),typeof F.metallicFactor=="number"&&(le=F.metallicFactor),H=E(D.emissiveFactor,[0,0,0]);let se=D.extensions||{};se.KHR_materials_clearcoat&&(ce=se.KHR_materials_clearcoat.clearcoatFactor??0,$=se.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof se.KHR_materials_ior?.ior=="number"&&(U=se.KHR_materials_ior.ior),_=ee*(1-(se.KHR_materials_transmission?.transmissionFactor??0))}y.push({name:T.length>1?`${b}_p${V}`:b,positions:B,indices:k,normals:N,uvs:ie,materialName:J,color:z,roughness:Y,metallic:le,clearcoat:ce,clearcoatRoughness:$,ior:U,opacity:_,emissiveColor:H,xrTraits:v||M.extras?.xr,...d?{invisible:!0}:{}})}return y}if(c.length>0){let x=new Float32Array(0),b=new Uint16Array(0),v=(B,N)=>{if(B===void 0)return null;let{acc:w,buffer:ie}=m(B);return new Float32Array(ie,0,w.count*N)},d=(B,N)=>Array.isArray(B)&&B.length>=3?[ve(B[0],N),ve(B[1],N),ve(B[2],N)]:[N,N,N],y=(B,N,w)=>B&&B.length>=(N+1)*3?[B[N*3],B[N*3+1],B[N*3+2]]:w,M=(B,N,w)=>B&&B.length>=(N+1)*4?[B[N*4],B[N*4+1],B[N*4+2],B[N*4+3]]:w,T=new Map,V=i.animations?.[0];if(V&&Array.isArray(V.channels)&&Array.isArray(V.samplers))for(let B of V.channels){let N=V.samplers[B?.sampler],w=B?.target?.node,ie=B?.target?.path;if(!N||typeof w!="number"||N.input===void 0)continue;let ae=T.get(w);ae||(ae={input:N.input},T.set(w,ae)),ie==="translation"?ae.t=N.output:ie==="rotation"?ae.r=N.output:ie==="scale"&&(ae.s=N.output)}let X=i.scenes?.[i.scene??0]?.nodes??[];if(!Array.isArray(X)||X.length===0){let B=new Set;for(let N of c)if(Array.isArray(N?.children))for(let w of N.children)B.add(w);X=[];for(let N=0;N<c.length;N++)B.has(N)||X.push(N);X.length===0&&(X=[0])}let P=new Set,R=[],C=(B,N)=>{if(Array.isArray(B))for(let w=B.length-1;w>=0;w--)R.push({idx:B[w],out:N})};for(C(X,r);R.length>0;){let{idx:B,out:N}=R.pop();if(typeof B!="number"||B<0||B>=c.length||P.has(B))continue;P.add(B);let w=c[B];if(!w)continue;let ie=[0,0,0],ae=[0,0,0,1],k=[1,1,1];if(Array.isArray(w.matrix)&&w.matrix.length===16){let _=Ms(w.matrix);ie=_.t,ae=_.r,k=_.s}else ie=d(w.translation,0),Array.isArray(w.rotation)&&w.rotation.length>=4&&(ae=[ve(w.rotation[0],0),ve(w.rotation[1],0),ve(w.rotation[2],0),ve(w.rotation[3],1)]),k=d(w.scale,1);let J,z=T.get(B);if(z){let _=v(z.input,1);if(_&&_.length>0){let H=v(z.t,3),D=v(z.r,4),F=v(z.s,3),E=Array.from(_),G=[],ee=[],se=[];for(let oe=0;oe<_.length;oe++)G.push(y(H,oe,ie)),ee.push(M(D,oe,ae)),se.push(y(F,oe,k));J={times:E,translations:G,rotations:ee,scales:se}}}let Y=Array.isArray(w.children)?w.children:[],le=typeof w.mesh=="number"&&w.mesh>=0&&w.mesh<h.length,ce=t?.[B]?.userData?.xr??w.extras?.xr;if(!le&&Y.length===0&&(w.camera!==void 0||w.extensions?.KHR_lights_punctual||!w.name&&!w.extras&&!ce&&!J))continue;let $=(_,H,D)=>({name:_,positions:x,indices:b,isXform:!0,xrTraits:ce,timeSamples:J,translation:ie,rotation:ae,scale:k,children:H,...D?{invisible:!0}:{}}),U=w.visible===!1||w.extensions?.KHR_node_visibility?.visible===!1||t?.[B]?.visible===!1;if(le){let _=w.name||h[w.mesh]?.name||`Mesh_${B}`,H=g(w.mesh,_,ce,U),D=w.extensions?.EXT_mesh_gpu_instancing?.attributes;if(D&&typeof D=="object"&&H.length>0){let F=v(D.TRANSLATION,3),E=v(D.ROTATION,4),G=v(D.SCALE,3),ee=v(D._COLOR_0,3),se=Math.min(1e3,F?F.length/3:E?E.length/4:G?G.length/3:0);if(se>0){let oe=[];for(let j=0;j<se;j++){let A=y(F,j,[0,0,0]),S=M(E,j,[0,0,0,1]),L=y(G,j,[1,1,1]);for(let O of H){let I=O.color||[.8,.8,.8],W=ee&&ee.length>=(j+1)*3;oe.push({...O,name:`${O.name}_${j}`,materialName:W?`${O.materialName}_inst_${j}`:O.materialName,color:W?[I[0]*ee[j*3],I[1]*ee[j*3+1],I[2]*ee[j*3+2]]:O.color,translation:A,rotation:S,scale:L})}}C(Y,oe),N.push($(_,oe,U));continue}}if(H.length===1)H[0].translation=ie,H[0].rotation=ae,H[0].scale=k,H[0].timeSamples=J,Y.length>0&&(H[0].children=[],C(Y,H[0].children)),N.push(H[0]);else{let F=[...H];C(Y,F),N.push($(_,F,U))}}else{let _=[];C(Y,_),N.push($(w.name||`Group_${B}`,_,U))}}}else for(let x=0;x<h.length;x++){let b=h[x].name||`Mesh_${x}`;r.push(...g(x,b,h[x].extras?.xr))}return r}function ur(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 Ni(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ge(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 xt=(e,t,r)=>`(${Ge(e)}, ${Ge(t)}, ${Ge(r)})`,gs=(e,t,r,i)=>`(${Ge(e)}, ${Ge(t)}, ${Ge(r)}, ${Ge(i)})`;function xs(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=xt(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function gc(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${Ge(e[i*2])}, ${Ge(1-e[i*2+1])})`;return r.join(", ")}function xc(e){return Array.from(e).join(", ")}function ki(e){let t=new Map,r=0,i=null,n=[...e];for(;n.length>0;){let m=n.pop();if(!m.isXform&&m.positions&&m.positions.length>0){let g=ur(m.materialName,"DefaultMaterial");t.has(g)||t.set(g,{color:m.color||[.8,.8,.8],roughness:m.roughness??.5,metallic:m.metallic??0,clearcoat:m.clearcoat??0,clearcoatRoughness:m.clearcoatRoughness??0,ior:m.ior??1.5,opacity:m.opacity??1,emissiveColor:m.emissiveColor||[0,0,0]})}if(m.timeSamples&&m.timeSamples.times.length>0){let g=m.timeSamples.times[m.timeSamples.times.length-1];g>r&&(r=g)}if(m.xrTraits?.anchor&&!i&&(i=m.xrTraits.anchor==="vertical"||m.xrTraits.anchor==="wall"?"vertical":"horizontal"),m.children)for(let g=m.children.length-1;g>=0;g--)n.push(m.children[g])}let s="";r>0&&(s=`startTimeCode = 0
251
- endTimeCode = ${Ge(r)}
215
+ void main(){fragColor=uColorId;}`;function bs(e,t,r){let i={};for(let n of r)i[n]=e.getUniformLocation(t,n);return i}var wp="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 Hc(){let e=He(),t=e.xrDepthShader,r=e.shadowMapShader;return{fs:gp.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:[...wp,...t?.uniformNames||[],...r?.uniformNames||[]]}}function Sp(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 $c(e,t,r,i,n,a,s,o){if(i===void 0||!t.accessors?.[i])return null;let l=Hn(t,r,t.accessors[i],a);if(!l)return null;o&&(l=l.slice(),Ed(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 Gc(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function Cd(e,t,r){let i=Hc(),n=jc,a=i.fs,s=!1;for(let l of kt)if(l.onResolveShader){let c=l.onResolveShader(t,r,n,a);c&&(n=c.vs,a=c.fs,s=!0)}let o=s?ir(e,n,a):null;return{program:o,uniforms:o?bs(e,o,i.uniforms):null}}function Mp(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 Ap(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 Nd=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Dd=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function hs(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function Ud(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 Bd(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 kd(e,t,r=Dd,i){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Tp(e,t,r,i,n)}catch(a){let s=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;Bd(e,s,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let o of n.buffers)e.deleteBuffer(o);throw a}}function Tp(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=ys("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=vr(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(...Wc(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=Sp($.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]:rt(),V=new Float32Array(9);Bt(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=Hn(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),Fe=rt();for(let _e=0;_e<H;_e++){let Le=_e*3,ne=_e*4;or(Fe,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(Fe,_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=ys("draco");z&&z.decodePrimitive(a,Q,o)}let ee=[],k=e.createVertexArray();n.vao=k,n.buffers=ee,e.bindVertexArray(k);let G=Mp(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=rt();for(let se=0;se<O;se++)at(X,F,J.instanceMatrices.subarray(se*16,se*16+16)),z(X)}else z(F)}let te=$c(e,a,o,Q.attributes.POSITION,0,3,ee),Z=$c(e,a,o,Q.attributes.NORMAL,1,3,ee),ae=$c(e,a,o,Q.attributes.TEXCOORD_0,2,2,ee,Ap(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 kt)if(z.onBuildPrimitiveVAO){let O=z.onBuildPrimitiveVAO(e,k,Q,a,o);O&&(Se[z.name]=O)}e.bindVertexArray(null);let Fe=a.materials&&Q.material!==void 0?a.materials[Q.material]:null,{program:_e,uniforms:Le}=Cd(e,Q,Fe),ne=Ud(Fe,v),Re=!!(Fe?.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 kt)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 ps(){return typeof performance<"u"?performance.now():Date.now()}function Ho(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 Ht=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=rt(),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=rt(),this.viewMatrix=rt(),this.activeViewMatrix=null,this.modelMatrix=rt(),this.mvpMatrix=rt(),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:rt(),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=Gc(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=Dr(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){bp(e,t)}static getDecoder(e){return ys(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=Hc();this.renderProg=ir(e,jc,t.fs),this.pickProg=ir(e,xp,vp),this.uRender=bs(e,this.renderProg,t.uniforms),this.uPick=bs(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}recompileRenderProgram(){if(this.contextLost)return;let e=this.gl,t=Hc();this.renderProg&&e.deleteProgram(this.renderProg),this.renderProg=ir(e,jc,t.fs),this.uRender=bs(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 kt)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}=kd(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 kt)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=Gc(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(Pd(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of kt)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(wr(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=wr(e),{meshes:i}=kd(this.gl,r,Dd,()=>this.render());if(t)for(let n of i)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],Bt(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),Bt(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=Gc(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=Dr(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){this.environmentSource=e&&typeof e=="object"?e:null;for(let t of kt)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e),this.render();return}this.render()}async setSkyboxImage(e){for(let t of kt)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,Ud(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=Cd(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 kt)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=rt();at(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]=Ho(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=ps;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=rt();at(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),at(this.modelMatrix,this.modelRootMatrix,E.transform);let R=E.instanceMatrices;if(R&&R.length>=16){let $=R.length>>4,F=rt();for(let V of E.primitives){i.bindVertexArray(V.vao);for(let Y=0;Y<$;Y++)at(F,this.modelMatrix,R.subarray(Y*16,Y*16+16)),at(this.mvpMatrix,s,F),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),hs(i,V)}}else{at(this.mvpMatrix,s,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let $ of E.primitives)i.bindVertexArray($.vao),hs(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]=Ho(this),y=rt();for(let b of o){at(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?at(this.modelMatrix,y,w.subarray(E*16,E*16+16)):this.modelMatrix.set(y),at(this.mvpMatrix,s,this.modelMatrix);let N=rt();if(!Kr(N,this.mvpMatrix))continue;let C=(l+.5)/n*2-1,_=(c+.5)/a*2-1,P=[0,0,0],R=[0,0,0];Rc(P,C,_,-1,N),Rc(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;gd(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){Bt(this.normalMatrix,this.modelMatrix);let Fe=this.normalMatrix,_e=ee.normal[0],Le=ee.normal[1],ne=ee.normal[2],Re=Fe[0]*_e+Fe[3]*Le+Fe[6]*ne,W=Fe[1]*_e+Fe[4]*Le+Fe[7]*ne,D=Fe[2]*_e+Fe[5]*Le+Fe[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 kt)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);Oo(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;xr(this.viewMatrix,Ho(this),r,[0,1,0]),at(this.mvpMatrix,this.projMatrix,this.viewMatrix),Bt(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 kt)r.onXRSessionEnd?.(this);if(this.lastTime=ps(),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 kt)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=ps();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 kt)a.onUpdate?.(this,e);let t=ps();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let a of kt)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]=Ho(this),Y=Math.cos(this.currTheta),J=-Math.sin(this.currTheta),re=.032;for(let Q of[-1,1]){let ee=rt(),k=rt(),G=Q<0?C:_,q=[$+Q*Y*re,F,V+Q*J*re];Oo(ee,this.fov,G/N,.1,P),xr(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=rt(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o;let l=e?.projMatrix??this.projMatrix;at(s,l,o);let c=He(),f=c.xrDepthShader,m=hp(this.toneMapping),[h,p,g]=e?e.eyePos:Ho(this);for(let E of kt)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 kt)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{at(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])}}at(this.mvpMatrix,s,this.modelMatrix),Bt(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 kt)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=rt(),H=new Float32Array(9);for(let te=0;te<k;te++){if(at(q,this.modelMatrix,ee.subarray(te*16,te*16+16)),at(this.mvpMatrix,s,q),Bt(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]])}hs(t,Y)}}else hs(t,Y)}}};if(S(!1),A){for(let E of kt)E.onBeforeTransmissivePass?.(t,this);S(!0)}for(let E of kt)E.onAfterRender?.(t,this,s,v,[r,i,n,a],l)}disposeMeshListGpuResources(e,t){Bd(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 kt)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()}};Ht.registerPlugin=gt,Ht.getRegisteredPlugins=as;function _p(e){return e+3&-4}var Je=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function Xc(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function Vd(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 Od(e,t=0){let[r,i,n,,a,s,o,,l,c,f,,m,h,p]=Array.from({length:15},(ee,k)=>Je(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 Ep(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 Nn=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function zd(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:Nn(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function kp(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 Qr(e,t){return $d(e,t)[0]}function $d(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?.(),Fe=me(q.map);Fe&&(ie.baseColorTexture=Fe);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,Je(Re,1)):Re?Math.max(0,(Je(Re.x,1)+Je(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,Je(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,Je(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=_p(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?.(),He().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=Je(k.position?.x,0),Z=Je(k.position?.y,0),ae=Je(k.position?.z,0),ie=Je(k.quaternion?.x,0),de=Je(k.quaternion?.y,0),me=Je(k.quaternion?.z,0),Se=Je(k.quaternion?.w,1),Fe=Je(k.scale?.x,1),_e=Je(k.scale?.y,1),Le=Je(k.scale?.z,1);if((te||Z||ae)&&(H.translation=[te,Z,ae]),(ie||de||me||Se!==1)&&(H.rotation=[ie,de,me,Se]),(Fe!==1||_e!==1||Le!==1)&&(H.scale=[Fe,_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=Ep(k.userData.xr);H.extensions={...H.extensions||{},MOZ_hubs_components:z,ANDROID_xr_scenecore:z},He().xrTraitSerializer?.gltfNode(H,k.userData.xr);let O=kp(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=Je(z?z[12]:k.position?.x,0),X=Je(z?z[13]:k.position?.y,0),se=Je(z?z[14]:k.position?.z,0),ce=ne.target,pe=ce?.parent?ce?.matrixWorld?.elements:void 0,xe=Je(pe?pe[12]:ce?.position?.x,0),he=Je(pe?pe[13]:ce?.position?.y,0),Ne=Je(pe?pe[14]:ce?.position?.z,0),ge=xe-O,Ae=he-X,Ee=Ne-se,De=Math.hypot(ge,Ae,Ee),ke=Math.max(.01,Math.min(Math.PI/2,Je(ne.angle,Math.PI/3))),ze=Math.max(0,Math.min(1,Je(ne.penumbra,0))),Be=Math.max(0,ke*(1-ze)),Ue=Math.max(0,Je(ne.distance,0)),We=k.type==="directional"||k.type==="spot"||k.type==="point",Ge;if(k.castShadow&&We){let Qe=ne.shadow,It=Math.max(256,Math.min(2048,Math.round(Je(Qe?.mapSize?.x??Qe?.mapSize?.width,1024))));Ge={cast:!0,mapSize:It<=384?256:It<=768?512:It<=1536?1024:2048,bias:Nn(Qe?.bias,-.05,.05,-5e-4),normalBias:Nn(Qe?.normalBias,0,.2,.015),radius:Nn(Qe?.radius,0,8,1.5)},b=!0}let ut=O-xe,nt=X-he,st=se-Ne,ft=Math.hypot(ut,nt,st);y.push({type:k.type,color:[k.color.r,k.color.g,k.color.b],intensity:k.intensity,position:k.type==="directional"?[ut,nt,st]:[O,X,se],...k.type==="directional"?{direction:ft>1e-6?[ut/ft,nt/ft,st/ft]:[0,1,0]}:k.type==="spot"?{direction:De>1e-6?[ge/De,Ae/De,Ee/De]:[0,-1,0],outerConeAngle:ke,innerConeAngle:Be,range:Ue}:k.type==="point"?{range:Ue}:k.type==="hemisphere"&&ne.groundColor?{groundColor:[ne.groundColor.r,ne.groundColor.g,ne.groundColor.b]}:{},...Ge?{shadow:Ge}:{}}),We&&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:De,outerAngle:ke,innerAngle:Be,range:Ue,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),De=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),De<X[2]&&(X[2]=De),De>se[2]&&(se[2]=De)}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 De=v.indexOf(Ae);if(De===-1&&v.length<256&&(De=v.length,v.push(Ae)),De===-1)continue;let ke=w(Ee),ze=ge.get(ke);ze||(ze=[],ge.set(ke,ze)),ze.push(De)}if(ge.size>0){let Ae=[];for(let[Ee,De]of ge.entries())Ae.push({material:Ee,variants:De});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),De=new Float32Array(ge*4),ke=new Float32Array(ge*3);for(let Be=0;Be<ge;Be++){let{t:Ue,r:We,s:Ge}=Od(Ae,Be*16);Ee[Be*3]=Ue[0],Ee[Be*3+1]=Ue[1],Ee[Be*3+2]=Ue[2],De[Be*4]=We[0],De[Be*4+1]=We[1],De[Be*4+2]=We[2],De[Be*4+3]=We[3],ke[Be*3]=Ge[0],ke[Be*3+1]=Ge[1],ke[Be*3+2]=Ge[2]}let ze={TRANSLATION:E(Ee,"VEC3",0,5126,ge),ROTATION:E(De,"VEC4",0,5126,ge),SCALE:E(ke,"VEC3",0,5126,ge)};if(he.instanceColor?.array&&he.instanceColor.array.length>=ge*3){let Be=new Float32Array(he.instanceColor.array.subarray(0,ge*3));ze._COLOR_0=E(Be,"VEC3",0,5126,ge)}H.extensions={...H.extensions||{},EXT_mesh_gpu_instancing:{attributes:ze}},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=Vd(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=>[Je(_e.position?.x,0),Je(_e.position?.y,0),Je(_e.position?.z,0),Je(_e.quaternion?.x,0),Je(_e.quaternion?.y,0),Je(_e.quaternion?.z,0),Je(_e.quaternion?.w,1),Je(_e.scale?.x,1),Je(_e.scale?.y,1),Je(_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]=Je(Re.position?.x,0),Z[ne][_e*3+1]=Je(Re.position?.y,0),Z[ne][_e*3+2]=Je(Re.position?.z,0);let W=Je(Re.quaternion?.x,0),D=Je(Re.quaternion?.y,0),z=Je(Re.quaternion?.z,0),O=Je(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]=Je(Re.scale?.x,1),ie[ne][_e*3+1]=Je(Re.scale?.y,1),ie[ne][_e*3+2]=Je(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=[],Fe=[];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&&Fe.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")}Fe.length>0&&$.push({name:"ProceduralLoop",samplers:Se,channels:Fe})}let F=fd(o,s,e.userData),V=[],Y=[],J=[];for(let k=0;k<o.length;k++){let G=o[k],q=zd(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:Nn(H.pitch,.25,4,1)}}:{}});let Fe=J.length,_e=Nn(H.refDistance,.05,100,1),Le=Nn(H.coneInnerAngle,0,360,360),ne=Nn(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:Nn(H.maxDistance,_e,500,Math.max(_e,25)),rolloffFactor:Nn(H.rolloffFactor,0,10,1),coneInnerAngle:+(Le*Math.PI/180).toFixed(6),coneOuterAngle:+(ne*Math.PI/180).toFixed(6),coneOuterGain:Nn(H.coneOuterGain,0,1,0)}}}),G.extensions={...G.extensions||{},KHR_audio_emitter:{emitter:Fe}},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 qc(e){return new TextEncoder().encode(e)}function qo(e,t){let{gltf:r,bin:i}=Qr(e,t),n=JSON.stringify(r),a=qc(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 Rp(e,t){let[r,i]=$d(e,t);return Gd(r,i)}function Gd(e,t){let r=[],i=e.gltf,n=He().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,_)=>Xc(x,Xo(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,Fe=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=(Be,Ue)=>Array.isArray(Be)&&Be.length>=3?[Be[0],Be[1],Be[2]]:Ue;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,De=b(D.normalTexture,[2*Ee,2*Ee,2,1],[-Ee,-Ee,-1,0]),ke=typeof D.occlusionTexture?.strength=="number"?D.occlusionTexture.strength:1,ze=ke!==1?b(D.occlusionTexture,[ke,ke,ke,1],[1-ke,1-ke,1-ke,0]):b(D.occlusionTexture);(ce||Ne||De||Ae||ze)&&(Re=[ce,Ne,De,Ae,ze]),W=D.extensions||{},W.KHR_materials_clearcoat&&(Se=W.KHR_materials_clearcoat.clearcoatFactor??0,Fe=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:Fe,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?[Je(k[0],G),Je(k[1],G),Je(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=Od(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=[Je(q.rotation[0],0),Je(q.rotation[1],0),Je(q.rotation[2],0),Je(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 Fe=(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 De=Ee.color||[.8,.8,.8],ke=ce&&ce.length>=(he+1)*3;xe.push({...Ee,name:`${Ee.name}_${he}`,materialName:ke?`${Ee.materialName}_inst_${he}`:Ee.materialName,color:ke?[De[0]*ce[he*3],De[1]*ce[he*3+1],De[2]*ce[he*3+2]]:Ee.color,translation:Ne,rotation:ge,scale:Ae})}}ee(de,xe),G.push(Fe(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(Fe(Le,O,_e))}}else{let Le=[];ee(de,Le),G.push(Fe(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)??Wc(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 Xo(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 gs(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ct(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 Dn=(e,t,r)=>`(${Ct(e)}, ${Ct(t)}, ${Ct(r)})`,Wo=(e,t,r,i)=>`(${Ct(e)}, ${Ct(t)}, ${Ct(r)}, ${Ct(i)})`;function Fd(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=Dn(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function Lp(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${Ct(e[i*2])}, ${Ct(1-e[i*2+1])})`;return r.join(", ")}function Pp(e){return Array.from(e).join(", ")}function Ip(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=Xo(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 = ${Ct(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,114 +230,224 @@ kind = "component"
265
230
  {
266
231
  ${l}def Scope "Materials"
267
232
  {
268
- `;for(let[m,g]of t.entries()){let[x,b,v]=g.color,[d,y,M]=g.emissiveColor,T="";g.clearcoat>0&&(T+=`float inputs:clearcoat = ${Ge(g.clearcoat)}
269
- `,T+=`float inputs:clearcoatRoughness = ${Ge(g.clearcoatRoughness)}
270
- `),g.ior!==1.5&&(T+=`float inputs:ior = ${Ge(g.ior)}
271
- `),g.opacity<1&&(T+=`float inputs:opacity = ${Ge(g.opacity)}
272
- `),(d>0||y>0||M>0)&&(T+=`color3f inputs:emissiveColor = ${xt(d,y,M)}
273
- `),o+=`def Material "${m}"
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 = ${Dn(A,b,w)}`,J=P?`float inputs:metallic${V("MetallicRoughnessTexture","b")}
234
+ float inputs:roughness${V("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${Ct(y.metallic)}
235
+ float inputs:roughness = ${Ct(y.roughness)}`,re="";y.clearcoat>0&&(re+=`float inputs:clearcoat = ${Ct(y.clearcoat)}
236
+ `,re+=`float inputs:clearcoatRoughness = ${Ct(y.clearcoatRoughness)}
237
+ `),y.ior!==1.5&&(re+=`float inputs:ior = ${Ct(y.ior)}
238
+ `),y.opacity<1&&(re+=`float inputs:opacity = ${Ct(y.opacity)}
239
+ `),$?re+=`color3f inputs:emissiveColor${V("EmissiveTexture","rgb")}
240
+ `:(S>0||E>0||N>0)&&(re+=`color3f inputs:emissiveColor = ${Dn(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"
244
+ {
245
+ uniform token info:id = "UsdPrimvarReader_float2"
246
+ string inputs:varname = "st"
247
+ float2 outputs:result
248
+ }
249
+ `;let G=(q,H,te,Z)=>{if(!H)return;let ae=H.scale?`float4 inputs:scale = ${Wo(H.scale[0],H.scale[1],H.scale[2],H.scale[3])}
250
+ `:"",ie=H.bias?`float4 inputs:bias = ${Wo(H.bias[0],H.bias[1],H.bias[2],H.bias[3])}
251
+ `:"";Q+=`def Shader "${q}"
252
+ {
253
+ uniform token info:id = "UsdUVTexture"
254
+ asset inputs:file = @${gs(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
262
+ float outputs:b
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&&He().tslUsdzSerializer?.(y.tslGraph,v,ee);k&&(ee=k.surfaceInputsUsda||ee,Q+=k.nodeGraphUsda),c+=`def Material "${v}"
274
269
  {
275
270
  def Shader "PBRShader"
276
271
  {
277
272
  uniform token info:id = "UsdPreviewSurface"
278
- color3f inputs:diffuseColor = ${xt(x,b,v)}
279
- float inputs:metallic = ${Ge(g.metallic)}
280
- float inputs:roughness = ${Ge(g.roughness)}
281
- ${T}token outputs:surface
273
+ ${ee}token outputs:surface
282
274
  }
283
- token outputs:surface.connect = </Root/Materials/${m}/PBRShader.outputs:surface>
284
- }
285
- `}o+=`}
275
+ token outputs:surface${V("PBRShader","surface")}
276
+ ${Q}}
277
+ `}c+=`}
286
278
  def Scope "Meshes"
287
279
  {
288
- `;let a=(m,g,x)=>{let b=[];g&&b.push('"MaterialBindingAPI"');let v=!!(m?.rigidBody&&m.rigidBody!=="none"&&(typeof m.rigidBody!="object"||m.rigidBody.enabled!==!1)),d=!!(m?.physics&&m.physics!=="none"||v);d&&b.push(...v?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let y=[];if(b.length>0&&y.push(`prepend apiSchemas = [${b.join(", ")}]`),m){let P=Me().xrTraitSerializer?.usdLines(m,Ni)??[];if(!P.length)for(let R of["grab","billboard","follow","anchor","physics"]){let C=R==="follow"&&typeof m.follow=="object"?m.follow.mode??"head":m[R];C!==void 0&&P.push(`string ${R} = "${Ni(C)}"`)}P.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=He().xrTraitSerializer;if(v){let $=N?.usdLines(v,gs)??[];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} = "${gs(V)}"`)}$.length>0&&E.push(`customData = {
289
281
  dictionary xr = {
290
- ${P.join(`
282
+ ${$.join(`
291
283
  `)}
292
284
  }
293
- }`)}let M=y.length>0?` (
294
- ${y.join(`
285
+ }`)}let C=E.length>0?` (
286
+ ${E.join(`
295
287
  `)}
296
- )`:"",T=x?`uniform token visibility = "invisible"
297
- `:"";if(d){let P=m?.rigidBody??m?.physics,R=P?.body??P?.mode??P;T+=`bool physics:rigidBodyEnabled = true
298
- bool physics:kinematicEnabled = ${R==="static"||R==="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"}
299
291
  bool physics:collisionEnabled = true
300
- `,P?.mass>0&&Number.isFinite(P.mass)&&(T+=`float physics:mass = ${Ge(P.mass)}
301
- `)}let V=Ts(m),X=V?`def SpatialAudio "AudioEmitter"
292
+ `,$?.mass>0&&Number.isFinite($.mass)&&(_+=`float physics:mass = ${Ct($.mass)}
293
+ `)}let P=zd(v),R=(P?`def SpatialAudio "AudioEmitter"
302
294
  {
303
- ${V.src?`asset inputs:file = @${Ni(V.src)}@
304
- `:""}uniform token inputs:auralMode = "${V.isGlobal?"nonSpatial":"spatial"}"
305
- uniform token inputs:playbackMode = "${V.loop?"loopFromStart":"onceFromStart"}"
306
- double gain = ${Ge(V.volume)}
307
- }
308
- `:"";return{header:M,body:T,tail:X}},u=m=>{if(m.timeSamples&&m.timeSamples.times.length>0){let y=m.timeSamples,M=(P,R,C)=>y.times.map((B,N)=>`${Ge(B)}: ${C(P?.[N]||R)}`).join(", "),T=M(y.translations,[0,0,0],P=>xt(P[0],P[1],P[2])),V=M(y.rotations,[0,0,0,1],P=>{let R=Math.hypot(P[0],P[1],P[2],P[3])||1;return gs(P[3]/R,P[0]/R,P[1]/R,P[2]/R)}),X=M(y.scales,[1,1,1],P=>xt(P[0],P[1],P[2]));return`double3 xformOp:translate.timeSamples = { ${T} }
309
- quatf xformOp:orient.timeSamples = { ${V} }
310
- double3 xformOp:scale.timeSamples = { ${X} }
295
+ ${P.src?`asset inputs:file = @${gs(P.src)}@
296
+ `:""}uniform token inputs:auralMode = "${P.isGlobal?"nonSpatial":"spatial"}"
297
+ uniform token inputs:playbackMode = "${P.loop?"loopFromStart":"onceFromStart"}"
298
+ double gain = ${Ct(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)=>`${Ct(V)}: ${F(R?.[Y]||$)}`).join(", "),C=N(E.translations,[0,0,0],R=>Dn(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 Wo(R[3]/$,R[0]/$,R[1]/$,R[2]/$)}),P=N(E.scales,[1,1,1],R=>Dn(R[0],R[1],R[2]));return`double3 xformOp:translate.timeSamples = { ${C} }
301
+ quatf xformOp:orient.timeSamples = { ${_} }
302
+ double3 xformOp:scale.timeSamples = { ${P} }
311
303
  uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
312
- `}let g=[],x="",b=m.translation;b&&(Math.abs(b[0])>1e-7||Math.abs(b[1])>1e-7||Math.abs(b[2])>1e-7)&&(x+=`double3 xformOp:translate = ${xt(b[0],b[1],b[2])}
313
- `,g.push('"xformOp:translate"'));let v=m.rotation;if(v){let y=Math.hypot(v[0],v[1],v[2],v[3])||1,M=v[0]/y,T=v[1]/y,V=v[2]/y,X=v[3]/y;(1-Math.abs(X)>1e-7||Math.hypot(M,T,V)>1e-7)&&(x+=`quatf xformOp:orient = ${gs(X,M,T,V)}
314
- `,g.push('"xformOp:orient"'))}let d=m.scale;return d&&(Math.abs(d[0]-1)>1e-7||Math.abs(d[1]-1)>1e-7||Math.abs(d[2]-1)>1e-7)&&(x+=`float3 xformOp:scale = ${xt(d[0],d[1],d[2])}
315
- `,g.push('"xformOp:scale"')),g.length>0&&(x+=`uniform token[] xformOpOrder = [${g.join(", ")}]
316
- `),x},h=m=>{let g=m.positions.length/3,x=1/0,b=1/0,v=1/0,d=-1/0,y=-1/0,M=-1/0;for(let R=0;R<g;R++){let C=m.positions[R*3],B=m.positions[R*3+1],N=m.positions[R*3+2];C<x&&(x=C),C>d&&(d=C),B<b&&(b=B),B>y&&(y=B),N<v&&(v=N),N>M&&(M=N)}isFinite(x)||(x=b=v=-1,d=y=M=1);let T=Math.floor(m.indices.length/3),V=ur(m.materialName,"DefaultMaterial"),X=T>0?T===1?"3":"3, ".repeat(T-1)+"3":"",P=`float3[] extent = [${xt(x,b,v)}, ${xt(d,y,M)}]
317
- int[] faceVertexCounts = [${X}]
318
- int[] faceVertexIndices = [${xc(m.indices)}]
319
- point3f[] points = [${xs(m.positions)}]
320
- `;return m.normals&&m.normals.length===m.positions.length&&(P+=`normal3f[] normals = [${xs(m.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 = ${Dn(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 = ${Wo(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 = ${Dn(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),_=Xo(v.materialName,"DefaultMaterial"),P=C>0?C===1?"3":"3, ".repeat(C-1)+"3":"",R=`float3[] extent = [${Dn(A,b,w)}, ${Dn(S,E,N)}]
309
+ int[] faceVertexCounts = [${P}]
310
+ int[] faceVertexIndices = [${Pp(v.indices)}]
311
+ point3f[] points = [${Fd(v.positions)}]
312
+ `;return v.normals&&v.normals.length===v.positions.length&&(R+=`normal3f[] normals = [${Fd(v.normals)}] (
321
313
  interpolation = "vertex"
322
314
  )
323
- `),m.uvs&&m.uvs.length===g*2&&(P+=`texCoord2f[] primvars:st = [${gc(m.uvs,g)}] (
315
+ `),v.uvs&&v.uvs.length===y*2&&(R+=`texCoord2f[] primvars:st = [${Lp(v.uvs,y)}] (
324
316
  interpolation = "vertex"
325
317
  )
326
- `),P+=`rel material:binding = </Root/Materials/${V}>
327
- `,P},c=new Set,f=[];for(let m=e.length-1;m>=0;m--)f.push({node:e[m],siblings:c});let p=0;for(;f.length>0;){let m=f.pop();if(m.close){o+=`}
328
- `;continue}let{node:g,siblings:x}=m,b=!!(g.isXform||g.positions.length===0),v=vs(x,ur(g.name,b?`Group_${p}`:`Mesh_${p}`));p++;let d=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=Xc(A,Xo(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}
329
322
  {
330
- ${y.body}${u(g)}${y.tail}`,f.push({close:!0});let M=new Set;for(let T=d.length-1;T>=0;T--)f.push({node:d[T],siblings:M})}else if(d.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}
331
324
  {
332
- ${y.body}${u(g)}${y.tail}`,o+=`def Mesh "${M}" (
325
+ ${E.body}${m(y)}${E.tail}`,c+=`def Mesh "${N}" (
333
326
  prepend apiSchemas = ["MaterialBindingAPI"]
334
327
  )
335
328
  {
336
- ${h(g)}}
337
- `,f.push({close:!0});let T=new Set([M]);for(let V=d.length-1;V>=0;V--)f.push({node:d[V],siblings:T})}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=Xc(v,Xo(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]=Vd($,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 = ${Dn(_,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 = ${Wo(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 = ${Ct(q)}
340
+ float inputs:shaping:cone:softness = ${Ct(te)}
341
+ `}c+=`def ${w} "${b}" (
342
+ prepend apiSchemas = ${S}
343
+ )
344
+ {
345
+ color3f inputs:color = ${Dn(E,N,C)}
346
+ float inputs:intensity = ${Ct(A.intensity??1)}
347
+ bool inputs:shadow:enable = 1
348
+ ${G}${ee}}
349
+ `}c+=`}
350
+ `}return c+=`}
351
+ `,c}var xs=null;function Yo(e){if(!xs){xs=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;xs[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=xs[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function jd(e){let t=[],r=0,i=[];for(let f of e){let m=qc(f.filename),h=Yo(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 Hd(e){let t=[{filename:"model.usda",data:qc(Ip(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 jd(t)}function Ko(e){return Hd(Rp(e))}function Jo(e){return Hd(Gd(wr(e)))}function Qo(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():Jo(e)}function Zr(e){let t=Qo(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function Zo(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 Br="GOOGLE_material_tsl",Xd=128,eo=16,Wn=3600,Cp={positionLocal:"vec3",positionWorld:"vec3",normalLocal:"vec3",normalWorld:"vec3",viewDirection:"vec3",uv:"vec2",vertexColor:"vec4",instanceIndex:"float",time:"float"},Np={color:"vec3",opacity:"float",emissive:"vec3",roughness:"float",metalness:"float",normalScale:"float",bump:"vec3",position:"vec3"},Dp=new Set(["neg","abs","sign","floor","ceil","fract","sqrt","exp","log","sin","cos","normalize"]),Up=new Set(["add","sub","mul","div","mod","pow","atan2","min","max"]),Wd={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"]},Bp=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,Fp=new Set(["__proto__","constructor","prototype"]);function vs(e,t){let r=Math.abs(t)<1e-6?t<0?-1e-6:1e-6:t;return e-r*Math.floor(e/r)}function Wt(e){return e==="vec4"?4:e==="vec3"?3:e==="vec2"?2:1}function Kc(e){return e===1?"float":e===2?"vec2":e===3?"vec3":e===4?"vec4":null}function Yc(e){return e==="float"||e==="vec2"||e==="vec3"||e==="vec4"}function mt(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 Ur(e,t){for(let r=0;r<t.length;r++)e=Math.imul((e^t.charCodeAt(r))>>>0,16777619)>>>0;return e}var qd=new Float32Array(1),Vp=new Uint32Array(qd.buffer);function Op(e,t){return qd[0]=t,Math.imul((e^Vp[0])>>>0,16777619)>>>0}function ei(e,t){let r=Wt(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 Sr(e,t="Material"){if(!e||typeof e!="object"||Array.isArray(e))return mt("TL501",`Invalid GOOGLE_material_tsl on '${t}'.`);let r=e;if(r.version!==1)return mt("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 mt("TL501",`Invalid TSL uniforms on '${t}'.`);let y=a,A=Object.keys(y).sort();if(A.length>16)return mt("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=Yc(E)?ei(E,S.value):null;if(Fp.has(w)||!Bp.test(w)||!Yc(E)||!N)return mt("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 mt("TL501",`Empty TSL nodes on '${t}'.`);if(s.length>128)return mt("TL502",`TSL '${t}' exceeds MAX_TSL_NODES (128).`);let o=[],l=2166136261;for(let y of i)l=Ur(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 mt("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 mt("TL504",`Unsupported loop/call op '${w}' at node ${y} on '${t}'.`);if(typeof w!="string"||!Yc(S))return mt("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 mt("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 mt("TL501",`Cyclic or out-of-order arg at node ${y} on '${t}'.`);C.push(P)}}l=Ur(l,`N${y}:${E}:${S}:`);for(let P of C)l=Ur(l,`${P},`);let _=C.map(P=>o[P].type);if(E==="const"){let P=Wt(S),R=b.value;if(C.length!==0||!Array.isArray(R)||R.length!==P)return mt("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 mt("TL501",`Non-finite const at node ${y}.`);let Y=Math.fround(V);$.push(Y),l=Op(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"||Cp[P]!==S)return mt("TL501",`Invalid builtin at node ${y}.`);l=Ur(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 mt("TL501",`Invalid uniform ref at node ${y}.`);l=Ur(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)||Kc(P.length)!==S)return mt("TL501",`Invalid swizzle at node ${y}.`);let R=Wt(_[0]);for(let $=0;$<P.length;$++)if("xyzw".indexOf(P[$])>=R)return mt("TL501",`Swizzle '.${P}' out of bounds at node ${y}.`);l=Ur(l,P),o.push({op:E,type:S,args:C,mask:P})}else if(E==="construct"){let P=Wt(S),R=_.reduce(($,F)=>$+Wt(F),0);if(C.length===0||!(C.length===1&&_[0]==="float")&&R!==P)return mt("TL501",`Invalid construct at node ${y}.`);o.push({op:E,type:S,args:C})}else if(Dp.has(E)){if(C.length!==1||_[0]!==S)return mt("TL501",`Type mismatch on '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(Up.has(E)){if((C.length===2?_[0]===_[1]?_[0]:_[0]==="float"?_[1]:_[1]==="float"?_[0]:null:null)!==S)return mt("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 mt("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 mt("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 mt("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 mt("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 mt("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 mt("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 mt("TL501",`Invalid 'reflect' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E in Wd){let[P,R]=Wd[E];if(C.length!==P.length||S!==R||P.some(($,F)=>_[F]!==$))return mt("TL501",`Invalid '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else return mt("TL501",`Unknown TSL op '${String(E)}' at node ${y}.`)}let c=r.outputs;if(!c||typeof c!="object"||Array.isArray(c))return mt("TL501",`Missing TSL outputs on '${t}'.`);let f=c,m={},h=0;for(let y of Object.keys(f).sort()){let A=Np[y];if(!A)return mt("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 mt("TL501",`Invalid TSL output '${y}' on '${t}'.`);m[y]=b,h++,l=Ur(l,`O:${y}=${b};`)}}if(h===0)return mt("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 mt("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 Un(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 ti(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 zp=["x","y","z","w"],Jd=[[2,"vec2"],[3,"vec3"],[4,"vec4"]];function to(e,t){return Jd.map(([r,i])=>{let n=zp.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 Yd(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);}",...to("_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);}",...to("_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));}",...to("_tslPow",2)),e.clamp&&r.push("float _tslClamp(float a,float b,float c){return clamp(a,min(b,c),max(b,c));}",...to("_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);}",...to("_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);}",...to("_tslAtan2",2)),e.norm&&r.push("float _tslNorm(float v){return abs(v)>1e-6?sign(v):0.0;}",...Jd.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 $p={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function Kd(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(Un);g=o==="float"?x[0]:`${o}(${x.join(",")})`;break}case"builtin":g=s.builtin==="time"?`_tslMod(uTslTime,${Un(3600)})`:$p[s.builtin]??"0.0";break;case"uniform":{let x=`uTslParams[${s.uniformSlot??0}]`,v=Wt(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 ws(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=Yd(ti(e.nodes,e.vertexReachable,e.usesTime),!1),c=Kd(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=Yd(ti(e.nodes,e.fragmentReachable,e.usesTime),!0),c=Kd(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 Gp={float:"float",vec2:"float2",vec3:"float3",vec4:"float4"},jp={float:"float",vec2:"vector2",vec3:"vector3",vec4:"vector4"};function xn(e){return Gp[e]||"float"}function Mr(e){return jp[e]||"float"}function ni(e,t){if(t===1)return Un(e[0]??0);let r=[];for(let i=0;i<t;i++)r.push(Un(e[i]??0));return`(${r.join(", ")})`}function Ss(e,t,r=""){let i;if(e&&typeof e=="object"&&"fragmentReachable"in e)i=e;else{let w=Sr(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=xn(w.type),E=Wt(w.type);s.push(`${S} inputs:u_${w.slot} = ${ni(w.defaultVec4,E)}`)}let l=(w,S,E,N)=>(a.push(`def Shader "${w}"
378
+ {
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=Wt(w),N=`C_${o++}`;return l(N,`ND_constant_${Mr(w)}`,xn(w),[`${xn(w)} inputs:value = ${ni(S,E)}`])},f=(w,S)=>{if(S==="float")return w;let E=Wt(S),N=`B_${o++}`,C=[];for(let _=1;_<=E;_++)C.push(`float inputs:in${_}.connect = <${w}>`);return l(N,`ND_combine${E}_${Mr(S)}`,xn(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_${Mr(S)}`,"float",[`${xn(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 = ${Un(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=xn(E),C=Mr(E),_=Wt(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 = ${ni(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=Wt(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 = ${ni([-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 = ${ni([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_${Mr(F)}`,"float",[`${xn(F)} inputs:in1.connect = <${P}>`,`${xn(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_${Mr(F)}`,"float",[`${xn(F)} inputs:in.connect = <${P}>`]);break;case"distance":{let re=l(`D_${o++}`,`ND_subtract_${Mr(F)}`,xn(F),[`${xn(F)} inputs:in1.connect = <${P}>`,`${xn(F)} inputs:in2.connect = <${R}>`]);x[w]=F==="float"?l(J,"ND_absval_float","float",[`float inputs:in.connect = <${re}>`]):l(J,`ND_magnitude_${Mr(F)}`,"float",[`${xn(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"
338
388
  {
339
- ${y.body}${u(g)}${h(g)}${y.tail}}
340
- `}}return o+=`}
389
+ ${[...s,...v,...a].join(`
390
+ `)}
341
391
  }
342
- `,o}function ws(e,t){if(e&&typeof e.traverse=="function"){let n=yc(e,t);return ki(n)}let r=gt(e),i=Ui(r);return ki(i)}var cr=null;function Mn(e){if(!cr){cr=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;cr[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=cr[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function Ss(e){let t=[],r=0,i=[];for(let h of e){let c=Oi(h.filename),f=Mn(h.data),p=h.data.length,m=30+c.length,g=(r+m)%64,x=g!==0?64-g:0,b=new Uint8Array(m+x),v=new DataView(b.buffer);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint32(14,f,!0),v.setUint32(18,p,!0),v.setUint32(22,p,!0),v.setUint16(26,c.length,!0),v.setUint16(28,x,!0),b.set(c,30),t.push({offset:r,size:p,crc:f,filenameBytes:c,entry:h}),i.push(b,h.data),r+=b.length+h.data.length}let n=r;for(let h of t){let c=new Uint8Array(46+h.filenameBytes.length),f=new DataView(c.buffer);f.setUint32(0,33639248,!0),f.setUint16(4,20,!0),f.setUint16(6,20,!0),f.setUint32(16,h.crc,!0),f.setUint32(20,h.size,!0),f.setUint32(24,h.size,!0),f.setUint16(28,h.filenameBytes.length,!0),f.setUint32(42,h.offset,!0),c.set(h.filenameBytes,46),i.push(c),r+=c.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}var Es=e=>Ss([{filename:"model.usda",data:Oi(e)}]);function Tn(e){return Es(ws(e))}function An(e){return Es(ki(Ui(gt(e))))}function wn(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():An(e)}function sn(e){let t=wn(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function Nt(e,t,r,i){let n=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,n))}function vc(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function Fi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Mc(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function Rs(e){let t=Fi(e);if(!t)return null;let r=t.target;return{target:vc(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:Nt(t.radius,.01,50,.5),speed:Nt(t.speed,-20,20,.5),height:Nt(t.height,-10,10,0),phase:Nt(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var Tc=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],Ac=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],Qu=new Set(Tc),Ju=new Set(Ac);function Vi(e,t){let r=Mc(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 Bi(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:Fi(e);if(!t||t.enabled===!1)return null;let r=Nt(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:Nt(t.threshold,0,4,.8),radius:Nt(t.radius,0,2,.5)}:null}function lr(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:Fi(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:Vi(t.color,"#38bdf8"),thickness:Nt(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var nt=class Ho{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 Ho(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}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)}},ge=class Go{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 Go(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addVectors(t,r){return this.x=t.x+r.x,this.y=t.y+r.y,this.z=t.z+r.z,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subVectors(t,r){return this.x=t.x-r.x,this.y=t.y-r.y,this.z=t.z-r.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t,t)}addScaledVector(t,r){return this.x+=t.x*r,this.y+=t.y*r,this.z+=t.z*r,this}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let t=this.length();return t>1e-5&&(this.x/=t,this.y/=t,this.z/=t),this}cross(t){let r=this.y*t.z-this.z*t.y,i=this.z*t.x-this.x*t.z,n=this.x*t.y-this.y*t.x;return this.x=r,this.y=i,this.z=n,this}crossVectors(t,r){let i=t.x,n=t.y,s=t.z,l=r.x,o=r.y,a=r.z;return this.x=n*a-s*o,this.y=s*l-i*a,this.z=i*o-n*l,this}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}},pr=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}},_n=class Fa{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._x=t.x,this._y=t.y,this._z=t.z,this.order=t.order,this._onChangeCallback?.(),this}clone(){return new Fa(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},Ln=class Va{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._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback?.(),this}clone(){return new Va(this._x,this._y,this._z,this._w)}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),c=Math.sin(s/2);return this._x=u*o*a+l*h*c,this._y=l*h*a-u*o*c,this._z=l*o*c+u*h*a,this._w=l*o*a-u*h*c,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 el{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 el;return t.copy(this),t}compose(t,r,i){return yt(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 Pe(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 ge(0,0,0),i=new ge(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}},br=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 ze(this.elements,e.elements),this}},Qe=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,mr=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,_s={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},it=class tl{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 _s)this.setHex(_s[r]);else if(r.startsWith("hsl")){let i=/^hsla?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);i&&i.length>=3&&this.setHSL((parseFloat(i[0])||0)/360,(parseFloat(i[1])||0)/100,(parseFloat(i[2])||0)/100)}else{let i=/^rgba?\(([^)]+)\)$/.exec(r)?.[1].trim().split(/[\s,/]+/);if(i&&i.length>=3){let n=s=>Qe(Math.max(0,Math.min(1,(parseFloat(s)||0)/(s.endsWith("%")?100:255))));this.setRGB(n(i[0]),n(i[1]),n(i[2]))}}return this}setHSL(t,r,i){if(t=((Number(t)||0)%1+1)%1,r=Math.max(0,Math.min(1,Number(r)||0)),i=Math.max(0,Math.min(1,Number(i)||0)),r===0){let o=Qe(i);return this.setRGB(o,o,o)}let n=i<=.5?i*(1+r):i+r-i*r,s=2*i-n,l=o=>(o<0&&(o+=1),o>1&&(o-=1),o<1/6?s+(n-s)*6*o:o<1/2?n:o<2/3?s+(n-s)*6*(2/3-o):s);return this.setRGB(Qe(l(t+1/3)),Qe(l(t)),Qe(l(t-1/3)))}lerp(t,r){let i=Number(r)||0;return this.r+=(t.r-this.r)*i,this.g+=(t.g-this.g)*i,this.b+=(t.b-this.b)*i,this}lerpColors(t,r,i){let n=Number(i)||0;return this.r=t.r+(r.r-t.r)*n,this.g=t.g+(r.g-t.g)*n,this.b=t.b+(r.b-t.b)*n,this}multiplyScalar(t){let r=Number(t)||0;return this.r*=r,this.g*=r,this.b*=r,this}setScalar(t){let r=Number(t)||0;return this.setRGB(r,r,r)}setHex(t){let r=Math.floor(t);return this.r=Qe((r>>16&255)/255),this.g=Qe((r>>8&255)/255),this.b=Qe((r&255)/255),this}setRGB(t,r,i){return this.r=Number(t),this.g=Number(r),this.b=Number(i),this}convertSRGBToLinear(){return this.r=Qe(this.r),this.g=Qe(this.g),this.b=Qe(this.b),this}convertLinearToSRGB(){return this.r=mr(this.r),this.g=mr(this.g),this.b=mr(this.b),this}getHex(){let t=r=>Math.round(mr(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.r=t.r,this.g=t.g,this.b=t.b,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}clone(){return new tl(this.r,this.g,this.b)}},Os={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 rl{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 rl(new t(this.array),this.itemSize)}},yr=class extends He{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},gr=class extends He{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},xr=class extends He{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},Fe=class il{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=t.count,i=new Float32Array(r*3),n=new ge,s=new ge,l=new ge,o=new ge,a=new ge,u=this.index?.array,h=u?u.length:r;for(let c=0;c<h;c+=3){let f=u?u[c]:c,p=u?u[c+1]:c+1,m=u?u[c+2]:c+2;n.set(t.getX(f),t.getY(f),t.getZ(f)),s.set(t.getX(p),t.getY(p),t.getZ(p)),l.set(t.getX(m),t.getY(m),t.getZ(m)),o.subVectors(l,s),a.subVectors(n,s),o.cross(a).normalize();for(let g of[f,p,m])i[g*3]+=o.x,i[g*3+1]+=o.y,i[g*3+2]+=o.z}for(let c=0;c<r;c++){let f=i[c*3],p=i[c*3+1],m=i[c*3+2],g=Math.hypot(f,p,m)||1;i[c*3]=f/g,i[c*3+1]=p/g,i[c*3+2]=m/g}return this.setAttribute("normal",new He(i,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 ge(1/0,1/0,1/0),i=new ge(-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 ge;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 il;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(){}},In=class extends Fe{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 c=h*4;a.push(0,0,1,0,1,1,0,1),u.push(c,c+1,c+2,c,c+2,c+3)}this.setFromBuffers(l,o,a,u)}},vr=class extends Fe{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 c=h/r;if(n.push((c-.5)*e,(.5-u)*t,0),s.push(0,0,1),l.push(c,1-u),a>0&&h>0){let f=(r+1)*a+h-1,p=f-(r+1);o.push(p,f,p+1,f,f+1,p+1)}}}this.setFromBuffers(n,s,l,o)}},Mr=class extends Fe{constructor(e=1,t=16,r=12){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let i=[],n=[],s=[],l=[];for(let o=0;o<=r;o++){let a=o/r;for(let u=0;u<=t;u++){let h=u/t,c=h*Math.PI*2,f=a*Math.PI,p=-Math.cos(c)*Math.sin(f),m=Math.cos(f),g=Math.sin(c)*Math.sin(f);if(i.push(e*p,e*m,e*g),n.push(p,m,g),s.push(h,1-a),o>0&&u>0){let x=(t+1)*o+u,b=x-(t+1),v=b-1,d=x-1;o!==1&&l.push(b,v,x),o!==r&&l.push(v,d,x)}}}this.setFromBuffers(i,n,s,l)}},Cn=class extends Fe{constructor(e=1,t=1,r=1,i=16){super(),i=Math.max(3,Math.floor(i));let n=[],s=[],l=[],o=[],a=r/2;for(let h=0;h<=1;h++){let c=h,f=h===0?e:t,p=h===0?a:-a;for(let m=0;m<=i;m++){let g=m/i,x=g*Math.PI*2,b=Math.sin(x),v=Math.cos(x);n.push(f*b,p,f*v),s.push(b,0,v),l.push(g,1-c)}}for(let h=0;h<i;h++){let c=h,f=h+i+1,p=h+i+2,m=h+1;o.push(c,f,m,f,p,m)}let u=(h,c)=>{if(h<=0)return;let f=c*a,p=n.length/3;n.push(0,f,0),s.push(0,c,0),l.push(.5,.5);let m=n.length/3;for(let g=0;g<=i;g++){let x=g/i*Math.PI*2,b=Math.sin(x),v=Math.cos(x);n.push(h*b,f,h*v),s.push(0,c,0),l.push(v*.5+.5,.5+c*b*.5)}for(let g=0;g<i;g++)o.push(p,m+g+(c>0?0:1),m+g+(c>0?1:0))};u(e,1),u(t,-1),this.setFromBuffers(n,s,l,o)}},Tr=class extends Cn{constructor(e=1,t=1,r=16){super(0,e,t,r)}},Ar=class extends Fe{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,c=Math.cos(h),f=Math.sin(h);for(let p=0;p<=i;p++){let m=p/i*n,g=Math.cos(m),x=Math.sin(m);if(s.push((e+t*c)*g,(e+t*c)*x,t*f),l.push(c*g,c*x,f),o.push(p/i,u/r),u>0&&p>0){let b=(i+1)*u+p-1,v=b-(i+1);a.push(b,v,b+1,v,v+1,b+1)}}}this.setFromBuffers(s,l,o,a)}};function Us(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=[],c=[],f=new ge,p=new ge,m=new ge,g=new ge,x=new ge;for(let v=0;v<=s;v++){let d=v/s;n(Math.max(0,d-.001),f),n(Math.min(1,d+.001),p),m.subVectors(p,f).normalize(),v===0&&g.set(Math.abs(m.y)>.9?1:0,Math.abs(m.y)>.9?0:1,0),x.crossVectors(m,g).normalize(),g.crossVectors(x,m).normalize(),n(d,f);for(let y=0;y<=l;y++){let M=y/l*Math.PI*2,T=-o*Math.cos(M),V=o*Math.sin(M),X=T*g.x+V*x.x,P=T*g.y+V*x.y,R=T*g.z+V*x.z;a.push(f.x+X,f.y+P,f.z+R);let C=Math.hypot(X,P,R)||1;u.push(X/C,P/C,R/C),h.push(d,y/l)}}let b=l+1;for(let v=1;v<=s;v++){let d=b*(v-1),y=d+b;for(let M=1;M<=l;M++){let T=d+M-1,V=y+M-1;c.push(T,V,d+M,V,y+M,d+M)}}e.setFromBuffers(a,u,h,c)}var wr=class extends Fe{constructor(e=1,t=.4,r=64,i=8,n=2,s=3){super(),r=Math.floor(r),i=Math.floor(i),Us(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)})}},Mt=class{getPoint(e,t=new ge){return t}getPointAt(e,t=new ge){return this.getPoint(e,t)}getTangent(e,t=new ge){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)}},Sr=class extends Mt{constructor(e=new ge,t=new ge){super(),this.v1=e,this.v2=t}getPoint(e,t=new ge){return t.lerpVectors(this.v1,this.v2,e)}},Er=class extends Mt{constructor(e=new ge,t=new ge,r=new ge){super(),this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new ge){return t.lerpVectors(this.v0,this.v1,e).lerp(new ge().lerpVectors(this.v1,this.v2,e),e)}},Rr=class extends Mt{constructor(e=new ge,t=new ge,r=new ge,i=new ge){super(),this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new ge){let r=new ge().lerpVectors(this.v0,this.v1,e),i=new ge().lerpVectors(this.v1,this.v2,e),n=new ge().lerpVectors(this.v2,this.v3,e);return t.lerpVectors(r.lerp(i,e),i.lerp(n,e),e)}},_r=class extends Mt{constructor(e=[],t=!1){super(),this.points=Array.isArray(e)?e:[],this.closed=!!t}getPoint(e,t=new ge){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),c=o(s+2),f=l*l,p=f*l,m=(g,x,b,v)=>.5*(2*x+(b-g)*l+(2*g-5*x+4*b-v)*f+(3*x-g-3*b+v)*p);return t.set(m(a.x,u.x,h.x,c.x),m(a.y,u.y,h.y,c.y),m(a.z,u.z,h.z,c.z))}},Dn=class extends Fe{constructor(e=[new nt(0,-.5),new nt(.5,0),new nt(0,.5)],t=12,r=0,i=Math.PI*2){super();let n=Array.isArray(e)&&e.length>=2?e:[new nt(.2,0),new nt(.2,.5)],s=Math.max(3,Math.min(128,Math.floor(Number(t)||12))),l=[],o=[],a=[],u=[],h=n.length;for(let c=0;c<=s;c++){let f=c/s,p=r+f*i,m=Math.sin(p),g=Math.cos(p);for(let x=0;x<h;x++){let b=n[x],v=Number(b?.x)||0,d=Number(b?.y)||0;l.push(v*m,d,v*g);let y=n[Math.max(0,x-1)],M=n[Math.min(h-1,x+1)],T=(Number(M?.x)||0)-(Number(y?.x)||0),V=(Number(M?.y)||0)-(Number(y?.y)||0),X=Math.hypot(V,T)||1;o.push(V/X*m,-T/X,V/X*g),a.push(f,x/(h-1))}}for(let c=0;c<s;c++){let f=c*h;for(let p=0;p<h-1;p++){let m=f+p,g=f+h+p;u.push(m,g,m+1,g,g+1,m+1)}}this.setFromBuffers(l,o,a,u)}},Lr=class extends Fe{constructor(e,t=64,r=1,i=8,n=!1){super(),Us(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)})}},fr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",an=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new nt(1,1),this.offset=new nt(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},Ir=class extends an{constructor(e=null,t=1,r=1,i=1023,n=1009,s,l=1001,o=1001,a=1003,u=1003,h=1,c=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1;let f=Number(t),p=Number(r),m=e&&typeof e.length=="number"?e:null;this.width=f,this.height=p,this.image={data:m,width:f,height:p},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=c||"",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,96),c=Math.min(s,96),f=c*(1+h*4),p=new Uint8Array(68+f),m=new DataView(p.buffer);m.setUint32(0,2303741511),m.setUint32(4,218765834),m.setUint32(8,13),m.setUint32(12,1229472850),m.setUint32(16,h),m.setUint32(20,c),p[24]=8,p[25]=6,m.setUint32(29,Mn(p.subarray(12,29))),m.setUint32(33,f+11),m.setUint32(37,1229209940),p[41]=120,p[42]=1,p[43]=1,m.setUint16(44,f,!0),m.setUint16(46,~f&65535,!0);let g=48,x=1,b=0,v=0,d=0,y=0,M=0,T=R=>{if(!Number.isFinite(R))return 0;let C=u&&R<=1?R*255:R;return C>0?C<255?C+.5|0:255:0};for(let R=0;R<c;R++){let C=R*s/c|0,B=this.flipY?s-1-C:C;p[g++]=0,b+=x;for(let N=0;N<h;N++){let w=(B*n+(N*n/h|0))*a,ie=o===1021?255:T(t[w]??0),ae=a>=3||o===1030?T(t[w+1]??0):ie,k=a>=3?T(t[w+2]??0):o===1030?0:ie,J=a===4?T(t[w+3]??255):o===1021?T(t[w]??255):o===1025?T(t[w+1]??255):255;p[g++]=ie,x+=ie,b+=x,p[g++]=ae,x+=ae,b+=x,p[g++]=k,x+=k,b+=x,p[g++]=J,x+=J,b+=x,v+=ie,d+=ae,y+=k,M+=J}x%=65521,b%=65521}m.setUint32(g,(b<<16|x)>>>0),m.setUint32(g+4,Mn(p.subarray(37,g+4))),m.setUint32(g+12,1229278788),m.setUint32(g+16,2923585666);let V=h*c*255,X=this.colorSpace==="srgb-linear";this.avgColor=[X?v/V:Qe(v/V),X?d/V:Qe(d/V),X?y/V:Qe(y/V),M/V];let P=["data:image/png;base64,"];for(let R=0;R<p.length;R+=3){let C=p[R]<<16|(p[R+1]??0)<<8|(p[R+2]??0);P.push(fr[C>>18&63]+fr[C>>12&63]+(R+1<p.length?fr[C>>6&63]:"=")+(R+2<p.length?fr[C&63]:"="))}this.source=P.join("")}},Cr=class{load(e,t){let r=new an(e);return t?.(r),r}};function qe(e,t){return e!==void 0?Number(e):t}function zi(e,t){return e!==void 0?!!e:t}var Je=class{constructor(e={}){this.name=e.name||"",this.color=new it(e.color!==void 0?e.color:16777215),this.emissive=new it(e.emissive!==void 0?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=zi(e.transparent,!1),this.wireframe=zi(e.wireframe,!1),this.side=qe(e.side,2),this.doubleSided=zi(e.doubleSided,!0),this.map=e.map||null,this.clearcoat=qe(e.clearcoat,0),this.clearcoatRoughness=qe(e.clearcoatRoughness,0),this.sheen=qe(e.sheen,0),this.sheenColor=new it(e.sheenColor!==void 0?e.sheenColor:0),this.sheenRoughness=qe(e.sheenRoughness,0),this.transmission=qe(e.transmission,0),this.thickness=qe(e.thickness,0),this.attenuationColor=new it(e.attenuationColor!==void 0?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(){}},zt=class extends Je{},Dr=class extends Je{},Pr=class extends Je{},Nr=class extends Je{},kr=class extends Je{},ot=class nl{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 ge,this.rotation=new _n,this.quaternion=new Ln,this.scale=new ge(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 nl&&(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=>{Fs(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 ge(t,r,i);this.target instanceof ge?this.target.copy(n):this.target?.position instanceof ge&&this.target.position.copy(n),this.updateMatrixWorld(!0);let s=new Ot;s.lookAt(this.position,n,new ge(0,1,0));let l=s.elements,o=l[0],a=l[4],u=l[8],h=l[1],c=l[5],f=l[9],p=l[2],m=l[6],g=l[10],x=o+c+g;if(x>0){let b=.5/Math.sqrt(x+1);this.quaternion.set((m-f)*b,(u-p)*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 ge(1,0,0),t)}translateY(t){return this.translateOnAxis(new ge(0,1,0),t)}translateZ(t){return this.translateOnAxis(new ge(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}clone(t=!0){let r=this instanceof Ut?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof mt?new mt(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}},Or=class extends ot{},mt=class extends ot{constructor(e,t){super(),this.isMesh=!0;let r=Array.isArray(t)?t[0]:t;this.geometry=e instanceof Fe?e:e?(Ht("unsupported geometry","BoxGeometry"),new In(.5,.5,.5)):new Fe,this.material=r instanceof Je?r:r?(Ht("unsupported material","MeshStandardMaterial"),new zt({color:13421772})):new zt}};function Fs(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=Me().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var Pn=1e4,Nn=class extends mt{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>Pn)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${Pn})`);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(){}},Gt=class extends ot{constructor(e=16777215,t=1){super(),this.color=new it(e),this.intensity=Number(t),this.type="directional"}},kn=class extends Gt{constructor(e,t){super(e,t),this.type="ambient"}},Ur=class extends Gt{constructor(e,t){super(e,t),this.target=new ot,this.type="directional"}},On=class extends Gt{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},Un=class extends ot{},Fr=class extends Un{constructor(e=45,t=1,r=.1,i=1e3){super(),this.target=new ge(0,0,0),this.fov=Number(e),this.aspect=Number(t),this.near=Number(r),this.far=Number(i)}},Fn=class extends ot{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return lt.validate(this),on(this)}toGLB(){return lt.validate(this),vn(this)}toUSDZ(){return lt.validate(this),Tn(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof mt){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},Gi=on,Hi=vn,Vs=Tn,lt=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(Fs(o),o instanceof mt||o.geometry?.attributes?.position?.count){if(i++,i>1e3&&s("MESHES",1e3,i),o instanceof Nn){let u=l("instance",o.count);(u<0||u>Pn)&&s("INSTANCES",Pn,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 c=a.index.array;if(c&&u>0){let f=Math.min(h,c.length);for(let p=0;p<f;p++){let m=c[p];if(!Number.isFinite(m)||m<0||m>=u)throw new Error(`SecurityError: Index buffer value (${String(m)}) out of vertex bounds [0, ${u}).`)}}}}if(o.material){let u=o.material;u.map&&n.add(u.map),u.normalMap&&n.add(u.normalMap),u.roughnessMap&&n.add(u.roughnessMap)}}}),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,c=Number(u?.height??a.height??0)||0;(!Number.isFinite(h)||!Number.isFinite(c)||h>2048||c>2048)&&s("TEXTURE_DIMENSION",2048,Math.max(h,c))}}},Vr=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 it(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){lt.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=Gi(e),s=Hi(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 Ls(){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 Br=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=Ls(),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=Ls();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function wc(){}var En=new Proxy(wc,{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:En},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>En,construct:()=>En}),Is=(()=>{try{if(typeof document>"u")return null;let e=document.currentScript;return e?.src?e.src:e?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([e.textContent],{type:"text/javascript"})):null}catch{return null}})();function ti(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function cn(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,ti());return!(i.protocol!=="https:"&&i.protocol!=="http:"&&i.protocol!=="blob:"||t?.requireSameOrigin&&i.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&i.origin!==location.origin)}catch{return!1}}var Cs,Sn;function Bs(e){if(!cn(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(Sn===void 0||Cs!==t){Cs=t;try{Sn=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!cn(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{Sn=null}}return Sn?Sn.createScriptURL(e):e}function Sc(e){Me().sandboxEngineSrc=e}function Xi(){let e=Me().sandboxEngineSrc;if(e)return e;if(Is)return Is;try{if(typeof document>"u")return null;let t=ti(),r=Array.from(document.querySelectorAll("script[src]"));for(let i of r){let n=i.src;if(!n)continue;let s=new URL(n,t).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(s)&&cn(n,{requireSameOrigin:!0}))return n}}catch{}return null}function $i(e,t){if(!cn(e))throw new Error(`SecurityError: Refusing to load ${t} from disallowed URL "${e}". Only http:, https:, and blob: URLs are permitted.`);return new URL(e,ti()).href}function Ec(){let e=Xi();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 $i(e,"sandbox engine")}function Rc(e){Me().sandboxIframeSrc=e}function zs(){let e=Me().sandboxIframeSrc;if(e)return e;let t=Xi();if(!t||!cn(t))return null;let r=new URL(t,ti());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function _c(){let e=zs();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 $i(e,"sandbox iframe")}function Lc(e){Me().allowClientScripts=e}function Gs(){return!!Me().allowClientScripts}function Ic(e){return $i(e,"procedural scene script")}var Cc=["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 Dc(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(d){a({type:"ERROR",nonce:i,message:String(d)})}let h=typeof r.importScripts=="function"?r.importScripts.bind(r):null,c=s,f=null;try{let d=n;if(typeof r.trustedTypes<"u"&&r.trustedTypes&&typeof r.trustedTypes.createPolicy=="function")try{let y={createScriptURL:function(T){if(T!==n&&(!s||T!==s))throw new TypeError("Disallowed worker importScripts URL");return T}};l&&(y.createScript=function(T){return String(T)});let M=r.trustedTypes.createPolicy("three-live#worker-boot",y);d=M.createScriptURL(n),s&&(c=M.createScriptURL(s)),l&&typeof M.createScript=="function"&&(f=M.createScript.bind(M))}catch{}h(d)}catch(d){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: '+(d&&d.message||d));return}let p=r.THREE;if(!p||typeof p.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 d=r.__THREE_LIVE_REGISTRY__;for(let y=0;y<t.length;y++)if(typeof t[y]=="function")try{t[y](p,d)}catch{}}function m(d,y,M){let T=r;for(;T&&T!==Object.prototype;){if(!M&&T!==r)try{delete T[d]}catch{}if(!M||T===r||Object.prototype.hasOwnProperty.call(T,d))try{Object.defineProperty(T,d,M?{value:y,writable:!1,configurable:!1}:{value:y,writable:!1,configurable:!1,enumerable:!1})}catch{}try{T=Object.getPrototypeOf(T)}catch{break}}}for(let d=0;d<o.length;d++)m(o[d],void 0);m("performance",Object.freeze({now:function(){return Date.now()}}));let g=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],x=!1;function b(d,y){if(d.type==="3D_MODEL_READY"){if(x)return;x=!0}d.nonce=i,y&&y.length?a(d,y):a(d)}m("postMessage",function(d,y){if(!d||g.indexOf(d.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");b(d,y)},!0);let v=!1;r.onmessage=function(d){let y=d&&d.data;if(!(!y||y.nonce!==i)&&!(y.type!=="EXECUTE"&&y.type!=="EXECUTE_URL")&&!v){v=!0;try{let M=new p.Scene,T=new p.PerspectiveCamera(60,1,.1,1e3),V=new p.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 X=c||s,P=h;if(h=null,c=null,r.THREE=p,r.scene=M,r.camera=T,r.renderer=V,P(X),typeof r.__THREE_LIVE_SCENE__=="function"){let R=r.__THREE_LIVE_SCENE__(p,M,T,V);R&&typeof R.toGLB=="function"&&(M=R)}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 X=f?(0,eval)(f(`(function (THREE, scene, camera, renderer) {
392
+ `,surfaceConnections:y,surfaceInputsUsda:b,usesTime:i.usesTime}}function Ar(e,t,r,i){let n=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,n))}function Hp(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function Jc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Wp(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function Qd(e){let t=Jc(e);if(!t)return null;let r=t.target;return{target:Hp(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:Ar(t.radius,.01,50,.5),speed:Ar(t.speed,-20,20,.5),height:Ar(t.height,-10,10,0),phase:Ar(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var Xp=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],qp=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],wg=new Set(Xp),Sg=new Set(qp);function Qc(e,t){let r=Wp(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 Zc(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:Jc(e);if(!t||t.enabled===!1)return null;let r=Ar(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:Ar(t.threshold,0,4,.8),radius:Ar(t.radius,0,2,.5)}:null}function Ms(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:Jc(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:Qc(t.color,"#38bdf8"),thickness:Ar(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var tn=class Dh{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 Dh(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 Fh{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 Fh(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}},ks=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}},si=class Bh{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 Bh(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},no=class zh{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 zh(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}},_r=class Vh{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 Vh;return t.copy(this),t}compose(t,r,i){return or(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 at(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 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}},Rs=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 Bt(this.elements,e.elements),this}},ln=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,As=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,Zd={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},Bn=class Uh{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 Zd)this.setHex(Zd[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=>ln(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=ln(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(ln(s(t+1/3)),ln(s(t)),ln(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(ln((r>>16&255)/255),ln((r>>8&255)/255),ln((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(ln(this.r),ln(this.g),ln(this.b))}convertLinearToSRGB(){return this.setRGB(As(this.r),As(this.g),As(this.b))}getHex(){let t=r=>Math.round(As(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 Uh(this.r,this.g,this.b)}},el=1234567,cf={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&&(el=Number.isFinite(e)?e|0:0);let t=el=el+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}},Vt=class Oh{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 Oh(new t(this.array),this.itemSize)}},Ls=class extends Vt{constructor(e,t){super(e instanceof Float32Array||Array.isArray(e)?e:new Float32Array(e),t)}},Ps=class extends Vt{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Is=class extends Vt{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},Nt=class jh{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 Vt)this.index=t;else if(Array.isArray(t)){let r=0;for(let i of t)i>r&&(r=i);this.index=new Vt(new(r>65535?Uint32Array:Uint16Array)(t),1)}else t&&t.buffer&&(this.index=new Vt(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 Vt(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 Vt(a,3)),this}setFromBuffers(t,r,i,n){this.setAttribute("position",new Vt(t,3)),this.setAttribute("normal",new Vt(r,3)),this.setAttribute("uv",new Vt(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 Vt(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 jh;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 Nt{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)}},Cs=class extends Nt{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)}},Ns=class extends Nt{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)}},ci=class extends Nt{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)}},Ds=class extends ci{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)}},Us=class extends Nt{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 lf(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 Bs=class extends Nt{constructor(e=1,t=.4,r=64,i=8,n=2,a=3){super(),r=Math.floor(r),i=Math.floor(i),lf(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)})}},ar=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)}},Fs=class extends ar{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)}},Vs=class extends ar{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)}},Os=class extends ar{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)}},zs=class extends ar{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))}},li=class extends Nt{constructor(e=[new tn(0,-.5),new tn(.5,0),new tn(0,.5)],t=12,r=0,i=Math.PI*2){super();let n=Array.isArray(e)&&e.length>=2?e:[new tn(.2,0),new tn(.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)}},$s=class extends Nt{constructor(e,t=64,r=1,i=8,n=!1){super(),lf(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)})}},Ts="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ro=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new tn(1,1),this.offset=new tn(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},Gs=class extends ro{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,Yo(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,Yo(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/_:ln(w/_),P?S/_:ln(S/_),P?E/_:ln(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(Ts[F>>18&63]+Ts[F>>12&63]+($+1<x.length?Ts[F>>6&63]:"=")+($+2<x.length?Ts[F&63]:"="))}this.source=R.join("")}},js=class{load(e,t){let r=new ro(e);return t?.(r),r}};function Ft(e,t){return e!==void 0?Number(e):t}function tl(e,t){return e!==void 0?!!e:t}var vn=class{constructor(e={}){this.name=e.name||"",this.color=new Bn(e.color??16777215),this._em=e.emissive!==void 0,this.emissive=new Bn(e.emissive??0),this.emissiveIntensity=Ft(e.emissiveIntensity,1),this.roughness=Ft(e.roughness,e.roughnessMap?1:.5),this.metalness=Ft(e.metalness,e.metalnessMap?1:0),this.opacity=Ft(e.opacity,1),this.transparent=tl(e.transparent,!1),this.wireframe=tl(e.wireframe,!1),this.side=Ft(e.side,2),this.doubleSided=tl(e.doubleSided,!0),this.map=e.map||null,this.normalMap=e.normalMap||null;let t=e.normalScale;this.normalScale=typeof t=="number"?new tn(t,t):new tn(Ft(t?.x,1),Ft(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=Ft(e.aoMapIntensity,1),this.bumpMap=e.bumpMap||null,this.bumpScale=Ft(e.bumpScale,1),this.clearcoat=Ft(e.clearcoat,0),this.clearcoatRoughness=Ft(e.clearcoatRoughness,0),this.sheen=Ft(e.sheen,0),this.sheenColor=new Bn(e.sheenColor??0),this.sheenRoughness=Ft(e.sheenRoughness,0),this.transmission=Ft(e.transmission,0),this.thickness=Ft(e.thickness,0),this.attenuationColor=new Bn(e.attenuationColor??16777215),this.attenuationDistance=Ft(e.attenuationDistance,1/0),this.ior=Ft(e.ior,1.5),this.dispersion=Ft(e.dispersion,0),this.iridescence=Ft(e.iridescence,0),this.iridescenceIOR=Ft(e.iridescenceIOR,1.3)}dispose(){}},Fr=class extends vn{},Hs=class extends vn{},Ws=class extends vn{},Xs=class extends vn{},qs=class extends vn{},Fn=class Gh{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 si,this.quaternion=new no,this.scale=new Ze(1,1,1),this.matrix=new _r,this.matrixWorld=new _r,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 Gh&&(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=>{uf(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 _r;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 _r().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 no){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 kr?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof qn?new qn(this.geometry,this.material):new this.constructor;if(this instanceof cr){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 vi&&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}},Ys=class extends Fn{},qn=class extends Fn{constructor(e,t){super(),this.isMesh=!0;let r=Array.isArray(t)?t[0]:t;this.geometry=e instanceof Nt?e:e?(Er("unsupported geometry","BoxGeometry"),new ai(.5,.5,.5)):new Nt,this.material=r instanceof vn?r:r?(Er("unsupported material","MeshStandardMaterial"),new Fr({color:13421772})):new Fr}};function uf(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=He().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var ui=1e4,di=class extends qn{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>ui)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${ui})`);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 Vt(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 Vt(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(){}},fi=class Hh{constructor(){this.mapSize=new tn(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 Hh().copy(this)}},cr=class extends Fn{constructor(e=16777215,t=1){super(),this.isLight=!0,this.shadow=new fi,this.color=new Bn(e),this.intensity=Number(t),this.type="directional"}},mi=class extends cr{constructor(e,t){super(e,t),this.type="ambient"}},Ks=class extends cr{constructor(e,t){super(e,t),this.target=new Fn,this.type="directional"}},hi=class extends cr{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},pi=class extends Fn{},Js=class extends pi{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)}},bi=class extends Fn{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return Xn.validate(this),Qr(this)}toGLB(){return Xn.validate(this),qo(this)}toUSDZ(){return Xn.validate(this),Ko(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof qn){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},nl=Qr,rl=qo,df=Ko;He().makePngDeflater=zc;var Xn=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(uf(o),o instanceof qn||o.geometry?.attributes?.position?.count){if(i++,i>1e3&&a("MESHES",1e3,i),o instanceof di){let c=s("instance",o.count);(c<0||c>ui)&&a("INSTANCES",ui,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))}}},Qs=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 Bn(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){Xn.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=nl(e),a=rl(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 ef(){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 Zs=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=ef(),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=ef();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Yp(){}var oi=new Proxy(Yp,{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:oi},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>oi,construct:()=>oi}),tf=(()=>{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 pa(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function oo(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,pa());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 nf,ri;function ff(e){if(!oo(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(ri===void 0||nf!==t){nf=t;try{ri=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!oo(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{ri=null}}return ri?ri.createScriptURL(e):e}function Kp(e){He().sandboxEngineSrc=e}function ol(){let e=He().sandboxEngineSrc;if(e)return e;if(tf)return tf;try{if(typeof document>"u")return null;let t=pa(),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)&&oo(n,{requireSameOrigin:!0}))return n}}catch{}return null}function il(e,t){if(!oo(e))throw new Error(`SecurityError: Disallowed ${t} URL "${e}" (http:, https:, or blob: required).`);return new URL(e,pa()).href}function Jp(){let e=ol();if(!e)throw new Error("SecurityError: Could not locate Three-Live bundle URL for worker sandbox; set ThreeLiveElement.sandboxEngineSrc explicitly.");return il(e,"sandbox engine")}function Qp(e){He().sandboxIframeSrc=e}function mf(){let e=He().sandboxIframeSrc;if(e)return e;let t=ol();if(!t||!oo(t))return null;let r=new URL(t,pa());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function Zp(){let e=mf();if(!e)throw new Error("SecurityError: Could not locate three-live-sandbox.html; set ThreeLiveElement.sandboxIframeSrc explicitly.");return il(e,"sandbox iframe")}function e0(e){He().allowClientScripts=e}function hf(){return!!He().allowClientScripts}function t0(e){return il(e,"procedural scene script")}var n0="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 r0(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) {
343
393
  return (function () {
344
- `+y.script+`
394
+ `+C.script+`
345
395
  ;
346
396
  return typeof scene === "object" && scene ? scene : undefined;
347
397
  })();
348
398
  })`)):new Function("THREE","scene","camera","renderer",`return (function () {
349
- `+y.script+`
399
+ `+C.script+`
350
400
  ;
351
401
  return typeof scene === "object" && scene ? scene : undefined;
352
- })();`);f=null;let P=X(p,M,T,V);P&&typeof P.toGLB=="function"&&(M=P)}if(!x){p.SceneQuotaValidator&&p.SceneQuotaValidator.validate(M);let X=M.toGLB(),P=X instanceof ArrayBuffer?X:X.buffer.slice(X.byteOffset,X.byteOffset+X.byteLength);b({type:"3D_MODEL_READY",glbBuffer:P},[P])}a({type:"DONE",nonce:i})}catch(M){u(M&&M.message||M)}}},a({type:"READY",nonce:i})}function Wi(e,t,r){let i=r?.allowedScriptUrl??null,n=r?.allowClientScripts??i===null,s={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:n,revoked:Cc},l=(Me().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${Dc.toString()})(${JSON.stringify(s)},[${l}]);`}function Hs(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 kt=0;function Xs(){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 Pc(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var Nc=1024,kc=256;function Ds(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 ji(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,Nc)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let n of i)if(!Ds(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>kc||o==="__proto__"||o==="constructor"||o==="prototype")return null;let a=l[o];if(!Ds(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 Oc(e){let t=Pc(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function $s(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 Uc(e,t,r,i){let n=Xs(),s=Wi(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,kt++;let o=!1,a=!1,u={modelDispatched:!1},h,c=()=>{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},"*"))},f=()=>{},p=g=>{if(o||!l.contentWindow||g.source!==l.contentWindow)return;let x=g.data;if(x&&typeof x=="object"&&x.type==="IFRAME_READY"){c();return}let b=ji(x,n);b&&$s(b,i,f,u)};f=()=>{o||(o=!0,h!==void 0&&clearTimeout(h),kt=Math.max(0,kt-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",p),typeof l.remove=="function"?l.remove():l.parentNode&&l.parentNode.removeChild(l))},h=setTimeout(()=>{o||(f(),Hs(i))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",p),l.onload=()=>{c()},l.onerror=()=>{f(),i.onError?.(new Error(`Sandbox iframe failed to load "${r}". Verify that three-live-sandbox.html is served at that URL.`))};let m=document.body||document.documentElement;if(!m||typeof m.appendChild!="function"){f();let g=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw i.onError?.(g),g}return m.appendChild(l),{terminate:f}}function Ps(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(kt>=32)return i(`SecurityError: ${kt} 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=Ec()}catch(f){let p=f instanceof Error?f.message:String(f);return i(p,"Security Error: sandbox engine URL is not configured.")}if(t==="iframe"){let f;try{f=_c()}catch(p){let m=p instanceof Error?p.message:String(p);return i(m,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Uc(e,n,f,r))}catch(p){return Promise.reject(p)}}let s=Xs(),l=Wi(n,s,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),o;try{let f=new Blob([l],{type:"application/javascript"}),p=URL.createObjectURL(f);try{let m=Bs(p);o=new Worker(m)}finally{URL.revokeObjectURL(p)}}catch(f){let p=f instanceof Error?f.message:String(f);return i(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${p}`,"Security Error: Failed to start Worker sandbox.")}kt++;let a=!1,u={modelDispatched:!1},h,c=()=>{a||(a=!0,h!==void 0&&clearTimeout(h),kt=Math.max(0,kt-1),o.terminate())};return h=setTimeout(()=>{a||(c(),Hs(r))},3e3),o.onmessage=f=>{let p=ji(f.data,s);p&&$s(p,r,c,u)},o.onerror=f=>{c(),r.onError?.(new Error(`Worker execution error: ${f.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:c})}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 ks=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},ln={execute(e,t,r,i){let n=ks(r),s=Ns(t,n);if(s)return s;try{Oc(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??Gs()?Ps({kind:"script",script:e},t,r,n):n(Zn,Qn)},executeUrl(e,t,r){let i=ks(r),n=Ns(t,i);if(n)return n;let s;try{s=Ic(e)}catch(l){let o=l instanceof Error?l.message:String(l);return i(o,"Security Error: disallowed scene script URL.")}return Ps({kind:"url",scriptUrl:s},t,r,i)}},zr=new Set;function Ht(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;zr.has(r)||(zr.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function Ws(){return Array.from(zr)}function js(){zr.clear()}var Vn=class extends zt{constructor(e={}){Ht("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}},Ks=Vn,Tt=class extends Fe{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=[],c=new ge,f=new ge,p=new ge,m=(b,v)=>v.set(e[b*3]||0,e[b*3+1]||0,e[b*3+2]||0),g=(b,v)=>{let d=b.clone().normalize();o.push(d.x*n,d.y*n,d.z*n),a.push(v.x,v.y,v.z),u.push(Math.atan2(d.z,-d.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,d.y)))/Math.PI)},x=(b,v,d)=>{let y=o.length/3,M=s===0?new ge().subVectors(d,v).cross(new ge().subVectors(b,v)).normalize():null;g(b,M||b.clone().normalize()),g(v,M||v.clone().normalize()),g(d,M||d.clone().normalize()),h.push(y,y+1,y+2)};for(let b=0;b<t.length;b+=3){m(t[b],c),m(t[b+1],f),m(t[b+2],p);let v=[];for(let d=0;d<=l;d++){v[d]=[];let y=c.clone().lerp(p,d/l),M=f.clone().lerp(p,d/l),T=l-d;for(let V=0;V<=T;V++)v[d][V]=T===0?y.clone():y.clone().lerp(M,V/T)}for(let d=0;d<l;d++)for(let y=0;y<2*(l-d)-1;y++){let M=y>>1;(y&1)===0?x(v[d][M+1],v[d+1][M],v[d][M]):x(v[d][M+1],v[d+1][M+1],v[d+1][M])}}this.setFromBuffers(o,a,u,h)}},Fc=Tt,Gr=class extends Tt{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)}},dr=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],qs=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],Hr=class extends Tt{constructor(e=1,t=0){super(dr,qs,e,t)}},ke=(1+Math.sqrt(5))/2,Xr=class extends Tt{constructor(e=1,t=0){super([-1,ke,0,1,ke,0,-1,-ke,0,1,-ke,0,0,-1,ke,0,1,ke,0,-1,-ke,0,1,-ke,ke,0,-1,ke,0,1,-ke,0,-1,-ke,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)}},tt=1/ke,$r=class extends Tt{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,-tt,-ke,0,-tt,ke,0,tt,-ke,0,tt,ke,-tt,-ke,0,-tt,ke,0,tt,-ke,0,tt,ke,0,-ke,0,-tt,ke,0,-tt,-ke,0,tt,ke,0,tt],[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)}},Wr=class extends Dn{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 nt(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))))}},Bn=class extends Fe{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)),c=Math.max(3,Math.min(256,Math.floor(Number(r)||32))),f=Math.max(1,Math.min(64,Math.floor(Number(i)||1))),p=Number.isFinite(Number(n))?Number(n):0,m=Number.isFinite(Number(s))?Number(s):Math.PI*2,g=[],x=[],b=[],v=[];for(let d=0;d<=f;d++){let y=h+d/f*(u-h);for(let M=0;M<=c;M++){let T=p+M/c*m,V=Math.cos(T),X=Math.sin(T);if(g.push(y*V,y*X,0),x.push(0,0,1),b.push(y/u*V*.5+.5,y/u*X*.5+.5),d<f&&M<c){let P=d*(c+1)+M,R=P+c+1;y>1e-6&&v.push(P,R,P+1),v.push(R,R+1,P+1)}}}this.setFromBuffers(g,x,b,v)}},jr=class extends Bn{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},zn=class extends Je{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)}},un=class extends Je{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)}},Kr=class extends un{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function Ys(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=f=>`${Math.round((i[f*3]||0)*1e4)},${Math.round((i[f*3+1]||0)*1e4)},${Math.round((i[f*3+2]||0)*1e4)}`,o=t===void 0,a=o?1:Math.cos(t*Math.PI/180),u={},h=[],c=(f,p)=>h.push(i[f*3]||0,i[f*3+1]||0,i[f*3+2]||0,i[p*3]||0,i[p*3+1]||0,i[p*3+2]||0);for(let f=0;f<s;f++){let p=n?n[f*3]:f*3,m=n?n[f*3+1]:f*3+1,g=n?n[f*3+2]:f*3+2,x=i[p*3]||0,b=i[p*3+1]||0,v=i[p*3+2]||0,d=(i[m*3]||0)-x,y=(i[m*3+1]||0)-b,M=(i[m*3+2]||0)-v,T=(i[g*3]||0)-x,V=(i[g*3+1]||0)-b,X=(i[g*3+2]||0)-v,P=y*X-M*V,R=M*T-d*X,C=d*V-y*T,B=Math.hypot(P,R,C);if(!o&&B<1e-8)continue;B>0&&(P/=B,R/=B,C/=B);let N=[p,m,g];for(let w=0;w<3;w++){let ie=N[w],ae=N[(w+1)%3],k=l(ie),J=l(ae);if(k===J)continue;let z=k<J?`${k}|${J}`:`${J}|${k}`,Y=u[z];Y?Y.m||(Y.m=1,Y.nx*P+Y.ny*R+Y.nz*C<=a&&c(ie,ae)):(u[z]={va:ie,vb:ae,nx:P,ny:R,nz:C,m:o?1:0},o&&c(ie,ae))}}if(!o){let f=Object.keys(u);for(let p=0;p<f.length;p++){let m=u[f[p]];m&&!m.m&&c(m.va,m.vb)}}return new Float32Array(h)}var qr=class extends Fe{constructor(e){super(),this.setAttribute("position",new He(Ys(e),3)),this.__isSegmentPairs=!0}},Yr=class extends Fe{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new He(Ys(e,r),3)),this.__isSegmentPairs=!0}};function Vc(e,t,r=1){let i=new Fe;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,c=h&&h.max.distanceTo(h.min)||1,f=Math.max(.0015,Math.min(.025,c*.003))*(.5+.5*Math.max(.5,Math.min(6,Number(r)||1))),p=[],m=[],g=[],x=[];for(let b=0;b<u;b++){let v=o==="segments"?b*2:b,d=o==="segments"?b*2+1:(b+1)%a,y=l?l[v]:v,M=l?l[d]:d,T=s[y*3]||0,V=s[y*3+1]||0,X=s[y*3+2]||0,P=(s[M*3]||0)-T,R=(s[M*3+1]||0)-V,C=(s[M*3+2]||0)-X,B=Math.hypot(P,R,C);if(B<1e-6)continue;let N=P/B,w=R/B,ie=C/B,ae=(Math.abs(w)<.9?Math.hypot(ie,N):Math.hypot(ie,w))||1,k=Math.abs(w)<.9?ie/ae:0,J=Math.abs(w)<.9?0:-ie/ae,z=Math.abs(w)<.9?-N/ae:w/ae,Y=w*z-ie*J,le=ie*k-N*z,ce=N*J-w*k,$=p.length/3,U=[[k,J,z],[Y,le,ce],[-k,-J,-z],[-Y,-le,-ce]];for(let _=0;_<2;_++){let H=T+_*P,D=V+_*R,F=X+_*C;for(let E=0;E<4;E++){let G=U[E];p.push(H+G[0]*f,D+G[1]*f,F+G[2]*f),m.push(G[0],G[1],G[2]),g.push(E/4,_)}}for(let _=0;_<4;_++){let H=(_+1)%4;x.push($+_,$+H,$+4+H,$+_,$+4+H,$+4+_)}}return p.length>0&&i.setFromBuffers(p,m,g,x),i}function Bc(e,t=.05){let r=new Fe;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=[],c=[];for(let f=0;f<l;f++){let p=s<=5e3?f:Math.floor(f*s/l),m=n[p*3]||0,g=n[p*3+1]||0,x=n[p*3+2]||0,b=f*6;for(let v=0;v<6;v++){let d=dr[v*3],y=dr[v*3+1],M=dr[v*3+2];a.push(m+d*o,g+y*o,x+M*o),u.push(d,y,M),h.push(.5,.5)}for(let v=0;v<24;v++)c.push(b+qs[v])}return r.setFromBuffers(a,u,h,c),r}var Ut=class extends mt{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},n=t instanceof Je?t:r==="points"?new zn(i):new un(i),s=e instanceof Fe?e:new Fe;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?Bc(this._sourceGeo,this.material?.size??.05):Vc(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},Zr=class extends Ut{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},Qr=class extends Ut{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},Jr=class extends Ut{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},ei=class extends On{constructor(e,t,r=0,i=Math.PI/3,n=0,s=2){super(e,t,r,s),this.target=new ot,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}},Gn=class extends kn{constructor(e,t,r){Ht("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new it(t??4473924)}},Zs=Gn,Qs={Vector2:nt,Vector3:ge,Vector4:pr,Euler:_n,Quaternion:Ln,Matrix4:Ot,Matrix3:br,Color:it,MathUtils:Os,BufferAttribute:He,Float32BufferAttribute:yr,Uint16BufferAttribute:gr,Uint32BufferAttribute:xr,BufferGeometry:Fe,BoxGeometry:In,PlaneGeometry:vr,SphereGeometry:Mr,CylinderGeometry:Cn,ConeGeometry:Tr,TorusGeometry:Ar,TorusKnotGeometry:wr,Curve:Mt,Curve3:Mt,LineCurve3:Sr,QuadraticBezierCurve3:Er,CubicBezierCurve3:Rr,CatmullRomCurve3:_r,LatheGeometry:Dn,TubeGeometry:Lr,PolyhedronGeometry:Tt,IcosahedronGeometry:Xr,OctahedronGeometry:Hr,DodecahedronGeometry:$r,TetrahedronGeometry:Gr,CapsuleGeometry:Wr,RingGeometry:Bn,CircleGeometry:jr,WireframeGeometry:qr,EdgesGeometry:Yr,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:an,DataTexture:Ir,TextureLoader:Cr,Material:Je,MeshStandardMaterial:zt,MeshBasicMaterial:Dr,MeshLambertMaterial:Pr,MeshPhongMaterial:Nr,MeshPhysicalMaterial:kr,PointsMaterial:zn,LineBasicMaterial:un,LineDashedMaterial:Kr,ShaderMaterial:Vn,RawShaderMaterial:Ks,Object3D:ot,Group:Or,Mesh:mt,InstancedMesh:Nn,Line:Ut,LineLoop:Zr,LineSegments:Qr,Points:Jr,Light:Gt,AmbientLight:kn,DirectionalLight:Ur,PointLight:On,SpotLight:ei,HemisphereLight:Gn,RectAreaLight:Zs,Camera:Un,PerspectiveCamera:Fr,Scene:Fn,WebGLRenderer:Vr,Clock:Br,SceneQuotaValidator:lt,exportSceneToCanvas3D:Gi,exportSceneToGLB:Hi,exportSceneToUSDZ:Vs,generateUSDZ:wn,glbToUSDZ:An,sceneToCanvas3D:on,sceneToGLB:vn,sceneToUSDZ:Tn,authorScriptRunner:ln,getAuthorWarnings:Ws,clearAuthorWarnings:js};Object.freeze(lt),Object.freeze(lt.prototype),Object.freeze(Fn.prototype),Object.freeze(Qs);var Xt=new Proxy(Qs,{get:(e,t)=>{if(t in e)return e[t];let r=Me().authorNamespace;return r&&typeof t=="string"&&t in r?r[t]:(typeof t=="string"&&t!=="then"&&t!=="toJSON"&&!t.startsWith("__")&&Ht(`THREE.${t}`,"no-op proxy"),En)},has:(e,t)=>{if(t in e)return!0;let r=Me().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")}}),hr=Me();if(hr.threeNamespace=Xt,hr.workerExtensionInstallers)for(let e of hr.workerExtensionInstallers)e(Xt,hr);var Rn={name:"three_author",THREE:Xt},zc=Rn,vt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof vt.THREE>"u"&&(vt.THREE=Xt),typeof vt.requestAnimationFrame!="function"&&(vt.requestAnimationFrame=e=>(typeof e=="function"&&typeof vt.__three_live_raf_cb__!="function"&&(vt.__three_live_raf_cb__=e),vt.__three_live_in_step__||Ht("requestAnimationFrame","single-frame static evaluation"),0)),typeof vt.cancelAnimationFrame!="function"&&(vt.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=Xt,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=Rn,e.ThreeLivePlugins.three_author=Rn,e.ThreeLivePlugins["three-author"]=Rn}function mn(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var Ki=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),Gc=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 Xe=class Ze extends Gc{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 Me().arProvider}static set arProvider(t){Me().arProvider=t}static get scriptRunner(){return Me().scriptRunner}static set scriptRunner(t){Me().scriptRunner=t}static get sandboxEngineSrc(){return Me().sandboxEngineSrc??null}static set sandboxEngineSrc(t){Me().sandboxEngineSrc=t}static get sandboxIframeSrc(){return Me().sandboxIframeSrc??null}static set sandboxIframeSrc(t){Me().sandboxIframeSrc=t}static get allowClientScripts(){return!!Me().allowClientScripts}static set allowClientScripts(t){Me().allowClientScripts=t}static registerScriptRunner(t){Ze.scriptRunner=t}static registerDecoder(t,r){je.registerDecoder(t,r)}static getDecoder(t){return je.getDecoder(t)}static registerAR(t){typeof t=="function"?Ze.arProvider={activateAR:t}:Ze.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof Ze&&r.updateARButtonVisibility()})}static isARSupported(){return!!Ze.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 je.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of je.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(Bt(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 je.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")||(Me().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||Ze.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 Ze.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 Bt(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 mn(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return mn(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():Ki(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:Ki(n,s,l),normal:Ki(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=gt(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>.")),Ze.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 Ze.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=typeof navigator<"u"&&navigator.userAgent||"",l=/Macintosh/i.test(s)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),o=/Android|iPhone|iPad|iPod/i.test(s),a=n.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(l&&!o&&typeof document<"u"&&this.currentModel&&Ze.arProvider.createUSDZBlob)try{let u=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:Ze.arProvider.createUSDZBlob(this.currentModel),h=URL.createObjectURL(u),c=document.createElement("a");c.href=h,c.download="three_live_model.usdz",document.body.appendChild(c),c.click(),document.body.removeChild(c),setTimeout(()=>URL.revokeObjectURL(h),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(a,6e3)}else this.showToast(a,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 je(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 je.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))}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.type="button",t.className="three-live-ar-button";for(let[n,s]of[["aria-label","View in Augmented Reality"],["part","default-ar-button"]])t.setAttribute(n,s);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");i.textContent="View in AR",t.appendChild(i),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")&&!!Ze.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.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 je.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=Ze.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,hs,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(!Ze.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Zn);return this.showToast(Qn),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};Xe.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"],Xe.registerPlugin=je.registerPlugin,Xe.getRegisteredPlugins=je.getRegisteredPlugins;var ft=Xe;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",ft);function Js(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function ni(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],c=r[3],f=n*a+s*u+l*h+o*c;if(f<0&&(a=-a,u=-u,h=-h,c=-c,f=-f),Math.abs(f)>=1)return e[0]=n,e[1]=s,e[2]=l,e[3]=o,e;let p=Math.acos(f),m=Math.sqrt(1-f*f);if(Math.abs(m)<.001)return e[0]=.5*(n+a),e[1]=.5*(s+u),e[2]=.5*(l+h),e[3]=.5*(o+c),e;let g=Math.sin((1-i)*p)/m,x=Math.sin(i*p)/m;return e[0]=n*g+a*x,e[1]=s*g+u*x,e[2]=l*g+h*x,e[3]=o*g+c*x,e}function ea(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 Ji(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],c=e.accessors?.[u.output];if(!h||!c)continue;let f=e.bufferViews?.[h.bufferView],p=e.bufferViews?.[c.bufferView];if(!f||!p)continue;let m=(f.byteOffset||0)+(h.byteOffset||0),g=(p.byteOffset||0)+(c.byteOffset||0),x=ut(e,t,h,1)??Js(t,m,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(c.count/Math.max(1,h.count))):3,v=a.target.path==="weights"?1:b,d=ut(e,t,c,v)??Js(t,g,c.count*v),y=u.interpolation==="STEP"?"STEP":"LINEAR";l.push({nodeIndex:a.target.node,path:a.target.path,times:x,values:d,interpolation:y})}l.length>0&&r.push({name:s,duration:o,channels:l})}return r}function fn(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 d=0;d<a;d++)r[d]=n[v+d];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 c=Math.max(0,h),f=Math.min(o-1,c+1);if(l==="STEP"||c===f){let v=c*a;for(let d=0;d<a;d++)r[d]=n[v+d];return}let p=i[c],m=i[f],g=(t-p)/Math.max(1e-5,m-p),x=c*a,b=f*a;if(s==="rotation"){let v=[n[x],n[x+1],n[x+2],n[x+3]],d=[n[b],n[b+1],n[b+2],n[b+3]];ni(r,v,d,g)}else for(let v=0;v<a;v++)r[v]=n[x+v]+g*(n[b+v]-n[x+v])}var Hn=new WeakMap;function eo(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(o=>o.name===t);if(!i)return;let n=Hn.get(e);n||(n=[],e.currentClip&&n.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),Hn.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 Zi(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=Hn.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 c=0;c<i;c++){let f=e.initialNodeTransforms[c];f?n.push({t:[f.t[0],f.t[1],f.t[2]],r:[f.r[0],f.r[1],f.r[2],f.r[3]],s:[f.s[0],f.s[1],f.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 c of r){let f=Math.max(0,Math.min(1,c.weight));if(!(f<=1e-4))for(let p of c.clip.channels){if(p.nodeIndex<0||p.nodeIndex>=i)continue;let m=n[p.nodeIndex];if(p.path==="translation")fn(p,c.time,s),ea(m.t,m.t,s,f);else if(p.path==="rotation")fn(p,c.time,l),ni(m.r,m.r,l,f);else if(p.path==="scale")fn(p,c.time,o),ea(m.s,m.s,o,f);else if(p.path==="weights"&&(fn(p,c.time,a),e.meshes)){for(let g of e.meshes)if(g.nodeIndex===p.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 d=0;d<v;d++)b[d]=b[d]*(1-f)+a[d]*f}}}}}let u=[];for(let c=0;c<i;c++){let f=Se(),{t:p,r:m,s:g}=n[c];yt(f,m,p,g),u.push(f)}let h=Vt(e.gltf,u);e.worldMatrices=h;for(let c of e.meshes)c.nodeIndex>=0&&c.nodeIndex<h.length&&(c.transform.set(h[c.nodeIndex]),ze(c.normalMatrix,c.transform))}var Qi=e=>{Hn.delete(e)},to={name:"keyframes",evaluateAnimation:Zi,crossFadeTo:eo,onParseGLB(e){!e.animations&&e.gltf?.animations&&(e.animations=Ji(e.gltf,e.bin))},onLoadModel:Qi,onClearScene:Qi,onDestroy:(e,t)=>Qi(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=Hn.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),Zi(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),Zi(e,e.animationTime))}},Xn=64;function ta(e,t,r){if(!(!e?.meshes||t<0||t>=Xn))for(let i of e.meshes)for(let n of i.primitives){let s=n.pluginData?.morph;s?.weights&&(s.weights[t]=r)}}var no={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 sl(e,t,r){let i=r?.allowedScriptUrl??null,n=r?.allowClientScripts??i===null,a={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:n,revoked:n0},s=(He().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${r0.toString()})(${JSON.stringify(a)},[${s}],(${zc.toString()}));`}function pf(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 Tr=0;function bf(){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 o0(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var i0=1024,s0=256;function rf(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 al(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,i0)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let n of i)if(!rf(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>s0||o==="__proto__"||o==="constructor"||o==="prototype")return null;let l=s[o];if(!rf(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 a0(e){let t=o0(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function yf(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 c0(e,t,r,i){let n=bf(),a=sl(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,Tr++;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=al(v,n);y&&yf(y,i,h,c)};h=()=>{o||(o=!0,f!==void 0&&clearTimeout(f),Tr=Math.max(0,Tr-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(),pf(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 of(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(Tr>=32)return i(`SecurityError: ${Tr} workers running, meeting SECURITY_3D_MAX_CONCURRENT_TASKS (32).`,"Security Error: too many concurrent sandboxed scripts.");let n;try{n=Jp()}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=Zp()}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(c0(e,n,h,r))}catch(p){return Promise.reject(p)}}let a=bf(),s=sl(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=ff(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.")}Tr++;let l=!1,c={modelDispatched:!1},f,m=()=>{l||(l=!0,f!==void 0&&clearTimeout(f),Tr=Math.max(0,Tr-1),o.terminate())};return f=setTimeout(()=>{l||(m(),pf(r))},3e3),o.onmessage=h=>{let p=al(h.data,a);p&&yf(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 sf(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 af=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},so={execute(e,t,r,i){let n=af(r),a=sf(t,n);if(a)return a;try{a0(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??hf()?of({kind:"script",script:e,texturePack:i?.texturePack},t,r,n):n(os,is)},executeUrl(e,t,r,i){let n=af(r),a=sf(t,n);if(a)return a;let s;try{s=t0(e)}catch(o){let l=o instanceof Error?o.message:String(o);return n(l,"Security Error: disallowed scene script URL.")}return of({kind:"url",scriptUrl:s,texturePack:i?.texturePack},t,r,n)}},ea=new Set;function Er(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;ea.has(r)||(ea.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function gf(){return Array.from(ea)}function xf(){ea.clear()}var yi=class extends Fr{constructor(e={}){Er("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}},vf=yi,lr=class extends Nt{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)}},l0=lr,ta=class extends lr{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)}},cl=e=>Array.from(e,t=>parseInt(t,36)),_s=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],wf=cl("024043035052125153134142"),na=class extends lr{constructor(e=1,t=0){super(_s,wf,e,t)}},Rt=(1+Math.sqrt(5))/2,ra=class extends lr{constructor(e=1,t=0){super([-1,Rt,0,1,Rt,0,-1,-Rt,0,1,-Rt,0,0,-1,Rt,0,1,Rt,0,-1,-Rt,0,1,-Rt,Rt,0,-1,Rt,0,1,-Rt,0,-1,-Rt,0,1],cl("0b505101707a0ab1595b4ba2a7671839434232636838949524b62a867981"),e,t)}},_n=1/Rt,oa=class extends lr{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,-_n,-Rt,0,-_n,Rt,0,_n,-Rt,0,_n,Rt,-_n,-Rt,0,-_n,Rt,0,_n,-Rt,0,_n,Rt,0,-Rt,0,-_n,Rt,0,-_n,-Rt,0,_n,Rt,0,_n],cl("3b737f3fd7jh7h676fh48h8aha680g8g282a0c101i0ig6a262d6df2gi2i323di19i9bib34ec4c0408b95b5jbj7j5eje4j4h1ce1e5159"),e,t)}},ia=class extends li{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 tn(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))))}},gi=class extends Nt{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)}},sa=class extends gi{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},xi=class extends vn{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)}},io=class extends vn{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)}},aa=class extends io{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function Sf(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 ca=class extends Nt{constructor(e){super(),this.setAttribute("position",new Vt(Sf(e),3)),this.__isSegmentPairs=!0}},la=class extends Nt{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new Vt(Sf(e,r),3)),this.__isSegmentPairs=!0}};function u0(e,t,r=1){let i=new Nt;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 d0(e,t=.05){let r=new Nt;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=_s[A*3],w=_s[A*3+1],S=_s[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+wf[A])}return r.setFromBuffers(l,c,f,m),r}var kr=class extends qn{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},n=t instanceof vn?t:r==="points"?new xi(i):new io(i),a=e instanceof Nt?e:new Nt;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?d0(this._sourceGeo,this.material?.size??.05):u0(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},ua=class extends kr{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},da=class extends kr{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},fa=class extends kr{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},ma=class extends hi{constructor(e,t,r=0,i=Math.PI/3,n=0,a=2){super(e,t,r,a),this.target=new Fn,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}},vi=class extends cr{constructor(e,t,r){super(e,r),this.type="hemisphere",this.groundColor=new Bn(t??4473924),this.position.set(0,1,0)}},ha=class extends mi{constructor(e,t){Er("RectAreaLight","AmbientLight"),super(e,t)}},Mf={Vector2:tn,Vector3:Ze,Vector4:ks,Euler:si,Quaternion:no,Matrix4:_r,Matrix3:Rs,Color:Bn,MathUtils:cf,BufferAttribute:Vt,Float32BufferAttribute:Ls,Uint16BufferAttribute:Ps,Uint32BufferAttribute:Is,BufferGeometry:Nt,BoxGeometry:ai,PlaneGeometry:Cs,SphereGeometry:Ns,CylinderGeometry:ci,ConeGeometry:Ds,TorusGeometry:Us,TorusKnotGeometry:Bs,Curve:ar,Curve3:ar,LineCurve3:Fs,QuadraticBezierCurve3:Vs,CubicBezierCurve3:Os,CatmullRomCurve3:zs,LatheGeometry:li,TubeGeometry:$s,PolyhedronGeometry:lr,IcosahedronGeometry:ra,OctahedronGeometry:na,DodecahedronGeometry:oa,TetrahedronGeometry:ta,CapsuleGeometry:ia,RingGeometry:gi,CircleGeometry:sa,WireframeGeometry:ca,EdgesGeometry:la,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:ro,DataTexture:Gs,TextureLoader:js,Material:vn,MeshStandardMaterial:Fr,MeshBasicMaterial:Hs,MeshLambertMaterial:Ws,MeshPhongMaterial:Xs,MeshPhysicalMaterial:qs,PointsMaterial:xi,LineBasicMaterial:io,LineDashedMaterial:aa,ShaderMaterial:yi,RawShaderMaterial:vf,Object3D:Fn,Group:Ys,Mesh:qn,InstancedMesh:di,Line:kr,LineLoop:ua,LineSegments:da,Points:fa,LightShadow:fi,Light:cr,AmbientLight:mi,DirectionalLight:Ks,PointLight:hi,SpotLight:ma,HemisphereLight:vi,RectAreaLight:ha,Camera:pi,PerspectiveCamera:Js,Scene:bi,WebGLRenderer:Qs,Clock:Zs,SceneQuotaValidator:Xn,exportSceneToCanvas3D:nl,exportSceneToGLB:rl,exportSceneToUSDZ:df,generateUSDZ:Qo,glbToUSDZ:Jo,sceneToCanvas3D:Qr,sceneToGLB:qo,sceneToUSDZ:Ko,authorScriptRunner:so,warnUnsupported:Er,getAuthorWarnings:gf,clearAuthorWarnings:xf};Object.freeze(Xn),Object.freeze(Xn.prototype),Object.freeze(bi.prototype),Object.freeze(Mf);var Vr=new Proxy(Mf,{get:(e,t)=>{if(t in e)return e[t];let r=He().authorNamespace;return r&&typeof t=="string"&&t in r?r[t]:(typeof t=="string"&&t!=="then"&&t!=="toJSON"&&!t.startsWith("__")&&Er(`THREE.${t}`,"no-op proxy"),oi)},has:(e,t)=>{if(t in e)return!0;let r=He().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")}}),Es=He();if(Es.threeNamespace=Vr,Es.workerExtensionInstallers)for(let e of Es.workerExtensionInstallers)e(Vr,Es);var ii={name:"three_author",THREE:Vr},f0=ii,sr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof sr.THREE>"u"&&(sr.THREE=Vr),typeof sr.requestAnimationFrame!="function"&&(sr.requestAnimationFrame=e=>(typeof e=="function"&&typeof sr.__three_live_raf_cb__!="function"&&(sr.__three_live_raf_cb__=e),sr.__three_live_in_step__||Er("requestAnimationFrame","single-frame static evaluation"),0)),typeof sr.cancelAnimationFrame!="function"&&(sr.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=Vr,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=ii,e.ThreeLivePlugins.three_author=ii,e.ThreeLivePlugins["three-author"]=ii}function ao(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var ll=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),m0=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 En=class Cn extends m0{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 He().sandboxEngineSrc??null}static set sandboxEngineSrc(t){He().sandboxEngineSrc=t}static get sandboxIframeSrc(){return He().sandboxIframeSrc??null}static set sandboxIframeSrc(t){He().sandboxIframeSrc=t}static get allowClientScripts(){return!!He().allowClientScripts}static set allowClientScripts(t){He().allowClientScripts=t}static registerScriptRunner(t){He().scriptRunner=t}static defineModelViewer(t="model-viewer"){if(typeof customElements>"u")return!1;let r=customElements.get(t);return r!=null?r===Cn||r.prototype instanceof Cn:(customElements.define(t,class extends Cn{}),!0)}static registerDecoder(t,r){Ht.registerDecoder(t,r)}static getDecoder(t){return Ht.getDecoder(t)}static registerAR(t){He().arProvider=typeof t=="function"?{activateAR:t}:t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof Cn&&r.updateARButtonVisibility()})}static isARSupported(){return!!He().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 Ht.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 Ht.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(Dr(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 Ht.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")||(He().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||Cn.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 Cn.isARSupported()}get toneMapping(){return Dr(this.getAttr("tone-mapping"))}set toneMapping(t){this.setAttr("tone-mapping",t)}get bloomThreshold(){return ao(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return ao(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():ll(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:ll(n,a,s),normal:ll(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=wr(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=He().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 Ht(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 Ht.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")&&Cn.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 Ht.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=He().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,Nd,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(!He().scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(os);return this.showToast(is),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};En.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(" "),En.registerPlugin=Ht.registerPlugin,En.getRegisteredPlugins=Ht.getRegisteredPlugins;var kn=En;{let e=kn.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",kn);function Af(e="model-viewer"){return kn.defineModelViewer(e)}var xl={eye:[0,1.6,5],target:[0,.8,0]},Pf=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(" ")),h0=["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(" ")),ga=[["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"]],Tf={grey:"gray",golden:"gold",crimson:"red",maroon:"red",violet:"purple",aqua:"cyan",turquoise:"cyan",tan:"beige"},pl={};function Vn(e,t){for(let r of e.split(" "))pl[r]=t}Vn("left leftmost",["right",!1]),Vn("right rightmost",["right",!0]),Vn("front nearest closest frontmost",["depth",!1]),Vn("back farthest furthest rear far backmost",["depth",!0]),Vn("top highest upper topmost",["up",!0]),Vn("bottom lowest lower bottommost",["up",!1]),Vn("biggest largest big large huge bigger larger",["size",!0]),Vn("smallest small tiny little smaller",["size",!1]),Vn("tallest tall taller",["height",!0]),Vn("shortest short shorter",["height",!1]),Vn("middle center centre central","middle");var _f={first:0,second:1,third:2,fourth:3,fifth:4,last:-1},Ef={two:2,pair:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10},If=new Set(["all","every","everything","each","everybody"]),bl=e=>/^[0-9]+$/.test(e),xa=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),vl=e=>xa(pl,e)?pl[e]:null,Cf=e=>xa(_f,e)?_f[e]:null;function Nf(e){let t;if(xa(Ef,e))t=Ef[e];else if(/^[0-9]{1,3}$/.test(e))t=Number(e);else return null;return t>=1&&t<=50?t:null}function Df(e){return xa(Tf,e)?Tf[e]:ga.some(t=>t[0]===e)?e:null}function p0(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&&!vl(a)&&a!=="side"&&a!=="end")return!0}}return!1}function b0(e){return String(e??"").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function Uf(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 y0(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(Uf)}var g0=e=>e.replace(/[^A-Za-z0-9]/g,"").toLowerCase(),x0=(e,t)=>h0.some(r=>r.includes(e)&&r.includes(t));function kf(e,t){return e===t||x0(e,t)||t.length>=4&&e.length>=4&&(e.startsWith(t)||t.startsWith(e))}function fl(e){let t=Math.min(1,Math.max(0,Number.isFinite(e)?e:0));return(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)*255}function v0(e){let t=[fl(e[0]),fl(e[1]),fl(e[2])],r=ga[0][0],i=1/0;for(let[n,a]of ga){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 w0=e=>ga.find(t=>t[0]===e)?.[2]??"";function S0(e,t){return e.words.includes(t)?!0:e.colorName!=null&&(e.colorName===t||w0(e.colorName)===t)}function wi(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:y0(t.name),colorName:t.color?v0(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 M0(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 co(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 Bf=e=>e.length?e.reduce((t,r)=>t+r,0)/e.length:0;function ml(e,t,r){let i;if(t==="middle"){if(e.length<3)return e;let n=e.map(o=>co(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=>co(s,t[0],r)),a=Bf(n);i=e.filter((s,o)=>t[1]?n[o]>a+1e-6:n[o]<a-1e-6)}return i.length?i:e}function Rf(e,t,r){let i;if(t==="middle"){let n=Bf(e.map(a=>co(a,"right",r)));i=e.map(a=>[a,Math.abs(co(a,"right",r)-n)])}else i=e.map(n=>[n,t[1]?-co(n,t[0],r):co(n,t[0],r)]);return i.sort((n,a)=>n[1]-a[1])}function un(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 Or=e=>un([],"none",e);function va(e,t,r=xl,i){let n=i?e.filter(s=>i.includes(s.name)):[...e],a=b0(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=hl(n,a.slice(0,s),r);if(f.confidence!=="high")return f;let m=n.filter(g=>f.ids.includes(g.id)),h=hl(m,a.slice(s+(c?1:2)),r);if(h.confidence!=="high")return un(m,"ambiguous","except");let p=m.filter(g=>!h.ids.includes(g.id));return p.length?un(p,"high","match"):Or("no_match")}return hl(n,a,r)}function A0(e){return!(Pf.has(e)||If.has(e)||e==="both"||Nf(e)!==null||Cf(e)!==null||Df(e)!==null||vl(e)!==null||bl(e))}function hl(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(A0)))return Lf(e,t,r);let a=[],s=!1;for(let l of n){let c=Lf(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?un(o,"ambiguous","multiple"):un(o,"high","match")}function Lf(e,t,r){if(!e.length)return Or("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=>g0(A.name)===n);if(y.length)return un(y,"high","exact")}if(p0(t))return Or("relation");let a=[],s=!1,o=!1,l=null,c=null,f=[],m=[],h=!1;for(let y of t){if(h&&bl(y)){a.push(y);continue}h=!1;let A,b,w;if(If.has(y))o=!0,s=!0;else if(y==="both")l=2,s=!0;else if((A=Nf(y))!==null)l=A,s=s||A>1;else if((A=Cf(y))!==null)c=A;else if((b=Df(y))!==null)f.push(b);else if((w=vl(y))!==null)m.push(w);else if(!Pf.has(y)){let S=Uf(y);S!==y&&(s=!0),a.push(S),h=!0}}if(!a.length&&!f.length&&!m.length&&c===null&&!o&&l===null)return Or("empty");let p=M0(r),g=e;if(a.length){let y=g.map(S=>({e:S,n:a.filter(E=>S.words.some(N=>kf(N,E))).length})),A=Math.max(0,...y.map(S=>S.n));if(A===0)return Or("no_match");g=y.filter(S=>S.n===A).map(S=>S.e);let b=S=>S.words.filter(E=>!bl(E)&&!a.some(N=>kf(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=>S0(y,A)))),!g.length)return Or("no_match");if(c!==null){for(let w of m)g=ml(g,w,p);let y=Rf(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 Or("no_match");b=y.slice(w,w+A)}return un(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=ml(g,b,p);let y=Rf(g,m[m.length-1],p),A=v;if(y.length<A)return un(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 un(y.filter(w=>Math.abs(w[1]-b)<=1e-6).map(w=>w[0]),"ambiguous","multiple")}return un(y.slice(0,A).map(b=>b[0]),"high","match")}for(let y of m)g=ml(g,y,p);return x?g.length===1?un(g,"high","match"):un(g,"ambiguous","multiple"):l!==null&&g.length!==l?un(g,"ambiguous","count_mismatch"):un(g,"high","match")}var Ff="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(" "),ba=(e,t)=>{for(let r of t)if(e.startsWith(r))return e.slice(r.length).trim()||null;return null},yl=(e,t)=>{for(let r of t)if(e.endsWith(r))return e.slice(0,-r.length).trim()||null;return null},gl=e=>e.replace(/[.!?,]+$/,"");function T0(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||!Ff.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 Vf(e,t){let r=e.split(/\s+/).filter(Boolean);return r.length&&gl(r[r.length-1]).toLowerCase()==="please"&&r.pop(),gl(r.slice(Math.max(0,r.length-t)).join(" "))}function ya(e,t,r){let[i,n]=T0(t),a=yl(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:Vf(r,s)}}return{kind:"select",mode:e,query:i}}var _0=["please ","ok ","ok, ","okay ","okay, ","now ","now, ","hey ","um ","um, ","uh ","uh, ","so ","so, ","and "],E0=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"]),k0=["select only ","select just ","only select ","just select ","select ","pick ","choose ","highlight ","grab ","focus on "];function wa(e){let t=String(e??"").trim(),r=t.toLowerCase().replace(/[\u2018\u2019]/g,"'").split(/\s+/).filter(Boolean).join(" ");for(r=gl(r);;){let n=r.length;for(let a of _0)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(),E0.has(r))return{kind:"clear",mode:"clear"};let i=ba(r,["deselect ","unselect ","don't select ","do not select "]);if(i!==null)return ya("remove",i,t);for(let n of["remove ","take "])if(r.startsWith(n)){let a=yl(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=ba(r,["also select ","also pick ","also choose ","also add "]),i!==null)return ya("add",i,t);if(r.startsWith("add ")){let n=yl(r.slice(4),[" to the selection"," to selection"]);if(n!==null)return{kind:"select",mode:"add",query:n}}return i=ba(r,k0),i!==null||(i=ba(r,["just ","only "]),i!==null&&!Ff.includes(i.split(" ")[0]))?ya("replace",i,t):{kind:"edit",instruction:Vf(t,1/0)}}var Of=50;function wl(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>=Of)break}return t}function nn(e){let t=e.__tlSelection??[],r=e.selectedMesh||null;return(t[0]??null)!==r?r?[r]:[]:[...t]}function rn(e,t,r={}){let i=r.mode??"replace",n=nn(e),a=wl(typeof t=="string"?[t]:t??[]),s;switch(i){case"clear":s=[];break;case"add":s=wl([...n,...a]);break;case"remove":s=n.filter(f=>!a.includes(f));break;case"toggle":s=wl([...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 zf(e){!e||e.__tlSelectionInstalled||(e.__tlSelectionInstalled=!0,"selectedMeshes"in e||Object.defineProperty(e,"selectedMeshes",{get:()=>nn(e),set:t=>{rn(e,t??[],{mode:"replace",source:"api"})},configurable:!0}),e.addEventListener?.("three-load",()=>{let t=nn(e);t.length>1&&e.viewer?.setSelectedMeshes?.(t)}))}function Si(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 Sl=new WeakMap;function R0(e){let t=e;if(Sl.has(t))return Sl.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 Sl.set(t,n),n}function uo(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?R0(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 Sa(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 xl;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 Ma(e,t,r={}){let i=wi(uo(e));return va(i,t,Sa(e),r.within??null)}var L0=["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(" "),lo=e=>Math.round(e*100)/100;function Ml(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(lo),target:r.target.map(lo),right:[lo(-n[2]/a),0,lo(n[0]/a)]},objects:e.slice(0,300).map(o=>({id:o.id,name:o.name,color:o.colorName,center:o.center.map(lo),size:lo(Math.cbrt(o.size))})),selected:i.slice(0,50),request:String(t).slice(0,500)};return[{role:"system",content:L0},{role:"user",content:JSON.stringify(s)}]}function Al(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<Of&&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 Aa(e,t,r,i={}){let n=uo(e);i.within&&(n=n.filter(o=>i.within.includes(o.name)));let a=wi(n);if(!a.length)return{names:[],confidence:"low",question:""};let s=await r.complete({messages:Ml(a,t,Sa(e),nn(e)),signal:i.signal});return Al(s,a)}var P0=32,I0=32,C0=80,jf=2e3,_a=32*1024*1024,N0=1024,D0=256,U0=2048,Tl=["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 $f(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,C0).join("")}function ur(e){let t=Math.round(e*100)/100;return(Object.is(t,-0)||Math.abs(t)<1e-9?0:t).toFixed(2)}function Gf(e){let t=Math.round(e),r=Object.is(t,-0)?0:t;return String(r)}function fo(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 B0(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 F0(e){let t=fo(e);return!t||t[0]<=0||t[1]<=0||t[2]<=0?null:t}function Mi(e){return`[${ur(e[0])}, ${ur(e[1])}, ${ur(e[2])}]`}function Ea(e){if(!e||typeof e!="object")return"";let t=[];if(typeof e.floorY=="number"&&Number.isFinite(e.floorY)&&t.push(`- Floor height: y = ${ur(e.floorY)} m`),e.camera&&typeof e.camera=="object"){let r=fo(e.camera.eye),i=fo(e.camera.target);if(r&&i){let n=`- Camera: eye ${Mi(r)}, target ${Mi(i)}`,a=Number(e.camera.fovDeg);Number.isFinite(a)&&a>=1&&a<=179&&(n+=`, fov ${Gf(a)} deg`),t.push(n)}}if(Array.isArray(e.planes)){let r=[];for(let i of e.planes){if(r.length>=P0)break;if(!i||typeof i!="object")continue;let n=fo(i.center);if(!n)continue;let a=String(i.orientation??"").toLowerCase()==="vertical"?"vertical":"horizontal",s=$f(i.label),o=B0(i.extent),l=fo(i.normal),c=` ${r.length+1}. ${a}`;s&&(c+=` "${s}"`),c+=` at ${Mi(n)}`,o&&(c+=`, extent ${ur(o[0])}m x ${ur(o[1])}m`),l&&(c+=`, normal ${Mi(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>=I0)break;if(!i||typeof i!="object")continue;let n=$f(i.label),a=fo(i.center);if(!n||!a)continue;let s=F0(i.size),o=typeof i.yawDeg=="number"&&Number.isFinite(i.yawDeg)?i.yawDeg:null,l=` ${r.length+1}. "${n}" at ${Mi(a)}`;s&&(l+=`, size ${ur(s[0])}m x ${ur(s[1])}m x ${ur(s[2])}m`),o!==null&&(l+=`, yaw ${Gf(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 On(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 _l(e,t){let r=`Reconstruct the 3D scene shown in this reference image as a complete Three-Live script.
409
+ `;r+=Ea(t);let i=Array.from(String(e??"").trim()).slice(0,jf).join("");return i&&(r+=`Additional instructions: ${i}
410
+ `),r+="Return only the complete script in a single ```js code block.",r}function El(e,t,r){let i=String(e??"").trim();if(!On(i))throw new Error("compileFromImage: imageUrl must be a base64 data:image/(png|jpeg|webp) URI or an https:// URL.");let n=_l(t,r);return[{role:"system",content:Tl},{role:"user",content:[{type:"image_url",image_url:{url:i}},{type:"text",text:n}]}]}function kl(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 Rl(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 V0(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 O0(e){let t=Number(e);return Number.isFinite(t)?Math.max(D0,Math.min(U0,Math.round(t))):N0}function Ta(e){if(e.byteLength===0)throw new Error("compileFromImage: image buffer is empty.");if(e.byteLength>_a)throw new Error("compileFromImage: image exceeds the 32 MB limit.");let t=Rl(e);if(!t)throw new Error("compileFromImage: unsupported image format (expected PNG, JPEG, or WebP magic bytes).");return`data:${t};base64,${V0(e)}`}function z0(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(On(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(On(m))return m}}}catch{}if(typeof l.toDataURL=="function")try{let c=l.toDataURL("image/jpeg",.88);if(On(c))return c}catch{}return null}async function ka(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=O0(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(!On(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)>_a)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)&&!On(s))throw new Error("compileFromImage: remote image URLs must use https:// (or http:// on localhost).");let o=/^https?:/i.test(s)&&On(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)&&!On(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>_a)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 Ta(new Uint8Array(h))}if(e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]")return Ta(new Uint8Array(e));if(ArrayBuffer.isView(e))return Ta(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>_a)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 Ta(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=z0(e,n,a,r);if(s)return s}if(typeof i.toDataURL=="function"){let s=i.toDataURL("image/jpeg",.88);if(On(s))return s}if(typeof i.src=="string"&&i.src.trim())return ka(i.src,t);throw new Error("compileFromImage: unsupported or unloaded image source.")}async function Ra(e,t,r={}){if(!e?.allowClientScripts)throw new Error("compileFromImage requires client scripts: add the allow-client-scripts attribute.");let i=La(e,r,"compileFromImage"),n=Pa(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,jf).join(""),c=Ea(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 ka(t,{maxEdge:r.maxEdge,signal:o,fetch:r.fetch});if(o.aborted)throw o.reason;let A=El(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=Ai(w),p=[],!m)h="The model reply did not contain a scene script.";else if(new TextEncoder().encode(m).length>Ll)h="The generated script exceeds the 1 MB script limit.";else try{let S=await Cl(e,m,o,"compileFromImage");p=[...S.warnings];let E=Il(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:kl(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>Pl&&y.shift()}e.__tlAiSource=m,rn(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 Nl="three-live-texture-pack",Dl=1,Hf=64,Wf=6*1024*1024,Ia=16*1024*1024,$0=64*1024*1024,Bl=" Seamless tileable PBR albedo texture, flat even lighting, orthographic top-down view, no perspective, no shadows, no text.";function Yf(){return He()}function Kf(e){let t=Yf().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 G0(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 Ca(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 j0(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 H0(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 Fl(e){let t=String(e?.endpoint??"");if(!G0(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+Bl,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 Ca(g.b64_json,Ia);let x=typeof g?.url=="string"?g.url:"";if(x.startsWith("data:image/"))return Ca(x.slice(x.indexOf(",")+1),Ia);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>Ia)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 Jf(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 Ei={async decode(e){let t=Jf(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=Yf().encodeRgbaPngDataUri;if(typeof r=="function"){let i=r(e,t,t),n=Ca(i.slice(i.indexOf(",")+1),1/0),a=He().makePngDeflater?.(globalThis.CompressionStream);return a?a.png(n):n}throw new Error("PNG encoding needs the procedural plugin")}};function W0(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 X0(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 Vl(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:W0(a,r,r,t,t);for(let o=3;o<s.length;o+=4)s[o]=255;return X0(s,t)}async function Ol(e,t=Ei){let r=typeof e=="string"?JSON.parse(e):e;if(!r||r.format!==Nl)throw new Error(`texture pack: format must be "${Nl}"`);if(r.version!==Dl)throw new Error(`texture pack: version must be ${Dl}`);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>Hf)throw new Error(`texture pack: more than ${Hf} 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=Kf(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=Ca(l.slice(c.length),Wf);if(f.length>Wf||Jf(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 zl(e,t=Ei){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,${j0(a)}`,...n.provenance?{provenance:n.provenance}:{}}}return{format:Nl,version:Dl,entries:r}}function q0(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 Na(e){let t=new Map;for(let r of q0(e)?.nodes??[]){let i=r?.extras?.xr?.material;if(!i||typeof i!="object"||i.prompt==null)continue;let n=Kf(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 $l(e=$0){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 Ti=null,Xf=!1;function Yn(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 Y0(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 K0(){let e=He(),t=e.scriptRunner;if(!t||t.__tlTexWrapped)return;let r=i=>Ti&&!i?.texturePack?{...i,texturePack:Ti}: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 Gl(e,t){K0();let r=Ti;Ti=Y0(e);try{return t()}finally{Ti=r}}function Qf(e,t){let r=t??e.aiImageProvider;if(r&&typeof r.generateImage=="function")return r;let i=e.getAttribute?.("ai-image-endpoint");return i?Fl({endpoint:i,model:e.getAttribute?.("ai-image-model")||void 0}):null}function Zf(e){if(e.textureCache!==void 0)return e.textureCache;let t=Yn(e);return t.cache===void 0&&(t.cache=$l()),t.cache}function jl(e){return e.textureCodec??Ei}function _i(e){let t=e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent,r=Yn(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 em(e,t){let r=Yn(e);r.pack.set(t.key,t),r.packJson=null,r.failed.delete(t.key)}async function tm(e,t){let r=Zf(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&&(em(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 nm(e,t,r,i){let n=Yn(e),a=n.inflight.get(r.key);if(a)return a;let s=(async()=>{try{let o=await H0(await t.generateImage({...r.spec,signal:i}));if(o.length>Ia)throw new Error("generated image exceeds 16 MB");let l=Vl(await jl(e).decode(o),r.spec.size),c={provider:t.name??"custom",...t.model?{model:t.model}:{},createdAt:new Date().toISOString()};return em(e,{key:r.key,spec:r.spec,rgba:l,provenance:c}),Zf(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 J0(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 Hl(e,t){let r=Yn(e);r.lastModel=t;let i;try{i=Na(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 tm(e,n)).length){await _i(e).catch(()=>{});return}if((e.getAttribute?.("ai-textures")||"auto").toLowerCase()==="manual")return;let a=Qf(e);if(!a)return;e.fireEvent?.("three-live-texture-start",{keys:n.map(o=>o.key)});let s=(await Promise.all(n.map(o=>nm(e,a,o)))).filter(Boolean).length;s&&(Xf||(Xf=!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 _i(e).catch(()=>{}))})()}function Wl(e,t){Yn(e).lastRun=t}async function Ul(e,t){let r=Yn(e),i=++r.loadSeq;if(t==null){r.pack=new Map,r.packJson=null,await _i(e).catch(()=>{});return}try{let n=await Ol(t,jl(e));if(i!==r.loadSeq)return;r.pack=n,r.packJson=typeof t=="string"?JSON.parse(t):t,r.failed.clear(),await _i(e).catch(()=>{})}catch(n){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(n?.message||n)})}}async function qf(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 Ul(e,await i.json())}catch(r){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(r?.message||r)})}}async function Q0(e,t={}){let r=Yn(e),i=t.meshes?new Set(t.meshes):null,n=Na(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 tm(e,n));a.push(...c),l=n.filter(f=>!c.has(f.key))}if(l.length){let c=Qf(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 J0(l,f,async h=>{r.failed.delete(h.key),t.force&&r.pack.delete(h.key),await nm(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 _i(e).catch(()=>{}),{generated:s,cached:a,failed:o,pack:await rm(e)}}async function rm(e){let t=Yn(e);return t.packJson??(t.packJson=await zl(t.pack,jl(e)))}function om(e){if(!e||e.__tlTexInstalled)return;e.__tlTexInstalled=!0,Yn(e),Object.defineProperty(e,"texturePack",{get:()=>e.__tlTex?.packJson??null,set:n=>{Ul(e,n)},configurable:!0}),e.generateTextures=n=>Q0(e,n),e.exportTexturePack=()=>rm(e);let t=e.querySelector?.('script[type="application/three-live-texture-pack"]');t?.textContent?.trim()&&Ul(e,t.textContent);let r=e.getAttribute?.("texture-pack");r&&qf(e,r);let i=e;typeof MutationObserver<"u"&&i&&typeof i.nodeType=="number"&&new MutationObserver(()=>{let n=e.getAttribute?.("texture-pack");n&&qf(e,n)}).observe(i,{attributes:!0,attributeFilter:["texture-pack"]})}var Da=12;function Ua(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 Z0(e){if(typeof document>"u")return!1;let t=(e.getAttribute?.("ai-select-chips")??"").toLowerCase();return t!=="off"&&t!=="false"}function Ba(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 mo(e){let t=e.__tlChips;t&&(t.off(),t.root.remove(),e.__tlChips=null)}function Va(e,t,r){if(!Z0(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&&Fa(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 Fa(e,t,r),i.root}function Fa(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,Da))n.appendChild(Ba(Ua(s),`Select ${Ua(s)}`,()=>{rn(e,[s],{mode:t.mode==="add"||t.mode==="remove"?t.mode:"replace",source:"tap",query:t.query}),Fa(e,{pending:t.pending},r)}))}else{let s=nn(e);if(!s.length&&!t.pending){mo(e);return}a(s.length?"Selected:":"Nothing selected");for(let o of s.slice(0,Da))n.appendChild(Ba(`${Ua(o)} \xD7`,`Remove ${Ua(o)} from the selection`,()=>rn(e,[o],{mode:"remove",source:"tap"})));if(s.length>Da&&a(`+${s.length-Da} more`),t.pending&&r&&s.length){let o=t.pending;n.appendChild(Ba(`Apply: ${o.slice(0,40)}`,`Apply: ${o.slice(0,200)}`,()=>{Fa(e,{},r),r(o)},!0))}}n.appendChild(Ba("\u2715","Dismiss",()=>mo(e)))}var eb=500,po=2e3,tb=8,nb=[{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."}}}}],rb=["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 ob(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 ib(e){if(!ob(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 _t(e){return typeof e=="string"?e:""}function Rn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Xl(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)?Xl(a,n):n}return r}function im(e){if(e&&typeof e=="object")return Rn(e);try{return Rn(JSON.parse(_t(e)||"{}"))}catch{return{}}}var ql={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:Xl(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(_t(e.type)){case"response.output_audio.delta":case"response.audio.delta":return _t(e.delta)?[{type:"audio",base64:_t(e.delta),rate:24e3}]:[];case"response.output_audio_transcript.delta":case"response.audio_transcript.delta":return[{type:"transcript",speaker:"model",text:_t(e.delta),isFinal:!1}];case"response.output_audio_transcript.done":case"response.audio_transcript.done":return[{type:"transcript",speaker:"model",text:_t(e.transcript),isFinal:!0}];case"conversation.item.input_audio_transcription.delta":return[{type:"transcript",speaker:"user",text:_t(e.delta),isFinal:!1}];case"conversation.item.input_audio_transcription.completed":return[{type:"transcript",speaker:"user",text:_t(e.transcript),isFinal:!0}];case"response.function_call_arguments.done":return[{type:"toolCall",id:_t(e.call_id)||_t(e.item_id),name:_t(e.name),args:im(e.arguments)}];case"input_audio_buffer.speech_started":return[{type:"interrupted"}];case"response.done":return[{type:"turnComplete"}];case"error":return[{type:"error",message:_t(Rn(e.error).message)||"Realtime server error"}];default:return[]}}},Yl={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:Xl(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=Rn(e.serverContent);r.interrupted&&t.push({type:"interrupted"});let i=Rn(r.inputTranscription);_t(i.text)&&t.push({type:"transcript",speaker:"user",text:_t(i.text),isFinal:!1});let n=Rn(r.outputTranscription);_t(n.text)&&t.push({type:"transcript",speaker:"model",text:_t(n.text),isFinal:!1});let a=Rn(r.modelTurn).parts;for(let l of Array.isArray(a)?a:[]){let c=Rn(Rn(l).inlineData),f=_t(c.mimeType);if(f.startsWith("audio/pcm")&&_t(c.data)){let m=Number(/rate=(\d+)/.exec(f)?.[1])||24e3;t.push({type:"audio",base64:_t(c.data),rate:m})}}r.turnComplete&&t.push({type:"turnComplete"});let s=Rn(e.toolCall).functionCalls;for(let l of Array.isArray(s)?s:[]){let c=Rn(l);t.push({type:"toolCall",id:_t(c.id),name:_t(c.name),args:im(c.args)})}let o=Rn(e.error);return _t(o.message)&&t.push({type:"error",message:_t(o.message)}),t}},sb={"ai-realtime":ql,"gemini-live":Yl};function ab(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 cb(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 lb(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 sm(){let e=globalThis;return e.AudioContext??e.webkitAudioContext}function ub(){let e=null,t=null,r=null;return{async start(i,n){let a=sm(),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=cb(c.inputBuffer.getChannelData(0),l,i);f.length&&n(ab(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 db(){let e=null,t=0,r=new Set,i={play(n,a){let s=sm();if(!e&&s)try{e=new s}catch{return}if(!e)return;e.state==="suspended"&&e.resume?.();let o=lb(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 Gt(e,t){e.fireEvent?.("three-live-voice",t)}var ki=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(Si(s))};let r=t.provider??"ai-realtime",i=sb[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=ib(t.url);else throw new Error("connectVoice: pass a wss:// url or a transport.");this.mic=t.microphone===!1?null:t.microphoneSource??ub(),this.sink=t.playAudio===!1?null:t.audioSink??db()}async start(){this.transport.onMessage=r=>this.handle(r),this.transport.onClose=()=>this.shutdown();let e=[rb,this.options.instructions].filter(Boolean).join(`
419
+ `);for(let r of this.adapter.setup({instructions:e,tools:nb,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=nn(this.el);t.length&&this.sendContext(Si(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,po);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,Gt(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(-po),Gt(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(-po),Gt(this.el,{state:this.state,reply:this.modelText,isFinal:r.isFinal}),r.isFinal&&(this.modelText=""));break;case"turnComplete":this.userText&&(Gt(this.el,{state:this.state,transcript:this.userText,isFinal:!0}),this.userText=""),this.modelText&&(Gt(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<=tb&&this.runTool(r.id,r.name,r.args);break;case"error":Gt(this.el,{state:this.state,error:r.message});break}}async runTool(e,t,r){let i;try{if(t==="edit_scene"){let n=_t(r.instruction).trim().slice(0,po);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=_t(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"?Jl(this.el,s,a):await yo(this.el,_t(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 Ri(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 ki(e,t??{});return e.__tlVoiceSession=r,Gt(e,{state:"connecting"}),r.start()}function Kl(){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 Oa(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 za(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 ho(e,t="and"){let r=e.slice(0,5).map(za),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 bo(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 ${ho(t.names)}. ${r.length} selected.`:`Removed ${ho(t.names)}. Nothing is selected.`:e==="add"?`Added ${ho(t.names)}. ${r.length} selected.`:t.names.length===1?`Selected ${za(t.names[0])}.`:`Selected ${t.names.length}: ${ho(t.names)}.`;if(t.confidence==="ambiguous")return t.reason==="count_mismatch"?`I found ${t.candidates.length}: ${ho(t.candidates)}. Which ones?`:`Which one: ${ho(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 yo(e,t,r={}){let i=r.mode??"replace",n=String(t??"").slice(0,po);if(i==="clear")return rn(e,[],{mode:"clear",source:"voice",query:n||"clear"}),{mode:i,query:n,match:null,applied:!0,tier:1,meshes:[],say:bo(i,null,[],n)};let a=i==="remove"?nn(e):null;if(a&&!a.length)return{mode:i,query:n,match:null,applied:!1,tier:1,meshes:[],say:"Nothing is selected."};let s=Ma(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 Aa(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&&(rn(e,s.names,{mode:i,source:"voice",query:n}),f=!0);let m=nn(e),h=!f&&l?l:bo(i,s,m,n);return{mode:i,query:n,match:s,applied:f,tier:o,meshes:m,say:h}}function Jl(e,t,r="replace"){let i=new Set(uo(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=nn(e);return{mode:r,query:a,match:l,applied:!1,tier:1,meshes:c,say:bo(r,l,c,a)}}rn(e,n,{mode:r,source:"voice",query:a});let s={ids:[],names:n,confidence:"high",candidates:[],reason:"exact"},o=nn(e);return{mode:r,query:a,match:s,applied:!0,tier:1,meshes:o,say:bo(r,s,o,a)}}function $a(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 fb(e,t,r){if(typeof e.editScene!="function")return;Gt(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)}}Gt(e,{state:"idle",transcript:t,isFinal:!0,result:i}),r.speak!==!1&&Oa($a(i),r.lang)}async function Li(e,t={}){if(typeof e.editScene!="function")throw new Error("startVoiceEdit needs three-live-ai.min.js (el.editScene).");let r=t.recognizer??Kl();if(!r)throw new Error("startVoiceEdit: this browser has no speech recognition; use el.connectVoice() (ai-realtime or gemini-live) instead.");Gt(e,{state:"listening"});let i="";try{i=(await r.listen({lang:t.lang,signal:t.signal,onPartial:l=>Gt(e,{state:"listening",transcript:l,isFinal:!1})})).trim().slice(0,po)}catch(l){throw Gt(e,{state:"error",error:l?.message||String(l)}),l}if(!i){let l="I didn't catch that.";throw Gt(e,{state:"idle",transcript:i,isFinal:!0,error:l}),t.speak!==!1&&Oa(l,t.lang),new Error(`startVoiceEdit: ${l}`)}let n=i,a,s=t.talkToSelect===!1?null:wa(i);if(s&&s.kind!=="edit"){Gt(e,{state:"thinking",transcript:i,isFinal:!0});try{a=await yo(e,s.kind==="clear"?"":s.query,{mode:s.mode,signal:t.signal})}catch(m){throw Gt(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;Va(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=>fb(e,h,t))}if(!c){if(Gt(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.":"";Oa(a.say+m,t.lang)}return{transcript:i,result:null,selection:a}}n=l}else t.chips!==!1&&e.__tlChips&&mo(e);Gt(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(Gt(e,{state:"idle",transcript:i,isFinal:!0,result:o,...a?{selection:a}:{}}),t.speak!==!1){let l=$a(o);Oa(a?`${a.say} ${l}`:l,t.lang)}return{transcript:i,result:o,...a?{selection:a}:{}}}function Pi(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>=eb,l=nn(e);r||o?rn(e,[s],{mode:"toggle",source:"tap"}):l.length===1&&l[0]===s?rn(e,[],{mode:"clear",source:"tap"}):rn(e,[s],{mode:"replace",source:"tap"}),r=!1,i=0},e.addEventListener?.("meshclick",e.__tlTapHandler)}var mb='<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 am(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=mb,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";Ri(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),Li(e,{signal:i.signal}).catch(()=>{}).finally(()=>{i=null,n(!1)})})}var Ll=1048576,Pl=20,cm=15e3,hb=["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 pb(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 Ql(e){let t=String(e?.endpoint??"");if(!pb(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 Ai(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 Il(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 Cl(e,t,r,i="editScene"){let n=He().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 ${cm} ms.`))),cm);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 bb=50;function yb(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>=bb)break}return r}function gb(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 La(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 Ql({endpoint:n,model:e.getAttribute?.("ai-model")||void 0})}function Pa(e){return typeof e.__tlAiSource=="string"?e.__tlAiSource:e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent??""}async function Zl(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??Pa(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=La(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=yb(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:hb},{role:"user",content:`Current scene script:
423
+ \`\`\`js
424
+ ${n}
425
+ \`\`\`
426
+ `+gb(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=Ai(b),!p)g="The model reply did not contain a scene script.";else if(new TextEncoder().encode(p).length>Ll)g="The generated script exceeds the 1 MB script limit.";else try{let w=await Cl(e,p,l);x=w.warnings;let S=Il(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>Pl&&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 eu(e){let t=e?.__tlAiHistory?.pop();return typeof t!="string"?!1:(e.__tlAiSource=t,await e.executeScript(t),!0)}var Ga={name:"ai",onRegister(){typeof document>"u"||document.querySelectorAll?.("three-live, xr-live").forEach(e=>Ga.onElementConnected?.(e))},onElementConnected(e){let t=e;if(!t||t.__tlAiInstalled)return;t.__tlAiInstalled=!0,t.editScene=(s,o)=>Zl(t,s,o),t.compileFromImage=(s,o)=>Ra(t,s,o),t.undoEdit=()=>eu(t),zf(t);let r=t;t.startVoiceEdit=s=>Li(r,s),r.__tlSelectProvider=()=>{try{return La(t,{})}catch{return null}},t.selectByVoice=(s,o)=>yo(r,s,o),t.connectVoice=s=>Ri(r,s),t.setSelectOnTap=s=>Pi(r,s),t.hasAttribute?.("ai-select-on-tap")&&Pi(r,!0),t.hasAttribute?.("ai-voice-button")&&am(r),"sceneSource"in t||Object.defineProperty(t,"sceneSource",{get:()=>Pa(t),configurable:!0});let i=t;om(i);let n=t.executeScript;typeof n=="function"&&(t.executeScript=s=>(Wl(i,{kind:"script",value:String(s)}),Gl(i,()=>n.call(t,s)).then(o=>(t.__tlAiSource=String(s),Hl(i,o),o))));let a=i.loadScriptFromSrc;typeof a=="function"&&(i.loadScriptFromSrc=s=>(Wl(i,{kind:"url",value:String(s)}),Gl(i,()=>a.call(t,s)).then(o=>(Hl(i,o),o))))}};gt(Ga);function lm(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function ja(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 um(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 ru(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=Hn(e,t,f,1)??lm(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=Hn(e,t,m,A)??lm(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 go(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]];ja(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 Ii=new WeakMap;function ou(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(o=>o.name===t);if(!i)return;let n=Ii.get(e);n||(n=[],e.currentClip&&n.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),Ii.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 tu(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=Ii.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")go(p,m.time,a),um(g.t,g.t,a,h);else if(p.path==="rotation")go(p,m.time,s),ja(g.r,g.r,s,h);else if(p.path==="scale")go(p,m.time,o),um(g.s,g.s,o,h);else if(p.path==="weights"&&(go(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=rt(),{t:p,r:g,s:x}=n[m];or(h,g,p,x),c.push(h)}let f=vr(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]),Bt(m.normalMatrix,m.transform))}var nu=e=>{Ii.delete(e)},iu={name:"keyframes",evaluateAnimation:tu,crossFadeTo:ou,onParseGLB(e){(e.animationsParsed===!1||!e.animations)&&(e.animations=ru(e.gltf,e.bin),e.animationsParsed=!0)},onLoadModel:nu,onClearScene:nu,onDestroy:(e,t)=>nu(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=Ii.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),tu(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),tu(e,e.animationTime))}},Ci=64;function dm(e,t,r){if(!(!e?.meshes||t<0||t>=Ci))for(let i of e.meshes)for(let n of i.primitives){let a=n.pluginData?.morph;a?.weights&&(a.weights[t]=r)}}var su={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;
353
428
  uniform sampler2D uMorphDeltasTex;
354
- uniform float uMorphWeights[${Xn}];
429
+ uniform float uMorphWeights[${Ci}];
355
430
  uniform int uNumMorphTargets;`);return n=n.replace("vec4 world=uModel*vec4(aPosition,1.0);",`vec3 morphedPos = aPosition;
356
- for (int m = 0; m < ${Xn}; m++) {
431
+ for (int m = 0; m < ${Ci}; m++) {
357
432
  if (m >= uNumMorphTargets) break;
358
433
  float w = uMorphWeights[m];
359
434
  if (abs(w) > 0.0001) {
360
435
  morphedPos += texelFetch(uMorphDeltasTex, ivec2(gl_VertexID, m), 0).xyz * w;
361
436
  }
362
437
  }
363
- 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,Xn),h=new Float32Array(a*u*4);for(let p=0;p<u;p++){let m=s[p].POSITION;if(m===void 0)continue;let g=i.accessors?.[m],x=i.bufferViews?.[g?.bufferView];if(!g||!x)continue;let b=ut(i,n,g,3);if(!b||b.length<a*3)continue;let v=p*a*4;for(let d=0;d<a;d++)h[v+d*4]=b[d*3],h[v+d*4+1]=b[d*3+1],h[v+d*4+2]=b[d*3+2],h[v+d*4+3]=0}let c=e.createTexture();e.bindTexture(3553,c),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 f=new Float32Array(Xn);return{hasMorph:!0,morphTex:c,numTargets:u,vertexCount:a,weights:f}},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)}},ro=64,io={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,Ci),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=Hn(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(Ci);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)}},au=64,cu={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;
364
439
  layout(location=4) in uvec4 aJoints;
365
440
  layout(location=5) in vec4 aWeights;
366
- uniform mat4 uJointMatrix[${ro}];`),s=n.includes("morphedPos")?"morphedPos":"aPosition";return n=n.replace(`vec4 world=uModel*vec4(${s},1.0);`,`mat4 skinMatrix =
441
+ uniform mat4 uJointMatrix[${au}];`),a=n.includes("morphedPos")?"morphedPos":"aPosition";return n=n.replace(`vec4 world=uModel*vec4(${a},1.0);`,`mat4 skinMatrix =
367
442
  aWeights.x * uJointMatrix[int(aJoints.x)] +
368
443
  aWeights.y * uJointMatrix[int(aJoints.y)] +
369
444
  aWeights.z * uJointMatrix[int(aJoints.z)] +
370
445
  aWeights.w * uJointMatrix[int(aJoints.w)];
371
- 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),c=(u.byteOffset||0)+(o.byteOffset||0),f=e.createBuffer();e.bindBuffer(34962,f);let p=l.componentType===5121?5121:5123,m=p===5121?new Uint8Array(n,h,l.count*4):new Uint16Array(n,h,l.count*4);e.bufferData(34962,m,35044),e.enableVertexAttribArray(4),e.vertexAttribIPointer(4,4,p,0,0);let g=e.createBuffer();e.bindBuffer(34962,g);let x=ut(i,n,o,4)??new Float32Array(n,c,o.count*4);return e.bufferData(34962,x,35044),e.enableVertexAttribArray(5),e.vertexAttribPointer(5,4,5126,!1,0,0),{hasSkin:!0,buffers:[f,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(ro*16);for(let h=0;h<o.length&&h<ro;h++){let c=o[h],f=n[c]||Se();a.subarray(h*16,(h+1)*16).set(f)}let u=e.getUniformLocation(t,"uJointMatrix[0]");u&&e.uniformMatrix4fv(u,!1,a)}};Ue(no),Ue(to),Ue(io),Ue(Li),Ue(xi);var Hc=`#version 300 es
372
- 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.);}`,Xc=`#version 300 es
373
- 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);}`,$n=new WeakMap,na=new Float32Array(20);function oo(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 $c(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 Wc(e){let t=$n.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,Hc)),e.attachShader(i,r(35632,Xc)),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")},$n.set(e,t),t}var Wn={name:"contact-shadow",onContextRestored(e){$n.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let n=Wc(e),s=!t.xrSessionActive&&(t.backdropMeshes?.length??0)>0,l=[],o=[];for(let m of t.meshes||[]){if(!m||m.visible===!1||m.isPluginMesh||m.name==="__xr_reticle__"||m.name?.startsWith("__xr_slot_"))continue;let g=$c(m);if(!g)continue;m.transform&&(g=oo(m.transform,g)),t.modelRootMatrix&&(g=oo(t.modelRootMatrix,g));let[x,b,v,d,y,M]=g,T=[x,v,d,M,b-y,b+y];/floor|table|pedestal|ground|base|plane/i.test(m.name||"")||y<.14&&Math.min(d,M)>.45?o.push(T):l.push(T)}let a=[],u=t.bounds.center||[0,0,0],h=Math.max(.05,Number(t.bounds.radius)||.5),c=t.bounds.min,f=c?[u[0],u[1],u[2],h,Math.max(.01,u[1]-c[1]),h]:[u[0],u[1],u[2],h,h,h];t.modelRootMatrix&&(f=oo(t.modelRootMatrix,f));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:f[1]-f[4]+.002;for(let[m,g,x,b,v]of l){let d=-1/0;for(let[M,T,V,X,,P]of o)v>=P-.08&&Math.abs(m-M)<=V&&Math.abs(g-T)<=X&&P+.002>d&&(d=P+.002);s&&(d=Math.max(d,m>=.04&&m<=.36&&g>=-.34&&g<=-.04&&v>=.01?.036:Math.hypot(m,g)<=.66&&v>=-.06?.003:-.477)),isFinite(d)||(d=p);let y=a.find(M=>Math.hypot(m-M[0],g-M[1])<.06&&Math.abs(d-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([m,g,x,b,v,d])}if(a.length===0){let m=Math.max(.1,f[3]*1.5)/1.45;a.push([f[0],f[2],m,m,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[m,g,x,b,v,d]of a){let y=Math.max(0,v-d),M=i/(1+y*2);if(M<.02)continue;let T=1+Math.min(.75,y*.85),V=Math.max(.045,x*1.45*T),X=Math.max(.045,b*1.45*T);na.set([m-V,d,g-X,0,0,m+V,d,g-X,1,0,m+V,d,g+X,1,1,m-V,d,g+X,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=$n.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),$n.delete(e))}};function co(){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 uo(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function lo(){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 oa(){return(await ii()).bestMode}async function ii(){let[e,t,r]=await Promise.all([lo(),Promise.resolve(co()),Promise.resolve(uo())]),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 ra(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=jc(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=ri(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 ri(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 jc(e){try{return ri(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function Kc(e,t={}){let r=ri(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",ri(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 qc(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=Kc(e,t);window.location.href=r}var $t=null;function Yc(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 c=h/24*Math.PI*2,f=Math.cos(c),p=Math.sin(c),m=h*2,g=m+1,x=(h+1)%24*2;r[m*3]=f*.11,r[m*3+1]=.002,r[m*3+2]=p*.11,r[g*3]=f*.145,r[g*3+1]=.002,r[g*3+2]=p*.145,i[m*3+1]=i[g*3+1]=1,s.set([m,x,g,g,x,x+1],h*6)}let l=e.createVertexArray();e.bindVertexArray(l);let o=(h,c,f)=>{let p=e.createBuffer();return e.bindBuffer(34962,p),e.bufferData(34962,h,35044),e.enableVertexAttribArray(c),e.vertexAttribPointer(c,f,5126,!1,0,0),p},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 ia(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 ao=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.");$t&&$t!==this&&$t.isSessionActive()&&await $t.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||"",c=/Android|iPhone|iPad|iPod/i.test(h)&&!/Quest|Oculus|Pico|Vision/i.test(h),f=s?i.arScale==="fixed"?1:c?.55:1:i.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,p=s?[0,-.25,0]:[a[0]||0,i.arPlacement==="wall"?a[1]:u[1]??0,a[2]||0],m="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(m="immersive-vr")}catch{m="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(m==="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 H=document.createElement("button");H.type="button",H.textContent="\u2715 Exit AR",H.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",H.addEventListener("beforexrselect",D=>D.preventDefault()),H.addEventListener("click",D=>{D.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(H),_.appendChild(b),document.body.appendChild(_),g=_,x=!0}}let d=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),y={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(d)};g&&(d.add("dom-overlay"),y.optionalFeatures=Array.from(d),y.domOverlay={root:g});for(let _ of Oe)_.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 H=String(_?.name||"");return H==="NotAllowedError"||H==="SecurityError"};try{this.s=await r.requestSession(m,y)}catch(_){if(v(),M(_))throw i.onError?.(_),_;try{this.s=await r.requestSession(m,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(H){if(M(H))throw i.onError?.(H),H;try{this.s=await r.requestSession(m)}catch(D){throw i.onError?.(D),D}}}let T=this.s;$t=this,this.placed=!1;let V=null,X=null,P=null,R=null,C=null,B=[0,-.25,-1.2],N=[0,-.25,-1.2],w=new Float32Array(16),ie=new Float32Array(16),ae=!1,k=1,J=0,z=!1,Y=null,le=null,ce=0,$=null,U=()=>{$t===this&&($t=null),$?.(),$=null;try{X?.cancel?.()}catch{}if(X=null,P){let _=e?.meshes;if(Array.isArray(_)){let D=_.indexOf(P);D!==-1&&_.splice(D,1)}let H=e.getGLContext?.()||e?.gl;if(H)for(let D of P.primitives||[]){H.deleteVertexArray?.(D.vao);for(let F of D.buffers||[])H.deleteBuffer?.(F)}P=null}e?.setXRSessionActive?.(!1),v(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=U,T.addEventListener("end",()=>{U(),i.onExit?.()}),T.addEventListener("select",()=>{if(!this.placed){let _=C||B;N=[_[0],_[1],_[2]],ia(this.placedMat,N,p,J,f*k),this.placed=!0,P&&(P.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 H=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;_&&typeof H=="function"&&typeof T.updateRenderState=="function"&&T.updateRenderState({baseLayer:new H(T,_,{alpha:!0})});try{V=await T.requestReferenceSpace("local")}catch{try{V=await T.requestReferenceSpace("local-floor")}catch{V=await T.requestReferenceSpace("viewer")}}let D=await T.requestReferenceSpace("viewer").catch(()=>V);if(typeof T.requestHitTestSource=="function"&&D&&(X=await T.requestHitTestSource({space:D}).catch(()=>null)),m==="immersive-ar"&&_&&typeof _.createVertexArray=="function"&&Array.isArray(e.meshes)&&(P=Yc(_,i.reticleColor),e.meshes.push(P)),typeof window<"u"&&typeof window.addEventListener=="function"){let E=j=>Math.hypot(j.touches[1].clientX-j.touches[0].clientX,j.touches[1].clientY-j.touches[0].clientY),G=j=>Math.atan2(j.touches[1].clientY-j.touches[0].clientY,j.touches[1].clientX-j.touches[0].clientX),ee=j=>{this.s&&(j.touches.length===1&&this.placed?z=!0:j.touches.length>=2&&(z=!1,Y=E(j),le=G(j)))},se=j=>{if(!this.s||j.touches.length<2)return;let A=E(j),S=G(j);if(Y&&Y>4&&i.arScale!=="fixed"&&(k=Math.max(.15,Math.min(6,k*(A/Y)))),le!==null){let L=S-le;L>Math.PI&&(L-=Math.PI*2),L<-Math.PI&&(L+=Math.PI*2),J-=L}Y=A,le=S},oe=j=>{(!j.touches||j.touches.length===0)&&(z=!1),(!j.touches||j.touches.length<2)&&(Y=null,le=null)};window.addEventListener("touchstart",ee,{passive:!0}),window.addEventListener("touchmove",se,{passive:!0}),window.addEventListener("touchend",oe,{passive:!0}),window.addEventListener("touchcancel",oe,{passive:!0}),$=()=>{window.removeEventListener("touchstart",ee),window.removeEventListener("touchmove",se),window.removeEventListener("touchend",oe),window.removeEventListener("touchcancel",oe)}}e.setXRSessionActive?.(!0);let F=(E,G)=>{if(this.s!==T)return;T.requestAnimationFrame(F);let ee=ce>0?Math.min(Math.max((E-ce)/1e3,0),.1):1/60;ce=E,e?.stepXRUpdate?.(ee);let se=G.getViewerPose(V);if(!se)return;let oe=se.views?.[0];if(!ae&&oe?.transform){let I=oe.transform.position,W=oe.transform.matrix,Q=I?.x??(W?W[12]:0),K=I?.y??(W?W[13]:0),Z=I?.z??(W?W[14]:0),q=W?-W[8]:0,re=W?-W[10]:-1,ne=Math.hypot(q,re);ne>1e-4?(q/=ne,re/=ne):(q=0,re=-1),B=[Q+q*1.2,K-.25,Z+re*1.2],J=Math.atan2(-q,-re),ae=!0}if(X&&typeof G.getHitTestResults=="function"&&(!this.placed||z)){let I=G.getHitTestResults(X)||[],W=!1;for(let Q of I){let K=Q.getPose(V);if(K?.transform?.matrix){let Z=K.transform.matrix,q=Z[5];if(i.arPlacement==="wall"&&Math.abs(q)>.35||i.arPlacement==="floor"&&Math.abs(q)<.65)continue;R||(R=new Float32Array(16)),R.set(Z),C=[Z[12],Z[13],Z[14]],this.placed&&z&&(N=[Z[12],Z[13],Z[14]]),P&&(P.visible=!this.placed||z,P.transform.set(Z)),!this.placed&&b&&(b.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(R),W=!0;break}}!W&&P&&(P.visible=!1)}ia(w,this.placed?N:C||B,p,J,f*k),this.placed&&this.placedMat.set(w);let j=e.xrRigMatrix;j instanceof Float32Array&&j.length===16?Pe(ie,j,w):ie.set(w),e.modelRootMatrix&&e.modelRootMatrix.set(ie);for(let I of Oe)I.onXRFrame?.(e,T,G,V);let A=e.getGLContext?.()||e?.gl,S=T.renderState?.baseLayer;A&&S&&S.framebuffer!==void 0&&A.bindFramebuffer(36160,S.framebuffer);let L=m==="immersive-ar",O=se.views||[];for(let I=0;I<O.length;I++){let W=O[I];if(typeof e.renderXRView=="function"){let Q;if(S&&typeof S.getViewport=="function"){let K=S.getViewport(W);K&&K.width>0&&K.height>0&&(Q=[K.x,K.y,K.width,K.height])}else S?.framebufferWidth>0&&S?.framebufferHeight>0&&(Q=[0,0,S.framebufferWidth,S.framebufferHeight]);e.renderXRView(W,ie,this.placed,Q,L,I)}}A&&S&&S.framebuffer&&A.bindFramebuffer(36160,null)};T.requestAnimationFrame(F)}catch(_){throw typeof T.end=="function"&&await T.end().catch(()=>{}),U(),i.onError?.(_),_}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function oi(e){let t=await ii(),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 ra(e.model,n),{mode:"quick-look",success:!0};o=sn(e.model)}return ra(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 qc(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 ao(l);return await o.start(e.view,e.element),{mode:"webxr",success:!0,session:o}}}catch(o){return{mode:i,success:!1,error:o}}return{mode:i,success:!1,error:new Error(`Unhandled AR mode: ${i}`)}}ft.registerAR({activateAR:oi,createUSDZBlob:sn}),ft.registerScriptRunner(ln),Ue(Wn);var fo=new WeakMap;function si(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);fo.set(e,r)}function ca(e){return fo.get(e)}async function Zc(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 mo=new WeakMap,sa=new Float32Array(16);async function aa(e,t,r){let i=r?await Zc(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var ho={name:"environment-map",onContextRestored(e){mo.delete(e)},setEnvironmentImage(e,t){return aa(e,"environmentTexture",t)},setSkyboxImage(e,t){return aa(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,n){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let s=mo.get(t);if(!s){let c=(m,g)=>{let x=t.createShader(m);return t.shaderSource(x,g),t.compileShader(x),x},f=t.createProgram();t.attachShader(f,c(35633,`#version 300 es
374
- 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(f,c(35632,`#version 300 es
375
- 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(f);let p=typeof t.createVertexArray=="function"?t.createVertexArray():null;s={program:f,vao:p},mo.set(t,s)}let l=tn(sa,r)||sa;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=Hn(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(au*16);for(let f=0;f<o.length&&f<au;f++){let m=o[f],h=n[m]||rt();l.subarray(f*16,(f+1)*16).set(h)}let c=e.getUniformLocation(t,"uJointMatrix[0]");c&&e.uniformMatrix4fv(c,!1,l)}};gt(su),gt(iu),gt(cu),gt(Fc),gt(kc);var xb=`#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.);}`,vb=`#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);}`,Ni=new WeakMap,fm=new Float32Array(20);function lu(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 wb(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 Sb(e){let t=Ni.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,xb)),e.attachShader(i,r(35632,vb)),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")},Ni.set(e,t),t}var Di={name:"contact-shadow",onContextRestored(e){Ni.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let n=Sb(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=wb(g);if(!x)continue;g.transform&&(x=lu(g.transform,x)),t.modelRootMatrix&&(x=lu(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=lu(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);fm.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,fm),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=Ni.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),Ni.delete(e))}};function fu(){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 mu(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function hu(){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 pm(){return(await Wa()).bestMode}async function Wa(){let[e,t,r]=await Promise.all([hu(),Promise.resolve(fu()),Promise.resolve(mu())]),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 mm(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=Mb(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=Ha(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 Ha(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 Mb(e){try{return Ha(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function Ab(e,t={}){let r=Ha(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",Ha(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 Tb(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=Ab(e,t);window.location.href=r}var zr=null;function _b(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 hm(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 du=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.");zr&&zr!==this&&zr.isSessionActive()&&await zr.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 kt)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;zr=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=()=>{zr===this&&(zr=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]],hm(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)&&(_=_b(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),Fe=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",Fe,{passive:!0}),window.addEventListener("touchmove",_e,{passive:!0}),window.addEventListener("touchend",Le,{passive:!0}),window.addEventListener("touchcancel",Le,{passive:!0}),H=()=>{window.removeEventListener("touchstart",Fe),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 Fe=q>0?Math.min(Math.max((me-q)/1e3,0),.1):1/60;q=me,e?.stepXRUpdate?.(Fe);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)}hm(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?at(Y,ne,V):Y.set(V),e.modelRootMatrix&&e.modelRootMatrix.set(Y);for(let O of kt)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 Xa(e){let t=await Wa(),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 mm(e.model,n),{mode:"quick-look",success:!0};o=Zr(e.model)}return mm(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 Tb(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 du(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}`)}}kn.registerAR({activateAR:Xa,createUSDZBlob:Zr}),kn.registerScriptRunner(so),gt(Di),gt(Oc);var bu=new WeakMap;function qa(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);bu.set(e,r)}function gm(e){return bu.get(e)}async function Eb(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 pu=new WeakMap,bm=new Float32Array(16);async function ym(e,t,r){let i=r?await Eb(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var yu={name:"environment-map",onContextRestored(e){pu.delete(e)},setEnvironmentImage(e,t){return ym(e,"environmentTexture",t)},setSkyboxImage(e,t){return ym(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,n){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let a=pu.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},pu.set(t,a)}let s=Kr(bm,r)||bm;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];
376
451
  uniform int uHasSH;
377
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);}
378
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));}
@@ -385,15 +460,15 @@ envDiffuse=uHasSH==1?evalSHIrradiance(N):textureLod(uEnvironmentMap,equirectangu
385
460
  }else if(uHasSH==1){
386
461
  specularIBL=getStudioRadiance(R,roughness)*integrateBRDFApprox(F,roughness,NoV);
387
462
  envDiffuse=evalSHIrradiance(N);
388
- }`),{vs:r,fs:n}},onBeforeDrawPrimitive(e,t,r,i,n,s){let l=fo.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)}},po=new WeakMap;function bo(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(c=>parseFloat(c.replace(/m$/,"")));if(o.length<3||o.some(isNaN))continue;let a=s.getAttribute("data-normal"),u;if(a){let c=a.trim().split(/\s+/).map(f=>parseFloat(f));c.length>=3&&!c.some(isNaN)&&(u=[c[0],c[1],c[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 yo={name:"hotspots",updateHotspotsForElement:bo,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{bo(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),po.set(e,t)},onCameraChange(e,t){t&&bo(t,e)},onElementDisconnected(e){let t=po.get(e);t&&(t.disconnect(),po.delete(e))}},ua=1024,go=256,ai=2048,Qc=128,Jc=64,eu=16,tu=1e4,nu=8,At=new Set(["__proto__","constructor","prototype"]),la={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))},ma={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},ci={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},ui=(e,t)=>e!==null&&typeof e=="object"&&!At.has(t)&&Object.prototype.hasOwnProperty.call(e,t),rt=e=>Array.isArray(e)?[...e]:e,pa=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&ui(e,"value")?e.value:e,Ne=(e,t)=>ui(e.configuration,t)?pa(e.configuration[t]):void 0,he=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},Wt=e=>Math.max(0,Math.min(1,e)),st=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function jn(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||At.has(i)||At.has(r))return null;t.push(i)}return{segments:t}}var dn=(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},fa=e=>{let t=he(e[0]),r=he(e[1]),i=he(e[2]),n=he(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]},da=(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 ni(n,fa(e),fa(t),r),n}return e.slice(0,t.length).map((n,s)=>n+(t[s]-n)*r)}return r>=.5?t:e},xo=(e,t,r)=>Array.isArray(e)&&Array.isArray(t)?e.slice(0,t.length).map((i,n)=>r(he(i),he(t[n]))):Array.isArray(e)?e.map(i=>r(he(i),he(t))):Array.isArray(t)?t.map(i=>r(he(e),he(i))):r(he(e),he(t)),ru=(e,t)=>Array.isArray(e)?e.map(r=>t(he(r))):t(he(e)),ha=(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,Kn=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>ua)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${ua})`);let n=Array.isArray(r.variables)?r.variables:[];if(n.length>go)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${go})`);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,c=new Map,f=new Map,p=[],m=[],g=new Map,x=1,b=0,v=0,d=0,y=0,M=!1,T=!1,V=!1;n.forEach(($,U)=>{if(!$||typeof $!="object")return;let _=rt(pa($.value));o.set(U,_);let H=$.id??$.name;typeof H=="string"&&H&&!At.has(H)&&o.set(H,_)}),(t?.nodes||[]).forEach(($,U)=>{for(let _ of $?.children||[])typeof _=="number"&&g.set(_,U)});let X=$=>$.op||typeof $.declaration=="number"&&s[$.declaration]?.op||"",P=($,U,_)=>{if(At.has(U))return;let H=a.get($);H||a.set($,H=Object.create(null)),H[U]=_},R=($,U)=>{if(typeof $!="number"&&typeof $!="string"||typeof $=="string"&&At.has($)||!o.has($)&&o.size>=go*2)return;let _=rt(U);if(o.set($,_),typeof $=="number"){let H=n[$]?.id??n[$]?.name;typeof H=="string"&&!At.has(H)&&o.set(H,_)}},C=$=>typeof $=="number"?l[$]?.id??String($):typeof $=="string"?/^\d+$/.test($)&&l[Number($)]?.id?l[Number($)].id:$:"",B=($,U)=>{for(let _=$,H=0;_!==void 0&&_>=0&&H<128;_=g.get(_),H++)if(_===U)return!0;return!1},N=$=>{for(let U=p.length-1;U>=0;U--)p[U].key===$&&p.splice(U,1)},w=$=>{N($.key),p.length>=Qc&&p.shift(),p.push($)},ie=$=>{let U=jn($)?.segments;if(U){if(U[0]==="nodes"&&Array.isArray(t?.nodes)){let _=t.nodes[dn(U[1],t.nodes.length)];if(!_)return;let H=U[2];if(H in ci){let D=ci[H],F=_[H]||D;return D.map((E,G)=>he(F[G],E))}if(H==="weights"){let D=Array.isArray(_.weights)?_.weights:[0],F=U.length===4?dn(U[3],64):-2;return F===-2?D.map(E=>he(E)):F>=0?he(D[F]):void 0}if(H==="visible"||H==="extensions"&&U[3]==="KHR_node_visibility"&&U[4]==="visible")return _.extensions?.KHR_node_visibility?.visible??_.visible??!0}else if(U[0]==="materials"&&Array.isArray(t?.materials)){let _=t.materials[dn(U[1],t.materials.length)];if(!_)return;let H=_.pbrMetallicRoughness||{};if(U[2]==="pbrMetallicRoughness"){if(U[3]==="baseColorFactor"){let D=H.baseColorFactor||[1,1,1,1];return[he(D[0],1),he(D[1],1),he(D[2],1),he(D[3],1)]}if(U[3]==="metallicFactor"||U[3]==="roughnessFactor")return he(H[U[3]],1)}if(U[2]==="emissiveFactor"){let D=_.emissiveFactor||[0,0,0];return[he(D[0]),he(D[1]),he(D[2])]}if(U[2]==="alphaCutoff")return he(_.alphaCutoff,.5)}}},ae=($,U)=>{let _=jn($)?.segments;if(!_)return!1;if(_[0]==="nodes"&&Array.isArray(t?.nodes)){let H=dn(_[1],t.nodes.length),D=t.nodes[H];if(!D)return!1;let F=_[2];if(F in ci&&Array.isArray(U)){let E=ci[F];if(U.length<E.length)return!1;let G=E.map((se,oe)=>he(U[oe],se));if(F==="rotation"){let se=Math.hypot(...G);G=se>1e-8?G.map(oe=>oe/se):[0,0,0,1]}D[F]=G,delete D.matrix;let ee=e?.initialNodeTransforms?.[H];return ee&&(ee[F[0]]=[...G]),M=!0,!0}if(F==="weights"){Array.isArray(D.weights)||(D.weights=[]);let E=(G,ee)=>{for(let se of e?.meshes||[])if(se.nodeIndex===H)for(let oe of se.primitives||[])oe.pluginData?.morph?.weights&&(oe.pluginData.morph.weights[G]=ee)};if(_.length===4){let G=dn(_[3],64);if(G<0)return!1;E(G,D.weights[G]=he(U))}else if(Array.isArray(U))D.weights=U.slice(0,64).map(G=>he(G)),D.weights.forEach((G,ee)=>E(ee,G));else return!1;return V=!0,!0}if(F==="visible"||F==="extensions"&&_[3]==="KHR_node_visibility"&&_[4]==="visible"){let E=st(U);return D.visible=E,(!D.extensions||typeof D.extensions!="object")&&(D.extensions={}),D.extensions.KHR_node_visibility={visible:E},T=!0,!0}}else if(_[0]==="materials"&&Array.isArray(t?.materials)){let H=dn(_[1],t.materials.length),D=t.materials[H];if(!D)return!1;let F=D.pbrMetallicRoughness||(D.pbrMetallicRoughness={}),E=G=>{for(let ee of e?.meshes||[])for(let se of ee.primitives||[])(se.materialIndex??0)===H&&G(se)};if(_[2]==="pbrMetallicRoughness"){if(_[3]==="baseColorFactor"&&Array.isArray(U)&&U.length>=3){let G=[Wt(he(U[0],1)),Wt(he(U[1],1)),Wt(he(U[2],1)),U[3]!==void 0?Wt(he(U[3],1)):F.baseColorFactor?.[3]??1];return F.baseColorFactor=G,E(ee=>ee.baseColor=[...G]),V=!0}if(_[3]==="metallicFactor"||_[3]==="roughnessFactor"){let G=_[3]==="metallicFactor",ee=Wt(he(U,G?0:.5));return F[_[3]]=ee,E(se=>se[G?"metallic":"roughness"]=ee),V=!0}}if(_[2]==="emissiveFactor"&&Array.isArray(U)&&U.length>=3)return D.emissiveFactor=[0,1,2].map(G=>Math.max(0,he(U[G]))),V=!0;if(_[2]==="alphaCutoff")return D.alphaCutoff=Wt(he(U,.5)),V=!0}return!1},k=($,U,_=new Set)=>{let H=Ne(U,"pointer");if(typeof H!="string"||!H.startsWith("/"))return null;let D=H.replace(/\{([a-zA-Z0-9_]+)\}/g,(F,E)=>{let G=Math.trunc(Number(J($,E,void 0,_)??Ne(U,E)));return Number.isSafeInteger(G)&&G>=0?String(G):"-1"});return jn(D)?D:null},J=($,U,_,H)=>{let D=i[$]?.values;if(!ui(D,U))return _;let F=D[U];if(F==null)return _;if(typeof F!="object"||Array.isArray(F))return rt(F);let E=F;return typeof E.node=="number"?z(E.node,E.socket||"value",H):ui(E,"value")?rt(E.value):_},z=($,U,_)=>{if($<0||$>=i.length||_.has($)||_.size>128||++d>tu)return;let H=i[$],D=X(H);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(D))return rt(a.get($)?.[U]);_.add($);try{let F=(E,G=0)=>J($,E,G,_);if(D==="variable/get"){let E=Ne(H,"variable")??Ne(H,"id");return typeof E=="number"||typeof E=="string"?rt(o.get(E)):void 0}if(D==="pointer/get"){let E=k($,H,_);return E?ie(E):void 0}if(D.startsWith("math/")){let E=D.slice(5);if(E in la)return ru(F("a"),la[E]);if(E in ma){let G=/^(mul|div|rem|mod|pow)$/.test(E)?1:0;return xo(F("a",E==="mul"?1:0),F("b",G),ma[E])}if(E==="pi")return Math.PI;if(E==="e")return Math.E;if(E==="random")return Math.random();if(E==="clamp")return xo(xo(F("a"),F("b",F("min",0)),Math.max),F("c",F("max",1)),Math.min);if(E==="mix"||E==="quatSlerp")return da(F("a",0),F("b",1),he(F("c",F("t",.5)),.5),E==="quatSlerp");if(E==="dot"){let G=F("a"),ee=F("b");return Array.isArray(G)&&Array.isArray(ee)?G.reduce((se,oe,j)=>se+(oe||0)*(ee[j]||0),0):he(G)*he(ee)}if(E==="cross"){let G=F("a",[0,0,0]),ee=F("b",[0,0,0]);return Array.isArray(G)&&Array.isArray(ee)?[(G[1]||0)*(ee[2]||0)-(G[2]||0)*(ee[1]||0),(G[2]||0)*(ee[0]||0)-(G[0]||0)*(ee[2]||0),(G[0]||0)*(ee[1]||0)-(G[1]||0)*(ee[0]||0)]:[0,0,0]}if(E==="length"){let G=F("a");return Array.isArray(G)?Math.hypot(...G):Math.abs(he(G))}if(E==="distance"){let G=F("a"),ee=F("b");return Array.isArray(G)&&Array.isArray(ee)?Math.hypot(...G.map((se,oe)=>(se||0)-(ee[oe]||0))):Math.abs(he(G)-he(ee))}if(E==="normalize"){let G=F("a");if(!Array.isArray(G))return he(G)>=0?1:-1;let ee=Math.hypot(...G);return ee>1e-8?G.map(se=>se/ee):G.map(()=>0)}if(E.startsWith("combine"))return["a","b","c","d"].slice(0,Number(E[7])||2).map(G=>he(F(G)));if(E.startsWith("extract")){let G=F("a");return Array.isArray(G)?G[U==="0"||U==="x"?0:U==="1"||U==="y"?1:U==="2"||U==="z"?2:3]??0:0}if(E==="eq")return ha(F("a"),F("b"));if(E==="ne")return!ha(F("a"),F("b"));if(E==="lt")return he(F("a"))<he(F("b"));if(E==="le")return he(F("a"))<=he(F("b"));if(E==="gt")return he(F("a"))>he(F("b"));if(E==="ge")return he(F("a"))>=he(F("b"));if(E==="isNaN")return Number.isNaN(Number(F("a")));if(E==="isInf"){let G=Number(F("a"));return!Number.isFinite(G)&&!Number.isNaN(G)}return E==="and"?st(F("a",!1))&&st(F("b",!1)):E==="or"?st(F("a",!1))||st(F("b",!1)):E==="xor"?st(F("a",!1))!==st(F("b",!1)):E==="not"?!st(F("a",!1)):E==="select"?rt(st(F("condition",!1))?F("a"):F("b")):void 0}return D==="type/boolToInt"||D==="type/boolToFloat"?st(F("a",!1))?1:0:D==="type/intToBool"||D==="type/floatToBool"?he(F("a",0))!==0:D==="type/intToFloat"?he(F("a",0)):D==="type/floatToInt"?Math.trunc(he(F("a",0))):void 0}finally{_.delete($)}},Y=()=>{if(M){M=!1,V=!0;let $=Vt(t);if(e){e.worldMatrices=$;for(let U of e.meshes||[])U.nodeIndex>=0&&U.nodeIndex<$.length&&(U.transform.set($[U.nodeIndex]),ze(U.normalMatrix,U.transform))}}if(T){T=!1,V=!0;let $=t?.nodes;if(Array.isArray(e?.meshes)&&Array.isArray($))for(let U of e.meshes){let _=!0;for(let H=U.nodeIndex,D=0;H!==void 0&&H>=0&&D<128;H=g.get(H),D++){let F=$[H];if(F?.visible===!1||F?.extensions?.KHR_node_visibility?.visible===!1){_=!1;break}}U.visible=_}}V&&(V=!1,e?.render?.())},le=($,U={steps:0})=>{if(!$||typeof $.node!="number")return;U.steps===0&&(d=0);let _=[$],H=D=>{_.length+U.steps<ai&&_.push(D)};for(;_.length>0&&U.steps<ai;){U.steps++;let D=_.shift();if(!D||D.node<0||D.node>=i.length)continue;let F=D.node,E=i[F];if(!E)continue;let G=D.socket||"in",ee=X(E),se=(j,A=void 0)=>J(F,j,A,new Set),oe=(j="out")=>{let A=E.flows?.[j];A&&H(A)};switch(ee){case"flow/branch":oe(st(se("condition",!1))?"true":"false");break;case"flow/sequence":for(let j of Object.keys(E.flows||{}).sort((A,S)=>Number(A)-Number(S)||A.localeCompare(S)))oe(j);break;case"flow/switch":{let j=E.flows?.[String(se("selection",se("value",0)))]??E.flows?.default;j&&H(j);break}case"flow/for":{let j=Math.trunc(he(se("startIndex",0))),A=Math.trunc(he(se("endIndex",0))),S=Math.max(1,Math.trunc(he(se("step",1),1))),L=E.flows?.body;if(L&&A>j&&y<nu){let I=Math.min(Math.ceil((A-j)/S),ai);y++;try{for(let W=0;W<I&&U.steps<ai;W++)P(F,"index",j+W*S),le(L,U)}finally{y--}}let O=E.flows?.completed??E.flows?.out;O&&H(O);break}case"flow/doN":{let j=G==="reset"?0:(u.get(F)||0)+1;if(u.set(F,j),P(F,"currentCount",j),P(F,"count",j),G!=="reset"){let A=Math.trunc(he(se("n",Ne(E,"stopIterations")??Ne(E,"n")??1),1));j<=A&&oe()}break}case"flow/multiGate":{if(G==="reset"){f.set(F,0);break}let j=Object.keys(E.flows||{}).sort();if(!j.length)break;let A=Ne(E,"isRandom")?Math.floor(Math.random()*j.length):f.get(F)||0;A<j.length&&(oe(j[A]),f.set(F,Ne(E,"isLoop")!==!1?(A+1)%j.length:A+1));break}case"flow/waitAll":{if(G==="reset"){h.delete(F);break}let j=h.get(F);j||h.set(F,j=new Set),j.add(G),j.size>=Math.max(1,Math.trunc(Number(Ne(E,"inputFlows")??2)||2))&&(j.clear(),oe("out"),oe("completed"));break}case"flow/throttle":{if(G==="reset"){c.delete(F);break}let j=Math.max(0,he(se("duration",0))),A=c.get(F);A===void 0||b-A>=j?(c.set(F,b),P(F,"lastRemainingTime",0),oe()):P(F,"lastRemainingTime",Math.max(0,j-(b-A)));break}case"flow/delay":case"flow/setDelay":{if(G==="cancel"){for(let L=m.length-1;L>=0;L--)m[L].nodeIdx===F&&m.splice(L,1);P(F,"lastDelayIndex",-1);break}let j=Math.max(0,he(se("duration",Ne(E,"duration")??0))),A=E.flows?.done??E.flows?.out;if(j<=0){P(F,"lastDelayIndex",-1),A&&H(A);break}m.length>=Jc&&m.shift();let S=x++;P(F,"lastDelayIndex",S),m.push({id:S,nodeIdx:F,rem:j,done:A}),ee==="flow/setDelay"&&E.flows?.out&&E.flows?.done&&oe("out");break}case"flow/cancelDelay":{let j=Math.trunc(he(se("delayIndex",-1),-1));if(j<0)m.length=0;else for(let A=m.length-1;A>=0;A--)m[A].id===j&&m.splice(A,1);oe();break}case"variable/set":R(Ne(E,"variable")??Ne(E,"id"),se("value")),oe();break;case"variable/interpolate":{let j=Ne(E,"variable")??Ne(E,"id"),A=se("value",se("target")),S=Math.max(0,he(se("duration",Ne(E,"duration")??.3),.3));j!==void 0&&A!==void 0&&w({key:`var:${String(j)}`,varKey:j,from:rt(se("from")??o.get(j)??0),to:rt(A),dur:S,elapsed:0,quat:!1,linear:Ne(E,"easing")==="linear",done:E.flows?.done}),oe();break}case"pointer/set":{let j=k(F,E),A=se("value");j&&A!==void 0&&(N(`ptr:${j}`),ae(j,A)),oe();break}case"pointer/interpolate":{let j=k(F,E),A=se("value",se("target")),S=Math.max(0,he(se("duration",Ne(E,"duration")??.3),.3));if(j&&A!==void 0){let L=se("from")??ie(j);L!==void 0&&(S<=0?(ae(j,A),oe("done")):w({key:`ptr:${j}`,ptr:j,from:rt(L),to:rt(A),dur:S,elapsed:0,quat:j.endsWith("/rotation"),linear:Ne(E,"easing")==="linear",done:E.flows?.done}))}oe();break}case"animation/start":{let j=se("animation")??Ne(E,"animation")??Ne(E,"clipName"),A=typeof j=="number"?e?.animations?.[j]?.name??t?.animations?.[j]?.name:typeof j=="string"?j:void 0;e?.playAnimation?.(A),V=!0,oe();break}case"animation/stop":case"animation/resetAt":e?.pauseAnimation?.(),ee==="animation/resetAt"&&e?.evaluateAnimation?.(he(se("time",0))),V=!0,oe();break;case"event/send":case"customEvent/send":{let j=C(Ne(E,"event")??Ne(E,"id")),A={};for(let S of Object.keys(E.values||{}))At.has(S)||(A[S]=se(S));j&&(typeof CustomEvent<"u"&&typeof e?.container?.dispatchEvent=="function"&&e.container.dispatchEvent(new CustomEvent("interactivityEvent",{bubbles:!0,composed:!0,detail:{id:j,values:A}})),ce(j,A,U)),oe();break}default:oe();break}}};this.readScenePointer=ie,this.writeScenePointer=ae,this.fireOnStart=()=>{i.forEach($=>{X($)==="event/onStart"&&le($.flows?.out)}),Y()},this.fireOnSelect=$=>{if(!$)return;let U=typeof $.meshIndex=="number"?$.meshIndex:-1,_=typeof $.nodeIndex=="number"?$.nodeIndex:e?.meshes?.[U]?.nodeIndex??-1;i.forEach((H,D)=>{if(!/^(pointer|event|scene)\/onSelect$/.test(X(H)))return;let F=Ne(H,"nodeIndex")??Ne(H,"node")??J(D,"nodeIndex",void 0,new Set),E=Ne(H,"meshName");if(typeof E=="string"&&E?$.meshName===E:F==null||Number(F)<0||Number.isNaN(Number(F))||B(_,Math.trunc(Number(F)))){if(P(D,"nodeIndex",_),P(D,"meshIndex",U),Array.isArray($.hitPoint)){let G=[he($.hitPoint[0]),he($.hitPoint[1]),he($.hitPoint[2])];P(D,"hitPoint",G),P(D,"point",G),P(D,"intersectionPoint",G)}if(Array.isArray($.normal)){let G=[he($.normal[0]),he($.normal[1],1),he($.normal[2])];P(D,"normal",G),P(D,"hitNormal",G)}typeof $.distance=="number"&&P(D,"distance",$.distance),le(H.flows?.out)}}),Y()},this.receiveCustomEvent=($,U={})=>ce($,U,{steps:0});function ce($,U,_){if(!(v>=eu)){v++;try{let H=C($);i.forEach((D,F)=>{if(!/^(customE|e)vent\/receive$/.test(X(D)))return;let E=Ne(D,"event")??Ne(D,"id");if(!(C(E)!==H&&String(E)!==String($))){for(let[G,ee]of Object.entries(U))At.has(G)||P(F,G,rt(ee));le(D.flows?.out,_)}}),Y()}finally{v--}}}this.tick=$=>{if(!Number.isFinite($)||$<0)return;let U=Math.min($,.25);b+=U,i.forEach((H,D)=>{X(H)==="event/onTick"&&(P(D,"timeDelta",U),P(D,"dt",U),P(D,"timeElapsed",b),le(H.flows?.out))});let _=[];for(let H=p.length-1;H>=0;H--){let D=p[H];D.elapsed+=U;let F=D.dur>1e-6?Wt(D.elapsed/D.dur):1,E=D.linear?F:F*F*(3-2*F),G=da(D.from,D.to,E,D.quat);D.ptr?ae(D.ptr,G):D.varKey!==void 0&&R(D.varKey,G),F>=1&&(p.splice(H,1),D.done&&_.push(D.done))}for(let H=m.length-1;H>=0;H--){let D=m[H];D.rem-=U,D.rem<=0&&(m.splice(H,1),D.done&&_.push(D.done))}for(let H of _)le(H);Y()},this.dispose=()=>{p.length=0,m.length=0,o.clear(),a.clear(),u.clear(),h.clear(),c.clear(),f.clear()}}},dt=new WeakMap,li=new WeakMap;function iu(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||er().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=(li.get(e)||0)+n,l=!1;for(let o=0;o<i.length;o++){let a=i[o],u=Rs(a?.extras?.xr?.orbit);if(!u)continue;let h=0,c=0,f=0;if(Array.isArray(u.target))h=u.target[0],c=u.target[1],f=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=he(b.translation[0]),c=he(b.translation[1]),f=he(b.translation[2]))}let p=u.phase+u.speed*s,m=h+Math.cos(p)*u.radius,g=c+u.height,x=f+Math.sin(p)*u.radius;if(a.translation=[m,g,x],u.faceCenter){let b=Math.atan2(h-m,f-x);a.rotation=[0,Math.sin(b*.5),0,Math.cos(b*.5)]}l=!0}if(l){li.set(e,s);let o=Vt(r);e.worldMatrices=o;for(let a of e.meshes||[])a.nodeIndex>=0&&a.nodeIndex<o.length&&(a.transform.set(o[a.nodeIndex]),ze(a.normalMatrix,a.transform))}}function mi(e){if(!(!e||typeof e!="object"))return dt.get(e)||dt.get(e.viewer)||dt.get(e._view)}function vo(e,t,r){let i=mi(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var Mo={name:"khr-interactivity",sendInteractivityEvent:vo,getInteractivityVM:mi,onLoadModel(e,t){if(!e||typeof e!="object")return;dt.get(e)?.dispose(),dt.delete(e),li.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 Kn(e,t,i);dt.set(e,n),n.fireOnStart()},onMeshSelect(e,t){dt.get(e)?.fireOnSelect(t)},onUpdate(e,t){dt.get(e)?.tick(t),iu(e,t)},onDestroy(e,t){dt.get(t)?.dispose(),dt.delete(t),li.delete(t)}},qn=new Map,fi=new WeakMap;function ba(e,t){qn.set(e,t)}var To={name:"materials",onContextRestored(e){fi.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=fi.get(e);r||(r=e.createTexture(),fi.set(e,r));let i=Math.max(1,t.canvas.width),n=Math.max(1,t.canvas.height);e.activeTexture(33990),e.bindTexture(3553,r),e.copyTexImage2D(3553,0,6408,0,0,i,n,0),e.texParameteri(3553,10242,33071),e.texParameteri(3553,10243,33071),e.texParameteri(3553,10241,9987),e.texParameteri(3553,10240,9729),e.generateMipmap(3553)},onResolveShader(e,t,r,i){if(!t)return null;if(t.name&&qn.has(t.name)){let m=qn.get(t.name);return{vs:m.vs||r,fs:m.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 m=h.includes("uniform vec2 uViewportSize;")?"":`uniform vec2 uViewportSize;
389
- `;h=h.replace("out vec4 fragColor;",`uniform sampler2D uTransmissionTex;
390
- ${m}out vec4 fragColor;`)}let c=(m,g,x=0,b=1e6,v=3)=>{let d=Number(m);return(Number.isFinite(d)?Math.min(b,Math.max(x,d)):g).toFixed(v)},f=Number(n.KHR_materials_ior?.ior??1.5),p=Number.isFinite(f)?Math.min(10,Math.max(1,f)):1.5;if(a){let m=Math.pow((p-1)/(p+1),2);h=h.replace("vec3 F0=mix(vec3(0.04),base.rgb,metallic);",`vec3 F0=mix(vec3(${c(m,.04,0,1,4)}),base.rgb,metallic);`)}if(u){let m=c(u.iridescenceFactor,1,0,1),g=c(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,${m}*pow(1.-NoV,2.));`)}if(o){let m=c(n.KHR_materials_transmission?.transmissionFactor,1,0,1),g=n.KHR_materials_volume||{},x=c(g.thicknessFactor,.5,0,1e4),b=c(g.attenuationDistance,1,.001,1e6),v=Array.isArray(g.attenuationColor)?g.attenuationColor:[1,1,1],d=c(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;
391
- vec2 sUV=gl_FragCoord.xy/max(uViewportSize,vec2(1.));float iorB=${c(p,1.5,1,10)},dV=${d},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=bu.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)}},gu=new WeakMap;function xu(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 vu={name:"hotspots",updateHotspotsForElement:xu,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{xu(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),gu.set(e,t)},onCameraChange(e,t){t&&xu(t,e)},onElementDisconnected(e){let t=gu.get(e);t&&(t.disconnect(),gu.delete(e))}},xm=1024,wu=256,Ya=2048,kb=128,Rb=64,Lb=16,Pb=1e4,Ib=8,dr=new Set(["__proto__","constructor","prototype"]),vm={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))},wm={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},Ka={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},Ja=(e,t)=>e!==null&&typeof e=="object"&&!dr.has(t)&&Object.prototype.hasOwnProperty.call(e,t),Ln=e=>Array.isArray(e)?[...e]:e,Tm=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&Ja(e,"value")?e.value:e,At=(e,t)=>Ja(e.configuration,t)?Tm(e.configuration[t]):void 0,$e=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},$r=e=>Math.max(0,Math.min(1,e)),zn=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function Ui(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||dr.has(i)||dr.has(r))return null;t.push(i)}return{segments:t}}var xo=(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},Sm=e=>{let t=$e(e[0]),r=$e(e[1]),i=$e(e[2]),n=$e(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]},Mm=(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 ja(n,Sm(e),Sm(t),r),n}return e.slice(0,t.length).map((n,a)=>n+(t[a]-n)*r)}return r>=.5?t:e},Su=(e,t,r)=>Array.isArray(e)&&Array.isArray(t)?e.slice(0,t.length).map((i,n)=>r($e(i),$e(t[n]))):Array.isArray(e)?e.map(i=>r($e(i),$e(t))):Array.isArray(t)?t.map(i=>r($e(e),$e(i))):r($e(e),$e(t)),Cb=(e,t)=>Array.isArray(e)?e.map(r=>t($e(r))):t($e(e)),Am=(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,Bi=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>xm)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${xm})`);let n=Array.isArray(r.variables)?r.variables:[];if(n.length>wu)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${wu})`);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=Ln(Tm(H.value));o.set(te,Z);let ae=H.id??H.name;typeof ae=="string"&&ae&&!dr.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(dr.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"&&dr.has(H)||!o.has(H)&&o.size>=wu*2)return;let Z=Ln(te);if(o.set(H,Z),typeof H=="number"){let ae=n[H]?.id??n[H]?.name;typeof ae=="string"&&!dr.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>=kb&&p.shift(),p.push(H)},Y=H=>{let te=Ui(H)?.segments;if(te){if(te[0]==="nodes"&&Array.isArray(t?.nodes)){let Z=t.nodes[xo(te[1],t.nodes.length)];if(!Z)return;let ae=te[2];if(ae in Ka){let ie=Ka[ae],de=Z[ae]||ie;return ie.map((me,Se)=>$e(de[Se],me))}if(ae==="weights"){let ie=Array.isArray(Z.weights)?Z.weights:[0],de=te.length===4?xo(te[3],64):-2;return de===-2?ie.map(me=>$e(me)):de>=0?$e(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[xo(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[$e(ie[0],1),$e(ie[1],1),$e(ie[2],1),$e(ie[3],1)]}if(te[3]==="metallicFactor"||te[3]==="roughnessFactor")return $e(ae[te[3]],1)}if(te[2]==="emissiveFactor"){let ie=Z.emissiveFactor||[0,0,0];return[$e(ie[0]),$e(ie[1]),$e(ie[2])]}if(te[2]==="alphaCutoff")return $e(Z.alphaCutoff,.5)}}},J=(H,te)=>{let Z=Ui(H)?.segments;if(!Z)return!1;if(Z[0]==="nodes"&&Array.isArray(t?.nodes)){let ae=xo(Z[1],t.nodes.length),ie=t.nodes[ae];if(!ie)return!1;let de=Z[2];if(de in Ka&&Array.isArray(te)){let me=Ka[de];if(te.length<me.length)return!1;let Se=me.map((_e,Le)=>$e(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 Fe=e?.initialNodeTransforms?.[ae];return Fe&&(Fe[de[0]]=[...Se]),S=!0,!0}if(de==="weights"){Array.isArray(ie.weights)||(ie.weights=[]);let me=(Se,Fe)=>{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]=Fe)};if(Z.length===4){let Se=xo(Z[3],64);if(Se<0)return!1;me(Se,ie.weights[Se]=$e(te))}else if(Array.isArray(te))ie.weights=te.slice(0,64).map(Se=>$e(Se)),ie.weights.forEach((Se,Fe)=>me(Fe,Se));else return!1;return N=!0,!0}if(de==="visible"||de==="extensions"&&Z[3]==="KHR_node_visibility"&&Z[4]==="visible"){let me=zn(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=xo(Z[1],t.materials.length),ie=t.materials[ae];if(!ie)return!1;let de=ie.pbrMetallicRoughness||(ie.pbrMetallicRoughness={}),me=Se=>{for(let Fe of e?.meshes||[])for(let _e of Fe.primitives||[])(_e.materialIndex??0)===ae&&Se(_e)};if(Z[2]==="pbrMetallicRoughness"){if(Z[3]==="baseColorFactor"&&Array.isArray(te)&&te.length>=3){let Se=[$r($e(te[0],1)),$r($e(te[1],1)),$r($e(te[2],1)),te[3]!==void 0?$r($e(te[3],1)):de.baseColorFactor?.[3]??1];return de.baseColorFactor=Se,me(Fe=>Fe.baseColor=[...Se]),N=!0}if(Z[3]==="metallicFactor"||Z[3]==="roughnessFactor"){let Se=Z[3]==="metallicFactor",Fe=$r($e(te,Se?0:.5));return de[Z[3]]=Fe,me(_e=>_e[Se?"metallic":"roughness"]=Fe),N=!0}}if(Z[2]==="emissiveFactor"&&Array.isArray(te)&&te.length>=3)return ie.emissiveFactor=[0,1,2].map(Se=>Math.max(0,$e(te[Se]))),N=!0;if(Z[2]==="alphaCutoff")return ie.alphaCutoff=$r($e(te,.5)),N=!0}return!1},re=(H,te,Z=new Set)=>{let ae=At(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)??At(te,me)));return Number.isSafeInteger(Se)&&Se>=0?String(Se):"-1"});return Ui(ie)?ie:null},Q=(H,te,Z,ae)=>{let ie=i[H]?.values;if(!Ja(ie,te))return Z;let de=ie[te];if(de==null)return Z;if(typeof de!="object"||Array.isArray(de))return Ln(de);let me=de;return typeof me.node=="number"?ee(me.node,me.socket||"value",ae):Ja(me,"value")?Ln(me.value):Z},ee=(H,te,Z)=>{if(H<0||H>=i.length||Z.has(H)||Z.size>128||++b>Pb)return;let ae=i[H],ie=C(ae);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(ie))return Ln(l.get(H)?.[te]);Z.add(H);try{let de=(me,Se=0)=>Q(H,me,Se,Z);if(ie==="variable/get"){let me=At(ae,"variable")??At(ae,"id");return typeof me=="number"||typeof me=="string"?Ln(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 vm)return Cb(de("a"),vm[me]);if(me in wm){let Se=/^(mul|div|rem|mod|pow)$/.test(me)?1:0;return Su(de("a",me==="mul"?1:0),de("b",Se),wm[me])}if(me==="pi")return Math.PI;if(me==="e")return Math.E;if(me==="random")return Math.random();if(me==="clamp")return Su(Su(de("a"),de("b",de("min",0)),Math.max),de("c",de("max",1)),Math.min);if(me==="mix"||me==="quatSlerp")return Mm(de("a",0),de("b",1),$e(de("c",de("t",.5)),.5),me==="quatSlerp");if(me==="dot"){let Se=de("a"),Fe=de("b");return Array.isArray(Se)&&Array.isArray(Fe)?Se.reduce((_e,Le,ne)=>_e+(Le||0)*(Fe[ne]||0),0):$e(Se)*$e(Fe)}if(me==="cross"){let Se=de("a",[0,0,0]),Fe=de("b",[0,0,0]);return Array.isArray(Se)&&Array.isArray(Fe)?[(Se[1]||0)*(Fe[2]||0)-(Se[2]||0)*(Fe[1]||0),(Se[2]||0)*(Fe[0]||0)-(Se[0]||0)*(Fe[2]||0),(Se[0]||0)*(Fe[1]||0)-(Se[1]||0)*(Fe[0]||0)]:[0,0,0]}if(me==="length"){let Se=de("a");return Array.isArray(Se)?Math.hypot(...Se):Math.abs($e(Se))}if(me==="distance"){let Se=de("a"),Fe=de("b");return Array.isArray(Se)&&Array.isArray(Fe)?Math.hypot(...Se.map((_e,Le)=>(_e||0)-(Fe[Le]||0))):Math.abs($e(Se)-$e(Fe))}if(me==="normalize"){let Se=de("a");if(!Array.isArray(Se))return $e(Se)>=0?1:-1;let Fe=Math.hypot(...Se);return Fe>1e-8?Se.map(_e=>_e/Fe):Se.map(()=>0)}if(me.startsWith("combine"))return["a","b","c","d"].slice(0,Number(me[7])||2).map(Se=>$e(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 Am(de("a"),de("b"));if(me==="ne")return!Am(de("a"),de("b"));if(me==="lt")return $e(de("a"))<$e(de("b"));if(me==="le")return $e(de("a"))<=$e(de("b"));if(me==="gt")return $e(de("a"))>$e(de("b"));if(me==="ge")return $e(de("a"))>=$e(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"?zn(de("a",!1))&&zn(de("b",!1)):me==="or"?zn(de("a",!1))||zn(de("b",!1)):me==="xor"?zn(de("a",!1))!==zn(de("b",!1)):me==="not"?!zn(de("a",!1)):me==="select"?Ln(zn(de("condition",!1))?de("a"):de("b")):void 0}return ie==="type/boolToInt"||ie==="type/boolToFloat"?zn(de("a",!1))?1:0:ie==="type/intToBool"||ie==="type/floatToBool"?$e(de("a",0))!==0:ie==="type/intToFloat"?$e(de("a",0)):ie==="type/floatToInt"?Math.trunc($e(de("a",0))):void 0}finally{Z.delete(H)}},k=()=>{if(S){S=!1,N=!0;let H=vr(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]),Bt(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<Ya&&Z.push(ie)};for(;Z.length>0&&te.steps<Ya;){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",Fe=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(Fe){case"flow/branch":Le(zn(_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($e(_e("startIndex",0))),Re=Math.trunc($e(_e("endIndex",0))),W=Math.max(1,Math.trunc($e(_e("step",1),1))),D=me.flows?.body;if(D&&Re>ne&&w<Ib){let O=Math.min(Math.ceil((Re-ne)/W),Ya);w++;try{for(let X=0;X<O&&te.steps<Ya;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($e(_e("n",At(me,"stopIterations")??At(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=At(me,"isRandom")?Math.floor(Math.random()*ne.length):h.get(de)||0;Re<ne.length&&(Le(ne[Re]),h.set(de,At(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(At(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,$e(_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,$e(_e("duration",At(me,"duration")??0))),Re=me.flows?.done??me.flows?.out;if(ne<=0){_(de,"lastDelayIndex",-1),Re&&ae(Re);break}g.length>=Rb&&g.shift();let W=v++;_(de,"lastDelayIndex",W),g.push({id:W,nodeIdx:de,rem:ne,done:Re}),Fe==="flow/setDelay"&&me.flows?.out&&me.flows?.done&&Le("out");break}case"flow/cancelDelay":{let ne=Math.trunc($e(_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(At(me,"variable")??At(me,"id"),_e("value")),Le();break;case"variable/interpolate":{let ne=At(me,"variable")??At(me,"id"),Re=_e("value",_e("target")),W=Math.max(0,$e(_e("duration",At(me,"duration")??.3),.3));ne!==void 0&&Re!==void 0&&V({key:`var:${String(ne)}`,varKey:ne,from:Ln(_e("from")??o.get(ne)??0),to:Ln(Re),dur:W,elapsed:0,quat:!1,linear:At(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,$e(_e("duration",At(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:Ln(D),to:Ln(Re),dur:W,elapsed:0,quat:ne.endsWith("/rotation"),linear:At(me,"easing")==="linear",done:me.flows?.done}))}Le();break}case"animation/start":{let ne=_e("animation")??At(me,"animation")??At(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?.(),Fe==="animation/resetAt"&&e?.evaluateAnimation?.($e(_e("time",0))),N=!0,Le();break;case"event/send":case"customEvent/send":{let ne=R(At(me,"event")??At(me,"id")),Re={};for(let W of Object.keys(me.values||{}))dr.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=At(ae,"nodeIndex")??At(ae,"node")??Q(ie,"nodeIndex",void 0,new Set),me=At(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=[$e(H.hitPoint[0]),$e(H.hitPoint[1]),$e(H.hitPoint[2])];_(ie,"hitPoint",Se),_(ie,"point",Se),_(ie,"intersectionPoint",Se)}if(Array.isArray(H.normal)){let Se=[$e(H.normal[0]),$e(H.normal[1],1),$e(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>=Lb)){A++;try{let ae=R(H);i.forEach((ie,de)=>{if(!/^(customE|e)vent\/receive$/.test(C(ie)))return;let me=At(ie,"event")??At(ie,"id");if(!(R(me)!==ae&&String(me)!==String(H))){for(let[Se,Fe]of Object.entries(te))dr.has(Se)||_(de,Se,Ln(Fe));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?$r(ie.elapsed/ie.dur):1,me=ie.linear?de:de*de*(3-2*de),Se=Mm(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()}}},Kn=new WeakMap,Qa=new WeakMap;function Nb(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||as().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=(Qa.get(e)||0)+n,s=!1;for(let o=0;o<i.length;o++){let l=i[o],c=Qd(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=$e(y.translation[0]),m=$e(y.translation[1]),h=$e(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){Qa.set(e,a);let o=vr(r);e.worldMatrices=o;for(let l of e.meshes||[])l.nodeIndex>=0&&l.nodeIndex<o.length&&(l.transform.set(o[l.nodeIndex]),Bt(l.normalMatrix,l.transform))}}function Za(e){if(!(!e||typeof e!="object"))return Kn.get(e)||Kn.get(e.viewer)||Kn.get(e._view)}function Mu(e,t,r){let i=Za(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var Au={name:"khr-interactivity",sendInteractivityEvent:Mu,getInteractivityVM:Za,onLoadModel(e,t){if(!e||typeof e!="object")return;Kn.get(e)?.dispose(),Kn.delete(e),Qa.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 Bi(e,t,i);Kn.set(e,n),n.fireOnStart()},onMeshSelect(e,t){Kn.get(e)?.fireOnSelect(t)},onUpdate(e,t){Kn.get(e)?.tick(t),Nb(e,t)},onDestroy(e,t){Kn.get(t)?.dispose(),Kn.delete(t),Qa.delete(t)}},Fi=new Map,ec=new WeakMap;function _m(e,t){Fi.set(e,t)}var Tu={name:"materials",onContextRestored(e){ec.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=ec.get(e);r||(r=e.createTexture(),ec.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&&Fi.has(t.name)){let g=Fi.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);
392
467
  vec3 refractedR=refract(-V,N,1./(iorB-.02*dV)),rG=refract(-V,N,1./iorB),refractedB=refract(-V,N,1./(iorB+.02*dV));
393
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);
394
- vec3 aCol=vec3(${c(v[0],1,0,1)},${c(v[1],1,0,1)},${c(v[2],1,0,1)});
395
- vec3 volumeAtten=exp(-tV*(vec3(1.)-aCol)/max(${b},.001));
396
- diffuseIBL=mix(diffuseIBL,tr*volumeAtten*base.rgb,${m});`)}if(s&&!i.includes("uClearcoat")){let m=c(s.clearcoatFactor,1,0,1),g=c(s.clearcoatRoughnessFactor,0,0,1);h=h.replace("fragColor=vec4(color,base.a);",`vec3 ccF=F_SchlickRoughness(vec3(.04),${g},NoV)*${m};color=color*(vec3(1.)-ccF)+getStudioRadiance(R,${g})*ccF;fragColor=vec4(color,base.a);`)}if(l){let m=Array.isArray(l.sheenColorFactor)?l.sheenColorFactor:[1,1,1],g=`color+=vec3(${c(m[0],1,0,1)},${c(m[1],1,0,1)},${c(m[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&&qn.has(o.name)&&qn.get(o.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let o=fi.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)}}}},ya=64*1024*1024,ga=128*1024*1024,ou=16777216;function su(e){return(e>>>1^-(e&1))&255}function au(e){return(e>>>1^-(e&1))&65535}function cu(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function xa(e){return(e<<1^e>>31)>>>0}function Ta(e){if(e!==void 0&&e!=="NONE"&&e!=="OCTAHEDRAL"&&e!=="QUATERNION"&&e!=="EXPONENTIAL"&&e!=="COLOR")throw Ee(`unknown filter "${String(e)}"`)}var Ae=Math.fround;function hn(e){return Math.trunc(Ae(e+(e>=0?.5:-.5)))}function Ao(e,t,r,i="NONE"){if(Ta(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 Ee(`OCTAHEDRAL filter requires byteStride 4 or 8 (got ${r})`);let c=r===8,f=c?32767:127,p=x=>c?n.getInt16(x,!0):n.getInt8(x),m=(x,b)=>c?n.setInt16(x,b,!0):n.setInt8(x,b<<24>>24),g=c?2:1;for(let x=0;x<t;x++){let b=x*r,v=p(b),d=p(b+g),y=Ae(p(b+2*g)-Math.abs(v)-Math.abs(d)),M=y>=0?0:y;v=Ae(v+(v>=0?M:-M)),d=Ae(d+(d>=0?M:-M));let T=Ae(Math.sqrt(Ae(Ae(Ae(v*v)+Ae(d*d))+Ae(y*y))));if(T===0){m(b,0),m(b+g,0),m(b+2*g,f);continue}let V=Ae(f/T);m(b,hn(Ae(v*V))),m(b+g,hn(Ae(d*V))),m(b+2*g,hn(Ae(y*V)))}return}if(i==="QUATERNION"){if(r!==8)throw Ee(`QUATERNION filter requires byteStride 8 (got ${r})`);let c=Ae(32767/Ae(Math.SQRT2));for(let f=0;f<t;f++){let p=f*8,m=n.getInt16(p+6,!0),g=m|3,x=n.getInt16(p,!0),b=n.getInt16(p+2,!0),v=n.getInt16(p+4,!0),d=Ae(g*g),y=Ae(Ae(Ae(Ae(d*2)-Ae(x*x))-Ae(b*b))-Ae(v*v)),M=Ae(Math.sqrt(y>=0?y:0)),T=Ae(c/g),V=m&3,X=[0,0,0,0];X[V+1&3]=hn(Ae(x*T)),X[V+2&3]=hn(Ae(b*T)),X[V+3&3]=hn(Ae(v*T)),X[V]=Math.trunc(Ae(Ae(M*T)+.5));for(let P=0;P<4;P++)n.setInt16(p+P*2,X[P]<<16>>16,!0)}return}if(i==="EXPONENTIAL"){if(r<4||r%4!==0)throw Ee(`EXPONENTIAL filter requires byteStride multiple of 4 (got ${r})`);let c=t*r>>>2;for(let f=0;f<c;f++){let p=f*4,m=n.getUint32(p,!0),g=m<<8>>8,x=m>>24;n.setUint32(p,x+127<<23>>>0,!0);let b=n.getFloat32(p,!0);n.setFloat32(p,Ae(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=c=>s?n.getUint16(c,!0):n.getUint8(c),a=c=>s?n.getInt16(c,!0):n.getInt8(c),u=(c,f)=>s?n.setUint16(c,f&65535,!0):n.setUint8(c,f&255),h=s?2:1;for(let c=0;c<t;c++){let f=c*r,p=o(f+3*h);p|=p>>1,p|=p>>2,p|=p>>4,p|=p>>8;let m=o(f),g=a(f+h),x=a(f+2*h),b=m+g-x,v=m+x,d=m-g-x,y=o(f+3*h);y=y<<1&p|y&1;let M=p===0?0:Ae(l/p);u(f,Math.trunc(Ae(Ae(b*M)+.5))),u(f+h,Math.trunc(Ae(Ae(v*M)+.5))),u(f+2*h,Math.trunc(Ae(Ae(d*M)+.5))),u(f+3*h,Math.trunc(Ae(Ae(y*M)+.5)))}}var Aa=160,ht=16,uu=24,wa=32,lu=24,mu=[0,2,4,8],fu=[0,1,2,4,8];function Sa(e){let t=Math.floor(8192/e)&~(ht-1);return t<256?t:256}function Ee(e){return new Error(`EXT_meshopt_compression: ${e}`)}function du(e,t,r,i,n){if(n===0)return r.fill(0,i,i+ht),t;if(n===8)return r.set(e.subarray(t,t+ht),i),t+ht;let s=(1<<n)-1,l=8/n,o=t+ht*n/8;for(let a=0;a<ht;a++){let u=e[t+Math.floor(a/l)],h=a%l,c=n===1?u>>h&1:u>>8-n-h*n&s;r[i+a]=c===s?e[o++]:c}return o}function va(e,t,r,i,n,s,l,o){let a=s/ht,u=a+3>>2;if(r-t<u)throw Ee("truncated ATTRIBUTES stream");let h=t;t+=u;for(let c=0;c<a;c++){if(r-t<uu)throw Ee("truncated ATTRIBUTES stream");let f=e[h+(c>>2)]>>(c&3)*2&3;t=du(e,t,i,n+c*ht,l[o+f])}return t}function hu(e,t,r,i){if(r%4!==0||r>256)throw Ee(`ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let n=e.byteLength;if(n<1)throw Ee("truncated ATTRIBUTES stream");let s=e[0];if((s&240)!==Aa)throw Ee(`unsupported ATTRIBUTES header 0x${s.toString(16)}`);let l=s&15;if(l>1)throw Ee(`unsupported ATTRIBUTES codec version ${l}`);let o=r+(l===0?0:r/4),a=l===0?wa:lu,u=o<a?a:o;if(n-1<u)throw Ee("truncated ATTRIBUTES stream");let h=n-o,c=e.slice(h,h+r),f=h+r,p=Sa(r),m=new Uint8Array(256*4),g=1;for(let x=0;x<t;){let b=Math.min(p,t-x),v=b+ht-1&~(ht-1),d=l===0?0:r/4;if(n-g<d)throw Ee("truncated ATTRIBUTES stream");let y=g;g+=d;for(let M=0;M<r;M+=4){let T=l===0?0:e[y+M/4];for(let P=0;P<4;P++){let R=T>>P*2&3;if(R===3){if(n-g<b)throw Ee("truncated ATTRIBUTES stream");m.set(e.subarray(g,g+b),P*b),g+=b}else R===2?m.fill(0,P*b,P*b+b):g=l===0?va(e,g,n,m,P*b,v,mu,0):va(e,g,n,m,P*b,v,fu,R)}let V=l===0?0:e[f+M/4],X=V&3;if(X===0)for(let P=0;P<4;P++){let R=c[M+P];for(let C=0;C<b;C++)R=su(m[P*b+C])+R&255,i[(x+C)*r+M+P]=R}else if(X===1)for(let P=0;P<4;P+=2){let R=c[M+P]|c[M+P+1]<<8,C=P*b;for(let B=0;B<b;B++){let N=m[C+B]|m[C+b+B]<<8;R=au(N)+R&65535;let w=(x+B)*r+M+P;i[w]=R&255,i[w+1]=R>>8}}else if(X===2){let P=32-(V>>4)&31,R=(c[M]|c[M+1]<<8|c[M+2]<<16|c[M+3]<<24)>>>0;for(let C=0;C<b;C++){let B=(m[C]|m[b+C]<<8|m[2*b+C]<<16|m[3*b+C]<<24)>>>0;B=((B<<P|B>>>(32-P&31))^R)>>>0,R=B;let N=(x+C)*r+M;i[N]=B&255,i[N+1]=B>>>8&255,i[N+2]=B>>>16&255,i[N+3]=B>>>24}}else throw Ee(`invalid ATTRIBUTES channel ${V}`)}c.set(i.subarray((x+b-1)*r,(x+b)*r)),x+=b}if(n-g!==u)throw Ee("ATTRIBUTES trailing data")}var Ea=224,Ra=208;function _a(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 di(e,t,r){let i=_a(e,t),n=i>>>1^-(i&1);return r+n>>>0}function pu(e,t,r){if(t%3!==0)throw Ee(`TRIANGLES count must be divisible by 3 (got ${t})`);let i=t/3;if(e.byteLength<1+i+16)throw Ee("truncated TRIANGLES stream");let n=e[0];if((n&240)!==Ea)throw Ee(`unsupported TRIANGLES header 0x${n.toString(16)}`);let s=n&15;if(s>1)throw Ee(`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,c=(T,V)=>{l[u]=T,o[u]=V,u=u+1&15},f=(T,V=1)=>{a[h]=T,h=h+V&15},p=0,m=0,g=s>=1?13:15,x=1+i,b=e.byteLength-16,v=b,d={pos:x},y=0,M=(T,V,X)=>{r(y++,T),r(y++,V),r(y++,X)};for(let T=1;T<x;T++){let V=e[T];if(V<240){let X=V>>4,P=u-1-X&15,R=l[P],C=o[P],B=0,N=V&15;if(N<g){let w=a[h-1-N&15];B=N===0?p:w;let ie=N===0?1:0;p=p+ie>>>0,f(B,ie)}else{if(d.pos>b)throw Ee("truncated TRIANGLES stream");B=N!==15?m+(N*2-27)>>>0:di(e,d,m),m=B,f(B)}c(B,C),c(R,B),M(R,C,B)}else if(V<254){let X=e[v+(V&15)],P=X>>4,R=X&15,C=p;p=p+1>>>0;let B=a[h-P&15],N=P===0?p:B,w=P===0?1:0;p=p+w>>>0;let ie=a[h-R&15],ae=R===0?p:ie,k=R===0?1:0;p=p+k>>>0,M(C,N,ae),f(C),f(N,w),f(ae,k),c(N,C),c(ae,N),c(C,ae)}else{if(d.pos>b)throw Ee("truncated TRIANGLES stream");let X=e[d.pos++],P=V===254?0:15,R=X>>4,C=X&15;X===0&&(p=0);let B=0;P===0&&(B=p,p=p+1>>>0);let N;R===0?(N=p,p=p+1>>>0):N=a[h-R&15];let w;C===0?(w=p,p=p+1>>>0):w=a[h-C&15],P===15&&(m=B=di(e,d,m)),R===15&&(m=N=di(e,d,m)),C===15&&(m=w=di(e,d,m)),M(B,N,w),f(B),f(N,R===0||R===15?1:0),f(w,C===0||C===15?1:0),c(N,B),c(w,N),c(B,w)}}if(d.pos!==b)throw Ee("TRIANGLES trailing data")}function bu(e,t,r){if(e.byteLength<1+t+4)throw Ee("truncated INDICES stream");let i=e[0];if((i&240)!==Ra)throw Ee(`unsupported INDICES header 0x${i.toString(16)}`);let n=i&15;if(n>1)throw Ee(`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 Ee("truncated INDICES stream");let u=_a(e,o),h=u&1;u>>>=1;let c=u>>>1^-(u&1),f=l[h]+c>>>0;l[h]=f,r(a,f)}if(o.pos!==s)throw Ee("INDICES trailing data")}function wo(e,t,r,i,n="NONE"){if(Ta(n),!Number.isInteger(t)||t<0||t>ou||!Number.isInteger(r)||r<=0||r>256)throw Ee(`invalid count (${t}) or byteStride (${r})`);let s=t*r;if(s>ya)throw Ee(`decompressed size (${s}) exceeds MAX_MESHOPT_BUFFER_BYTES (${ya})`);if(t===0)return new Uint8Array(0);let l=new Uint8Array(s);if(i==="ATTRIBUTES")return hu(e,t,r,l),Ao(l,t,r,n),l;if(i==="TRIANGLES"||i==="INDICES"){if(r!==2&&r!==4)throw Ee(`${i} byteStride must be 2 or 4 (got ${r})`);if(n&&n!=="NONE")throw Ee(`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"?pu(e,t,a):bu(e,t,a),l}throw Ee(`unknown mode "${String(i)}"`)}function Ma(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function La(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=[Aa],a=Sa(r),u=new Uint8Array(r);t>0&&u.set(e.subarray(0,r));let h=u.slice(),c=new Uint8Array(256);for(let f=0;f<t;){let p=Math.min(a,t-f),m=p+15&-16;for(let g=0;g<r;g++){c.fill(0);let x=u[g];for(let d=0;d<p;d++){let y=e[(f+d)*r+g];c[d]=cu(y-x&255),x=y}u[g]=x;let b=m/16,v=o.length;for(let d=0;d<b+3>>2;d++)o.push(0);for(let d=0;d<b;d++){let y=c.subarray(d*16,d*16+16);if(!y.every(M=>M===0)){o[v+(d>>2)]|=3<<(d&3)*2;for(let M of y)o.push(M)}}}f+=p}for(let f=r;f<wa;f++)o.push(0);for(let f=0;f<r;f++)o.push(h[f]);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=[Ra|1],a=0;for(let u=0;u<t;u++){let h=l(u),c=h-a|0;a=h,Ma(o,xa(c)<<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=[Ea|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 c=0;c<3;c++){let f=l(h*3+c);Ma(a,xa(f-u|0)),u=f}}for(let h=0;h<16;h++)a.push(0);return new Uint8Array(a)}throw new Error(`encodeMeshoptBuffer: unknown mode "${String(i)}"`)}function hi(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 c=0;c<i.bufferViews.length;c++){let f=i.bufferViews[c],p=f?.extensions?.KHR_meshopt_compression,m=p??f?.extensions?.EXT_meshopt_compression;if(!m||typeof m!="object")continue;let g=p?"KHR_meshopt_compression":"EXT_meshopt_compression",x=Number(m.count),b=Number(m.byteStride),v=Number(m.byteOffset??0),d=Number(m.byteLength??0),y=m.mode||"ATTRIBUTES",M=m.filter||"NONE";if(M==="COLOR"&&!p)throw Ee(`bufferView ${c} uses the COLOR filter, which requires KHR_meshopt_compression`);if(Number(m.buffer??0)!==0)throw new Error(`${g}: bufferView ${c} references buffer ${String(m.buffer)}; only the GLB BIN chunk (buffer 0) is supported`);if(!Number.isInteger(v)||v<0||!Number.isInteger(d)||d<0||v+d>n.byteLength)throw new Error(`${g}: bufferView ${c} compressed range [${v}, ${v+d}] out of bounds (${n.byteLength})`);let T=x*b;if(l+=T,l>ga)throw Ee(`total decompressed size (${l}) exceeds MAX_MESHOPT_TOTAL_BYTES (${ga})`);let V=n.subarray(v,v+d),X=wo(V,x,b,y,M);s.push({index:c,bytes:X,ext:m})}if(s.length===0)return;let o=n.byteLength+3&-4,a=0;for(let c of s)a+=c.bytes.byteLength+3&-4;let u=new Uint8Array(o+a);u.set(n,0);let h=o;for(let c of s){u.set(c.bytes,h);let f=i.bufferViews[c.index];f.buffer=0,f.byteOffset=h,f.byteLength=c.bytes.byteLength,f._decoded=c.bytes,c.ext.mode==="ATTRIBUTES"&&f.byteStride===void 0&&(f.byteStride=Number(c.ext.byteStride)),f.extensions&&(delete f.extensions.EXT_meshopt_compression,delete f.extensions.KHR_meshopt_compression),h+=c.bytes.byteLength+3&-4}r.bin=u.buffer}var pi={decodeBufferViews(e,t){hi(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}};Me().decoders.set("meshopt",pi);var So={name:"meshopt",onParseGLB(e){Me().decoders.set("meshopt",pi),hi(e)}},yu=`#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&&Fi.has(o.name)&&Fi.get(o.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let o=ec.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)}}}},Em=64*1024*1024,km=128*1024*1024,Db=16777216;function Ub(e){return(e>>>1^-(e&1))&255}function Bb(e){return(e>>>1^-(e&1))&65535}function Fb(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function Rm(e){return(e<<1^e>>31)>>>0}function Im(e){if(e!==void 0&&e!=="NONE"&&e!=="OCTAHEDRAL"&&e!=="QUATERNION"&&e!=="EXPONENTIAL"&&e!=="COLOR")throw ht(`unknown filter "${String(e)}"`)}var ct=Math.fround;function vo(e){return Math.trunc(ct(e+(e>=0?.5:-.5)))}function _u(e,t,r,i="NONE"){if(Im(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 ht(`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=ct(p(y+2*x)-Math.abs(A)-Math.abs(b)),S=w>=0?0:w;A=ct(A+(A>=0?S:-S)),b=ct(b+(b>=0?S:-S));let E=ct(Math.sqrt(ct(ct(ct(A*A)+ct(b*b))+ct(w*w))));if(E===0){g(y,0),g(y+x,0),g(y+2*x,h);continue}let N=ct(h/E);g(y,vo(ct(A*N))),g(y+x,vo(ct(b*N))),g(y+2*x,vo(ct(w*N)))}return}if(i==="QUATERNION"){if(r!==8)throw ht(`QUATERNION filter requires byteStride 8 (got ${r})`);let m=ct(32767/ct(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=ct(x*x),w=ct(ct(ct(ct(b*2)-ct(v*v))-ct(y*y))-ct(A*A)),S=ct(Math.sqrt(w>=0?w:0)),E=ct(m/x),N=g&3,C=[0,0,0,0];C[N+1&3]=vo(ct(v*E)),C[N+2&3]=vo(ct(y*E)),C[N+3&3]=vo(ct(A*E)),C[N]=Math.trunc(ct(ct(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 ht(`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,ct(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:ct(s/p);c(h,Math.trunc(ct(ct(y*S)+.5))),c(h+f,Math.trunc(ct(ct(A*S)+.5))),c(h+2*f,Math.trunc(ct(ct(b*S)+.5))),c(h+3*f,Math.trunc(ct(ct(w*S)+.5)))}}var Cm=160,Jn=16,Vb=24,Nm=32,Ob=24,zb=[0,2,4,8],$b=[0,1,2,4,8];function Dm(e){let t=Math.floor(8192/e)&~(Jn-1);return t<256?t:256}function ht(e){return new Error(`EXT_meshopt_compression: ${e}`)}function Gb(e,t,r,i,n){if(n===0)return r.fill(0,i,i+Jn),t;if(n===8)return r.set(e.subarray(t,t+Jn),i),t+Jn;let a=(1<<n)-1,s=8/n,o=t+Jn*n/8;for(let l=0;l<Jn;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 Lm(e,t,r,i,n,a,s,o){let l=a/Jn,c=l+3>>2;if(r-t<c)throw ht("truncated ATTRIBUTES stream");let f=t;t+=c;for(let m=0;m<l;m++){if(r-t<Vb)throw ht("truncated ATTRIBUTES stream");let h=e[f+(m>>2)]>>(m&3)*2&3;t=Gb(e,t,i,n+m*Jn,s[o+h])}return t}function jb(e,t,r,i){if(r%4!==0||r>256)throw ht(`ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let n=e.byteLength;if(n<1)throw ht("truncated ATTRIBUTES stream");let a=e[0];if((a&240)!==Cm)throw ht(`unsupported ATTRIBUTES header 0x${a.toString(16)}`);let s=a&15;if(s>1)throw ht(`unsupported ATTRIBUTES codec version ${s}`);let o=r+(s===0?0:r/4),l=s===0?Nm:Ob,c=o<l?l:o;if(n-1<c)throw ht("truncated ATTRIBUTES stream");let f=n-o,m=e.slice(f,f+r),h=f+r,p=Dm(r),g=new Uint8Array(256*4),x=1;for(let v=0;v<t;){let y=Math.min(p,t-v),A=y+Jn-1&~(Jn-1),b=s===0?0:r/4;if(n-x<b)throw ht("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 ht("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?Lm(e,x,n,g,_*y,A,zb,0):Lm(e,x,n,g,_*y,A,$b,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=Ub(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=Bb(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 ht(`invalid ATTRIBUTES channel ${N}`)}m.set(i.subarray((v+y-1)*r,(v+y)*r)),v+=y}if(n-x!==c)throw ht("ATTRIBUTES trailing data")}var Um=224,Bm=208;function Fm(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 tc(e,t,r){let i=Fm(e,t),n=i>>>1^-(i&1);return r+n>>>0}function Hb(e,t,r){if(t%3!==0)throw ht(`TRIANGLES count must be divisible by 3 (got ${t})`);let i=t/3;if(e.byteLength<1+i+16)throw ht("truncated TRIANGLES stream");let n=e[0];if((n&240)!==Um)throw ht(`unsupported TRIANGLES header 0x${n.toString(16)}`);let a=n&15;if(a>1)throw ht(`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 ht("truncated TRIANGLES stream");$=F!==15?g+(F*2-27)>>>0:tc(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 ht("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=$=tc(e,b,g)),P===15&&(g=F=tc(e,b,g)),R===15&&(g=V=tc(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 ht("TRIANGLES trailing data")}function Wb(e,t,r){if(e.byteLength<1+t+4)throw ht("truncated INDICES stream");let i=e[0];if((i&240)!==Bm)throw ht(`unsupported INDICES header 0x${i.toString(16)}`);let n=i&15;if(n>1)throw ht(`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 ht("truncated INDICES stream");let c=Fm(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 ht("INDICES trailing data")}function Eu(e,t,r,i,n="NONE"){if(Im(n),!Number.isInteger(t)||t<0||t>Db||!Number.isInteger(r)||r<=0||r>256)throw ht(`invalid count (${t}) or byteStride (${r})`);let a=t*r;if(a>Em)throw ht(`decompressed size (${a}) exceeds MAX_MESHOPT_BUFFER_BYTES (${Em})`);if(t===0)return new Uint8Array(0);let s=new Uint8Array(a);if(i==="ATTRIBUTES")return jb(e,t,r,s),_u(s,t,r,n),s;if(i==="TRIANGLES"||i==="INDICES"){if(r!==2&&r!==4)throw ht(`${i} byteStride must be 2 or 4 (got ${r})`);if(n&&n!=="NONE")throw ht(`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"?Hb(e,t,l):Wb(e,t,l),s}throw ht(`unknown mode "${String(i)}"`)}function Pm(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function Vm(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=[Cm],l=Dm(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]=Fb(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<Nm;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=[Bm|1],l=0;for(let c=0;c<t;c++){let f=s(c),m=f-l|0;l=f,Pm(o,Rm(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=[Um|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);Pm(l,Rm(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 nc(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 ht(`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>km)throw ht(`total decompressed size (${s}) exceeds MAX_MESHOPT_TOTAL_BYTES (${km})`);let N=n.subarray(A,A+b),C=Eu(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 rc={decodeBufferViews(e,t){nc(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}};He().decoders.set("meshopt",rc);var ku={name:"meshopt",onParseGLB(e){He().decoders.set("meshopt",rc),nc(e)}},Xb=`#version 300 es
397
472
  layout(location=0) in vec3 aPosition;
398
473
  layout(location=1) in vec3 aNormal;
399
474
  uniform mat4 uMVP,uVP;
@@ -414,19 +489,19 @@ vec2 pxOffset=dir*(uOutlineThickness*2.0/max(uViewportSize,vec2(1.0)))*clipPos.w
414
489
  clipPos.xy+=pxOffset;
415
490
  clipPos.z+=1e-4*clipPos.w;
416
491
  gl_Position=clipPos;
417
- }`,gu=`#version 300 es
492
+ }`,qb=`#version 300 es
418
493
  precision highp float;
419
494
  uniform vec4 uOutlineColor;
420
495
  out vec4 fragColor;
421
496
  void main(){
422
497
  fragColor=uOutlineColor;
423
- }`,Ia=`#version 300 es
498
+ }`,Om=`#version 300 es
424
499
  out vec2 vUV;
425
500
  void main(){
426
501
  vec2 pos=vec2((gl_VertexID<<1)&2,gl_VertexID&2);
427
502
  vUV=pos;
428
503
  gl_Position=vec4(pos*2.0-1.0,0.0,1.0);
429
- }`,xu=`#version 300 es
504
+ }`,Yb=`#version 300 es
430
505
  precision highp float;
431
506
  in vec2 vUV;
432
507
  uniform sampler2D uSourceTex;
@@ -449,7 +524,7 @@ c+=prefilter(texture(uSourceTex,vUV+vec2(h.x,-h.y)).rgb)*0.125;
449
524
  c+=prefilter(texture(uSourceTex,vUV+vec2(-h.x,h.y)).rgb)*0.125;
450
525
  c+=prefilter(texture(uSourceTex,vUV+vec2(h.x,h.y)).rgb)*0.125;
451
526
  fragColor=vec4(c,1.0);
452
- }`,vu=`#version 300 es
527
+ }`,Kb=`#version 300 es
453
528
  precision highp float;
454
529
  in vec2 vUV;
455
530
  uniform sampler2D uBloomTex;
@@ -471,4 +546,674 @@ sum+=texture(uBloomTex,vUV+vec2(-d.x,-d.y)).rgb*2.0;
471
546
  vec3 bloom=(sum/12.0)*uStrength;
472
547
  float a=clamp(min(bloom.r,min(bloom.g,bloom.b)),0.0,1.0);
473
548
  fragColor=vec4(bloom,a);
474
- }`,bi=3,Yn=new WeakMap;function Eo(e,t=[.22,.74,.97]){let r=Vi(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 Pa(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),c=Math.max(0,Math.min(2*h,a-u+h)),f=c*c/(4*h+1e-4),p=Math.min(1,Math.max(0,Math.max(f,a-u)/Math.max(a,1e-4)))*n;return[s*p,l*p,o*p]}function Na(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 Ca=new WeakSet;function Da(e){let t=Yn.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;Yn.delete(e)}if(Ca.has(e)||e.isContextLost?.())return null;let r=Dt(e,yu,gu,!1),i=Dt(e,Ia,xu,!1),n=Dt(e,Ia,vu,!1);if(!r||!i||!n){for(let l of[r,i,n])l&&e.deleteProgram(l);return Ca.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},Yn.set(e,t),t}function Mu(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===bi&&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<bi;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 Tu(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=Bi({strength:s,threshold:mn(t.getAttribute("bloom-threshold"),.62),radius:mn(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=Bi(n);s&&(!r||s.strength>r.strength)&&(r=s)}return r}function Au(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 lr({color:n,thickness:s,pulse:l})}var wu=new Set(["floor","pedestal","ground","table","grid","pad"]);function Su(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>wu.has(t))}function Eu(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=lr(n);if(s)return s;let l=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",o=Au(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?lr({color:l,thickness:3,pulse:!1}):null);if(o){let h=t.name||"";return Su(h)?null:o}return null}var Ro={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 f of t.meshes){if(f.visible===!1)continue;let p=Eu(t,f);p&&s.push({mesh:f,trait:p})}let l=s.length>0?Da(e):null;if(l){let f=l,p=Se(),m=Se(),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),d=Math.max(1,b?.[3]||n);e.useProgram(f.outlineProg),f.uOutlineViewportSize&&e.uniform2f(f.uOutlineViewportSize,v,d),f.uOutlineVP&&e.uniformMatrix4fv(f.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[T,V,X]=Eo(M.color),P=M.pulse?.8+.25*Math.sin(x*4):1;f.uOutlineColor&&e.uniform4f(f.uOutlineColor,T,V,X,1),f.uOutlineThickness&&e.uniform1f(f.uOutlineThickness,M.thickness*P),y.worldSpace===!0?p.set(y.transform):Pe(p,t.modelRootMatrix,y.transform);let R=y.instanceMatrices;for(let C of y.primitives)if(!(C.pluginData?.skinning?.hasSkin||C.pluginData?.morph?.hasMorph))if(e.bindVertexArray(C.vao),R&&R.length>=16){let B=R.length>>4,N=Se();for(let w=0;w<B;w++)Pe(N,p,R.subarray(w*16,w*16+16)),Pe(m,r,N),ze(g,N),e.uniformMatrix4fv(f.uOutlineMVP,!1,m),e.uniformMatrix3fv(f.uOutlineNormalMatrix,!1,g),C.indices?e.drawElements(4,C.indexCount,C.indexType,0):e.drawArrays(4,0,C.indexCount)}else Pe(m,r,p),ze(g,p),e.uniformMatrix4fv(f.uOutlineMVP,!1,m),e.uniformMatrix3fv(f.uOutlineNormalMatrix,!1,g),C.indices?e.drawElements(4,C.indexCount,C.indexType,0):e.drawArrays(4,0,C.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=Tu(t);if(!o||o.strength<=0)return;let a=Da(e);if(!a||!Mu(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,c=n;for(let f=0;f<bi;f++){let p=a.mipWidth[f],m=a.mipHeight[f];e.bindFramebuffer(36160,a.bloomFbo[f]),e.viewport(0,0,p,m),e.bindTexture(3553,u),e.uniform2f(a.uDownTexelSize,1/h,1/c),e.uniform1f(a.uDownThreshold,f===0?o.threshold:0),e.drawArrays(4,0,3),u=a.bloomTex[f],h=p,c=m}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 f=bi-1;f>=1;f--){let p=f-1;e.bindFramebuffer(36160,a.bloomFbo[p]),e.viewport(0,0,a.mipWidth[p],a.mipHeight[p]),e.bindTexture(3553,a.bloomTex[f]),e.uniform2f(a.uUpTexelSize,1/a.mipWidth[f],1/a.mipHeight[f]),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=Yn.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);Yn.delete(e)}}};function _o(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 ka(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 Oa(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=_o(s).indexOf(o);if(a<0)return i;for(let u of l)if(u.variants.includes(a))return u.material;return i}var Lo={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},Ua=new WeakMap,Io={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=Ua.get(t);if(n||(n={lightProbe:null},Ua.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&&si(e.gl,s.sphericalHarmonicsCoefficients)}}}};Ue(Wn),Ue(yo),Ue(ho),Ue(To),Ue(Io),Ue(Mo),Ue(So),Ue(Lo),Ue(Ro),Ue(Ii),ft.registerScriptRunner(ln),typeof window<"u"&&(window.ThreeLiveBundle=Co);
549
+ }`,oc=3,Vi=new WeakMap;function Ru(e,t=[.22,.74,.97]){let r=Qc(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 Gm(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 jm(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 zm=new WeakSet;function $m(e){let t=Vi.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;Vi.delete(e)}if(zm.has(e)||e.isContextLost?.())return null;let r=ir(e,Xb,qb,!1),i=ir(e,Om,Yb,!1),n=ir(e,Om,Kb,!1);if(!r||!i||!n){for(let s of[r,i,n])s&&e.deleteProgram(s);return zm.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},Vi.set(e,t),t}function Jb(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===oc&&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<oc;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 Qb(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=Zc({strength:a,threshold:ao(t.getAttribute("bloom-threshold"),.62),radius:ao(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=Zc(n);a&&(!r||a.strength>r.strength)&&(r=a)}return r}function Zb(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 Ms({color:n,thickness:a,pulse:s})}var ey=new Set(["floor","pedestal","ground","table","grid","pad"]);function ty(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>ey.has(t))}function ny(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=Ms(n);if(a)return a;let s=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",o=Zb(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?Ms({color:s,thickness:3,pulse:!1}):null);if(o){let f=t.name||"";return ty(f)?null:o}return null}var Lu={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=ny(t,h);p&&a.push({mesh:h,trait:p})}let s=a.length>0?$m(e):null;if(s){let h=s,p=rt(),g=rt(),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]=Ru(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):at(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=rt();for(let V=0;V<$;V++)at(F,p,P.subarray(V*16,V*16+16)),at(g,r,F),Bt(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 at(g,r,p),Bt(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=Qb(t);if(!o||o.strength<=0)return;let l=$m(e);if(!l||!Jb(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<oc;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=oc-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=Vi.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);Vi.delete(e)}}},Ao=4,Cu=9,ry=32*1024*1024,ac=rt(),Hm=new Int32Array([-1,-1]);function Pu(e,t,r,i){let n=Number(e);return Number.isFinite(n)?Math.max(t,Math.min(r,n)):i}var Wm=new WeakMap,hr=new WeakMap,zi=new WeakMap,Mo=rt(),ic=rt(),pr=rt(),wo=rt(),Ym=new Float32Array(1),oy=new Uint32Array(Ym.buffer);function Nu(e){if(typeof e!="string")return"auto";let t=e.trim().toLowerCase();return t==="pcf"||t==="off"?t:"auto"}function iy(e){let t=Wm.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 Wm.set(e,l),l}function So(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 Du(e){let t=e||{},r=t.modelRootMatrix??ac,i=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let m of t.meshes??[]){if(!Fu(m))continue;m.worldSpace===!0?pr.set(m.transform):at(pr,r,m.transform);let h=m.instanceMatrices;for(let p of m.primitives??[]){if(!p.positions||p.positions.length<3)continue;let g=iy(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)at(wo,pr,h.subarray(y*16,y*16+16)),So(g,wo,i,n);if(v>1){let y=x-1;at(wo,pr,h.subarray(y*16,y*16+16)),So(g,wo,i,n)}}else So(g,pr,i,n)}}if(!Number.isFinite(i[0])){let m=t.bounds;m&&Array.isArray(m.min)&&Array.isArray(m.max)&&So([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 Uu(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];xr(Mo,h,r.center,p);let g=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0];So([...r.min,...r.max],Mo,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 yd(ic,g[0]-v,Math.max(g[0]+.05,x[0])+v,g[1]-v,Math.max(g[1]+.05,x[1])+v,y,A),at(e,ic,Mo)}function sc(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];xr(Mo,[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];So([...a.min,...a.max],Mo,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 Oo(ic,C,1,N,Math.max(N+.1,S)),at(e,ic,Mo)}function Bu(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??ac,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 Fu(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 Gr(e,t){if(!Fu(e))return!1;let r=e.castShadow??e.extras?.shadow?.cast;return r===!1?!1:t?!0:r===!0}function $i(e,t){if(!e||typeof e!="object")return!1;let r=e;if(!Fu(r))return!1;let i=r.receiveShadow??r.extras?.shadow?.receive;return i!==void 0?!!i:t}function Iu(e){return!(e.isTransmissive||e.alphaMode==="BLEND"||(e.baseColor?.[3]??1)<.98)}function fr(e,t){return Math.imul((e^t>>>0)>>>0,16777619)>>>0}function mr(e,t){return Ym[0]=t||0,fr(e,oy[0])}function Oi(e,t,r=64){let i=t.length;if(e=fr(e,i),i<=r)for(let n=0;n<i;n++)e=mr(e,t[n]);else{let n=Math.max(1,Math.floor(i/r));for(let a=0;a<i;a+=n)e=mr(e,t[a]);e=mr(e,t[i-1])}return e}function Gi(e){let t=e||{},r=t.shadowMaps??t.container?.getAttribute?.("shadow-maps")??"auto",i=Nu(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<Ao&&o.push({kind:"directional",subIdx:m,light:$}),m++):($.type==="spot"||$.type==="point")&&h<2&&(c||(c={kind:$.type,light:$}),$.shadow?.cast&&o.length<Ao&&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(Gr($,x)){for(let F of $.primitives??[])if(Iu(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>ry;)b=Math.max(256,b>>1);let S=Du(t),E=S.radius*2.2/b,N=[];for(let $=0;$<o.length;$++){let F=o[$],V=F.light,Y=V.shadow,J=rt(),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],Uu(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));sc(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],sc(J,G,re,Math.PI/3,V.range,S)}}let Q=Pu(Y?.bias,-.05,.05,-5e-4),ee=Pu(Y?.normalBias,0,.5,.015),k=Pu(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=Bu(t),_=2166136261;_=fr(_,i==="pcf"?2:1),_=fr(_,b),_=fr(_,N.length);for(let $ of N)_=Oi(_,$.viewProj,16),_=mr(_,$.depthBias),_=mr(_,$.normalBiasWorld);C?.enabled?(_=fr(_,1),_=mr(_,C.normal[0]),_=mr(_,C.normal[1]),_=mr(_,C.normal[2]),_=mr(_,C.constant)):_=fr(_,0);let P=t.modelRootMatrix??ac;_=Oi(_,P,16);let R=0;for(let $ of p){if(!Gr($,x)){R++;continue}_=fr(_,R++),_=Oi(_,$.transform,16),$.instanceMatrices&&(_=Oi(_,$.instanceMatrices,64));for(let F of $.primitives??[])Iu(F)&&(_=fr(_,F.indexCount),F.translations&&(_=Oi(_,F.translations,48)))}return _===0&&(_=1),{mode:i,mapSize:b,slices:N,dirSlots:n,ptSlots:a,promoteAllCasters:x,promoteAllReceivers:v,digest:_,sectionPlane:C}}function Km(e){let t=hr.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 sy=`#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
+ }`,ay=`#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
+ }`,cy=`
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
+ }`,ly=["uShadowMap","uShadowVP","uShadowParams","uDirShdSlot","uPtShdSlot","uReceiveShadow"];function uy(e){let t=hr.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},hr.set(e,t)),t}function Jm(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 Qm(e){let t=zi.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,sy),e.compileShader(i),e.shaderSource(n,ay),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:Jm(e,1,1)},zi.set(e,t),t}var Xm={uniformsGLSL:cy,dirGLSL:"*shdEval(uDirShdSlot[i],vWorldPos,N,normalize(uDirLightDir[i]))",ptGLSL:"*shdEval(uPtShdSlot[i],vWorldPos,N,L)",uniformNames:ly,bind(e,t,r,i){let n=t.uShadowMap;if(n===void 0)return;let a=r&&typeof r=="object"?hr.get(r):void 0,s=Qm(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,Cu);let c=t.uDirShdSlot,f=t.uPtShdSlot,m=t.uReceiveShadow;if(!o){c&&e.uniform1iv?.(c,Hm),f&&e.uniform1iv?.(f,Hm),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,$i(i,a.promoteAllReceivers)?1:0)}};function qm(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}var Vu={name:"shadow-maps",onRegister(){He().shadowMapShader=Xm},onLoadModel(e){if(e&&typeof e=="object"){let t=hr.get(e);t&&(t.lastDigest=0)}},onClearScene(e){if(e&&typeof e=="object"){let t=hr.get(e);t&&(t.lastDigest=0,t.activeLights=0)}},onContextRestored(e,t){if(zi.delete(e),t&&typeof t=="object"){let r=hr.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=hr.get(t);r&&(r.texArray&&e.deleteTexture?.(r.texArray),r.fbo&&e.deleteFramebuffer?.(r.fbo),hr.delete(t))}else if(e){let r=zi.get(e);r&&(r.prog&&e.deleteProgram?.(r.prog),r.dummyArrayTex&&e.deleteTexture?.(r.dummyArrayTex),zi.delete(e))}},onBeforeDrawScene(e,t){if(!e||typeof e!="object")return;let r=e,i=He();if(i.shadowMapShader||(i.shadowMapShader=Xm),r.uRender&&!("uShadowMap"in r.uRender)&&r.recompileRenderProgram?.(),i.gpuSceneAccelerator?.willRenderScene?.(e))return;let n=uy(e),a=Gi(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=Qm(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=Jm(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??ac,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(!Gr(g,a.promoteAllCasters))continue;g.worldSpace===!0?pr.set(g.transform):at(pr,m,g.transform);let x=g.instanceMatrices;for(let v of g.primitives??[])if(!(!v.vao||v.indexCount<=0||!Iu(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,pr),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++)at(wo,pr,x.subarray(A*16,A*16+16)),s.uModel&&t.uniformMatrix4fv(s.uModel,!1,wo),qm(t,v)}else qm(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 Ou(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 Zm(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 eh(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=Ou(a).indexOf(o);if(l<0)return i;for(let c of s)if(c.variants.includes(l))return c.material;return i}var zu={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},th=new WeakMap,$u={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=th.get(t);if(n||(n={lightProbe:null},th.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&&qa(e.gl,a.sphericalHarmonicsCoefficients)}}}};gt(Di),gt(Vu),gt(vu),gt(yu),gt(Tu),gt($u),gt(Au),gt(ku),gt(zu),gt(Lu),gt(Vc);var rh=272,dy=["x","y","z","w"],oh=[[2,"vec2<f32>"],[3,"vec3<f32>"],[4,"vec4<f32>"]];function To(e,t){return oh.map(([r,i])=>{let n=dy.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 nh(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);}",...To("_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);}",...To("_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);}",...To("_tslPow",2)),e.clamp&&r.push("fn _tslClamp1(a:f32,b:f32,c:f32)->f32{return clamp(a,min(b,c),max(b,c));}",...To("_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);}",...To("_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);}",...To("_tslAtan",2)),e.norm&&r.push("fn _tslNorm1(v:f32)->f32{return select(0.0,sign(v),abs(v)>1e-6);}",...oh.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 fy={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function Gu(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=Wt(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(Un);v=l==="float"?y[0]:`${l}<f32>(${y.join(",")})`;break}case"builtin":v=o.builtin==="time"?`_tslMod1(tslU.timeAndPad.x,${Un(3600)})`:fy[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 cc(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=nh(ti(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
+ ${Gu(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
+ ${Gu(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=nh(ti(e.nodes,e.vertexReachable,e.usesTime),!1),f=Gu(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 Wi=new WeakMap,_o=new WeakMap,ih=new WeakMap,ji=new Map,my=128;function hy(e,t){let r=ih.get(t);return r||(r={paramsLoc:e.getUniformLocation(t,"uTslParams[0]")??e.getUniformLocation(t,"uTslParams"),timeLoc:e.getUniformLocation(t,"uTslTime")},ih.set(t,r)),r}function py(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 Hi(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?.[Br];if(!f)continue;let m=typeof c.name=="string"&&c.name.length>0?c.name:`Material_${l}`,h=Sr(f,m);if(!h.ok){console.warn(`[three-live] [${h.issue.code}] ${h.issue.message} Falling back to base PBR material.`);continue}let p=py(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};Wi.set(e,s);let o=e.gl;return o&&typeof o=="object"&&_o.set(o,s),s}function sh(e,t){let r=Wi.get(e);if(!r){let i=t??e.gltf;if(!i)return null;r=Hi(e,i)}return r}function by(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 ju(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=sh(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=by(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=ei(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 lc(e){if(!e||typeof e!="object")return;let t=e;typeof t.setMaterialUniform!="function"&&(t.setMaterialUniform=(r,i,n)=>ju(e,r,i,n))}function yy(){let e=He();jn(Zo);let t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t?Zo(t,e):e.authorNamespace||(e.authorNamespace={}),e.tslWgslCompiler=(r,i,n)=>!r||typeof r!="object"?null:cc(r,i,n),e.tslMaterialResolver=(r,i)=>i===void 0||i<0?null:sh(r)?.materialsByIndex.get(i)??null,e.tslUsdzSerializer=Ss}var uc={name:"tsl",onRegister(){yy()},onElementConnected(e){lc(e),e?.viewer&&(lc(e.viewer),e.viewer.gltf&&(Hi(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?.[Br];if(!a)return null;let s=Sr(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?.[Br];if(!n)return null;let a=Sr(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=ji.get(s);if(!o){if(ji.size>=my){let l=ji.keys().next().value;l!==void 0&&ji.delete(l)}o=ws(a.graph,r,i),ji.set(s,o)}return o},onLoadModel(e,t){lc(e),e?.container&&lc(e.container),Hi(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=Wi.get(e);if(!r||!r.hasAnimatedTsl)return;let i=Number.isFinite(t)&&t>0?Math.min(t,.25):0;r.elapsedSec=vs(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?.[Br])return;let o=hy(e,t);if(!o.paramsLoc&&!o.timeLoc)return;let l=_o.get(e);l||(l=Hi(e,a),_o.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){Wi.delete(e),e?.gl&&typeof e.gl=="object"&&_o.delete(e.gl)},onContextRestored(e,t){if(t?.gltf){let r=Hi(t,t.gltf);e&&typeof e=="object"&&_o.set(e,r)}},onDestroy(e,t){Wi.delete(t),e&&typeof e=="object"&&_o.delete(e)}};gt(uc);var jr=800,qi=32,Yi=128,Eo=8,Hr=32;function Xi(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 Ki(e,t){let r=new Float32Array(e,0,200),i=new Uint32Array(e,0,200),n=new Int32Array(e,0,200);r.fill(0),Xi(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;Xi(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 ah(e,t,r,i,n,a){let s=new Float32Array(e,0,44),o=new Uint32Array(e,0,44);s.fill(0),Xi(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 Hu=`
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
+ `,Ji=Hu+`
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
+ `,dc=Hu+`
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
+ `,fc=Hu+`
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
+ `,Wu=`
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
+ `,lh=1,br=8,My=16,Ay=32,vc=64,Ty=128,_y=1,Mh=2,bc=4,Pr=16,Ey=1,Qi=1,Qn=2,Xu=4,Rr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),qt=null,Xt=null,Zn=!1,Qt="bgra8unorm",pc=null,yc=new WeakMap;function vt(e){try{e()}catch{}}function uh(e){return Math.max(16,e+3&-4)}function gc(){let e=globalThis.navigator?.gpu;return e&&typeof e.requestAdapter=="function"?e:null}function dh(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 qr(){if(qt)return Promise.resolve(qt);let e=He(),t=e.webgpuDeviceProvider?.peekDevice?.();return dh(t)?(qt=t,Qt=e.webgpuDeviceProvider?.getCanvasFormat?.()||Qt,Promise.resolve(t)):Zn?Promise.resolve(null):Xt||(e.webgpuDeviceProvider&&e.webgpuDeviceProvider!==Ah?(Xt=e.webgpuDeviceProvider.acquireDevice().then(r=>(Xt=null,dh(r)?(qt=r,Qt=e.webgpuDeviceProvider?.getCanvasFormat?.()||Qt,r):qu())).catch(()=>(Xt=null,qu())),Xt):qu())}function qu(){let e=gc();if(!e)return Zn=!0,Promise.resolve(null);try{Qt=e.getPreferredCanvasFormat?.()||"bgra8unorm"}catch{Qt="bgra8unorm"}return Xt=e.requestAdapter({powerPreference:"high-performance"}).then(async t=>{if(!t)return Zn=!0,Xt=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 qt=n,Xt=null,n.lost?.then?.(()=>{qt===n&&(qt=null,Xt=null,Zn=!1,pc?.onDeviceLost(n))}),n}).catch(()=>(Zn=!0,Xt=null,null)),Xt}var Ah={acquireDevice:()=>qr(),peekDevice:()=>qt,getCanvasFormat:()=>Qt};function Th(e,t="bgra8unorm"){qt=e,Xt=null,Zn=e===null,Qt=t}function _h(){qt=null,Xt=null,Zn=!1,Qt="bgra8unorm"}function Ju(e){let t=String(e??"").trim().toLowerCase();return t==="webgpu"||t==="webgl2"?t:"auto"}function ky(e){let t=e.container?.getAttribute?.("renderer")??e.renderer??"auto";return Ju(t)}function Ry(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&&!(He().tslWgslCompiler&&He().tslMaterialResolver?.(e,c.materialIndex))||c.pluginData?.morph||c.pluginData?.skinning||c.instanceCount!==void 0)return!0}return!1}function xc(e,t=!!(qt||gc())){let r=e;if(!r||r.xrSessionActive)return"webgl2";let i=ky(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"&&Ry(r)?"webgl2":"webgpu"}function fh(e){let t=yc.get(e);if(t)return t;let r=e.createBindGroupLayout({entries:[{binding:0,visibility:Qi|Qn,buffer:{type:"uniform"}},{binding:1,visibility:Qi|Qn,buffer:{type:"read-only-storage"}},{binding:2,visibility:Qn,sampler:{type:"filtering"}},{binding:3,visibility:Qn,texture:{sampleType:"float"}},{binding:4,visibility:Qn,sampler:{type:"comparison"}},{binding:5,visibility:Qn,texture:{sampleType:"depth",viewDimension:"2d-array"}}]}),i=e.createBindGroupLayout({entries:[0,1,2,3,4].map(C=>({binding:C,visibility:Qn,texture:{sampleType:"float"}}))}),n=e.createBindGroupLayout({entries:[{binding:0,visibility:Qi|Qn,buffer:{type:"uniform"}}]}),a=e.createBindGroupLayout({entries:[{binding:0,visibility:Qi|Qn,buffer:{type:"uniform"}},{binding:1,visibility:Qi|Qn,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:Ji}),h=e.createShaderModule({code:dc}),p=e.createShaderModule({code:Wu}),g=e.createShaderModule({code:fc}),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:bc|Mh|Pr});vt(()=>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:bc|Pr}),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])},yc.set(e,t),t}function Ly(e,t,r,i){let n=t.tslShaders.get(r);if(n)return n;let a=He().tslWgslCompiler;if(!a)return null;let s=a(i,Ji,Wu);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 Py=[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"}]}];function Eh(e,t,r,i,n){let a=s=>e.createRenderPipeline({layout:t,vertex:{module:r,entryPoint:"vsMain",buffers:Py},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 Iy(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=Eh(e,t.tslScenePipeLayout,s.pbrMod,i,n),t.tslPipelinesByFormat.set(o,l)),a?l.blend:l.opaque}function kh(e,t,r,i){let n=`${r}:${i}`,a=t.byFormat.get(n);if(a)return a;let{opaque:s,blend:o}=Eh(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 Rh(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 Lr(e){return!e||typeof e!="object"?null:e.__gpuImageSource||(Rh(e)?e:null)}function Xr(e,t,r){if(!r)return{view:t.whiteView,src:null,valid:!1};let i=Lr(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=Rh(i);if(!a)return{view:t.whiteView,src:null,valid:!1};n&&(t.ownedTextures.delete(n.tex),vt(()=>n.tex.destroy()));let[s,o]=a,l=e.createTexture({size:{width:s,height:o,depthOrArrayLayers:1},format:"rgba8unorm",usage:bc|Mh|Pr}),c=!1;if(typeof e.queue.copyExternalImageToTexture=="function"&&vt(()=>{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);vt(()=>{e.queue.writeTexture({texture:l},p,{bytesPerRow:h,rowsPerImage:o},{width:s,height:o,depthOrArrayLayers:1}),c=!0})}if(!c)return vt(()=>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 Lh(e,t,r){let i=Xr(e,t,r.texture),n=Xr(e,t,r.metallicRoughnessTexture),a=Xr(e,t,r.normalTexture),s=Xr(e,t,r.occlusionTexture),o=Xr(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 Cy(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 mh(e){return Bu(e)}function Ny(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??Rr,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 Ph(e){return e.environmentTexture&&typeof e.environmentTexture=="object"?e.environmentTexture:e.environmentSource&&typeof e.environmentSource=="object"?e.environmentSource:null}function ko(e){if(e){vt(()=>e.vertexBuf.destroy()),vt(()=>e.indexBuf?.destroy()),vt(()=>e.partBuf.destroy()),vt(()=>e.uniformBuf.destroy()),vt(()=>e.pickUniformBuf?.destroy());for(let t of e.shadowSliceBufs)vt(()=>t?.destroy());for(let t of e.tslSlots.values())vt(()=>t.buf.destroy())}}function Ih(e,t,r,i,n){let a=He().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=Ly(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){vt(()=>l?.buf.destroy());let c=e.createBuffer({size:s.buf68.byteLength,usage:vc|br});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 Yu(e){vt(()=>e.shadowTex?.destroy()),e.shadowTex=null,e.shadowArrayView=null,e.shadowLayerViews=[],e.shadowSize=0,e.shadowLayers=0,e.lastShadowDigest=0}function mc(e){vt(()=>e.msaaTex?.destroy()),vt(()=>e.depthTex?.destroy()),e.msaaTex=null,e.msaaView=null,e.depthTex=null,e.depthView=null,e.width=0,e.height=0}function hc(e){vt(()=>e.pickColorTex?.destroy()),vt(()=>e.pickDepthTex?.destroy()),vt(()=>e.pickReadBuf?.destroy()),e.pickColorTex=null,e.pickColorView=null,e.pickDepthTex=null,e.pickDepthView=null,e.pickReadBuf=null,e.pickBusy=!1}function hh(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 ph(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=Lh(e,t,F),G=Ih(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:uh(h.byteLength),usage:Ay|br});e.queue.writeBuffer(g,0,h);let x=null;p&&(x=e.createBuffer({size:uh(p.byteLength),usage:My|br}),e.queue.writeBuffer(x,0,p));let v=Math.max(128,c*128),y=e.createBuffer({size:v,usage:Ty|br}),A=e.createBuffer({size:800,usage:vc|br}),b=Ph(r),w=Xr(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:Lr(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 Dy(e,t,r,i,n){let a=kh(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?Iy(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 Uy(e,t,r){if(r.pickUniformBuf||(r.pickUniformBuf=e.createBuffer({size:800,usage:vc|br})),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 By(e,t,r,i){if(i<0||i>=Ao)return null;if(r.shadowSliceBufs[i]||(r.shadowSliceBufs[i]=e.createBuffer({size:176,usage:vc|br})),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 Ku=rt(),Wr=rt();function bh(e,t,r,i,n,a,s){let o=Ph(r),l=Lr(o),c=i.envView;if(l!==i.envSourceRef){let b=Xr(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??Rr,v=n.eye==="none"&&!r.stereoSBS;i.tslVertexDirty=!1;let y=He().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=Ih(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||Lr(E)!==b.src0||Lr(N)!==b.src1||Lr(C)!==b.src2||Lr(_)!==b.src3||Lr(P)!==b.src4){let D=Lh(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&&Gr(w,a.promoteAllCasters)&&(re|=1024),a&&a.slices.length>0&&!b.isBackdrop&&$i(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__"?Ku.set(w.transform):at(Ku,x,w.transform);let D=Ku,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,Fe=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)at(Wr,G,ne.subarray(D*16,D*16+16)),O=Wr;else if(W&&W.length>=(D+1)*3){Wr.set(G);let X=W[D*3],se=W[D*3+1],ce=W[D*3+2];Wr[12]+=G[0]*X+G[4]*se+G[8]*ce,Wr[13]+=G[1]*X+G[5]*se+G[9]*ce,Wr[14]+=G[2]*X+G[6]*se+G[10]*ce,O=Wr}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]=Fe,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 Fy(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 Zi=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:Xu,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 vt(()=>l.remove?.()),null;t.canvas=l,t.ctx=c,t.visible=!0,t.unhookSnapshot=Cy(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!==Qt||s)&&(t.ctx.configure({device:r,format:Qt,alphaMode:"premultiplied"}),t.dev=r,t.configuredFormat=Qt),t.width!==n||t.height!==a||!t.depthTex){mc(t),t.width=n,t.height=a;let o=Xu,l=null;vt(()=>{l=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:Qt,sampleCount:Xu,usage:Pr})}),l||(o=1);let c=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:"depth24plus",sampleCount:o,usage:Pr});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(!qt){if(!Zn&&!Xt){let G=h.gen;qr().then(q=>{q&&h.gen===G&&this.trackedViewers.has(f.viewer)&&vt(()=>f.viewer.render?.())})}return this.hideLayer(f.viewer),!1}let p=qt;if(xc(m,!0)!=="webgpu")return this.hideLayer(f.viewer),!1;h.dev&&h.dev!==p&&(ko(h.scene),h.scene=null,mc(h),Yu(h),hc(h));let g=this.ensureCanvas(m,h,p);if(!g)return!1;let x=fh(p),v=!f.isAR,y=v?m.backdropMeshes??[]:[],A=m.meshes??[];if((!h.scene||!hh(h.scene,y,A))&&(ko(h.scene),h.scene=ph(p,x,m,v),h.lastShadowDigest=0,!h.scene))return this.hideLayer(f.viewer),!1;let b=h.scene,w=Gi(m),S=x.dummyShadowView,E=w.slices.length;if(E>0){if(!h.shadowTex||h.shadowSize!==w.mapSize||h.shadowLayers<E){vt(()=>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:Pr|bc});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}bh(p,x,m,b,f,w,S),(b.bundlesDirty||b.bundleFormat!==Qt||b.bundleSamples!==h.sampleCount)&&(Dy(p,x,b,Qt,h.sampleCount),this.bundleRecordCount++);let N=w.sectionPlane??mh(m),C=Ny(m,f.isAR);Ki(h.uniformScratch,{vp:f.vp,modelRoot:m.modelRootMatrix??Rr,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??Rr;for(let q of w.slices){let H=By(p,x,b,q.slot),te=b.shadowSliceBufs[q.slot],Z=h.shadowLayerViews[q.slot];if(!te||!Z)continue;ah(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=kh(p,x,Qt,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=qt??await qr();if(!s||typeof s.createCommandEncoder!="function")return-1;let o=this.getState(e),l=o.gen,c=fh(s),f=n.backdropMeshes??[];if((!o.scene||!hh(o.scene,f,a))&&(ko(o.scene),o.scene=ph(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=rt();i?y.set(i):n.projMatrix&&n.viewMatrix?at(y,n.projMatrix,n.viewMatrix):y.set(Rr),bh(s,c,n,m,{viewer:e,vp:y,proj:n.projMatrix??Rr,view:n.viewMatrix??Rr,eyePos:[0,0,3],toneMappingIndex:0,viewport:[0,0,h,p],eye:"none",clear:!0,isAR:!1}),(!o.pickColorTex||!o.pickDepthTex)&&(hc(o),o.pickColorTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"rgba8unorm",usage:Pr|_y}),o.pickColorView=o.pickColorTex.createView(),o.pickDepthTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"depth24plus",usage:Pr}),o.pickDepthView=o.pickDepthTex.createView(),o.pickReadBuf=s.createBuffer({size:256,usage:br|lh}));let A=Fy(rt(),y,x,v,h,p),b=Uy(s,c,m),w=new ArrayBuffer(800);Ki(w,{vp:A,modelRoot:n.modelRootMatrix??Rr,eyePos:[0,0,0],exposure:1,envIntensity:1,toneMappingIndex:2,lights:[],hasEnvMap:!1,sectionPlane:mh(n)}),s.queue.writeBuffer(m.pickUniformBuf,0,w);let S=!!(o.pickReadBuf&&!o.pickBusy),E=S?o.pickReadBuf:s.createBuffer({size:256,usage:br|lh});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(Ey,0,4),o.gen!==l)return vt(()=>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:vt(()=>E.destroy())}}willRenderScene(e){if(!qt)return!1;let t=e;if(t.xrSessionActive||xc(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++,ko(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,ko(t.scene),t.scene=null,mc(t),Yu(t),hc(t),vt(()=>t.ctx?.unconfigure?.()),vt(()=>t.canvas?.remove?.()),t.ctx=null,t.canvas=null,t.dev=null,t.visible=!1)}onDeviceLost(e){let t=yc.get(e);if(t){for(let r of t.ownedTextures)vt(()=>r.destroy());t.ownedTextures.clear(),yc.delete(e)}for(let r of this.trackedViewers){let i=this.states.get(r);i&&i.dev===e&&(i.gen++,ko(i.scene),i.scene=null,mc(i),Yu(i),hc(i),i.dev=null,i.configuredFormat="")}}};function Ro(){return pc||(pc=new Zi),pc}var wc={name:"three-live-webgpu-scene",onRegister(){let e=He();e.gpuSceneAccelerator=Ro(),e.webgpuDeviceProvider||(e.webgpuDeviceProvider=Ah),!qt&&!Zn&&!Xt&&gc()&&qr()},onElementConnected(e){let t=e;!qt&&!Zn&&!Xt&&gc()&&qr().then(r=>{r&&t?.viewer&&vt(()=>t.viewer.render?.())})},onAttributeChanged(e,t){(t==="renderer"||t==="section-plane"||t==="shadow-maps")&&e?.viewer?.render?.()},onLoadModel(e){e&&typeof e=="object"&&Ro().clearViewerScene(e)},onClearScene(e){e&&typeof e=="object"&&Ro().clearViewerScene(e)},onXRSessionEnd(e){e&&typeof e=="object"&&vt(()=>e.render?.())},onDestroy(e,t){t&&typeof t=="object"&&Ro().disposeViewer(t)}};gt(wc),kn.registerScriptRunner(so),typeof window<"u"&&(window.ThreeLiveBundle=Qu);