three-live 1.1.1 → 1.2.1

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.
@@ -14,9 +14,9 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- var Ye="__THREE_LIVE_REGISTRY__";function Z(){let n=typeof globalThis<"u"?globalThis:{};if(!n[Ye]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,Ye,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[Ye]=e}}return n[Ye]}var Q=Z().plugins;function je(n){let e=Z().plugins;e.some(t=>t.name===n.name)||e.push(n)}function mn(){return Z().plugins}var Qn=`#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.);}`,Jn=`#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);}`,Ke=new WeakMap,dn=new Float32Array(20);function Rt(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 er(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 c=l.positions;if(c)for(let o=0;o<c.length;o+=3)c[o]<e&&(e=c[o]),c[o+1]<t&&(t=c[o+1]),c[o+2]<r&&(r=c[o+2]),c[o]>i&&(i=c[o]),c[o+1]>s&&(s=c[o+1]),c[o+2]>a&&(a=c[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 tr(n){let e=Ke.get(n);if(e)return e;let t=(l,c)=>{let o=n.createShader(l);return n.shaderSource(o,c),n.compileShader(o),o},r=n.createProgram();n.attachShader(r,t(35633,Qn)),n.attachShader(r,t(35632,Jn)),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")},Ke.set(n,e),e}var fn={name:"contact-shadow",onAfterRender(n,e,t){let r=e.shadowIntensity;if(r<=0||!e.bounds)return;let i=tr(n),s=!e.xrSessionActive&&(e.backdropMeshes?.length??0)>0,a=[],l=[];for(let g of e.meshes||[]){if(!g||g.visible===!1||g.isPluginMesh||g.name==="__xr_reticle__"||g.name?.startsWith("__xr_slot_"))continue;let w=er(g);if(!w)continue;g.transform&&(w=Rt(g.transform,w)),e.modelRootMatrix&&(w=Rt(e.modelRootMatrix,w));let[T,C,b,x,p,A]=w,d=[T,b,x,A,C-p,C+p];/floor|table|pedestal|ground|base|plane/i.test(g.name||"")||p<.14&&Math.min(x,A)>.45?l.push(d):a.push(d)}let c=[],o=e.bounds.center||[0,0,0],u=Math.max(.05,Number(e.bounds.radius)||.5),m=e.bounds.min,h=m?[o[0],o[1],o[2],u,Math.max(.01,o[1]-m[1]),u]:[o[0],o[1],o[2],u,u,u];e.modelRootMatrix&&(h=Rt(e.modelRootMatrix,h));let f=e.xrSessionActive&&l.length===0&&String(e.container?.tagName||"").toLowerCase()==="xr-live"?(e.modelRootMatrix?e.modelRootMatrix[5]*-.25+e.modelRootMatrix[13]:-.25)+.002:h[1]-h[4]+.002;for(let[g,w,T,C,b]of a){let x=-1/0;for(let[A,d,v,R,,M]of l)b>=M-.08&&Math.abs(g-A)<=v&&Math.abs(w-d)<=R&&M+.002>x&&(x=M+.002);s&&(x=Math.max(x,g>=.04&&g<=.36&&w>=-.34&&w<=-.04&&b>=.01?.036:Math.hypot(g,w)<=.66&&b>=-.06?.003:-.477)),isFinite(x)||(x=f);let p=c.find(A=>Math.hypot(g-A[0],w-A[1])<.06&&Math.abs(x-A[5])<.05);p?(p[2]=Math.max(p[2],T*.78),p[3]=Math.max(p[3],C*.78),p[4]=Math.min(p[4],b)):c.push([g,w,T,C,b,x])}if(c.length===0){let g=Math.max(.1,h[3]*1.5)/1.45;c.push([h[0],h[2],g,g,f,f])}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[g,w,T,C,b,x]of c){let p=Math.max(0,b-x),A=r/(1+p*2);if(A<.02)continue;let d=1+Math.min(.75,p*.85),v=Math.max(.045,T*1.45*d),R=Math.max(.045,C*1.45*d);dn.set([g-v,x,w-R,0,0,g+v,x,w-R,1,0,g+v,x,w+R,1,1,g-v,x,w+R,0,1]),n.bufferSubData(34962,0,dn),n.uniform1f(i.uIntensity,A),n.uniform1f(i.uSoftness,Math.min(1,e.shadowSoftness+Math.min(.45,p*.6))),n.drawElements(4,6,5123,0)}n.bindVertexArray(null),n.depthMask(!0),n.disable(3042)},onDestroy(n){let e=Ke.get(n);e&&(n.deleteVertexArray(e.vao),n.deleteBuffer(e.vbo),n.deleteBuffer(e.ibo),n.deleteProgram(e.prog),Ke.delete(n))}};function pn(n,e,t){let r=[],i=new Map,s=[],a=[],l=[],c=new Map,o=b=>{let x=i.get(b);return x===void 0&&(x=r.length,r.push({op:b}),i.set(b,x)),x},u=b=>{let x=c.get(b);return x===void 0&&(x=l.length,l.push({id:b}),c.set(b,x)),x},m=(b,x={})=>s.push({declaration:o(b),...x})-1,h=(b,x,p)=>a.push({id:b,type:x,value:p})-1,y=b=>({node:b,socket:"value"}),f=t?.interactivity??t?.gltfExtensions?.KHR_interactivity;if(f&&typeof f=="object"){let b=Array.isArray(f.graphs)?f.graphs[f.graph??0]:f;if(b&&Array.isArray(b.nodes)){let x=Array.isArray(b.declarations)?b.declarations:[];for(let p of x)p?.op&&o(p.op);Array.isArray(b.variables)&&a.push(...b.variables);for(let p of b.events||[])p?.id&&u(p.id);for(let p of b.nodes){if(!p||typeof p!="object")continue;let A=p.op||(typeof p.declaration=="number"?x[p.declaration]?.op:"");s.push(A?{...p,declaration:o(A)}:{...p})}}}let g=(b,x,p="translation")=>p==="baseColorFactor"||p==="metallicFactor"||p==="roughnessFactor"?`/materials/${Math.max(0,x)}/pbrMetallicRoughness/${p}`:p==="emissiveFactor"||p==="alphaCutoff"?`/materials/${Math.max(0,x)}/${p}`:p==="visible"?`/nodes/${b}/extensions/KHR_node_visibility/visible`:`/nodes/${b}/${p}`,w=new Map;n.forEach((b,x)=>{typeof b?.name=="string"&&!w.has(b.name)&&w.set(b.name,x)});let T=(b,x)=>typeof b.target=="string"&&w.has(b.target)?w.get(b.target):typeof b.targetNode=="number"?b.targetNode:x,C=b=>{let x=n[b];return(typeof x?.mesh=="number"?e[x.mesh]?.primitives?.[0]?.material:0)??0};for(let b=0;b<n.length;b++){let x=n[b],p=x?.extras?.interactivity;if(!p||typeof p!="object")continue;let A=(typeof x.mesh=="number"?e[x.mesh]?.primitives?.[0]?.material:0)??0,d=R=>{let M=Array.isArray(R)?R:[R],D=[];for(let E=0;E<M.length;E++){let S=M[E];if(!S||typeof S!="object")continue;let k=S.action||"interpolate",P=typeof S.duration=="number"?S.duration:.35;if(k==="toggleTransform"){let X=S.property==="rotation"||S.property==="scale"?S.property:"translation",V=X==="rotation"?x.rotation||[0,0,0,1]:X==="scale"?x.scale||[1,1,1]:x.translation||[0,0,0],I=`/nodes/${b}/${X}`,U=h(`__toggle_${b}_${E}`,"bool",!1),_=m("variable/get",{configuration:{variable:U}}),B=m("math/not",{values:{a:y(_)}}),O=m("variable/set",{configuration:{variable:U},values:{value:y(B)}}),z=m("pointer/interpolate",{configuration:{pointer:I},values:{value:{value:Array.isArray(S.to)?S.to:V},duration:{value:P}}}),L=m("pointer/interpolate",{configuration:{pointer:I},values:{value:{value:Array.isArray(S.from)?S.from:V},duration:{value:P}}});s[O].flows={out:{node:m("flow/branch",{values:{condition:y(_)},flows:{true:{node:z},false:{node:L}}})}},D.push(O)}else if(k==="interpolate"){let X=S.to??S.value;if(X===void 0)continue;let V={value:{value:X},duration:{value:P}};S.from!==void 0&&(V.from={value:S.from}),D.push(m("pointer/interpolate",{configuration:{pointer:typeof S.pointer=="string"?S.pointer:g(T(S,b),C(T(S,b)),S.property)},values:V}))}else if(k==="setProperty"){if(S.value===void 0)continue;D.push(m("pointer/set",{configuration:{pointer:typeof S.pointer=="string"?S.pointer:g(T(S,b),C(T(S,b)),S.property)},values:{value:{value:S.value}}}))}else if(k==="toggleVisibility"){let X=T(S,b),V=h(`__vis_${X}_${E}`,"bool",!0),I=m("variable/get",{configuration:{variable:V}}),U=m("math/not",{values:{a:y(I)}}),_=m("variable/set",{configuration:{variable:V},values:{value:y(U)}});s[_].flows={out:{node:m("pointer/set",{configuration:{pointer:`/nodes/${X}/extensions/KHR_node_visibility/visible`},values:{value:y(I)}})}},D.push(_)}else if(k==="cycleMaterialColor"&&Array.isArray(S.colors)&&S.colors.length>0){let X=typeof S.duration=="number"?S.duration:.25,V=`/materials/${Math.max(0,A)}/pbrMetallicRoughness/baseColorFactor`,I=h(`__color_idx_${b}_${E}`,"int",0),U=m("variable/get",{configuration:{variable:I}}),_=m("math/add",{values:{a:y(U),b:{value:1}}}),B=m("math/rem",{values:{a:y(_),b:{value:S.colors.length}}}),O=m("variable/set",{configuration:{variable:I},values:{value:y(B)}}),z={};for(let L=0;L<S.colors.length;L++){let N=S.colors[L],H=Array.isArray(N)&&N.length>=3?[N[0],N[1],N[2],N[3]??1]:[1,1,1,1];z[String(L)]={node:X>0?m("pointer/interpolate",{configuration:{pointer:V},values:{value:{value:H},duration:{value:X}}}):m("pointer/set",{configuration:{pointer:V},values:{value:{value:H}}})}}s[O].flows={out:{node:m("flow/switch",{values:{selection:y(U)},flows:z})}},D.push(O)}else if(k==="playAnimation")D.push(m("animation/start",{configuration:{animation:S.animation??S.clip??0}}));else if(k==="stopAnimation")D.push(m("animation/stop"));else if(k==="sendEvent"){let X={};for(let[V,I]of Object.entries(S.values||{}))X[V]={value:I};D.push(m("event/send",{configuration:{event:u(String(S.event??S.id??"custom"))},values:X}))}}if(!D.length)return null;if(D.length===1)return D[0];let F={};return D.forEach((E,S)=>{F[String(S)]={node:E}}),m("flow/sequence",{flows:F})},v=(R,M,D)=>{let F=d(M);F!==null&&m(R,{...D?{configuration:D}:{},flows:{out:{node:F}}})};if(p.onSelect&&v("pointer/onSelect",p.onSelect,{nodeIndex:b}),p.onHoverIn&&v("pointer/onHoverIn",p.onHoverIn,{nodeIndex:b}),p.onHoverOut&&v("pointer/onHoverOut",p.onHoverOut,{nodeIndex:b}),p.onStart&&v("event/onStart",p.onStart),p.onReceive&&typeof p.onReceive=="object")for(let[R,M]of Object.entries(p.onReceive))v("event/receive",M,{event:u(R)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:a,events:l}],graph:0}:null}var Ze='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).',Qe="Security Error: client-side scripts require allow-client-scripts opt-in.";function J(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function Je(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 Ie(n,e,t,r){let[i,s,a]=e,[l,c,o]=r,[u,m,h]=t,y=i-u,f=s-m,g=a-h,w=Math.hypot(y,f,g);w<=1e-5?(y=0,f=0,g=1):(y/=w,f/=w,g/=w);let T=c*g-o*f,C=o*y-l*g,b=l*f-c*y;w=Math.hypot(T,C,b),w<=1e-5?(T=0,C=0,b=0):(T/=w,C/=w,b/=w);let x=f*b-g*C,p=g*T-y*b,A=y*C-f*T;return w=Math.hypot(x,p,A),w<=1e-5?(x=0,p=0,A=0):(x/=w,p/=w,A/=w),n[0]=T,n[1]=x,n[2]=y,n[3]=0,n[4]=C,n[5]=p,n[6]=f,n[7]=0,n[8]=b,n[9]=A,n[10]=g,n[11]=0,n[12]=-(T*i+C*s+b*a),n[13]=-(x*i+p*s+A*a),n[14]=-(y*i+f*s+g*a),n[15]=1,n}function de(n,e,t){let r=e[0],i=e[1],s=e[2],a=e[3],l=e[4],c=e[5],o=e[6],u=e[7],m=e[8],h=e[9],y=e[10],f=e[11],g=e[12],w=e[13],T=e[14],C=e[15],b=t[0],x=t[1],p=t[2],A=t[3];return n[0]=b*r+x*l+p*m+A*g,n[1]=b*i+x*c+p*h+A*w,n[2]=b*s+x*o+p*y+A*T,n[3]=b*a+x*u+p*f+A*C,b=t[4],x=t[5],p=t[6],A=t[7],n[4]=b*r+x*l+p*m+A*g,n[5]=b*i+x*c+p*h+A*w,n[6]=b*s+x*o+p*y+A*T,n[7]=b*a+x*u+p*f+A*C,b=t[8],x=t[9],p=t[10],A=t[11],n[8]=b*r+x*l+p*m+A*g,n[9]=b*i+x*c+p*h+A*w,n[10]=b*s+x*o+p*y+A*T,n[11]=b*a+x*u+p*f+A*C,b=t[12],x=t[13],p=t[14],A=t[15],n[12]=b*r+x*l+p*m+A*g,n[13]=b*i+x*c+p*h+A*w,n[14]=b*s+x*o+p*y+A*T,n[15]=b*a+x*u+p*f+A*C,n}function et(n,e,t,r){let i=e[0],s=e[1],a=e[2],l=e[3],c=i+i,o=s+s,u=a+a,m=i*c,h=i*o,y=i*u,f=s*o,g=s*u,w=a*u,T=l*c,C=l*o,b=l*u,x=r[0],p=r[1],A=r[2];return n[0]=(1-(f+w))*x,n[1]=(h+b)*x,n[2]=(y-C)*x,n[3]=0,n[4]=(h-b)*p,n[5]=(1-(m+w))*p,n[6]=(g+T)*p,n[7]=0,n[8]=(y+C)*A,n[9]=(g-T)*A,n[10]=(1-(m+f))*A,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function be(n,e){let t=e[0],r=e[1],i=e[2],s=e[4],a=e[5],l=e[6],c=e[8],o=e[9],u=e[10],m=u*a-l*o,h=-u*s+l*c,y=o*s-a*c,f=t*m+r*h+i*y;return f&&(f=1/f,n[0]=m*f,n[1]=(-u*r+i*o)*f,n[2]=(l*r-i*a)*f,n[3]=h*f,n[4]=(u*t-i*c)*f,n[5]=(-l*t+i*s)*f,n[6]=y*f,n[7]=(-o*t+r*c)*f,n[8]=(a*t-r*s)*f),n}function bn(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],a=e[4],l=e[5],c=e[6],o=e[7],u=e[8],m=e[9],h=e[10],y=e[11],f=e[12],g=e[13],w=e[14],T=e[15],C=t*l-r*a,b=t*c-i*a,x=t*o-s*a,p=r*c-i*l,A=r*o-s*l,d=i*o-s*c,v=u*g-m*f,R=u*w-h*f,M=u*T-y*f,D=m*w-h*g,F=m*T-y*g,E=h*T-y*w,S=C*E-b*F+x*D+p*M-A*R+d*v;return S?(S=1/S,n[0]=(l*E-c*F+o*D)*S,n[1]=(i*F-r*E-s*D)*S,n[2]=(g*d-w*A+T*p)*S,n[3]=(h*A-m*d-y*p)*S,n[4]=(c*M-a*E-o*R)*S,n[5]=(t*E-i*M+s*R)*S,n[6]=(w*x-f*d-T*b)*S,n[7]=(u*d-h*x+y*b)*S,n[8]=(a*F-l*M+o*v)*S,n[9]=(r*M-t*F-s*v)*S,n[10]=(f*A-g*x+T*C)*S,n[11]=(m*x-u*A-y*C)*S,n[12]=(l*R-a*D-c*v)*S,n[13]=(t*D-r*R+i*v)*S,n[14]=(g*b-f*p-w*C)*S,n[15]=(u*p-m*b+h*C)*S,n):null}function At(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],c=i[3]*e+i[7]*t+i[11]*r+i[15],o=c!==0?1/c:1;n[0]=s*o,n[1]=a*o,n[2]=l*o}function yn(n,e,t,r,i,s,a,l,c,o,u,m,h,y,f,g,w=0){let T=o-a,C=u-l,b=m-c,x=h-a,p=y-l,A=f-c,d=i*A-s*p,v=s*x-r*A,R=r*p-i*x,M=T*d+C*v+b*R;if(M>-1e-7&&M<1e-7)return!1;let D=1/M,F=n-a,E=e-l,S=t-c,k=D*(F*d+E*v+S*R);if(k<-w||k>1+w)return!1;let P=E*b-S*C,X=S*T-F*b,V=F*C-E*T,I=D*(r*P+i*X+s*V);if(I<-w||k+I>1+w)return!1;let U=D*(x*P+p*X+A*V);if(U>1e-4&&U<g.distance){g.distance=U,g.point=[n+r*U,e+i*U,t+s*U];let _=C*A-b*p,B=b*x-T*A,O=T*p-C*x,z=Math.hypot(_,B,O)||1;return g.normal=[_/z,B/z,O/z],!0}return!1}function tt(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let u=0;u<t;u++)r.push(J());if(t===0)return r;let i=new Set;for(let u of n.nodes)if(Array.isArray(u.children))for(let m of u.children)i.add(m);let s=new Set,a=128,l=(u,m,h=0)=>{if(h>a||u<0||u>=t||s.has(u))return;s.add(u);let y=n.nodes[u];if(!y)return;let f=J();if(e&&e[u])f.set(e[u]);else if(y.matrix&&y.matrix.length===16)f.set(y.matrix);else{let w=y.translation||[0,0,0],T=y.rotation||[0,0,0,1],C=y.scale||[1,1,1];et(f,T,w,C)}let g=r[u];if(m?de(g,m,f):g.set(f),Array.isArray(y.children))for(let w of y.children)typeof w=="number"&&l(w,g,h+1)},c=[],o=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(o&&Array.isArray(o.nodes))c.push(...o.nodes);else for(let u=0;u<t;u++)i.has(u)||c.push(u);for(let u of c)l(u,null);for(let u=0;u<t;u++)!i.has(u)&&!c.includes(u)&&l(u,null);return r}function nr(n){return new TextDecoder().decode(n)}var vn=Z().decoders;function rr(n,e){vn.set(n.toLowerCase(),e)}function Ve(n){return vn.get(n.toLowerCase())}function wn(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 h=t.getUint8(0);throw h===123||h===32||h===10||h===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${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,c=null;for(;a+8<=s&&a+8<=e.byteLength;){let h=t.getUint32(a,!0),y=t.getUint32(a+4,!0),f=a+8;if(f+h>e.byteLength)throw new Error(`Truncated GLB chunk: required ${f+h} bytes, buffer has ${e.byteLength}`);if(y===1313821514){let g=new Uint8Array(e,f,h),w=nr(g);l=JSON.parse(w,(T,C)=>T==="__proto__"||T==="constructor"||T==="prototype"?void 0:C)}else y===5130562&&(c=e.slice(f,f+h));a=f+h}if(!l)throw new Error("Missing JSON chunk in GLB");let o=l.extensionsRequired||[];if(o.includes("KHR_draco_mesh_compression")&&!Ve("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(o.includes("EXT_meshopt_compression")&&!Ve("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(o.includes("KHR_texture_basisu")&&!Ve("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let u=c||new ArrayBuffer(0),m={gltf:l,bin:u,animations:[]};for(let h of Q)h.onParseGLB?.(m);return m}function ir(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 Me(n){if(ir(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return wn(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Rn=`#version 300 es
17
+ var je="__THREE_LIVE_REGISTRY__";function K(){let n=typeof globalThis<"u"?globalThis:{};if(!n[je]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,je,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[je]=e}}return n[je]}var Q=K().plugins;function Ke(n){let e=K().plugins;e.some(t=>t.name===n.name)||e.push(n)}function dn(){return K().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.);}`,er=`#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);}`,Ze=new WeakMap,fn=new Float32Array(20);function Rt(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 tr(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 c=l.positions;if(c)for(let o=0;o<c.length;o+=3)c[o]<e&&(e=c[o]),c[o+1]<t&&(t=c[o+1]),c[o+2]<r&&(r=c[o+2]),c[o]>i&&(i=c[o]),c[o+1]>s&&(s=c[o+1]),c[o+2]>a&&(a=c[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 nr(n){let e=Ze.get(n);if(e)return e;let t=(l,c)=>{let o=n.createShader(l);return n.shaderSource(o,c),n.compileShader(o),o},r=n.createProgram();n.attachShader(r,t(35633,Jn)),n.attachShader(r,t(35632,er)),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")},Ze.set(n,e),e}var pn={name:"contact-shadow",onAfterRender(n,e,t){let r=e.shadowIntensity;if(r<=0||!e.bounds)return;let i=nr(n),s=!e.xrSessionActive&&(e.backdropMeshes?.length??0)>0,a=[],l=[];for(let g of e.meshes||[]){if(!g||g.visible===!1||g.isPluginMesh||g.name==="__xr_reticle__"||g.name?.startsWith("__xr_slot_"))continue;let w=tr(g);if(!w)continue;g.transform&&(w=Rt(g.transform,w)),e.modelRootMatrix&&(w=Rt(e.modelRootMatrix,w));let[T,C,b,x,p,A]=w,d=[T,b,x,A,C-p,C+p];/floor|table|pedestal|ground|base|plane/i.test(g.name||"")||p<.14&&Math.min(x,A)>.45?l.push(d):a.push(d)}let c=[],o=e.bounds.center||[0,0,0],u=Math.max(.05,Number(e.bounds.radius)||.5),m=e.bounds.min,h=m?[o[0],o[1],o[2],u,Math.max(.01,o[1]-m[1]),u]:[o[0],o[1],o[2],u,u,u];e.modelRootMatrix&&(h=Rt(e.modelRootMatrix,h));let f=e.xrSessionActive&&l.length===0&&String(e.container?.tagName||"").toLowerCase()==="xr-live"?(e.modelRootMatrix?e.modelRootMatrix[5]*-.25+e.modelRootMatrix[13]:-.25)+.002:h[1]-h[4]+.002;for(let[g,w,T,C,b]of a){let x=-1/0;for(let[A,d,v,S,,M]of l)b>=M-.08&&Math.abs(g-A)<=v&&Math.abs(w-d)<=S&&M+.002>x&&(x=M+.002);s&&(x=Math.max(x,g>=.04&&g<=.36&&w>=-.34&&w<=-.04&&b>=.01?.036:Math.hypot(g,w)<=.66&&b>=-.06?.003:-.477)),isFinite(x)||(x=f);let p=c.find(A=>Math.hypot(g-A[0],w-A[1])<.06&&Math.abs(x-A[5])<.05);p?(p[2]=Math.max(p[2],T*.78),p[3]=Math.max(p[3],C*.78),p[4]=Math.min(p[4],b)):c.push([g,w,T,C,b,x])}if(c.length===0){let g=Math.max(.1,h[3]*1.5)/1.45;c.push([h[0],h[2],g,g,f,f])}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[g,w,T,C,b,x]of c){let p=Math.max(0,b-x),A=r/(1+p*2);if(A<.02)continue;let d=1+Math.min(.75,p*.85),v=Math.max(.045,T*1.45*d),S=Math.max(.045,C*1.45*d);fn.set([g-v,x,w-S,0,0,g+v,x,w-S,1,0,g+v,x,w+S,1,1,g-v,x,w+S,0,1]),n.bufferSubData(34962,0,fn),n.uniform1f(i.uIntensity,A),n.uniform1f(i.uSoftness,Math.min(1,e.shadowSoftness+Math.min(.45,p*.6))),n.drawElements(4,6,5123,0)}n.bindVertexArray(null),n.depthMask(!0),n.disable(3042)},onDestroy(n){let e=Ze.get(n);e&&(n.deleteVertexArray(e.vao),n.deleteBuffer(e.vbo),n.deleteBuffer(e.ibo),n.deleteProgram(e.prog),Ze.delete(n))}};function bn(n,e,t){let r=[],i=new Map,s=[],a=[],l=[],c=new Map,o=b=>{let x=i.get(b);return x===void 0&&(x=r.length,r.push({op:b}),i.set(b,x)),x},u=b=>{let x=c.get(b);return x===void 0&&(x=l.length,l.push({id:b}),c.set(b,x)),x},m=(b,x={})=>s.push({declaration:o(b),...x})-1,h=(b,x,p)=>a.push({id:b,type:x,value:p})-1,y=b=>({node:b,socket:"value"}),f=t?.interactivity??t?.gltfExtensions?.KHR_interactivity;if(f&&typeof f=="object"){let b=Array.isArray(f.graphs)?f.graphs[f.graph??0]:f;if(b&&Array.isArray(b.nodes)){let x=Array.isArray(b.declarations)?b.declarations:[];for(let p of x)p?.op&&o(p.op);Array.isArray(b.variables)&&a.push(...b.variables);for(let p of b.events||[])p?.id&&u(p.id);for(let p of b.nodes){if(!p||typeof p!="object")continue;let A=p.op||(typeof p.declaration=="number"?x[p.declaration]?.op:"");s.push(A?{...p,declaration:o(A)}:{...p})}}}let g=(b,x,p="translation")=>p==="baseColorFactor"||p==="metallicFactor"||p==="roughnessFactor"?`/materials/${Math.max(0,x)}/pbrMetallicRoughness/${p}`:p==="emissiveFactor"||p==="alphaCutoff"?`/materials/${Math.max(0,x)}/${p}`:p==="visible"?`/nodes/${b}/extensions/KHR_node_visibility/visible`:`/nodes/${b}/${p}`,w=new Map;n.forEach((b,x)=>{typeof b?.name=="string"&&!w.has(b.name)&&w.set(b.name,x)});let T=(b,x)=>typeof b.target=="string"&&w.has(b.target)?w.get(b.target):typeof b.targetNode=="number"?b.targetNode:x,C=b=>{let x=n[b];return(typeof x?.mesh=="number"?e[x.mesh]?.primitives?.[0]?.material:0)??0};for(let b=0;b<n.length;b++){let x=n[b],p=x?.extras?.interactivity;if(!p||typeof p!="object")continue;let A=(typeof x.mesh=="number"?e[x.mesh]?.primitives?.[0]?.material:0)??0,d=S=>{let M=Array.isArray(S)?S:[S],L=[];for(let E=0;E<M.length;E++){let R=M[E];if(!R||typeof R!="object")continue;let U=R.action||"interpolate",D=typeof R.duration=="number"?R.duration:.35;if(U==="toggleTransform"){let H=R.property==="rotation"||R.property==="scale"?R.property:"translation",z=H==="rotation"?x.rotation||[0,0,0,1]:H==="scale"?x.scale||[1,1,1]:x.translation||[0,0,0],F=`/nodes/${b}/${H}`,k=h(`__toggle_${b}_${E}`,"bool",!1),_=m("variable/get",{configuration:{variable:k}}),O=m("math/not",{values:{a:y(_)}}),B=m("variable/set",{configuration:{variable:k},values:{value:y(O)}}),V=m("pointer/interpolate",{configuration:{pointer:F},values:{value:{value:Array.isArray(R.to)?R.to:z},duration:{value:D}}}),N=m("pointer/interpolate",{configuration:{pointer:F},values:{value:{value:Array.isArray(R.from)?R.from:z},duration:{value:D}}});s[B].flows={out:{node:m("flow/branch",{values:{condition:y(_)},flows:{true:{node:V},false:{node:N}}})}},L.push(B)}else if(U==="interpolate"){let H=R.to??R.value;if(H===void 0)continue;let z={value:{value:H},duration:{value:D}};R.from!==void 0&&(z.from={value:R.from}),L.push(m("pointer/interpolate",{configuration:{pointer:typeof R.pointer=="string"?R.pointer:g(T(R,b),C(T(R,b)),R.property)},values:z}))}else if(U==="setProperty"){if(R.value===void 0)continue;L.push(m("pointer/set",{configuration:{pointer:typeof R.pointer=="string"?R.pointer:g(T(R,b),C(T(R,b)),R.property)},values:{value:{value:R.value}}}))}else if(U==="toggleVisibility"){let H=T(R,b),z=h(`__vis_${H}_${E}`,"bool",!0),F=m("variable/get",{configuration:{variable:z}}),k=m("math/not",{values:{a:y(F)}}),_=m("variable/set",{configuration:{variable:z},values:{value:y(k)}});s[_].flows={out:{node:m("pointer/set",{configuration:{pointer:`/nodes/${H}/extensions/KHR_node_visibility/visible`},values:{value:y(F)}})}},L.push(_)}else if(U==="cycleMaterialColor"&&Array.isArray(R.colors)&&R.colors.length>0){let H=typeof R.duration=="number"?R.duration:.25,z=`/materials/${Math.max(0,A)}/pbrMetallicRoughness/baseColorFactor`,F=h(`__color_idx_${b}_${E}`,"int",0),k=m("variable/get",{configuration:{variable:F}}),_=m("math/add",{values:{a:y(k),b:{value:1}}}),O=m("math/rem",{values:{a:y(_),b:{value:R.colors.length}}}),B=m("variable/set",{configuration:{variable:F},values:{value:y(O)}}),V={};for(let N=0;N<R.colors.length;N++){let I=R.colors[N],X=Array.isArray(I)&&I.length>=3?[I[0],I[1],I[2],I[3]??1]:[1,1,1,1];V[String(N)]={node:H>0?m("pointer/interpolate",{configuration:{pointer:z},values:{value:{value:X},duration:{value:H}}}):m("pointer/set",{configuration:{pointer:z},values:{value:{value:X}}})}}s[B].flows={out:{node:m("flow/switch",{values:{selection:y(k)},flows:V})}},L.push(B)}else if(U==="playAnimation")L.push(m("animation/start",{configuration:{animation:R.animation??R.clip??0}}));else if(U==="stopAnimation")L.push(m("animation/stop"));else if(U==="sendEvent"){let H={};for(let[z,F]of Object.entries(R.values||{}))H[z]={value:F};L.push(m("event/send",{configuration:{event:u(String(R.event??R.id??"custom"))},values:H}))}}if(!L.length)return null;if(L.length===1)return L[0];let P={};return L.forEach((E,R)=>{P[String(R)]={node:E}}),m("flow/sequence",{flows:P})},v=(S,M,L)=>{let P=d(M);P!==null&&m(S,{...L?{configuration:L}:{},flows:{out:{node:P}}})};if(p.onSelect&&v("pointer/onSelect",p.onSelect,{nodeIndex:b}),p.onHoverIn&&v("pointer/onHoverIn",p.onHoverIn,{nodeIndex:b}),p.onHoverOut&&v("pointer/onHoverOut",p.onHoverOut,{nodeIndex:b}),p.onStart&&v("event/onStart",p.onStart),p.onReceive&&typeof p.onReceive=="object")for(let[S,M]of Object.entries(p.onReceive))v("event/receive",M,{event:u(S)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:a,events:l}],graph:0}:null}var Qe='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).',Je="Security Error: client-side scripts require allow-client-scripts opt-in.";function J(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function et(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 Ie(n,e,t,r){let[i,s,a]=e,[l,c,o]=r,[u,m,h]=t,y=i-u,f=s-m,g=a-h,w=Math.hypot(y,f,g);w<=1e-5?(y=0,f=0,g=1):(y/=w,f/=w,g/=w);let T=c*g-o*f,C=o*y-l*g,b=l*f-c*y;w=Math.hypot(T,C,b),w<=1e-5?(T=0,C=0,b=0):(T/=w,C/=w,b/=w);let x=f*b-g*C,p=g*T-y*b,A=y*C-f*T;return w=Math.hypot(x,p,A),w<=1e-5?(x=0,p=0,A=0):(x/=w,p/=w,A/=w),n[0]=T,n[1]=x,n[2]=y,n[3]=0,n[4]=C,n[5]=p,n[6]=f,n[7]=0,n[8]=b,n[9]=A,n[10]=g,n[11]=0,n[12]=-(T*i+C*s+b*a),n[13]=-(x*i+p*s+A*a),n[14]=-(y*i+f*s+g*a),n[15]=1,n}function ae(n,e,t){let r=e[0],i=e[1],s=e[2],a=e[3],l=e[4],c=e[5],o=e[6],u=e[7],m=e[8],h=e[9],y=e[10],f=e[11],g=e[12],w=e[13],T=e[14],C=e[15],b=t[0],x=t[1],p=t[2],A=t[3];return n[0]=b*r+x*l+p*m+A*g,n[1]=b*i+x*c+p*h+A*w,n[2]=b*s+x*o+p*y+A*T,n[3]=b*a+x*u+p*f+A*C,b=t[4],x=t[5],p=t[6],A=t[7],n[4]=b*r+x*l+p*m+A*g,n[5]=b*i+x*c+p*h+A*w,n[6]=b*s+x*o+p*y+A*T,n[7]=b*a+x*u+p*f+A*C,b=t[8],x=t[9],p=t[10],A=t[11],n[8]=b*r+x*l+p*m+A*g,n[9]=b*i+x*c+p*h+A*w,n[10]=b*s+x*o+p*y+A*T,n[11]=b*a+x*u+p*f+A*C,b=t[12],x=t[13],p=t[14],A=t[15],n[12]=b*r+x*l+p*m+A*g,n[13]=b*i+x*c+p*h+A*w,n[14]=b*s+x*o+p*y+A*T,n[15]=b*a+x*u+p*f+A*C,n}function tt(n,e,t,r){let i=e[0],s=e[1],a=e[2],l=e[3],c=i+i,o=s+s,u=a+a,m=i*c,h=i*o,y=i*u,f=s*o,g=s*u,w=a*u,T=l*c,C=l*o,b=l*u,x=r[0],p=r[1],A=r[2];return n[0]=(1-(f+w))*x,n[1]=(h+b)*x,n[2]=(y-C)*x,n[3]=0,n[4]=(h-b)*p,n[5]=(1-(m+w))*p,n[6]=(g+T)*p,n[7]=0,n[8]=(y+C)*A,n[9]=(g-T)*A,n[10]=(1-(m+f))*A,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function ye(n,e){let t=e[0],r=e[1],i=e[2],s=e[4],a=e[5],l=e[6],c=e[8],o=e[9],u=e[10],m=u*a-l*o,h=-u*s+l*c,y=o*s-a*c,f=t*m+r*h+i*y;return f&&(f=1/f,n[0]=m*f,n[1]=(-u*r+i*o)*f,n[2]=(l*r-i*a)*f,n[3]=h*f,n[4]=(u*t-i*c)*f,n[5]=(-l*t+i*s)*f,n[6]=y*f,n[7]=(-o*t+r*c)*f,n[8]=(a*t-r*s)*f),n}function yn(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],a=e[4],l=e[5],c=e[6],o=e[7],u=e[8],m=e[9],h=e[10],y=e[11],f=e[12],g=e[13],w=e[14],T=e[15],C=t*l-r*a,b=t*c-i*a,x=t*o-s*a,p=r*c-i*l,A=r*o-s*l,d=i*o-s*c,v=u*g-m*f,S=u*w-h*f,M=u*T-y*f,L=m*w-h*g,P=m*T-y*g,E=h*T-y*w,R=C*E-b*P+x*L+p*M-A*S+d*v;return R?(R=1/R,n[0]=(l*E-c*P+o*L)*R,n[1]=(i*P-r*E-s*L)*R,n[2]=(g*d-w*A+T*p)*R,n[3]=(h*A-m*d-y*p)*R,n[4]=(c*M-a*E-o*S)*R,n[5]=(t*E-i*M+s*S)*R,n[6]=(w*x-f*d-T*b)*R,n[7]=(u*d-h*x+y*b)*R,n[8]=(a*P-l*M+o*v)*R,n[9]=(r*M-t*P-s*v)*R,n[10]=(f*A-g*x+T*C)*R,n[11]=(m*x-u*A-y*C)*R,n[12]=(l*S-a*L-c*v)*R,n[13]=(t*L-r*S+i*v)*R,n[14]=(g*b-f*p-w*C)*R,n[15]=(u*p-m*b+h*C)*R,n):null}function Et(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],c=i[3]*e+i[7]*t+i[11]*r+i[15],o=c!==0?1/c:1;n[0]=s*o,n[1]=a*o,n[2]=l*o}function gn(n,e,t,r,i,s,a,l,c,o,u,m,h,y,f,g,w=0){let T=o-a,C=u-l,b=m-c,x=h-a,p=y-l,A=f-c,d=i*A-s*p,v=s*x-r*A,S=r*p-i*x,M=T*d+C*v+b*S;if(M>-1e-7&&M<1e-7)return!1;let L=1/M,P=n-a,E=e-l,R=t-c,U=L*(P*d+E*v+R*S);if(U<-w||U>1+w)return!1;let D=E*b-R*C,H=R*T-P*b,z=P*C-E*T,F=L*(r*D+i*H+s*z);if(F<-w||U+F>1+w)return!1;let k=L*(x*D+p*H+A*z);if(k>1e-4&&k<g.distance){g.distance=k,g.point=[n+r*k,e+i*k,t+s*k];let _=C*A-b*p,O=b*x-T*A,B=T*p-C*x,V=Math.hypot(_,O,B)||1;return g.normal=[_/V,O/V,B/V],!0}return!1}function nt(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let u=0;u<t;u++)r.push(J());if(t===0)return r;let i=new Set;for(let u of n.nodes)if(Array.isArray(u.children))for(let m of u.children)i.add(m);let s=new Set,a=128,l=(u,m,h=0)=>{if(h>a||u<0||u>=t||s.has(u))return;s.add(u);let y=n.nodes[u];if(!y)return;let f=J();if(e&&e[u])f.set(e[u]);else if(y.matrix&&y.matrix.length===16)f.set(y.matrix);else{let w=y.translation||[0,0,0],T=y.rotation||[0,0,0,1],C=y.scale||[1,1,1];tt(f,T,w,C)}let g=r[u];if(m?ae(g,m,f):g.set(f),Array.isArray(y.children))for(let w of y.children)typeof w=="number"&&l(w,g,h+1)},c=[],o=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(o&&Array.isArray(o.nodes))c.push(...o.nodes);else for(let u=0;u<t;u++)i.has(u)||c.push(u);for(let u of c)l(u,null);for(let u=0;u<t;u++)!i.has(u)&&!c.includes(u)&&l(u,null);return r}function rr(n){return new TextDecoder().decode(n)}var Sn=K().decoders;function ir(n,e){Sn.set(n.toLowerCase(),e)}function ze(n){return Sn.get(n.toLowerCase())}function Rn(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 h=t.getUint8(0);throw h===123||h===32||h===10||h===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${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,c=null;for(;a+8<=s&&a+8<=e.byteLength;){let h=t.getUint32(a,!0),y=t.getUint32(a+4,!0),f=a+8;if(f+h>e.byteLength)throw new Error(`Truncated GLB chunk: required ${f+h} bytes, buffer has ${e.byteLength}`);if(y===1313821514){let g=new Uint8Array(e,f,h),w=rr(g);l=JSON.parse(w,(T,C)=>T==="__proto__"||T==="constructor"||T==="prototype"?void 0:C)}else y===5130562&&(c=e.slice(f,f+h));a=f+h}if(!l)throw new Error("Missing JSON chunk in GLB");let o=l.extensionsRequired||[];if(o.includes("KHR_draco_mesh_compression")&&!ze("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(o.includes("EXT_meshopt_compression")&&!ze("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(o.includes("KHR_texture_basisu")&&!ze("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let u=c||new ArrayBuffer(0),m={gltf:l,bin:u,animations:[]};for(let h of Q)h.onParseGLB?.(m);return m}function sr(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 Te(n){if(sr(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return Rn(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var An=`#version 300 es
20
20
  layout(location=0) in vec3 aPosition;
21
21
  layout(location=1) in vec3 aNormal;
22
22
  layout(location=2) in vec2 aUV;
@@ -34,7 +34,7 @@ vec2 scaleUV=uUvTransform.zw;
34
34
  if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
35
35
  vUV=aUV*scaleUV+uUvTransform.xy;
36
36
  gl_Position=uMVP*vec4(aPosition,1.0);
37
- }`,Sn=`#version 300 es
37
+ }`,or=`#version 300 es
38
38
  precision highp float;
39
39
  in vec3 vNormal,vWorldPos;
40
40
  in vec2 vUV;
@@ -42,14 +42,13 @@ uniform vec4 uBaseColor;
42
42
  uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity;
43
43
  uniform vec2 uClearcoat;
44
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;
45
+ uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap;
46
+ uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap;
47
+ uniform float uNormalScale,uOcclusionStrength;
48
+ /*XRD_U*/
49
49
  uniform vec2 uViewportSize;
50
- uniform vec4 uViewport;
51
- uniform vec3 uCameraFwd;
52
- uniform int uToneMapping,uNumDirLights,uNumPointLights;
50
+ uniform vec4 uSectionPlane;
51
+ uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
53
52
  uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2];
54
53
  out vec4 fragColor;
55
54
 
@@ -118,6 +117,7 @@ return color;
118
117
  }
119
118
 
120
119
  void main(){
120
+ if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
121
121
  vec4 base=uBaseColor;
122
122
  if(uHasTexture==1)base*=texture(uBaseColorTexture,vUV);
123
123
  if(length(vNormal)<1e-4&&uHasTexture==1){
@@ -198,31 +198,17 @@ color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
198
198
  }
199
199
  color=applyToneMapping(color,uToneMapping);
200
200
  float outAlpha=base.a;
201
- if(uXrDepthEnabled==1){
202
- vec2 normViewUV=vec2((gl_FragCoord.x-uViewport.x)/max(uViewport.z,1.0),1.0-(gl_FragCoord.y-uViewport.y)/max(uViewport.w,1.0));
203
- vec2 depthUV=(uXrDepthUVTransform*vec4(normViewUV,0.0,1.0)).xy;
204
- if(depthUV.x>=0.0&&depthUV.x<=1.0&&depthUV.y>=0.0&&depthUV.y<=1.0){
205
- vec4 depthSample=texture(uXrDepthTex,depthUV);
206
- float rawDepth=uXrDepthFormat==1?depthSample.r:(depthSample.r*255.0+depthSample.a*65280.0);
207
- float realDepth=rawDepth*uXrRawValueToMeters;
208
- float virtDepth=dot(uCameraFwd,uCameraFwd)>0.5?dot(vWorldPos-uCameraPos,uCameraFwd):length(uCameraPos-vWorldPos);
209
- if(rawDepth>0.0&&(uXrDepthFormat==1||rawDepth<65500.0)&&realDepth>0.15&&realDepth<20.0&&virtDepth>realDepth+0.02){
210
- float occAlpha=1.0-smoothstep(0.0,0.035,virtDepth-realDepth-0.02);
211
- outAlpha*=occAlpha;
212
- if(outAlpha<0.01)discard;
213
- }
214
- }
215
- }
201
+ /*XRD_O*/
216
202
  fragColor=vec4(color,outAlpha);
217
- }`,sr=`#version 300 es
203
+ }`,ar=`#version 300 es
218
204
  layout(location=0) in vec3 aPosition;
219
205
  uniform mat4 uMVP;
220
- void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,or=`#version 300 es
206
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,cr=`#version 300 es
221
207
  precision highp float;
222
208
  uniform vec4 uColorId;
223
209
  out vec4 fragColor;
224
- void main(){fragColor=uColorId;}`;function gn(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 Mt(n,e,t){let r=gn(n,35633,e),i=gn(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 Tt(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var An=["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","uViewport","uCameraFwd"];function ar(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 Et(n,e,t,r,i,s,a){if(r===void 0||!e.accessors?.[r])return null;let l=e.accessors[r],c=e.bufferViews[l.bufferView],o=(c.byteOffset||0)+(l.byteOffset||0),u=c.byteStride&&c.byteStride>s*4?c.byteStride>>2:s,m;if(u===s)m=new Float32Array(t,o,l.count*s);else{m=new Float32Array(l.count*s);let y=new Float32Array(t,c.byteOffset||0,Math.floor(c.byteLength/4)),f=(l.byteOffset||0)>>2;for(let g=0;g<l.count;g++){let w=f+g*u;for(let T=0;T<s;T++)m[g*s+T]=y[w+T]}}let h=n.createBuffer();return a.push(h),n.bindBuffer(34962,h),n.bufferData(34962,m,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),m}var En=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Mn=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function xn(n,e,t=Mn,r){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:i,bin:s}=e,a=[],l=tt(i),c=[];if(Array.isArray(i.nodes))for(let v=0;v<i.nodes.length;v++){let R=i.nodes[v];R.mesh!==void 0&&i.meshes&&i.meshes[R.mesh]&&c.push({node:R,nodeIdx:v,meshIdx:R.mesh})}let o=c.length>0?c:(i.meshes||[]).map((v,R)=>({node:v,nodeIdx:-1,meshIdx:R})),u=[];if(Array.isArray(e.lights)&&e.lights.length>0)u.push(...e.lights);else if(i.extensions?.KHR_lights_punctual?.lights){let v=i.extensions.KHR_lights_punctual.lights;for(let R of v){let M=R.type==="directional"?"directional":R.type==="point"?"point":"ambient";u.push({type:M,color:R.color||[1,1,1],intensity:R.intensity!==void 0?R.intensity:1})}}if(u.length===0&&(u.push({type:"ambient",color:[1,1,1],intensity:.35}),u.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 m=[];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 v=0;v<i.textures.length;v++){let R=i.textures[v],M=i.images[R.source];if(M){let D=n.createTexture();if(n.bindTexture(3553,D),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 F=i.bufferViews[M.bufferView],E=s.slice(F.byteOffset||0,(F.byteOffset||0)+F.byteLength),S=new Blob([E],{type:M.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(S).then(k=>{n.bindTexture(3553,D),n.texImage2D(3553,0,6408,6408,5121,k),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(M.uri){let F=ar(M.uri);if(F){let E=new Image;E.crossOrigin="anonymous",E.referrerPolicy="no-referrer",E.onload=()=>{n.bindTexture(3553,D),n.texImage2D(3553,0,6408,6408,5121,E),n.generateMipmap(3553),r?.()},E.src=F}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",M.uri)}m.push(D)}else m.push(null)}}let h=[1/0,1/0,1/0],y=[-1/0,-1/0,-1/0],f=0,g=0;for(let v=0;v<o.length;v++){let R=o[v],M=i.meshes[R.meshIdx],D=R.nodeIdx>=0?l[R.nodeIdx]:J(),F=new Float32Array(9);be(F,D);let E={name:R.node.name||M.name||`Mesh_${R.meshIdx}`,nodeIndex:R.nodeIdx,transform:D,normalMatrix:F,primitives:[],extras:R.node.extras||M.extras};for(let S of M.primitives||[]){if(S.extensions?.KHR_draco_mesh_compression){let q=Ve("draco");q&&q.decodePrimitive(i,S,s)}let k=[],P=n.createVertexArray();n.bindVertexArray(P);let X=i.accessors[S.attributes.POSITION],V=Number(X?.count??0);if(!Number.isFinite(V)||V<0||f+V>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(f+=V,X?.min&&X?.max)for(let q=0;q<3;q++){let he=D[12+q],Pe=D[12+q];for(let Se=0;Se<3;Se++){let $e=D[Se*4+q]*X.min[Se],qe=D[Se*4+q]*X.max[Se];he+=$e<qe?$e:qe,Pe+=$e>qe?$e:qe}he<h[q]&&(h[q]=he),Pe>y[q]&&(y[q]=Pe)}let I=Et(n,i,s,S.attributes.POSITION,0,3,k);Et(n,i,s,S.attributes.NORMAL,1,3,k),Et(n,i,s,S.attributes.TEXCOORD_0,2,2,k);let U=0,_=5123,B=null;if(S.indices!==void 0){let q=i.accessors[S.indices],Pe=(i.bufferViews[q.bufferView].byteOffset||0)+(q.byteOffset||0);if(U=Number(q.count??0),!Number.isFinite(U)||U<0||g+U>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);g+=U,_=q.componentType===5125?5125||5125:5123||5123;let Se=n.createBuffer();k.push(Se),n.bindBuffer(34963,Se),q.componentType===5125?(B=new Uint32Array(s,Pe,q.count),n.bufferData(34963,B,35044)):(B=new Uint16Array(s,Pe,q.count),n.bufferData(34963,B,35044))}else U=X.count;let O={};for(let q of Q)if(q.onBuildPrimitiveVAO){let he=q.onBuildPrimitiveVAO(n,P,S,i,s);he&&(O[q.name]=he)}n.bindVertexArray(null);let z=i.materials&&S.material!==void 0?i.materials[S.material]:null,L=Rn,N=Sn,H=!1;for(let q of Q)if(q.onResolveShader){let he=q.onResolveShader(S,z,L,N);he&&(L=he.vs,N=he.fs,H=!0)}let G=H?Mt(n,L,N):null,ae=G?Tt(n,G,An):null,K=z?.pbrMetallicRoughness,ee=K?.baseColorFactor||[.8,.8,.8,1],le=K?.metallicFactor??.1,se=K?.roughnessFactor??.5,W=z?.extensions?.KHR_materials_clearcoat,j=W?W.clearcoatFactor??1:0,fe=Math.max(.04,W?.clearcoatRoughnessFactor??.04),oe=K?.baseColorTexture!==void 0&&m[K.baseColorTexture.index]?m[K.baseColorTexture.index]:null,re=K?.metallicRoughnessTexture!==void 0&&m[K.metallicRoughnessTexture.index]?m[K.metallicRoughnessTexture.index]:null,ie=z?.normalTexture!==void 0&&m[z.normalTexture.index]?m[z.normalTexture.index]:null,Re=z?.normalTexture?.scale??1,me=z?.occlusionTexture!==void 0&&m[z.occlusionTexture.index]?m[z.occlusionTexture.index]:null,pe=z?.occlusionTexture?.strength??1,xe=!!(z?.extensions?.KHR_materials_transmission||O.materials?.isTransmissive);E.primitives.push({vao:P,indexCount:U,indexType:_,baseColor:ee,metallic:le,roughness:se,clearcoat:j,clearcoatRoughness:fe,positions:I,indices:B,texture:oe,metallicRoughnessTexture:re,normalTexture:ie,occlusionTexture:me,normalScale:Re,occlusionStrength:pe,buffers:k,materialIndex:S.material,pluginData:O,customProgram:G,customUniforms:ae,isTransmissive:xe})}a.push(E)}isFinite(h[0])||(h=[-1,-1,-1]),isFinite(y[0])||(y=[1,1,1]);let w=[(h[0]+y[0])/2,(h[1]+y[1])/2,(h[2]+y[2])/2],T=y[0]-h[0],C=y[1]-h[1],b=y[2]-h[2],x=Math.max(Math.hypot(T,C,b)/2,.5),p=[h[0],h[1],h[2]],A=[y[0],y[1],y[2]],d=e.animations;if(!d){for(let v of Q)if(v.onParseGLB?.(e),e.animations){d=e.animations;break}}return d||(d=[]),{meshes:a,bounds:{center:w,radius:x,min:p,max:A},lights:u,animations:d,worldMatrices:l}}var ce=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=J();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=J();this.viewMatrix=J();this.modelMatrix=J();this.mvpMatrix=J();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:J(),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 c=e.querySelector("canvas");c||(c=document.createElement("canvas"),c.style.width="100%",c.style.height="100%",c.style.display="block",c.style.touchAction="none",e.prepend(c)),i=c}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=Mt(l,Rn,Sn),this.pickProg=Mt(l,sr,or),this.uRender=Tt(l,this.renderProg,An),this.uPick=Tt(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){rr(e,t)}static getDecoder(e){return Ve(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}=xn(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 Q)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 c=e.exposure??e.environmentIntensity??e.gltf?.extras?.exposure??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.exposure??e.gltf?.asset?.extras?.environmentIntensity;c!==void 0&&(this.envIntensity=Math.max(0,Number(c))),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(wn(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Me(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Me(e),{meshes:i}=xn(this.gl,r,Mn,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],be(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),be(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],a=[],l=[];for(let c of this.lights){let o=c.color||[1,1,1],u=c.intensity!==void 0?c.intensity:1;if(c.type==="ambient")r=[o[0]*u,o[1]*u,o[2]*u];else if(c.type==="directional"&&i.length<6){let m=c.direction||[.5,1,.8];i.push(m[0],m[1],m[2]),s.push(o[0]*u,o[1]*u,o[2]*u)}else if(c.type==="point"&&a.length<6){let m=c.position||[0,0,0];a.push(m[0],m[1],m[2]),l.push(o[0]*u,o[1]*u,o[2]*u)}}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 Q)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of Q)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(u=>u.primitives.filter(m=>m.materialIndex===r||e.length===1&&m.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,c=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,o={baseColorFactor:a,metallicFactor:l,roughnessFactor:c,setBaseColorFactor:u=>{let m=[u[0],u[1],u[2],u[3]??1];o.baseColorFactor=m,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=m);for(let h of i)h.baseColor=m;this.render()},setMetallicFactor:u=>{o.metallicFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=u);for(let m of i)m.metallic=u;this.render()},setRoughnessFactor:u=>{o.roughnessFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=u);for(let m of i)m.roughness=u;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 Q)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=J();de(r,this.projMatrix,this.viewMatrix);let[i,s,a]=e,l=t?t[0]:0,c=t?t[1]:0,o=t?t[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*e[0]+u[4]*e[1]+u[8]*e[2]+u[12],s=u[1]*e[0]+u[5]*e[1]+u[9]*e[2]+u[13],a=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]+u[14],t&&(l=u[0]*t[0]+u[4]*t[1]+u[8]*t[2],c=u[1]*t[0]+u[5]*t[1]+u[9]*t[2],o=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]));let m=r[0]*i+r[4]*s+r[8]*a+r[12],h=r[1]*i+r[5]*s+r[9]*a+r[13],y=r[2]*i+r[6]*s+r[10]*a+r[14],f=r[3]*i+r[7]*s+r[11]*a+r[15];if(f<=1e-4)return{x:0,y:0,z:1,visible:!1};let g=m/f,w=h/f,T=y/f,C=this.canvas.getBoundingClientRect(),b=C.width||this.canvas.clientWidth||this.canvas.width||300,x=C.height||this.canvas.clientHeight||this.canvas.height||150,p=(g*.5+.5)*b,A=(-w*.5+.5)*x,d=g>=-1.1&&g<=1.1&&w>=-1.1&&w<=1.1&&T>=-1&&T<=1;if(d&&t){let v=this.customTarget||this.bounds.center,R=v[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),M=v[1]+this.currDistance*Math.sin(this.currPhi),D=v[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),F=[i-R,s-M,a-D];l*F[0]+c*F[1]+o*F[2]>.05&&(d=!1)}return{x:p,y:A,z:T,visible:d}}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]],c=this.customTarget?[...this.customTarget]:[...this.bounds.center],o=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;c[0]+=(-i*a[0]+s*l[0])*o,c[1]+=(-i*a[1]+s*l[1])*o,c[2]+=(-i*a[2]+s*l[2])*o,this.customTarget=c}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),c=i.height>0?Math.floor((t-i.top)*(a/i.height)):Math.floor(t);return this.performMeshPick(l,c,!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);e=this.mapStereoPickX(e,s);let l=J();de(l,this.projMatrix,this.viewMatrix);let c=[],o=Math.max(0,Math.min(s-1,e)),u=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(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 d=0;d<this.meshes.length;d++){let v=this.meshes[d];if(v.visible===!1||v.isPluginMesh)continue;let R=d+1,M=(R&255)/255,D=(R>>8&255)/255,F=(R>>16&255)/255;i.uniform4f(this.uPick.uColorId,M,D,F,1),de(this.modelMatrix,this.modelRootMatrix,v.transform),de(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let E of v.primitives)i.bindVertexArray(E.vao),i.drawElements(4,E.indexCount,E.indexType,0)}let p=new Uint8Array(4);i.readPixels(o,u,1,1,6408,5121,p),i.bindFramebuffer(36160,null);let A=p[0]+(p[1]<<8)+(p[2]<<16);A>0&&A<=this.meshes.length&&(c=[this.meshes[A-1]])}c.length===0&&(c=this.meshes.filter(p=>p.visible!==!1));let m=null,h=1/0,y=[0,0,0],f=[0,1,0],g=this.customTarget||this.bounds.center,w=g[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),T=g[1]+this.currDistance*Math.sin(this.currPhi),C=g[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let p of c){de(this.modelMatrix,this.modelRootMatrix,p.transform),de(this.mvpMatrix,l,this.modelMatrix);let A=J();if(!bn(A,this.mvpMatrix))continue;let d=(o+.5)/s*2-1,v=(u+.5)/a*2-1,R=[0,0,0],M=[0,0,0];At(R,d,v,-1,A),At(M,d,v,1,A);let D=M[0]-R[0],F=M[1]-R[1],E=M[2]-R[2],S=Math.hypot(D,F,E)||1,k=D/S,P=F/S,X=E/S,V={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((U=>{for(let _ of p.primitives){if(!_.positions)continue;let B=_.positions,O=_.indices,z=Math.floor(O?O.length/3:B.length/9);for(let L=0;L<z;L++){let N=O?O[L*3]:L*3,H=O?O[L*3+1]:L*3+1,G=O?O[L*3+2]:L*3+2;yn(R[0],R[1],R[2],k,P,X,B[N*3],B[N*3+1],B[N*3+2],B[H*3],B[H*3+1],B[H*3+2],B[G*3],B[G*3+1],B[G*3+2],V,U)}}})(1e-4),isFinite(V.distance)){let U=V.point[0],_=V.point[1],B=V.point[2],O=this.modelMatrix,z=O[0]*U+O[4]*_+O[8]*B+O[12],L=O[1]*U+O[5]*_+O[9]*B+O[13],N=O[2]*U+O[6]*_+O[10]*B+O[14],H=z-w,G=L-T,ae=N-C,K=Math.hypot(H,G,ae);if(K<h){be(this.normalMatrix,this.modelMatrix);let ee=this.normalMatrix,le=V.normal[0],se=V.normal[1],W=V.normal[2],j=ee[0]*le+ee[3]*se+ee[6]*W,fe=ee[1]*le+ee[4]*se+ee[7]*W,oe=ee[2]*le+ee[5]*se+ee[8]*W,re=Math.hypot(j,fe,oe)||1;j/=re,fe/=re,oe/=re,j*H+fe*G+oe*ae>0&&(j=-j,fe=-fe,oe=-oe),m=p,h=Math.round(K*1e3)/1e3,y=[Math.round(z*1e3)/1e3,Math.round(L*1e3)/1e3,Math.round(N*1e3)/1e3],f=[Math.round(j*1e3)/1e3,Math.round(fe*1e3)/1e3,Math.round(oe*1e3)/1e3]}}}if(!m)return null;let x={meshIndex:this.meshes.indexOf(m),meshName:m.name,nodeIndex:m.nodeIndex,distance:h,hitPoint:y,normal:f,screenX:e,screenY:t};if(r){for(let p of Q)p.onMeshSelect?.(this,x);this.opts.onMeshClick&&this.opts.onMeshClick(x),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:x}))}return x}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,s=i?e-r:e,a=i?Math.max(1,t-r):r,l=(s+.5)/a*2-1;return Math.floor((l*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);Je(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center,i=r[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),s=r[1]+this.currDistance*Math.sin(this.currPhi),a=r[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);Ie(this.viewMatrix,[i,s,a],r,[0,1,0]),de(this.mvpMatrix,this.projMatrix,this.viewMatrix),be(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let r of Q)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of Q)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],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 a of Q)a.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 a of Q)a.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=s;let a={theta:r,phi:i,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(a),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:a}))}}renderXRView(e,t,r,i,s=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let l=e?.transform?.inverse?.matrix||this.viewMatrix,c=e?.projectionMatrix||this.projMatrix,o=e?.transform?.position,u=o?[o.x,o.y,o.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:l,projMatrix:c,eyePos:u,viewport:i,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:s})}render(e){if(!e&&this.stereoSBS){let x=Math.max(2,this.canvas.width||2),p=Math.max(1,this.canvas.height||1),A=Math.max(1,Math.floor(x*.5)),d=Math.max(1,x-A),v=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),R=this.customTarget||this.bounds.center,M=R[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),D=R[1]+this.currDistance*Math.sin(this.currPhi),F=R[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),E=Math.cos(this.currTheta),S=-Math.sin(this.currTheta),k=.032,P=J(),X=J(),V=[M-E*k,D,F-S*k],I=[R[0]-E*k*.25,R[1],R[2]-S*k*.25];Je(P,this.fov,A/p,.1,v),Ie(X,V,I,[0,1,0]);let U=J(),_=J(),B=[M+E*k,D,F+S*k],O=[R[0]+E*k*.25,R[1],R[2]+S*k*.25];Je(U,this.fov,d/p,.1,v),Ie(_,B,O,[0,1,0]),this.render({viewMatrix:X,projMatrix:P,eyePos:V,viewport:[0,0,A,p],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:_,projMatrix:U,eyePos:B,viewport:[A,0,d,p],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,x,p);return}let t=this.gl,r=0,i=0,s=this.canvas.width,a=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],s=e.viewport[2],a=e.viewport[3],t.viewport(r,i,s,a)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16384|256));let l=J(),c=e?.viewMatrix??this.viewMatrix;de(l,e?.projMatrix??this.projMatrix,c);let o=[-c[2],-c[6],-c[10]],u=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:0,m=this.customTarget||this.bounds.center,h=e?e.eyePos[0]:m[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),y=e?e.eyePos[1]:m[1]+this.currDistance*Math.sin(this.currPhi),f=e?e.eyePos[2]:m[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let x of Q)x.onBeforeDrawScene?.(this,t,l,[h,y,f],u);let g=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&g===0)return;let w=e?.eye||"none",T=!1,C=g>0?[...this.backdropMeshes,...this.meshes]:this.meshes,b=x=>{for(let p=0;p<C.length;p++){let A=C[p];if(A.visible===!1)continue;let d=this.selectedMeshName!==""&&A.name===this.selectedMeshName;p<g||A.worldSpace===!0||A.name==="__xr_reticle__"?this.modelMatrix.set(A.transform):de(this.modelMatrix,this.modelRootMatrix,A.transform),de(this.mvpMatrix,l,this.modelMatrix),be(A.normalMatrix,this.modelMatrix);let v=A.extras?.xr?.stereo||A.userData?.xr?.stereo,R=0,M=0,D=1,F=1;v==="sbs"?(D=.5,R=w==="right"?.5:0):v==="ou"&&(F=.5,M=w==="right"?.5:0);for(let E of A.primitives){let S=!!E.isTransmissive;if(!x&&S){T=!0;continue}if(x&&!S)continue;let k=E.customProgram||this.renderProg,P=E.customUniforms||this.uRender;t.useProgram(k),t.uniform1i(P.uToneMapping,u),t.uniform1f(P.uEnvIntensity,this.envIntensity),t.uniform3f(P.uCameraPos,h,y,f),P.uCameraFwd&&t.uniform3f(P.uCameraFwd,o[0],o[1],o[2]),t.uniform1f(P.uEmissive,d?1:0),t.uniformMatrix4fv(P.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(P.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(P.uNormalMatrix,!1,A.normalMatrix),P.uUvTransform&&t.uniform4f(P.uUvTransform,R,M,D,F),P.uViewportSize&&t.uniform2f(P.uViewportSize,Math.max(1,s),Math.max(1,a)),P.uViewport&&t.uniform4f(P.uViewport,r,i,Math.max(1,s),Math.max(1,a)),this.xrDepthState.enabled&&this.xrDepthState.texture?(t.activeTexture(33989),t.bindTexture(3553,this.xrDepthState.texture),P.uXrDepthTex&&t.uniform1i(P.uXrDepthTex,5),P.uXrDepthEnabled&&t.uniform1i(P.uXrDepthEnabled,1),P.uXrDepthFormat&&t.uniform1i(P.uXrDepthFormat,this.xrDepthState.format||0),P.uXrRawValueToMeters&&t.uniform1f(P.uXrRawValueToMeters,this.xrDepthState.rawValueToMeters),P.uXrDepthUVTransform&&t.uniformMatrix4fv(P.uXrDepthUVTransform,!1,this.xrDepthState.uvTransform)):P.uXrDepthEnabled&&t.uniform1i(P.uXrDepthEnabled,0),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(P.uEnvironmentMap,4),t.uniform1i(P.uHasEnvironmentMap,1)):t.uniform1i(P.uHasEnvironmentMap,0),this.bindLights(P);for(let X of Q)X.onBeforeDrawPrimitive?.(t,k,E,A,this.worldMatrices||[],this.gltf);t.uniform4fv(P.uBaseColor,E.baseColor),t.uniform1f(P.uMetallic,E.metallic),t.uniform1f(P.uRoughness,E.roughness),P.uClearcoat&&t.uniform2f(P.uClearcoat,E.clearcoat??0,E.clearcoatRoughness??.04),E.texture?(t.activeTexture(33984),t.bindTexture(3553,E.texture),t.uniform1i(P.uBaseColorTexture,0),t.uniform1i(P.uHasTexture,1)):t.uniform1i(P.uHasTexture,0),E.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,E.metallicRoughnessTexture),t.uniform1i(P.uMetallicRoughnessTexture,1),t.uniform1i(P.uHasMetallicRoughnessTexture,1)):t.uniform1i(P.uHasMetallicRoughnessTexture,0),E.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,E.normalTexture),t.uniform1i(P.uNormalTexture,2),t.uniform1i(P.uHasNormalTexture,1),t.uniform1f(P.uNormalScale,E.normalScale)):t.uniform1i(P.uHasNormalTexture,0),E.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,E.occlusionTexture),t.uniform1i(P.uOcclusionTexture,3),t.uniform1i(P.uHasOcclusionTexture,1),t.uniform1f(P.uOcclusionStrength,E.occlusionStrength)):t.uniform1i(P.uHasOcclusionTexture,0),t.bindVertexArray(E.vao),t.drawElements(4,E.indexCount,E.indexType,0)}}};if(b(!1),T){for(let x of Q)x.onBeforeTransmissivePass?.(t,this);b(!0)}for(let x of Q)x.onAfterRender?.(t,this,l)}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 Q)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()}};ce.registerPlugin=je,ce.getRegisteredPlugins=mn;function cr(n){return n+3&-4}function ur(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 ze(n,e){n.updateMatrixWorld(!0);let t=[],r=0,i=[],s=[],a=[],l=[],c=new Set,o=[],u=[],m=new Map,h=[];function y(d,v){let R=new Uint8Array(d.buffer,d.byteOffset,d.byteLength),M=cr(R.byteLength),D=new Uint8Array(M);D.set(R),t.push(D);let F=i.length;return i.push({buffer:0,byteOffset:r,byteLength:R.byteLength,target:v}),r+=M,F}function f(d,v,R,M,D,F,E){let S=y(d,R),k=s.length,P={bufferView:S,byteOffset:0,componentType:M,count:D,type:v};return F&&(P.min=F),E&&(P.max=E),s.push(P),k}n.traverse(d=>{(d.isLight||d.color&&d.intensity!==void 0)&&h.push({type:d.type,color:[d.color.r,d.color.g,d.color.b],intensity:d.intensity,position:[d.position.x,d.position.y,d.position.z]})});let g=[];function w(d){let v={name:d.name||""},R=d.position,M=d.quaternion,D=d.scale;if((R.x||R.y||R.z)&&(v.translation=[R.x,R.y,R.z]),(M.x||M.y||M.z||M.w!==1)&&(v.rotation=[M.x,M.y,M.z,M.w]),(D.x!==1||D.y!==1||D.z!==1)&&(v.scale=[D.x,D.y,D.z]),d.userData&&Object.keys(d.userData).length>0&&(v.extras=JSON.parse(JSON.stringify(d.userData,(E,S)=>{if(!(E==="__proto__"||E==="prototype"||E==="constructor"))return typeof S=="function"?void 0:S})),d.userData.xr)){let E=ur(d.userData.xr);v.extensions={...v.extensions||{},MOZ_hubs_components:E,ANDROID_xr_scenecore:E},Z().xrTraitSerializer?.gltfNode(v,d.userData.xr),c.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(d.geometry){let E=d.geometry,S=E.attributes.position;if(S&&S.count>0){let k=[1/0,1/0,1/0],P=[-1/0,-1/0,-1/0];for(let U=0;U<S.count;U++){let _=S.getX(U),B=S.getY(U),O=S.getZ(U);_<k[0]&&(k[0]=_),_>P[0]&&(P[0]=_),B<k[1]&&(k[1]=B),B>P[1]&&(P[1]=B),O<k[2]&&(k[2]=O),O>P[2]&&(P[2]=O)}let V={attributes:{POSITION:f(S.array,"VEC3",34962,5126,S.count,k,P)}};if(E.attributes.normal&&(V.attributes.NORMAL=f(E.attributes.normal.array,"VEC3",34962,5126,E.attributes.normal.count)),E.attributes.uv&&(V.attributes.TEXCOORD_0=f(E.attributes.uv.array,"VEC2",34962,5126,E.attributes.uv.count)),E.index){let U=E.index.array instanceof Uint32Array;V.indices=f(E.index.array,"SCALAR",34963,U?5125:5123,E.index.count)}if(d.material){let U=m.get(d.material);if(U===void 0){U=u.length,m.set(d.material,U);let _=d.material,B={name:_.name||"",pbrMetallicRoughness:{baseColorFactor:[_.color.r,_.color.g,_.color.b,_.opacity],metallicFactor:_.metalness,roughnessFactor:_.roughness},doubleSided:_.side===2||_.doubleSided};if(_.emissive&&(_.emissive.r>0||_.emissive.g>0||_.emissive.b>0)){let z=_.emissiveIntensity??1;B.emissiveFactor=[_.emissive.r*z,_.emissive.g*z,_.emissive.b*z]}let O={};_.clearcoat>0&&(O.KHR_materials_clearcoat={clearcoatFactor:_.clearcoat,clearcoatRoughnessFactor:_.clearcoatRoughness||0}),_.sheen>0&&(O.KHR_materials_sheen={sheenColorFactor:_.sheenColor?[_.sheenColor.r,_.sheenColor.g,_.sheenColor.b]:[1,1,1],sheenRoughnessFactor:_.sheenRoughness||0}),_.transmission>0&&(O.KHR_materials_transmission={transmissionFactor:_.transmission}),_.thickness>0&&(O.KHR_materials_volume={thicknessFactor:_.thickness,attenuationDistance:_.attenuationDistance??1/0,attenuationColor:_.attenuationColor?[_.attenuationColor.r,_.attenuationColor.g,_.attenuationColor.b]:[1,1,1]}),_.ior!==void 0&&_.ior!==1.5&&(O.KHR_materials_ior={ior:_.ior}),_.dispersion>0&&(O.KHR_materials_dispersion={dispersion:_.dispersion}),_.iridescence>0&&(O.KHR_materials_iridescence={iridescenceFactor:_.iridescence,iridescenceIor:_.iridescenceIOR??1.3}),Object.keys(O).length>0&&(B.extensions=O),u.push(B)}V.material=U}let I=a.length;a.push({primitives:[V],name:d.name,...v.extras?{extras:v.extras}:{}}),v.mesh=I}}let F=l.length;if(l.push(v),o.push(d),d.children.length>0){v.children=[];for(let E of d.children)v.children.push(w(E))}return F}for(let d of n.children)g.push(w(d));let 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),C=[];if(typeof T=="function"&&o.length>0){let d=e?.duration??4,v=e?.fps??15,R=Math.max(2,Math.round(d*v)+1),M=new Float32Array(R),D=o.map(I=>({px:I.position.x,py:I.position.y,pz:I.position.z,qx:I.quaternion.x,qy:I.quaternion.y,qz:I.quaternion.z,qw:I.quaternion.w,sx:I.scale.x,sy:I.scale.y,sz:I.scale.z})),F=o.map(()=>new Float32Array(R*3)),E=o.map(()=>new Float32Array(R*4)),S=o.map(()=>new Float32Array(R*3));for(let I=0;I<R;I++){let U=I/(R-1)*d;M[I]=U;try{T(U)}catch{}for(let _=0;_<o.length;_++){let B=o[_];F[_][I*3]=B.position.x,F[_][I*3+1]=B.position.y,F[_][I*3+2]=B.position.z,E[_][I*4]=B.quaternion.x,E[_][I*4+1]=B.quaternion.y,E[_][I*4+2]=B.quaternion.z,E[_][I*4+3]=B.quaternion.w,S[_][I*3]=B.scale.x,S[_][I*3+1]=B.scale.y,S[_][I*3+2]=B.scale.z}}for(let I=0;I<o.length;I++){let U=o[I],_=D[I];U.position.set(_.px,_.py,_.pz),U.quaternion.set(_.qx,_.qy,_.qz,_.qw),U.scale.set(_.sx,_.sy,_.sz)}n.updateMatrixWorld(!0);let k=null,P=()=>(k===null&&(k=f(M,"SCALAR",0,5126,R,[0],[d])),k),X=[],V=[];for(let I=0;I<o.length;I++){let U=D[I],_=!1,B=!1,O=!1;for(let z=0;z<R;z++)(Math.abs(F[I][z*3]-U.px)>1e-4||Math.abs(F[I][z*3+1]-U.py)>1e-4||Math.abs(F[I][z*3+2]-U.pz)>1e-4)&&(_=!0),(Math.abs(E[I][z*4]-U.qx)>1e-4||Math.abs(E[I][z*4+1]-U.qy)>1e-4||Math.abs(E[I][z*4+2]-U.qz)>1e-4||Math.abs(E[I][z*4+3]-U.qw)>1e-4)&&(B=!0),(Math.abs(S[I][z*3]-U.sx)>1e-4||Math.abs(S[I][z*3+1]-U.sy)>1e-4||Math.abs(S[I][z*3+2]-U.sz)>1e-4)&&(O=!0);if(_){let z=f(F[I],"VEC3",0,5126,R),L=X.length;X.push({input:P(),interpolation:"LINEAR",output:z}),V.push({sampler:L,target:{node:I,path:"translation"}})}if(B){let z=f(E[I],"VEC4",0,5126,R),L=X.length;X.push({input:P(),interpolation:"LINEAR",output:z}),V.push({sampler:L,target:{node:I,path:"rotation"}})}if(O){let z=f(S[I],"VEC3",0,5126,R),L=X.length;X.push({input:P(),interpolation:"LINEAR",output:z}),V.push({sampler:L,target:{node:I,path:"scale"}})}}V.length>0&&C.push({name:"ProceduralLoop",samplers:X,channels:V})}let b=pn(l,a,n.userData),x={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:n.environmentIntensity}},scenes:[{nodes:g}],scene:0,nodes:l,meshes:a,materials:u,accessors:s,bufferViews:i,buffers:[{byteLength:r}],...C.length>0?{animations:C}:{},...b||c.size>0?{extensionsUsed:[...b?["KHR_interactivity"]:[],...c]}:{},...b?{extensions:{KHR_interactivity:b}}:{}},p=new Uint8Array(r),A=0;for(let d of t)p.set(d,A),A+=d.byteLength;return{gltf:x,bin:p.buffer,lights:h,environmentIntensity:n.environmentIntensity}}function rt(n){return new TextEncoder().encode(n)}function it(n,e){let{gltf:t,bin:r}=ze(n,e),i=JSON.stringify(t),s=rt(i),a=(4-s.byteLength%4)%4,l=s.byteLength+a,c=20+l+8+r.byteLength,o=new Uint8Array(c),u=new DataView(o.buffer);u.setUint32(0,1179937895,!0),u.setUint32(4,2,!0),u.setUint32(8,c,!0),u.setUint32(12,l,!0),u.setUint32(16,1313821514,!0),o.set(s,20);for(let h=0;h<a;h++)o[20+s.byteLength+h]=32;let m=20+l;return u.setUint32(m,r.byteLength,!0),u.setUint32(m+4,5130562,!0),o.set(new Uint8Array(r),m+8),o}function lr(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),c=r.matrixWorld.elements;for(let d=0;d<a;d++){let v=s.getX(d),R=s.getY(d),M=s.getZ(d);l[d*3]=c[0]*v+c[4]*R+c[8]*M+c[12],l[d*3+1]=c[1]*v+c[5]*R+c[9]*M+c[13],l[d*3+2]=c[2]*v+c[6]*R+c[10]*M+c[14]}let o;if(i.attributes.normal){let d=i.attributes.normal;o=new Float32Array(a*3);let v=new Float32Array(9);be(v,c);for(let R=0;R<a;R++){let M=d.getX(R),D=d.getY(R),F=d.getZ(R),E=v[0]*M+v[3]*D+v[6]*F,S=v[1]*M+v[4]*D+v[7]*F,k=v[2]*M+v[5]*D+v[8]*F,P=Math.hypot(E,S,k)||1;o[R*3]=E/P,o[R*3+1]=S/P,o[R*3+2]=k/P}}let u;if(i.attributes.uv){let d=i.attributes.uv;u=new Float32Array(a*2);for(let v=0;v<a;v++)u[v*2]=d.getX(v),u[v*2+1]=d.getY(v)}let m;if(i.index)m=i.index.array;else{m=a>65535?new Uint32Array(a):new Uint16Array(a);for(let d=0;d<a;d++)m[d]=d}let h="DefaultMaterial",y=[.8,.8,.8],f=.5,g=.1,w=0,T=0,C=1.5,b=1,x=[0,0,0];if(r.material){let d=r.material;h=d.name||`Material_${t.length}`,d.color&&(y=[d.color.r,d.color.g,d.color.b]),typeof d.roughness=="number"&&(f=d.roughness),typeof d.metalness=="number"&&(g=d.metalness),typeof d.clearcoat=="number"&&(w=d.clearcoat),typeof d.clearcoatRoughness=="number"&&(T=d.clearcoatRoughness),typeof d.ior=="number"&&(C=d.ior);let v=typeof d.opacity=="number"?d.opacity:1,R=typeof d.transmission=="number"?d.transmission:0;if(b=v*(1-R),d.emissive&&(d.emissive.r>0||d.emissive.g>0||d.emissive.b>0)){let M=d.emissiveIntensity??1;x=[d.emissive.r*M,d.emissive.g*M,d.emissive.b*M]}}let p,A=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 A=="function"){let d=e?.duration??4,v=e?.fps??4,R=Math.max(2,Math.round(d*v)+1),M=[],D=[],F=[],E=[],S=[r.position.x,r.position.y,r.position.z],k=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],P=[r.scale.x,r.scale.y,r.scale.z],X=!1;for(let V=0;V<R;V++){let I=V/(R-1)*d;M.push(I);try{A(I)}catch{}D.push([r.position.x,r.position.y,r.position.z]),F.push([r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w]),E.push([r.scale.x,r.scale.y,r.scale.z]),(Math.abs(r.position.x-S[0])>1e-4||Math.abs(r.position.y-S[1])>1e-4||Math.abs(r.position.z-S[2])>1e-4||Math.abs(r.quaternion.x-k[0])>1e-4||Math.abs(r.quaternion.y-k[1])>1e-4||Math.abs(r.quaternion.z-k[2])>1e-4||Math.abs(r.quaternion.w-k[3])>1e-4||Math.abs(r.scale.x-P[0])>1e-4)&&(X=!0)}r.position.set(S[0],S[1],S[2]),r.quaternion.set(k[0],k[1],k[2],k[3]),r.scale.set(P[0],P[1],P[2]),X&&(p={times:M,translations:D,rotations:F,scales:E})}t.push({name:r.name||`Mesh_${t.length}`,positions:l,indices:m,normals:o,uvs:u,materialName:h,color:y,roughness:f,metallic:g,clearcoat:w,clearcoatRoughness:T,ior:C,opacity:b,emissiveColor:x,xrTraits:r.userData?.xr,timeSamples:p})}}),t}function Cn(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||[],c=t.meshes||[],o=t.nodes||[];function u(y){let f=s[y];if(!f)throw new Error(`Accessor ${y} not found`);let g=a[f.bufferView||0],w=(g.byteOffset||0)+(f.byteOffset||0),T=g.byteLength||0,C=i.slice(w,w+T);return{acc:f,buffer:C}}let m=new Map;if(o.length>0){let y=tt(t);for(let f=0;f<y.length;f++)m.set(f,y[f])}function h(y,f,g,w){let T=c[y];if(!T)return;let C=new Float32Array(9);be(C,f);for(let b=0;b<(T.primitives||[]).length;b++){let x=T.primitives[b],p=x.attributes?.POSITION;if(p===void 0)continue;let{acc:A,buffer:d}=u(p),v=new Float32Array(d,0,A.count*3),R=new Float32Array(v.length);for(let L=0;L<A.count;L++){let N=v[L*3],H=v[L*3+1],G=v[L*3+2];R[L*3]=f[0]*N+f[4]*H+f[8]*G+f[12],R[L*3+1]=f[1]*N+f[5]*H+f[9]*G+f[13],R[L*3+2]=f[2]*N+f[6]*H+f[10]*G+f[14]}let M,D=x.attributes?.NORMAL;if(D!==void 0){let{acc:L,buffer:N}=u(D),H=new Float32Array(N,0,L.count*3);M=new Float32Array(H.length);for(let G=0;G<L.count;G++){let ae=H[G*3],K=H[G*3+1],ee=H[G*3+2],le=C[0]*ae+C[3]*K+C[6]*ee,se=C[1]*ae+C[4]*K+C[7]*ee,W=C[2]*ae+C[5]*K+C[8]*ee,j=Math.hypot(le,se,W)||1;M[G*3]=le/j,M[G*3+1]=se/j,M[G*3+2]=W/j}}let F,E=x.attributes?.TEXCOORD_0;if(E!==void 0){let{acc:L,buffer:N}=u(E);F=new Float32Array(N,0,L.count*2)}let S;if(x.indices!==void 0){let{acc:L,buffer:N}=u(x.indices);L.componentType===5125?S=new Uint32Array(N,0,L.count):S=new Uint16Array(N,0,L.count);let H=A.count;for(let G of S)if(G>=H)throw new Error(`SecurityError: Index buffer value (${G}) out of vertex bounds [0, ${H}).`)}else{let L=A.count;S=L>65535?new Uint32Array(L):new Uint16Array(L);for(let N=0;N<L;N++)S[N]=N}let k="DefaultMaterial",P=[.8,.8,.8],X=.5,V=.1,I=0,U=0,_=1.5,B=1,O=[0,0,0];if(x.material!==void 0&&l[x.material]){let L=l[x.material];k=L.name||`Material_${x.material}`;let N=L.pbrMetallicRoughness||{},H=1;Array.isArray(N.baseColorFactor)&&(P=[N.baseColorFactor[0],N.baseColorFactor[1],N.baseColorFactor[2]],typeof N.baseColorFactor[3]=="number"&&(H=N.baseColorFactor[3])),typeof N.roughnessFactor=="number"&&(X=N.roughnessFactor),typeof N.metallicFactor=="number"&&(V=N.metallicFactor),Array.isArray(L.emissiveFactor)&&L.emissiveFactor.length>=3&&(O=[L.emissiveFactor[0],L.emissiveFactor[1],L.emissiveFactor[2]]);let G=L.extensions||{};G.KHR_materials_clearcoat&&(I=G.KHR_materials_clearcoat.clearcoatFactor??0,U=G.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),G.KHR_materials_ior&&typeof G.KHR_materials_ior.ior=="number"&&(_=G.KHR_materials_ior.ior);let ae=G.KHR_materials_transmission?.transmissionFactor??0;B=H*(1-ae)}let z=(T.primitives||[]).length>1?`${g}_p${b}`:g;e.push({name:z,positions:R,indices:S,normals:M,uvs:F,materialName:k,color:P,roughness:X,metallic:V,clearcoat:I,clearcoatRoughness:U,ior:_,opacity:B,emissiveColor:O,xrTraits:w?.xr||T.extras?.xr})}}if(o.length>0)for(let y=0;y<o.length;y++){let f=o[y];if(f.mesh!==void 0&&f.mesh<c.length){let g=m.get(y)||J(),w=f.name||c[f.mesh].name||`Node_${y}`;h(f.mesh,g,w,f.extras)}}else{let y=J();for(let f=0;f<c.length;f++){let g=c[f].name||`Mesh_${f}`;h(f,y,g,c[f].extras)}}return e}function _t(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 Tn(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function $(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 _n(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${$(n[r*3])}, ${$(n[r*3+1])}, ${$(n[r*3+2])})`;return t.join(", ")}function hr(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${$(n[r*2])}, ${$(1-n[r*2+1])})`;return t.join(", ")}function mr(n){return Array.from(n).join(", ")}function Ct(n){let e=new Map;for(let c of n){let o=_t(c.materialName,"DefaultMaterial");e.has(o)||e.set(o,{color:c.color||[.8,.8,.8],roughness:c.roughness??.5,metallic:c.metallic??0,clearcoat:c.clearcoat??0,clearcoatRoughness:c.clearcoatRoughness??0,ior:c.ior??1.5,opacity:c.opacity??1,emissiveColor:c.emissiveColor||[0,0,0]})}let t=0,r=null;for(let c of n){if(c.timeSamples&&c.timeSamples.times.length>0){let o=c.timeSamples.times[c.timeSamples.times.length-1];o>t&&(t=o)}c.xrTraits?.anchor&&!r&&(r=c.xrTraits.anchor==="vertical"||c.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
225
- endTimeCode = ${$(t)}
210
+ void main(){fragColor=uColorId;}`;function xn(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 Tt(n,e,t){let r=xn(n,35633,e),i=xn(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 _t(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var vn=["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","uViewportSize","uSectionPlane","uSectionEnabled"];function En(){let n=K().xrDepthShader;return{fs:or.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...vn,...n.uniformNames]:vn}}function ur(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 Mt(n,e,t,r,i,s,a){if(r===void 0||!e.accessors?.[r])return null;let l=e.accessors[r],c=e.bufferViews[l.bufferView],o=(c.byteOffset||0)+(l.byteOffset||0),u=c.byteStride&&c.byteStride>s*4?c.byteStride>>2:s,m;if(u===s)m=new Float32Array(t,o,l.count*s);else{m=new Float32Array(l.count*s);let y=new Float32Array(t,c.byteOffset||0,Math.floor(c.byteLength/4)),f=(l.byteOffset||0)>>2;for(let g=0;g<l.count;g++){let w=f+g*u;for(let T=0;T<s;T++)m[g*s+T]=y[w+T]}}let h=n.createBuffer();return a.push(h),n.bindBuffer(34962,h),n.bufferData(34962,m,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),m}var Mn=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Tn=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function wn(n,e,t=Tn,r){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:i,bin:s}=e,a=[],l=nt(i),c=[];if(Array.isArray(i.nodes))for(let v=0;v<i.nodes.length;v++){let S=i.nodes[v];S.mesh!==void 0&&i.meshes&&i.meshes[S.mesh]&&c.push({node:S,nodeIdx:v,meshIdx:S.mesh})}let o=c.length>0?c:(i.meshes||[]).map((v,S)=>({node:v,nodeIdx:-1,meshIdx:S})),u=[];if(Array.isArray(e.lights)&&e.lights.length>0)u.push(...e.lights);else if(i.extensions?.KHR_lights_punctual?.lights){let v=i.extensions.KHR_lights_punctual.lights;for(let S of v){let M=S.type==="directional"?"directional":S.type==="point"?"point":"ambient";u.push({type:M,color:S.color||[1,1,1],intensity:S.intensity!==void 0?S.intensity:1})}}if(u.length===0&&(u.push({type:"ambient",color:[1,1,1],intensity:.35}),u.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 m=[];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 v=0;v<i.textures.length;v++){let S=i.textures[v],M=i.images[S.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 P=i.bufferViews[M.bufferView],E=s.slice(P.byteOffset||0,(P.byteOffset||0)+P.byteLength),R=new Blob([E],{type:M.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(R).then(U=>{n.bindTexture(3553,L),n.texImage2D(3553,0,6408,6408,5121,U),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(M.uri){let P=ur(M.uri);if(P){let E=new Image;E.crossOrigin="anonymous",E.referrerPolicy="no-referrer",E.onload=()=>{n.bindTexture(3553,L),n.texImage2D(3553,0,6408,6408,5121,E),n.generateMipmap(3553),r?.()},E.src=P}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",M.uri)}m.push(L)}else m.push(null)}}let h=[1/0,1/0,1/0],y=[-1/0,-1/0,-1/0],f=0,g=0;for(let v=0;v<o.length;v++){let S=o[v],M=i.meshes[S.meshIdx],L=S.nodeIdx>=0?l[S.nodeIdx]:J(),P=new Float32Array(9);ye(P,L);let E={name:S.node.name||M.name||`Mesh_${S.meshIdx}`,nodeIndex:S.nodeIdx,transform:L,normalMatrix:P,primitives:[],extras:S.node.extras||M.extras};for(let R of M.primitives||[]){if(R.extensions?.KHR_draco_mesh_compression){let $=ze("draco");$&&$.decodePrimitive(i,R,s)}let U=[],D=n.createVertexArray();n.bindVertexArray(D);let H=i.accessors[R.attributes.POSITION],z=Number(H?.count??0);if(!Number.isFinite(z)||z<0||f+z>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(f+=z,H?.min&&H?.max)for(let $=0;$<3;$++){let oe=L[12+$],ve=L[12+$];for(let Ae=0;Ae<3;Ae++){let qe=L[Ae*4+$]*H.min[Ae],Ye=L[Ae*4+$]*H.max[Ae];oe+=qe<Ye?qe:Ye,ve+=qe>Ye?qe:Ye}oe<h[$]&&(h[$]=oe),ve>y[$]&&(y[$]=ve)}let F=Mt(n,i,s,R.attributes.POSITION,0,3,U);Mt(n,i,s,R.attributes.NORMAL,1,3,U),Mt(n,i,s,R.attributes.TEXCOORD_0,2,2,U);let k=0,_=5123,O=null;if(R.indices!==void 0){let $=i.accessors[R.indices],ve=(i.bufferViews[$.bufferView].byteOffset||0)+($.byteOffset||0);if(k=Number($.count??0),!Number.isFinite(k)||k<0||g+k>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);g+=k,_=$.componentType===5125?5125||5125:5123||5123;let Ae=n.createBuffer();U.push(Ae),n.bindBuffer(34963,Ae),$.componentType===5125?(O=new Uint32Array(s,ve,$.count),n.bufferData(34963,O,35044)):(O=new Uint16Array(s,ve,$.count),n.bufferData(34963,O,35044))}else k=H.count;let B={};for(let $ of Q)if($.onBuildPrimitiveVAO){let oe=$.onBuildPrimitiveVAO(n,D,R,i,s);oe&&(B[$.name]=oe)}n.bindVertexArray(null);let V=i.materials&&R.material!==void 0?i.materials[R.material]:null,N=En(),I=An,X=N.fs,G=!1;for(let $ of Q)if($.onResolveShader){let oe=$.onResolveShader(R,V,I,X);oe&&(I=oe.vs,X=oe.fs,G=!0)}let ie=G?Tt(n,I,X):null,he=ie?_t(n,ie,N.uniforms):null,Y=V?.pbrMetallicRoughness,fe=Y?.baseColorFactor||[.8,.8,.8,1],le=Y?.metallicFactor??.1,se=Y?.roughnessFactor??.5,W=V?.extensions?.KHR_materials_clearcoat,ne=W?W.clearcoatFactor??1:0,Z=Math.max(.04,W?.clearcoatRoughnessFactor??.04),pe=Y?.baseColorTexture!==void 0&&m[Y.baseColorTexture.index]?m[Y.baseColorTexture.index]:null,$e=Y?.metallicRoughnessTexture!==void 0&&m[Y.metallicRoughnessTexture.index]?m[Y.metallicRoughnessTexture.index]:null,me=V?.normalTexture!==void 0&&m[V.normalTexture.index]?m[V.normalTexture.index]:null,re=V?.normalTexture?.scale??1,Re=V?.occlusionTexture!==void 0&&m[V.occlusionTexture.index]?m[V.occlusionTexture.index]:null,de=V?.occlusionTexture?.strength??1,be=!!(V?.extensions?.KHR_materials_transmission||B.materials?.isTransmissive);E.primitives.push({vao:D,indexCount:k,indexType:_,baseColor:fe,metallic:le,roughness:se,clearcoat:ne,clearcoatRoughness:Z,positions:F,indices:O,texture:pe,metallicRoughnessTexture:$e,normalTexture:me,occlusionTexture:Re,normalScale:re,occlusionStrength:de,buffers:U,materialIndex:R.material,pluginData:B,customProgram:ie,customUniforms:he,isTransmissive:be})}a.push(E)}isFinite(h[0])||(h=[-1,-1,-1]),isFinite(y[0])||(y=[1,1,1]);let w=[(h[0]+y[0])/2,(h[1]+y[1])/2,(h[2]+y[2])/2],T=y[0]-h[0],C=y[1]-h[1],b=y[2]-h[2],x=Math.max(Math.hypot(T,C,b)/2,.5),p=[h[0],h[1],h[2]],A=[y[0],y[1],y[2]],d=e.animations;if(!d){for(let v of Q)if(v.onParseGLB?.(e),e.animations){d=e.animations;break}}return d||(d=[]),{meshes:a,bounds:{center:w,radius:x,min:p,max:A},lights:u,animations:d,worldMatrices:l}}var ce=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=J();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=J();this.viewMatrix=J();this.modelMatrix=J();this.mvpMatrix=J();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:J(),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 o=e.querySelector("canvas");o||(o=document.createElement("canvas"),o.style.width="100%",o.style.height="100%",o.style.display="block",o.style.touchAction="none",e.prepend(o)),i=o}this.canvas=i,this.opts=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;let c=En();this.renderProg=Tt(l,An,c.fs),this.pickProg=Tt(l,ar,cr),this.uRender=_t(l,this.renderProg,c.uniforms),this.uPick=_t(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){ir(e,t)}static getDecoder(e){return ze(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}=wn(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 Q)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 c=e.exposure??e.environmentIntensity??e.gltf?.extras?.exposure??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.exposure??e.gltf?.asset?.extras?.environmentIntensity;c!==void 0&&(this.envIntensity=Math.max(0,Number(c))),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(Rn(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Te(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Te(e),{meshes:i}=wn(this.gl,r,Tn,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],ye(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),ye(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],a=[],l=[];for(let c of this.lights){let o=c.color||[1,1,1],u=c.intensity!==void 0?c.intensity:1;if(c.type==="ambient")r=[o[0]*u,o[1]*u,o[2]*u];else if(c.type==="directional"&&i.length<6){let m=c.direction||[.5,1,.8];i.push(m[0],m[1],m[2]),s.push(o[0]*u,o[1]*u,o[2]*u)}else if(c.type==="point"&&a.length<6){let m=c.position||[0,0,0];a.push(m[0],m[1],m[2]),l.push(o[0]*u,o[1]*u,o[2]*u)}}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 Q)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of Q)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(u=>u.primitives.filter(m=>m.materialIndex===r||e.length===1&&m.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,c=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,o={baseColorFactor:a,metallicFactor:l,roughnessFactor:c,setBaseColorFactor:u=>{let m=[u[0],u[1],u[2],u[3]??1];o.baseColorFactor=m,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=m);for(let h of i)h.baseColor=m;this.render()},setMetallicFactor:u=>{o.metallicFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=u);for(let m of i)m.metallic=u;this.render()},setRoughnessFactor:u=>{o.roughnessFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=u);for(let m of i)m.roughness=u;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 Q)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=J();ae(r,this.projMatrix,this.viewMatrix);let[i,s,a]=e,l=t?t[0]:0,c=t?t[1]:0,o=t?t[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*e[0]+u[4]*e[1]+u[8]*e[2]+u[12],s=u[1]*e[0]+u[5]*e[1]+u[9]*e[2]+u[13],a=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]+u[14],t&&(l=u[0]*t[0]+u[4]*t[1]+u[8]*t[2],c=u[1]*t[0]+u[5]*t[1]+u[9]*t[2],o=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]));let m=r[0]*i+r[4]*s+r[8]*a+r[12],h=r[1]*i+r[5]*s+r[9]*a+r[13],y=r[2]*i+r[6]*s+r[10]*a+r[14],f=r[3]*i+r[7]*s+r[11]*a+r[15];if(f<=1e-4)return{x:0,y:0,z:1,visible:!1};let g=m/f,w=h/f,T=y/f,C=this.canvas.getBoundingClientRect(),b=C.width||this.canvas.clientWidth||this.canvas.width||300,x=C.height||this.canvas.clientHeight||this.canvas.height||150,p=(g*.5+.5)*b,A=(-w*.5+.5)*x,d=g>=-1.1&&g<=1.1&&w>=-1.1&&w<=1.1&&T>=-1&&T<=1;if(d&&t){let v=this.customTarget||this.bounds.center,S=v[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),M=v[1]+this.currDistance*Math.sin(this.currPhi),L=v[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),P=[i-S,s-M,a-L];l*P[0]+c*P[1]+o*P[2]>.05&&(d=!1)}return{x:p,y:A,z:T,visible:d}}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]],c=this.customTarget?[...this.customTarget]:[...this.bounds.center],o=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;c[0]+=(-i*a[0]+s*l[0])*o,c[1]+=(-i*a[1]+s*l[1])*o,c[2]+=(-i*a[2]+s*l[2])*o,this.customTarget=c}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),c=i.height>0?Math.floor((t-i.top)*(a/i.height)):Math.floor(t);return this.performMeshPick(l,c,!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);e=this.mapStereoPickX(e,s);let l=J();ae(l,this.projMatrix,this.viewMatrix);let c=[],o=Math.max(0,Math.min(s-1,e)),u=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(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 d=0;d<this.meshes.length;d++){let v=this.meshes[d];if(v.visible===!1||v.isPluginMesh)continue;let S=d+1,M=(S&255)/255,L=(S>>8&255)/255,P=(S>>16&255)/255;i.uniform4f(this.uPick.uColorId,M,L,P,1),ae(this.modelMatrix,this.modelRootMatrix,v.transform),ae(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let E of v.primitives)i.bindVertexArray(E.vao),i.drawElements(4,E.indexCount,E.indexType,0)}let p=new Uint8Array(4);i.readPixels(o,u,1,1,6408,5121,p),i.bindFramebuffer(36160,null);let A=p[0]+(p[1]<<8)+(p[2]<<16);A>0&&A<=this.meshes.length&&(c=[this.meshes[A-1]])}c.length===0&&(c=this.meshes.filter(p=>p.visible!==!1));let m=null,h=1/0,y=[0,0,0],f=[0,1,0],g=this.customTarget||this.bounds.center,w=g[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),T=g[1]+this.currDistance*Math.sin(this.currPhi),C=g[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let p of c){ae(this.modelMatrix,this.modelRootMatrix,p.transform),ae(this.mvpMatrix,l,this.modelMatrix);let A=J();if(!yn(A,this.mvpMatrix))continue;let d=(o+.5)/s*2-1,v=(u+.5)/a*2-1,S=[0,0,0],M=[0,0,0];Et(S,d,v,-1,A),Et(M,d,v,1,A);let L=M[0]-S[0],P=M[1]-S[1],E=M[2]-S[2],R=Math.hypot(L,P,E)||1,U=L/R,D=P/R,H=E/R,z={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((k=>{for(let _ of p.primitives){if(!_.positions)continue;let O=_.positions,B=_.indices,V=Math.floor(B?B.length/3:O.length/9);for(let N=0;N<V;N++){let I=B?B[N*3]:N*3,X=B?B[N*3+1]:N*3+1,G=B?B[N*3+2]:N*3+2;gn(S[0],S[1],S[2],U,D,H,O[I*3],O[I*3+1],O[I*3+2],O[X*3],O[X*3+1],O[X*3+2],O[G*3],O[G*3+1],O[G*3+2],z,k)}}})(1e-4),isFinite(z.distance)){let k=z.point[0],_=z.point[1],O=z.point[2],B=this.modelMatrix,V=B[0]*k+B[4]*_+B[8]*O+B[12],N=B[1]*k+B[5]*_+B[9]*O+B[13],I=B[2]*k+B[6]*_+B[10]*O+B[14],X=V-w,G=N-T,ie=I-C,he=Math.hypot(X,G,ie);if(he<h){ye(this.normalMatrix,this.modelMatrix);let Y=this.normalMatrix,fe=z.normal[0],le=z.normal[1],se=z.normal[2],W=Y[0]*fe+Y[3]*le+Y[6]*se,ne=Y[1]*fe+Y[4]*le+Y[7]*se,Z=Y[2]*fe+Y[5]*le+Y[8]*se,pe=Math.hypot(W,ne,Z)||1;W/=pe,ne/=pe,Z/=pe,W*X+ne*G+Z*ie>0&&(W=-W,ne=-ne,Z=-Z),m=p,h=Math.round(he*1e3)/1e3,y=[Math.round(V*1e3)/1e3,Math.round(N*1e3)/1e3,Math.round(I*1e3)/1e3],f=[Math.round(W*1e3)/1e3,Math.round(ne*1e3)/1e3,Math.round(Z*1e3)/1e3]}}}if(!m)return null;let x={meshIndex:this.meshes.indexOf(m),meshName:m.name,nodeIndex:m.nodeIndex,distance:h,hitPoint:y,normal:f,screenX:e,screenY:t};if(r){for(let p of Q)p.onMeshSelect?.(this,x);this.opts.onMeshClick&&this.opts.onMeshClick(x),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:x}))}return x}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let r=Math.max(1,Math.floor(t*.5)),i=e>=r,s=i?e-r:e,a=i?Math.max(1,t-r):r,l=(s+.5)/a*2-1;return Math.floor((l*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);et(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center,i=r[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),s=r[1]+this.currDistance*Math.sin(this.currPhi),a=r[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);Ie(this.viewMatrix,[i,s,a],r,[0,1,0]),ae(this.mvpMatrix,this.projMatrix,this.viewMatrix),ye(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let r of Q)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of Q)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],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 a of Q)a.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 a of Q)a.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=s;let a={theta:r,phi:i,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(a),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:a}))}}renderXRView(e,t,r,i,s=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let l=e?.transform?.inverse?.matrix||this.viewMatrix,c=e?.projectionMatrix||this.projMatrix,o=e?.transform?.position,u=o?[o.x,o.y,o.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:l,projMatrix:c,eyePos:u,viewport:i,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:s})}render(e){if(!e&&this.stereoSBS){let x=Math.max(2,this.canvas.width||2),p=Math.max(1,this.canvas.height||1),A=Math.max(1,Math.floor(x*.5)),d=Math.max(1,x-A),v=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),S=this.customTarget||this.bounds.center,M=S[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),L=S[1]+this.currDistance*Math.sin(this.currPhi),P=S[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),E=Math.cos(this.currTheta),R=-Math.sin(this.currTheta),U=.032,D=J(),H=J(),z=[M-E*U,L,P-R*U],F=[S[0]-E*U*.25,S[1],S[2]-R*U*.25];et(D,this.fov,A/p,.1,v),Ie(H,z,F,[0,1,0]);let k=J(),_=J(),O=[M+E*U,L,P+R*U],B=[S[0]+E*U*.25,S[1],S[2]+R*U*.25];et(k,this.fov,d/p,.1,v),Ie(_,O,B,[0,1,0]),this.render({viewMatrix:H,projMatrix:D,eyePos:z,viewport:[0,0,A,p],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:_,projMatrix:k,eyePos:O,viewport:[A,0,d,p],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,x,p);return}let t=this.gl,r=0,i=0,s=this.canvas.width,a=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],s=e.viewport[2],a=e.viewport[3],t.viewport(r,i,s,a)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16384|256));let l=J(),c=e?.viewMatrix??this.viewMatrix;ae(l,e?.projMatrix??this.projMatrix,c);let o=K().xrDepthShader,u=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:0,m=this.customTarget||this.bounds.center,h=e?e.eyePos[0]:m[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),y=e?e.eyePos[1]:m[1]+this.currDistance*Math.sin(this.currPhi),f=e?e.eyePos[2]:m[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let x of Q)x.onBeforeDrawScene?.(this,t,l,[h,y,f],u);let g=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&g===0)return;let w=e?.eye||"none",T=!1,C=g>0?[...this.backdropMeshes,...this.meshes]:this.meshes,b=x=>{for(let p=0;p<C.length;p++){let A=C[p];if(A.visible===!1)continue;let d=this.selectedMeshName!==""&&A.name===this.selectedMeshName;p<g||A.worldSpace===!0||A.name==="__xr_reticle__"?this.modelMatrix.set(A.transform):ae(this.modelMatrix,this.modelRootMatrix,A.transform),ae(this.mvpMatrix,l,this.modelMatrix),ye(A.normalMatrix,this.modelMatrix);let v=A.extras?.xr?.stereo||A.userData?.xr?.stereo,S=0,M=0,L=1,P=1;v==="sbs"?(L=.5,S=w==="right"?.5:0):v==="ou"&&(P=.5,M=w==="right"?.5:0);for(let E of A.primitives){let R=!!E.isTransmissive;if(!x&&R){T=!0;continue}if(x&&!R)continue;let U=E.customProgram||this.renderProg,D=E.customUniforms||this.uRender;t.useProgram(U),t.uniform1i(D.uToneMapping,u),t.uniform1f(D.uEnvIntensity,this.envIntensity),t.uniform3f(D.uCameraPos,h,y,f),t.uniform1f(D.uEmissive,d?1:0),t.uniformMatrix4fv(D.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(D.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(D.uNormalMatrix,!1,A.normalMatrix),D.uUvTransform&&t.uniform4f(D.uUvTransform,S,M,L,P),D.uViewportSize&&t.uniform2f(D.uViewportSize,Math.max(1,s),Math.max(1,a)),o?.bind(t,D,this.xrDepthState,c,[r,i,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(D.uEnvironmentMap,4),t.uniform1i(D.uHasEnvironmentMap,1)):t.uniform1i(D.uHasEnvironmentMap,0),this.bindLights(D),D.uSectionEnabled&&t.uniform1i(D.uSectionEnabled,0);for(let H of Q)H.onBeforeDrawPrimitive?.(t,U,E,A,this.worldMatrices||[],this.gltf);t.uniform4fv(D.uBaseColor,E.baseColor),t.uniform1f(D.uMetallic,E.metallic),t.uniform1f(D.uRoughness,E.roughness),D.uClearcoat&&t.uniform2f(D.uClearcoat,E.clearcoat??0,E.clearcoatRoughness??.04),E.texture?(t.activeTexture(33984),t.bindTexture(3553,E.texture),t.uniform1i(D.uBaseColorTexture,0),t.uniform1i(D.uHasTexture,1)):t.uniform1i(D.uHasTexture,0),E.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,E.metallicRoughnessTexture),t.uniform1i(D.uMetallicRoughnessTexture,1),t.uniform1i(D.uHasMetallicRoughnessTexture,1)):t.uniform1i(D.uHasMetallicRoughnessTexture,0),E.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,E.normalTexture),t.uniform1i(D.uNormalTexture,2),t.uniform1i(D.uHasNormalTexture,1),t.uniform1f(D.uNormalScale,E.normalScale)):t.uniform1i(D.uHasNormalTexture,0),E.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,E.occlusionTexture),t.uniform1i(D.uOcclusionTexture,3),t.uniform1i(D.uHasOcclusionTexture,1),t.uniform1f(D.uOcclusionStrength,E.occlusionStrength)):t.uniform1i(D.uHasOcclusionTexture,0),t.bindVertexArray(E.vao),t.drawElements(4,E.indexCount,E.indexType,0)}}};if(b(!1),T){for(let x of Q)x.onBeforeTransmissivePass?.(t,this);b(!0)}for(let x of Q)x.onAfterRender?.(t,this,l)}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 Q)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()}};ce.registerPlugin=Ke,ce.getRegisteredPlugins=dn;function lr(n){return n+3&-4}function hr(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 Ve(n,e){n.updateMatrixWorld(!0);let t=[],r=0,i=[],s=[],a=[],l=[],c=new Set,o=[],u=[],m=new Map,h=[];function y(d,v){let S=new Uint8Array(d.buffer,d.byteOffset,d.byteLength),M=lr(S.byteLength),L=new Uint8Array(M);L.set(S),t.push(L);let P=i.length;return i.push({buffer:0,byteOffset:r,byteLength:S.byteLength,target:v}),r+=M,P}function f(d,v,S,M,L,P,E){let R=y(d,S),U=s.length,D={bufferView:R,byteOffset:0,componentType:M,count:L,type:v};return P&&(D.min=P),E&&(D.max=E),s.push(D),U}n.traverse(d=>{(d.isLight||d.color&&d.intensity!==void 0)&&h.push({type:d.type,color:[d.color.r,d.color.g,d.color.b],intensity:d.intensity,position:[d.position.x,d.position.y,d.position.z]})});let g=[];function w(d){let v={name:d.name||""},S=d.position,M=d.quaternion,L=d.scale;if((S.x||S.y||S.z)&&(v.translation=[S.x,S.y,S.z]),(M.x||M.y||M.z||M.w!==1)&&(v.rotation=[M.x,M.y,M.z,M.w]),(L.x!==1||L.y!==1||L.z!==1)&&(v.scale=[L.x,L.y,L.z]),d.userData&&Object.keys(d.userData).length>0&&(v.extras=JSON.parse(JSON.stringify(d.userData,(E,R)=>{if(!(E==="__proto__"||E==="prototype"||E==="constructor"))return typeof R=="function"?void 0:R})),d.userData.xr)){let E=hr(d.userData.xr);v.extensions={...v.extensions||{},MOZ_hubs_components:E,ANDROID_xr_scenecore:E},K().xrTraitSerializer?.gltfNode(v,d.userData.xr),c.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(d.geometry){let E=d.geometry,R=E.attributes.position;if(R&&R.count>0){let U=[1/0,1/0,1/0],D=[-1/0,-1/0,-1/0];for(let k=0;k<R.count;k++){let _=R.getX(k),O=R.getY(k),B=R.getZ(k);_<U[0]&&(U[0]=_),_>D[0]&&(D[0]=_),O<U[1]&&(U[1]=O),O>D[1]&&(D[1]=O),B<U[2]&&(U[2]=B),B>D[2]&&(D[2]=B)}let z={attributes:{POSITION:f(R.array,"VEC3",34962,5126,R.count,U,D)}};if(E.attributes.normal&&(z.attributes.NORMAL=f(E.attributes.normal.array,"VEC3",34962,5126,E.attributes.normal.count)),E.attributes.uv&&(z.attributes.TEXCOORD_0=f(E.attributes.uv.array,"VEC2",34962,5126,E.attributes.uv.count)),E.index){let k=E.index.array instanceof Uint32Array;z.indices=f(E.index.array,"SCALAR",34963,k?5125:5123,E.index.count)}if(d.material){let k=m.get(d.material);if(k===void 0){k=u.length,m.set(d.material,k);let _=d.material,O={name:_.name||"",pbrMetallicRoughness:{baseColorFactor:[_.color.r,_.color.g,_.color.b,_.opacity],metallicFactor:_.metalness,roughnessFactor:_.roughness},doubleSided:_.side===2||_.doubleSided};if(_.emissive&&(_.emissive.r>0||_.emissive.g>0||_.emissive.b>0)){let V=_.emissiveIntensity??1;O.emissiveFactor=[_.emissive.r*V,_.emissive.g*V,_.emissive.b*V]}let B={};_.clearcoat>0&&(B.KHR_materials_clearcoat={clearcoatFactor:_.clearcoat,clearcoatRoughnessFactor:_.clearcoatRoughness||0}),_.sheen>0&&(B.KHR_materials_sheen={sheenColorFactor:_.sheenColor?[_.sheenColor.r,_.sheenColor.g,_.sheenColor.b]:[1,1,1],sheenRoughnessFactor:_.sheenRoughness||0}),_.transmission>0&&(B.KHR_materials_transmission={transmissionFactor:_.transmission}),_.thickness>0&&(B.KHR_materials_volume={thicknessFactor:_.thickness,attenuationDistance:_.attenuationDistance??1/0,attenuationColor:_.attenuationColor?[_.attenuationColor.r,_.attenuationColor.g,_.attenuationColor.b]:[1,1,1]}),_.ior!==void 0&&_.ior!==1.5&&(B.KHR_materials_ior={ior:_.ior}),_.dispersion>0&&(B.KHR_materials_dispersion={dispersion:_.dispersion}),_.iridescence>0&&(B.KHR_materials_iridescence={iridescenceFactor:_.iridescence,iridescenceIor:_.iridescenceIOR??1.3}),Object.keys(B).length>0&&(O.extensions=B),u.push(O)}z.material=k}let F=a.length;a.push({primitives:[z],name:d.name,...v.extras?{extras:v.extras}:{}}),v.mesh=F}}let P=l.length;if(l.push(v),o.push(d),d.children.length>0){v.children=[];for(let E of d.children)v.children.push(w(E))}return P}for(let d of n.children)g.push(w(d));let 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),C=[];if(typeof T=="function"&&o.length>0){let d=e?.duration??4,v=e?.fps??15,S=Math.max(2,Math.round(d*v)+1),M=new Float32Array(S),L=o.map(F=>({px:F.position.x,py:F.position.y,pz:F.position.z,qx:F.quaternion.x,qy:F.quaternion.y,qz:F.quaternion.z,qw:F.quaternion.w,sx:F.scale.x,sy:F.scale.y,sz:F.scale.z})),P=o.map(()=>new Float32Array(S*3)),E=o.map(()=>new Float32Array(S*4)),R=o.map(()=>new Float32Array(S*3));for(let F=0;F<S;F++){let k=F/(S-1)*d;M[F]=k;try{T(k)}catch{}for(let _=0;_<o.length;_++){let O=o[_];P[_][F*3]=O.position.x,P[_][F*3+1]=O.position.y,P[_][F*3+2]=O.position.z,E[_][F*4]=O.quaternion.x,E[_][F*4+1]=O.quaternion.y,E[_][F*4+2]=O.quaternion.z,E[_][F*4+3]=O.quaternion.w,R[_][F*3]=O.scale.x,R[_][F*3+1]=O.scale.y,R[_][F*3+2]=O.scale.z}}for(let F=0;F<o.length;F++){let k=o[F],_=L[F];k.position.set(_.px,_.py,_.pz),k.quaternion.set(_.qx,_.qy,_.qz,_.qw),k.scale.set(_.sx,_.sy,_.sz)}n.updateMatrixWorld(!0);let U=null,D=()=>(U===null&&(U=f(M,"SCALAR",0,5126,S,[0],[d])),U),H=[],z=[];for(let F=0;F<o.length;F++){let k=L[F],_=!1,O=!1,B=!1;for(let V=0;V<S;V++)(Math.abs(P[F][V*3]-k.px)>1e-4||Math.abs(P[F][V*3+1]-k.py)>1e-4||Math.abs(P[F][V*3+2]-k.pz)>1e-4)&&(_=!0),(Math.abs(E[F][V*4]-k.qx)>1e-4||Math.abs(E[F][V*4+1]-k.qy)>1e-4||Math.abs(E[F][V*4+2]-k.qz)>1e-4||Math.abs(E[F][V*4+3]-k.qw)>1e-4)&&(O=!0),(Math.abs(R[F][V*3]-k.sx)>1e-4||Math.abs(R[F][V*3+1]-k.sy)>1e-4||Math.abs(R[F][V*3+2]-k.sz)>1e-4)&&(B=!0);if(_){let V=f(P[F],"VEC3",0,5126,S),N=H.length;H.push({input:D(),interpolation:"LINEAR",output:V}),z.push({sampler:N,target:{node:F,path:"translation"}})}if(O){let V=f(E[F],"VEC4",0,5126,S),N=H.length;H.push({input:D(),interpolation:"LINEAR",output:V}),z.push({sampler:N,target:{node:F,path:"rotation"}})}if(B){let V=f(R[F],"VEC3",0,5126,S),N=H.length;H.push({input:D(),interpolation:"LINEAR",output:V}),z.push({sampler:N,target:{node:F,path:"scale"}})}}z.length>0&&C.push({name:"ProceduralLoop",samplers:H,channels:z})}let b=bn(l,a,n.userData),x={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:n.environmentIntensity}},scenes:[{nodes:g}],scene:0,nodes:l,meshes:a,materials:u,accessors:s,bufferViews:i,buffers:[{byteLength:r}],...C.length>0?{animations:C}:{},...b||c.size>0?{extensionsUsed:[...b?["KHR_interactivity"]:[],...c]}:{},...b?{extensions:{KHR_interactivity:b}}:{}},p=new Uint8Array(r),A=0;for(let d of t)p.set(d,A),A+=d.byteLength;return{gltf:x,bin:p.buffer,lights:h,environmentIntensity:n.environmentIntensity}}function it(n){return new TextEncoder().encode(n)}function st(n,e){let{gltf:t,bin:r}=Ve(n,e),i=JSON.stringify(t),s=it(i),a=(4-s.byteLength%4)%4,l=s.byteLength+a,c=20+l+8+r.byteLength,o=new Uint8Array(c),u=new DataView(o.buffer);u.setUint32(0,1179937895,!0),u.setUint32(4,2,!0),u.setUint32(8,c,!0),u.setUint32(12,l,!0),u.setUint32(16,1313821514,!0),o.set(s,20);for(let h=0;h<a;h++)o[20+s.byteLength+h]=32;let m=20+l;return u.setUint32(m,r.byteLength,!0),u.setUint32(m+4,5130562,!0),o.set(new Uint8Array(r),m+8),o}function mr(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),c=r.matrixWorld.elements;for(let d=0;d<a;d++){let v=s.getX(d),S=s.getY(d),M=s.getZ(d);l[d*3]=c[0]*v+c[4]*S+c[8]*M+c[12],l[d*3+1]=c[1]*v+c[5]*S+c[9]*M+c[13],l[d*3+2]=c[2]*v+c[6]*S+c[10]*M+c[14]}let o;if(i.attributes.normal){let d=i.attributes.normal;o=new Float32Array(a*3);let v=new Float32Array(9);ye(v,c);for(let S=0;S<a;S++){let M=d.getX(S),L=d.getY(S),P=d.getZ(S),E=v[0]*M+v[3]*L+v[6]*P,R=v[1]*M+v[4]*L+v[7]*P,U=v[2]*M+v[5]*L+v[8]*P,D=Math.hypot(E,R,U)||1;o[S*3]=E/D,o[S*3+1]=R/D,o[S*3+2]=U/D}}let u;if(i.attributes.uv){let d=i.attributes.uv;u=new Float32Array(a*2);for(let v=0;v<a;v++)u[v*2]=d.getX(v),u[v*2+1]=d.getY(v)}let m;if(i.index)m=i.index.array;else{m=a>65535?new Uint32Array(a):new Uint16Array(a);for(let d=0;d<a;d++)m[d]=d}let h="DefaultMaterial",y=[.8,.8,.8],f=.5,g=.1,w=0,T=0,C=1.5,b=1,x=[0,0,0];if(r.material){let d=r.material;h=d.name||`Material_${t.length}`,d.color&&(y=[d.color.r,d.color.g,d.color.b]),typeof d.roughness=="number"&&(f=d.roughness),typeof d.metalness=="number"&&(g=d.metalness),typeof d.clearcoat=="number"&&(w=d.clearcoat),typeof d.clearcoatRoughness=="number"&&(T=d.clearcoatRoughness),typeof d.ior=="number"&&(C=d.ior);let v=typeof d.opacity=="number"?d.opacity:1,S=typeof d.transmission=="number"?d.transmission:0;if(b=v*(1-S),d.emissive&&(d.emissive.r>0||d.emissive.g>0||d.emissive.b>0)){let M=d.emissiveIntensity??1;x=[d.emissive.r*M,d.emissive.g*M,d.emissive.b*M]}}let p,A=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 A=="function"){let d=e?.duration??4,v=e?.fps??4,S=Math.max(2,Math.round(d*v)+1),M=[],L=[],P=[],E=[],R=[r.position.x,r.position.y,r.position.z],U=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],D=[r.scale.x,r.scale.y,r.scale.z],H=!1;for(let z=0;z<S;z++){let F=z/(S-1)*d;M.push(F);try{A(F)}catch{}L.push([r.position.x,r.position.y,r.position.z]),P.push([r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w]),E.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-U[0])>1e-4||Math.abs(r.quaternion.y-U[1])>1e-4||Math.abs(r.quaternion.z-U[2])>1e-4||Math.abs(r.quaternion.w-U[3])>1e-4||Math.abs(r.scale.x-D[0])>1e-4)&&(H=!0)}r.position.set(R[0],R[1],R[2]),r.quaternion.set(U[0],U[1],U[2],U[3]),r.scale.set(D[0],D[1],D[2]),H&&(p={times:M,translations:L,rotations:P,scales:E})}t.push({name:r.name||`Mesh_${t.length}`,positions:l,indices:m,normals:o,uvs:u,materialName:h,color:y,roughness:f,metallic:g,clearcoat:w,clearcoatRoughness:T,ior:C,opacity:b,emissiveColor:x,xrTraits:r.userData?.xr,timeSamples:p})}}),t}function Ln(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||[],c=t.meshes||[],o=t.nodes||[];function u(y){let f=s[y];if(!f)throw new Error(`Accessor ${y} not found`);let g=a[f.bufferView||0],w=(g.byteOffset||0)+(f.byteOffset||0),T=g.byteLength||0,C=i.slice(w,w+T);return{acc:f,buffer:C}}let m=new Map;if(o.length>0){let y=nt(t);for(let f=0;f<y.length;f++)m.set(f,y[f])}function h(y,f,g,w){let T=c[y];if(!T)return;let C=new Float32Array(9);ye(C,f);for(let b=0;b<(T.primitives||[]).length;b++){let x=T.primitives[b],p=x.attributes?.POSITION;if(p===void 0)continue;let{acc:A,buffer:d}=u(p),v=new Float32Array(d,0,A.count*3),S=new Float32Array(v.length);for(let N=0;N<A.count;N++){let I=v[N*3],X=v[N*3+1],G=v[N*3+2];S[N*3]=f[0]*I+f[4]*X+f[8]*G+f[12],S[N*3+1]=f[1]*I+f[5]*X+f[9]*G+f[13],S[N*3+2]=f[2]*I+f[6]*X+f[10]*G+f[14]}let M,L=x.attributes?.NORMAL;if(L!==void 0){let{acc:N,buffer:I}=u(L),X=new Float32Array(I,0,N.count*3);M=new Float32Array(X.length);for(let G=0;G<N.count;G++){let ie=X[G*3],he=X[G*3+1],Y=X[G*3+2],fe=C[0]*ie+C[3]*he+C[6]*Y,le=C[1]*ie+C[4]*he+C[7]*Y,se=C[2]*ie+C[5]*he+C[8]*Y,W=Math.hypot(fe,le,se)||1;M[G*3]=fe/W,M[G*3+1]=le/W,M[G*3+2]=se/W}}let P,E=x.attributes?.TEXCOORD_0;if(E!==void 0){let{acc:N,buffer:I}=u(E);P=new Float32Array(I,0,N.count*2)}let R;if(x.indices!==void 0){let{acc:N,buffer:I}=u(x.indices);N.componentType===5125?R=new Uint32Array(I,0,N.count):R=new Uint16Array(I,0,N.count);let X=A.count;for(let G of R)if(G>=X)throw new Error(`SecurityError: Index buffer value (${G}) out of vertex bounds [0, ${X}).`)}else{let N=A.count;R=N>65535?new Uint32Array(N):new Uint16Array(N);for(let I=0;I<N;I++)R[I]=I}let U="DefaultMaterial",D=[.8,.8,.8],H=.5,z=.1,F=0,k=0,_=1.5,O=1,B=[0,0,0];if(x.material!==void 0&&l[x.material]){let N=l[x.material];U=N.name||`Material_${x.material}`;let I=N.pbrMetallicRoughness||{},X=1;Array.isArray(I.baseColorFactor)&&(D=[I.baseColorFactor[0],I.baseColorFactor[1],I.baseColorFactor[2]],typeof I.baseColorFactor[3]=="number"&&(X=I.baseColorFactor[3])),typeof I.roughnessFactor=="number"&&(H=I.roughnessFactor),typeof I.metallicFactor=="number"&&(z=I.metallicFactor),Array.isArray(N.emissiveFactor)&&N.emissiveFactor.length>=3&&(B=[N.emissiveFactor[0],N.emissiveFactor[1],N.emissiveFactor[2]]);let G=N.extensions||{};G.KHR_materials_clearcoat&&(F=G.KHR_materials_clearcoat.clearcoatFactor??0,k=G.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),G.KHR_materials_ior&&typeof G.KHR_materials_ior.ior=="number"&&(_=G.KHR_materials_ior.ior);let ie=G.KHR_materials_transmission?.transmissionFactor??0;O=X*(1-ie)}let V=(T.primitives||[]).length>1?`${g}_p${b}`:g;e.push({name:V,positions:S,indices:R,normals:M,uvs:P,materialName:U,color:D,roughness:H,metallic:z,clearcoat:F,clearcoatRoughness:k,ior:_,opacity:O,emissiveColor:B,xrTraits:w?.xr||T.extras?.xr})}}if(o.length>0)for(let y=0;y<o.length;y++){let f=o[y];if(f.mesh!==void 0&&f.mesh<c.length){let g=m.get(y)||J(),w=f.name||c[f.mesh].name||`Node_${y}`;h(f.mesh,g,w,f.extras)}}else{let y=J();for(let f=0;f<c.length;f++){let g=c[f].name||`Mesh_${f}`;h(f,y,g,c[f].extras)}}return e}function Ct(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 _n(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function q(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 Cn(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${q(n[r*3])}, ${q(n[r*3+1])}, ${q(n[r*3+2])})`;return t.join(", ")}function dr(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${q(n[r*2])}, ${q(1-n[r*2+1])})`;return t.join(", ")}function fr(n){return Array.from(n).join(", ")}function Lt(n){let e=new Map;for(let c of n){let o=Ct(c.materialName,"DefaultMaterial");e.has(o)||e.set(o,{color:c.color||[.8,.8,.8],roughness:c.roughness??.5,metallic:c.metallic??0,clearcoat:c.clearcoat??0,clearcoatRoughness:c.clearcoatRoughness??0,ior:c.ior??1.5,opacity:c.opacity??1,emissiveColor:c.emissiveColor||[0,0,0]})}let t=0,r=null;for(let c of n){if(c.timeSamples&&c.timeSamples.times.length>0){let o=c.timeSamples.times[c.timeSamples.times.length-1];o>t&&(t=o)}c.xrTraits?.anchor&&!r&&(r=c.xrTraits.anchor==="vertical"||c.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
211
+ endTimeCode = ${q(t)}
226
212
  timeCodesPerSecond = 1.0
227
213
  `);let s="";r&&(s=`uniform token preliminary:anchoring:type = "plane"
228
214
  uniform token preliminary:planeAnchoring:alignment = "${r}"
@@ -239,19 +225,19 @@ kind = "component"
239
225
  {
240
226
  ${s}def Scope "Materials"
241
227
  {
242
- `;for(let[c,o]of e.entries()){let[u,m,h]=o.color,[y,f,g]=o.emissiveColor,w="";o.clearcoat>0&&(w+=`float inputs:clearcoat = ${$(o.clearcoat)}
243
- `,w+=`float inputs:clearcoatRoughness = ${$(o.clearcoatRoughness)}
244
- `),o.ior!==1.5&&(w+=`float inputs:ior = ${$(o.ior)}
245
- `),o.opacity<1&&(w+=`float inputs:opacity = ${$(o.opacity)}
246
- `),(y>0||f>0||g>0)&&(w+=`color3f inputs:emissiveColor = (${$(y)}, ${$(f)}, ${$(g)})
228
+ `;for(let[c,o]of e.entries()){let[u,m,h]=o.color,[y,f,g]=o.emissiveColor,w="";o.clearcoat>0&&(w+=`float inputs:clearcoat = ${q(o.clearcoat)}
229
+ `,w+=`float inputs:clearcoatRoughness = ${q(o.clearcoatRoughness)}
230
+ `),o.ior!==1.5&&(w+=`float inputs:ior = ${q(o.ior)}
231
+ `),o.opacity<1&&(w+=`float inputs:opacity = ${q(o.opacity)}
232
+ `),(y>0||f>0||g>0)&&(w+=`color3f inputs:emissiveColor = (${q(y)}, ${q(f)}, ${q(g)})
247
233
  `),a+=`def Material "${c}"
248
234
  {
249
235
  def Shader "PBRShader"
250
236
  {
251
237
  uniform token info:id = "UsdPreviewSurface"
252
- color3f inputs:diffuseColor = (${$(u)}, ${$(m)}, ${$(h)})
253
- float inputs:metallic = ${$(o.metallic)}
254
- float inputs:roughness = ${$(o.roughness)}
238
+ color3f inputs:diffuseColor = (${q(u)}, ${q(m)}, ${q(h)})
239
+ float inputs:metallic = ${q(o.metallic)}
240
+ float inputs:roughness = ${q(o.roughness)}
255
241
  ${w}token outputs:surface
256
242
  }
257
243
  token outputs:surface.connect = </Root/Materials/${c}/PBRShader.outputs:surface>
@@ -259,7 +245,7 @@ token outputs:surface.connect = </Root/Materials/${c}/PBRShader.outputs:surface>
259
245
  `}a+=`}
260
246
  def Scope "Meshes"
261
247
  {
262
- `;let l=new Set;for(let c=0;c<n.length;c++){let o=n[c],u=o.positions.length/3,m=1/0,h=1/0,y=1/0,f=-1/0,g=-1/0,w=-1/0;for(let d=0;d<u;d++){let v=o.positions[d*3],R=o.positions[d*3+1],M=o.positions[d*3+2];v<m&&(m=v),v>f&&(f=v),R<h&&(h=R),R>g&&(g=R),M<y&&(y=M),M>w&&(w=M)}isFinite(m)||(m=h=y=-1,f=g=w=1);let T=Math.floor(o.indices.length/3),C=_t(o.materialName,"DefaultMaterial"),b=_t(o.name,`Mesh_${c}`);l.has(b)&&(b=`${b}_${c}`),l.add(b);let x=T>0?T===1?"3":"3, ".repeat(T-1)+"3":"",p=o.xrTraits,A="";if(p){let d=[];p.physics&&p.physics!=="none"&&d.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let v=Z().xrTraitSerializer?.usdLines(p,Tn)??[];if(!v.length)for(let R of["grab","billboard","follow","anchor","physics"]){let M=R==="follow"&&typeof p.follow=="object"?p.follow.mode??"head":p[R];M!==void 0&&v.push(`string ${R} = "${Tn(M)}"`)}v.length>0&&d.push(`customData = {
248
+ `;let l=new Set;for(let c=0;c<n.length;c++){let o=n[c],u=o.positions.length/3,m=1/0,h=1/0,y=1/0,f=-1/0,g=-1/0,w=-1/0;for(let d=0;d<u;d++){let v=o.positions[d*3],S=o.positions[d*3+1],M=o.positions[d*3+2];v<m&&(m=v),v>f&&(f=v),S<h&&(h=S),S>g&&(g=S),M<y&&(y=M),M>w&&(w=M)}isFinite(m)||(m=h=y=-1,f=g=w=1);let T=Math.floor(o.indices.length/3),C=Ct(o.materialName,"DefaultMaterial"),b=Ct(o.name,`Mesh_${c}`);l.has(b)&&(b=`${b}_${c}`),l.add(b);let x=T>0?T===1?"3":"3, ".repeat(T-1)+"3":"",p=o.xrTraits,A="";if(p){let d=[];p.physics&&p.physics!=="none"&&d.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let v=K().xrTraitSerializer?.usdLines(p,_n)??[];if(!v.length)for(let S of["grab","billboard","follow","anchor","physics"]){let M=S==="follow"&&typeof p.follow=="object"?p.follow.mode??"head":p[S];M!==void 0&&v.push(`string ${S} = "${_n(M)}"`)}v.length>0&&d.push(`customData = {
263
249
  dictionary xr = {
264
250
  ${v.join(`
265
251
  `)}
@@ -272,28 +258,28 @@ ${d.join(`
272
258
  `,p?.physics&&p.physics!=="none"){let d=p.physics==="static"?"true":"false";a+=`bool physics:rigidBodyEnabled = true
273
259
  bool physics:kinematicEnabled = ${d}
274
260
  bool physics:collisionEnabled = true
275
- `}if(o.timeSamples&&o.timeSamples.times.length>0){let d=o.timeSamples,v=d.times.map((D,F)=>{let E=d.translations?.[F]||[0,0,0];return`${$(D)}: (${$(E[0])}, ${$(E[1])}, ${$(E[2])})`}).join(", "),R=d.times.map((D,F)=>{let E=d.rotations?.[F]||[0,0,0,1];return`${$(D)}: (${$(E[3])}, ${$(E[0])}, ${$(E[1])}, ${$(E[2])})`}).join(", "),M=d.times.map((D,F)=>{let E=d.scales?.[F]||[1,1,1];return`${$(D)}: (${$(E[0])}, ${$(E[1])}, ${$(E[2])})`}).join(", ");a+=`double3 xformOp:translate.timeSamples = { ${v} }
276
- quatf xformOp:orient.timeSamples = { ${R} }
261
+ `}if(o.timeSamples&&o.timeSamples.times.length>0){let d=o.timeSamples,v=d.times.map((L,P)=>{let E=d.translations?.[P]||[0,0,0];return`${q(L)}: (${q(E[0])}, ${q(E[1])}, ${q(E[2])})`}).join(", "),S=d.times.map((L,P)=>{let E=d.rotations?.[P]||[0,0,0,1];return`${q(L)}: (${q(E[3])}, ${q(E[0])}, ${q(E[1])}, ${q(E[2])})`}).join(", "),M=d.times.map((L,P)=>{let E=d.scales?.[P]||[1,1,1];return`${q(L)}: (${q(E[0])}, ${q(E[1])}, ${q(E[2])})`}).join(", ");a+=`double3 xformOp:translate.timeSamples = { ${v} }
262
+ quatf xformOp:orient.timeSamples = { ${S} }
277
263
  double3 xformOp:scale.timeSamples = { ${M} }
278
264
  uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
279
- `}a+=`float3[] extent = [(${$(m)}, ${$(h)}, ${$(y)}), (${$(f)}, ${$(g)}, ${$(w)})]
265
+ `}a+=`float3[] extent = [(${q(m)}, ${q(h)}, ${q(y)}), (${q(f)}, ${q(g)}, ${q(w)})]
280
266
  int[] faceVertexCounts = [${x}]
281
- int[] faceVertexIndices = [${mr(o.indices)}]
282
- point3f[] points = [${_n(o.positions)}]
283
- `,o.normals&&o.normals.length===o.positions.length&&(a+=`normal3f[] normals = [${_n(o.normals)}] (
267
+ int[] faceVertexIndices = [${fr(o.indices)}]
268
+ point3f[] points = [${Cn(o.positions)}]
269
+ `,o.normals&&o.normals.length===o.positions.length&&(a+=`normal3f[] normals = [${Cn(o.normals)}] (
284
270
  interpolation = "vertex"
285
271
  )
286
- `),o.uvs&&o.uvs.length===u*2&&(a+=`texCoord2f[] primvars:st = [${hr(o.uvs,u)}] (
272
+ `),o.uvs&&o.uvs.length===u*2&&(a+=`texCoord2f[] primvars:st = [${dr(o.uvs,u)}] (
287
273
  interpolation = "vertex"
288
274
  )
289
275
  `),a+=`rel material:binding = </Root/Materials/${C}>
290
276
  }
291
277
  `}return a+=`}
292
278
  }
293
- `,a}function Dn(n,e){if(n&&typeof n.traverse=="function"){let i=lr(n,e);return Ct(i)}let t=Me(n),r=Cn(t);return Ct(r)}var nt=null;function Ln(n){if(!nt){nt=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;nt[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=nt[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Dt(n){let e=[],t=0,r=[];for(let u of n){let m=rt(u.filename),h=Ln(u.data),y=u.data.length,f=30+m.length,g=t+f,w=0,T=g%64;T!==0&&(w=64-T);let C=new Uint8Array(f+w),b=new DataView(C.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,h,!0),b.setUint32(18,y,!0),b.setUint32(22,y,!0),b.setUint16(26,m.length,!0),b.setUint16(28,w,!0),C.set(m,30),w>0&&C.fill(0,30+m.length),e.push({offset:t,size:y,crc:h,filenameBytes:m,entry:u}),r.push(C),r.push(u.data),t+=C.length+u.data.length}let i=t;for(let u of e){let m=new Uint8Array(46+u.filenameBytes.length),h=new DataView(m.buffer);h.setUint32(0,33639248,!0),h.setUint16(4,20,!0),h.setUint16(6,20,!0),h.setUint16(8,0,!0),h.setUint16(10,0,!0),h.setUint16(12,0,!0),h.setUint16(14,0,!0),h.setUint32(16,u.crc,!0),h.setUint32(20,u.size,!0),h.setUint32(24,u.size,!0),h.setUint16(28,u.filenameBytes.length,!0),h.setUint16(30,0,!0),h.setUint16(32,0,!0),h.setUint16(34,0,!0),h.setUint16(36,0,!0),h.setUint32(38,0,!0),h.setUint32(42,u.offset,!0),m.set(u.filenameBytes,46),r.push(m),t+=m.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 c=new Uint8Array(t),o=0;for(let u of r)c.set(u,o),o+=u.length;return c}function Xe(n){let e=Dn(n),t=rt(e);return Dt([{filename:"model.usda",data:t}])}function st(n){let e=Me(n),t=Cn(e),r=Ct(t),i=rt(r);return Dt([{filename:"model.usda",data:i}])}function ot(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?Xe(n):st(n)}function He(n){let e=ot(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}var It=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}},te=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,c=t.z;return this.x=i*c-s*l,this.y=s*a-r*c,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}},Ft=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}},ct=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}},ut=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),c=Math.cos(s/2),o=Math.sin(r/2),u=Math.sin(i/2),m=Math.sin(s/2);return this._x=o*l*c+a*u*m,this._y=a*u*c-o*l*m,this._z=a*l*m+o*u*c,this._w=a*l*c-o*u*m,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,c=t.y,o=t.z,u=t.w;return this._x=r*u+a*l+i*o-s*c,this._y=i*u+a*c+s*l-r*o,this._z=s*u+a*o+r*c-i*l,this._w=a*u-r*l-i*c-s*o,this._onChangeCallback?.(),this}_onChange(e){return this._onChangeCallback=e,this}},Fe=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 et(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 de(this.elements,e.elements,t.elements),this}lookAt(e,t,r){return Ie(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 te(0,0,0),r=new te(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}},Ut=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 be(this.elements,e.elements),this}},ve=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)}},dr={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)},Y=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}},kt=class extends Y{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},Nt=class extends Y{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Ot=class extends Y{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},ye=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 Y)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 Y(r,1)}else e&&e.buffer&&(this.index=new Y(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 te,s=new te,a=new te,l=new te,c=new te;if(this.index){let o=this.index.array;for(let u=0;u<o.length;u+=3){let m=o[u],h=o[u+1],y=o[u+2];i.set(e.getX(m),e.getY(m),e.getZ(m)),s.set(e.getX(h),e.getY(h),e.getZ(h)),a.set(e.getX(y),e.getY(y),e.getZ(y)),l.subVectors(a,s),c.subVectors(i,s),l.cross(c).normalize();for(let f of[m,h,y])r[f*3]+=l.x,r[f*3+1]+=l.y,r[f*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),c.subVectors(i,s),l.cross(c).normalize();for(let u=0;u<3;u++)r[(o+u)*3]=l.x,r[(o+u)*3+1]=l.y,r[(o+u)*3+2]=l.z}for(let o=0;o<t;o++){let u=r[o*3],m=r[o*3+1],h=r[o*3+2],y=Math.hypot(u,m,h)||1;r[o*3]=u/y,r[o*3+1]=m/y,r[o*3+2]=h/y}return this.setAttribute("normal",new Y(r,3)),this}setFromBuffers(e,t,r,i){this.setAttribute("position",new Y(e instanceof Float32Array?e:new Float32Array(e),3)),this.setAttribute("normal",new Y(t instanceof Float32Array?t:new Float32Array(t),3)),this.setAttribute("uv",new Y(r instanceof Float32Array?r:new Float32Array(r),2)),this.setIndex(i)}dispose(){}},lt=class extends ye{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],c=[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],u=[];for(let m=0;m<6;m++){let h=m*4;u.push(h,h+1,h+2,h,h+2,h+3)}this.setAttribute("position",new Y(new Float32Array(l),3)),this.setAttribute("normal",new Y(new Float32Array(c),3)),this.setAttribute("uv",new Y(new Float32Array(o),2)),this.setIndex(u)}},Bt=class extends ye{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],c=[0,2,1,2,3,1];this.setAttribute("position",new Y(new Float32Array(s),3)),this.setAttribute("normal",new Y(new Float32Array(a),3)),this.setAttribute("uv",new Y(new Float32Array(l),2)),this.setIndex(c)}},ht=class extends ye{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=[],c=[];for(let o=0;o<=r;o++){let u=[],m=o/r;for(let h=0;h<=t;h++){let y=h/t,f=y*Math.PI*2,g=m*Math.PI,w=-e*Math.cos(f)*Math.sin(g),T=e*Math.cos(g),C=e*Math.sin(f)*Math.sin(g);i.push(w,T,C);let b=Math.hypot(w,T,C)||1;s.push(w/b,T/b,C/b),a.push(y,1-m),u.push(i.length/3-1)}c.push(u)}for(let o=0;o<r;o++)for(let u=0;u<t;u++){let m=c[o][u+1],h=c[o][u],y=c[o+1][u],f=c[o+1][u+1];o!==0&&l.push(m,h,f),o!==r-1&&l.push(h,y,f)}this.setAttribute("position",new Y(new Float32Array(i),3)),this.setAttribute("normal",new Y(new Float32Array(s),3)),this.setAttribute("uv",new Y(new Float32Array(a),2)),this.setIndex(l)}},_e=class extends ye{constructor(e=1,t=1,r=1,i=16){super(),i=Math.max(3,Math.floor(i));let s=[],a=[],l=[],c=[],o=r/2;for(let u=0;u<=1;u++){let m=u,h=u===0?e:t,y=u===0?o:-o;for(let f=0;f<=i;f++){let g=f/i,w=g*Math.PI*2,T=Math.sin(w),C=Math.cos(w);s.push(h*T,y,h*C),a.push(T,0,C),l.push(g,1-m)}}for(let u=0;u<i;u++){let m=u,h=u+i+1,y=u+i+2,f=u+1;c.push(m,h,f,h,y,f)}if(e>0){let u=s.length/3;s.push(0,o,0),a.push(0,1,0),l.push(.5,.5);let m=s.length/3;for(let h=0;h<=i;h++){let y=h/i*Math.PI*2,f=Math.sin(y),g=Math.cos(y);s.push(e*f,o,e*g),a.push(0,1,0),l.push(g*.5+.5,f*.5+.5)}for(let h=0;h<i;h++)c.push(u,m+h,m+h+1)}if(t>0){let u=s.length/3;s.push(0,-o,0),a.push(0,-1,0),l.push(.5,.5);let m=s.length/3;for(let h=0;h<=i;h++){let y=h/i*Math.PI*2,f=Math.sin(y),g=Math.cos(y);s.push(t*f,-o,t*g),a.push(0,-1,0),l.push(g*.5+.5,1-(f*.5+.5))}for(let h=0;h<i;h++)c.push(u,m+h+1,m+h)}this.setAttribute("position",new Y(new Float32Array(s),3)),this.setAttribute("normal",new Y(new Float32Array(a),3)),this.setAttribute("uv",new Y(new Float32Array(l),2)),this.setIndex(c)}},Vt=class extends _e{constructor(e=1,t=1,r=16){super(0,e,t,r)}},zt=class extends ye{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=[],c=[];for(let o=0;o<=r;o++){let u=o/r*Math.PI*2;for(let m=0;m<=i;m++){let h=m/i*Math.PI*2,y=(e+t*Math.cos(u))*Math.cos(h),f=(e+t*Math.cos(u))*Math.sin(h),g=t*Math.sin(u);s.push(y,f,g);let w=e*Math.cos(h),T=e*Math.sin(h),C=y-w,b=f-T,x=g,p=Math.hypot(C,b,x)||1;a.push(C/p,b/p,x/p),l.push(m/i,o/r)}}for(let o=1;o<=r;o++)for(let u=1;u<=i;u++){let m=(i+1)*o+u-1,h=(i+1)*(o-1)+u-1,y=(i+1)*(o-1)+u,f=(i+1)*o+u;c.push(m,h,f,h,y,f)}this.setAttribute("position",new Y(new Float32Array(s),3)),this.setAttribute("normal",new Y(new Float32Array(a),3)),this.setAttribute("uv",new Y(new Float32Array(l),2)),this.setIndex(c)}},Xt=class extends ye{constructor(e=1,t=.4,r=64,i=8,s=2,a=3){super(),r=Math.floor(r),i=Math.floor(i);let l=[],c=[],o=[],u=[],m=new te,h=new te,y=new te,f=new te,g=new te;function w(b,x){let p=Math.cos(x),A=Math.sin(x),d=a/s*x,v=e*(2+Math.cos(d))*.5;b.set(v*p,v*A,e*Math.sin(d)*.5)}let T=[];for(let b=0;b<=i;++b){let x=b/i*Math.PI*2;T.push(-t*Math.cos(x),t*Math.sin(x),b/i)}for(let b=0;b<=r;++b){let x=b/r,p=x*s*Math.PI*2;w(m,p),w(h,p+.01),y.subVectors(h,m).normalize(),f.addVectors(m,h).normalize(),g.crossVectors(y,f).normalize(),f.crossVectors(g,y).normalize();for(let A=0;A<=i;++A){let d=A*3,v=T[d],R=T[d+1],M=T[d+2],D=v*f.x+R*g.x,F=v*f.y+R*g.y,E=v*f.z+R*g.z;l.push(m.x+D,m.y+F,m.z+E);let S=Math.hypot(D,F,E)||1;c.push(D/S,F/S,E/S),o.push(x,M)}}let C=i+1;for(let b=1;b<=r;b++){let x=C*(b-1),p=x+C;for(let A=1;A<=i;A++){let d=x+(A-1),v=p+(A-1),R=p+A,M=x+A;u.push(d,v,M,v,R,M)}}this.setAttribute("position",new Y(new Float32Array(l),3)),this.setAttribute("normal",new Y(new Float32Array(c),3)),this.setAttribute("uv",new Y(new Float32Array(o),2)),this.setIndex(u)}},mt=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(){}},Ht=class{load(e,t){let r=new mt(e);return t?.(r),r}};function ue(n,e){return n!==void 0?Number(n):e}function Lt(n,e){return n!==void 0?!!n:e}var Ee=class{constructor(e={}){this.name=e.name||"",this.color=new ve(e.color!==void 0?e.color:16777215),this.emissive=new ve(e.emissive!==void 0?e.emissive:0),this.emissiveIntensity=ue(e.emissiveIntensity,1),this.roughness=ue(e.roughness,.5),this.metalness=ue(e.metalness,.1),this.opacity=ue(e.opacity,1),this.transparent=Lt(e.transparent,!1),this.wireframe=Lt(e.wireframe,!1),this.side=ue(e.side,2),this.doubleSided=Lt(e.doubleSided,!0),this.map=e.map||null,this.clearcoat=ue(e.clearcoat,0),this.clearcoatRoughness=ue(e.clearcoatRoughness,0),this.sheen=ue(e.sheen,0),this.sheenColor=new ve(e.sheenColor!==void 0?e.sheenColor:0),this.sheenRoughness=ue(e.sheenRoughness,0),this.transmission=ue(e.transmission,0),this.thickness=ue(e.thickness,0),this.attenuationColor=new ve(e.attenuationColor!==void 0?e.attenuationColor:16777215),this.attenuationDistance=ue(e.attenuationDistance,1/0),this.ior=ue(e.ior,1.5),this.dispersion=ue(e.dispersion,0),this.iridescence=ue(e.iridescence,0),this.iridescenceIOR=ue(e.iridescenceIOR,1.3)}dispose(){}},Ue=class extends Ee{},Wt=class extends Ee{},Gt=class extends Ee{},$t=class extends Ee{},qt=class extends Ee{},we=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 te,this.rotation=new ct,this.quaternion=new ut,this.scale=new te(1,1,1),this.matrix=new Fe,this.matrixWorld=new Fe,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 te(e,t,r);this.updateMatrixWorld(!0);let s=new Fe;s.lookAt(this.position,i,new te(0,1,0));let a=s.elements,l=a[0],c=a[4],o=a[8],u=a[1],m=a[5],h=a[9],y=a[2],f=a[6],g=a[10],w=l+m+g;if(w>0){let T=.5/Math.sqrt(w+1);this.quaternion.set((f-h)*T,(o-y)*T,(u-c)*T,.25/T)}}},Yt=class extends we{},Ge=class extends we{constructor(t,r){super();this.isMesh=!0;let i=Array.isArray(r)?r[0]:r;this.geometry=t instanceof ye?t:t?(ge("unsupported geometry","BoxGeometry"),new lt(.5,.5,.5)):new ye,this.material=i instanceof Ee?i:i?(ge("unsupported material","MeshStandardMaterial"),new Ue({color:13421772})):new Ue}},ke=class extends we{constructor(e=16777215,t=1){super(),this.color=new ve(e),this.intensity=Number(t),this.type="directional"}},dt=class extends ke{constructor(e,t){super(e,t),this.type="ambient"}},jt=class extends ke{constructor(t,r){super(t,r);this.target=new we;this.type="directional"}},ft=class extends ke{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}},pt=class extends we{},Kt=class extends pt{constructor(t=45,r=1,i=.1,s=1e3){super();this.target=new te(0,0,0);this.fov=Number(t),this.aspect=Number(r),this.near=Number(i),this.far=Number(s)}},bt=class extends we{constructor(){super(...arguments);this.background=null;this.environmentIntensity=1}toCanvas3D(){return Ae.validate(this),ze(this)}toGLB(){return Ae.validate(this),it(this)}toUSDZ(){return Ae.validate(this),Xe(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let t=new Map,r=0;return this.traverse(i=>{if(i instanceof Ge){let s=new Float32Array(i.matrixWorld.elements);t.set(r,s),i.name&&t.set(i.name,s),r++}}),t}},On=ze,Bn=it,fr=Xe;var Ae=class{static validate(e){let t=0,r=0,i=0,s=new Set,a=(c,o,u)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${c} (${o}). Found: ${u}`)},l=(c,o)=>{if(!Number.isFinite(o))throw new Error(`SecurityError: Scene reports a non-finite ${c} count (${String(o)}), which cannot be bounds-checked.`);return o};e.traverse(c=>{if(c instanceof Ge){i++,i>1e3&&a("MESHES",1e3,i);let o=c.geometry;if(o){let u=0;if(o.attributes.position&&(u=l("vertex",o.attributes.position.count),t+=u,t>1e5&&a("VERTICES",1e5,t)),o.index){let m=l("index",o.index.count);r+=m,r>3e5&&a("INDICES",3e5,r);let h=o.index.array;if(h&&u>0){let y=Math.min(m,h.length);for(let f=0;f<y;f++){let g=h[f];if(!Number.isFinite(g)||g<0||g>=u)throw new Error(`SecurityError: Index buffer value (${String(g)}) out of vertex bounds [0, ${u}).`)}}}}if(c.material){let u=c.material;u.map&&s.add(u.map),u.normalMap&&s.add(u.normalMap),u.roughnessMap&&s.add(u.roughnessMap)}}}),s.size>16&&a("TEXTURES",16,s.size);for(let c of s){let o=c,u=o.image,m=Number(u?.width??o.width??0)||0,h=Number(u?.height??o.height??0)||0;(!Number.isFinite(m)||!Number.isFinite(h)||m>2048||h>2048)&&a("TEXTURE_DIMENSION",2048,Math.max(m,h))}}},Zt=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 ve(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){Ae.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,c]of s.entries())a[l]=Array.from(c);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:a})}else{this.hasInitialModelRendered=!0;let s=On(e),a=Bn(e),l=(s.lights||[]).map(c=>({type:c.type,color:c.color,intensity:c.intensity,position:c.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 Pn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Qt=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=Pn(),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=Pn();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function pr(){}var at=new Proxy(pr,{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:at},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>at,construct:()=>at}),In=(()=>{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 Be(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Ce(n,e){if(!n||typeof n!="string")return!1;let t=n.trim();if(!t)return!1;try{let r=new URL(t,Be());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 Fn,We;function br(n){if(!Ce(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(We===void 0||Fn!==t){Fn=t;try{We=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!Ce(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{We=null}}return We?We.createScriptURL(n):n}function Vn(){let n=Z().sandboxEngineSrc;if(n)return n;if(In)return In;try{if(typeof document>"u")return null;let e=Be(),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)&&Ce(i,{requireSameOrigin:!0}))return i}}catch{}return null}function yr(){let n=Vn();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(!Ce(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,Be()).href}function gr(){let n=Z().sandboxIframeSrc;if(n)return n;let e=Vn();if(!e||!Ce(e))return null;let t=new URL(e,Be());return t.protocol==="blob:"?null:new URL("three-live-sandbox.html",t).href}function xr(){let n=gr();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(!Ce(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,Be()).href}function vr(){return!!Z().allowClientScripts}function wr(n){if(!Ce(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,Be()).href}var Rr=["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 Sr(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 c(p){l({type:"ERROR",nonce:t,message:String(p)})}let o=typeof e.importScripts=="function"?e.importScripts.bind(e):null,u=i,m=null;try{let p=r;if(typeof e.trustedTypes<"u"&&e.trustedTypes&&typeof e.trustedTypes.createPolicy=="function")try{let A={createScriptURL:function(v){if(v!==r&&(!i||v!==i))throw new TypeError("Disallowed worker importScripts URL");return v}};s&&(A.createScript=function(v){return String(v)});let d=e.trustedTypes.createPolicy("three-live#worker-boot",A);p=d.createScriptURL(r),i&&(u=d.createScriptURL(i)),s&&typeof d.createScript=="function"&&(m=d.createScript.bind(d))}catch{}o(p)}catch(p){c('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: '+(p&&p.message||p));return}let h=e.THREE;if(!h||typeof h.Scene!="function"){c('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 p=0;p<a.length;p++){let A=a[p],d=e;for(;d&&d!==Object.prototype;){if(d!==e)try{delete d[A]}catch{}try{Object.defineProperty(d,A,{value:void 0,writable:!1,configurable:!1,enumerable:!1})}catch{}try{d=Object.getPrototypeOf(d)}catch{break}}}let y=Object.freeze({now:function(){return Date.now()}}),f=e;for(;f&&f!==Object.prototype;){if(f!==e)try{delete f.performance}catch{}try{Object.defineProperty(f,"performance",{value:y,writable:!1,configurable:!1,enumerable:!1})}catch{}try{f=Object.getPrototypeOf(f)}catch{break}}let g=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],w=!1;function T(p,A){if(p.type==="3D_MODEL_READY"){if(w)return;w=!0}p.nonce=t,A&&A.length?l(p,A):l(p)}let C=function(p,A){if(!p||g.indexOf(p.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");T(p,A)},b=e;for(;b&&b!==Object.prototype;){if(b===e||Object.prototype.hasOwnProperty.call(b,"postMessage"))try{Object.defineProperty(b,"postMessage",{value:C,writable:!1,configurable:!1})}catch{}try{b=Object.getPrototypeOf(b)}catch{break}}let x=!1;e.onmessage=function(p){let A=p&&p.data;if(!(!A||A.nonce!==t)&&!(A.type!=="EXECUTE"&&A.type!=="EXECUTE_URL")&&!x){x=!0;try{let d=new h.Scene,v=new h.PerspectiveCamera(60,1,.1,1e3),R=new h.WebGLRenderer({isSandboxed:!0});if(A.type==="EXECUTE_URL"){if(!i||A.scriptUrl!==i||typeof o!="function"){c("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let M=u||i,D=o;if(o=null,u=null,e.THREE=h,e.scene=d,e.camera=v,e.renderer=R,D(M),typeof e.__THREE_LIVE_SCENE__=="function"){let F=e.__THREE_LIVE_SCENE__(h,d,v,R);F&&typeof F.toGLB=="function"&&(d=F)}else e.scene&&typeof e.scene.toGLB=="function"&&(d=e.scene)}else{if(!s){c("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let M=m?(0,eval)(m(`(function (THREE, scene, camera, renderer) {
279
+ `,a}function Dn(n,e){if(n&&typeof n.traverse=="function"){let i=mr(n,e);return Lt(i)}let t=Te(n),r=Ln(t);return Lt(r)}var rt=null;function Pn(n){if(!rt){rt=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;rt[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=rt[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Dt(n){let e=[],t=0,r=[];for(let u of n){let m=it(u.filename),h=Pn(u.data),y=u.data.length,f=30+m.length,g=t+f,w=0,T=g%64;T!==0&&(w=64-T);let C=new Uint8Array(f+w),b=new DataView(C.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,h,!0),b.setUint32(18,y,!0),b.setUint32(22,y,!0),b.setUint16(26,m.length,!0),b.setUint16(28,w,!0),C.set(m,30),w>0&&C.fill(0,30+m.length),e.push({offset:t,size:y,crc:h,filenameBytes:m,entry:u}),r.push(C),r.push(u.data),t+=C.length+u.data.length}let i=t;for(let u of e){let m=new Uint8Array(46+u.filenameBytes.length),h=new DataView(m.buffer);h.setUint32(0,33639248,!0),h.setUint16(4,20,!0),h.setUint16(6,20,!0),h.setUint16(8,0,!0),h.setUint16(10,0,!0),h.setUint16(12,0,!0),h.setUint16(14,0,!0),h.setUint32(16,u.crc,!0),h.setUint32(20,u.size,!0),h.setUint32(24,u.size,!0),h.setUint16(28,u.filenameBytes.length,!0),h.setUint16(30,0,!0),h.setUint16(32,0,!0),h.setUint16(34,0,!0),h.setUint16(36,0,!0),h.setUint32(38,0,!0),h.setUint32(42,u.offset,!0),m.set(u.filenameBytes,46),r.push(m),t+=m.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 c=new Uint8Array(t),o=0;for(let u of r)c.set(u,o),o+=u.length;return c}function He(n){let e=Dn(n),t=it(e);return Dt([{filename:"model.usda",data:t}])}function ot(n){let e=Te(n),t=Ln(e),r=Lt(t),i=it(r);return Dt([{filename:"model.usda",data:i}])}function at(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?He(n):ot(n)}function Xe(n){let e=at(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}var Ft=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}},ee=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,c=t.z;return this.x=i*c-s*l,this.y=s*a-r*c,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}},kt=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}},ut=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}},lt=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),c=Math.cos(s/2),o=Math.sin(r/2),u=Math.sin(i/2),m=Math.sin(s/2);return this._x=o*l*c+a*u*m,this._y=a*u*c-o*l*m,this._z=a*l*m+o*u*c,this._w=a*l*c-o*u*m,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,c=t.y,o=t.z,u=t.w;return this._x=r*u+a*l+i*o-s*c,this._y=i*u+a*c+s*l-r*o,this._z=s*u+a*o+r*c-i*l,this._w=a*u-r*l-i*c-s*o,this._onChangeCallback?.(),this}_onChange(e){return this._onChangeCallback=e,this}},Fe=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 tt(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 ae(this.elements,e.elements,t.elements),this}lookAt(e,t,r){return Ie(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 ee(0,0,0),r=new ee(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}},Ut=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[4]=1,e[8]=1,this}getNormalMatrix(e){return ye(this.elements,e.elements),this}},we=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)}},pr={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)},j=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}},Nt=class extends j{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},Ot=class extends j{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Bt=class extends j{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},ge=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 j)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 j(r,1)}else e&&e.buffer&&(this.index=new j(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 ee,s=new ee,a=new ee,l=new ee,c=new ee;if(this.index){let o=this.index.array;for(let u=0;u<o.length;u+=3){let m=o[u],h=o[u+1],y=o[u+2];i.set(e.getX(m),e.getY(m),e.getZ(m)),s.set(e.getX(h),e.getY(h),e.getZ(h)),a.set(e.getX(y),e.getY(y),e.getZ(y)),l.subVectors(a,s),c.subVectors(i,s),l.cross(c).normalize();for(let f of[m,h,y])r[f*3]+=l.x,r[f*3+1]+=l.y,r[f*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),c.subVectors(i,s),l.cross(c).normalize();for(let u=0;u<3;u++)r[(o+u)*3]=l.x,r[(o+u)*3+1]=l.y,r[(o+u)*3+2]=l.z}for(let o=0;o<t;o++){let u=r[o*3],m=r[o*3+1],h=r[o*3+2],y=Math.hypot(u,m,h)||1;r[o*3]=u/y,r[o*3+1]=m/y,r[o*3+2]=h/y}return this.setAttribute("normal",new j(r,3)),this}setFromBuffers(e,t,r,i){this.setAttribute("position",new j(e instanceof Float32Array?e:new Float32Array(e),3)),this.setAttribute("normal",new j(t instanceof Float32Array?t:new Float32Array(t),3)),this.setAttribute("uv",new j(r instanceof Float32Array?r:new Float32Array(r),2)),this.setIndex(i)}dispose(){}},ht=class extends ge{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],c=[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],u=[];for(let m=0;m<6;m++){let h=m*4;u.push(h,h+1,h+2,h,h+2,h+3)}this.setAttribute("position",new j(new Float32Array(l),3)),this.setAttribute("normal",new j(new Float32Array(c),3)),this.setAttribute("uv",new j(new Float32Array(o),2)),this.setIndex(u)}},zt=class extends ge{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],c=[0,2,1,2,3,1];this.setAttribute("position",new j(new Float32Array(s),3)),this.setAttribute("normal",new j(new Float32Array(a),3)),this.setAttribute("uv",new j(new Float32Array(l),2)),this.setIndex(c)}},mt=class extends ge{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=[],c=[];for(let o=0;o<=r;o++){let u=[],m=o/r;for(let h=0;h<=t;h++){let y=h/t,f=y*Math.PI*2,g=m*Math.PI,w=-e*Math.cos(f)*Math.sin(g),T=e*Math.cos(g),C=e*Math.sin(f)*Math.sin(g);i.push(w,T,C);let b=Math.hypot(w,T,C)||1;s.push(w/b,T/b,C/b),a.push(y,1-m),u.push(i.length/3-1)}c.push(u)}for(let o=0;o<r;o++)for(let u=0;u<t;u++){let m=c[o][u+1],h=c[o][u],y=c[o+1][u],f=c[o+1][u+1];o!==0&&l.push(m,h,f),o!==r-1&&l.push(h,y,f)}this.setAttribute("position",new j(new Float32Array(i),3)),this.setAttribute("normal",new j(new Float32Array(s),3)),this.setAttribute("uv",new j(new Float32Array(a),2)),this.setIndex(l)}},Ce=class extends ge{constructor(e=1,t=1,r=1,i=16){super(),i=Math.max(3,Math.floor(i));let s=[],a=[],l=[],c=[],o=r/2;for(let u=0;u<=1;u++){let m=u,h=u===0?e:t,y=u===0?o:-o;for(let f=0;f<=i;f++){let g=f/i,w=g*Math.PI*2,T=Math.sin(w),C=Math.cos(w);s.push(h*T,y,h*C),a.push(T,0,C),l.push(g,1-m)}}for(let u=0;u<i;u++){let m=u,h=u+i+1,y=u+i+2,f=u+1;c.push(m,h,f,h,y,f)}if(e>0){let u=s.length/3;s.push(0,o,0),a.push(0,1,0),l.push(.5,.5);let m=s.length/3;for(let h=0;h<=i;h++){let y=h/i*Math.PI*2,f=Math.sin(y),g=Math.cos(y);s.push(e*f,o,e*g),a.push(0,1,0),l.push(g*.5+.5,f*.5+.5)}for(let h=0;h<i;h++)c.push(u,m+h,m+h+1)}if(t>0){let u=s.length/3;s.push(0,-o,0),a.push(0,-1,0),l.push(.5,.5);let m=s.length/3;for(let h=0;h<=i;h++){let y=h/i*Math.PI*2,f=Math.sin(y),g=Math.cos(y);s.push(t*f,-o,t*g),a.push(0,-1,0),l.push(g*.5+.5,1-(f*.5+.5))}for(let h=0;h<i;h++)c.push(u,m+h+1,m+h)}this.setAttribute("position",new j(new Float32Array(s),3)),this.setAttribute("normal",new j(new Float32Array(a),3)),this.setAttribute("uv",new j(new Float32Array(l),2)),this.setIndex(c)}},Vt=class extends Ce{constructor(e=1,t=1,r=16){super(0,e,t,r)}},Ht=class extends ge{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=[],c=[];for(let o=0;o<=r;o++){let u=o/r*Math.PI*2;for(let m=0;m<=i;m++){let h=m/i*Math.PI*2,y=(e+t*Math.cos(u))*Math.cos(h),f=(e+t*Math.cos(u))*Math.sin(h),g=t*Math.sin(u);s.push(y,f,g);let w=e*Math.cos(h),T=e*Math.sin(h),C=y-w,b=f-T,x=g,p=Math.hypot(C,b,x)||1;a.push(C/p,b/p,x/p),l.push(m/i,o/r)}}for(let o=1;o<=r;o++)for(let u=1;u<=i;u++){let m=(i+1)*o+u-1,h=(i+1)*(o-1)+u-1,y=(i+1)*(o-1)+u,f=(i+1)*o+u;c.push(m,h,f,h,y,f)}this.setAttribute("position",new j(new Float32Array(s),3)),this.setAttribute("normal",new j(new Float32Array(a),3)),this.setAttribute("uv",new j(new Float32Array(l),2)),this.setIndex(c)}},Xt=class extends ge{constructor(e=1,t=.4,r=64,i=8,s=2,a=3){super(),r=Math.floor(r),i=Math.floor(i);let l=[],c=[],o=[],u=[],m=new ee,h=new ee,y=new ee,f=new ee,g=new ee;function w(b,x){let p=Math.cos(x),A=Math.sin(x),d=a/s*x,v=e*(2+Math.cos(d))*.5;b.set(v*p,v*A,e*Math.sin(d)*.5)}let T=[];for(let b=0;b<=i;++b){let x=b/i*Math.PI*2;T.push(-t*Math.cos(x),t*Math.sin(x),b/i)}for(let b=0;b<=r;++b){let x=b/r,p=x*s*Math.PI*2;w(m,p),w(h,p+.01),y.subVectors(h,m).normalize(),f.addVectors(m,h).normalize(),g.crossVectors(y,f).normalize(),f.crossVectors(g,y).normalize();for(let A=0;A<=i;++A){let d=A*3,v=T[d],S=T[d+1],M=T[d+2],L=v*f.x+S*g.x,P=v*f.y+S*g.y,E=v*f.z+S*g.z;l.push(m.x+L,m.y+P,m.z+E);let R=Math.hypot(L,P,E)||1;c.push(L/R,P/R,E/R),o.push(x,M)}}let C=i+1;for(let b=1;b<=r;b++){let x=C*(b-1),p=x+C;for(let A=1;A<=i;A++){let d=x+(A-1),v=p+(A-1),S=p+A,M=x+A;u.push(d,v,M,v,S,M)}}this.setAttribute("position",new j(new Float32Array(l),3)),this.setAttribute("normal",new j(new Float32Array(c),3)),this.setAttribute("uv",new j(new Float32Array(o),2)),this.setIndex(u)}},dt=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(){}},Gt=class{load(e,t){let r=new dt(e);return t?.(r),r}};function ue(n,e){return n!==void 0?Number(n):e}function Pt(n,e){return n!==void 0?!!n:e}var Me=class{constructor(e={}){this.name=e.name||"",this.color=new we(e.color!==void 0?e.color:16777215),this.emissive=new we(e.emissive!==void 0?e.emissive:0),this.emissiveIntensity=ue(e.emissiveIntensity,1),this.roughness=ue(e.roughness,.5),this.metalness=ue(e.metalness,.1),this.opacity=ue(e.opacity,1),this.transparent=Pt(e.transparent,!1),this.wireframe=Pt(e.wireframe,!1),this.side=ue(e.side,2),this.doubleSided=Pt(e.doubleSided,!0),this.map=e.map||null,this.clearcoat=ue(e.clearcoat,0),this.clearcoatRoughness=ue(e.clearcoatRoughness,0),this.sheen=ue(e.sheen,0),this.sheenColor=new we(e.sheenColor!==void 0?e.sheenColor:0),this.sheenRoughness=ue(e.sheenRoughness,0),this.transmission=ue(e.transmission,0),this.thickness=ue(e.thickness,0),this.attenuationColor=new we(e.attenuationColor!==void 0?e.attenuationColor:16777215),this.attenuationDistance=ue(e.attenuationDistance,1/0),this.ior=ue(e.ior,1.5),this.dispersion=ue(e.dispersion,0),this.iridescence=ue(e.iridescence,0),this.iridescenceIOR=ue(e.iridescenceIOR,1.3)}dispose(){}},ke=class extends Me{},Wt=class extends Me{},$t=class extends Me{},qt=class extends Me{},Yt=class extends Me{},Se=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 ee,this.rotation=new ut,this.quaternion=new lt,this.scale=new ee(1,1,1),this.matrix=new Fe,this.matrixWorld=new Fe,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 ee(e,t,r);this.updateMatrixWorld(!0);let s=new Fe;s.lookAt(this.position,i,new ee(0,1,0));let a=s.elements,l=a[0],c=a[4],o=a[8],u=a[1],m=a[5],h=a[9],y=a[2],f=a[6],g=a[10],w=l+m+g;if(w>0){let T=.5/Math.sqrt(w+1);this.quaternion.set((f-h)*T,(o-y)*T,(u-c)*T,.25/T)}}},jt=class extends Se{},We=class extends Se{constructor(t,r){super();this.isMesh=!0;let i=Array.isArray(r)?r[0]:r;this.geometry=t instanceof ge?t:t?(xe("unsupported geometry","BoxGeometry"),new ht(.5,.5,.5)):new ge,this.material=i instanceof Me?i:i?(xe("unsupported material","MeshStandardMaterial"),new ke({color:13421772})):new ke}},Ue=class extends Se{constructor(e=16777215,t=1){super(),this.color=new we(e),this.intensity=Number(t),this.type="directional"}},ft=class extends Ue{constructor(e,t){super(e,t),this.type="ambient"}},Kt=class extends Ue{constructor(t,r){super(t,r);this.target=new Se;this.type="directional"}},pt=class extends Ue{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}},bt=class extends Se{},Zt=class extends bt{constructor(t=45,r=1,i=.1,s=1e3){super();this.target=new ee(0,0,0);this.fov=Number(t),this.aspect=Number(r),this.near=Number(i),this.far=Number(s)}},yt=class extends Se{constructor(){super(...arguments);this.background=null;this.environmentIntensity=1}toCanvas3D(){return Ee.validate(this),Ve(this)}toGLB(){return Ee.validate(this),st(this)}toUSDZ(){return Ee.validate(this),He(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let t=new Map,r=0;return this.traverse(i=>{if(i instanceof We){let s=new Float32Array(i.matrixWorld.elements);t.set(r,s),i.name&&t.set(i.name,s),r++}}),t}},Bn=Ve,zn=st,br=He;var Ee=class{static validate(e){let t=0,r=0,i=0,s=new Set,a=(c,o,u)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${c} (${o}). Found: ${u}`)},l=(c,o)=>{if(!Number.isFinite(o))throw new Error(`SecurityError: Scene reports a non-finite ${c} count (${String(o)}), which cannot be bounds-checked.`);return o};e.traverse(c=>{if(c instanceof We){i++,i>1e3&&a("MESHES",1e3,i);let o=c.geometry;if(o){let u=0;if(o.attributes.position&&(u=l("vertex",o.attributes.position.count),t+=u,t>1e5&&a("VERTICES",1e5,t)),o.index){let m=l("index",o.index.count);r+=m,r>3e5&&a("INDICES",3e5,r);let h=o.index.array;if(h&&u>0){let y=Math.min(m,h.length);for(let f=0;f<y;f++){let g=h[f];if(!Number.isFinite(g)||g<0||g>=u)throw new Error(`SecurityError: Index buffer value (${String(g)}) out of vertex bounds [0, ${u}).`)}}}}if(c.material){let u=c.material;u.map&&s.add(u.map),u.normalMap&&s.add(u.normalMap),u.roughnessMap&&s.add(u.roughnessMap)}}}),s.size>16&&a("TEXTURES",16,s.size);for(let c of s){let o=c,u=o.image,m=Number(u?.width??o.width??0)||0,h=Number(u?.height??o.height??0)||0;(!Number.isFinite(m)||!Number.isFinite(h)||m>2048||h>2048)&&a("TEXTURE_DIMENSION",2048,Math.max(m,h))}}},Qt=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 we(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){Ee.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,c]of s.entries())a[l]=Array.from(c);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:a})}else{this.hasInitialModelRendered=!0;let s=Bn(e),a=zn(e),l=(s.lights||[]).map(c=>({type:c.type,color:c.color,intensity:c.intensity,position:c.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 In(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Jt=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=In(),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=In();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function yr(){}var ct=new Proxy(yr,{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:ct},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>ct,construct:()=>ct}),Fn=(()=>{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 Be(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Le(n,e){if(!n||typeof n!="string")return!1;let t=n.trim();if(!t)return!1;try{let r=new URL(t,Be());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 kn,Ge;function gr(n){if(!Le(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(Ge===void 0||kn!==t){kn=t;try{Ge=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!Le(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{Ge=null}}return Ge?Ge.createScriptURL(n):n}function Vn(){let n=K().sandboxEngineSrc;if(n)return n;if(Fn)return Fn;try{if(typeof document>"u")return null;let e=Be(),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)&&Le(i,{requireSameOrigin:!0}))return i}}catch{}return null}function xr(){let n=Vn();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(!Le(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,Be()).href}function vr(){let n=K().sandboxIframeSrc;if(n)return n;let e=Vn();if(!e||!Le(e))return null;let t=new URL(e,Be());return t.protocol==="blob:"?null:new URL("three-live-sandbox.html",t).href}function wr(){let n=vr();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(!Le(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,Be()).href}function Sr(){return!!K().allowClientScripts}function Rr(n){if(!Le(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,Be()).href}var Ar=["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 Er(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 c(p){l({type:"ERROR",nonce:t,message:String(p)})}let o=typeof e.importScripts=="function"?e.importScripts.bind(e):null,u=i,m=null;try{let p=r;if(typeof e.trustedTypes<"u"&&e.trustedTypes&&typeof e.trustedTypes.createPolicy=="function")try{let A={createScriptURL:function(v){if(v!==r&&(!i||v!==i))throw new TypeError("Disallowed worker importScripts URL");return v}};s&&(A.createScript=function(v){return String(v)});let d=e.trustedTypes.createPolicy("three-live#worker-boot",A);p=d.createScriptURL(r),i&&(u=d.createScriptURL(i)),s&&typeof d.createScript=="function"&&(m=d.createScript.bind(d))}catch{}o(p)}catch(p){c('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: '+(p&&p.message||p));return}let h=e.THREE;if(!h||typeof h.Scene!="function"){c('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 p=0;p<a.length;p++){let A=a[p],d=e;for(;d&&d!==Object.prototype;){if(d!==e)try{delete d[A]}catch{}try{Object.defineProperty(d,A,{value:void 0,writable:!1,configurable:!1,enumerable:!1})}catch{}try{d=Object.getPrototypeOf(d)}catch{break}}}let y=Object.freeze({now:function(){return Date.now()}}),f=e;for(;f&&f!==Object.prototype;){if(f!==e)try{delete f.performance}catch{}try{Object.defineProperty(f,"performance",{value:y,writable:!1,configurable:!1,enumerable:!1})}catch{}try{f=Object.getPrototypeOf(f)}catch{break}}let g=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],w=!1;function T(p,A){if(p.type==="3D_MODEL_READY"){if(w)return;w=!0}p.nonce=t,A&&A.length?l(p,A):l(p)}let C=function(p,A){if(!p||g.indexOf(p.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");T(p,A)},b=e;for(;b&&b!==Object.prototype;){if(b===e||Object.prototype.hasOwnProperty.call(b,"postMessage"))try{Object.defineProperty(b,"postMessage",{value:C,writable:!1,configurable:!1})}catch{}try{b=Object.getPrototypeOf(b)}catch{break}}let x=!1;e.onmessage=function(p){let A=p&&p.data;if(!(!A||A.nonce!==t)&&!(A.type!=="EXECUTE"&&A.type!=="EXECUTE_URL")&&!x){x=!0;try{let d=new h.Scene,v=new h.PerspectiveCamera(60,1,.1,1e3),S=new h.WebGLRenderer({isSandboxed:!0});if(A.type==="EXECUTE_URL"){if(!i||A.scriptUrl!==i||typeof o!="function"){c("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let M=u||i,L=o;if(o=null,u=null,e.THREE=h,e.scene=d,e.camera=v,e.renderer=S,L(M),typeof e.__THREE_LIVE_SCENE__=="function"){let P=e.__THREE_LIVE_SCENE__(h,d,v,S);P&&typeof P.toGLB=="function"&&(d=P)}else e.scene&&typeof e.scene.toGLB=="function"&&(d=e.scene)}else{if(!s){c("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let M=m?(0,eval)(m(`(function (THREE, scene, camera, renderer) {
294
280
  return (function () {
295
281
  `+A.script+`
296
282
  })();
297
283
  })`)):new Function("THREE","scene","camera","renderer",`return (function () {
298
284
  `+A.script+`
299
- })();`);m=null;let D=M(h,d,v,R);D&&typeof D.toGLB=="function"&&(d=D)}if(!w){h.SceneQuotaValidator&&h.SceneQuotaValidator.validate(d);let M=d.toGLB(),D=M instanceof ArrayBuffer?M:M.buffer.slice(M.byteOffset,M.byteOffset+M.byteLength);T({type:"3D_MODEL_READY",glbBuffer:D},[D])}l({type:"DONE",nonce:t})}catch(d){c(d&&d.message||d)}}},l({type:"READY",nonce:t})}function zn(n,e,t){let r=t?.allowedScriptUrl??null,i=t?.allowClientScripts??r===null,s={nonce:e,engineSrc:n,allowedScriptUrl:r,allowClientScripts:i,revoked:Rr};return`'use strict';(${Sr.toString()})(${JSON.stringify(s)});`}function Xn(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 Te=0;function Hn(){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 Ar(n){try{return new TextEncoder().encode(n).length}catch{return n.length}}var Er=1024,Mr=256;function Un(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 Wn(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,Er)};case"3D_UPDATE_TRANSFORMS":{let i=t.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let s of i)if(!Un(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 c of s){if(c.length>Mr||c==="__proto__"||c==="constructor"||c==="prototype")return null;let o=l[c];if(!Un(o))return null;a[c]=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 Tr(n){let e=Ar(n);if(e>1048576)throw new Error(`SecurityError: Script length (${e} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Gn(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 _r(n,e,t,r){let i=Hn(),s=zn(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,Te++;let l=!1,c=!1,o={modelDispatched:!1},u,m=()=>{if(l||c)return;let g=a.contentWindow;!g||typeof g.postMessage!="function"||(c=!0,g.postMessage(n.kind==="url"?{type:"SANDBOX_RUN",nonce:i,workerSource:s,scriptUrl:n.scriptUrl}:{type:"SANDBOX_RUN",nonce:i,workerSource:s,script:n.script},"*"))},h=()=>{},y=g=>{if(l||!a.contentWindow||g.source!==a.contentWindow)return;let w=g.data;if(w&&typeof w=="object"&&w.type==="IFRAME_READY"){m();return}let T=Wn(w,i);T&&Gn(T,r,h,o)};h=()=>{l||(l=!0,u!==void 0&&clearTimeout(u),Te=Math.max(0,Te-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",y),typeof a.remove=="function"?a.remove():a.parentNode&&a.parentNode.removeChild(a))},u=setTimeout(()=>{l||(h(),Xn(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",y),a.onload=()=>{m()},a.onerror=()=>{h(),r.onError?.(new Error(`Sandbox iframe failed to load "${t}". Verify that three-live-sandbox.html is served at that URL.`))};let f=document.body||document.documentElement;if(!f||typeof f.appendChild!="function"){h();let g=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(g),g}return f.appendChild(a),{terminate:h}}function kn(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(Te>=32)return r(`SecurityError: ${Te} 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=yr()}catch(h){let y=h instanceof Error?h.message:String(h);return r(y,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let h;try{h=xr()}catch(y){let f=y instanceof Error?y.message:String(y);return r(f,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(_r(n,i,h,t))}catch(y){return Promise.reject(y)}}let s=Hn(),a=zn(i,s,n.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:n.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),l;try{let h=new Blob([a],{type:"application/javascript"}),y=URL.createObjectURL(h);try{let f=br(y);l=new Worker(f)}finally{URL.revokeObjectURL(y)}}catch(h){let y=h instanceof Error?h.message:String(h);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${y}`,"Security Error: Failed to start Worker sandbox.")}Te++;let c=!1,o={modelDispatched:!1},u,m=()=>{c||(c=!0,u!==void 0&&clearTimeout(u),Te=Math.max(0,Te-1),l.terminate())};return u=setTimeout(()=>{c||(m(),Xn(t))},3e3),l.onmessage=h=>{let y=Wn(h.data,s);y&&Gn(y,t,m,o)},l.onerror=h=>{m(),t.onError?.(new Error(`Worker execution error: ${h.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:m})}function Nn(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 cn={execute(n,e,t,r){let i=(l,c)=>{let o=new Error(l);return t.onError?.(o),c&&t.onToast?.(c),Promise.reject(o)},s=Nn(e,i);if(s)return s;try{Tr(n)}catch(l){let c=l instanceof Error?l.message:String(l);return i(c,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??vr()?kn({kind:"script",script:n},e,t,i):i(Ze,Qe)},executeUrl(n,e,t){let r=(a,l)=>{let c=new Error(a);return t.onError?.(c),l&&t.onToast?.(l),Promise.reject(c)},i=Nn(e,r);if(i)return i;let s;try{s=wr(n)}catch(a){let l=a instanceof Error?a.message:String(a);return r(l,"Security Error: disallowed scene script URL.")}return kn({kind:"url",scriptUrl:s},e,t,r)}},yt=new Set;function ge(n,e){let t=`[three-live] ${n} is unsupported; degraded to ${e}.`;yt.has(t)||(yt.add(t),typeof console<"u"&&typeof console.warn=="function"&&console.warn(t))}function Cr(){return Array.from(yt)}function Dr(){yt.clear()}var gt=class extends Ue{constructor(e={}){ge("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}},Lr=gt,Ne=class extends ht{constructor(e=1,t=0,r="PolyhedronGeometry"){ge(r,"SphereGeometry");let i=Math.max(4,Math.min(32,4<<Math.min(t,3)));super(e,i,i)}},Jt=class extends Ne{constructor(e=1,t=0){super(e,t,"IcosahedronGeometry")}},en=class extends Ne{constructor(e=1,t=0){super(e,t,"OctahedronGeometry")}},tn=class extends Ne{constructor(e=1,t=0){super(e,t,"DodecahedronGeometry")}},nn=class extends Ne{constructor(e=1,t=0){super(e,t,"TetrahedronGeometry")}},rn=class extends _e{constructor(e=1,t=1,r=4,i=8){ge("CapsuleGeometry","CylinderGeometry"),super(e,e,t+e*2,i)}},sn=class extends _e{constructor(e=.5,t=1,r=16){ge("RingGeometry","CylinderGeometry"),super(t,t,.01,Math.max(8,r))}},on=class extends _e{constructor(e=1,t=16){ge("CircleGeometry","CylinderGeometry"),super(e,e,.01,Math.max(8,t))}},an=class extends ft{constructor(t,r,i=0,s=Math.PI/3,a=0,l=2){ge("SpotLight","PointLight");super(t,r,i,l);this.target=new we;this.angle=Math.PI/3;this.penumbra=0;this.angle=s,this.penumbra=a}},xt=class extends dt{constructor(e,t,r){ge("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new ve(t??4473924)}},Pr=xt,$n={Vector2:It,Vector3:te,Vector4:Ft,Euler:ct,Quaternion:ut,Matrix4:Fe,Matrix3:Ut,Color:ve,MathUtils:dr,BufferAttribute:Y,Float32BufferAttribute:kt,Uint16BufferAttribute:Nt,Uint32BufferAttribute:Ot,BufferGeometry:ye,BoxGeometry:lt,PlaneGeometry:Bt,SphereGeometry:ht,CylinderGeometry:_e,ConeGeometry:Vt,TorusGeometry:zt,TorusKnotGeometry:Xt,IcosahedronGeometry:Jt,OctahedronGeometry:en,DodecahedronGeometry:tn,TetrahedronGeometry:nn,CapsuleGeometry:rn,RingGeometry:sn,CircleGeometry:on,Texture:mt,TextureLoader:Ht,Material:Ee,MeshStandardMaterial:Ue,MeshBasicMaterial:Wt,MeshLambertMaterial:Gt,MeshPhongMaterial:$t,MeshPhysicalMaterial:qt,ShaderMaterial:gt,RawShaderMaterial:Lr,Object3D:we,Group:Yt,Mesh:Ge,Light:ke,AmbientLight:dt,DirectionalLight:jt,PointLight:ft,SpotLight:an,HemisphereLight:xt,RectAreaLight:Pr,Camera:pt,PerspectiveCamera:Kt,Scene:bt,WebGLRenderer:Zt,Clock:Qt,SceneQuotaValidator:Ae,exportSceneToCanvas3D:On,exportSceneToGLB:Bn,exportSceneToUSDZ:fr,generateUSDZ:ot,glbToUSDZ:st,sceneToCanvas3D:ze,sceneToGLB:it,sceneToUSDZ:Xe,authorScriptRunner:cn,getAuthorWarnings:Cr,clearAuthorWarnings:Dr};Object.freeze(Ae);Object.freeze(Ae.prototype);Object.freeze(bt.prototype);Object.freeze($n);var vt=new Proxy($n,{get:(n,e)=>e in n?n[e]:(typeof e=="string"&&e!=="then"&&e!=="toJSON"&&!e.startsWith("__")&&ge(`THREE.${e}`,"no-op proxy"),at),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")}}),Pt={name:"three_author",THREE:vt};var Oe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;typeof Oe.THREE>"u"&&(Oe.THREE=vt);typeof Oe.requestAnimationFrame!="function"&&(Oe.requestAnimationFrame=()=>(ge("requestAnimationFrame","single-frame static evaluation"),0));typeof Oe.cancelAnimationFrame!="function"&&(Oe.cancelAnimationFrame=()=>{});if(typeof window<"u"){let n=window;n.ThreeLive=n.ThreeLive||{},n.ThreeLive.THREE=vt,n.ThreeLivePlugins=n.ThreeLivePlugins||{},n.ThreeLivePlugins.threeAuthor=Pt,n.ThreeLivePlugins.three_author=Pt,n.ThreeLivePlugins["three-author"]=Pt}var Ir=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 ne=class ne extends Ir{constructor(){super(...arguments);this.viewer=null;this.canvas=null;this.posterEl=null;this.arButton=null;this.currentModel=null;this.activeXRSession=null;this.toastTimer=null;this.currentModelLimits=void 0;this.isModelLoaded=!1;this.scriptHandle=null;this.resizeObserver=null;this.mutationObserver=null}static get arProvider(){return Z().arProvider}static set arProvider(t){Z().arProvider=t}static get scriptRunner(){return Z().scriptRunner}static set scriptRunner(t){Z().scriptRunner=t}static get sandboxEngineSrc(){return Z().sandboxEngineSrc??null}static set sandboxEngineSrc(t){Z().sandboxEngineSrc=t}static get sandboxIframeSrc(){return Z().sandboxIframeSrc??null}static set sandboxIframeSrc(t){Z().sandboxIframeSrc=t}static get allowClientScripts(){return!!Z().allowClientScripts}static set allowClientScripts(t){Z().allowClientScripts=t}static registerScriptRunner(t){ne.scriptRunner=t}static registerDecoder(t,r){ce.registerDecoder(t,r)}static getDecoder(t){return ce.getDecoder(t)}static registerAR(t){typeof t=="function"?ne.arProvider={activateAR:t}:ne.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof ne&&i.updateARButtonVisibility()})}static isARSupported(){return!!ne.arProvider}getLoadedModel(){return this.currentModel}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 ce.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of ce.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.activeXRSession&&(this.activeXRSession.stop?.().catch?.(()=>{}),this.activeXRSession=null),this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=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 ce.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")||(Z().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttribute("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||ne.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 ne.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,[c,o,u]=i.normal;return{position:{x:s,y:a,z:l,toString(){return`${s}m ${a}m ${l}m`}},normal:{x:c,y:o,z:u,toString(){return`${c}m ${o}m ${u}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"){this.isModelLoaded=!1,this.viewer?.clearScene?.();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=Me(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=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=t,this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),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)"),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){if(this.activeXRSession&&typeof this.activeXRSession.isSessionActive=="function"&&this.activeXRSession.isSessionActive()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null),!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,6e3),i}if(!ne.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,6e3),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 ne.arProvider.activateAR({model:t||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"not-presenting"}}))},onError:s=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:s}})),this.showToast(`AR error: ${s.message}`,6e3)}}});if(i.success)i.session&&(this.activeXRSession=i.session),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{let s=typeof navigator<"u"&&navigator.userAgent||"",a=/Macintosh/i.test(s)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),l=/Android|iPhone|iPad|iPod/i.test(s);if(a&&!l&&typeof document<"u"&&this.currentModel&&ne.arProvider.createUSDZBlob)try{let c=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:ne.arProvider.createUSDZBlob(this.currentModel),o=URL.createObjectURL(c),u=document.createElement("a");u.href=o,u.download="three_live_model.usdz",document.body.appendChild(u),u.click(),document.body.removeChild(u),setTimeout(()=>URL.revokeObjectURL(o),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3)}else this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3);i.error&&this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i.error}}))}return i}catch(i){throw this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(`AR error: ${i.message||String(i)}`,6e3),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 ce(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 u of ce.getRegisteredPlugins())u.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 c=this.getAttribute("camera-orbit");c&&this.applyCameraOrbit(c),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 c=document.createElementNS(r,"line");c.setAttribute("x1","12"),c.setAttribute("y1","22.08"),c.setAttribute("x2","12"),c.setAttribute("y2","12"),s.appendChild(a),s.appendChild(l),s.appendChild(c),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")&&!!ne.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=c=>c.endsWith("rad")?parseFloat(c)*180/Math.PI:parseFloat(c.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 ce.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}async loadModelFromSrc(t){await this.loadModel(t)}runWithScriptRunner(t){let r=ne.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),this.isModelLoaded=!1,this.viewer?.clearScene?.(),new Promise((i,s)=>{let a=!1;t(r,{onModelReady:c=>{this.loadModelWithLimits(c,En).then(()=>{a||(a=!0,i(c))},o=>{let u=o instanceof Error?o.message:String(o);this.showToast(u),a||(a=!0,s(o))})},onUpdateTransforms:c=>this.viewer?.updateMeshTransforms(c),onError:c=>{this.showToast(c.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:c}})),a||(a=!0,s(c))},onToast:c=>this.showToast(c)}).then(c=>{c&&(this.scriptHandle=c)},c=>{c instanceof Error&&c.message&&this.showToast(c.message),a||(a=!0,s(c))})})}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(!ne.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Ze);return this.showToast(Qe),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}))}};ne.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"],ne.registerPlugin=ce.registerPlugin,ne.getRegisteredPlugins=ce.getRegisteredPlugins;var De=ne;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",De);function jn(){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 Kn(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function Zn(){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 Fr(){return(await ln()).bestMode}async function ln(){let[n,e,t]=await Promise.all([Zn(),Promise.resolve(jn()),Promise.resolve(Kn())]),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 qn(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=Ur(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=wt(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 wt(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 Ur(n){try{return wt(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function kr(n,e={}){let t=wt(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",wt(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 Nr(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=kr(n,e);window.location.href=t}var Le=null;function Or(n,e){let r=new Float32Array(144),i=new Float32Array(24*6),s=new Float32Array(24*4),a=new Uint16Array(24*6);for(let m=0;m<24;m++){let h=m/24*Math.PI*2,y=Math.cos(h),f=Math.sin(h),g=m*2,w=g+1,T=(m+1)%24*2;r[g*3]=y*.11,r[g*3+1]=.002,r[g*3+2]=f*.11,r[w*3]=y*.145,r[w*3+1]=.002,r[w*3+2]=f*.145,i[g*3+1]=i[w*3+1]=1,a.set([g,T,w,w,T,T+1],m*6)}let l=n.createVertexArray();n.bindVertexArray(l);let c=(m,h,y)=>{let f=n.createBuffer();return n.bindBuffer(34962,f),n.bufferData(34962,m,35044),n.enableVertexAttribArray(h),n.vertexAttribPointer(h,y,5126,!1,0,0),f},o=[c(r,0,3),c(i,1,3),c(s,2,2)],u=n.createBuffer();return o.push(u),n.bindBuffer(34963,u),n.bufferData(34963,a,35044),n.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:l,indexCount:a.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:a,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:o}]}}function Yn(n,e,t,r,i){let s=Math.cos(r),a=Math.sin(r),l=Math.max(.01,i);n.fill(0),n[0]=l*s,n[2]=-l*a,n[5]=l,n[8]=l*a,n[10]=l*s,n[12]=e[0]-l*(s*t[0]+a*t[2]),n[13]=e[1]-l*t[1],n[14]=e[2]-l*(-a*t[0]+s*t[2]),n[15]=1}var un=class{constructor(e={}){this.s=null;this.placed=!1;this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);this.cleanFn=null;this.opts=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");Le&&Le!==this&&Le.isSessionActive()&&await Le.stop().catch(()=>{});let r=navigator.xr,i=this.opts,s=t||e?.container,a=String(s?.tagName||"").toLowerCase()==="xr-live",l=e?.bounds,c=Number(l?.radius)||1,o=Array.isArray(l?.center)?l.center:[0,0,0],u=Array.isArray(l?.min)?l.min:[-.5,-.5,-.5],m=typeof navigator<"u"&&navigator.userAgent||"",h=/Android|iPhone|iPad|iPod/i.test(m)&&!/Quest|Oculus|Pico|Vision/i.test(m),y=a?i.arScale==="fixed"?1:h?.55:1:i.arScale==="fixed"?1:c>.45?.3/c:c<.05?.12/Math.max(c,.001):1,f=a?[0,-.25,0]:[o[0]||0,i.arPlacement==="wall"?o[1]:u[1]??0,o[2]||0],g="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(g="immersive-vr")}catch{g="immersive-vr"}let w=s?.querySelector?.('[slot="ar-overlay"]')||null,T=!1,C=null,b=()=>{T&&w?.parentNode&&w.parentNode.removeChild(w),w=null,C=null,T=!1};if(g==="immersive-ar"){if(w)w.addEventListener?.("beforexrselect",L=>L.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let L=document.createElement("div");L.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let N=document.createElement("button");N.type="button",N.textContent="\u2715 Exit AR",N.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",N.addEventListener("beforexrselect",H=>H.preventDefault()),N.addEventListener("click",H=>{H.stopPropagation(),this.stop().catch(()=>{})}),C=document.createElement("div"),C.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",C.textContent="Move phone to detect a surface \u2022 Tap to place",L.appendChild(N),L.appendChild(C),document.body.appendChild(L),w=L,T=!0}}let x=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),p={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(x)};w&&(x.add("dom-overlay"),p.optionalFeatures=Array.from(x),p.domOverlay={root:w});for(let L of Q)L.onConfigureXRSessionInit?.(s,p);Array.isArray(p.optionalFeatures)&&p.optionalFeatures.includes("dom-overlay")&&!p.domOverlay?.root&&(p.optionalFeatures=p.optionalFeatures.filter(L=>L!=="dom-overlay"));let A=L=>{let N=String(L?.name||"");return N==="NotAllowedError"||N==="SecurityError"};try{this.s=await r.requestSession(g,p)}catch(L){if(b(),A(L))throw i.onError?.(L),L;try{this.s=await r.requestSession(g,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(N){if(A(N))throw i.onError?.(N),N;try{this.s=await r.requestSession(g)}catch(H){throw i.onError?.(H),H}}}let d=this.s;Le=this,this.placed=!1;let v=null,R=null,M=null,D=null,F=null,E=[0,-.25,-1.2],S=[0,-.25,-1.2],k=new Float32Array(16),P=!1,X=1,V=0,I=!1,U=null,_=null,B=0,O=null,z=()=>{Le===this&&(Le=null),O?.(),O=null;try{R?.cancel?.()}catch{}if(R=null,M){let L=e?.meshes;if(Array.isArray(L)){let H=L.indexOf(M);H!==-1&&L.splice(H,1)}let N=e.getGLContext?.()||e?.gl;if(N)for(let H of M.primitives||[]){N.deleteVertexArray?.(H.vao);for(let G of H.buffers||[])N.deleteBuffer?.(G)}M=null}e?.setXRSessionActive?.(!1),b(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=z,d.addEventListener("end",()=>{z(),i.onExit?.()}),d.addEventListener("select",()=>{if(!this.placed){let L=F||E;S=[L[0],L[1],L[2]],Yn(this.placedMat,S,f,V,y*X),this.placed=!0,M&&(M.visible=!1),C&&(C.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let L=e.getGLContext?.()||e?.gl;L&&typeof L.makeXRCompatible=="function"&&await L.makeXRCompatible();let N=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;L&&typeof N=="function"&&typeof d.updateRenderState=="function"&&d.updateRenderState({baseLayer:new N(d,L,{alpha:!0})});try{v=await d.requestReferenceSpace("local")}catch{try{v=await d.requestReferenceSpace("local-floor")}catch{v=await d.requestReferenceSpace("viewer")}}let H=await d.requestReferenceSpace("viewer").catch(()=>v);if(typeof d.requestHitTestSource=="function"&&H&&(R=await d.requestHitTestSource({space:H}).catch(()=>null)),g==="immersive-ar"&&L&&typeof L.createVertexArray=="function"&&Array.isArray(e.meshes)&&(M=Or(L,i.reticleColor),e.meshes.push(M)),typeof window<"u"&&typeof window.addEventListener=="function"){let ae=W=>Math.hypot(W.touches[1].clientX-W.touches[0].clientX,W.touches[1].clientY-W.touches[0].clientY),K=W=>Math.atan2(W.touches[1].clientY-W.touches[0].clientY,W.touches[1].clientX-W.touches[0].clientX),ee=W=>{this.s&&(W.touches.length===1&&this.placed?I=!0:W.touches.length>=2&&(I=!1,U=ae(W),_=K(W)))},le=W=>{if(!this.s||W.touches.length<2)return;let j=ae(W),fe=K(W);if(U&&U>4&&i.arScale!=="fixed"&&(X=Math.max(.15,Math.min(6,X*(j/U)))),_!==null){let oe=fe-_;oe>Math.PI&&(oe-=Math.PI*2),oe<-Math.PI&&(oe+=Math.PI*2),V-=oe}U=j,_=fe},se=W=>{(!W.touches||W.touches.length===0)&&(I=!1),(!W.touches||W.touches.length<2)&&(U=null,_=null)};window.addEventListener("touchstart",ee,{passive:!0}),window.addEventListener("touchmove",le,{passive:!0}),window.addEventListener("touchend",se,{passive:!0}),window.addEventListener("touchcancel",se,{passive:!0}),O=()=>{window.removeEventListener("touchstart",ee),window.removeEventListener("touchmove",le),window.removeEventListener("touchend",se),window.removeEventListener("touchcancel",se)}}e.setXRSessionActive?.(!0);let G=(ae,K)=>{if(this.s!==d)return;d.requestAnimationFrame(G);let ee=B>0?Math.min(Math.max((ae-B)/1e3,0),.1):1/60;B=ae,e?.stepXRUpdate?.(ee);let le=K.getViewerPose(v);if(!le)return;let se=le.views?.[0];if(!P&&se?.transform){let re=se.transform.position,ie=se.transform.matrix,Re=re?.x??(ie?ie[12]:0),me=re?.y??(ie?ie[13]:0),pe=re?.z??(ie?ie[14]:0),xe=ie?-ie[8]:0,q=ie?-ie[10]:-1,he=Math.hypot(xe,q);he>1e-4?(xe/=he,q/=he):(xe=0,q=-1),E=[Re+xe*1.2,me-.25,pe+q*1.2],V=Math.atan2(-xe,-q),P=!0}if(R&&typeof K.getHitTestResults=="function"&&(!this.placed||I)){let re=K.getHitTestResults(R)||[],ie=!1;for(let Re of re){let me=Re.getPose(v);if(me?.transform?.matrix){let pe=me.transform.matrix,xe=pe[5];if(i.arPlacement==="wall"&&Math.abs(xe)>.35||i.arPlacement==="floor"&&Math.abs(xe)<.65)continue;D||(D=new Float32Array(16)),D.set(pe),F=[pe[12],pe[13],pe[14]],this.placed&&I&&(S=[pe[12],pe[13],pe[14]]),M&&(M.visible=!this.placed||I,M.transform.set(pe)),!this.placed&&C&&(C.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(D),ie=!0;break}}!ie&&M&&(M.visible=!1)}Yn(k,this.placed?S:F||E,f,V,y*X),this.placed&&this.placedMat.set(k),e.modelRootMatrix&&e.modelRootMatrix.set(k);for(let re of Q)re.onXRFrame?.(e,d,K,v);let W=e.getGLContext?.()||e?.gl,j=d.renderState?.baseLayer;W&&j&&j.framebuffer!==void 0&&W.bindFramebuffer(36160,j.framebuffer);let fe=g==="immersive-ar",oe=le.views||[];for(let re=0;re<oe.length;re++){let ie=oe[re];if(typeof e.renderXRView=="function"){let Re;if(j&&typeof j.getViewport=="function"){let me=j.getViewport(ie);me&&me.width>0&&me.height>0&&(Re=[me.x,me.y,me.width,me.height])}else j?.framebufferWidth>0&&j?.framebufferHeight>0&&(Re=[0,0,j.framebufferWidth,j.framebufferHeight]);e.renderXRView(ie,k,this.placed,Re,fe,re)}}W&&j&&j.framebuffer&&W.bindFramebuffer(36160,null)};d.requestAnimationFrame(G)}catch(L){throw typeof d.end=="function"&&await d.end().catch(()=>{}),z(),i.onError?.(L),L}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function hn(n){let e=await ln(),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,arScale:n.arScale||n.webXROptions?.arScale,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 qn(n.model,i),{mode:"quick-look",success:!0};l=He(n.model)}return qn(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 Nr(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 un(a);return await l.start(n.view,n.element),{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}`)}}De.registerAR({activateAR:hn,createUSDZBlob:He});De.registerScriptRunner(cn);je(fn);export{vt as THREE,De as ThreeLiveElement,ce as ThreeView,hn as activateAR,He as createUSDZBlob,ln as getARCapabilities,Fr as getBestARMode,jn as isQuickLookSupported,Kn as isSceneViewerSupported,Zn as isWebXRSupported,Me as toGLBData};
285
+ })();`);m=null;let L=M(h,d,v,S);L&&typeof L.toGLB=="function"&&(d=L)}if(!w){h.SceneQuotaValidator&&h.SceneQuotaValidator.validate(d);let M=d.toGLB(),L=M instanceof ArrayBuffer?M:M.buffer.slice(M.byteOffset,M.byteOffset+M.byteLength);T({type:"3D_MODEL_READY",glbBuffer:L},[L])}l({type:"DONE",nonce:t})}catch(d){c(d&&d.message||d)}}},l({type:"READY",nonce:t})}function Hn(n,e,t){let r=t?.allowedScriptUrl??null,i=t?.allowClientScripts??r===null,s={nonce:e,engineSrc:n,allowedScriptUrl:r,allowClientScripts:i,revoked:Ar};return`'use strict';(${Er.toString()})(${JSON.stringify(s)});`}function Xn(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 _e=0;function Gn(){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 Mr(n){try{return new TextEncoder().encode(n).length}catch{return n.length}}var Tr=1024,_r=256;function Un(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 Wn(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,Tr)};case"3D_UPDATE_TRANSFORMS":{let i=t.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let s of i)if(!Un(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 c of s){if(c.length>_r||c==="__proto__"||c==="constructor"||c==="prototype")return null;let o=l[c];if(!Un(o))return null;a[c]=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 Cr(n){let e=Mr(n);if(e>1048576)throw new Error(`SecurityError: Script length (${e} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function $n(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 Lr(n,e,t,r){let i=Gn(),s=Hn(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,_e++;let l=!1,c=!1,o={modelDispatched:!1},u,m=()=>{if(l||c)return;let g=a.contentWindow;!g||typeof g.postMessage!="function"||(c=!0,g.postMessage(n.kind==="url"?{type:"SANDBOX_RUN",nonce:i,workerSource:s,scriptUrl:n.scriptUrl}:{type:"SANDBOX_RUN",nonce:i,workerSource:s,script:n.script},"*"))},h=()=>{},y=g=>{if(l||!a.contentWindow||g.source!==a.contentWindow)return;let w=g.data;if(w&&typeof w=="object"&&w.type==="IFRAME_READY"){m();return}let T=Wn(w,i);T&&$n(T,r,h,o)};h=()=>{l||(l=!0,u!==void 0&&clearTimeout(u),_e=Math.max(0,_e-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",y),typeof a.remove=="function"?a.remove():a.parentNode&&a.parentNode.removeChild(a))},u=setTimeout(()=>{l||(h(),Xn(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",y),a.onload=()=>{m()},a.onerror=()=>{h(),r.onError?.(new Error(`Sandbox iframe failed to load "${t}". Verify that three-live-sandbox.html is served at that URL.`))};let f=document.body||document.documentElement;if(!f||typeof f.appendChild!="function"){h();let g=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(g),g}return f.appendChild(a),{terminate:h}}function Nn(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(_e>=32)return r(`SecurityError: ${_e} 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=xr()}catch(h){let y=h instanceof Error?h.message:String(h);return r(y,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let h;try{h=wr()}catch(y){let f=y instanceof Error?y.message:String(y);return r(f,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Lr(n,i,h,t))}catch(y){return Promise.reject(y)}}let s=Gn(),a=Hn(i,s,n.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:n.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),l;try{let h=new Blob([a],{type:"application/javascript"}),y=URL.createObjectURL(h);try{let f=gr(y);l=new Worker(f)}finally{URL.revokeObjectURL(y)}}catch(h){let y=h instanceof Error?h.message:String(h);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${y}`,"Security Error: Failed to start Worker sandbox.")}_e++;let c=!1,o={modelDispatched:!1},u,m=()=>{c||(c=!0,u!==void 0&&clearTimeout(u),_e=Math.max(0,_e-1),l.terminate())};return u=setTimeout(()=>{c||(m(),Xn(t))},3e3),l.onmessage=h=>{let y=Wn(h.data,s);y&&$n(y,t,m,o)},l.onerror=h=>{m(),t.onError?.(new Error(`Worker execution error: ${h.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:m})}function On(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 un={execute(n,e,t,r){let i=(l,c)=>{let o=new Error(l);return t.onError?.(o),c&&t.onToast?.(c),Promise.reject(o)},s=On(e,i);if(s)return s;try{Cr(n)}catch(l){let c=l instanceof Error?l.message:String(l);return i(c,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??Sr()?Nn({kind:"script",script:n},e,t,i):i(Qe,Je)},executeUrl(n,e,t){let r=(a,l)=>{let c=new Error(a);return t.onError?.(c),l&&t.onToast?.(l),Promise.reject(c)},i=On(e,r);if(i)return i;let s;try{s=Rr(n)}catch(a){let l=a instanceof Error?a.message:String(a);return r(l,"Security Error: disallowed scene script URL.")}return Nn({kind:"url",scriptUrl:s},e,t,r)}},gt=new Set;function xe(n,e){let t=`[three-live] ${n} is unsupported; degraded to ${e}.`;gt.has(t)||(gt.add(t),typeof console<"u"&&typeof console.warn=="function"&&console.warn(t))}function Dr(){return Array.from(gt)}function Pr(){gt.clear()}var xt=class extends ke{constructor(e={}){xe("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}},Ir=xt,Ne=class extends mt{constructor(e=1,t=0,r="PolyhedronGeometry"){xe(r,"SphereGeometry");let i=Math.max(4,Math.min(32,4<<Math.min(t,3)));super(e,i,i)}},en=class extends Ne{constructor(e=1,t=0){super(e,t,"IcosahedronGeometry")}},tn=class extends Ne{constructor(e=1,t=0){super(e,t,"OctahedronGeometry")}},nn=class extends Ne{constructor(e=1,t=0){super(e,t,"DodecahedronGeometry")}},rn=class extends Ne{constructor(e=1,t=0){super(e,t,"TetrahedronGeometry")}},sn=class extends Ce{constructor(e=1,t=1,r=4,i=8){xe("CapsuleGeometry","CylinderGeometry"),super(e,e,t+e*2,i)}},on=class extends Ce{constructor(e=.5,t=1,r=16){xe("RingGeometry","CylinderGeometry"),super(t,t,.01,Math.max(8,r))}},an=class extends Ce{constructor(e=1,t=16){xe("CircleGeometry","CylinderGeometry"),super(e,e,.01,Math.max(8,t))}},cn=class extends pt{constructor(t,r,i=0,s=Math.PI/3,a=0,l=2){xe("SpotLight","PointLight");super(t,r,i,l);this.target=new Se;this.angle=Math.PI/3;this.penumbra=0;this.angle=s,this.penumbra=a}},vt=class extends ft{constructor(e,t,r){xe("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new we(t??4473924)}},Fr=vt,qn={Vector2:Ft,Vector3:ee,Vector4:kt,Euler:ut,Quaternion:lt,Matrix4:Fe,Matrix3:Ut,Color:we,MathUtils:pr,BufferAttribute:j,Float32BufferAttribute:Nt,Uint16BufferAttribute:Ot,Uint32BufferAttribute:Bt,BufferGeometry:ge,BoxGeometry:ht,PlaneGeometry:zt,SphereGeometry:mt,CylinderGeometry:Ce,ConeGeometry:Vt,TorusGeometry:Ht,TorusKnotGeometry:Xt,IcosahedronGeometry:en,OctahedronGeometry:tn,DodecahedronGeometry:nn,TetrahedronGeometry:rn,CapsuleGeometry:sn,RingGeometry:on,CircleGeometry:an,Texture:dt,TextureLoader:Gt,Material:Me,MeshStandardMaterial:ke,MeshBasicMaterial:Wt,MeshLambertMaterial:$t,MeshPhongMaterial:qt,MeshPhysicalMaterial:Yt,ShaderMaterial:xt,RawShaderMaterial:Ir,Object3D:Se,Group:jt,Mesh:We,Light:Ue,AmbientLight:ft,DirectionalLight:Kt,PointLight:pt,SpotLight:cn,HemisphereLight:vt,RectAreaLight:Fr,Camera:bt,PerspectiveCamera:Zt,Scene:yt,WebGLRenderer:Qt,Clock:Jt,SceneQuotaValidator:Ee,exportSceneToCanvas3D:Bn,exportSceneToGLB:zn,exportSceneToUSDZ:br,generateUSDZ:at,glbToUSDZ:ot,sceneToCanvas3D:Ve,sceneToGLB:st,sceneToUSDZ:He,authorScriptRunner:un,getAuthorWarnings:Dr,clearAuthorWarnings:Pr};Object.freeze(Ee);Object.freeze(Ee.prototype);Object.freeze(yt.prototype);Object.freeze(qn);var wt=new Proxy(qn,{get:(n,e)=>e in n?n[e]:(typeof e=="string"&&e!=="then"&&e!=="toJSON"&&!e.startsWith("__")&&xe(`THREE.${e}`,"no-op proxy"),ct),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")}}),It={name:"three_author",THREE:wt};var Oe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;typeof Oe.THREE>"u"&&(Oe.THREE=wt);typeof Oe.requestAnimationFrame!="function"&&(Oe.requestAnimationFrame=()=>(xe("requestAnimationFrame","single-frame static evaluation"),0));typeof Oe.cancelAnimationFrame!="function"&&(Oe.cancelAnimationFrame=()=>{});if(typeof window<"u"){let n=window;n.ThreeLive=n.ThreeLive||{},n.ThreeLive.THREE=wt,n.ThreeLivePlugins=n.ThreeLivePlugins||{},n.ThreeLivePlugins.threeAuthor=It,n.ThreeLivePlugins.three_author=It,n.ThreeLivePlugins["three-author"]=It}var kr=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 te=class te extends kr{constructor(){super(...arguments);this.viewer=null;this.canvas=null;this.posterEl=null;this.arButton=null;this.currentModel=null;this.activeXRSession=null;this.toastTimer=null;this.currentModelLimits=void 0;this.isModelLoaded=!1;this.scriptHandle=null;this.resizeObserver=null;this.mutationObserver=null}static get arProvider(){return K().arProvider}static set arProvider(t){K().arProvider=t}static get scriptRunner(){return K().scriptRunner}static set scriptRunner(t){K().scriptRunner=t}static get sandboxEngineSrc(){return K().sandboxEngineSrc??null}static set sandboxEngineSrc(t){K().sandboxEngineSrc=t}static get sandboxIframeSrc(){return K().sandboxIframeSrc??null}static set sandboxIframeSrc(t){K().sandboxIframeSrc=t}static get allowClientScripts(){return!!K().allowClientScripts}static set allowClientScripts(t){K().allowClientScripts=t}static registerScriptRunner(t){te.scriptRunner=t}static registerDecoder(t,r){ce.registerDecoder(t,r)}static getDecoder(t){return ce.getDecoder(t)}static registerAR(t){typeof t=="function"?te.arProvider={activateAR:t}:te.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof te&&i.updateARButtonVisibility()})}static isARSupported(){return!!te.arProvider}getLoadedModel(){return this.currentModel}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 ce.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of ce.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.activeXRSession&&(this.activeXRSession.stop?.().catch?.(()=>{}),this.activeXRSession=null),this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=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 ce.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")||(K().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttribute("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||te.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 te.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,[c,o,u]=i.normal;return{position:{x:s,y:a,z:l,toString(){return`${s}m ${a}m ${l}m`}},normal:{x:c,y:o,z:u,toString(){return`${c}m ${o}m ${u}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"){this.isModelLoaded=!1,this.viewer?.clearScene?.();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=Te(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=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=t,this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),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)"),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){if(this.activeXRSession&&typeof this.activeXRSession.isSessionActive=="function"&&this.activeXRSession.isSessionActive()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null),!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,6e3),i}if(!te.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,6e3),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 te.arProvider.activateAR({model:t||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"not-presenting"}}))},onError:s=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:s}})),this.showToast(`AR error: ${s.message}`,6e3)}}});if(i.success)i.session&&(this.activeXRSession=i.session),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{let s=typeof navigator<"u"&&navigator.userAgent||"",a=/Macintosh/i.test(s)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),l=/Android|iPhone|iPad|iPod/i.test(s);if(a&&!l&&typeof document<"u"&&this.currentModel&&te.arProvider.createUSDZBlob)try{let c=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:te.arProvider.createUSDZBlob(this.currentModel),o=URL.createObjectURL(c),u=document.createElement("a");u.href=o,u.download="three_live_model.usdz",document.body.appendChild(u),u.click(),document.body.removeChild(u),setTimeout(()=>URL.revokeObjectURL(o),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3)}else this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3);i.error&&this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i.error}}))}return i}catch(i){throw this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(`AR error: ${i.message||String(i)}`,6e3),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 ce(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 u of ce.getRegisteredPlugins())u.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 c=this.getAttribute("camera-orbit");c&&this.applyCameraOrbit(c),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 c=document.createElementNS(r,"line");c.setAttribute("x1","12"),c.setAttribute("y1","22.08"),c.setAttribute("x2","12"),c.setAttribute("y2","12"),s.appendChild(a),s.appendChild(l),s.appendChild(c),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")&&!!te.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=c=>c.endsWith("rad")?parseFloat(c)*180/Math.PI:parseFloat(c.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 ce.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}async loadModelFromSrc(t){await this.loadModel(t)}runWithScriptRunner(t){let r=te.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),this.isModelLoaded=!1,this.viewer?.clearScene?.(),new Promise((i,s)=>{let a=!1;t(r,{onModelReady:c=>{this.loadModelWithLimits(c,Mn).then(()=>{a||(a=!0,i(c))},o=>{let u=o instanceof Error?o.message:String(o);this.showToast(u),a||(a=!0,s(o))})},onUpdateTransforms:c=>this.viewer?.updateMeshTransforms(c),onError:c=>{this.showToast(c.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:c}})),a||(a=!0,s(c))},onToast:c=>this.showToast(c)}).then(c=>{c&&(this.scriptHandle=c)},c=>{c instanceof Error&&c.message&&this.showToast(c.message),a||(a=!0,s(c))})})}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(!te.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Qe);return this.showToast(Je),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}))}};te.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"],te.registerPlugin=ce.registerPlugin,te.getRegisteredPlugins=ce.getRegisteredPlugins;var De=te;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",De);function Kn(){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 Zn(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function Qn(){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 Ur(){return(await hn()).bestMode}async function hn(){let[n,e,t]=await Promise.all([Qn(),Promise.resolve(Kn()),Promise.resolve(Zn())]),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 Yn(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=Nr(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=St(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 St(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 Nr(n){try{return St(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function Or(n,e={}){let t=St(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",St(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 Br(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=Or(n,e);window.location.href=t}var Pe=null;function zr(n,e){let r=new Float32Array(144),i=new Float32Array(24*6),s=new Float32Array(24*4),a=new Uint16Array(24*6);for(let m=0;m<24;m++){let h=m/24*Math.PI*2,y=Math.cos(h),f=Math.sin(h),g=m*2,w=g+1,T=(m+1)%24*2;r[g*3]=y*.11,r[g*3+1]=.002,r[g*3+2]=f*.11,r[w*3]=y*.145,r[w*3+1]=.002,r[w*3+2]=f*.145,i[g*3+1]=i[w*3+1]=1,a.set([g,T,w,w,T,T+1],m*6)}let l=n.createVertexArray();n.bindVertexArray(l);let c=(m,h,y)=>{let f=n.createBuffer();return n.bindBuffer(34962,f),n.bufferData(34962,m,35044),n.enableVertexAttribArray(h),n.vertexAttribPointer(h,y,5126,!1,0,0),f},o=[c(r,0,3),c(i,1,3),c(s,2,2)],u=n.createBuffer();return o.push(u),n.bindBuffer(34963,u),n.bufferData(34963,a,35044),n.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:l,indexCount:a.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:r,indices:a,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:o}]}}function jn(n,e,t,r,i){let s=Math.cos(r),a=Math.sin(r),l=Math.max(.01,i);n.fill(0),n[0]=l*s,n[2]=-l*a,n[5]=l,n[8]=l*a,n[10]=l*s,n[12]=e[0]-l*(s*t[0]+a*t[2]),n[13]=e[1]-l*t[1],n[14]=e[2]-l*(-a*t[0]+s*t[2]),n[15]=1}var ln=class{constructor(e={}){this.s=null;this.placed=!1;this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);this.cleanFn=null;this.opts=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");Pe&&Pe!==this&&Pe.isSessionActive()&&await Pe.stop().catch(()=>{});let r=navigator.xr,i=this.opts,s=t||e?.container,a=String(s?.tagName||"").toLowerCase()==="xr-live",l=e?.bounds,c=Number(l?.radius)||1,o=Array.isArray(l?.center)?l.center:[0,0,0],u=Array.isArray(l?.min)?l.min:[-.5,-.5,-.5],m=typeof navigator<"u"&&navigator.userAgent||"",h=/Android|iPhone|iPad|iPod/i.test(m)&&!/Quest|Oculus|Pico|Vision/i.test(m),y=a?i.arScale==="fixed"?1:h?.55:1:i.arScale==="fixed"?1:c>.45?.3/c:c<.05?.12/Math.max(c,.001):1,f=a?[0,-.25,0]:[o[0]||0,i.arPlacement==="wall"?o[1]:u[1]??0,o[2]||0],g="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(g="immersive-vr")}catch{g="immersive-vr"}let w=s?.querySelector?.('[slot="ar-overlay"]')||null,T=!1,C=null,b=()=>{T&&w?.parentNode&&w.parentNode.removeChild(w),w=null,C=null,T=!1};if(g==="immersive-ar"){if(w)w.addEventListener?.("beforexrselect",I=>I.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let I=document.createElement("div");I.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let X=document.createElement("button");X.type="button",X.textContent="\u2715 Exit AR",X.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",X.addEventListener("beforexrselect",G=>G.preventDefault()),X.addEventListener("click",G=>{G.stopPropagation(),this.stop().catch(()=>{})}),C=document.createElement("div"),C.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",C.textContent="Move phone to detect a surface \u2022 Tap to place",I.appendChild(X),I.appendChild(C),document.body.appendChild(I),w=I,T=!0}}let x=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),p={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(x)};w&&(x.add("dom-overlay"),p.optionalFeatures=Array.from(x),p.domOverlay={root:w});for(let I of Q)I.onConfigureXRSessionInit?.(s,p);Array.isArray(p.optionalFeatures)&&p.optionalFeatures.includes("dom-overlay")&&!p.domOverlay?.root&&(p.optionalFeatures=p.optionalFeatures.filter(I=>I!=="dom-overlay"));let A=I=>{let X=String(I?.name||"");return X==="NotAllowedError"||X==="SecurityError"};try{this.s=await r.requestSession(g,p)}catch(I){if(b(),A(I))throw i.onError?.(I),I;try{this.s=await r.requestSession(g,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(X){if(A(X))throw i.onError?.(X),X;try{this.s=await r.requestSession(g)}catch(G){throw i.onError?.(G),G}}}let d=this.s;Pe=this,this.placed=!1;let v=null,S=null,M=null,L=null,P=null,E=[0,-.25,-1.2],R=[0,-.25,-1.2],U=new Float32Array(16),D=new Float32Array(16),H=!1,z=1,F=0,k=!1,_=null,O=null,B=0,V=null,N=()=>{Pe===this&&(Pe=null),V?.(),V=null;try{S?.cancel?.()}catch{}if(S=null,M){let I=e?.meshes;if(Array.isArray(I)){let G=I.indexOf(M);G!==-1&&I.splice(G,1)}let X=e.getGLContext?.()||e?.gl;if(X)for(let G of M.primitives||[]){X.deleteVertexArray?.(G.vao);for(let ie of G.buffers||[])X.deleteBuffer?.(ie)}M=null}e?.setXRSessionActive?.(!1),b(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=N,d.addEventListener("end",()=>{N(),i.onExit?.()}),d.addEventListener("select",()=>{if(!this.placed){let I=P||E;R=[I[0],I[1],I[2]],jn(this.placedMat,R,f,F,y*z),this.placed=!0,M&&(M.visible=!1),C&&(C.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let I=e.getGLContext?.()||e?.gl;I&&typeof I.makeXRCompatible=="function"&&await I.makeXRCompatible();let X=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;I&&typeof X=="function"&&typeof d.updateRenderState=="function"&&d.updateRenderState({baseLayer:new X(d,I,{alpha:!0})});try{v=await d.requestReferenceSpace("local")}catch{try{v=await d.requestReferenceSpace("local-floor")}catch{v=await d.requestReferenceSpace("viewer")}}let G=await d.requestReferenceSpace("viewer").catch(()=>v);if(typeof d.requestHitTestSource=="function"&&G&&(S=await d.requestHitTestSource({space:G}).catch(()=>null)),g==="immersive-ar"&&I&&typeof I.createVertexArray=="function"&&Array.isArray(e.meshes)&&(M=zr(I,i.reticleColor),e.meshes.push(M)),typeof window<"u"&&typeof window.addEventListener=="function"){let he=W=>Math.hypot(W.touches[1].clientX-W.touches[0].clientX,W.touches[1].clientY-W.touches[0].clientY),Y=W=>Math.atan2(W.touches[1].clientY-W.touches[0].clientY,W.touches[1].clientX-W.touches[0].clientX),fe=W=>{this.s&&(W.touches.length===1&&this.placed?k=!0:W.touches.length>=2&&(k=!1,_=he(W),O=Y(W)))},le=W=>{if(!this.s||W.touches.length<2)return;let ne=he(W),Z=Y(W);if(_&&_>4&&i.arScale!=="fixed"&&(z=Math.max(.15,Math.min(6,z*(ne/_)))),O!==null){let pe=Z-O;pe>Math.PI&&(pe-=Math.PI*2),pe<-Math.PI&&(pe+=Math.PI*2),F-=pe}_=ne,O=Z},se=W=>{(!W.touches||W.touches.length===0)&&(k=!1),(!W.touches||W.touches.length<2)&&(_=null,O=null)};window.addEventListener("touchstart",fe,{passive:!0}),window.addEventListener("touchmove",le,{passive:!0}),window.addEventListener("touchend",se,{passive:!0}),window.addEventListener("touchcancel",se,{passive:!0}),V=()=>{window.removeEventListener("touchstart",fe),window.removeEventListener("touchmove",le),window.removeEventListener("touchend",se),window.removeEventListener("touchcancel",se)}}e.setXRSessionActive?.(!0);let ie=(he,Y)=>{if(this.s!==d)return;d.requestAnimationFrame(ie);let fe=B>0?Math.min(Math.max((he-B)/1e3,0),.1):1/60;B=he,e?.stepXRUpdate?.(fe);let le=Y.getViewerPose(v);if(!le)return;let se=le.views?.[0];if(!H&&se?.transform){let me=se.transform.position,re=se.transform.matrix,Re=me?.x??(re?re[12]:0),de=me?.y??(re?re[13]:0),be=me?.z??(re?re[14]:0),$=re?-re[8]:0,oe=re?-re[10]:-1,ve=Math.hypot($,oe);ve>1e-4?($/=ve,oe/=ve):($=0,oe=-1),E=[Re+$*1.2,de-.25,be+oe*1.2],F=Math.atan2(-$,-oe),H=!0}if(S&&typeof Y.getHitTestResults=="function"&&(!this.placed||k)){let me=Y.getHitTestResults(S)||[],re=!1;for(let Re of me){let de=Re.getPose(v);if(de?.transform?.matrix){let be=de.transform.matrix,$=be[5];if(i.arPlacement==="wall"&&Math.abs($)>.35||i.arPlacement==="floor"&&Math.abs($)<.65)continue;L||(L=new Float32Array(16)),L.set(be),P=[be[12],be[13],be[14]],this.placed&&k&&(R=[be[12],be[13],be[14]]),M&&(M.visible=!this.placed||k,M.transform.set(be)),!this.placed&&C&&(C.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(L),re=!0;break}}!re&&M&&(M.visible=!1)}jn(U,this.placed?R:P||E,f,F,y*z),this.placed&&this.placedMat.set(U);let W=e.xrRigMatrix;W instanceof Float32Array&&W.length===16?ae(D,W,U):D.set(U),e.modelRootMatrix&&e.modelRootMatrix.set(D);for(let me of Q)me.onXRFrame?.(e,d,Y,v);let ne=e.getGLContext?.()||e?.gl,Z=d.renderState?.baseLayer;ne&&Z&&Z.framebuffer!==void 0&&ne.bindFramebuffer(36160,Z.framebuffer);let pe=g==="immersive-ar",$e=le.views||[];for(let me=0;me<$e.length;me++){let re=$e[me];if(typeof e.renderXRView=="function"){let Re;if(Z&&typeof Z.getViewport=="function"){let de=Z.getViewport(re);de&&de.width>0&&de.height>0&&(Re=[de.x,de.y,de.width,de.height])}else Z?.framebufferWidth>0&&Z?.framebufferHeight>0&&(Re=[0,0,Z.framebufferWidth,Z.framebufferHeight]);e.renderXRView(re,D,this.placed,Re,pe,me)}}ne&&Z&&Z.framebuffer&&ne.bindFramebuffer(36160,null)};d.requestAnimationFrame(ie)}catch(I){throw typeof d.end=="function"&&await d.end().catch(()=>{}),N(),i.onError?.(I),I}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function mn(n){let e=await hn(),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,arScale:n.arScale||n.webXROptions?.arScale,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 Yn(n.model,i),{mode:"quick-look",success:!0};l=Xe(n.model)}return Yn(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 Br(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 ln(a);return await l.start(n.view,n.element),{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}`)}}De.registerAR({activateAR:mn,createUSDZBlob:Xe});De.registerScriptRunner(un);Ke(pn);export{wt as THREE,De as ThreeLiveElement,ce as ThreeView,mn as activateAR,Xe as createUSDZBlob,hn as getARCapabilities,Ur as getBestARMode,Kn as isQuickLookSupported,Zn as isSceneViewerSupported,Qn as isWebXRSupported,Te as toGLBData};