three-live 0.0.1-alpha.0 → 1.1.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 (40) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +58 -0
  3. package/dist/index.d.ts +224 -0
  4. package/dist/three-author-engine.js +292 -0
  5. package/dist/three-author.cjs +292 -0
  6. package/dist/three-author.d.ts +224 -0
  7. package/dist/three-author.js +292 -0
  8. package/dist/three-convert.cjs +286 -0
  9. package/dist/three-convert.d.ts +224 -0
  10. package/dist/three-convert.js +286 -0
  11. package/dist/three-live-animation.cjs +36 -0
  12. package/dist/three-live-animation.d.ts +224 -0
  13. package/dist/three-live-animation.js +36 -0
  14. package/dist/three-live-animation.min.js +36 -0
  15. package/dist/three-live-element.cjs +217 -0
  16. package/dist/three-live-element.d.ts +224 -0
  17. package/dist/three-live-element.js +217 -0
  18. package/dist/three-live-extras.cjs +42 -0
  19. package/dist/three-live-extras.d.ts +224 -0
  20. package/dist/three-live-extras.js +42 -0
  21. package/dist/three-live-extras.min.js +42 -0
  22. package/dist/three-live-full.cjs +336 -0
  23. package/dist/three-live-full.js +336 -0
  24. package/dist/three-live-full.min.js +336 -0
  25. package/dist/three-live-sandbox.html +157 -0
  26. package/dist/three-live-viewer.cjs +217 -0
  27. package/dist/three-live-viewer.d.ts +224 -0
  28. package/dist/three-live-viewer.js +217 -0
  29. package/dist/three-live-viewer.min.js +217 -0
  30. package/dist/three-live.cjs +294 -0
  31. package/dist/three-live.js +294 -0
  32. package/dist/three-live.min.js +294 -0
  33. package/dist/three-view.cjs +217 -0
  34. package/dist/three-view.d.ts +224 -0
  35. package/dist/three-view.js +217 -0
  36. package/dist/three-xr.cjs +286 -0
  37. package/dist/three-xr.d.ts +224 -0
  38. package/dist/three-xr.js +286 -0
  39. package/package.json +78 -6
  40. package/index.js +0 -1
@@ -0,0 +1,294 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var He="__THREE_LIVE_REGISTRY__";function Y(){let n=typeof globalThis<"u"?globalThis:{};if(!n[He]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,He,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[He]=e}}return n[He]}var j=Y().plugins;function Xe(n){let e=Y().plugins;e.some(t=>t.name===n.name)||e.push(n)}function nn(){return Y().plugins}var jn=`#version 300 es
18
+ 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.);}`,Kn=`#version 300 es
19
+ 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);}`,Ge=new WeakMap,rn=new Float32Array(20);function sn(n,e){let[t,r,i,s,a,l]=e;return[n[0]*t+n[4]*r+n[8]*i+n[12],n[1]*t+n[5]*r+n[9]*i+n[13],n[2]*t+n[6]*r+n[10]*i+n[14],Math.abs(n[0])*s+Math.abs(n[4])*a+Math.abs(n[8])*l,Math.abs(n[1])*s+Math.abs(n[5])*a+Math.abs(n[9])*l,Math.abs(n[2])*s+Math.abs(n[6])*a+Math.abs(n[10])*l]}function Zn(n){if(n._lb!==void 0)return n._lb;let e=1e9,t=1e9,r=1e9,i=-1e9,s=-1e9,a=-1e9;for(let l of n.primitives||[]){let u=l.positions;if(u)for(let o=0;o<u.length;o+=3)u[o]<e&&(e=u[o]),u[o+1]<t&&(t=u[o+1]),u[o+2]<r&&(r=u[o+2]),u[o]>i&&(i=u[o]),u[o+1]>s&&(s=u[o+1]),u[o+2]>a&&(a=u[o+2])}return n._lb=e<=i?[(e+i)*.5,(t+s)*.5,(r+a)*.5,(i-e)*.5,(s-t)*.5,(a-r)*.5]:null}function Qn(n){let e=Ge.get(n);if(e)return e;let t=(l,u)=>{let o=n.createShader(l);return n.shaderSource(o,u),n.compileShader(o),o},r=n.createProgram();n.attachShader(r,t(35633,jn)),n.attachShader(r,t(35632,Kn)),n.linkProgram(r);let i=n.createVertexArray(),s=n.createBuffer(),a=n.createBuffer();return n.bindVertexArray(i),n.bindBuffer(34962,s),n.bufferData(34962,80,35048),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,3,5126,!1,20,0),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,5126,!1,20,12),n.bindBuffer(34963,a),n.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),n.bindVertexArray(null),e={prog:r,vao:i,vbo:s,ibo:a,uMVP:n.getUniformLocation(r,"uMVP"),uIntensity:n.getUniformLocation(r,"uShadowIntensity"),uSoftness:n.getUniformLocation(r,"uShadowSoftness")},Ge.set(n,e),e}var on={name:"contact-shadow",onAfterRender(n,e,t){let r=e.shadowIntensity;if(r<=0||!e.bounds)return;let i=Qn(n),s=(e.backdropMeshes?.length??0)>0,a=[],l=[];for(let c of e.meshes||[]){if(!c||c.visible===!1||c.isPluginMesh||c.name==="__xr_reticle__"||c.name?.startsWith("__xr_slot_"))continue;let h=Zn(c);if(!h)continue;c.transform&&(h=sn(c.transform,h)),e.modelRootMatrix&&(h=sn(e.modelRootMatrix,h));let[m,p,d,x,v,E]=h,_=[m,d,x,E,p-v,p+v];/floor|table|pedestal|ground|base|plane/i.test(c.name||"")||v<.14&&Math.min(x,E)>.45?l.push(_):a.push(_)}let u=[],o=(e.bounds.min?e.bounds.min[1]:e.bounds.center[1]-e.bounds.radius)+.002;for(let[c,h,m,p,d]of a){let x=-1/0;for(let[E,_,b,S,,y]of l)d>=y-.08&&Math.abs(c-E)<=b&&Math.abs(h-_)<=S&&y+.002>x&&(x=y+.002);s&&(x=Math.max(x,c>=.04&&c<=.36&&h>=-.34&&h<=-.04&&d>=.01?.036:Math.hypot(c,h)<=.66&&d>=-.06?.003:-.477)),isFinite(x)||(x=o);let v=u.find(E=>Math.hypot(c-E[0],h-E[1])<.06&&Math.abs(x-E[5])<.05);v?(v[2]=Math.max(v[2],m*.78),v[3]=Math.max(v[3],p*.78),v[4]=Math.min(v[4],d)):u.push([c,h,m,p,d,x])}if(u.length===0){let c=e.bounds.center,h=Math.max(.1,e.bounds.radius*1.5)/1.45;u.push([c[0],c[2],h,h,o,o])}n.useProgram(i.prog),n.uniformMatrix4fv(i.uMVP,!1,t),n.enable(3042),(n.blendFuncSeparate||n.blendFunc).call(n,770,771,1,771),n.depthMask(!1),n.bindVertexArray(i.vao),n.bindBuffer(34962,i.vbo);for(let[c,h,m,p,d,x]of u){let v=Math.max(0,d-x),E=r/(1+v*2);if(E<.02)continue;let _=1+Math.min(.75,v*.85),b=Math.max(.045,m*1.45*_),S=Math.max(.045,p*1.45*_);rn.set([c-b,x,h-S,0,0,c+b,x,h-S,1,0,c+b,x,h+S,1,1,c-b,x,h+S,0,1]),n.bufferSubData(34962,0,rn),n.uniform1f(i.uIntensity,E),n.uniform1f(i.uSoftness,Math.min(1,e.shadowSoftness+Math.min(.45,v*.6))),n.drawElements(4,6,5123,0)}n.bindVertexArray(null),n.depthMask(!0),n.disable(3042)},onDestroy(n){let e=Ge.get(n);e&&(n.deleteVertexArray(e.vao),n.deleteBuffer(e.vbo),n.deleteBuffer(e.ibo),n.deleteProgram(e.prog),Ge.delete(n))}};function an(n,e,t){let r=[],i=new Map,s=[],a=[],l=[],u=new Map,o=b=>{let S=i.get(b);return S===void 0&&(S=r.length,r.push({op:b}),i.set(b,S)),S},c=b=>{let S=u.get(b);return S===void 0&&(S=l.length,l.push({id:b}),u.set(b,S)),S},h=(b,S={})=>s.push({declaration:o(b),...S})-1,m=(b,S,y)=>a.push({id:b,type:S,value:y})-1,p=b=>({node:b,socket:"value"}),d=t?.interactivity??t?.gltfExtensions?.KHR_interactivity;if(d&&typeof d=="object"){let b=Array.isArray(d.graphs)?d.graphs[d.graph??0]:d;if(b&&Array.isArray(b.nodes)){let S=Array.isArray(b.declarations)?b.declarations:[];for(let y of S)y?.op&&o(y.op);Array.isArray(b.variables)&&a.push(...b.variables);for(let y of b.events||[])y?.id&&c(y.id);for(let y of b.nodes){if(!y||typeof y!="object")continue;let T=y.op||(typeof y.declaration=="number"?S[y.declaration]?.op:"");s.push(T?{...y,declaration:o(T)}:{...y})}}}let x=(b,S,y="translation")=>y==="baseColorFactor"||y==="metallicFactor"||y==="roughnessFactor"?`/materials/${Math.max(0,S)}/pbrMetallicRoughness/${y}`:y==="emissiveFactor"||y==="alphaCutoff"?`/materials/${Math.max(0,S)}/${y}`:y==="visible"?`/nodes/${b}/extensions/KHR_node_visibility/visible`:`/nodes/${b}/${y}`,v=new Map;n.forEach((b,S)=>{typeof b?.name=="string"&&!v.has(b.name)&&v.set(b.name,S)});let E=(b,S)=>typeof b.target=="string"&&v.has(b.target)?v.get(b.target):typeof b.targetNode=="number"?b.targetNode:S,_=b=>{let S=n[b];return(typeof S?.mesh=="number"?e[S.mesh]?.primitives?.[0]?.material:0)??0};for(let b=0;b<n.length;b++){let S=n[b],y=S?.extras?.interactivity;if(!y||typeof y!="object")continue;let T=(typeof S.mesh=="number"?e[S.mesh]?.primitives?.[0]?.material:0)??0,f=g=>{let M=Array.isArray(g)?g:[g],L=[];for(let D=0;D<M.length;D++){let R=M[D];if(!R||typeof R!="object")continue;let N=R.action||"interpolate",H=typeof R.duration=="number"?R.duration:.35;if(N==="toggleTransform"){let V=R.property==="rotation"||R.property==="scale"?R.property:"translation",B=V==="rotation"?S.rotation||[0,0,0,1]:V==="scale"?S.scale||[1,1,1]:S.translation||[0,0,0],P=`/nodes/${b}/${V}`,I=m(`__toggle_${b}_${D}`,"bool",!1),C=h("variable/get",{configuration:{variable:I}}),k=h("math/not",{values:{a:p(C)}}),U=h("variable/set",{configuration:{variable:I},values:{value:p(k)}}),O=h("pointer/interpolate",{configuration:{pointer:P},values:{value:{value:Array.isArray(R.to)?R.to:B},duration:{value:H}}}),F=h("pointer/interpolate",{configuration:{pointer:P},values:{value:{value:Array.isArray(R.from)?R.from:B},duration:{value:H}}});s[U].flows={out:{node:h("flow/branch",{values:{condition:p(C)},flows:{true:{node:O},false:{node:F}}})}},L.push(U)}else if(N==="interpolate"){let V=R.to??R.value;if(V===void 0)continue;let B={value:{value:V},duration:{value:H}};R.from!==void 0&&(B.from={value:R.from}),L.push(h("pointer/interpolate",{configuration:{pointer:typeof R.pointer=="string"?R.pointer:x(E(R,b),_(E(R,b)),R.property)},values:B}))}else if(N==="setProperty"){if(R.value===void 0)continue;L.push(h("pointer/set",{configuration:{pointer:typeof R.pointer=="string"?R.pointer:x(E(R,b),_(E(R,b)),R.property)},values:{value:{value:R.value}}}))}else if(N==="toggleVisibility"){let V=E(R,b),B=m(`__vis_${V}_${D}`,"bool",!0),P=h("variable/get",{configuration:{variable:B}}),I=h("math/not",{values:{a:p(P)}}),C=h("variable/set",{configuration:{variable:B},values:{value:p(I)}});s[C].flows={out:{node:h("pointer/set",{configuration:{pointer:`/nodes/${V}/extensions/KHR_node_visibility/visible`},values:{value:p(P)}})}},L.push(C)}else if(N==="cycleMaterialColor"&&Array.isArray(R.colors)&&R.colors.length>0){let V=typeof R.duration=="number"?R.duration:.25,B=`/materials/${Math.max(0,T)}/pbrMetallicRoughness/baseColorFactor`,P=m(`__color_idx_${b}_${D}`,"int",0),I=h("variable/get",{configuration:{variable:P}}),C=h("math/add",{values:{a:p(I),b:{value:1}}}),k=h("math/rem",{values:{a:p(C),b:{value:R.colors.length}}}),U=h("variable/set",{configuration:{variable:P},values:{value:p(k)}}),O={};for(let F=0;F<R.colors.length;F++){let z=R.colors[F],q=Array.isArray(z)&&z.length>=3?[z[0],z[1],z[2],z[3]??1]:[1,1,1,1];O[String(F)]={node:V>0?h("pointer/interpolate",{configuration:{pointer:B},values:{value:{value:q},duration:{value:V}}}):h("pointer/set",{configuration:{pointer:B},values:{value:{value:q}}})}}s[U].flows={out:{node:h("flow/switch",{values:{selection:p(I)},flows:O})}},L.push(U)}else if(N==="playAnimation")L.push(h("animation/start",{configuration:{animation:R.animation??R.clip??0}}));else if(N==="stopAnimation")L.push(h("animation/stop"));else if(N==="sendEvent"){let V={};for(let[B,P]of Object.entries(R.values||{}))V[B]={value:P};L.push(h("event/send",{configuration:{event:c(String(R.event??R.id??"custom"))},values:V}))}}if(!L.length)return null;if(L.length===1)return L[0];let A={};return L.forEach((D,R)=>{A[String(R)]={node:D}}),h("flow/sequence",{flows:A})},w=(g,M,L)=>{let A=f(M);A!==null&&h(g,{...L?{configuration:L}:{},flows:{out:{node:A}}})};if(y.onSelect&&w("pointer/onSelect",y.onSelect,{nodeIndex:b}),y.onHoverIn&&w("pointer/onHoverIn",y.onHoverIn,{nodeIndex:b}),y.onHoverOut&&w("pointer/onHoverOut",y.onHoverOut,{nodeIndex:b}),y.onStart&&w("event/onStart",y.onStart),y.onReceive&&typeof y.onReceive=="object")for(let[g,M]of Object.entries(y.onReceive))w("event/receive",M,{event:c(g)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:a,events:l}],graph:0}:null}var We='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).',$e="Security Error: client-side scripts require allow-client-scripts opt-in.";function Q(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function cn(n,e,t,r,i){let s=1/Math.tan(e/2);n.fill(0),n[0]=s/t,n[5]=s,n[11]=-1;let a=1/(r-i);return n[10]=(i+r)*a,n[14]=2*i*r*a,n}function qe(n,e,t,r){let[i,s,a]=e,[l,u,o]=r,[c,h,m]=t,p=i-c,d=s-h,x=a-m,v=Math.hypot(p,d,x);v<=1e-5?(p=0,d=0,x=1):(p/=v,d/=v,x/=v);let E=u*x-o*d,_=o*p-l*x,b=l*d-u*p;v=Math.hypot(E,_,b),v<=1e-5?(E=0,_=0,b=0):(E/=v,_/=v,b/=v);let S=d*b-x*_,y=x*E-p*b,T=p*_-d*E;return v=Math.hypot(S,y,T),v<=1e-5?(S=0,y=0,T=0):(S/=v,y/=v,T/=v),n[0]=E,n[1]=S,n[2]=p,n[3]=0,n[4]=_,n[5]=y,n[6]=d,n[7]=0,n[8]=b,n[9]=T,n[10]=x,n[11]=0,n[12]=-(E*i+_*s+b*a),n[13]=-(S*i+y*s+T*a),n[14]=-(p*i+d*s+x*a),n[15]=1,n}function re(n,e,t){let r=e[0],i=e[1],s=e[2],a=e[3],l=e[4],u=e[5],o=e[6],c=e[7],h=e[8],m=e[9],p=e[10],d=e[11],x=e[12],v=e[13],E=e[14],_=e[15],b=t[0],S=t[1],y=t[2],T=t[3];return n[0]=b*r+S*l+y*h+T*x,n[1]=b*i+S*u+y*m+T*v,n[2]=b*s+S*o+y*p+T*E,n[3]=b*a+S*c+y*d+T*_,b=t[4],S=t[5],y=t[6],T=t[7],n[4]=b*r+S*l+y*h+T*x,n[5]=b*i+S*u+y*m+T*v,n[6]=b*s+S*o+y*p+T*E,n[7]=b*a+S*c+y*d+T*_,b=t[8],S=t[9],y=t[10],T=t[11],n[8]=b*r+S*l+y*h+T*x,n[9]=b*i+S*u+y*m+T*v,n[10]=b*s+S*o+y*p+T*E,n[11]=b*a+S*c+y*d+T*_,b=t[12],S=t[13],y=t[14],T=t[15],n[12]=b*r+S*l+y*h+T*x,n[13]=b*i+S*u+y*m+T*v,n[14]=b*s+S*o+y*p+T*E,n[15]=b*a+S*c+y*d+T*_,n}function Ye(n,e,t,r){let i=e[0],s=e[1],a=e[2],l=e[3],u=i+i,o=s+s,c=a+a,h=i*u,m=i*o,p=i*c,d=s*o,x=s*c,v=a*c,E=l*u,_=l*o,b=l*c,S=r[0],y=r[1],T=r[2];return n[0]=(1-(d+v))*S,n[1]=(m+b)*S,n[2]=(p-_)*S,n[3]=0,n[4]=(m-b)*y,n[5]=(1-(h+v))*y,n[6]=(x+E)*y,n[7]=0,n[8]=(p+_)*T,n[9]=(x-E)*T,n[10]=(1-(h+d))*T,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function se(n,e){let t=e[0],r=e[1],i=e[2],s=e[4],a=e[5],l=e[6],u=e[8],o=e[9],c=e[10],h=c*a-l*o,m=-c*s+l*u,p=o*s-a*u,d=t*h+r*m+i*p;return d&&(d=1/d,n[0]=h*d,n[1]=(-c*r+i*o)*d,n[2]=(l*r-i*a)*d,n[3]=m*d,n[4]=(c*t-i*u)*d,n[5]=(-l*t+i*s)*d,n[6]=p*d,n[7]=(-o*t+r*u)*d,n[8]=(a*t-r*s)*d),n}function un(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],a=e[4],l=e[5],u=e[6],o=e[7],c=e[8],h=e[9],m=e[10],p=e[11],d=e[12],x=e[13],v=e[14],E=e[15],_=t*l-r*a,b=t*u-i*a,S=t*o-s*a,y=r*u-i*l,T=r*o-s*l,f=i*o-s*u,w=c*x-h*d,g=c*v-m*d,M=c*E-p*d,L=h*v-m*x,A=h*E-p*x,D=m*E-p*v,R=_*D-b*A+S*L+y*M-T*g+f*w;return R?(R=1/R,n[0]=(l*D-u*A+o*L)*R,n[1]=(i*A-r*D-s*L)*R,n[2]=(x*f-v*T+E*y)*R,n[3]=(m*T-h*f-p*y)*R,n[4]=(u*M-a*D-o*g)*R,n[5]=(t*D-i*M+s*g)*R,n[6]=(v*S-d*f-E*b)*R,n[7]=(c*f-m*S+p*b)*R,n[8]=(a*A-l*M+o*w)*R,n[9]=(r*M-t*A-s*w)*R,n[10]=(d*T-x*S+E*_)*R,n[11]=(h*S-c*T-p*_)*R,n[12]=(l*g-a*L-u*w)*R,n[13]=(t*L-r*g+i*w)*R,n[14]=(x*b-d*y-v*_)*R,n[15]=(c*y-h*b+m*_)*R,n):null}function ft(n,e,t,r,i){let s=i[0]*e+i[4]*t+i[8]*r+i[12],a=i[1]*e+i[5]*t+i[9]*r+i[13],l=i[2]*e+i[6]*t+i[10]*r+i[14],u=i[3]*e+i[7]*t+i[11]*r+i[15],o=u!==0?1/u:1;n[0]=s*o,n[1]=a*o,n[2]=l*o}function ln(n,e,t,r,i,s,a,l,u,o,c,h,m,p,d,x,v=0){let E=o-a,_=c-l,b=h-u,S=m-a,y=p-l,T=d-u,f=i*T-s*y,w=s*S-r*T,g=r*y-i*S,M=E*f+_*w+b*g;if(M>-1e-7&&M<1e-7)return!1;let L=1/M,A=n-a,D=e-l,R=t-u,N=L*(A*f+D*w+R*g);if(N<-v||N>1+v)return!1;let H=D*b-R*_,V=R*E-A*b,B=A*_-D*E,P=L*(r*H+i*V+s*B);if(P<-v||N+P>1+v)return!1;let I=L*(S*H+y*V+T*B);if(I>1e-4&&I<x.distance){x.distance=I,x.point=[n+r*I,e+i*I,t+s*I];let C=_*T-b*y,k=b*S-E*T,U=E*y-_*S,O=Math.hypot(C,k,U)||1;return x.normal=[C/O,k/O,U/O],!0}return!1}function je(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let c=0;c<t;c++)r.push(Q());if(t===0)return r;let i=new Set;for(let c of n.nodes)if(Array.isArray(c.children))for(let h of c.children)i.add(h);let s=new Set,a=128,l=(c,h,m=0)=>{if(m>a||c<0||c>=t||s.has(c))return;s.add(c);let p=n.nodes[c];if(!p)return;let d=Q();if(e&&e[c])d.set(e[c]);else if(p.matrix&&p.matrix.length===16)d.set(p.matrix);else{let v=p.translation||[0,0,0],E=p.rotation||[0,0,0,1],_=p.scale||[1,1,1];Ye(d,E,v,_)}let x=r[c];if(h?re(x,h,d):x.set(d),Array.isArray(p.children))for(let v of p.children)typeof v=="number"&&l(v,x,m+1)},u=[],o=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(o&&Array.isArray(o.nodes))u.push(...o.nodes);else for(let c=0;c<t;c++)i.has(c)||u.push(c);for(let c of u)l(c,null);for(let c=0;c<t;c++)!i.has(c)&&!u.includes(c)&&l(c,null);return r}function Jn(n){return new TextDecoder().decode(n)}var dn=Y().decoders;function er(n,e){dn.set(n.toLowerCase(),e)}function Ie(n){return dn.get(n.toLowerCase())}function fn(n){let e=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,t=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=t.getUint32(0,!0);if(r!==1179937895){let m=t.getUint8(0);throw m===123||m===32||m===10||m===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${r.toString(16)}`)}let i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let s=t.getUint32(8,!0),a=12,l=null,u=null;for(;a+8<=s&&a+8<=e.byteLength;){let m=t.getUint32(a,!0),p=t.getUint32(a+4,!0),d=a+8;if(d+m>e.byteLength)throw new Error(`Truncated GLB chunk: required ${d+m} bytes, buffer has ${e.byteLength}`);if(p===1313821514){let x=new Uint8Array(e,d,m),v=Jn(x);l=JSON.parse(v,(E,_)=>E==="__proto__"||E==="constructor"||E==="prototype"?void 0:_)}else p===5130562&&(u=e.slice(d,d+m));a=d+m}if(!l)throw new Error("Missing JSON chunk in GLB");let o=l.extensionsRequired||[];if(o.includes("KHR_draco_mesh_compression")&&!Ie("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(o.includes("EXT_meshopt_compression")&&!Ie("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(o.includes("KHR_texture_basisu")&&!Ie("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let c=u||new ArrayBuffer(0),h={gltf:l,bin:c,animations:[]};for(let m of j)m.onParseGLB?.(h);return h}function tr(n){return typeof n=="object"&&n!==null&&"gltf"in n&&typeof n.gltf=="object"&&n.gltf!==null&&"bin"in n&&(n.bin instanceof ArrayBuffer||ArrayBuffer.isView(n.bin))}function ve(n){if(tr(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return fn(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var pn=`#version 300 es
20
+ layout(location=0) in vec3 aPosition;
21
+ layout(location=1) in vec3 aNormal;
22
+ layout(location=2) in vec2 aUV;
23
+ uniform mat4 uMVP,uModel;
24
+ uniform mat3 uNormalMatrix;
25
+ uniform vec4 uUvTransform;
26
+ out vec3 vNormal,vWorldPos;
27
+ out vec2 vUV;
28
+ void main(){
29
+ vec3 rawN=uNormalMatrix*aNormal;
30
+ vNormal=length(rawN)>1e-5?normalize(rawN):vec3(0.0);
31
+ vec4 world=uModel*vec4(aPosition,1.0);
32
+ vWorldPos=world.xyz;
33
+ vec2 scaleUV=uUvTransform.zw;
34
+ if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
35
+ vUV=aUV*scaleUV+uUvTransform.xy;
36
+ gl_Position=uMVP*vec4(aPosition,1.0);
37
+ }`,bn=`#version 300 es
38
+ precision highp float;
39
+ in vec3 vNormal,vWorldPos;
40
+ in vec2 vUV;
41
+ uniform vec4 uBaseColor;
42
+ uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity;
43
+ uniform vec2 uClearcoat;
44
+ uniform vec3 uCameraPos,uAmbientColor;
45
+ uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap,uXrDepthTex;
46
+ uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap,uXrDepthEnabled,uXrDepthFormat;
47
+ uniform float uNormalScale,uOcclusionStrength,uXrRawValueToMeters;
48
+ uniform mat4 uXrDepthUVTransform;
49
+ uniform vec2 uViewportSize;
50
+ uniform int uToneMapping,uNumDirLights,uNumPointLights;
51
+ uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2];
52
+ out vec4 fragColor;
53
+
54
+ vec2 envBRDF(float r,float n){
55
+ vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04);
56
+ vec4 rv=r*c0+c1;
57
+ float a=min(rv.x*rv.x,exp2(-9.28*n))*rv.x+rv.y;
58
+ return vec2(-1.04,1.04)*a+rv.zw;
59
+ }
60
+
61
+ vec3 F_SchlickRoughness(vec3 F0,float r,float n){
62
+ return F0+(max(vec3(1.0-r),F0)-F0)*pow(clamp(1.0-n,0.0,1.0),5.0);
63
+ }
64
+
65
+ vec3 getStudioRadiance(vec3 R,float r){
66
+ vec3 kd=normalize(vec3(0.0,1.0,0.35));
67
+ float ki=pow(max(dot(R,kd),0.0),mix(96.0,1.5,r))*mix(2.4,0.5,r);
68
+ vec3 fd=normalize(vec3(-0.85,0.45,-0.35));
69
+ float fi=pow(max(dot(R,fd),0.0),mix(36.0,1.2,r))*mix(1.3,0.35,r);
70
+ float ri=pow(clamp(1.0-abs(R.y),0.0,1.0),3.5)*mix(0.55,0.22,r);
71
+ vec3 ag=mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5);
72
+ 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;
73
+ }
74
+
75
+ vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D normalMap,float scale){
76
+ vec3 mapNormal=texture(normalMap,uv).xyz*2.0-1.0;
77
+ mapNormal.xy*=scale;
78
+ vec3 dp1=dFdx(vWorldPos);
79
+ vec3 dp2=dFdy(vWorldPos);
80
+ vec2 duv1=dFdx(uv);
81
+ vec2 duv2=dFdy(uv);
82
+ vec3 dp2perp=cross(dp2,N);
83
+ vec3 dp1perp=cross(N,dp1);
84
+ vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;
85
+ vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;
86
+ float invmax=inversesqrt(max(dot(T,T),dot(B,B)));
87
+ return normalize(mat3(T*invmax,B*invmax,N)*normalize(mapNormal));
88
+ }
89
+
90
+ vec2 equirectangularUV(vec3 dir){
91
+ vec3 d=normalize(dir);
92
+ float u=atan(d.z,d.x)*0.15915494309+0.5;
93
+ float v=asin(clamp(d.y,-1.0,1.0))*0.31830988618+0.5;
94
+ return vec2(u,1.0-v);
95
+ }
96
+
97
+ vec3 neutralToneMapping(vec3 color){
98
+ const float startCompression=0.76;
99
+ const float desaturation=0.15;
100
+ float x=min(color.r,min(color.g,color.b));
101
+ float offset=x<0.08?x-6.25*x*x:0.04;
102
+ color-=offset;
103
+ float peak=max(color.r,max(color.g,color.b));
104
+ if(peak<startCompression)return color;
105
+ const float d=1.0-startCompression;
106
+ float newPeak=1.0-d*d/(peak+d-startCompression);
107
+ color*=newPeak/peak;
108
+ float g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);
109
+ return mix(color,newPeak*vec3(1.0),g);
110
+ }
111
+
112
+ vec3 applyToneMapping(vec3 color,int mode){
113
+ if(mode==0)return neutralToneMapping(color);
114
+ if(mode==1)return color/(color+vec3(1.0));
115
+ return color;
116
+ }
117
+
118
+ void main(){
119
+ vec4 base=uBaseColor;
120
+ if(uHasTexture==1)base*=texture(uBaseColorTexture,vUV);
121
+ if(length(vNormal)<1e-4&&uHasTexture==1){
122
+ vec3 unlit=base.rgb+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
123
+ fragColor=vec4(unlit,base.a);
124
+ return;
125
+ }
126
+ vec3 N=length(vNormal)<1e-4?normalize(cross(dFdx(vWorldPos),dFdy(vWorldPos))):normalize(vNormal);
127
+ if(!gl_FrontFacing)N=-N;
128
+ vec3 V=normalize(uCameraPos-vWorldPos);
129
+ if(uHasNormalTexture==1){
130
+ N=perturbNormal(N,V,vUV,uNormalTexture,uNormalScale);
131
+ }
132
+
133
+ float metallic=uMetallic;
134
+ float roughness=uRoughness;
135
+ if(uHasMetallicRoughnessTexture==1){
136
+ vec4 mr=texture(uMetallicRoughnessTexture,vUV);
137
+ roughness*=mr.g;
138
+ metallic*=mr.b;
139
+ }
140
+ roughness=clamp(roughness,0.04,1.0);
141
+ metallic=clamp(metallic,0.0,1.0);
142
+
143
+ float occ=1.0;
144
+ if(uHasOcclusionTexture==1){
145
+ occ=mix(1.0,texture(uOcclusionTexture,vUV).r,uOcclusionStrength);
146
+ }
147
+
148
+ float gloss=1.0-roughness;
149
+ float specExp=mix(16.0,256.0,gloss*gloss);
150
+ float specWeight=mix(0.22*gloss,1.0,metallic);
151
+ vec3 directLight=vec3(0.0);
152
+ for(int i=0;i<2;i++){
153
+ if(i>=uNumDirLights)break;
154
+ vec3 L=normalize(uDirLightDir[i]);
155
+ float NdotL=max(dot(N,L),0.0);
156
+ vec3 H=normalize(L+V);
157
+ float NoH=max(dot(N,H),0.0);
158
+ float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
159
+ directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uDirLightColor[i];
160
+ }
161
+ for(int i=0;i<2;i++){
162
+ if(i>=uNumPointLights)break;
163
+ vec3 toLight=uPointLightPos[i]-vWorldPos;
164
+ float dist=length(toLight);
165
+ vec3 L=toLight/max(dist,0.0001);
166
+ float atten=1.0/(1.0+0.09*dist+0.032*dist*dist);
167
+ float NdotL=max(dot(N,L),0.0);
168
+ vec3 H=normalize(L+V);
169
+ float NoH=max(dot(N,H),0.0);
170
+ float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
171
+ directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uPointLightColor[i]*atten;
172
+ }
173
+
174
+ vec3 R=reflect(-V,N);
175
+ float NoV=clamp(dot(N,V),0.001,1.0);
176
+ vec3 F0=mix(vec3(0.04),base.rgb,metallic);
177
+ vec3 F=F_SchlickRoughness(F0,roughness,NoV);
178
+ vec2 brdf=envBRDF(roughness,NoV);
179
+
180
+ vec3 specularIBL;
181
+ vec3 envDiffuse;
182
+ if(uHasEnvironmentMap==1){
183
+ specularIBL=texture(uEnvironmentMap,equirectangularUV(R)).rgb*(F*brdf.x+brdf.y);
184
+ envDiffuse=texture(uEnvironmentMap,equirectangularUV(N)).rgb;
185
+ }else{
186
+ specularIBL=getStudioRadiance(R,roughness)*(F*brdf.x+brdf.y);
187
+ envDiffuse=mix(vec3(0.10,0.10,0.12),vec3(0.52,0.54,0.58),N.y*0.5+0.5);
188
+ }
189
+
190
+ vec3 kD=(vec3(1.0)-F)*(1.0-metallic);
191
+ vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
192
+ vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
193
+ if(uClearcoat.x>0.0){
194
+ vec3 ccF=F_SchlickRoughness(vec3(0.04),uClearcoat.y,NoV)*uClearcoat.x;
195
+ color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
196
+ }
197
+ color=applyToneMapping(color,uToneMapping);
198
+ float outAlpha=base.a;
199
+ if(uXrDepthEnabled==1){
200
+ vec2 normViewUV=gl_FragCoord.xy/max(uViewportSize,vec2(1.0));
201
+ vec2 depthUV=(uXrDepthUVTransform*vec4(normViewUV,0.0,1.0)).xy;
202
+ vec4 depthSample=texture(uXrDepthTex,depthUV);
203
+ float realDepth=(uXrDepthFormat==1?depthSample.r:(depthSample.r+depthSample.a*256.0))*uXrRawValueToMeters;
204
+ float virtDepth=length(uCameraPos-vWorldPos);
205
+ if(realDepth>0.05&&virtDepth>realDepth){
206
+ float occAlpha=1.0-smoothstep(0.0,0.025,virtDepth-realDepth);
207
+ outAlpha*=occAlpha;
208
+ if(outAlpha<0.01)discard;
209
+ }
210
+ }
211
+ fragColor=vec4(color,outAlpha);
212
+ }`,nr=`#version 300 es
213
+ layout(location=0) in vec3 aPosition;
214
+ uniform mat4 uMVP;
215
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,rr=`#version 300 es
216
+ precision highp float;
217
+ uniform vec4 uColorId;
218
+ out vec4 fragColor;
219
+ void main(){fragColor=uColorId;}`;function hn(n,e,t){let r=n.createShader(e);if(n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,35713)){let i=n.getShaderInfoLog(r);throw n.deleteShader(r),new Error(`Shader compile error: ${i}`)}return r}function bt(n,e,t){let r=hn(n,35633,e),i=hn(n,35632,t),s=n.createProgram();if(n.attachShader(s,r),n.attachShader(s,i),n.linkProgram(s),!n.getProgramParameter(s,35714)){let a=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${a}`)}return s}function yt(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var yn=["uMVP","uModel","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","uEnvIntensity","uXrDepthTex","uXrDepthEnabled","uXrDepthFormat","uXrRawValueToMeters","uXrDepthUVTransform","uViewportSize"];function ir(n){if(typeof n!="string")return null;let e=n.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let t=e.toLowerCase();return t.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:t.startsWith("https://")||t.startsWith("blob:")?e:t.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function pt(n,e,t,r,i,s,a){if(r===void 0||!e.accessors?.[r])return null;let l=e.accessors[r],u=e.bufferViews[l.bufferView],o=(u.byteOffset||0)+(l.byteOffset||0),c=u.byteStride&&u.byteStride>s*4?u.byteStride>>2:s,h;if(c===s)h=new Float32Array(t,o,l.count*s);else{h=new Float32Array(l.count*s);let p=new Float32Array(t,u.byteOffset||0,Math.floor(u.byteLength/4)),d=(l.byteOffset||0)>>2;for(let x=0;x<l.count;x++){let v=d+x*c;for(let E=0;E<s;E++)h[x*s+E]=p[v+E]}}let m=n.createBuffer();return a.push(m),n.bindBuffer(34962,m),n.bufferData(34962,h,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),h}var gn=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),xn=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function mn(n,e,t=xn,r){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:i,bin:s}=e,a=[],l=je(i),u=[];if(Array.isArray(i.nodes))for(let w=0;w<i.nodes.length;w++){let g=i.nodes[w];g.mesh!==void 0&&i.meshes&&i.meshes[g.mesh]&&u.push({node:g,nodeIdx:w,meshIdx:g.mesh})}let o=u.length>0?u:(i.meshes||[]).map((w,g)=>({node:w,nodeIdx:-1,meshIdx:g})),c=[];if(Array.isArray(e.lights)&&e.lights.length>0)c.push(...e.lights);else if(i.extensions?.KHR_lights_punctual?.lights){let w=i.extensions.KHR_lights_punctual.lights;for(let g of w){let M=g.type==="directional"?"directional":g.type==="point"?"point":"ambient";c.push({type:M,color:g.color||[1,1,1],intensity:g.intensity!==void 0?g.intensity:1})}}if(c.length===0&&(c.push({type:"ambient",color:[1,1,1],intensity:.35}),c.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),o.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${o.length}`);let h=[];if(i.textures&&i.images){if(i.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${i.textures.length}`);for(let w=0;w<i.textures.length;w++){let g=i.textures[w],M=i.images[g.source];if(M){let L=n.createTexture();if(n.bindTexture(3553,L),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),M.bufferView!==void 0){let A=i.bufferViews[M.bufferView],D=s.slice(A.byteOffset||0,(A.byteOffset||0)+A.byteLength),R=new Blob([D],{type:M.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(R).then(N=>{n.bindTexture(3553,L),n.texImage2D(3553,0,6408,6408,5121,N),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(M.uri){let A=ir(M.uri);if(A){let D=new Image;D.crossOrigin="anonymous",D.referrerPolicy="no-referrer",D.onload=()=>{n.bindTexture(3553,L),n.texImage2D(3553,0,6408,6408,5121,D),n.generateMipmap(3553),r?.()},D.src=A}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",M.uri)}h.push(L)}else h.push(null)}}let m=[1/0,1/0,1/0],p=[-1/0,-1/0,-1/0],d=0,x=0;for(let w=0;w<o.length;w++){let g=o[w],M=i.meshes[g.meshIdx],L=g.nodeIdx>=0?l[g.nodeIdx]:Q(),A=new Float32Array(9);se(A,L);let D={name:g.node.name||M.name||`Mesh_${g.meshIdx}`,nodeIndex:g.nodeIdx,transform:L,normalMatrix:A,primitives:[],extras:g.node.extras||M.extras};for(let R of M.primitives||[]){if(R.extensions?.KHR_draco_mesh_compression){let $=Ie("draco");$&&$.decodePrimitive(i,R,s)}let N=[],H=n.createVertexArray();n.bindVertexArray(H);let V=i.accessors[R.attributes.POSITION],B=Number(V?.count??0);if(!Number.isFinite(B)||B<0||d+B>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(d+=B,V?.min&&V?.max)for(let $=0;$<3;$++){let oe=L[12+$],Ee=L[12+$];for(let de=0;de<3;de++){let ze=L[de*4+$]*V.min[de],Ve=L[de*4+$]*V.max[de];oe+=ze<Ve?ze:Ve,Ee+=ze>Ve?ze:Ve}oe<m[$]&&(m[$]=oe),Ee>p[$]&&(p[$]=Ee)}let P=pt(n,i,s,R.attributes.POSITION,0,3,N);pt(n,i,s,R.attributes.NORMAL,1,3,N),pt(n,i,s,R.attributes.TEXCOORD_0,2,2,N);let I=0,C=5123,k=null;if(R.indices!==void 0){let $=i.accessors[R.indices],Ee=(i.bufferViews[$.bufferView].byteOffset||0)+($.byteOffset||0);if(I=Number($.count??0),!Number.isFinite(I)||I<0||x+I>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);x+=I,C=$.componentType===5125?5125||5125:5123||5123;let de=n.createBuffer();N.push(de),n.bindBuffer(34963,de),$.componentType===5125?(k=new Uint32Array(s,Ee,$.count),n.bufferData(34963,k,35044)):(k=new Uint16Array(s,Ee,$.count),n.bufferData(34963,k,35044))}else I=V.count;let U={};for(let $ of j)if($.onBuildPrimitiveVAO){let oe=$.onBuildPrimitiveVAO(n,H,R,i,s);oe&&(U[$.name]=oe)}n.bindVertexArray(null);let O=i.materials&&R.material!==void 0?i.materials[R.material]:null,F=pn,z=bn,q=!1;for(let $ of j)if($.onResolveShader){let oe=$.onResolveShader(R,O,F,z);oe&&(F=oe.vs,z=oe.fs,q=!0)}let G=q?bt(n,F,z):null,ue=G?yt(n,G,yn):null,J=O?.pbrMetallicRoughness,ne=J?.baseColorFactor||[.8,.8,.8,1],be=J?.metallicFactor??.1,ye=J?.roughnessFactor??.5,le=O?.extensions?.KHR_materials_clearcoat,ie=le?le.clearcoatFactor??1:0,ge=Math.max(.04,le?.clearcoatRoughnessFactor??.04),xe=J?.baseColorTexture!==void 0&&h[J.baseColorTexture.index]?h[J.baseColorTexture.index]:null,Pe=J?.metallicRoughnessTexture!==void 0&&h[J.metallicRoughnessTexture.index]?h[J.metallicRoughnessTexture.index]:null,Gn=O?.normalTexture!==void 0&&h[O.normalTexture.index]?h[O.normalTexture.index]:null,Wn=O?.normalTexture?.scale??1,$n=O?.occlusionTexture!==void 0&&h[O.occlusionTexture.index]?h[O.occlusionTexture.index]:null,qn=O?.occlusionTexture?.strength??1,Yn=!!(O?.extensions?.KHR_materials_transmission||U.materials?.isTransmissive);D.primitives.push({vao:H,indexCount:I,indexType:C,baseColor:ne,metallic:be,roughness:ye,clearcoat:ie,clearcoatRoughness:ge,positions:P,indices:k,texture:xe,metallicRoughnessTexture:Pe,normalTexture:Gn,occlusionTexture:$n,normalScale:Wn,occlusionStrength:qn,buffers:N,materialIndex:R.material,pluginData:U,customProgram:G,customUniforms:ue,isTransmissive:Yn})}a.push(D)}isFinite(m[0])||(m=[-1,-1,-1]),isFinite(p[0])||(p=[1,1,1]);let v=[(m[0]+p[0])/2,(m[1]+p[1])/2,(m[2]+p[2])/2],E=p[0]-m[0],_=p[1]-m[1],b=p[2]-m[2],S=Math.max(Math.hypot(E,_,b)/2,.5),y=[m[0],m[1],m[2]],T=[p[0],p[1],p[2]],f=e.animations;if(!f){for(let w of j)if(w.onParseGLB?.(e),e.animations){f=e.animations;break}}return f||(f=[]),{meshes:a,bounds:{center:v,radius:S,min:y,max:T},lights:c,animations:f,worldMatrices:l}}var ee=class{constructor(e,t,r){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=Q();this.clearColor=[0,0,0,0];this.envIntensity=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.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=Q();this.viewMatrix=Q();this.modelMatrix=Q();this.mvpMatrix=Q();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.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.xrDepthState={enabled:!1,texture:null,uvTransform:Q(),rawValueToMeters:.001,format:0};this.container=e;let i,s;if(t&&typeof t.getContext=="function"?(i=t,s=r):(s=t,i=s?.canvas),!i){let u=e.querySelector("canvas");u||(u=document.createElement("canvas"),u.style.width="100%",u.style.height="100%",u.style.display="block",u.style.touchAction="none",e.prepend(u)),i=u}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!a:a&&(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.envIntensity=Math.max(0,Number(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=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.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.renderProg=bt(l,pn,bn),this.pickProg=bt(l,nr,rr),this.uRender=yt(l,this.renderProg,yn),this.uPick=yt(l,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo(),this.setupEvents(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){er(e,t)}static getDecoder(e){return Ie(e)}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),s=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=s,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,s,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,s)}loadGLBData(e,t){let{meshes:r,bounds:i,lights:s,animations:a,worldMatrices:l}=mn(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=a||[],this.worldMatrices=l||[],this.gltf=e.gltf,this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let o of e.gltf.nodes)this.initialNodeTransforms.push({t:o.translation?[o.translation[0],o.translation[1],o.translation[2]]:[0,0,0],r:o.rotation?[o.rotation[0],o.rotation[1],o.rotation[2],o.rotation[3]]:[0,0,0,1],s:o.scale?[o.scale[0],o.scale[1],o.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let o of j)o.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.environmentIntensity??e.gltf?.extras?.exposure??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.exposure??e.gltf?.asset?.extras?.environmentIntensity;u!==void 0&&(this.envIntensity=Math.max(0,Number(u))),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(fn(e))}loadModel(e){this.loadGLBData(ve(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=ve(e),{meshes:i}=mn(this.gl,r,xn,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],se(s.normalMatrix,s.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),se(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],a=[],l=[];for(let u of this.lights){let o=u.color||[1,1,1],c=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")r=[o[0]*c,o[1]*c,o[2]*c];else if(u.type==="directional"&&i.length<6){let h=u.direction||[.5,1,.8];i.push(h[0],h[1],h[2]),s.push(o[0]*c,o[1]*c,o[2]*c)}else if(u.type==="point"&&a.length<6){let h=u.position||[0,0,0];a.push(h[0],h[1],h[2]),l.push(o[0]*c,o[1]*c,o[2]*c)}}i.length===0&&(i.push(.5,1,.8),s.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,s)),t.uniform1i(e.uNumPointLights,a.length/3),a.length>0&&(t.uniform3fv(e.uPointLightPos,a),t.uniform3fv(e.uPointLightColor,l)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.envIntensity=Math.max(0,Number(e))}getExposure(){return this.envIntensity}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=e}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of j)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of j)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(c=>c.primitives.filter(h=>h.materialIndex===r||e.length===1&&h.materialIndex===void 0)),s=i[0],a=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,u=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,o={baseColorFactor:a,metallicFactor:l,roughnessFactor:u,setBaseColorFactor:c=>{let h=[c[0],c[1],c[2],c[3]??1];o.baseColorFactor=h,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=h);for(let m of i)m.baseColor=h;this.render()},setMetallicFactor:c=>{o.metallicFactor=c,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=c);for(let h of i)h.metallic=c;this.render()},setRoughnessFactor:c=>{o.roughnessFactor=c,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=c);for(let h of i)h.roughness=c;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:o}})}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)}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 j)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 s=this.clampDistance(r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(i!==void 0&&i>0){let s=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}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=Q();re(r,this.projMatrix,this.viewMatrix);let[i,s,a]=e,l=t?t[0]:0,u=t?t[1]:0,o=t?t[2]:0,c=this.modelRootMatrix;c&&(i=c[0]*e[0]+c[4]*e[1]+c[8]*e[2]+c[12],s=c[1]*e[0]+c[5]*e[1]+c[9]*e[2]+c[13],a=c[2]*e[0]+c[6]*e[1]+c[10]*e[2]+c[14],t&&(l=c[0]*t[0]+c[4]*t[1]+c[8]*t[2],u=c[1]*t[0]+c[5]*t[1]+c[9]*t[2],o=c[2]*t[0]+c[6]*t[1]+c[10]*t[2]));let h=r[0]*i+r[4]*s+r[8]*a+r[12],m=r[1]*i+r[5]*s+r[9]*a+r[13],p=r[2]*i+r[6]*s+r[10]*a+r[14],d=r[3]*i+r[7]*s+r[11]*a+r[15];if(d<=1e-4)return{x:0,y:0,z:1,visible:!1};let x=h/d,v=m/d,E=p/d,_=this.canvas.getBoundingClientRect(),b=_.width||this.canvas.clientWidth||this.canvas.width||300,S=_.height||this.canvas.clientHeight||this.canvas.height||150,y=(x*.5+.5)*b,T=(-v*.5+.5)*S,f=x>=-1.1&&x<=1.1&&v>=-1.1&&v<=1.1&&E>=-1&&E<=1;if(f&&t){let w=this.customTarget||this.bounds.center,g=w[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),M=w[1]+this.currDistance*Math.sin(this.currPhi),L=w[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),A=[i-g,s-M,a-L];l*A[0]+u*A[1]+o*A[2]>.05&&(f=!1)}return{x:y,y:T,z:E,visible:f}}setSelectedMesh(e){this.selectedMeshName=e||""}setupEvents(){let e=this.canvas;this.boundContextMenu=t=>{t.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=t=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist=0,this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.isPanning=t.button===2||t.shiftKey||this.activePointers.size===2,e.setPointerCapture(t.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=t=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=t.clientX-r.x,s=t.clientY-r.y;if(this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let a=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],l=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],u=this.customTarget?[...this.customTarget]:[...this.bounds.center],o=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;u[0]+=(-i*a[0]+s*l[0])*o,u[1]+=(-i*a[1]+s*l[1])*o,u[2]+=(-i*a[2]+s*l[2])*o,this.customTarget=u}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=t=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(t.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(t.pointerId)}catch{}if(this.totalDragDist<5&&t.button===0){let r=e.getBoundingClientRect(),i=Math.floor((t.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((t.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=t=>{if(!this.interactive)return;t.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let r=t.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.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=t=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),t.preventDefault();break}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=this.canvas;this.boundContextMenu&&(e.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(e.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(e.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(e.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(e.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(e.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(e,t){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,a=r.height||300,l=i.width>0?Math.floor((e-i.left)*(s/i.width)):Math.floor(e),u=i.height>0?Math.floor((t-i.top)*(a/i.height)):Math.floor(t);return this.performMeshPick(l,u,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300),l=Q();re(l,this.projMatrix,this.viewMatrix);let u=[],o=Math.max(0,Math.min(s-1,e)),c=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&i){(this.pickFboWidth!==s||this.pickFboHeight!==a)&&this.resizePickingFbo(s,a),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,a),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let f=0;f<this.meshes.length;f++){let w=this.meshes[f];if(w.visible===!1||w.isPluginMesh)continue;let g=f+1,M=(g&255)/255,L=(g>>8&255)/255,A=(g>>16&255)/255;i.uniform4f(this.uPick.uColorId,M,L,A,1),re(this.modelMatrix,this.modelRootMatrix,w.transform),re(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let D of w.primitives)i.bindVertexArray(D.vao),i.drawElements(4,D.indexCount,D.indexType,0)}let y=new Uint8Array(4);i.readPixels(o,c,1,1,6408,5121,y),i.bindFramebuffer(36160,null);let T=y[0]+(y[1]<<8)+(y[2]<<16);T>0&&T<=this.meshes.length&&(u=[this.meshes[T-1]])}u.length===0&&(u=this.meshes.filter(y=>y.visible!==!1));let h=null,m=1/0,p=[0,0,0],d=[0,1,0],x=this.customTarget||this.bounds.center,v=x[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),E=x[1]+this.currDistance*Math.sin(this.currPhi),_=x[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let y of u){re(this.modelMatrix,this.modelRootMatrix,y.transform),re(this.mvpMatrix,l,this.modelMatrix);let T=Q();if(!un(T,this.mvpMatrix))continue;let f=(o+.5)/s*2-1,w=(c+.5)/a*2-1,g=[0,0,0],M=[0,0,0];ft(g,f,w,-1,T),ft(M,f,w,1,T);let L=M[0]-g[0],A=M[1]-g[1],D=M[2]-g[2],R=Math.hypot(L,A,D)||1,N=L/R,H=A/R,V=D/R,B={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((I=>{for(let C of y.primitives){if(!C.positions)continue;let k=C.positions,U=C.indices,O=Math.floor(U?U.length/3:k.length/9);for(let F=0;F<O;F++){let z=U?U[F*3]:F*3,q=U?U[F*3+1]:F*3+1,G=U?U[F*3+2]:F*3+2;ln(g[0],g[1],g[2],N,H,V,k[z*3],k[z*3+1],k[z*3+2],k[q*3],k[q*3+1],k[q*3+2],k[G*3],k[G*3+1],k[G*3+2],B,I)}}})(1e-4),isFinite(B.distance)){let I=B.point[0],C=B.point[1],k=B.point[2],U=this.modelMatrix,O=U[0]*I+U[4]*C+U[8]*k+U[12],F=U[1]*I+U[5]*C+U[9]*k+U[13],z=U[2]*I+U[6]*C+U[10]*k+U[14],q=O-v,G=F-E,ue=z-_,J=Math.hypot(q,G,ue);if(J<m){se(this.normalMatrix,this.modelMatrix);let ne=this.normalMatrix,be=B.normal[0],ye=B.normal[1],le=B.normal[2],ie=ne[0]*be+ne[3]*ye+ne[6]*le,ge=ne[1]*be+ne[4]*ye+ne[7]*le,xe=ne[2]*be+ne[5]*ye+ne[8]*le,Pe=Math.hypot(ie,ge,xe)||1;ie/=Pe,ge/=Pe,xe/=Pe,ie*q+ge*G+xe*ue>0&&(ie=-ie,ge=-ge,xe=-xe),h=y,m=Math.round(J*1e3)/1e3,p=[Math.round(O*1e3)/1e3,Math.round(F*1e3)/1e3,Math.round(z*1e3)/1e3],d=[Math.round(ie*1e3)/1e3,Math.round(ge*1e3)/1e3,Math.round(xe*1e3)/1e3]}}}if(!h)return null;let S={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:m,hitPoint:p,normal:d,screenX:e,screenY:t};if(r){for(let y of j)y.onMeshSelect?.(this,S);this.opts.onMeshClick&&this.opts.onMeshClick(S),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:S}))}return S}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))}start(){if(this.animFrameId!==null)return;this.lastTime=performance.now();let e=t=>{let r=Math.min((t-this.lastTime)/1e3,.1);this.lastTime=t,this.isVisible&&(this.resize(),this.update(r),this.render()),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],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=r-(e*r+t*i),s[13]=0,s[14]=i-(-t*r+e*i),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let m of j)m.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 m of j)m.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;let r=(this.canvas.width||1)/(this.canvas.height||1),i=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):this.bounds.radius*20;cn(this.projMatrix,this.fov,r,.1,i);let s=this.customTarget||this.bounds.center,a=s[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),l=s[1]+this.currDistance*Math.sin(this.currPhi),u=s[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);qe(this.viewMatrix,[a,l,u],s,[0,1,0]),re(this.mvpMatrix,this.projMatrix,this.viewMatrix),se(this.normalMatrix,this.modelMatrix);let o=Math.round((this.currTheta*180/Math.PI%360+360)%360),c=Math.round(this.currPhi*180/Math.PI),h=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(o-this.lastReportedTheta)>=1||Math.abs(c-this.lastReportedPhi)>=1||Math.abs(h-this.lastReportedZoom)>=.02){this.lastReportedTheta=o,this.lastReportedPhi=c,this.lastReportedZoom=h;let m={theta:o,phi:c,zoom:h,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(m),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:m}))}}renderXRView(e,t,r,i){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let s=e?.transform?.inverse?.matrix||this.viewMatrix,a=e?.projectionMatrix||this.projMatrix,l=e?.transform?.position,u=l?[l.x,l.y,l.z]:[0,1.6,0];r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:s,projMatrix:a,eyePos:u,viewport:i,eye:e?.eye||"none",clear:e?.eye!=="right"})}render(e){let t=this.gl,r=this.canvas.width,i=this.canvas.height;e?.viewport?(t.viewport(e.viewport[0],e.viewport[1],e.viewport[2],e.viewport[3]),r=e.viewport[2],i=e.viewport[3]):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16384|256));let s=Q();re(s,e?.projMatrix??this.projMatrix,e?.viewMatrix??this.viewMatrix);let a=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:0,l=this.customTarget||this.bounds.center,u=e?e.eyePos[0]:l[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),o=e?e.eyePos[1]:l[1]+this.currDistance*Math.sin(this.currPhi),c=e?e.eyePos[2]:l[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let v of j)v.onBeforeDrawScene?.(this,t,s,[u,o,c],a);if(this.meshes.length===0&&this.backdropMeshes.length===0)return;let h=e?.eye||"none",m=!1,p=this.backdropMeshes.length,d=p>0?[...this.backdropMeshes,...this.meshes]:this.meshes,x=v=>{for(let E=0;E<d.length;E++){let _=d[E];if(_.visible===!1)continue;let b=this.selectedMeshName!==""&&_.name===this.selectedMeshName;E<p?this.modelMatrix.set(_.transform):re(this.modelMatrix,this.modelRootMatrix,_.transform),re(this.mvpMatrix,s,this.modelMatrix),se(_.normalMatrix,this.modelMatrix);let S=_.extras?.xr?.stereo||_.userData?.xr?.stereo,y=0,T=0,f=1,w=1;S==="sbs"?(f=.5,y=h==="right"?.5:0):S==="ou"&&(w=.5,T=h==="right"?.5:0);for(let g of _.primitives){let M=!!g.isTransmissive;if(!v&&M){m=!0;continue}if(v&&!M)continue;let L=g.customProgram||this.renderProg,A=g.customUniforms||this.uRender;t.useProgram(L),t.uniform1i(A.uToneMapping,a),t.uniform1f(A.uEnvIntensity,this.envIntensity),t.uniform3f(A.uCameraPos,u,o,c),t.uniform1f(A.uEmissive,b?1:0),t.uniformMatrix4fv(A.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(A.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(A.uNormalMatrix,!1,_.normalMatrix),A.uUvTransform&&t.uniform4f(A.uUvTransform,y,T,f,w),A.uViewportSize&&t.uniform2f(A.uViewportSize,Math.max(1,r),Math.max(1,i)),this.xrDepthState.enabled&&this.xrDepthState.texture?(t.activeTexture(33989),t.bindTexture(3553,this.xrDepthState.texture),A.uXrDepthTex&&t.uniform1i(A.uXrDepthTex,5),A.uXrDepthEnabled&&t.uniform1i(A.uXrDepthEnabled,1),A.uXrDepthFormat&&t.uniform1i(A.uXrDepthFormat,this.xrDepthState.format||0),A.uXrRawValueToMeters&&t.uniform1f(A.uXrRawValueToMeters,this.xrDepthState.rawValueToMeters),A.uXrDepthUVTransform&&t.uniformMatrix4fv(A.uXrDepthUVTransform,!1,this.xrDepthState.uvTransform)):A.uXrDepthEnabled&&t.uniform1i(A.uXrDepthEnabled,0),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(A.uEnvironmentMap,4),t.uniform1i(A.uHasEnvironmentMap,1)):t.uniform1i(A.uHasEnvironmentMap,0),this.bindLights(A);for(let D of j)D.onBeforeDrawPrimitive?.(t,L,g,_,this.worldMatrices||[],this.gltf);t.uniform4fv(A.uBaseColor,g.baseColor),t.uniform1f(A.uMetallic,g.metallic),t.uniform1f(A.uRoughness,g.roughness),A.uClearcoat&&t.uniform2f(A.uClearcoat,g.clearcoat??0,g.clearcoatRoughness??.04),g.texture?(t.activeTexture(33984),t.bindTexture(3553,g.texture),t.uniform1i(A.uBaseColorTexture,0),t.uniform1i(A.uHasTexture,1)):t.uniform1i(A.uHasTexture,0),g.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,g.metallicRoughnessTexture),t.uniform1i(A.uMetallicRoughnessTexture,1),t.uniform1i(A.uHasMetallicRoughnessTexture,1)):t.uniform1i(A.uHasMetallicRoughnessTexture,0),g.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,g.normalTexture),t.uniform1i(A.uNormalTexture,2),t.uniform1i(A.uHasNormalTexture,1),t.uniform1f(A.uNormalScale,g.normalScale)):t.uniform1i(A.uHasNormalTexture,0),g.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,g.occlusionTexture),t.uniform1i(A.uOcclusionTexture,3),t.uniform1i(A.uHasOcclusionTexture,1),t.uniform1f(A.uOcclusionStrength,g.occlusionStrength)):t.uniform1i(A.uHasOcclusionTexture,0),t.bindVertexArray(g.vao),t.drawElements(4,g.indexCount,g.indexType,0)}}};if(x(!1),m){for(let v of j)v.onBeforeTransmissivePass?.(t,this);x(!0)}for(let v of j)v.onAfterRender?.(t,this,s)}disposeMeshListGpuResources(e){let t=this.gl;for(let r of e)for(let i of r.primitives){if(i.vao&&t.deleteVertexArray(i.vao),i.buffers)for(let s of i.buffers)t.deleteBuffer(s);i.texture&&t.deleteTexture(i.texture),i.metallicRoughnessTexture&&t.deleteTexture(i.metallicRoughnessTexture),i.normalTexture&&t.deleteTexture(i.normalTexture),i.occlusionTexture&&t.deleteTexture(i.occlusionTexture),i.customProgram&&t.deleteProgram(i.customProgram)}}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes),this.meshes=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of j)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()}};ee.registerPlugin=Xe,ee.getRegisteredPlugins=nn;function sr(n){return n+3&-4}function or(n){let e={};return n.grab&&(e.interactable={mode:typeof n.grab=="string"?n.grab:"2-hand"},e.movable={scaleInZ:!!n.scale,minScale:typeof n.scale=="object"?n.scale.min??.1:.1,maxScale:typeof n.scale=="object"?n.scale.max??10:10}),n.billboard&&(e.billboard={mode:typeof n.billboard=="string"?n.billboard:"capsule"}),n.follow&&(e.follow={target:typeof n.follow=="object"?n.follow.mode??"head":n.follow}),n.anchor&&(e.anchor={plane:n.anchor}),n.physics&&n.physics!=="none"&&(e.rigidbody={type:n.physics}),e}function Fe(n,e){n.updateMatrixWorld(!0);let t=[],r=0,i=[],s=[],a=[],l=[],u=new Set,o=[],c=[],h=new Map,m=[];function p(f,w){let g=new Uint8Array(f.buffer,f.byteOffset,f.byteLength),M=sr(g.byteLength),L=new Uint8Array(M);L.set(g),t.push(L);let A=i.length;return i.push({buffer:0,byteOffset:r,byteLength:g.byteLength,target:w}),r+=M,A}function d(f,w,g,M,L,A,D){let R=p(f,g),N=s.length,H={bufferView:R,byteOffset:0,componentType:M,count:L,type:w};return A&&(H.min=A),D&&(H.max=D),s.push(H),N}n.traverse(f=>{(f.isLight||f.color&&f.intensity!==void 0)&&m.push({type:f.type,color:[f.color.r,f.color.g,f.color.b],intensity:f.intensity,position:[f.position.x,f.position.y,f.position.z]})});let x=[];function v(f){let w={name:f.name||""},g=f.position,M=f.quaternion,L=f.scale;if((g.x||g.y||g.z)&&(w.translation=[g.x,g.y,g.z]),(M.x||M.y||M.z||M.w!==1)&&(w.rotation=[M.x,M.y,M.z,M.w]),(L.x!==1||L.y!==1||L.z!==1)&&(w.scale=[L.x,L.y,L.z]),f.userData&&Object.keys(f.userData).length>0&&(w.extras=JSON.parse(JSON.stringify(f.userData,(D,R)=>{if(!(D==="__proto__"||D==="prototype"||D==="constructor"))return typeof R=="function"?void 0:R})),f.userData.xr)){let D=or(f.userData.xr);w.extensions={...w.extensions||{},MOZ_hubs_components:D,ANDROID_xr_scenecore:D},Y().xrTraitSerializer?.gltfNode(w,f.userData.xr),u.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(f.geometry){let D=f.geometry,R=D.attributes.position;if(R&&R.count>0){let N=[1/0,1/0,1/0],H=[-1/0,-1/0,-1/0];for(let I=0;I<R.count;I++){let C=R.getX(I),k=R.getY(I),U=R.getZ(I);C<N[0]&&(N[0]=C),C>H[0]&&(H[0]=C),k<N[1]&&(N[1]=k),k>H[1]&&(H[1]=k),U<N[2]&&(N[2]=U),U>H[2]&&(H[2]=U)}let B={attributes:{POSITION:d(R.array,"VEC3",34962,5126,R.count,N,H)}};if(D.attributes.normal&&(B.attributes.NORMAL=d(D.attributes.normal.array,"VEC3",34962,5126,D.attributes.normal.count)),D.attributes.uv&&(B.attributes.TEXCOORD_0=d(D.attributes.uv.array,"VEC2",34962,5126,D.attributes.uv.count)),D.index){let I=D.index.array instanceof Uint32Array;B.indices=d(D.index.array,"SCALAR",34963,I?5125:5123,D.index.count)}if(f.material){let I=h.get(f.material);if(I===void 0){I=c.length,h.set(f.material,I);let C=f.material,k={name:C.name||"",pbrMetallicRoughness:{baseColorFactor:[C.color.r,C.color.g,C.color.b,C.opacity],metallicFactor:C.metalness,roughnessFactor:C.roughness},doubleSided:C.side===2||C.doubleSided};if(C.emissive&&(C.emissive.r>0||C.emissive.g>0||C.emissive.b>0)){let O=C.emissiveIntensity??1;k.emissiveFactor=[C.emissive.r*O,C.emissive.g*O,C.emissive.b*O]}let U={};C.clearcoat>0&&(U.KHR_materials_clearcoat={clearcoatFactor:C.clearcoat,clearcoatRoughnessFactor:C.clearcoatRoughness||0}),C.sheen>0&&(U.KHR_materials_sheen={sheenColorFactor:C.sheenColor?[C.sheenColor.r,C.sheenColor.g,C.sheenColor.b]:[1,1,1],sheenRoughnessFactor:C.sheenRoughness||0}),C.transmission>0&&(U.KHR_materials_transmission={transmissionFactor:C.transmission}),C.thickness>0&&(U.KHR_materials_volume={thicknessFactor:C.thickness,attenuationDistance:C.attenuationDistance??1/0,attenuationColor:C.attenuationColor?[C.attenuationColor.r,C.attenuationColor.g,C.attenuationColor.b]:[1,1,1]}),C.ior!==void 0&&C.ior!==1.5&&(U.KHR_materials_ior={ior:C.ior}),C.dispersion>0&&(U.KHR_materials_dispersion={dispersion:C.dispersion}),C.iridescence>0&&(U.KHR_materials_iridescence={iridescenceFactor:C.iridescence,iridescenceIor:C.iridescenceIOR??1.3}),Object.keys(U).length>0&&(k.extensions=U),c.push(k)}B.material=I}let P=a.length;a.push({primitives:[B],name:f.name,...w.extras?{extras:w.extras}:{}}),w.mesh=P}}let A=l.length;if(l.push(w),o.push(f),f.children.length>0){w.children=[];for(let D of f.children)w.children.push(v(D))}return A}for(let f of n.children)x.push(v(f));let E=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),_=[];if(typeof E=="function"&&o.length>0){let f=e?.duration??4,w=e?.fps??15,g=Math.max(2,Math.round(f*w)+1),M=new Float32Array(g),L=o.map(P=>({px:P.position.x,py:P.position.y,pz:P.position.z,qx:P.quaternion.x,qy:P.quaternion.y,qz:P.quaternion.z,qw:P.quaternion.w,sx:P.scale.x,sy:P.scale.y,sz:P.scale.z})),A=o.map(()=>new Float32Array(g*3)),D=o.map(()=>new Float32Array(g*4)),R=o.map(()=>new Float32Array(g*3));for(let P=0;P<g;P++){let I=P/(g-1)*f;M[P]=I;try{E(I)}catch{}for(let C=0;C<o.length;C++){let k=o[C];A[C][P*3]=k.position.x,A[C][P*3+1]=k.position.y,A[C][P*3+2]=k.position.z,D[C][P*4]=k.quaternion.x,D[C][P*4+1]=k.quaternion.y,D[C][P*4+2]=k.quaternion.z,D[C][P*4+3]=k.quaternion.w,R[C][P*3]=k.scale.x,R[C][P*3+1]=k.scale.y,R[C][P*3+2]=k.scale.z}}for(let P=0;P<o.length;P++){let I=o[P],C=L[P];I.position.set(C.px,C.py,C.pz),I.quaternion.set(C.qx,C.qy,C.qz,C.qw),I.scale.set(C.sx,C.sy,C.sz)}n.updateMatrixWorld(!0);let N=null,H=()=>(N===null&&(N=d(M,"SCALAR",0,5126,g,[0],[f])),N),V=[],B=[];for(let P=0;P<o.length;P++){let I=L[P],C=!1,k=!1,U=!1;for(let O=0;O<g;O++)(Math.abs(A[P][O*3]-I.px)>1e-4||Math.abs(A[P][O*3+1]-I.py)>1e-4||Math.abs(A[P][O*3+2]-I.pz)>1e-4)&&(C=!0),(Math.abs(D[P][O*4]-I.qx)>1e-4||Math.abs(D[P][O*4+1]-I.qy)>1e-4||Math.abs(D[P][O*4+2]-I.qz)>1e-4||Math.abs(D[P][O*4+3]-I.qw)>1e-4)&&(k=!0),(Math.abs(R[P][O*3]-I.sx)>1e-4||Math.abs(R[P][O*3+1]-I.sy)>1e-4||Math.abs(R[P][O*3+2]-I.sz)>1e-4)&&(U=!0);if(C){let O=d(A[P],"VEC3",0,5126,g),F=V.length;V.push({input:H(),interpolation:"LINEAR",output:O}),B.push({sampler:F,target:{node:P,path:"translation"}})}if(k){let O=d(D[P],"VEC4",0,5126,g),F=V.length;V.push({input:H(),interpolation:"LINEAR",output:O}),B.push({sampler:F,target:{node:P,path:"rotation"}})}if(U){let O=d(R[P],"VEC3",0,5126,g),F=V.length;V.push({input:H(),interpolation:"LINEAR",output:O}),B.push({sampler:F,target:{node:P,path:"scale"}})}}B.length>0&&_.push({name:"ProceduralLoop",samplers:V,channels:B})}let b=an(l,a,n.userData),S={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:n.environmentIntensity}},scenes:[{nodes:x}],scene:0,nodes:l,meshes:a,materials:c,accessors:s,bufferViews:i,buffers:[{byteLength:r}],..._.length>0?{animations:_}:{},...b||u.size>0?{extensionsUsed:[...b?["KHR_interactivity"]:[],...u]}:{},...b?{extensions:{KHR_interactivity:b}}:{}},y=new Uint8Array(r),T=0;for(let f of t)y.set(f,T),T+=f.byteLength;return{gltf:S,bin:y.buffer,lights:m,environmentIntensity:n.environmentIntensity}}function Ze(n){return new TextEncoder().encode(n)}function Qe(n,e){let{gltf:t,bin:r}=Fe(n,e),i=JSON.stringify(t),s=Ze(i),a=(4-s.byteLength%4)%4,l=s.byteLength+a,u=20+l+8+r.byteLength,o=new Uint8Array(u),c=new DataView(o.buffer);c.setUint32(0,1179937895,!0),c.setUint32(4,2,!0),c.setUint32(8,u,!0),c.setUint32(12,l,!0),c.setUint32(16,1313821514,!0),o.set(s,20);for(let m=0;m<a;m++)o[20+s.byteLength+m]=32;let h=20+l;return c.setUint32(h,r.byteLength,!0),c.setUint32(h+4,5130562,!0),o.set(new Uint8Array(r),h+8),o}function ar(n,e){n.updateMatrixWorld(!0);let t=[];return n.traverse(r=>{if(r.geometry){let i=r.geometry,s=i.attributes.position;if(!s||s.count===0)return;let a=s.count,l=new Float32Array(a*3),u=r.matrixWorld.elements;for(let f=0;f<a;f++){let w=s.getX(f),g=s.getY(f),M=s.getZ(f);l[f*3]=u[0]*w+u[4]*g+u[8]*M+u[12],l[f*3+1]=u[1]*w+u[5]*g+u[9]*M+u[13],l[f*3+2]=u[2]*w+u[6]*g+u[10]*M+u[14]}let o;if(i.attributes.normal){let f=i.attributes.normal;o=new Float32Array(a*3);let w=new Float32Array(9);se(w,u);for(let g=0;g<a;g++){let M=f.getX(g),L=f.getY(g),A=f.getZ(g),D=w[0]*M+w[3]*L+w[6]*A,R=w[1]*M+w[4]*L+w[7]*A,N=w[2]*M+w[5]*L+w[8]*A,H=Math.hypot(D,R,N)||1;o[g*3]=D/H,o[g*3+1]=R/H,o[g*3+2]=N/H}}let c;if(i.attributes.uv){let f=i.attributes.uv;c=new Float32Array(a*2);for(let w=0;w<a;w++)c[w*2]=f.getX(w),c[w*2+1]=f.getY(w)}let h;if(i.index)h=i.index.array;else{h=a>65535?new Uint32Array(a):new Uint16Array(a);for(let f=0;f<a;f++)h[f]=f}let m="DefaultMaterial",p=[.8,.8,.8],d=.5,x=.1,v=0,E=0,_=1.5,b=1,S=[0,0,0];if(r.material){let f=r.material;m=f.name||`Material_${t.length}`,f.color&&(p=[f.color.r,f.color.g,f.color.b]),typeof f.roughness=="number"&&(d=f.roughness),typeof f.metalness=="number"&&(x=f.metalness),typeof f.clearcoat=="number"&&(v=f.clearcoat),typeof f.clearcoatRoughness=="number"&&(E=f.clearcoatRoughness),typeof f.ior=="number"&&(_=f.ior);let w=typeof f.opacity=="number"?f.opacity:1,g=typeof f.transmission=="number"?f.transmission:0;if(b=w*(1-g),f.emissive&&(f.emissive.r>0||f.emissive.g>0||f.emissive.b>0)){let M=f.emissiveIntensity??1;S=[f.emissive.r*M,f.emissive.g*M,f.emissive.b*M]}}let y,T=e?.animateCallback||e?.animateFn||(typeof n.userData?.animate=="function"?n.userData.animate:typeof n.__animateFn=="function"?n.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0);if(typeof T=="function"){let f=e?.duration??4,w=e?.fps??4,g=Math.max(2,Math.round(f*w)+1),M=[],L=[],A=[],D=[],R=[r.position.x,r.position.y,r.position.z],N=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],H=[r.scale.x,r.scale.y,r.scale.z],V=!1;for(let B=0;B<g;B++){let P=B/(g-1)*f;M.push(P);try{T(P)}catch{}L.push([r.position.x,r.position.y,r.position.z]),A.push([r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w]),D.push([r.scale.x,r.scale.y,r.scale.z]),(Math.abs(r.position.x-R[0])>1e-4||Math.abs(r.position.y-R[1])>1e-4||Math.abs(r.position.z-R[2])>1e-4||Math.abs(r.quaternion.x-N[0])>1e-4||Math.abs(r.quaternion.y-N[1])>1e-4||Math.abs(r.quaternion.z-N[2])>1e-4||Math.abs(r.quaternion.w-N[3])>1e-4||Math.abs(r.scale.x-H[0])>1e-4)&&(V=!0)}r.position.set(R[0],R[1],R[2]),r.quaternion.set(N[0],N[1],N[2],N[3]),r.scale.set(H[0],H[1],H[2]),V&&(y={times:M,translations:L,rotations:A,scales:D})}t.push({name:r.name||`Mesh_${t.length}`,positions:l,indices:h,normals:o,uvs:c,materialName:m,color:p,roughness:d,metallic:x,clearcoat:v,clearcoatRoughness:E,ior:_,opacity:b,emissiveColor:S,xrTraits:r.userData?.xr,timeSamples:y})}}),t}function Sn(n){let e=[],t=n.gltf,r=n.bin,i=r instanceof ArrayBuffer?r:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),s=t.accessors||[],a=t.bufferViews||[],l=t.materials||[],u=t.meshes||[],o=t.nodes||[];function c(p){let d=s[p];if(!d)throw new Error(`Accessor ${p} not found`);let x=a[d.bufferView||0],v=(x.byteOffset||0)+(d.byteOffset||0),E=x.byteLength||0,_=i.slice(v,v+E);return{acc:d,buffer:_}}let h=new Map;if(o.length>0){let p=je(t);for(let d=0;d<p.length;d++)h.set(d,p[d])}function m(p,d,x,v){let E=u[p];if(!E)return;let _=new Float32Array(9);se(_,d);for(let b=0;b<(E.primitives||[]).length;b++){let S=E.primitives[b],y=S.attributes?.POSITION;if(y===void 0)continue;let{acc:T,buffer:f}=c(y),w=new Float32Array(f,0,T.count*3),g=new Float32Array(w.length);for(let F=0;F<T.count;F++){let z=w[F*3],q=w[F*3+1],G=w[F*3+2];g[F*3]=d[0]*z+d[4]*q+d[8]*G+d[12],g[F*3+1]=d[1]*z+d[5]*q+d[9]*G+d[13],g[F*3+2]=d[2]*z+d[6]*q+d[10]*G+d[14]}let M,L=S.attributes?.NORMAL;if(L!==void 0){let{acc:F,buffer:z}=c(L),q=new Float32Array(z,0,F.count*3);M=new Float32Array(q.length);for(let G=0;G<F.count;G++){let ue=q[G*3],J=q[G*3+1],ne=q[G*3+2],be=_[0]*ue+_[3]*J+_[6]*ne,ye=_[1]*ue+_[4]*J+_[7]*ne,le=_[2]*ue+_[5]*J+_[8]*ne,ie=Math.hypot(be,ye,le)||1;M[G*3]=be/ie,M[G*3+1]=ye/ie,M[G*3+2]=le/ie}}let A,D=S.attributes?.TEXCOORD_0;if(D!==void 0){let{acc:F,buffer:z}=c(D);A=new Float32Array(z,0,F.count*2)}let R;if(S.indices!==void 0){let{acc:F,buffer:z}=c(S.indices);F.componentType===5125?R=new Uint32Array(z,0,F.count):R=new Uint16Array(z,0,F.count);let q=T.count;for(let G of R)if(G>=q)throw new Error(`SecurityError: Index buffer value (${G}) out of vertex bounds [0, ${q}).`)}else{let F=T.count;R=F>65535?new Uint32Array(F):new Uint16Array(F);for(let z=0;z<F;z++)R[z]=z}let N="DefaultMaterial",H=[.8,.8,.8],V=.5,B=.1,P=0,I=0,C=1.5,k=1,U=[0,0,0];if(S.material!==void 0&&l[S.material]){let F=l[S.material];N=F.name||`Material_${S.material}`;let z=F.pbrMetallicRoughness||{},q=1;Array.isArray(z.baseColorFactor)&&(H=[z.baseColorFactor[0],z.baseColorFactor[1],z.baseColorFactor[2]],typeof z.baseColorFactor[3]=="number"&&(q=z.baseColorFactor[3])),typeof z.roughnessFactor=="number"&&(V=z.roughnessFactor),typeof z.metallicFactor=="number"&&(B=z.metallicFactor),Array.isArray(F.emissiveFactor)&&F.emissiveFactor.length>=3&&(U=[F.emissiveFactor[0],F.emissiveFactor[1],F.emissiveFactor[2]]);let G=F.extensions||{};G.KHR_materials_clearcoat&&(P=G.KHR_materials_clearcoat.clearcoatFactor??0,I=G.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),G.KHR_materials_ior&&typeof G.KHR_materials_ior.ior=="number"&&(C=G.KHR_materials_ior.ior);let ue=G.KHR_materials_transmission?.transmissionFactor??0;k=q*(1-ue)}let O=(E.primitives||[]).length>1?`${x}_p${b}`:x;e.push({name:O,positions:g,indices:R,normals:M,uvs:A,materialName:N,color:H,roughness:V,metallic:B,clearcoat:P,clearcoatRoughness:I,ior:C,opacity:k,emissiveColor:U,xrTraits:v?.xr||E.extras?.xr})}}if(o.length>0)for(let p=0;p<o.length;p++){let d=o[p];if(d.mesh!==void 0&&d.mesh<u.length){let x=h.get(p)||Q(),v=d.name||u[d.mesh].name||`Node_${p}`;m(d.mesh,x,v,d.extras)}}else{let p=Q();for(let d=0;d<u.length;d++){let x=u[d].name||`Mesh_${d}`;m(d,p,x,u[d].extras)}}return e}function gt(n,e){if(!n||typeof n!="string")return e;let t=n.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(t)&&(t="_"+t),t||e}function vn(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function X(n){if(!Number.isFinite(n)||Math.abs(n)<1e-7)return"0";let e=Number(n.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}function wn(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${X(n[r*3])}, ${X(n[r*3+1])}, ${X(n[r*3+2])})`;return t.join(", ")}function cr(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${X(n[r*2])}, ${X(1-n[r*2+1])})`;return t.join(", ")}function ur(n){return Array.from(n).join(", ")}function xt(n){let e=new Map;for(let u of n){let o=gt(u.materialName,"DefaultMaterial");e.has(o)||e.set(o,{color:u.color||[.8,.8,.8],roughness:u.roughness??.5,metallic:u.metallic??0,clearcoat:u.clearcoat??0,clearcoatRoughness:u.clearcoatRoughness??0,ior:u.ior??1.5,opacity:u.opacity??1,emissiveColor:u.emissiveColor||[0,0,0]})}let t=0,r=null;for(let u of n){if(u.timeSamples&&u.timeSamples.times.length>0){let o=u.timeSamples.times[u.timeSamples.times.length-1];o>t&&(t=o)}u.xrTraits?.anchor&&!r&&(r=u.xrTraits.anchor==="vertical"||u.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
220
+ endTimeCode = ${X(t)}
221
+ timeCodesPerSecond = 1.0
222
+ `);let s="";r&&(s=`uniform token preliminary:anchoring:type = "plane"
223
+ uniform token preliminary:planeAnchoring:alignment = "${r}"
224
+ `);let a=`#usda 1.0
225
+ (
226
+ defaultPrim = "Root"
227
+ metersPerUnit = 1.0
228
+ upAxis = "Y"
229
+ ${i})
230
+
231
+ def Xform "Root" (
232
+ kind = "component"
233
+ )
234
+ {
235
+ ${s}def Scope "Materials"
236
+ {
237
+ `;for(let[u,o]of e.entries()){let[c,h,m]=o.color,[p,d,x]=o.emissiveColor,v="";o.clearcoat>0&&(v+=`float inputs:clearcoat = ${X(o.clearcoat)}
238
+ `,v+=`float inputs:clearcoatRoughness = ${X(o.clearcoatRoughness)}
239
+ `),o.ior!==1.5&&(v+=`float inputs:ior = ${X(o.ior)}
240
+ `),o.opacity<1&&(v+=`float inputs:opacity = ${X(o.opacity)}
241
+ `),(p>0||d>0||x>0)&&(v+=`color3f inputs:emissiveColor = (${X(p)}, ${X(d)}, ${X(x)})
242
+ `),a+=`def Material "${u}"
243
+ {
244
+ def Shader "PBRShader"
245
+ {
246
+ uniform token info:id = "UsdPreviewSurface"
247
+ color3f inputs:diffuseColor = (${X(c)}, ${X(h)}, ${X(m)})
248
+ float inputs:metallic = ${X(o.metallic)}
249
+ float inputs:roughness = ${X(o.roughness)}
250
+ ${v}token outputs:surface
251
+ }
252
+ token outputs:surface.connect = </Root/Materials/${u}/PBRShader.outputs:surface>
253
+ }
254
+ `}a+=`}
255
+ def Scope "Meshes"
256
+ {
257
+ `;let l=new Set;for(let u=0;u<n.length;u++){let o=n[u],c=o.positions.length/3,h=1/0,m=1/0,p=1/0,d=-1/0,x=-1/0,v=-1/0;for(let f=0;f<c;f++){let w=o.positions[f*3],g=o.positions[f*3+1],M=o.positions[f*3+2];w<h&&(h=w),w>d&&(d=w),g<m&&(m=g),g>x&&(x=g),M<p&&(p=M),M>v&&(v=M)}isFinite(h)||(h=m=p=-1,d=x=v=1);let E=Math.floor(o.indices.length/3),_=gt(o.materialName,"DefaultMaterial"),b=gt(o.name,`Mesh_${u}`);l.has(b)&&(b=`${b}_${u}`),l.add(b);let S=E>0?E===1?"3":"3, ".repeat(E-1)+"3":"",y=o.xrTraits,T="";if(y){let f=[];y.physics&&y.physics!=="none"&&f.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let w=Y().xrTraitSerializer?.usdLines(y,vn)??[];if(!w.length)for(let g of["grab","billboard","follow","anchor","physics"]){let M=g==="follow"&&typeof y.follow=="object"?y.follow.mode??"head":y[g];M!==void 0&&w.push(`string ${g} = "${vn(M)}"`)}w.length>0&&f.push(`customData = {
258
+ dictionary xr = {
259
+ ${w.join(`
260
+ `)}
261
+ }
262
+ }`),f.length>0&&(T=` (
263
+ ${f.join(`
264
+ `)}
265
+ )`)}if(a+=`def Mesh "${b}"${T}
266
+ {
267
+ `,y?.physics&&y.physics!=="none"){let f=y.physics==="static"?"true":"false";a+=`bool physics:rigidBodyEnabled = true
268
+ bool physics:kinematicEnabled = ${f}
269
+ bool physics:collisionEnabled = true
270
+ `}if(o.timeSamples&&o.timeSamples.times.length>0){let f=o.timeSamples,w=f.times.map((L,A)=>{let D=f.translations?.[A]||[0,0,0];return`${X(L)}: (${X(D[0])}, ${X(D[1])}, ${X(D[2])})`}).join(", "),g=f.times.map((L,A)=>{let D=f.rotations?.[A]||[0,0,0,1];return`${X(L)}: (${X(D[3])}, ${X(D[0])}, ${X(D[1])}, ${X(D[2])})`}).join(", "),M=f.times.map((L,A)=>{let D=f.scales?.[A]||[1,1,1];return`${X(L)}: (${X(D[0])}, ${X(D[1])}, ${X(D[2])})`}).join(", ");a+=`double3 xformOp:translate.timeSamples = { ${w} }
271
+ quatf xformOp:orient.timeSamples = { ${g} }
272
+ double3 xformOp:scale.timeSamples = { ${M} }
273
+ uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
274
+ `}a+=`float3[] extent = [(${X(h)}, ${X(m)}, ${X(p)}), (${X(d)}, ${X(x)}, ${X(v)})]
275
+ int[] faceVertexCounts = [${S}]
276
+ int[] faceVertexIndices = [${ur(o.indices)}]
277
+ point3f[] points = [${wn(o.positions)}]
278
+ `,o.normals&&o.normals.length===o.positions.length&&(a+=`normal3f[] normals = [${wn(o.normals)}] (
279
+ interpolation = "vertex"
280
+ )
281
+ `),o.uvs&&o.uvs.length===c*2&&(a+=`texCoord2f[] primvars:st = [${cr(o.uvs,c)}] (
282
+ interpolation = "vertex"
283
+ )
284
+ `),a+=`rel material:binding = </Root/Materials/${_}>
285
+ }
286
+ `}return a+=`}
287
+ }
288
+ `,a}function Rn(n,e){if(n&&typeof n.traverse=="function"){let i=ar(n,e);return xt(i)}let t=ve(n),r=Sn(t);return xt(r)}var Ke=null;function An(n){if(!Ke){Ke=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;Ke[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=Ke[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function vt(n){let e=[],t=0,r=[];for(let c of n){let h=Ze(c.filename),m=An(c.data),p=c.data.length,d=30+h.length,x=t+d,v=0,E=x%64;E!==0&&(v=64-E);let _=new Uint8Array(d+v),b=new DataView(_.buffer);b.setUint32(0,67324752,!0),b.setUint16(4,20,!0),b.setUint16(6,0,!0),b.setUint16(8,0,!0),b.setUint16(10,0,!0),b.setUint16(12,0,!0),b.setUint32(14,m,!0),b.setUint32(18,p,!0),b.setUint32(22,p,!0),b.setUint16(26,h.length,!0),b.setUint16(28,v,!0),_.set(h,30),v>0&&_.fill(0,30+h.length),e.push({offset:t,size:p,crc:m,filenameBytes:h,entry:c}),r.push(_),r.push(c.data),t+=_.length+c.data.length}let i=t;for(let c of e){let h=new Uint8Array(46+c.filenameBytes.length),m=new DataView(h.buffer);m.setUint32(0,33639248,!0),m.setUint16(4,20,!0),m.setUint16(6,20,!0),m.setUint16(8,0,!0),m.setUint16(10,0,!0),m.setUint16(12,0,!0),m.setUint16(14,0,!0),m.setUint32(16,c.crc,!0),m.setUint32(20,c.size,!0),m.setUint32(24,c.size,!0),m.setUint16(28,c.filenameBytes.length,!0),m.setUint16(30,0,!0),m.setUint16(32,0,!0),m.setUint16(34,0,!0),m.setUint16(36,0,!0),m.setUint32(38,0,!0),m.setUint32(42,c.offset,!0),h.set(c.filenameBytes,46),r.push(h),t+=h.length}let s=t-i,a=new Uint8Array(22),l=new DataView(a.buffer);l.setUint32(0,101010256,!0),l.setUint16(4,0,!0),l.setUint16(6,0,!0),l.setUint16(8,e.length,!0),l.setUint16(10,e.length,!0),l.setUint32(12,s,!0),l.setUint32(16,i,!0),l.setUint16(20,0,!0),r.push(a),t+=22;let u=new Uint8Array(t),o=0;for(let c of r)u.set(c,o),o+=c.length;return u}function Ue(n){let e=Rn(n),t=Ze(e);return vt([{filename:"model.usda",data:t}])}function ke(n){let e=ve(n),t=Sn(e),r=xt(t),i=Ze(r);return vt([{filename:"model.usda",data:i}])}function wt(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?Ue(n):ke(n)}function Ne(n){let e=n&&typeof n.toUSDZ=="function"?n.toUSDZ():ke(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}var At=class n{constructor(e=0,t=0){this.x=Number(e),this.y=Number(t)}set(e,t){return this.x=Number(e),this.y=Number(t),this}clone(){return new n(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}sub(e){return this.x-=e.x,this.y-=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}},K=class n{constructor(e=0,t=0,r=0){this.x=Number(e),this.y=Number(t),this.z=Number(r)}set(e,t,r){return this.x=Number(e),this.y=Number(t),this.z=Number(r),this}clone(){return new n(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let e=this.length();return e>1e-5&&(this.x/=e,this.y/=e,this.z/=e),this}cross(e){let t=this.y*e.z-this.z*e.y,r=this.z*e.x-this.x*e.z,i=this.x*e.y-this.y*e.x;return this.x=t,this.y=r,this.z=i,this}crossVectors(e,t){let r=e.x,i=e.y,s=e.z,a=t.x,l=t.y,u=t.z;return this.x=i*u-s*l,this.y=s*a-r*u,this.z=r*l-i*a,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y,this.z-e.z)}applyMatrix4(e){let t=this.x,r=this.y,i=this.z,s=e.elements,a=1/(s[3]*t+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*r+s[8]*i+s[12])*a,this.y=(s[1]*t+s[5]*r+s[9]*i+s[13])*a,this.z=(s[2]*t+s[6]*r+s[10]*i+s[14])*a,this}},Et=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}},et=class n{constructor(e=0,t=0,r=0,i="XYZ"){this._onChangeCallback=null;this._x=Number(e),this._y=Number(t),this._z=Number(r),this.order=i}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}set(e,t,r,i=this.order){return this._x=Number(e),this._y=Number(t),this._z=Number(r),this.order=i,this._onChangeCallback?.(),this}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this.order=e.order,this._onChangeCallback?.(),this}clone(){return new n(this._x,this._y,this._z,this.order)}_onChange(e){return this._onChangeCallback=e,this}},tt=class n{constructor(e=0,t=0,r=0,i=1){this._onChangeCallback=null;this._x=Number(e),this._y=Number(t),this._z=Number(r),this._w=Number(i)}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}get w(){return this._w}set w(e){this._w=Number(e),this._onChangeCallback?.()}set(e,t,r,i){return this._x=Number(e),this._y=Number(t),this._z=Number(r),this._w=Number(i),this._onChangeCallback?.(),this}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback?.(),this}clone(){return new n(this._x,this._y,this._z,this._w)}setFromEuler(e,t=!0){let r=e.x,i=e.y,s=e.z,a=Math.cos(r/2),l=Math.cos(i/2),u=Math.cos(s/2),o=Math.sin(r/2),c=Math.sin(i/2),h=Math.sin(s/2);return this._x=o*l*u+a*c*h,this._y=a*c*u-o*l*h,this._z=a*l*h+o*c*u,this._w=a*l*u-o*c*h,t&&this._onChangeCallback?.(),this}setFromAxisAngle(e,t){let r=t/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback?.(),this}multiply(e){return this.multiplyQuaternions(this,e)}multiplyQuaternions(e,t){let r=e.x,i=e.y,s=e.z,a=e.w,l=t.x,u=t.y,o=t.z,c=t.w;return this._x=r*c+a*l+i*o-s*u,this._y=i*c+a*u+s*l-r*o,this._z=s*c+a*o+r*u-i*l,this._w=a*c-r*l-i*u-s*o,this._onChangeCallback?.(),this}_onChange(e){return this._onChangeCallback=e,this}},Te=class n{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,this}copy(e){return this.elements.set(e.elements),this}clone(){let e=new n;return e.copy(this),e}compose(e,t,r){return Ye(this.elements,[t.x,t.y,t.z,t.w],[e.x,e.y,e.z],[r.x,r.y,r.z]),this}multiply(e){return this.multiplyMatrices(this,e)}multiplyMatrices(e,t){return re(this.elements,e.elements,t.elements),this}lookAt(e,t,r){return qe(this.elements,[e.x,e.y,e.z],[t.x,t.y,t.z],[r.x,r.y,r.z]),this}makeRotationFromQuaternion(e){let t=new K(0,0,0),r=new K(1,1,1);return this.compose(t,e,r)}makeTranslation(e,t,r){return this.identity(),this.elements[12]=Number(e),this.elements[13]=Number(t),this.elements[14]=Number(r),this}makeScale(e,t,r){return this.identity(),this.elements[0]=Number(e),this.elements[5]=Number(t),this.elements[10]=Number(r),this}},Tt=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 se(this.elements,e.elements),this}},he=class n{constructor(e,t,r){this.r=1;this.g=1;this.b=1;e!==void 0&&(t!==void 0&&r!==void 0?this.setRGB(e,t,r):this.set(e))}set(e){if(typeof e=="number")this.setHex(e);else if(typeof e=="string")if(e.startsWith("#")){let t=parseInt(e.slice(1),16);this.setHex(t)}else e==="red"?this.setRGB(1,0,0):e==="green"?this.setRGB(0,1,0):e==="blue"?this.setRGB(0,0,1):e==="white"?this.setRGB(1,1,1):e==="black"&&this.setRGB(0,0,0);else e&&typeof e=="object"&&"r"in e&&(this.r=Number(e.r),this.g=Number(e.g),this.b=Number(e.b));return this}setHex(e){let t=Math.floor(e);return this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,this}setRGB(e,t,r){return this.r=Number(e),this.g=Number(t),this.b=Number(r),this}getHex(){return Math.round(Math.max(0,Math.min(1,this.r))*255)<<16|Math.round(Math.max(0,Math.min(1,this.g))*255)<<8|Math.round(Math.max(0,Math.min(1,this.b))*255)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}clone(){return new n(this.r,this.g,this.b)}},lr={degToRad:n=>n*Math.PI/180,radToDeg:n=>n*180/Math.PI,clamp:(n,e,t)=>Math.max(e,Math.min(t,n)),lerp:(n,e,t)=>n+(e-n)*t,generateUUID:()=>Math.random().toString(36).substring(2,15),randFloat:(n,e)=>n+Math.random()*(e-n)},W=class{constructor(e,t){this.needsUpdate=!1;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(t)}`);Array.isArray(e)?this.array=new Float32Array(e):this.array=e,this.itemSize=t;let r=this.array?this.array.length:0;if(!Number.isFinite(r)||r<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(r)}`);this.count=Math.floor(r/t)}getX(e){return this.array[e*this.itemSize]}getY(e){return this.array[e*this.itemSize+1]}getZ(e){return this.array[e*this.itemSize+2]}setX(e,t){return this.array[e*this.itemSize]=t,this.needsUpdate=!0,this}setY(e,t){return this.array[e*this.itemSize+1]=t,this.needsUpdate=!0,this}setZ(e,t){return this.array[e*this.itemSize+2]=t,this.needsUpdate=!0,this}setXYZ(e,t,r,i){let s=e*this.itemSize;return this.array[s]=t,this.array[s+1]=r,this.array[s+2]=i,this.needsUpdate=!0,this}},Mt=class extends W{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},_t=class extends W{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Ct=class extends W{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},ae=class{constructor(){this.name="";this.attributes={};this.index=null;this.boundingBox=null}setAttribute(e,t){return this.attributes[e]=t,this}getAttribute(e){return this.attributes[e]}setIndex(e){if(e instanceof W)this.index=e;else if(Array.isArray(e)){let t=0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);let r=t>65535?new Uint32Array(e):new Uint16Array(e);this.index=new W(r,1)}else e&&e.buffer&&(this.index=new W(e,1));return this}computeVertexNormals(){let e=this.attributes.position;if(!e)return this;let t=e.count,r=new Float32Array(t*3),i=new K,s=new K,a=new K,l=new K,u=new K;if(this.index){let o=this.index.array;for(let c=0;c<o.length;c+=3){let h=o[c],m=o[c+1],p=o[c+2];i.set(e.getX(h),e.getY(h),e.getZ(h)),s.set(e.getX(m),e.getY(m),e.getZ(m)),a.set(e.getX(p),e.getY(p),e.getZ(p)),l.subVectors(a,s),u.subVectors(i,s),l.cross(u).normalize();for(let d of[h,m,p])r[d*3]+=l.x,r[d*3+1]+=l.y,r[d*3+2]+=l.z}}else for(let o=0;o<t;o+=3){i.set(e.getX(o),e.getY(o),e.getZ(o)),s.set(e.getX(o+1),e.getY(o+1),e.getZ(o+1)),a.set(e.getX(o+2),e.getY(o+2),e.getZ(o+2)),l.subVectors(a,s),u.subVectors(i,s),l.cross(u).normalize();for(let c=0;c<3;c++)r[(o+c)*3]=l.x,r[(o+c)*3+1]=l.y,r[(o+c)*3+2]=l.z}for(let o=0;o<t;o++){let c=r[o*3],h=r[o*3+1],m=r[o*3+2],p=Math.hypot(c,h,m)||1;r[o*3]=c/p,r[o*3+1]=h/p,r[o*3+2]=m/p}return this.setAttribute("normal",new W(r,3)),this}setFromBuffers(e,t,r,i){this.setAttribute("position",new W(e instanceof Float32Array?e:new Float32Array(e),3)),this.setAttribute("normal",new W(t instanceof Float32Array?t:new Float32Array(t),3)),this.setAttribute("uv",new W(r instanceof Float32Array?r:new Float32Array(r),2)),this.setIndex(i)}dispose(){}},nt=class extends ae{constructor(e=1,t=1,r=1){super();let i=e/2,s=t/2,a=r/2,l=[-i,-s,a,i,-s,a,i,s,a,-i,s,a,i,-s,-a,-i,-s,-a,-i,s,-a,i,s,-a,-i,s,a,i,s,a,i,s,-a,-i,s,-a,-i,-s,-a,i,-s,-a,i,-s,a,-i,-s,a,i,-s,a,i,-s,-a,i,s,-a,i,s,a,-i,-s,-a,-i,-s,a,-i,s,a,-i,s,-a],u=[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],o=[0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1],c=[];for(let h=0;h<6;h++){let m=h*4;c.push(m,m+1,m+2,m,m+2,m+3)}this.setAttribute("position",new W(new Float32Array(l),3)),this.setAttribute("normal",new W(new Float32Array(u),3)),this.setAttribute("uv",new W(new Float32Array(o),2)),this.setIndex(c)}},Dt=class extends ae{constructor(e=1,t=1){super();let r=e/2,i=t/2,s=[-r,i,0,r,i,0,-r,-i,0,r,-i,0],a=[0,0,1,0,0,1,0,0,1,0,0,1],l=[0,1,1,1,0,0,1,0],u=[0,2,1,2,3,1];this.setAttribute("position",new W(new Float32Array(s),3)),this.setAttribute("normal",new W(new Float32Array(a),3)),this.setAttribute("uv",new W(new Float32Array(l),2)),this.setIndex(u)}},rt=class extends ae{constructor(e=1,t=16,r=12){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let i=[],s=[],a=[],l=[],u=[];for(let o=0;o<=r;o++){let c=[],h=o/r;for(let m=0;m<=t;m++){let p=m/t,d=p*Math.PI*2,x=h*Math.PI,v=-e*Math.cos(d)*Math.sin(x),E=e*Math.cos(x),_=e*Math.sin(d)*Math.sin(x);i.push(v,E,_);let b=Math.hypot(v,E,_)||1;s.push(v/b,E/b,_/b),a.push(p,1-h),c.push(i.length/3-1)}u.push(c)}for(let o=0;o<r;o++)for(let c=0;c<t;c++){let h=u[o][c+1],m=u[o][c],p=u[o+1][c],d=u[o+1][c+1];o!==0&&l.push(h,m,d),o!==r-1&&l.push(m,p,d)}this.setAttribute("position",new W(new Float32Array(i),3)),this.setAttribute("normal",new W(new Float32Array(s),3)),this.setAttribute("uv",new W(new Float32Array(a),2)),this.setIndex(l)}},Se=class extends ae{constructor(e=1,t=1,r=1,i=16){super(),i=Math.max(3,Math.floor(i));let s=[],a=[],l=[],u=[],o=r/2;for(let c=0;c<=1;c++){let h=c,m=c===0?e:t,p=c===0?o:-o;for(let d=0;d<=i;d++){let x=d/i,v=x*Math.PI*2,E=Math.sin(v),_=Math.cos(v);s.push(m*E,p,m*_),a.push(E,0,_),l.push(x,1-h)}}for(let c=0;c<i;c++){let h=c,m=c+i+1,p=c+i+2,d=c+1;u.push(h,m,d,m,p,d)}if(e>0){let c=s.length/3;s.push(0,o,0),a.push(0,1,0),l.push(.5,.5);let h=s.length/3;for(let m=0;m<=i;m++){let p=m/i*Math.PI*2,d=Math.sin(p),x=Math.cos(p);s.push(e*d,o,e*x),a.push(0,1,0),l.push(x*.5+.5,d*.5+.5)}for(let m=0;m<i;m++)u.push(c,h+m,h+m+1)}if(t>0){let c=s.length/3;s.push(0,-o,0),a.push(0,-1,0),l.push(.5,.5);let h=s.length/3;for(let m=0;m<=i;m++){let p=m/i*Math.PI*2,d=Math.sin(p),x=Math.cos(p);s.push(t*d,-o,t*x),a.push(0,-1,0),l.push(x*.5+.5,1-(d*.5+.5))}for(let m=0;m<i;m++)u.push(c,h+m+1,h+m)}this.setAttribute("position",new W(new Float32Array(s),3)),this.setAttribute("normal",new W(new Float32Array(a),3)),this.setAttribute("uv",new W(new Float32Array(l),2)),this.setIndex(u)}},Lt=class extends Se{constructor(e=1,t=1,r=16){super(0,e,t,r)}},Pt=class extends ae{constructor(e=1,t=.4,r=12,i=32){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let s=[],a=[],l=[],u=[];for(let o=0;o<=r;o++){let c=o/r*Math.PI*2;for(let h=0;h<=i;h++){let m=h/i*Math.PI*2,p=(e+t*Math.cos(c))*Math.cos(m),d=(e+t*Math.cos(c))*Math.sin(m),x=t*Math.sin(c);s.push(p,d,x);let v=e*Math.cos(m),E=e*Math.sin(m),_=p-v,b=d-E,S=x,y=Math.hypot(_,b,S)||1;a.push(_/y,b/y,S/y),l.push(h/i,o/r)}}for(let o=1;o<=r;o++)for(let c=1;c<=i;c++){let h=(i+1)*o+c-1,m=(i+1)*(o-1)+c-1,p=(i+1)*(o-1)+c,d=(i+1)*o+c;u.push(h,m,d,m,p,d)}this.setAttribute("position",new W(new Float32Array(s),3)),this.setAttribute("normal",new W(new Float32Array(a),3)),this.setAttribute("uv",new W(new Float32Array(l),2)),this.setIndex(u)}},It=class extends ae{constructor(e=1,t=.4,r=64,i=8,s=2,a=3){super(),r=Math.floor(r),i=Math.floor(i);let l=[],u=[],o=[],c=[],h=new K,m=new K,p=new K,d=new K,x=new K;function v(b,S){let y=Math.cos(S),T=Math.sin(S),f=a/s*S,w=e*(2+Math.cos(f))*.5;b.set(w*y,w*T,e*Math.sin(f)*.5)}let E=[];for(let b=0;b<=i;++b){let S=b/i*Math.PI*2;E.push(-t*Math.cos(S),t*Math.sin(S),b/i)}for(let b=0;b<=r;++b){let S=b/r,y=S*s*Math.PI*2;v(h,y),v(m,y+.01),p.subVectors(m,h).normalize(),d.addVectors(h,m).normalize(),x.crossVectors(p,d).normalize(),d.crossVectors(x,p).normalize();for(let T=0;T<=i;++T){let f=T*3,w=E[f],g=E[f+1],M=E[f+2],L=w*d.x+g*x.x,A=w*d.y+g*x.y,D=w*d.z+g*x.z;l.push(h.x+L,h.y+A,h.z+D);let R=Math.hypot(L,A,D)||1;u.push(L/R,A/R,D/R),o.push(S,M)}}let _=i+1;for(let b=1;b<=r;b++){let S=_*(b-1),y=S+_;for(let T=1;T<=i;T++){let f=S+(T-1),w=y+(T-1),g=y+T,M=S+T;c.push(f,w,M,w,g,M)}}this.setAttribute("position",new W(new Float32Array(l),3)),this.setAttribute("normal",new W(new Float32Array(u),3)),this.setAttribute("uv",new W(new Float32Array(o),2)),this.setIndex(c)}},it=class{constructor(e=""){this.isTexture=!0;this.wrapS=10497;this.wrapT=10497;this.image=null;this.width=0;this.height=0;this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},Ft=class{load(e,t){let r=new it(e);return t?.(r),r}};function te(n,e){return n!==void 0?Number(n):e}function St(n,e){return n!==void 0?!!n:e}var pe=class{constructor(e={}){this.name=e.name||"",this.color=new he(e.color!==void 0?e.color:16777215),this.emissive=new he(e.emissive!==void 0?e.emissive:0),this.emissiveIntensity=te(e.emissiveIntensity,1),this.roughness=te(e.roughness,.5),this.metalness=te(e.metalness,.1),this.opacity=te(e.opacity,1),this.transparent=St(e.transparent,!1),this.wireframe=St(e.wireframe,!1),this.side=te(e.side,2),this.doubleSided=St(e.doubleSided,!0),this.map=e.map||null,this.clearcoat=te(e.clearcoat,0),this.clearcoatRoughness=te(e.clearcoatRoughness,0),this.sheen=te(e.sheen,0),this.sheenColor=new he(e.sheenColor!==void 0?e.sheenColor:0),this.sheenRoughness=te(e.sheenRoughness,0),this.transmission=te(e.transmission,0),this.thickness=te(e.thickness,0),this.attenuationColor=new he(e.attenuationColor!==void 0?e.attenuationColor:16777215),this.attenuationDistance=te(e.attenuationDistance,1/0),this.ior=te(e.ior,1.5),this.dispersion=te(e.dispersion,0),this.iridescence=te(e.iridescence,0),this.iridescenceIOR=te(e.iridescenceIOR,1.3)}dispose(){}},Me=class extends pe{},Ut=class extends pe{},kt=class extends pe{},Nt=class extends pe{},Ot=class extends pe{},me=class n{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 K,this.rotation=new et,this.quaternion=new tt,this.scale=new K(1,1,1),this.matrix=new Te,this.matrixWorld=new Te,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let e=this.quaternion,t=Math.atan2(2*(e.w*e.x+e.y*e.z),1-2*(e.x*e.x+e.y*e.y)),r=Math.asin(Math.max(-1,Math.min(1,2*(e.w*e.y-e.z*e.x)))),i=Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z));this.rotation.set(t,r,i)})}add(...e){for(let t of e)t&&t instanceof n&&(t.parent&&t.parent.remove(t),t.parent=this,this.children.push(t));return this}remove(...e){for(let t of e){let r=this.children.indexOf(t);r!==-1&&(t.parent=null,this.children.splice(r,1))}return this}traverse(e){e(this);for(let t of this.children)t.traverse(e)}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(e=!1){(this.matrixAutoUpdate||e)&&this.updateMatrix(),this.parent?this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix):this.matrixWorld.copy(this.matrix);for(let t of this.children)t.updateMatrixWorld(e)}lookAt(e,t,r){let i=typeof e=="object"?e:new K(e,t,r);this.updateMatrixWorld(!0);let s=new Te;s.lookAt(this.position,i,new K(0,1,0));let a=s.elements,l=a[0],u=a[4],o=a[8],c=a[1],h=a[5],m=a[9],p=a[2],d=a[6],x=a[10],v=l+h+x;if(v>0){let E=.5/Math.sqrt(v+1);this.quaternion.set((d-m)*E,(o-p)*E,(c-u)*E,.25/E)}}},Bt=class extends me{},Be=class extends me{constructor(t,r){super();this.isMesh=!0;let i=Array.isArray(r)?r[0]:r;this.geometry=t instanceof ae?t:t?(ce("unsupported geometry","BoxGeometry"),new nt(.5,.5,.5)):new ae,this.material=i instanceof pe?i:i?(ce("unsupported material","MeshStandardMaterial"),new Me({color:13421772})):new Me}},_e=class extends me{constructor(e=16777215,t=1){super(),this.color=new he(e),this.intensity=Number(t),this.type="directional"}},st=class extends _e{constructor(e,t){super(e,t),this.type="ambient"}},zt=class extends _e{constructor(t,r){super(t,r);this.target=new me;this.type="directional"}},ot=class extends _e{constructor(t,r,i=0,s=2){super(t,r);this.distance=0;this.decay=2;this.type="point",this.distance=i,this.decay=s}},at=class extends me{},Vt=class extends at{constructor(t=45,r=1,i=.1,s=1e3){super();this.target=new K(0,0,0);this.fov=Number(t),this.aspect=Number(r),this.near=Number(i),this.far=Number(s)}},ct=class extends me{constructor(){super(...arguments);this.background=null;this.environmentIntensity=1}toCanvas3D(){return fe.validate(this),Fe(this)}toGLB(){return fe.validate(this),Qe(this)}toUSDZ(){return fe.validate(this),Ue(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let t=new Map,r=0;return this.traverse(i=>{if(i instanceof Be){let s=new Float32Array(i.matrixWorld.elements);t.set(r,s),i.name&&t.set(i.name,s),r++}}),t}},Ln=Fe,Pn=Qe,hr=Ue;var fe=class{static validate(e){let t=0,r=0,i=0,s=new Set,a=(u,o,c)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${u} (${o}). Found: ${c}`)},l=(u,o)=>{if(!Number.isFinite(o))throw new Error(`SecurityError: Scene reports a non-finite ${u} count (${String(o)}), which cannot be bounds-checked.`);return o};e.traverse(u=>{if(u instanceof Be){i++,i>1e3&&a("MESHES",1e3,i);let o=u.geometry;if(o){let c=0;if(o.attributes.position&&(c=l("vertex",o.attributes.position.count),t+=c,t>1e5&&a("VERTICES",1e5,t)),o.index){let h=l("index",o.index.count);r+=h,r>3e5&&a("INDICES",3e5,r);let m=o.index.array;if(m&&c>0){let p=Math.min(h,m.length);for(let d=0;d<p;d++){let x=m[d];if(!Number.isFinite(x)||x<0||x>=c)throw new Error(`SecurityError: Index buffer value (${String(x)}) out of vertex bounds [0, ${c}).`)}}}}if(u.material){let c=u.material;c.map&&s.add(c.map),c.normalMap&&s.add(c.normalMap),c.roughnessMap&&s.add(c.roughnessMap)}}}),s.size>16&&a("TEXTURES",16,s.size);for(let u of s){let o=u,c=o.image,h=Number(c?.width??o.width??0)||0,m=Number(c?.height??o.height??0)||0;(!Number.isFinite(h)||!Number.isFinite(m)||h>2048||m>2048)&&a("TEXTURE_DIMENSION",2048,Math.max(h,m))}}},Ht=class{constructor(e={}){this.shadowMap={enabled:!1,type:0};this.capabilities={isWebGL2:!0,maxTextures:16};this.boundViewer=null;this.isSandboxed=!1;this.containerId="";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 he(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){fe.validate(e);let i=(s,a)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(a&&a.length?self.postMessage(s,a):self.postMessage(s))};if(this.hasInitialModelRendered){let s=e.getMeshTransforms(),a={};for(let[l,u]of s.entries())a[l]=Array.from(u);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:a})}else{this.hasInitialModelRendered=!0;let s=Ln(e),a=Pn(e),l=(s.lights||[]).map(u=>({type:u.type,color:u.color,intensity:u.intensity,position:u.position}));i({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:a.buffer,dynamicLights:l,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 En(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Xt=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=En(),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=En();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function mr(){}var Je=new Proxy(mr,{get:(n,e)=>{if(e==="isProxy")return!0;if(!(e==="constructor"||e==="__proto__"||e==="prototype"))return e==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:e==="shadowMap"?{enabled:!1,type:0}:e==="capabilities"?{isWebGL2:!0,maxTextures:16}:e===Symbol.toPrimitive?()=>0:Je},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>Je,construct:()=>Je}),Tn=(()=>{try{if(typeof document>"u")return null;let n=document.currentScript;return n?.src?n.src:n?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([n.textContent],{type:"text/javascript"})):null}catch{return null}})();function Le(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Re(n,e){if(!n||typeof n!="string")return!1;let t=n.trim();if(!t)return!1;try{let r=new URL(t,Le());return!(r.protocol!=="https:"&&r.protocol!=="http:"&&r.protocol!=="blob:"||e?.requireSameOrigin&&r.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&r.origin!==location.origin)}catch{return!1}}var Mn,Oe;function dr(n){if(!Re(n))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${n}".`);let t=globalThis.trustedTypes;if(!t||typeof t.createPolicy!="function")return n;if(Oe===void 0||Mn!==t){Mn=t;try{Oe=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!Re(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{Oe=null}}return Oe?Oe.createScriptURL(n):n}function In(){let n=Y().sandboxEngineSrc;if(n)return n;if(Tn)return Tn;try{if(typeof document>"u")return null;let e=Le(),t=Array.from(document.querySelectorAll("script[src]"));for(let r of t){let i=r.src;if(!i)continue;let s=new URL(i,e).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(s)&&Re(i,{requireSameOrigin:!0}))return i}}catch{}return null}function fr(){let n=In();if(!n)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.");if(!Re(n))throw new Error(`SecurityError: Refusing to load sandbox engine from disallowed URL "${n}". Only http:, https:, and blob: URLs are permitted.`);return new URL(n,Le()).href}function pr(){let n=Y().sandboxIframeSrc;if(n)return n;let e=In();if(!e||!Re(e))return null;let t=new URL(e,Le());return t.protocol==="blob:"?null:new URL("three-live-sandbox.html",t).href}function br(){let n=pr();if(!n)throw new Error("Three-Live could not locate three-live-sandbox.html for iframe sandbox execution. Set ThreeLiveElement.sandboxIframeSrc (or ThreeLiveElement.sandboxEngineSrc) explicitly.");if(!Re(n))throw new Error(`SecurityError: Refusing to load sandbox iframe from disallowed URL "${n}". Only http:, https:, and blob: URLs are permitted.`);return new URL(n,Le()).href}function yr(){return!!Y().allowClientScripts}function gr(n){if(!Re(n))throw new Error(`SecurityError: Refusing to load procedural scene script from disallowed URL "${n}". Only http:, https:, and blob: URLs are permitted.`);return new URL(n,Le()).href}var xr=["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 vr(n){let e=self,t=n.nonce,r=n.engineSrc,i=n.allowedScriptUrl,s=n.allowClientScripts,a=n.revoked,l=e.postMessage.bind(e);function u(y){l({type:"ERROR",nonce:t,message:String(y)})}let o=typeof e.importScripts=="function"?e.importScripts.bind(e):null,c=i,h=null;try{let y=r;if(typeof e.trustedTypes<"u"&&e.trustedTypes&&typeof e.trustedTypes.createPolicy=="function")try{let T={createScriptURL:function(w){if(w!==r&&(!i||w!==i))throw new TypeError("Disallowed worker importScripts URL");return w}};s&&(T.createScript=function(w){return String(w)});let f=e.trustedTypes.createPolicy("three-live#worker-boot",T);y=f.createScriptURL(r),i&&(c=f.createScriptURL(i)),s&&typeof f.createScript=="function"&&(h=f.createScript.bind(f))}catch{}o(y)}catch(y){u('Sandbox failed to load the Three-Live engine from "'+r+'". It must be a same-origin (or CORS-enabled) IIFE bundle such as three-live.min.js. Underlying error: '+(y&&y.message||y));return}let m=e.THREE;if(!m||typeof m.Scene!="function"){u('Sandbox loaded "'+r+'" but it did not install a THREE namespace. Point sandboxEngineSrc at an IIFE build (three-live.min.js), not an ES module build.');return}for(let y=0;y<a.length;y++){let T=a[y],f=e;for(;f&&f!==Object.prototype;){if(f!==e)try{delete f[T]}catch{}try{Object.defineProperty(f,T,{value:void 0,writable:!1,configurable:!1,enumerable:!1})}catch{}try{f=Object.getPrototypeOf(f)}catch{break}}}let p=Object.freeze({now:function(){return Date.now()}}),d=e;for(;d&&d!==Object.prototype;){if(d!==e)try{delete d.performance}catch{}try{Object.defineProperty(d,"performance",{value:p,writable:!1,configurable:!1,enumerable:!1})}catch{}try{d=Object.getPrototypeOf(d)}catch{break}}let x=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],v=!1;function E(y,T){if(y.type==="3D_MODEL_READY"){if(v)return;v=!0}y.nonce=t,T&&T.length?l(y,T):l(y)}let _=function(y,T){if(!y||x.indexOf(y.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+x.join(", ")+").");E(y,T)},b=e;for(;b&&b!==Object.prototype;){if(b===e||Object.prototype.hasOwnProperty.call(b,"postMessage"))try{Object.defineProperty(b,"postMessage",{value:_,writable:!1,configurable:!1})}catch{}try{b=Object.getPrototypeOf(b)}catch{break}}let S=!1;e.onmessage=function(y){let T=y&&y.data;if(!(!T||T.nonce!==t)&&!(T.type!=="EXECUTE"&&T.type!=="EXECUTE_URL")&&!S){S=!0;try{let f=new m.Scene,w=new m.PerspectiveCamera(60,1,.1,1e3),g=new m.WebGLRenderer({isSandboxed:!0});if(T.type==="EXECUTE_URL"){if(!i||T.scriptUrl!==i||typeof o!="function"){u("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let M=c||i,L=o;if(o=null,c=null,e.THREE=m,e.scene=f,e.camera=w,e.renderer=g,L(M),typeof e.__THREE_LIVE_SCENE__=="function"){let A=e.__THREE_LIVE_SCENE__(m,f,w,g);A&&typeof A.toGLB=="function"&&(f=A)}else e.scene&&typeof e.scene.toGLB=="function"&&(f=e.scene)}else{if(!s){u("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let M=h?(0,eval)(h(`(function (THREE, scene, camera, renderer) {
289
+ return (function () {
290
+ `+T.script+`
291
+ })();
292
+ })`)):new Function("THREE","scene","camera","renderer",`return (function () {
293
+ `+T.script+`
294
+ })();`);h=null;let L=M(m,f,w,g);L&&typeof L.toGLB=="function"&&(f=L)}if(!v){m.SceneQuotaValidator&&m.SceneQuotaValidator.validate(f);let M=f.toGLB(),L=M instanceof ArrayBuffer?M:M.buffer.slice(M.byteOffset,M.byteOffset+M.byteLength);E({type:"3D_MODEL_READY",glbBuffer:L},[L])}l({type:"DONE",nonce:t})}catch(f){u(f&&f.message||f)}}},l({type:"READY",nonce:t})}function Fn(n,e,t){let r=t?.allowedScriptUrl??null,i=t?.allowClientScripts??r===null,s={nonce:e,engineSrc:n,allowedScriptUrl:r,allowClientScripts:i,revoked:xr};return`'use strict';(${vr.toString()})(${JSON.stringify(s)});`}function Un(n){n.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),n.onToast?.("Security Error: script timed out and was stopped.")}var we=0;function kn(){try{let n=new Uint32Array(4);return globalThis.crypto?.getRandomValues(n),Array.from(n,t=>t.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function wr(n){try{return new TextEncoder().encode(n).length}catch{return n.length}}var Sr=1024,Rr=256;function _n(n){if(!Array.isArray(n)&&!(n instanceof Float32Array)||n.length!==16)return!1;for(let e=0;e<16;e++){let t=n[e];if(typeof t!="number"||!Number.isFinite(t))return!1}return!0}function Nn(n,e){if(!n||typeof n!="object")return null;let t=n;if(t.nonce!==e)return null;switch(t.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof t.message=="string"?t.message:String(t.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,Sr)};case"3D_UPDATE_TRANSFORMS":{let i=t.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let s of i)if(!_n(s))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:i}}if(i&&typeof i=="object"){let s=Object.keys(i);if(s.length>1e3)return null;let a=Object.create(null),l=i;for(let u of s){if(u.length>Rr||u==="__proto__"||u==="constructor"||u==="prototype")return null;let o=l[u];if(!_n(o))return null;a[u]=o}return{type:"3D_UPDATE_TRANSFORMS",transforms:a}}return null}case"3D_MODEL_READY":{let i=t.glbBuffer;return!(i instanceof ArrayBuffer)||i.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:i}}default:return null}}function Ar(n){let e=wr(n);if(e>1048576)throw new Error(`SecurityError: Script length (${e} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function On(n,e,t,r){switch(n.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":e.onUpdateTransforms?.(n.transforms);return;case"3D_MODEL_READY":if(r.modelDispatched)return;r.modelDispatched=!0,e.onModelReady(n.payload);return;case"DONE":t();return;case"ERROR":t(),e.onError?.(new Error(`Worker script error: ${n.message}`));return;default:return n}}function Er(n,e,t,r){let i=kn(),s=Fn(e,i,n.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:n.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),a=document.createElement("iframe");a.setAttribute("sandbox","allow-scripts"),a.setAttribute("aria-hidden","true"),a.tabIndex=-1,a.style.display="none",a.src=t,we++;let l=!1,u=!1,o={modelDispatched:!1},c,h=()=>{if(l||u)return;let x=a.contentWindow;!x||typeof x.postMessage!="function"||(u=!0,x.postMessage(n.kind==="url"?{type:"SANDBOX_RUN",nonce:i,workerSource:s,scriptUrl:n.scriptUrl}:{type:"SANDBOX_RUN",nonce:i,workerSource:s,script:n.script},"*"))},m=()=>{},p=x=>{if(l||!a.contentWindow||x.source!==a.contentWindow)return;let v=x.data;if(v&&typeof v=="object"&&v.type==="IFRAME_READY"){h();return}let E=Nn(v,i);E&&On(E,r,m,o)};m=()=>{l||(l=!0,c!==void 0&&clearTimeout(c),we=Math.max(0,we-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",p),typeof a.remove=="function"?a.remove():a.parentNode&&a.parentNode.removeChild(a))},c=setTimeout(()=>{l||(m(),Un(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",p),a.onload=()=>{h()},a.onerror=()=>{m(),r.onError?.(new Error(`Sandbox iframe failed to load "${t}". Verify that three-live-sandbox.html is served at that URL.`))};let d=document.body||document.documentElement;if(!d||typeof d.appendChild!="function"){m();let x=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(x),x}return d.appendChild(a),{terminate:m}}function Cn(n,e,t,r){if(e==="worker"&&typeof Worker>"u")return r("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(e==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return r("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(we>=32)return r(`SecurityError: ${we} 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 i;try{i=fr()}catch(m){let p=m instanceof Error?m.message:String(m);return r(p,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let m;try{m=br()}catch(p){let d=p instanceof Error?p.message:String(p);return r(d,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Er(n,i,m,t))}catch(p){return Promise.reject(p)}}let s=kn(),a=Fn(i,s,n.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:n.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),l;try{let m=new Blob([a],{type:"application/javascript"}),p=URL.createObjectURL(m);try{let d=dr(p);l=new Worker(d)}finally{URL.revokeObjectURL(p)}}catch(m){let p=m instanceof Error?m.message:String(m);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${p}`,"Security Error: Failed to start Worker sandbox.")}we++;let u=!1,o={modelDispatched:!1},c,h=()=>{u||(u=!0,c!==void 0&&clearTimeout(c),we=Math.max(0,we-1),l.terminate())};return c=setTimeout(()=>{u||(h(),Un(t))},3e3),l.onmessage=m=>{let p=Nn(m.data,s);p&&On(p,t,h,o)},l.onerror=m=>{h(),t.onError?.(new Error(`Worker execution error: ${m.message}`))},n.kind==="url"?l.postMessage({type:"EXECUTE_URL",scriptUrl:n.scriptUrl,nonce:s}):l.postMessage({type:"EXECUTE",script:n.script,nonce:s}),Promise.resolve({terminate:h})}function Dn(n,e){return n==="none"||n==="unsafe-host-realm"?e(`SecurityError: sandbox="${n}" is prohibited. Sandboxing is mandatory for live compilation and cannot be bypassed. Use sandbox="worker" (default) or sandbox="iframe".`,`Security Error: sandbox="${n}" is not permitted.`):n!=="worker"&&n!=="iframe"?e(`SecurityError: Unsupported sandbox mode "${n}". Live compilation requires sandbox="worker" or sandbox="iframe".`,"Security Error: unsupported sandbox mode."):null}var Qt={execute(n,e,t,r){let i=(l,u)=>{let o=new Error(l);return t.onError?.(o),u&&t.onToast?.(u),Promise.reject(o)},s=Dn(e,i);if(s)return s;try{Ar(n)}catch(l){let u=l instanceof Error?l.message:String(l);return i(u,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??yr()?Cn({kind:"script",script:n},e,t,i):i(We,$e)},executeUrl(n,e,t){let r=(a,l)=>{let u=new Error(a);return t.onError?.(u),l&&t.onToast?.(l),Promise.reject(u)},i=Dn(e,r);if(i)return i;let s;try{s=gr(n)}catch(a){let l=a instanceof Error?a.message:String(a);return r(l,"Security Error: disallowed scene script URL.")}return Cn({kind:"url",scriptUrl:s},e,t,r)}},ut=new Set;function ce(n,e){let t=`[three-live] ${n} is unsupported; degraded to ${e}.`;ut.has(t)||(ut.add(t),typeof console<"u"&&typeof console.warn=="function"&&console.warn(t))}function Tr(){return Array.from(ut)}function Mr(){ut.clear()}var lt=class extends Me{constructor(e={}){ce("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}},_r=lt,Ce=class extends rt{constructor(e=1,t=0,r="PolyhedronGeometry"){ce(r,"SphereGeometry");let i=Math.max(4,Math.min(32,4<<Math.min(t,3)));super(e,i,i)}},Gt=class extends Ce{constructor(e=1,t=0){super(e,t,"IcosahedronGeometry")}},Wt=class extends Ce{constructor(e=1,t=0){super(e,t,"OctahedronGeometry")}},$t=class extends Ce{constructor(e=1,t=0){super(e,t,"DodecahedronGeometry")}},qt=class extends Ce{constructor(e=1,t=0){super(e,t,"TetrahedronGeometry")}},Yt=class extends Se{constructor(e=1,t=1,r=4,i=8){ce("CapsuleGeometry","CylinderGeometry"),super(e,e,t+e*2,i)}},jt=class extends Se{constructor(e=.5,t=1,r=16){ce("RingGeometry","CylinderGeometry"),super(t,t,.01,Math.max(8,r))}},Kt=class extends Se{constructor(e=1,t=16){ce("CircleGeometry","CylinderGeometry"),super(e,e,.01,Math.max(8,t))}},Zt=class extends ot{constructor(t,r,i=0,s=Math.PI/3,a=0,l=2){ce("SpotLight","PointLight");super(t,r,i,l);this.target=new me;this.angle=Math.PI/3;this.penumbra=0;this.angle=s,this.penumbra=a}},ht=class extends st{constructor(e,t,r){ce("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new he(t??4473924)}},Cr=ht,Bn={Vector2:At,Vector3:K,Vector4:Et,Euler:et,Quaternion:tt,Matrix4:Te,Matrix3:Tt,Color:he,MathUtils:lr,BufferAttribute:W,Float32BufferAttribute:Mt,Uint16BufferAttribute:_t,Uint32BufferAttribute:Ct,BufferGeometry:ae,BoxGeometry:nt,PlaneGeometry:Dt,SphereGeometry:rt,CylinderGeometry:Se,ConeGeometry:Lt,TorusGeometry:Pt,TorusKnotGeometry:It,IcosahedronGeometry:Gt,OctahedronGeometry:Wt,DodecahedronGeometry:$t,TetrahedronGeometry:qt,CapsuleGeometry:Yt,RingGeometry:jt,CircleGeometry:Kt,Texture:it,TextureLoader:Ft,Material:pe,MeshStandardMaterial:Me,MeshBasicMaterial:Ut,MeshLambertMaterial:kt,MeshPhongMaterial:Nt,MeshPhysicalMaterial:Ot,ShaderMaterial:lt,RawShaderMaterial:_r,Object3D:me,Group:Bt,Mesh:Be,Light:_e,AmbientLight:st,DirectionalLight:zt,PointLight:ot,SpotLight:Zt,HemisphereLight:ht,RectAreaLight:Cr,Camera:at,PerspectiveCamera:Vt,Scene:ct,WebGLRenderer:Ht,Clock:Xt,SceneQuotaValidator:fe,exportSceneToCanvas3D:Ln,exportSceneToGLB:Pn,exportSceneToUSDZ:hr,generateUSDZ:wt,glbToUSDZ:ke,sceneToCanvas3D:Fe,sceneToGLB:Qe,sceneToUSDZ:Ue,authorScriptRunner:Qt,getAuthorWarnings:Tr,clearAuthorWarnings:Mr};Object.freeze(fe);Object.freeze(fe.prototype);Object.freeze(ct.prototype);Object.freeze(Bn);var mt=new Proxy(Bn,{get:(n,e)=>e in n?n[e]:(typeof e=="string"&&e!=="then"&&e!=="toJSON"&&!e.startsWith("__")&&ce(`THREE.${e}`,"no-op proxy"),Je),set:(n,e)=>{throw new TypeError(`Cannot assign to read only property '${String(e)}' of #<THREE>`)},defineProperty:(n,e)=>{throw new TypeError(`Cannot define property '${String(e)}', object is not extensible`)},deleteProperty:(n,e)=>{throw new TypeError(`Cannot delete property '${String(e)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),Rt={name:"three_author",THREE:mt};var De=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;typeof De.THREE>"u"&&(De.THREE=mt);typeof De.requestAnimationFrame!="function"&&(De.requestAnimationFrame=()=>(ce("requestAnimationFrame","single-frame static evaluation"),0));typeof De.cancelAnimationFrame!="function"&&(De.cancelAnimationFrame=()=>{});if(typeof window<"u"){let n=window;n.ThreeLive=n.ThreeLive||{},n.ThreeLive.THREE=mt,n.ThreeLivePlugins=n.ThreeLivePlugins||{},n.ThreeLivePlugins.threeAuthor=Rt,n.ThreeLivePlugins.three_author=Rt,n.ThreeLivePlugins["three-author"]=Rt}var Dr=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(n,e){super(n,e),this.detail=e?.detail??null}});var Z=class Z extends Dr{constructor(){super(...arguments);this.viewer=null;this.canvas=null;this.posterEl=null;this.arButton=null;this.currentModel=null;this.currentModelLimits=void 0;this.isModelLoaded=!1;this.scriptHandle=null;this.resizeObserver=null;this.mutationObserver=null}static get arProvider(){return Y().arProvider}static set arProvider(t){Y().arProvider=t}static get scriptRunner(){return Y().scriptRunner}static set scriptRunner(t){Y().scriptRunner=t}static get sandboxEngineSrc(){return Y().sandboxEngineSrc??null}static set sandboxEngineSrc(t){Y().sandboxEngineSrc=t}static get sandboxIframeSrc(){return Y().sandboxIframeSrc??null}static set sandboxIframeSrc(t){Y().sandboxIframeSrc=t}static get allowClientScripts(){return!!Y().allowClientScripts}static set allowClientScripts(t){Y().allowClientScripts=t}static registerScriptRunner(t){Z.scriptRunner=t}static registerDecoder(t,r){ee.registerDecoder(t,r)}static getDecoder(t){return ee.getDecoder(t)}static registerAR(t){typeof t=="function"?Z.arProvider={activateAR:t}:Z.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof Z&&i.updateARButtonVisibility()})}static isARSupported(){return!!Z.arProvider}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.loadModelFromSrc(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 ee.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of ee.getRegisteredPlugins())t.onElementDisconnected?.(this);this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.viewer&&(this.viewer.destroy(),this.viewer=null),this.isModelLoaded=!1}attributeChangedCallback(t,r,i){if(r!==i){switch(t){case"src":i&&this.loadModelFromSrc(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 s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer&&i&&this.viewer.setToneMapping(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 s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"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"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 s of ee.getRegisteredPlugins())s.onAttributeChanged?.(this,t,r,i)}}getAttr(t){return this.getAttribute(t)}setAttr(t,r){r!==null?this.setAttribute(t,r):this.removeAttribute(t)}getBoolAttr(t){return this.hasAttribute(t)&&this.getAttribute(t)!=="false"}setBoolAttr(t,r){r?this.setAttribute(t,""):this.removeAttribute(t)}getFloatAttr(t,r){let i=this.getAttribute(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.getAttribute("sandbox")||(Y().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttribute("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||Z.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.setAttribute("exposure",String(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.setAttribute("auto-rotate-delay",String(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.getAttribute("ar-scale")||"auto"}set arScale(t){this.setAttribute("ar-scale",t)}get arPlacement(){return this.getAttribute("ar-placement")||"floor"}set arPlacement(t){this.setAttribute("ar-placement",t)}get canActivateAR(){return Z.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(t){this.setAttribute("shadow-intensity",String(t))}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(t){this.setAttribute("shadow-softness",String(t))}get toneMapping(){return this.getAttribute("tone-mapping")||"neutral"}set toneMapping(t){this.setAttribute("tone-mapping",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 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,s){this.viewer&&this.viewer.setCamera(t,r,i,s)}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():{x:0,y:0,z:0,toString(){return"0m 0m 0m"}}}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(t,r){return this.viewer&&this.viewer.render?.(),this.canvas?this.canvas.toDataURL(t,r):""}toBlob(t){return this.viewer&&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(s=>{s?r(s):i(new Error("Failed to capture canvas blob."))},t?.mimeType,t?.qualityArgument)})}positionAndNormalFromPoint(t,r){if(!this.viewer)return null;let i=this.viewer.raycastFromScreenPoint(t,r);if(!i)return null;let[s,a,l]=i.hitPoint||i.point,[u,o,c]=i.normal;return{position:{x:s,y:a,z:l,toString(){return`${s}m ${a}m ${l}m`}},normal:{x:u,y:o,z:c,toString(){return`${u}m ${o}m ${c}m`}}}}async loadModel(t){return this.loadModelWithLimits(t)}async loadModelWithLimits(t,r){if(!this.viewer){this.currentModel=t,this.currentModelLimits=r;return}try{let i;if(typeof t=="string"){let l=await fetch(t);if(!l.ok)throw new Error(`Failed to load 3D model from "${t}": HTTP ${l.status}`);i=await l.arrayBuffer()}else i=t;let s=ve(i);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.updateHotspots();let a=this.getAttribute("selected-mesh");a&&this.viewer.setSelectedMesh(a),this.dispatchEvent(new CustomEvent("load",{bubbles:!0,composed:!0,detail:{model:s}}))}catch(i){throw this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),i}}showToast(t,r=4e3){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 18px;background-color:rgba(15,23,42,0.92);color:#f8fafc;border:1px solid rgba(56,189,248,0.4);border-radius:9999px;font:500 13px system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.4);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:90%;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis",this.appendChild(i)),i.textContent=t,typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")}):(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)"),setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)")},r)}async activateAR(){if(!this.currentModel){let i=new Error("No 3D model is loaded in <three-live>.");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message),i}if(!Z.arProvider){let i=new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR().");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message),i}let t=this.getAttribute("ios-src"),r=(this.getAttribute("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"session-started"}}));let i=await Z.arProvider.activateAR({model:t||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"not-presenting"}}))},onError:s=>{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:s}})),this.showToast(`AR error: ${s.message}`)}}});if(i.success)i.mode==="quick-look"?this.showToast("Opening Apple AR Quick Look..."):i.mode==="scene-viewer"?this.showToast("Opening Google Scene Viewer..."):i.mode==="webxr"&&this.showToast("WebXR AR session started.");else{if(typeof document<"u"&&this.currentModel&&Z.arProvider.createUSDZBlob)try{let s=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:Z.arProvider.createUSDZBlob(this.currentModel),a=URL.createObjectURL(s),l=document.createElement("a");l.href=a,l.download="three_live_model.usdz",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(a),3e3),this.showToast("\u{1F4F1} AR camera requires iOS / Android. Downloaded USDZ for macOS Quick Look!")}catch{this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (Scene Viewer / WebXR) device.")}else this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (Scene Viewer / WebXR) device.");i.error&&this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i.error}}))}return i}catch(i){throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(`AR error: ${i.message||String(i)}`),i}}setupDOM(){let t=this.querySelector("canvas");t||(t=document.createElement("canvas"),t.style.width="100%",t.style.height="100%",t.style.display="block",t.style.touchAction=this.cameraControls?"none":"auto",t.style.outline="none",this.appendChild(t)),this.canvas=t;let r=this.getAttribute("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.getAttribute("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttribute("max-camera-orbit")),a=this.parseCameraTarget(this.getAttribute("camera-target")),l=this.parseFieldOfView(this.getAttribute("field-of-view"));this.viewer=new ee(this,this.canvas,{autoRotate:t,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttribute("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,fieldOfView:l,cameraTarget:a,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:o=>{this.dispatchEvent(new CustomEvent("meshclick",{bubbles:!0,composed:!0,detail:o}))},onCameraChange:o=>{this.updateHotspots();for(let c of ee.getRegisteredPlugins())c.onCameraChange?.(this.viewer,this);this.dispatchEvent(new CustomEvent("camera-change",{bubbles:!0,composed:!0,detail:o}))}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let u=this.getAttribute("camera-orbit");u&&this.applyCameraOrbit(u),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.setAttribute("alt","3D Scene Preview"),this.posterEl.style.position="absolute",this.posterEl.style.inset="0",this.posterEl.style.width="100%",this.posterEl.style.height="100%",this.posterEl.style.objectFit="cover",this.posterEl.style.transition="opacity 0.35s ease-out",this.posterEl.style.pointerEvents="none",this.posterEl.style.zIndex="1",this.appendChild(this.posterEl)),this.posterEl.src=t,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){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.setAttribute("type","button"),t.setAttribute("aria-label","View in Augmented Reality"),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 s=document.createElementNS(r,"svg");s.setAttribute("width","20"),s.setAttribute("height","20"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","currentColor"),s.setAttribute("stroke-width","2"),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.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 16z");let l=document.createElementNS(r,"polyline");l.setAttribute("points","3.27 6.96 12 12.01 20.73 6.96");let u=document.createElementNS(r,"line");u.setAttribute("x1","12"),u.setAttribute("y1","22.08"),u.setAttribute("x2","12"),u.setAttribute("y2","12"),s.appendChild(a),s.appendChild(l),s.appendChild(u),t.appendChild(s)}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",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&!!Z.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=t.trim().split(/\s+/);if(r.length>=2){let i=u=>u.endsWith("rad")?parseFloat(u)*180/Math.PI:parseFloat(u.replace(/deg$/,"")),s=r[0]==="auto"?void 0:i(r[0]),a=r[1]==="auto"?void 0:i(r[1]),l;r.length>=3&&r[2]!=="auto"&&(l=parseFloat(r[2].replace(/m$/,""))),(s!==void 0&&!isNaN(s)||a!==void 0&&!isNaN(a))&&this.viewer.setInitialCamera(s!==void 0&&!isNaN(s)?s:void 0,a!==void 0&&!isNaN(a)?a:void 0,l!==void 0&&!isNaN(l)?l:void 0)}}}parseOrbitLimit(t){if(!t)return{};let r=t.trim().split(/\s+/),i={};if(r.length>0&&r[0]!=="auto"){let s=r[0].endsWith("rad")?parseFloat(r[0])*180/Math.PI:parseFloat(r[0].replace(/deg$/,""));isNaN(s)||(i.theta=s)}if(r.length>1&&r[1]!=="auto"){let s=r[1].endsWith("rad")?parseFloat(r[1])*180/Math.PI:parseFloat(r[1].replace(/deg$/,""));isNaN(s)||(i.phi=s)}if(r.length>2&&r[2]!=="auto"){let s=parseFloat(r[2].replace(/m$/,""));isNaN(s)||(i.distance=s)}return i}applyOrbitLimits(){if(!this.viewer)return;let t=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttribute("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(i=>parseFloat(i.replace(/m$/,"")));return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(t){if(!t)return;let r=t.endsWith("rad")?parseFloat(t)*180/Math.PI:parseFloat(t.replace(/deg$/,""));return isNaN(r)?void 0: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 ee.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}async loadModelFromSrc(t){await this.loadModel(t)}runWithScriptRunner(t){let r=Z.scriptRunner;if(!r){let i=new Error('Procedural script execution requires "three-live/full" or ThreeLiveElement.registerScriptRunner().');return this.showToast(i.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),Promise.reject(i)}return this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),new Promise((i,s)=>{let a=!1;t(r,{onModelReady:u=>{this.loadModelWithLimits(u,gn).then(()=>{a||(a=!0,i(u))},o=>{let c=o instanceof Error?o.message:String(o);this.showToast(c),a||(a=!0,s(o))})},onUpdateTransforms:u=>this.viewer?.updateMeshTransforms(u),onError:u=>{this.showToast(u.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:u}})),a||(a=!0,s(u))},onToast:u=>this.showToast(u)}).then(u=>{u&&(this.scriptHandle=u)},u=>{u instanceof Error&&u.message&&this.showToast(u.message),a||(a=!0,s(u))})})}loadScriptFromSrc(t){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(s),Promise.reject(s)}return r.executeUrl(t,this.sandbox,i)})}executeScript(t){if(!Z.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(We);return this.showToast($e),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:r}})),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};Z.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","environment-image","skybox-image","autoplay","animation-name","auto-rotate","auto-rotate-delay","rotation-per-second"],Z.registerPlugin=ee.registerPlugin,Z.getRegisteredPlugins=ee.getRegisteredPlugins;var Ae=Z;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",Ae);function Vn(){if(typeof window>"u"||typeof navigator>"u")return!1;let n=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(n)||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 Hn(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function Xn(){if(typeof navigator>"u")return!1;let n=navigator;if(!n.xr||typeof n.xr.isSessionSupported!="function")return!1;try{return await n.xr.isSessionSupported("immersive-ar")?!0:await n.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function Lr(){return(await en()).bestMode}async function en(){let[n,e,t]=await Promise.all([Xn(),Promise.resolve(Vn()),Promise.resolve(Hn())]),r=[];e&&r.push("quick-look"),n&&r.push("webxr"),t&&r.push("scene-viewer");let i=null;return e?i="quick-look":n?i="webxr":t&&(i="scene-viewer"),{webxr:n,quickLook:e,sceneViewer:t,availableModes:r,bestMode:i}}function zn(n,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let t,r=!1;if(typeof n=="string"){if(t=Pr(n),!t)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else t=URL.createObjectURL(n),r=!0;let i=[];if(e.allowScale===!1&&i.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let l=dt(e.canonicalWebPageUrl,!1);l&&i.push(`canonicalWebPageURL=${encodeURIComponent(l)}`)}e.checkoutTitle&&i.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&i.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&i.push(`price=${encodeURIComponent(e.price)}`),i.length>0&&(t+=`#${i.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",t);let a=document.createElement("img");a.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),a.style.display="none",s.appendChild(a),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),r&&URL.revokeObjectURL(t.split("#")[0])},3e3)}function dt(n,e=!1){if(typeof n!="string")return"";let t=n.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!t)return"";if(/^[\\/]{2}/.test(t))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${t.slice(0,32)}`);let r=t.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||e&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(t))return t;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${t.slice(0,32)}`)}function Pr(n){try{return dt(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function Ir(n,e={}){let t=dt(n,!0),r=e.mode||"ar_preferred",i=new URLSearchParams({file:t,mode:r,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&i.set("title",e.title),e.link&&i.set("link",dt(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${i.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function Fr(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=Ir(n,e);window.location.href=t}var Jt=class{constructor(e={}){this.session=null;this.refSpace=null;this.viewerSpace=null;this.hitTestSource=null;this.isPlaced=!1;this.placedMatrix=new Float32Array(16);this.currentHitMatrix=null;this.view=null;this.options=e}isSessionActive(){return this.session!==null}hasPlacedModel(){return this.isPlaced}getPlacedMatrix(){return this.placedMatrix}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");let r=navigator.xr;this.view=e;let i={requiredFeatures:this.options.requiredFeatures||[],optionalFeatures:this.options.optionalFeatures||["local","hit-test","dom-overlay","light-estimation"]},s=t||e?.container;for(let u of j)u.onConfigureXRSessionInit?.(s,i);let a="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(a="immersive-vr")}catch{a="immersive-vr"}try{this.session=await r.requestSession(a,i)}catch(u){throw this.options.onError?.(u),u}this.session.addEventListener("end",()=>{this.cleanup(),this.options.onExit?.()}),this.session.addEventListener("select",()=>{this.handleSelect()});let l=e.getGLContext?.();if(l&&l.makeXRCompatible&&await l.makeXRCompatible(),l&&typeof window<"u"&&typeof window.XRWebGLLayer=="function"&&typeof this.session.updateRenderState=="function"){let u=new window.XRWebGLLayer(this.session,l);this.session.updateRenderState({baseLayer:u})}if(this.refSpace=await this.session.requestReferenceSpace("local"),this.viewerSpace=await this.session.requestReferenceSpace("viewer"),this.session.requestHitTestSource)try{this.hitTestSource=await this.session.requestHitTestSource({space:this.viewerSpace})}catch{}this.session.requestAnimationFrame(this.onXRFrame.bind(this))}async stop(){this.session&&(await this.session.end(),this.cleanup())}handleSelect(){this.currentHitMatrix&&!this.isPlaced&&(this.placedMatrix.set(this.currentHitMatrix),this.isPlaced=!0,this.options.onPlaced?.(this.placedMatrix))}onXRFrame(e,t){if(!this.session)return;this.session.requestAnimationFrame(this.onXRFrame.bind(this));let r=t.getViewerPose(this.refSpace);if(!r)return;let i=this.view?.getGLContext?.(),s=this.session.renderState?.baseLayer;if(i&&s&&s.framebuffer&&i.bindFramebuffer(36160,s.framebuffer),this.hitTestSource&&!this.isPlaced){let a=t.getHitTestResults(this.hitTestSource);for(let l of a){let u=l.getPose(this.refSpace);if(u){let o=u.transform.matrix,c=o[5];if(this.options.arPlacement==="wall"&&Math.abs(c)>.35||this.options.arPlacement==="floor"&&Math.abs(c)<.65)continue;this.currentHitMatrix=o,this.options.onHit?.(this.currentHitMatrix);break}}}for(let a of j)a.onXRFrame?.(this.view,this.session,t,this.refSpace);for(let a of r.views)this.view&&typeof this.view.renderXRView=="function"&&this.view.renderXRView(a,this.isPlaced?this.placedMatrix:this.currentHitMatrix,this.isPlaced);i&&s&&s.framebuffer&&i.bindFramebuffer(36160,null)}cleanup(){this.hitTestSource&&(this.hitTestSource.cancel?.(),this.hitTestSource=null),this.session=null,this.refSpace=null,this.viewerSpace=null,this.currentHitMatrix=null,this.isPlaced=!1,this.view=null}};async function tn(n){let e=await en(),t=n.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let l of t)if(e.availableModes.includes(l)){r=l;break}if(r||(r=e.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let i={...n.quickLookOptions,allowScale:n.arScale==="fixed"?!1:n.quickLookOptions?.allowScale},s={...n.sceneViewerOptions,resizable:n.arScale==="fixed"?!1:n.sceneViewerOptions?.resizable,enableVerticalPlacement:n.arPlacement==="wall"?!0:n.sceneViewerOptions?.enableVerticalPlacement},a={...n.webXROptions,arPlacement:n.arPlacement||n.webXROptions?.arPlacement};try{if(r==="quick-look"){let l;if(n.model instanceof Blob&&n.model.type==="model/vnd.usdz+zip")l=n.model;else{if(typeof n.model=="string")return zn(n.model,i),{mode:"quick-look",success:!0};l=Ne(n.model)}return zn(l,i),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let l=n.glbUrl||(typeof n.model=="string"?n.model:null);if(!l)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return Fr(l,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!n.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let l=new Jt(a);return await l.start(n.view),{mode:"webxr",success:!0,session:l}}}catch(l){return{mode:r,success:!1,error:l}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}Ae.registerAR({activateAR:tn,createUSDZBlob:Ne});Ae.registerScriptRunner(Qt);Xe(on);export{mt as THREE,Ae as ThreeLiveElement,ee as ThreeView,tn as activateAR,Ne as createUSDZBlob,en as getARCapabilities,Lr as getBestARMode,Vn as isQuickLookSupported,Hn as isSceneViewerSupported,Xn as isWebXRSupported,ve as toGLBData};