three-live 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +6 -1
  2. package/dist/index.d.ts +182 -6
  3. package/dist/three-author-engine.js +66 -41
  4. package/dist/three-author.cjs +63 -39
  5. package/dist/three-author.d.ts +182 -6
  6. package/dist/three-author.js +63 -39
  7. package/dist/three-convert.cjs +61 -37
  8. package/dist/three-convert.d.ts +182 -6
  9. package/dist/three-convert.js +61 -37
  10. package/dist/three-live-animation.cjs +7 -7
  11. package/dist/three-live-animation.d.ts +182 -6
  12. package/dist/three-live-animation.js +7 -7
  13. package/dist/three-live-animation.min.js +7 -7
  14. package/dist/three-live-cad.cjs +18 -0
  15. package/dist/{three-live-extras.d.ts → three-live-cad.d.ts} +182 -6
  16. package/dist/three-live-cad.js +18 -0
  17. package/dist/three-live-cad.min.js +18 -0
  18. package/dist/three-live-element.cjs +29 -5
  19. package/dist/three-live-element.d.ts +182 -6
  20. package/dist/three-live-element.js +29 -5
  21. package/dist/three-live-full.cjs +159 -56
  22. package/dist/three-live-full.js +159 -56
  23. package/dist/three-live-full.min.js +159 -56
  24. package/dist/three-live-studio.cjs +120 -0
  25. package/dist/three-live-studio.d.ts +509 -0
  26. package/dist/three-live-studio.js +120 -0
  27. package/dist/three-live-studio.min.js +120 -0
  28. package/dist/three-live-viewer.cjs +29 -5
  29. package/dist/three-live-viewer.d.ts +182 -6
  30. package/dist/three-live-viewer.js +29 -5
  31. package/dist/three-live-viewer.min.js +29 -5
  32. package/dist/three-live.cjs +66 -42
  33. package/dist/three-live.js +66 -42
  34. package/dist/three-live.min.js +66 -42
  35. package/dist/three-view.cjs +29 -5
  36. package/dist/three-view.d.ts +182 -6
  37. package/dist/three-view.js +29 -5
  38. package/dist/three-xr.cjs +65 -41
  39. package/dist/three-xr.d.ts +182 -6
  40. package/dist/three-xr.js +65 -41
  41. package/package.json +10 -5
  42. package/dist/three-live-extras.cjs +0 -42
  43. package/dist/three-live-extras.js +0 -42
  44. package/dist/three-live-extras.min.js +0 -42
package/dist/three-xr.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- function Z(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function Te(n,e,t,i,r){let s=1/Math.tan(e/2);n.fill(0),n[0]=s/t,n[5]=s,n[11]=-1;let c=1/(i-r);return n[10]=(r+i)*c,n[14]=2*r*i*c,n}function Re(n,e,t,i){let[r,s,c]=e,[l,u,a]=i,[o,f,d]=t,p=r-o,m=s-f,x=c-d,b=Math.hypot(p,m,x);b<=1e-5?(p=0,m=0,x=1):(p/=b,m/=b,x/=b);let E=u*x-a*m,P=a*p-l*x,A=l*m-u*p;b=Math.hypot(E,P,A),b<=1e-5?(E=0,P=0,A=0):(E/=b,P/=b,A/=b);let R=m*A-x*P,g=x*E-p*A,M=p*P-m*E;return b=Math.hypot(R,g,M),b<=1e-5?(R=0,g=0,M=0):(R/=b,g/=b,M/=b),n[0]=E,n[1]=R,n[2]=p,n[3]=0,n[4]=P,n[5]=g,n[6]=m,n[7]=0,n[8]=A,n[9]=M,n[10]=x,n[11]=0,n[12]=-(E*r+P*s+A*c),n[13]=-(R*r+g*s+M*c),n[14]=-(p*r+m*s+x*c),n[15]=1,n}function oe(n,e,t){let i=e[0],r=e[1],s=e[2],c=e[3],l=e[4],u=e[5],a=e[6],o=e[7],f=e[8],d=e[9],p=e[10],m=e[11],x=e[12],b=e[13],E=e[14],P=e[15],A=t[0],R=t[1],g=t[2],M=t[3];return n[0]=A*i+R*l+g*f+M*x,n[1]=A*r+R*u+g*d+M*b,n[2]=A*s+R*a+g*p+M*E,n[3]=A*c+R*o+g*m+M*P,A=t[4],R=t[5],g=t[6],M=t[7],n[4]=A*i+R*l+g*f+M*x,n[5]=A*r+R*u+g*d+M*b,n[6]=A*s+R*a+g*p+M*E,n[7]=A*c+R*o+g*m+M*P,A=t[8],R=t[9],g=t[10],M=t[11],n[8]=A*i+R*l+g*f+M*x,n[9]=A*r+R*u+g*d+M*b,n[10]=A*s+R*a+g*p+M*E,n[11]=A*c+R*o+g*m+M*P,A=t[12],R=t[13],g=t[14],M=t[15],n[12]=A*i+R*l+g*f+M*x,n[13]=A*r+R*u+g*d+M*b,n[14]=A*s+R*a+g*p+M*E,n[15]=A*c+R*o+g*m+M*P,n}function Ne(n,e,t,i){let r=e[0],s=e[1],c=e[2],l=e[3],u=r+r,a=s+s,o=c+c,f=r*u,d=r*a,p=r*o,m=s*a,x=s*o,b=c*o,E=l*u,P=l*a,A=l*o,R=i[0],g=i[1],M=i[2];return n[0]=(1-(m+b))*R,n[1]=(d+A)*R,n[2]=(p-P)*R,n[3]=0,n[4]=(d-A)*g,n[5]=(1-(f+b))*g,n[6]=(x+E)*g,n[7]=0,n[8]=(p+P)*M,n[9]=(x-E)*M,n[10]=(1-(f+m))*M,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function he(n,e){let t=e[0],i=e[1],r=e[2],s=e[4],c=e[5],l=e[6],u=e[8],a=e[9],o=e[10],f=o*c-l*a,d=-o*s+l*u,p=a*s-c*u,m=t*f+i*d+r*p;return m&&(m=1/m,n[0]=f*m,n[1]=(-o*i+r*a)*m,n[2]=(l*i-r*c)*m,n[3]=d*m,n[4]=(o*t-r*u)*m,n[5]=(-l*t+r*s)*m,n[6]=p*m,n[7]=(-a*t+i*u)*m,n[8]=(c*t-i*s)*m),n}function Oe(n,e){let t=e[0],i=e[1],r=e[2],s=e[3],c=e[4],l=e[5],u=e[6],a=e[7],o=e[8],f=e[9],d=e[10],p=e[11],m=e[12],x=e[13],b=e[14],E=e[15],P=t*l-i*c,A=t*u-r*c,R=t*a-s*c,g=i*u-r*l,M=i*a-s*l,h=r*a-s*u,v=o*x-f*m,y=o*b-d*m,T=o*E-p*m,F=f*b-d*x,C=f*E-p*x,w=d*E-p*b,D=P*w-A*C+R*F+g*T-M*y+h*v;return D?(D=1/D,n[0]=(l*w-u*C+a*F)*D,n[1]=(r*C-i*w-s*F)*D,n[2]=(x*h-b*M+E*g)*D,n[3]=(d*M-f*h-p*g)*D,n[4]=(u*T-c*w-a*y)*D,n[5]=(t*w-r*T+s*y)*D,n[6]=(b*R-m*h-E*A)*D,n[7]=(o*h-d*R+p*A)*D,n[8]=(c*C-l*T+a*v)*D,n[9]=(i*T-t*C-s*v)*D,n[10]=(m*M-x*R+E*P)*D,n[11]=(f*R-o*M-p*P)*D,n[12]=(l*y-c*F-u*v)*D,n[13]=(t*F-i*y+r*v)*D,n[14]=(x*A-m*g-b*P)*D,n[15]=(o*g-f*A+d*P)*D,n):null}function De(n,e,t,i,r){let s=r[0]*e+r[4]*t+r[8]*i+r[12],c=r[1]*e+r[5]*t+r[9]*i+r[13],l=r[2]*e+r[6]*t+r[10]*i+r[14],u=r[3]*e+r[7]*t+r[11]*i+r[15],a=u!==0?1/u:1;n[0]=s*a,n[1]=c*a,n[2]=l*a}function Ve(n,e,t,i,r,s,c,l,u,a,o,f,d,p,m,x,b=0){let E=a-c,P=o-l,A=f-u,R=d-c,g=p-l,M=m-u,h=r*M-s*g,v=s*R-i*M,y=i*g-r*R,T=E*h+P*v+A*y;if(T>-1e-7&&T<1e-7)return!1;let F=1/T,C=n-c,w=e-l,D=t-u,B=F*(C*h+w*v+D*y);if(B<-b||B>1+b)return!1;let L=w*A-D*P,q=D*E-C*A,z=C*P-w*E,j=F*(i*L+r*q+s*z);if(j<-b||B+j>1+b)return!1;let H=F*(R*L+g*q+M*z);if(H>1e-4&&H<x.distance){x.distance=H,x.point=[n+i*H,e+r*H,t+s*H];let $=P*M-A*g,G=A*R-E*M,N=E*g-P*R,W=Math.hypot($,G,N)||1;return x.normal=[$/W,G/W,N/W],!0}return!1}function we(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,i=[];for(let o=0;o<t;o++)i.push(Z());if(t===0)return i;let r=new Set;for(let o of n.nodes)if(Array.isArray(o.children))for(let f of o.children)r.add(f);let s=new Set,c=128,l=(o,f,d=0)=>{if(d>c||o<0||o>=t||s.has(o))return;s.add(o);let p=n.nodes[o];if(!p)return;let m=Z();if(e&&e[o])m.set(e[o]);else if(p.matrix&&p.matrix.length===16)m.set(p.matrix);else{let b=p.translation||[0,0,0],E=p.rotation||[0,0,0,1],P=p.scale||[1,1,1];Ne(m,E,b,P)}let x=i[o];if(f?oe(x,f,m):x.set(m),Array.isArray(p.children))for(let b of p.children)typeof b=="number"&&l(b,x,d+1)},u=[],a=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(a&&Array.isArray(a.nodes))u.push(...a.nodes);else for(let o=0;o<t;o++)r.has(o)||u.push(o);for(let o of u)l(o,null);for(let o=0;o<t;o++)!r.has(o)&&!u.includes(o)&&l(o,null);return i}var Ae="__THREE_LIVE_REGISTRY__";function pe(){let n=typeof globalThis<"u"?globalThis:{};if(!n[Ae]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,Ae,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[Ae]=e}}return n[Ae]}var K=pe().plugins;function Ge(n){let e=pe().plugins;e.some(t=>t.name===n.name)||e.push(n)}function He(){return pe().plugins}function mt(n){return new TextDecoder().decode(n)}var $e=pe().decoders;function ht(n,e){$e.set(n.toLowerCase(),e)}function ye(n){return $e.get(n.toLowerCase())}function qe(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 i=t.getUint32(0,!0);if(i!==1179937895){let d=t.getUint8(0);throw d===123||d===32||d===10||d===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${i.toString(16)}`)}let r=t.getUint32(4,!0);if(r!==2)throw new Error(`Unsupported GLB version: ${r}`);let s=t.getUint32(8,!0),c=12,l=null,u=null;for(;c+8<=s&&c+8<=e.byteLength;){let d=t.getUint32(c,!0),p=t.getUint32(c+4,!0),m=c+8;if(m+d>e.byteLength)throw new Error(`Truncated GLB chunk: required ${m+d} bytes, buffer has ${e.byteLength}`);if(p===1313821514){let x=new Uint8Array(e,m,d),b=mt(x);l=JSON.parse(b,(E,P)=>E==="__proto__"||E==="constructor"||E==="prototype"?void 0:P)}else p===5130562&&(u=e.slice(m,m+d));c=m+d}if(!l)throw new Error("Missing JSON chunk in GLB");let a=l.extensionsRequired||[];if(a.includes("KHR_draco_mesh_compression")&&!ye("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(a.includes("EXT_meshopt_compression")&&!ye("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(a.includes("KHR_texture_basisu")&&!ye("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let o=u||new ArrayBuffer(0),f={gltf:l,bin:o,animations:[]};for(let d of K)d.onParseGLB?.(f);return f}function ft(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 ge(n){if(ft(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return qe(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Ye=`#version 300 es
17
+ function Z(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function De(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 Pe(n,e,t,r){let[i,s,a]=e,[u,l,c]=r,[o,h,g]=t,R=i-o,f=s-h,m=a-g,p=Math.hypot(R,f,m);p<=1e-5?(R=0,f=0,m=1):(R/=p,f/=p,m/=p);let L=l*m-c*f,F=c*R-u*m,A=u*f-l*R;p=Math.hypot(L,F,A),p<=1e-5?(L=0,F=0,A=0):(L/=p,F/=p,A/=p);let I=f*A-m*F,x=m*L-R*A,v=R*F-f*L;return p=Math.hypot(I,x,v),p<=1e-5?(I=0,x=0,v=0):(I/=p,x/=p,v/=p),n[0]=L,n[1]=I,n[2]=R,n[3]=0,n[4]=F,n[5]=x,n[6]=f,n[7]=0,n[8]=A,n[9]=v,n[10]=m,n[11]=0,n[12]=-(L*i+F*s+A*a),n[13]=-(I*i+x*s+v*a),n[14]=-(R*i+f*s+m*a),n[15]=1,n}function te(n,e,t){let r=e[0],i=e[1],s=e[2],a=e[3],u=e[4],l=e[5],c=e[6],o=e[7],h=e[8],g=e[9],R=e[10],f=e[11],m=e[12],p=e[13],L=e[14],F=e[15],A=t[0],I=t[1],x=t[2],v=t[3];return n[0]=A*r+I*u+x*h+v*m,n[1]=A*i+I*l+x*g+v*p,n[2]=A*s+I*c+x*R+v*L,n[3]=A*a+I*o+x*f+v*F,A=t[4],I=t[5],x=t[6],v=t[7],n[4]=A*r+I*u+x*h+v*m,n[5]=A*i+I*l+x*g+v*p,n[6]=A*s+I*c+x*R+v*L,n[7]=A*a+I*o+x*f+v*F,A=t[8],I=t[9],x=t[10],v=t[11],n[8]=A*r+I*u+x*h+v*m,n[9]=A*i+I*l+x*g+v*p,n[10]=A*s+I*c+x*R+v*L,n[11]=A*a+I*o+x*f+v*F,A=t[12],I=t[13],x=t[14],v=t[15],n[12]=A*r+I*u+x*h+v*m,n[13]=A*i+I*l+x*g+v*p,n[14]=A*s+I*c+x*R+v*L,n[15]=A*a+I*o+x*f+v*F,n}function we(n,e,t,r){let i=e[0],s=e[1],a=e[2],u=e[3],l=i+i,c=s+s,o=a+a,h=i*l,g=i*c,R=i*o,f=s*c,m=s*o,p=a*o,L=u*l,F=u*c,A=u*o,I=r[0],x=r[1],v=r[2];return n[0]=(1-(f+p))*I,n[1]=(g+A)*I,n[2]=(R-F)*I,n[3]=0,n[4]=(g-A)*x,n[5]=(1-(h+p))*x,n[6]=(m+L)*x,n[7]=0,n[8]=(R+F)*v,n[9]=(m-L)*v,n[10]=(1-(h+f))*v,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function de(n,e){let t=e[0],r=e[1],i=e[2],s=e[4],a=e[5],u=e[6],l=e[8],c=e[9],o=e[10],h=o*a-u*c,g=-o*s+u*l,R=c*s-a*l,f=t*h+r*g+i*R;return f&&(f=1/f,n[0]=h*f,n[1]=g*f,n[2]=R*f,n[3]=(-o*r+i*c)*f,n[4]=(o*t-i*l)*f,n[5]=(-c*t+r*l)*f,n[6]=(u*r-i*a)*f,n[7]=(-u*t+i*s)*f,n[8]=(a*t-r*s)*f),n}function We(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],a=e[4],u=e[5],l=e[6],c=e[7],o=e[8],h=e[9],g=e[10],R=e[11],f=e[12],m=e[13],p=e[14],L=e[15],F=t*u-r*a,A=t*l-i*a,I=t*c-s*a,x=r*l-i*u,v=r*c-s*u,E=i*c-s*l,b=o*m-h*f,S=o*p-g*f,w=o*L-R*f,D=h*p-g*m,M=h*L-R*m,d=g*L-R*p,C=F*d-A*M+I*D+x*w-v*S+E*b;return C?(C=1/C,n[0]=(u*d-l*M+c*D)*C,n[1]=(i*M-r*d-s*D)*C,n[2]=(m*E-p*v+L*x)*C,n[3]=(g*v-h*E-R*x)*C,n[4]=(l*w-a*d-c*S)*C,n[5]=(t*d-i*w+s*S)*C,n[6]=(p*I-f*E-L*A)*C,n[7]=(o*E-g*I+R*A)*C,n[8]=(a*M-u*w+c*b)*C,n[9]=(r*w-t*M-s*b)*C,n[10]=(f*v-m*I+L*F)*C,n[11]=(h*I-o*v-R*F)*C,n[12]=(u*S-a*D-l*b)*C,n[13]=(t*D-r*S+i*b)*C,n[14]=(m*A-f*x-p*F)*C,n[15]=(o*x-h*A+g*F)*C,n):null}function Ue(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],u=i[2]*e+i[6]*t+i[10]*r+i[14],l=i[3]*e+i[7]*t+i[11]*r+i[15],c=l!==0?1/l:1;n[0]=s*c,n[1]=a*c,n[2]=u*c}function $e(n,e,t,r,i,s,a,u,l,c,o,h,g,R,f,m,p=0){let L=c-a,F=o-u,A=h-l,I=g-a,x=R-u,v=f-l,E=i*v-s*x,b=s*I-r*v,S=r*x-i*I,w=L*E+F*b+A*S;if(w>-1e-7&&w<1e-7)return!1;let D=1/w,M=n-a,d=e-u,C=t-l,_=D*(M*E+d*b+C*S);if(_<-p||_>1+p)return!1;let T=d*A-C*F,O=C*L-M*A,U=M*F-d*L,$=D*(r*T+i*O+s*U);if($<-p||_+$>1+p)return!1;let B=D*(I*T+x*O+v*U);if(B>1e-4&&B<m.distance){m.distance=B,m.point=[n+r*B,e+i*B,t+s*B];let H=F*v-A*x,G=A*I-L*v,X=L*x-F*I,q=Math.hypot(H,G,X)||1;return m.normal=[H/q,G/q,X/q],!0}return!1}function Le(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let o=0;o<t;o++)r.push(Z());if(t===0)return r;let i=new Set;for(let o of n.nodes)if(Array.isArray(o.children))for(let h of o.children)i.add(h);let s=new Set,a=128,u=(o,h,g=0)=>{if(g>a||o<0||o>=t||s.has(o))return;s.add(o);let R=n.nodes[o];if(!R)return;let f=Z();if(e&&e[o])f.set(e[o]);else if(R.matrix&&R.matrix.length===16)f.set(R.matrix);else{let p=R.translation||[0,0,0],L=R.rotation||[0,0,0,1],F=R.scale||[1,1,1];we(f,L,p,F)}let m=r[o];if(h?te(m,h,f):m.set(f),Array.isArray(R.children))for(let p of R.children)typeof p=="number"&&u(p,m,g+1)},l=[],c=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(c&&Array.isArray(c.nodes))l.push(...c.nodes);else for(let o=0;o<t;o++)i.has(o)||l.push(o);for(let o of l)u(o,null);for(let o=0;o<t;o++)!i.has(o)&&!l.includes(o)&&u(o,null);return r}var Fe="__THREE_LIVE_REGISTRY__";function ge(){let n=typeof globalThis<"u"?globalThis:{};if(!n[Fe]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,Fe,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[Fe]=e}}return n[Fe]}var ne=ge().plugins;function qe(n){let e=ge().plugins;e.some(t=>t.name===n.name)||e.push(n),n.onRegister?.()}function Ke(){return ge().plugins}function xt(n){return new TextDecoder().decode(n)}var Qe=ge().decoders;function vt(n,e){Qe.set(n.toLowerCase(),e)}function Me(n){return Qe.get(n.toLowerCase())}function Je(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 g=t.getUint8(0);throw g===123||g===32||g===10||g===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,u=null,l=null;for(;a+8<=s&&a+8<=e.byteLength;){let g=t.getUint32(a,!0),R=t.getUint32(a+4,!0),f=a+8;if(f+g>e.byteLength)throw new Error(`Truncated GLB chunk: required ${f+g} bytes, buffer has ${e.byteLength}`);if(R===1313821514){let m=new Uint8Array(e,f,g),p=xt(m);u=JSON.parse(p,(L,F)=>L==="__proto__"||L==="constructor"||L==="prototype"?void 0:F)}else R===5130562&&(l=e.slice(f,f+g));a=f+g}if(!u)throw new Error("Missing JSON chunk in GLB");let c=u.extensionsRequired||[];if(c.includes("KHR_draco_mesh_compression")&&!Me("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(c.includes("EXT_meshopt_compression")&&!Me("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(c.includes("KHR_texture_basisu")&&!Me("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let o=l||new ArrayBuffer(0),h={gltf:u,bin:o,animations:[]};for(let g of ne)g.onParseGLB?.(h);return h}function Mt(n,e,t){return e%4===0?new Float32Array(n,e,t):new Float32Array(n.slice(e,e+t*4))}function Tt(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 Re(n){if(Tt(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return Je(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var et=`#version 300 es
18
18
  layout(location=0) in vec3 aPosition;
19
19
  layout(location=1) in vec3 aNormal;
20
20
  layout(location=2) in vec2 aUV;
@@ -32,7 +32,7 @@ vec2 scaleUV=uUvTransform.zw;
32
32
  if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
33
33
  vUV=aUV*scaleUV+uUvTransform.xy;
34
34
  gl_Position=uMVP*vec4(aPosition,1.0);
35
- }`,dt=`#version 300 es
35
+ }`,At=`#version 300 es
36
36
  precision highp float;
37
37
  in vec3 vNormal,vWorldPos;
38
38
  in vec2 vUV;
@@ -108,9 +108,33 @@ float g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);
108
108
  return mix(color,newPeak*vec3(1.0),g);
109
109
  }
110
110
 
111
+ vec3 acesToneMapping(vec3 color){
112
+ color*=0.6;
113
+ return clamp((color*(2.51*color+0.03))/(color*(2.43*color+0.59)+0.14),0.0,1.0);
114
+ }
115
+
116
+ vec3 agxToneMapping(vec3 color){
117
+ color=max(color,vec3(0.0));
118
+ vec3 inset=vec3(
119
+ 0.84247906*color.r+0.0784336*color.g+0.07922375*color.b,
120
+ 0.04232824*color.r+0.87846864*color.g+0.07916613*color.b,
121
+ 0.04237565*color.r+0.0784336*color.g+0.87914297*color.b);
122
+ vec3 ev=clamp((log2(max(inset,vec3(1e-6)))+12.47393)/16.5,0.0,1.0);
123
+ vec3 x2=ev*ev;
124
+ vec3 x4=x2*x2;
125
+ vec3 s=15.5*x4*x2-40.14*x4*ev+31.96*x4-6.868*x2*ev+0.4298*x2+0.1191*ev-0.00232;
126
+ vec3 outset=vec3(
127
+ 1.196879*s.r-0.09802088*s.g-0.09902974*s.b,
128
+ -0.05289685*s.r+1.15190313*s.g-0.09896118*s.b,
129
+ -0.05297164*s.r-0.09804345*s.g+1.15107367*s.b);
130
+ return clamp(pow(max(outset,vec3(0.0)),vec3(2.2)),0.0,1.0);
131
+ }
132
+
111
133
  vec3 applyToneMapping(vec3 color,int mode){
112
134
  if(mode==0)return neutralToneMapping(color);
113
135
  if(mode==1)return color/(color+vec3(1.0));
136
+ if(mode==3)return acesToneMapping(color);
137
+ if(mode==4)return agxToneMapping(color);
114
138
  return color;
115
139
  }
116
140
 
@@ -198,24 +222,24 @@ color=applyToneMapping(color,uToneMapping);
198
222
  float outAlpha=base.a;
199
223
  /*XRD_O*/
200
224
  fragColor=vec4(color,outAlpha);
201
- }`,pt=`#version 300 es
225
+ }`;var wt=`#version 300 es
202
226
  layout(location=0) in vec3 aPosition;
203
227
  uniform mat4 uMVP;
204
- void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,bt=`#version 300 es
228
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Rt=`#version 300 es
205
229
  precision highp float;
206
230
  uniform vec4 uColorId;
207
231
  out vec4 fragColor;
208
- void main(){fragColor=uColorId;}`;function ze(n,e,t){let i=n.createShader(e);if(n.shaderSource(i,t),n.compileShader(i),!n.getShaderParameter(i,35713)){let r=n.getShaderInfoLog(i);throw n.deleteShader(i),new Error(`Shader compile error: ${r}`)}return i}function Fe(n,e,t){let i=ze(n,35633,e),r=ze(n,35632,t),s=n.createProgram();if(n.attachShader(s,i),n.attachShader(s,r),n.linkProgram(s),!n.getProgramParameter(s,35714)){let c=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${c}`)}return s}function Ce(n,e,t){let i={};for(let r of t)i[r]=n.getUniformLocation(e,r);return i}var Xe=["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 Ke(){let n=pe().xrDepthShader;return{fs:dt.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Xe,...n.uniformNames]:Xe}}function yt(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 Le(n,e,t,i,r,s,c){if(i===void 0||!e.accessors?.[i])return null;let l=e.accessors[i],u=e.bufferViews[l.bufferView],a=(u.byteOffset||0)+(l.byteOffset||0),o=u.byteStride&&u.byteStride>s*4?u.byteStride>>2:s,f;if(o===s)f=new Float32Array(t,a,l.count*s);else{f=new Float32Array(l.count*s);let p=new Float32Array(t,u.byteOffset||0,Math.floor(u.byteLength/4)),m=(l.byteOffset||0)>>2;for(let x=0;x<l.count;x++){let b=m+x*o;for(let E=0;E<s;E++)f[x*s+E]=p[b+E]}}let d=n.createBuffer();return c.push(d),n.bindBuffer(34962,d),n.bufferData(34962,f,35044),n.enableVertexAttribArray(r),n.vertexAttribPointer(r,s,5126,!1,0,0),f}var Ft=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Ze=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function We(n,e,t=Ze,i){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:r,bin:s}=e,c=[],l=we(r),u=[];if(Array.isArray(r.nodes))for(let v=0;v<r.nodes.length;v++){let y=r.nodes[v];y.mesh!==void 0&&r.meshes&&r.meshes[y.mesh]&&u.push({node:y,nodeIdx:v,meshIdx:y.mesh})}let a=u.length>0?u:(r.meshes||[]).map((v,y)=>({node:v,nodeIdx:-1,meshIdx:y})),o=[];if(Array.isArray(e.lights)&&e.lights.length>0)o.push(...e.lights);else if(r.extensions?.KHR_lights_punctual?.lights){let v=r.extensions.KHR_lights_punctual.lights;for(let y of v){let T=y.type==="directional"?"directional":y.type==="point"?"point":"ambient";o.push({type:T,color:y.color||[1,1,1],intensity:y.intensity!==void 0?y.intensity:1})}}if(o.length===0&&(o.push({type:"ambient",color:[1,1,1],intensity:.35}),o.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),a.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${a.length}`);let f=[];if(r.textures&&r.images){if(r.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${r.textures.length}`);for(let v=0;v<r.textures.length;v++){let y=r.textures[v],T=r.images[y.source];if(T){let F=n.createTexture();if(n.bindTexture(3553,F),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),T.bufferView!==void 0){let C=r.bufferViews[T.bufferView],w=s.slice(C.byteOffset||0,(C.byteOffset||0)+C.byteLength),D=new Blob([w],{type:T.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(D).then(B=>{n.bindTexture(3553,F),n.texImage2D(3553,0,6408,6408,5121,B),n.generateMipmap(3553),i?.()}).catch(()=>{})}else if(T.uri){let C=yt(T.uri);if(C){let w=new Image;w.crossOrigin="anonymous",w.referrerPolicy="no-referrer",w.onload=()=>{n.bindTexture(3553,F),n.texImage2D(3553,0,6408,6408,5121,w),n.generateMipmap(3553),i?.()},w.src=C}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",T.uri)}f.push(F)}else f.push(null)}}let d=[1/0,1/0,1/0],p=[-1/0,-1/0,-1/0],m=0,x=0;for(let v=0;v<a.length;v++){let y=a[v],T=r.meshes[y.meshIdx],F=y.nodeIdx>=0?l[y.nodeIdx]:Z(),C=new Float32Array(9);he(C,F);let w={name:y.node.name||T.name||`Mesh_${y.meshIdx}`,nodeIndex:y.nodeIdx,transform:F,normalMatrix:C,primitives:[],extras:y.node.extras||T.extras};for(let D of T.primitives||[]){if(D.extensions?.KHR_draco_mesh_compression){let O=ye("draco");O&&O.decodePrimitive(r,D,s)}let B=[],L=n.createVertexArray();n.bindVertexArray(L);let q=r.accessors[D.attributes.POSITION],z=Number(q?.count??0);if(!Number.isFinite(z)||z<0||m+z>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(m+=z,q?.min&&q?.max)for(let O=0;O<3;O++){let ne=F[12+O],me=F[12+O];for(let de=0;de<3;de++){let xe=F[de*4+O]*q.min[de],Me=F[de*4+O]*q.max[de];ne+=xe<Me?xe:Me,me+=xe>Me?xe:Me}ne<d[O]&&(d[O]=ne),me>p[O]&&(p[O]=me)}let j=Le(n,r,s,D.attributes.POSITION,0,3,B);Le(n,r,s,D.attributes.NORMAL,1,3,B),Le(n,r,s,D.attributes.TEXCOORD_0,2,2,B);let H=0,$=5123,G=null;if(D.indices!==void 0){let O=r.accessors[D.indices],me=(r.bufferViews[O.bufferView].byteOffset||0)+(O.byteOffset||0);if(H=Number(O.count??0),!Number.isFinite(H)||H<0||x+H>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);x+=H,$=O.componentType===5125?5125||5125:5123||5123;let de=n.createBuffer();B.push(de),n.bindBuffer(34963,de),O.componentType===5125?(G=new Uint32Array(s,me,O.count),n.bufferData(34963,G,35044)):(G=new Uint16Array(s,me,O.count),n.bufferData(34963,G,35044))}else H=q.count;let N={};for(let O of K)if(O.onBuildPrimitiveVAO){let ne=O.onBuildPrimitiveVAO(n,L,D,r,s);ne&&(N[O.name]=ne)}n.bindVertexArray(null);let W=r.materials&&D.material!==void 0?r.materials[D.material]:null,I=Ke(),S=Ye,U=I.fs,_=!1;for(let O of K)if(O.onResolveShader){let ne=O.onResolveShader(D,W,S,U);ne&&(S=ne.vs,U=ne.fs,_=!0)}let ee=_?Fe(n,S,U):null,re=ee?Ce(n,ee,I.uniforms):null,X=W?.pbrMetallicRoughness,ce=X?.baseColorFactor||[.8,.8,.8,1],ie=X?.metallicFactor??.1,te=X?.roughnessFactor??.5,k=W?.extensions?.KHR_materials_clearcoat,Q=k?k.clearcoatFactor??1:0,Y=Math.max(.04,k?.clearcoatRoughnessFactor??.04),ue=X?.baseColorTexture!==void 0&&f[X.baseColorTexture.index]?f[X.baseColorTexture.index]:null,ve=X?.metallicRoughnessTexture!==void 0&&f[X.metallicRoughnessTexture.index]?f[X.metallicRoughnessTexture.index]:null,se=W?.normalTexture!==void 0&&f[W.normalTexture.index]?f[W.normalTexture.index]:null,J=W?.normalTexture?.scale??1,fe=W?.occlusionTexture!==void 0&&f[W.occlusionTexture.index]?f[W.occlusionTexture.index]:null,ae=W?.occlusionTexture?.strength??1,le=!!(W?.extensions?.KHR_materials_transmission||N.materials?.isTransmissive);w.primitives.push({vao:L,indexCount:H,indexType:$,baseColor:ce,metallic:ie,roughness:te,clearcoat:Q,clearcoatRoughness:Y,positions:j,indices:G,texture:ue,metallicRoughnessTexture:ve,normalTexture:se,occlusionTexture:fe,normalScale:J,occlusionStrength:ae,buffers:B,materialIndex:D.material,pluginData:N,customProgram:ee,customUniforms:re,isTransmissive:le})}c.push(w)}isFinite(d[0])||(d=[-1,-1,-1]),isFinite(p[0])||(p=[1,1,1]);let b=[(d[0]+p[0])/2,(d[1]+p[1])/2,(d[2]+p[2])/2],E=p[0]-d[0],P=p[1]-d[1],A=p[2]-d[2],R=Math.max(Math.hypot(E,P,A)/2,.5),g=[d[0],d[1],d[2]],M=[p[0],p[1],p[2]],h=e.animations;if(!h){for(let v of K)if(v.onParseGLB?.(e),e.animations){h=e.animations;break}}return h||(h=[]),{meshes:c,bounds:{center:b,radius:R,min:g,max:M},lights:o,animations:h,worldMatrices:l}}var Ee=class{constructor(e,t,i){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=Z();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=Z();this.viewMatrix=Z();this.modelMatrix=Z();this.mvpMatrix=Z();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:Z(),rawValueToMeters:.001,format:0};this.container=e;let r,s;if(t&&typeof t.getContext=="function"?(r=t,s=i):(s=t,r=s?.canvas),!r){let a=e.querySelector("canvas");a||(a=document.createElement("canvas"),a.style.width="100%",a.style.height="100%",a.style.display="block",a.style.touchAction="none",e.prepend(a)),r=a}this.canvas=r,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let c=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!c:c&&(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=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!l)throw new Error("WebGL2 not supported");this.gl=l;let u=Ke();this.renderProg=Fe(l,Ye,u.fs),this.pickProg=Fe(l,pt,bt),this.uRender=Ce(l,this.renderProg,u.uniforms),this.uPick=Ce(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){ht(e,t)}static getDecoder(e){return ye(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),i=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=i,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,i,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,i),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 i=this.gl,r=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=r,this.pickFboHeight=s,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,s,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,s)}loadGLBData(e,t){let{meshes:i,bounds:r,lights:s,animations:c,worldMatrices:l}=We(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=c||[],this.worldMatrices=l||[],this.gltf=e.gltf,this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let a of e.gltf.nodes)this.initialNodeTransforms.push({t:a.translation?[a.translation[0],a.translation[1],a.translation[2]]:[0,0,0],r:a.rotation?[a.rotation[0],a.rotation[1],a.rotation[2],a.rotation[3]]:[0,0,0,1],s:a.scale?[a.scale[0],a.scale[1],a.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let a of K)a.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:r.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let u=e.exposure??e.environmentIntensity??e.gltf?.extras?.exposure??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.exposure??e.gltf?.asset?.extras?.environmentIntensity;u!==void 0&&(this.envIntensity=Math.max(0,Number(u))),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(qe(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(ge(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=ge(e),{meshes:r}=We(this.gl,i,Ze,()=>this.render());if(t)for(let s of r)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],he(s.normalMatrix,s.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(e,t,i,r=1){this.clearColor=[e,t,i,r]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let i=this.meshes[t],r;e instanceof Map?r=e.get(i.name)??e.get(t):Array.isArray(e)?r=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,i.name)?r=e[i.name]:Object.prototype.hasOwnProperty.call(e,t)&&(r=e[t])),r&&r.length===16&&(i.transform.set(r),he(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[],s=[],c=[],l=[];for(let u of this.lights){let a=u.color||[1,1,1],o=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")i=[a[0]*o,a[1]*o,a[2]*o];else if(u.type==="directional"&&r.length<6){let f=u.direction||[.5,1,.8];r.push(f[0],f[1],f[2]),s.push(a[0]*o,a[1]*o,a[2]*o)}else if(u.type==="point"&&c.length<6){let f=u.position||[0,0,0];c.push(f[0],f[1],f[2]),l.push(a[0]*o,a[1]*o,a[2]*o)}}r.length===0&&(r.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,i),t.uniform1i(e.uNumDirLights,r.length/3),r.length>0&&(t.uniform3fv(e.uDirLightDir,r),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,c.length/3),c.length>0&&(t.uniform3fv(e.uPointLightPos,c),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 K)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of K)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,i=this.currDistance;return{theta:e,phi:t,radius:i,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${i.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,i)=>{let r=this.meshes.flatMap(o=>o.primitives.filter(f=>f.materialIndex===i||e.length===1&&f.materialIndex===void 0)),s=r[0],c=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,u=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,a={baseColorFactor:c,metallicFactor:l,roughnessFactor:u,setBaseColorFactor:o=>{let f=[o[0],o[1],o[2],o[3]??1];a.baseColorFactor=f,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=f);for(let d of r)d.baseColor=f;this.render()},setMetallicFactor:o=>{a.metallicFactor=o,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=o);for(let f of r)f.metallic=o;this.render()},setRoughnessFactor:o=>{a.roughnessFactor=o,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=o);for(let f of r)f.roughness=o;this.render()}};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:a}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(i=>i.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 K)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,i){this.customTarget=[e,t,i],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,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(i,e))}setCamera(e,t,i,r){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(e,t,i,r){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),i!==void 0&&i>0){let s=this.clampDistance(i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(r!==void 0&&r>0){let s=this.clampDistance(this.bounds.radius*2.5/r);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 i=Z();oe(i,this.projMatrix,this.viewMatrix);let[r,s,c]=e,l=t?t[0]:0,u=t?t[1]:0,a=t?t[2]:0,o=this.modelRootMatrix;o&&(r=o[0]*e[0]+o[4]*e[1]+o[8]*e[2]+o[12],s=o[1]*e[0]+o[5]*e[1]+o[9]*e[2]+o[13],c=o[2]*e[0]+o[6]*e[1]+o[10]*e[2]+o[14],t&&(l=o[0]*t[0]+o[4]*t[1]+o[8]*t[2],u=o[1]*t[0]+o[5]*t[1]+o[9]*t[2],a=o[2]*t[0]+o[6]*t[1]+o[10]*t[2]));let f=i[0]*r+i[4]*s+i[8]*c+i[12],d=i[1]*r+i[5]*s+i[9]*c+i[13],p=i[2]*r+i[6]*s+i[10]*c+i[14],m=i[3]*r+i[7]*s+i[11]*c+i[15];if(m<=1e-4)return{x:0,y:0,z:1,visible:!1};let x=f/m,b=d/m,E=p/m,P=this.canvas.getBoundingClientRect(),A=P.width||this.canvas.clientWidth||this.canvas.width||300,R=P.height||this.canvas.clientHeight||this.canvas.height||150,g=(x*.5+.5)*A,M=(-b*.5+.5)*R,h=x>=-1.1&&x<=1.1&&b>=-1.1&&b<=1.1&&E>=-1&&E<=1;if(h&&t){let v=this.customTarget||this.bounds.center,y=v[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),T=v[1]+this.currDistance*Math.sin(this.currPhi),F=v[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),C=[r-y,s-T,c-F];l*C[0]+u*C[1]+a*C[2]>.05&&(h=!1)}return{x:g,y:M,z:E,visible:h}}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 i=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},r=t.clientX-i.x,s=t.clientY-i.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(r,s),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let c=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],l=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],u=this.customTarget?[...this.customTarget]:[...this.bounds.center],a=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;u[0]+=(-r*c[0]+s*l[0])*a,u[1]+=(-r*c[1]+s*l[1])*a,u[2]+=(-r*c[2]+s*l[2])*a,this.customTarget=u}else this.targetTheta=this.clampTheta(this.targetTheta-r*.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 i=e.getBoundingClientRect(),r=Math.floor((t.clientX-i.left)*(e.width/Math.max(i.width,1))),s=Math.floor((t.clientY-i.top)*(e.height/Math.max(i.height,1)));this.performMeshPick(r,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 i=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*i)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let i=t.detail||{};i.reset?this.resetCamera():this.setCamera(i.theta,i.phi,i.distance,i.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=t=>{if(!this.interactive)return;let i=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=i,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=i,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=i,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=i,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=i,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=i,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=i,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 i=this.canvas,r=i.getBoundingClientRect(),s=i.width||300,c=i.height||300,l=r.width>0?Math.floor((e-r.left)*(s/r.width)):Math.floor(e),u=r.height>0?Math.floor((t-r.top)*(c/r.height)):Math.floor(t);return this.performMeshPick(l,u,!1)}performMeshPick(e,t,i=!0){if(this.meshes.length===0)return null;let r=this.gl,s=Math.max(1,this.canvas.width||300),c=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let l=Z();oe(l,this.projMatrix,this.viewMatrix);let u=[],a=Math.max(0,Math.min(s-1,e)),o=Math.max(0,Math.min(c-1,c-1-t));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==c)&&this.resizePickingFbo(s,c),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,s,c),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16384|256),r.useProgram(this.pickProg);for(let h=0;h<this.meshes.length;h++){let v=this.meshes[h];if(v.visible===!1||v.isPluginMesh)continue;let y=h+1,T=(y&255)/255,F=(y>>8&255)/255,C=(y>>16&255)/255;r.uniform4f(this.uPick.uColorId,T,F,C,1),oe(this.modelMatrix,this.modelRootMatrix,v.transform),oe(this.mvpMatrix,l,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let w of v.primitives)r.bindVertexArray(w.vao),r.drawElements(4,w.indexCount,w.indexType,0)}let g=new Uint8Array(4);r.readPixels(a,o,1,1,6408,5121,g),r.bindFramebuffer(36160,null);let M=g[0]+(g[1]<<8)+(g[2]<<16);M>0&&M<=this.meshes.length&&(u=[this.meshes[M-1]])}u.length===0&&(u=this.meshes.filter(g=>g.visible!==!1));let f=null,d=1/0,p=[0,0,0],m=[0,1,0],x=this.customTarget||this.bounds.center,b=x[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),E=x[1]+this.currDistance*Math.sin(this.currPhi),P=x[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let g of u){oe(this.modelMatrix,this.modelRootMatrix,g.transform),oe(this.mvpMatrix,l,this.modelMatrix);let M=Z();if(!Oe(M,this.mvpMatrix))continue;let h=(a+.5)/s*2-1,v=(o+.5)/c*2-1,y=[0,0,0],T=[0,0,0];De(y,h,v,-1,M),De(T,h,v,1,M);let F=T[0]-y[0],C=T[1]-y[1],w=T[2]-y[2],D=Math.hypot(F,C,w)||1,B=F/D,L=C/D,q=w/D,z={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((H=>{for(let $ of g.primitives){if(!$.positions)continue;let G=$.positions,N=$.indices,W=Math.floor(N?N.length/3:G.length/9);for(let I=0;I<W;I++){let S=N?N[I*3]:I*3,U=N?N[I*3+1]:I*3+1,_=N?N[I*3+2]:I*3+2;Ve(y[0],y[1],y[2],B,L,q,G[S*3],G[S*3+1],G[S*3+2],G[U*3],G[U*3+1],G[U*3+2],G[_*3],G[_*3+1],G[_*3+2],z,H)}}})(1e-4),isFinite(z.distance)){let H=z.point[0],$=z.point[1],G=z.point[2],N=this.modelMatrix,W=N[0]*H+N[4]*$+N[8]*G+N[12],I=N[1]*H+N[5]*$+N[9]*G+N[13],S=N[2]*H+N[6]*$+N[10]*G+N[14],U=W-b,_=I-E,ee=S-P,re=Math.hypot(U,_,ee);if(re<d){he(this.normalMatrix,this.modelMatrix);let X=this.normalMatrix,ce=z.normal[0],ie=z.normal[1],te=z.normal[2],k=X[0]*ce+X[3]*ie+X[6]*te,Q=X[1]*ce+X[4]*ie+X[7]*te,Y=X[2]*ce+X[5]*ie+X[8]*te,ue=Math.hypot(k,Q,Y)||1;k/=ue,Q/=ue,Y/=ue,k*U+Q*_+Y*ee>0&&(k=-k,Q=-Q,Y=-Y),f=g,d=Math.round(re*1e3)/1e3,p=[Math.round(W*1e3)/1e3,Math.round(I*1e3)/1e3,Math.round(S*1e3)/1e3],m=[Math.round(k*1e3)/1e3,Math.round(Q*1e3)/1e3,Math.round(Y*1e3)/1e3]}}}if(!f)return null;let R={meshIndex:this.meshes.indexOf(f),meshName:f.name,nodeIndex:f.nodeIndex,distance:d,hitPoint:p,normal:m,screenX:e,screenY:t};if(i){for(let g of K)g.onMeshSelect?.(this,R);this.opts.onMeshClick&&this.opts.onMeshClick(R),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:R}))}return R}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,s=r?e-i:e,c=r?Math.max(1,t-i):i,l=(s+.5)/c*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);Te(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center,r=i[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),s=i[1]+this.currDistance*Math.sin(this.currPhi),c=i[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);Re(this.viewMatrix,[r,s,c],i,[0,1,0]),oe(this.mvpMatrix,this.projMatrix,this.viewMatrix),he(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.floor(t.width*e)),r=Math.max(1,Math.floor(t.height*e));this.canvas.width!==i||this.canvas.height!==r?(this.canvas.width=i,this.canvas.height=r,this.resizePickingFbo(i,r),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 i of K)i.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(i){this.reportRenderError(i)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of K)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 i=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}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),i=this.bounds.center[0],r=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]=i-(e*i+t*r),s[13]=0,s[14]=r-(-t*i+e*r),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let c of K)c.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 c of K)c.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 i=Math.round((this.currTheta*180/Math.PI%360+360)%360),r=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(i-this.lastReportedTheta)>=1||Math.abs(r-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=s;let c={theta:i,phi:r,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(c),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:c}))}}renderXRView(e,t,i,r,s=!0,c=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let l=e?.transform?.inverse?.matrix||this.viewMatrix,u=e?.projectionMatrix||this.projMatrix,a=e?.transform?.position,o=a?[a.x,a.y,a.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):i&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:l,projMatrix:u,eyePos:o,viewport:r,eye:e?.eye||"none",clear:c>0?!1:e?.eye!=="right",isAR:s})}render(e){if(!e&&this.stereoSBS){let R=Math.max(2,this.canvas.width||2),g=Math.max(1,this.canvas.height||1),M=Math.max(1,Math.floor(R*.5)),h=Math.max(1,R-M),v=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),y=this.customTarget||this.bounds.center,T=y[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),F=y[1]+this.currDistance*Math.sin(this.currPhi),C=y[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),w=Math.cos(this.currTheta),D=-Math.sin(this.currTheta),B=.032,L=Z(),q=Z(),z=[T-w*B,F,C-D*B],j=[y[0]-w*B*.25,y[1],y[2]-D*B*.25];Te(L,this.fov,M/g,.1,v),Re(q,z,j,[0,1,0]);let H=Z(),$=Z(),G=[T+w*B,F,C+D*B],N=[y[0]+w*B*.25,y[1],y[2]+D*B*.25];Te(H,this.fov,h/g,.1,v),Re($,G,N,[0,1,0]),this.render({viewMatrix:q,projMatrix:L,eyePos:z,viewport:[0,0,M,g],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:$,projMatrix:H,eyePos:G,viewport:[M,0,h,g],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,R,g);return}let t=this.gl,i=0,r=0,s=this.canvas.width,c=this.canvas.height;e?.viewport?(i=e.viewport[0],r=e.viewport[1],s=e.viewport[2],c=e.viewport[3],t.viewport(i,r,s,c)):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=Z(),u=e?.viewMatrix??this.viewMatrix;oe(l,e?.projMatrix??this.projMatrix,u);let a=pe().xrDepthShader,o=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:0,f=this.customTarget||this.bounds.center,d=e?e.eyePos[0]:f[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),p=e?e.eyePos[1]:f[1]+this.currDistance*Math.sin(this.currPhi),m=e?e.eyePos[2]:f[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let R of K)R.onBeforeDrawScene?.(this,t,l,[d,p,m],o);let x=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&x===0)return;let b=e?.eye||"none",E=!1,P=x>0?[...this.backdropMeshes,...this.meshes]:this.meshes,A=R=>{for(let g=0;g<P.length;g++){let M=P[g];if(M.visible===!1)continue;let h=this.selectedMeshName!==""&&M.name===this.selectedMeshName;g<x||M.worldSpace===!0||M.name==="__xr_reticle__"?this.modelMatrix.set(M.transform):oe(this.modelMatrix,this.modelRootMatrix,M.transform),oe(this.mvpMatrix,l,this.modelMatrix),he(M.normalMatrix,this.modelMatrix);let v=M.extras?.xr?.stereo||M.userData?.xr?.stereo,y=0,T=0,F=1,C=1;v==="sbs"?(F=.5,y=b==="right"?.5:0):v==="ou"&&(C=.5,T=b==="right"?.5:0);for(let w of M.primitives){let D=!!w.isTransmissive;if(!R&&D){E=!0;continue}if(R&&!D)continue;let B=w.customProgram||this.renderProg,L=w.customUniforms||this.uRender;t.useProgram(B),t.uniform1i(L.uToneMapping,o),t.uniform1f(L.uEnvIntensity,this.envIntensity),t.uniform3f(L.uCameraPos,d,p,m),t.uniform1f(L.uEmissive,h?1:0),t.uniformMatrix4fv(L.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(L.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(L.uNormalMatrix,!1,M.normalMatrix),L.uUvTransform&&t.uniform4f(L.uUvTransform,y,T,F,C),L.uViewportSize&&t.uniform2f(L.uViewportSize,Math.max(1,s),Math.max(1,c)),a?.bind(t,L,this.xrDepthState,u,[i,r,Math.max(1,s),Math.max(1,c)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(L.uEnvironmentMap,4),t.uniform1i(L.uHasEnvironmentMap,1)):t.uniform1i(L.uHasEnvironmentMap,0),this.bindLights(L),L.uSectionEnabled&&t.uniform1i(L.uSectionEnabled,0);for(let q of K)q.onBeforeDrawPrimitive?.(t,B,w,M,this.worldMatrices||[],this.gltf);t.uniform4fv(L.uBaseColor,w.baseColor),t.uniform1f(L.uMetallic,w.metallic),t.uniform1f(L.uRoughness,w.roughness),L.uClearcoat&&t.uniform2f(L.uClearcoat,w.clearcoat??0,w.clearcoatRoughness??.04),w.texture?(t.activeTexture(33984),t.bindTexture(3553,w.texture),t.uniform1i(L.uBaseColorTexture,0),t.uniform1i(L.uHasTexture,1)):t.uniform1i(L.uHasTexture,0),w.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,w.metallicRoughnessTexture),t.uniform1i(L.uMetallicRoughnessTexture,1),t.uniform1i(L.uHasMetallicRoughnessTexture,1)):t.uniform1i(L.uHasMetallicRoughnessTexture,0),w.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,w.normalTexture),t.uniform1i(L.uNormalTexture,2),t.uniform1i(L.uHasNormalTexture,1),t.uniform1f(L.uNormalScale,w.normalScale)):t.uniform1i(L.uHasNormalTexture,0),w.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,w.occlusionTexture),t.uniform1i(L.uOcclusionTexture,3),t.uniform1i(L.uHasOcclusionTexture,1),t.uniform1f(L.uOcclusionStrength,w.occlusionStrength)):t.uniform1i(L.uHasOcclusionTexture,0),t.bindVertexArray(w.vao),t.drawElements(4,w.indexCount,w.indexType,0)}}};if(A(!1),E){for(let R of K)R.onBeforeTransmissivePass?.(t,this);A(!0)}for(let R of K)R.onAfterRender?.(t,this,l)}disposeMeshListGpuResources(e){let t=this.gl;for(let i of e)for(let r of i.primitives){if(r.vao&&t.deleteVertexArray(r.vao),r.buffers)for(let s of r.buffers)t.deleteBuffer(s);r.texture&&t.deleteTexture(r.texture),r.metallicRoughnessTexture&&t.deleteTexture(r.metallicRoughnessTexture),r.normalTexture&&t.deleteTexture(r.normalTexture),r.occlusionTexture&&t.deleteTexture(r.occlusionTexture),r.customProgram&&t.deleteProgram(r.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 K)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};Ee.registerPlugin=Ge,Ee.getRegisteredPlugins=He;function Ue(n){return new TextEncoder().encode(n)}function gt(n,e){n.updateMatrixWorld(!0);let t=[];return n.traverse(i=>{if(i.geometry){let r=i.geometry,s=r.attributes.position;if(!s||s.count===0)return;let c=s.count,l=new Float32Array(c*3),u=i.matrixWorld.elements;for(let h=0;h<c;h++){let v=s.getX(h),y=s.getY(h),T=s.getZ(h);l[h*3]=u[0]*v+u[4]*y+u[8]*T+u[12],l[h*3+1]=u[1]*v+u[5]*y+u[9]*T+u[13],l[h*3+2]=u[2]*v+u[6]*y+u[10]*T+u[14]}let a;if(r.attributes.normal){let h=r.attributes.normal;a=new Float32Array(c*3);let v=new Float32Array(9);he(v,u);for(let y=0;y<c;y++){let T=h.getX(y),F=h.getY(y),C=h.getZ(y),w=v[0]*T+v[3]*F+v[6]*C,D=v[1]*T+v[4]*F+v[7]*C,B=v[2]*T+v[5]*F+v[8]*C,L=Math.hypot(w,D,B)||1;a[y*3]=w/L,a[y*3+1]=D/L,a[y*3+2]=B/L}}let o;if(r.attributes.uv){let h=r.attributes.uv;o=new Float32Array(c*2);for(let v=0;v<c;v++)o[v*2]=h.getX(v),o[v*2+1]=h.getY(v)}let f;if(r.index)f=r.index.array;else{f=c>65535?new Uint32Array(c):new Uint16Array(c);for(let h=0;h<c;h++)f[h]=h}let d="DefaultMaterial",p=[.8,.8,.8],m=.5,x=.1,b=0,E=0,P=1.5,A=1,R=[0,0,0];if(i.material){let h=i.material;d=h.name||`Material_${t.length}`,h.color&&(p=[h.color.r,h.color.g,h.color.b]),typeof h.roughness=="number"&&(m=h.roughness),typeof h.metalness=="number"&&(x=h.metalness),typeof h.clearcoat=="number"&&(b=h.clearcoat),typeof h.clearcoatRoughness=="number"&&(E=h.clearcoatRoughness),typeof h.ior=="number"&&(P=h.ior);let v=typeof h.opacity=="number"?h.opacity:1,y=typeof h.transmission=="number"?h.transmission:0;if(A=v*(1-y),h.emissive&&(h.emissive.r>0||h.emissive.g>0||h.emissive.b>0)){let T=h.emissiveIntensity??1;R=[h.emissive.r*T,h.emissive.g*T,h.emissive.b*T]}}let g,M=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 M=="function"){let h=e?.duration??4,v=e?.fps??4,y=Math.max(2,Math.round(h*v)+1),T=[],F=[],C=[],w=[],D=[i.position.x,i.position.y,i.position.z],B=[i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w],L=[i.scale.x,i.scale.y,i.scale.z],q=!1;for(let z=0;z<y;z++){let j=z/(y-1)*h;T.push(j);try{M(j)}catch{}F.push([i.position.x,i.position.y,i.position.z]),C.push([i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w]),w.push([i.scale.x,i.scale.y,i.scale.z]),(Math.abs(i.position.x-D[0])>1e-4||Math.abs(i.position.y-D[1])>1e-4||Math.abs(i.position.z-D[2])>1e-4||Math.abs(i.quaternion.x-B[0])>1e-4||Math.abs(i.quaternion.y-B[1])>1e-4||Math.abs(i.quaternion.z-B[2])>1e-4||Math.abs(i.quaternion.w-B[3])>1e-4||Math.abs(i.scale.x-L[0])>1e-4)&&(q=!0)}i.position.set(D[0],D[1],D[2]),i.quaternion.set(B[0],B[1],B[2],B[3]),i.scale.set(L[0],L[1],L[2]),q&&(g={times:T,translations:F,rotations:C,scales:w})}t.push({name:i.name||`Mesh_${t.length}`,positions:l,indices:f,normals:a,uvs:o,materialName:d,color:p,roughness:m,metallic:x,clearcoat:b,clearcoatRoughness:E,ior:P,opacity:A,emissiveColor:R,xrTraits:i.userData?.xr,timeSamples:g})}}),t}function Je(n){let e=[],t=n.gltf,i=n.bin,r=i instanceof ArrayBuffer?i:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),s=t.accessors||[],c=t.bufferViews||[],l=t.materials||[],u=t.meshes||[],a=t.nodes||[];function o(p){let m=s[p];if(!m)throw new Error(`Accessor ${p} not found`);let x=c[m.bufferView||0],b=(x.byteOffset||0)+(m.byteOffset||0),E=x.byteLength||0,P=r.slice(b,b+E);return{acc:m,buffer:P}}let f=new Map;if(a.length>0){let p=we(t);for(let m=0;m<p.length;m++)f.set(m,p[m])}function d(p,m,x,b){let E=u[p];if(!E)return;let P=new Float32Array(9);he(P,m);for(let A=0;A<(E.primitives||[]).length;A++){let R=E.primitives[A],g=R.attributes?.POSITION;if(g===void 0)continue;let{acc:M,buffer:h}=o(g),v=new Float32Array(h,0,M.count*3),y=new Float32Array(v.length);for(let I=0;I<M.count;I++){let S=v[I*3],U=v[I*3+1],_=v[I*3+2];y[I*3]=m[0]*S+m[4]*U+m[8]*_+m[12],y[I*3+1]=m[1]*S+m[5]*U+m[9]*_+m[13],y[I*3+2]=m[2]*S+m[6]*U+m[10]*_+m[14]}let T,F=R.attributes?.NORMAL;if(F!==void 0){let{acc:I,buffer:S}=o(F),U=new Float32Array(S,0,I.count*3);T=new Float32Array(U.length);for(let _=0;_<I.count;_++){let ee=U[_*3],re=U[_*3+1],X=U[_*3+2],ce=P[0]*ee+P[3]*re+P[6]*X,ie=P[1]*ee+P[4]*re+P[7]*X,te=P[2]*ee+P[5]*re+P[8]*X,k=Math.hypot(ce,ie,te)||1;T[_*3]=ce/k,T[_*3+1]=ie/k,T[_*3+2]=te/k}}let C,w=R.attributes?.TEXCOORD_0;if(w!==void 0){let{acc:I,buffer:S}=o(w);C=new Float32Array(S,0,I.count*2)}let D;if(R.indices!==void 0){let{acc:I,buffer:S}=o(R.indices);I.componentType===5125?D=new Uint32Array(S,0,I.count):D=new Uint16Array(S,0,I.count);let U=M.count;for(let _ of D)if(_>=U)throw new Error(`SecurityError: Index buffer value (${_}) out of vertex bounds [0, ${U}).`)}else{let I=M.count;D=I>65535?new Uint32Array(I):new Uint16Array(I);for(let S=0;S<I;S++)D[S]=S}let B="DefaultMaterial",L=[.8,.8,.8],q=.5,z=.1,j=0,H=0,$=1.5,G=1,N=[0,0,0];if(R.material!==void 0&&l[R.material]){let I=l[R.material];B=I.name||`Material_${R.material}`;let S=I.pbrMetallicRoughness||{},U=1;Array.isArray(S.baseColorFactor)&&(L=[S.baseColorFactor[0],S.baseColorFactor[1],S.baseColorFactor[2]],typeof S.baseColorFactor[3]=="number"&&(U=S.baseColorFactor[3])),typeof S.roughnessFactor=="number"&&(q=S.roughnessFactor),typeof S.metallicFactor=="number"&&(z=S.metallicFactor),Array.isArray(I.emissiveFactor)&&I.emissiveFactor.length>=3&&(N=[I.emissiveFactor[0],I.emissiveFactor[1],I.emissiveFactor[2]]);let _=I.extensions||{};_.KHR_materials_clearcoat&&(j=_.KHR_materials_clearcoat.clearcoatFactor??0,H=_.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),_.KHR_materials_ior&&typeof _.KHR_materials_ior.ior=="number"&&($=_.KHR_materials_ior.ior);let ee=_.KHR_materials_transmission?.transmissionFactor??0;G=U*(1-ee)}let W=(E.primitives||[]).length>1?`${x}_p${A}`:x;e.push({name:W,positions:y,indices:D,normals:T,uvs:C,materialName:B,color:L,roughness:q,metallic:z,clearcoat:j,clearcoatRoughness:H,ior:$,opacity:G,emissiveColor:N,xrTraits:b?.xr||E.extras?.xr})}}if(a.length>0)for(let p=0;p<a.length;p++){let m=a[p];if(m.mesh!==void 0&&m.mesh<u.length){let x=f.get(p)||Z(),b=m.name||u[m.mesh].name||`Node_${p}`;d(m.mesh,x,b,m.extras)}}else{let p=Z();for(let m=0;m<u.length;m++){let x=u[m].name||`Mesh_${m}`;d(m,p,x,u[m].extras)}}return e}function Ie(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 je(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function V(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 Qe(n){let e=n.length/3,t=new Array(e);for(let i=0;i<e;i++)t[i]=`(${V(n[i*3])}, ${V(n[i*3+1])}, ${V(n[i*3+2])})`;return t.join(", ")}function vt(n,e){let t=new Array(e);for(let i=0;i<e;i++)t[i]=`(${V(n[i*2])}, ${V(1-n[i*2+1])})`;return t.join(", ")}function xt(n){return Array.from(n).join(", ")}function _e(n){let e=new Map;for(let u of n){let a=Ie(u.materialName,"DefaultMaterial");e.has(a)||e.set(a,{color:u.color||[.8,.8,.8],roughness:u.roughness??.5,metallic:u.metallic??0,clearcoat:u.clearcoat??0,clearcoatRoughness:u.clearcoatRoughness??0,ior:u.ior??1.5,opacity:u.opacity??1,emissiveColor:u.emissiveColor||[0,0,0]})}let t=0,i=null;for(let u of n){if(u.timeSamples&&u.timeSamples.times.length>0){let a=u.timeSamples.times[u.timeSamples.times.length-1];a>t&&(t=a)}u.xrTraits?.anchor&&!i&&(i=u.xrTraits.anchor==="vertical"||u.xrTraits.anchor==="wall"?"vertical":"horizontal")}let r="";t>0&&(r=`startTimeCode = 0
209
- endTimeCode = ${V(t)}
232
+ void main(){fragColor=uColorId;}`;function Ye(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 ke(n,e,t){let r=Ye(n,35633,e),i=Ye(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 Be(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var Ze=["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 tt(){let n=ge().xrDepthShader;return{fs:At.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Ze,...n.uniformNames]:Ze}}function Et(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 Ne(n,e,t,r,i,s,a){if(r===void 0||!e.accessors?.[r])return null;let u=e.accessors[r],l=e.bufferViews[u.bufferView],c=(l.byteOffset||0)+(u.byteOffset||0),o=l.byteStride&&l.byteStride>s*4?l.byteStride>>2:s,h;if(o===s)h=new Float32Array(t,c,u.count*s);else{h=new Float32Array(u.count*s);let R=new Float32Array(t,l.byteOffset||0,Math.floor(l.byteLength/4)),f=(u.byteOffset||0)>>2;for(let m=0;m<u.count;m++){let p=f+m*o;for(let L=0;L<s;L++)h[m*s+L]=R[p+L]}}let g=n.createBuffer();return a.push(g),n.bindBuffer(34962,g),n.bufferData(34962,h,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),h}var Ot=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),nt=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function je(n,e,t=nt,r){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:i}=e,s=Me("meshopt");s?.decodeBufferViews&&s.decodeBufferViews(i,e);let a=e.bin,u=[],l=[],c=i.extensions?.KHR_materials_variants;if(c&&Array.isArray(c.variants))for(let D of c.variants)D&&typeof D.name=="string"&&l.push(D.name);let o=Le(i),h=[];if(Array.isArray(i.nodes))for(let D=0;D<i.nodes.length;D++){let M=i.nodes[D];M.mesh!==void 0&&i.meshes&&i.meshes[M.mesh]&&h.push({node:M,nodeIdx:D,meshIdx:M.mesh})}let g=h.length>0?h:(i.meshes||[]).map((D,M)=>({node:D,nodeIdx:-1,meshIdx:M})),R=[];if(Array.isArray(e.lights)&&e.lights.length>0)R.push(...e.lights);else if(i.extensions?.KHR_lights_punctual?.lights){let D=i.extensions.KHR_lights_punctual.lights;for(let M of D){let d=M.type==="directional"?"directional":M.type==="point"?"point":"ambient";R.push({type:d,color:M.color||[1,1,1],intensity:M.intensity!==void 0?M.intensity:1})}}if(R.length===0&&(R.push({type:"ambient",color:[1,1,1],intensity:.35}),R.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),g.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${g.length}`);let f=[];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 D=0;D<i.textures.length;D++){let M=i.textures[D],d=i.images[M.source];if(d){let C=n.createTexture();if(n.bindTexture(3553,C),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),d.bufferView!==void 0){let _=i.bufferViews[d.bufferView],T=a.slice(_.byteOffset||0,(_.byteOffset||0)+_.byteLength),O=new Blob([T],{type:d.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(O).then(U=>{n.bindTexture(3553,C),n.texImage2D(3553,0,6408,6408,5121,U),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(d.uri){let _=Et(d.uri);if(_){let T=new Image;T.crossOrigin="anonymous",T.referrerPolicy="no-referrer",T.onload=()=>{n.bindTexture(3553,C),n.texImage2D(3553,0,6408,6408,5121,T),n.generateMipmap(3553),r?.()},T.src=_}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",d.uri)}f.push(C)}else f.push(null)}}let m=[1/0,1/0,1/0],p=[-1/0,-1/0,-1/0],L=0,F=0;for(let D=0;D<g.length;D++){let M=g[D],d=i.meshes[M.meshIdx],C=M.nodeIdx>=0?o[M.nodeIdx]:Z(),_=new Float32Array(9);de(_,C);let T={name:M.node.name||d.name||`Mesh_${M.meshIdx}`,nodeIndex:M.nodeIdx,transform:C,normalMatrix:_,primitives:[],extras:M.node.extras||d.extras},O=M.node?.extensions?.EXT_mesh_gpu_instancing;if(O&&O.attributes&&typeof O.attributes=="object"){let U=O.attributes,$=U.TRANSLATION!==void 0?i.accessors?.[U.TRANSLATION]:null,B=U.ROTATION!==void 0?i.accessors?.[U.ROTATION]:null,H=U.SCALE!==void 0?i.accessors?.[U.SCALE]:null,G=U._COLOR_0!==void 0?i.accessors?.[U._COLOR_0]:null,X=Number($?.count??B?.count??H?.count??0);if(!Number.isFinite(X)||X<0||X>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${X}`);if(X>0){let q=(z,K)=>{if(!z||z.bufferView===void 0||!i.bufferViews?.[z.bufferView])return null;let k=(i.bufferViews[z.bufferView].byteOffset||0)+(z.byteOffset||0);return Mt(a,k,X*K)},ee=q($,3),y=q(B,4),P=q(H,3),N=G?.type==="VEC4"?4:3,V=q(G,N),j=new Float32Array(X*16),Q=Z();for(let z=0;z<X;z++){let K=ee?[ee[z*3],ee[z*3+1],ee[z*3+2]]:[0,0,0],se=y?[y[z*4],y[z*4+1],y[z*4+2],y[z*4+3]]:[0,0,0,1],k=P?[P[z*3],P[z*3+1],P[z*3+2]]:[1,1,1];we(Q,se,K,k),j.set(Q,z*16)}if(T.instanceMatrices=j,V){let z=new Float32Array(X*3);for(let K=0;K<X;K++)z[K*3]=V[K*N],z[K*3+1]=V[K*N+1],z[K*3+2]=V[K*N+2];T.instanceColors=z}}}for(let U of d.primitives||[]){if(U.extensions?.KHR_draco_mesh_compression){let Y=Me("draco");Y&&Y.decodePrimitive(i,U,a)}let $=[],B=n.createVertexArray();n.bindVertexArray(B);let H=i.accessors[U.attributes.POSITION],G=Number(H?.count??0);if(!Number.isFinite(G)||G<0||L+G>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(L+=G,H?.min&&H?.max){let Y=oe=>{for(let ce=0;ce<3;ce++){let pe=oe[12+ce],Ae=oe[12+ce];for(let ve=0;ve<3;ve++){let Ee=oe[ve*4+ce]*H.min[ve],Se=oe[ve*4+ce]*H.max[ve];pe+=Ee<Se?Ee:Se,Ae+=Ee>Se?Ee:Se}pe<m[ce]&&(m[ce]=pe),Ae>p[ce]&&(p[ce]=Ae)}};if(T.instanceMatrices&&T.instanceMatrices.length>=16){let oe=T.instanceMatrices.length>>4,ce=Z();for(let pe=0;pe<oe;pe++){let Ae=T.instanceMatrices.subarray(pe*16,pe*16+16);te(ce,C,Ae),Y(ce)}}else Y(C)}let X=Ne(n,i,a,U.attributes.POSITION,0,3,$);Ne(n,i,a,U.attributes.NORMAL,1,3,$),Ne(n,i,a,U.attributes.TEXCOORD_0,2,2,$);let q=0,ee=5123,y=null;if(U.indices!==void 0){let Y=i.accessors[U.indices],ce=(i.bufferViews[Y.bufferView].byteOffset||0)+(Y.byteOffset||0);if(q=Number(Y.count??0),!Number.isFinite(q)||q<0||F+q>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);F+=q,ee=Y.componentType===5125?5125||5125:5123||5123;let pe=n.createBuffer();$.push(pe),n.bindBuffer(34963,pe),Y.componentType===5125?(y=new Uint32Array(a,ce,Y.count),n.bufferData(34963,y,35044)):(y=new Uint16Array(a,ce,Y.count),n.bufferData(34963,y,35044))}else q=H.count;let P={};for(let Y of ne)if(Y.onBuildPrimitiveVAO){let oe=Y.onBuildPrimitiveVAO(n,B,U,i,a);oe&&(P[Y.name]=oe)}n.bindVertexArray(null);let N=i.materials&&U.material!==void 0?i.materials[U.material]:null,V=tt(),j=et,Q=V.fs,z=!1;for(let Y of ne)if(Y.onResolveShader){let oe=Y.onResolveShader(U,N,j,Q);oe&&(j=oe.vs,Q=oe.fs,z=!0)}let K=z?ke(n,j,Q):null,se=K?Be(n,K,V.uniforms):null,k=N?.pbrMetallicRoughness,ae=k?.baseColorFactor||[.8,.8,.8,1],re=k?.metallicFactor??.1,le=k?.roughnessFactor??.5,me=N?.extensions?.KHR_materials_clearcoat,ie=me?me.clearcoatFactor??1:0,J=Math.max(.04,me?.clearcoatRoughnessFactor??.04),he=k?.baseColorTexture!==void 0&&f[k.baseColorTexture.index]?f[k.baseColorTexture.index]:null,ue=k?.metallicRoughnessTexture!==void 0&&f[k.metallicRoughnessTexture.index]?f[k.metallicRoughnessTexture.index]:null,fe=N?.normalTexture!==void 0&&f[N.normalTexture.index]?f[N.normalTexture.index]:null,be=N?.normalTexture?.scale??1,ye=N?.occlusionTexture!==void 0&&f[N.occlusionTexture.index]?f[N.occlusionTexture.index]:null,Te=N?.occlusionTexture?.strength??1,gt=!!(N?.extensions?.KHR_materials_transmission||P.materials?.isTransmissive),Xe=U.extensions?.KHR_materials_variants?.mappings,yt=Array.isArray(Xe)?Xe.filter(Y=>Y&&typeof Y.material=="number"&&Array.isArray(Y.variants)).map(Y=>({material:Y.material|0,variants:Y.variants.map(oe=>Number(oe)|0)})):void 0;T.primitives.push({vao:B,indexCount:q,indexType:ee,baseColor:ae,metallic:re,roughness:le,clearcoat:ie,clearcoatRoughness:J,positions:X,indices:y,texture:he,metallicRoughnessTexture:ue,normalTexture:fe,occlusionTexture:ye,normalScale:be,occlusionStrength:Te,buffers:$,materialIndex:U.material,defaultMaterialIndex:U.material,variantMappings:yt,pluginData:P,customProgram:K,customUniforms:se,isTransmissive:gt})}u.push(T)}isFinite(m[0])||(m=[-1,-1,-1]),isFinite(p[0])||(p=[1,1,1]);let A=[(m[0]+p[0])/2,(m[1]+p[1])/2,(m[2]+p[2])/2],I=p[0]-m[0],x=p[1]-m[1],v=p[2]-m[2],E=Math.max(Math.hypot(I,x,v)/2,.5),b=[m[0],m[1],m[2]],S=[p[0],p[1],p[2]],w=e.animations;if(!w){for(let D of ne)if(D.onParseGLB?.(e),e.animations){w=e.animations;break}}return w||(w=[]),{meshes:u,bounds:{center:A,radius:E,min:b,max:S},lights:R,animations:w,worldMatrices:o,gpuTextures:f,availableVariants: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=Z();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.gpuTextures=[];this.availableVariants=[];this.activeVariantName=null;this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=Z();this.viewMatrix=Z();this.modelMatrix=Z();this.mvpMatrix=Z();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:Z(),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.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let u=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!u)throw new Error("WebGL2 not supported");this.gl=u;let l=tt();this.renderProg=ke(u,et,l.fs),this.pickProg=ke(u,wt,Rt),this.uRender=Be(u,this.renderProg,l.uniforms),this.uPick=Be(u,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){vt(e,t)}static getDecoder(e){return Me(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:u,gpuTextures:l,availableVariants:c}=je(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=u||[],this.gpuTextures=l||[],this.availableVariants=c||[],this.gltf=e.gltf,this.activeVariantName&&this.applyVariantMaterial(this.activeVariantName),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let h of e.gltf.nodes)this.initialNodeTransforms.push({t:h.translation?[h.translation[0],h.translation[1],h.translation[2]]:[0,0,0],r:h.rotation?[h.rotation[0],h.rotation[1],h.rotation[2],h.rotation[3]]:[0,0,0,1],s:h.scale?[h.scale[0],h.scale[1],h.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let h of ne)h.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 o=e.exposure??e.environmentIntensity??e.gltf?.extras?.exposure??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.exposure??e.gltf?.asset?.extras?.environmentIntensity;o!==void 0&&(this.envIntensity=Math.max(0,Number(o))),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(Je(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(Re(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Re(e),{meshes:i}=je(this.gl,r,nt,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],de(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),de(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],a=[],u=[];for(let l of this.lights){let c=l.color||[1,1,1],o=l.intensity!==void 0?l.intensity:1;if(l.type==="ambient")r=[c[0]*o,c[1]*o,c[2]*o];else if(l.type==="directional"&&i.length<6){let h=l.direction||[.5,1,.8];i.push(h[0],h[1],h[2]),s.push(c[0]*o,c[1]*o,c[2]*o)}else if(l.type==="point"&&a.length<6){let h=l.position||[0,0,0];a.push(h[0],h[1],h[2]),u.push(c[0]*o,c[1]*o,c[2]*o)}}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,u)),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 ne)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ne)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(o=>o.primitives.filter(h=>h.materialIndex===r||e.length===1&&h.materialIndex===void 0)),s=i[0],a=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],u=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,l=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,c={baseColorFactor:a,metallicFactor:u,roughnessFactor:l,setBaseColorFactor:o=>{let h=[o[0],o[1],o[2],o[3]??1];c.baseColorFactor=h,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=h);for(let g of i)g.baseColor=h;this.render()},setMetallicFactor:o=>{c.metallicFactor=o,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=o);for(let h of i)h.metallic=o;this.render()},setRoughnessFactor:o=>{c.roughnessFactor=o,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=o);for(let h of i)h.roughness=o;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:c}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e===""||e==="default",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let s of this.meshes)for(let a of s.primitives){let u=a.defaultMaterialIndex;if(!t&&Array.isArray(a.variantMappings)){for(let h of a.variantMappings)if(Array.isArray(h.variants)&&h.variants.includes(r)){u=h.material;break}}if(u===void 0||!i[u]){a.materialIndex=void 0,a.baseColor=[.8,.8,.8,1],a.metallic=.1,a.roughness=.5,a.clearcoat=0,a.clearcoatRoughness=.04,a.texture=null,a.metallicRoughnessTexture=null,a.normalTexture=null,a.normalScale=1,a.occlusionTexture=null,a.occlusionStrength=1,a.isTransmissive=!1;continue}let l=i[u];a.materialIndex=u;let c=l.pbrMetallicRoughness;a.baseColor=c?.baseColorFactor?[c.baseColorFactor[0],c.baseColorFactor[1],c.baseColorFactor[2],c.baseColorFactor[3]??1]:[.8,.8,.8,1],a.metallic=c?.metallicFactor??.1,a.roughness=c?.roughnessFactor??.5;let o=l.extensions?.KHR_materials_clearcoat;a.clearcoat=o?o.clearcoatFactor??1:0,a.clearcoatRoughness=Math.max(.04,o?.clearcoatRoughnessFactor??.04),a.texture=c?.baseColorTexture!==void 0&&this.gpuTextures[c.baseColorTexture.index]?this.gpuTextures[c.baseColorTexture.index]:null,a.metallicRoughnessTexture=c?.metallicRoughnessTexture!==void 0&&this.gpuTextures[c.metallicRoughnessTexture.index]?this.gpuTextures[c.metallicRoughnessTexture.index]:null,a.normalTexture=l.normalTexture!==void 0&&this.gpuTextures[l.normalTexture.index]?this.gpuTextures[l.normalTexture.index]:null,a.normalScale=l.normalTexture?.scale??1,a.occlusionTexture=l.occlusionTexture!==void 0&&this.gpuTextures[l.occlusionTexture.index]?this.gpuTextures[l.occlusionTexture.index]:null,a.occlusionStrength=l.occlusionTexture?.strength??1,a.isTransmissive=!!(l.extensions?.KHR_materials_transmission||a.pluginData?.materials?.isTransmissive)}return!0}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of ne)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=Z();te(r,this.projMatrix,this.viewMatrix);let[i,s,a]=e,u=t?t[0]:0,l=t?t[1]:0,c=t?t[2]:0,o=this.modelRootMatrix;o&&(i=o[0]*e[0]+o[4]*e[1]+o[8]*e[2]+o[12],s=o[1]*e[0]+o[5]*e[1]+o[9]*e[2]+o[13],a=o[2]*e[0]+o[6]*e[1]+o[10]*e[2]+o[14],t&&(u=o[0]*t[0]+o[4]*t[1]+o[8]*t[2],l=o[1]*t[0]+o[5]*t[1]+o[9]*t[2],c=o[2]*t[0]+o[6]*t[1]+o[10]*t[2]));let h=r[0]*i+r[4]*s+r[8]*a+r[12],g=r[1]*i+r[5]*s+r[9]*a+r[13],R=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 m=h/f,p=g/f,L=R/f,F=this.canvas.getBoundingClientRect(),A=F.width||this.canvas.clientWidth||this.canvas.width||300,I=F.height||this.canvas.clientHeight||this.canvas.height||150,x=(m*.5+.5)*A,v=(-p*.5+.5)*I,E=m>=-1.1&&m<=1.1&&p>=-1.1&&p<=1.1&&L>=-1&&L<=1;if(E&&t){let b=this.customTarget||this.bounds.center,S=b[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),w=b[1]+this.currDistance*Math.sin(this.currPhi),D=b[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),M=[i-S,s-w,a-D];u*M[0]+l*M[1]+c*M[2]>.05&&(E=!1)}return{x,y:v,z:L,visible:E}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}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]],u=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],l=this.customTarget?[...this.customTarget]:[...this.bounds.center],c=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;l[0]+=(-i*a[0]+s*u[0])*c,l[1]+=(-i*a[1]+s*u[1])*c,l[2]+=(-i*a[2]+s*u[2])*c,this.customTarget=l}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,u=i.width>0?Math.floor((e-i.left)*(s/i.width)):Math.floor(e),l=i.height>0?Math.floor((t-i.top)*(a/i.height)):Math.floor(t);return this.performMeshPick(u,l,!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 u=Z();te(u,this.projMatrix,this.viewMatrix);let l=[],c=Math.max(0,Math.min(s-1,e)),o=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 b=0;b<this.meshes.length;b++){let S=this.meshes[b];if(S.visible===!1||S.isPluginMesh)continue;let w=b+1,D=(w&255)/255,M=(w>>8&255)/255,d=(w>>16&255)/255;i.uniform4f(this.uPick.uColorId,D,M,d,1),te(this.modelMatrix,this.modelRootMatrix,S.transform);let C=S.instanceMatrices;if(C&&C.length>=16){let _=C.length>>4,T=Z();for(let O of S.primitives){i.bindVertexArray(O.vao);for(let U=0;U<_;U++)te(T,this.modelMatrix,C.subarray(U*16,U*16+16)),te(this.mvpMatrix,u,T),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),O.indices?i.drawElements(4,O.indexCount,O.indexType,0):i.drawArrays(4,0,O.indexCount)}}else{te(this.mvpMatrix,u,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let _ of S.primitives)i.bindVertexArray(_.vao),_.indices?i.drawElements(4,_.indexCount,_.indexType,0):i.drawArrays(4,0,_.indexCount)}}let v=new Uint8Array(4);i.readPixels(c,o,1,1,6408,5121,v),i.bindFramebuffer(36160,null);let E=v[0]+(v[1]<<8)+(v[2]<<16);E>0&&E<=this.meshes.length&&(l=[this.meshes[E-1]])}l.length===0&&(l=this.meshes.filter(v=>v.visible!==!1));let h=null,g=1/0,R=[0,0,0],f=[0,1,0],m=this.customTarget||this.bounds.center,p=m[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),L=m[1]+this.currDistance*Math.sin(this.currPhi),F=m[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),A=Z();for(let v of l){te(A,this.modelRootMatrix,v.transform);let E=v.instanceMatrices,b=E&&E.length>=16?E.length>>4:1;for(let S=0;S<b;S++){E&&E.length>=16?te(this.modelMatrix,A,E.subarray(S*16,S*16+16)):this.modelMatrix.set(A),te(this.mvpMatrix,u,this.modelMatrix);let w=Z();if(!We(w,this.mvpMatrix))continue;let D=(c+.5)/s*2-1,M=(o+.5)/a*2-1,d=[0,0,0],C=[0,0,0];Ue(d,D,M,-1,w),Ue(C,D,M,1,w);let _=C[0]-d[0],T=C[1]-d[1],O=C[2]-d[2],U=Math.hypot(_,T,O)||1,$=_/U,B=T/U,H=O/U,G={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((q=>{for(let ee of v.primitives){if(!ee.positions)continue;let y=ee.positions,P=ee.indices,N=Math.floor(P?P.length/3:y.length/9);for(let V=0;V<N;V++){let j=P?P[V*3]:V*3,Q=P?P[V*3+1]:V*3+1,z=P?P[V*3+2]:V*3+2;$e(d[0],d[1],d[2],$,B,H,y[j*3],y[j*3+1],y[j*3+2],y[Q*3],y[Q*3+1],y[Q*3+2],y[z*3],y[z*3+1],y[z*3+2],G,q)}}})(1e-4),isFinite(G.distance)){let q=G.point[0],ee=G.point[1],y=G.point[2],P=this.modelMatrix,N=P[0]*q+P[4]*ee+P[8]*y+P[12],V=P[1]*q+P[5]*ee+P[9]*y+P[13],j=P[2]*q+P[6]*ee+P[10]*y+P[14],Q=N-p,z=V-L,K=j-F,se=Math.hypot(Q,z,K);if(se<g){de(this.normalMatrix,this.modelMatrix);let k=this.normalMatrix,ae=G.normal[0],re=G.normal[1],le=G.normal[2],me=k[0]*ae+k[3]*re+k[6]*le,ie=k[1]*ae+k[4]*re+k[7]*le,J=k[2]*ae+k[5]*re+k[8]*le,he=Math.hypot(me,ie,J)||1;me/=he,ie/=he,J/=he,me*Q+ie*z+J*K>0&&(me=-me,ie=-ie,J=-J),h=v,g=Math.round(se*1e3)/1e3,R=[Math.round(N*1e3)/1e3,Math.round(V*1e3)/1e3,Math.round(j*1e3)/1e3],f=[Math.round(me*1e3)/1e3,Math.round(ie*1e3)/1e3,Math.round(J*1e3)/1e3]}}}}if(!h)return null;let x={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:g,hitPoint:R,normal:f,screenX:e,screenY:t};if(r){for(let v of ne)v.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,u=(s+.5)/a*2-1;return Math.floor((u*.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);De(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);Pe(this.viewMatrix,[i,s,a],r,[0,1,0]),te(this.mvpMatrix,this.projMatrix,this.viewMatrix),de(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 ne)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 ne)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 ne)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 ne)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 u=e?.transform?.inverse?.matrix||this.viewMatrix,l=e?.projectionMatrix||this.projMatrix,c=e?.transform?.position,o=c?[c.x,c.y,c.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:u,projMatrix:l,eyePos:o,viewport:i,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:s})}render(e){if(!e&&this.stereoSBS){let I=Math.max(2,this.canvas.width||2),x=Math.max(1,this.canvas.height||1),v=Math.max(1,Math.floor(I*.5)),E=Math.max(1,I-v),b=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),S=this.customTarget||this.bounds.center,w=S[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),D=S[1]+this.currDistance*Math.sin(this.currPhi),M=S[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),d=Math.cos(this.currTheta),C=-Math.sin(this.currTheta),_=.032,T=Z(),O=Z(),U=[w-d*_,D,M-C*_],$=[S[0]-d*_*.25,S[1],S[2]-C*_*.25];De(T,this.fov,v/x,.1,b),Pe(O,U,$,[0,1,0]);let B=Z(),H=Z(),G=[w+d*_,D,M+C*_],X=[S[0]+d*_*.25,S[1],S[2]+C*_*.25];De(B,this.fov,E/x,.1,b),Pe(H,G,X,[0,1,0]),this.render({viewMatrix:O,projMatrix:T,eyePos:U,viewport:[0,0,v,x],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:H,projMatrix:B,eyePos:G,viewport:[v,0,E,x],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,I,x);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 u=Z(),l=e?.viewMatrix??this.viewMatrix;te(u,e?.projMatrix??this.projMatrix,l);let c=ge().xrDepthShader,o=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:this.toneMapping==="aces"?3:this.toneMapping==="agx"?4:0,h=this.customTarget||this.bounds.center,g=e?e.eyePos[0]:h[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),R=e?e.eyePos[1]:h[1]+this.currDistance*Math.sin(this.currPhi),f=e?e.eyePos[2]:h[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let I of ne)I.onBeforeDrawScene?.(this,t,u,[g,R,f],o);let m=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&m===0)return;let p=e?.eye||"none",L=!1,F=m>0?[...this.backdropMeshes,...this.meshes]:this.meshes,A=I=>{for(let x=0;x<F.length;x++){let v=F[x];if(v.visible===!1)continue;let E=this.selectedMeshName!==""&&v.name===this.selectedMeshName;x<m||v.worldSpace===!0||v.name==="__xr_reticle__"?this.modelMatrix.set(v.transform):te(this.modelMatrix,this.modelRootMatrix,v.transform),te(this.mvpMatrix,u,this.modelMatrix),de(v.normalMatrix,this.modelMatrix);let b=v.extras?.xr?.stereo||v.userData?.xr?.stereo,S=0,w=0,D=1,M=1;b==="sbs"?(D=.5,S=p==="right"?.5:0):b==="ou"&&(M=.5,w=p==="right"?.5:0);for(let d of v.primitives){let C=!!d.isTransmissive;if(!I&&C){L=!0;continue}if(I&&!C)continue;let _=d.customProgram||this.renderProg,T=d.customUniforms||this.uRender;t.useProgram(_),t.uniform1i(T.uToneMapping,o),t.uniform1f(T.uEnvIntensity,this.envIntensity),t.uniform3f(T.uCameraPos,g,R,f),t.uniform1f(T.uEmissive,E?1:0),t.uniformMatrix4fv(T.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(T.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(T.uNormalMatrix,!1,v.normalMatrix),T.uUvTransform&&t.uniform4f(T.uUvTransform,S,w,D,M),T.uViewportSize&&t.uniform2f(T.uViewportSize,Math.max(1,s),Math.max(1,a)),c?.bind(t,T,this.xrDepthState,l,[r,i,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(T.uEnvironmentMap,4),t.uniform1i(T.uHasEnvironmentMap,1)):t.uniform1i(T.uHasEnvironmentMap,0),this.bindLights(T),T.uSectionEnabled&&t.uniform1i(T.uSectionEnabled,0);for(let U of ne)U.onBeforeDrawPrimitive?.(t,_,d,v,this.worldMatrices||[],this.gltf);t.uniform4fv(T.uBaseColor,d.baseColor),t.uniform1f(T.uMetallic,d.metallic),t.uniform1f(T.uRoughness,d.roughness),T.uClearcoat&&t.uniform2f(T.uClearcoat,d.clearcoat??0,d.clearcoatRoughness??.04),d.texture?(t.activeTexture(33984),t.bindTexture(3553,d.texture),t.uniform1i(T.uBaseColorTexture,0),t.uniform1i(T.uHasTexture,1)):t.uniform1i(T.uHasTexture,0),d.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,d.metallicRoughnessTexture),t.uniform1i(T.uMetallicRoughnessTexture,1),t.uniform1i(T.uHasMetallicRoughnessTexture,1)):t.uniform1i(T.uHasMetallicRoughnessTexture,0),d.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,d.normalTexture),t.uniform1i(T.uNormalTexture,2),t.uniform1i(T.uHasNormalTexture,1),t.uniform1f(T.uNormalScale,d.normalScale)):t.uniform1i(T.uHasNormalTexture,0),d.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,d.occlusionTexture),t.uniform1i(T.uOcclusionTexture,3),t.uniform1i(T.uHasOcclusionTexture,1),t.uniform1f(T.uOcclusionStrength,d.occlusionStrength)):t.uniform1i(T.uHasOcclusionTexture,0),t.bindVertexArray(d.vao);let O=v.instanceMatrices;if(O&&O.length>=16){let U=O.length>>4,$=v.instanceColors,B=Z(),H=new Float32Array(9),G=[d.baseColor[0],d.baseColor[1],d.baseColor[2],d.baseColor[3]];for(let X=0;X<U;X++)te(B,this.modelMatrix,O.subarray(X*16,X*16+16)),te(this.mvpMatrix,u,B),de(H,B),t.uniformMatrix4fv(T.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(T.uModel,!1,B),t.uniformMatrix3fv(T.uNormalMatrix,!1,H),$&&(G[0]=d.baseColor[0]*$[X*3],G[1]=d.baseColor[1]*$[X*3+1],G[2]=d.baseColor[2]*$[X*3+2],G[3]=d.baseColor[3],t.uniform4fv(T.uBaseColor,G)),d.indices?t.drawElements(4,d.indexCount,d.indexType,0):t.drawArrays(4,0,d.indexCount)}else d.indices?t.drawElements(4,d.indexCount,d.indexType,0):t.drawArrays(4,0,d.indexCount)}}};if(A(!1),L){for(let I of ne)I.onBeforeTransmissivePass?.(t,this);A(!0)}for(let I of ne)I.onAfterRender?.(t,this,u)}disposeMeshListGpuResources(e,t){let r=this.gl,i=new Set,s=a=>{a&&!i.has(a)&&(i.add(a),r.deleteTexture(a))};for(let a of e)for(let u of a.primitives){if(u.vao&&r.deleteVertexArray(u.vao),u.buffers)for(let l of u.buffers)r.deleteBuffer(l);s(u.texture),s(u.metallicRoughnessTexture),s(u.normalTexture),s(u.occlusionTexture),u.customProgram&&r.deleteProgram(u.customProgram)}if(t)for(let a of t)s(a)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of ne)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=qe,Ce.getRegisteredPlugins=Ke;function Ge(n){return new TextEncoder().encode(n)}function St(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,u=new Float32Array(a*3),l=r.matrixWorld.elements;for(let b=0;b<a;b++){let S=s.getX(b),w=s.getY(b),D=s.getZ(b);u[b*3]=l[0]*S+l[4]*w+l[8]*D+l[12],u[b*3+1]=l[1]*S+l[5]*w+l[9]*D+l[13],u[b*3+2]=l[2]*S+l[6]*w+l[10]*D+l[14]}let c;if(i.attributes.normal){let b=i.attributes.normal;c=new Float32Array(a*3);let S=new Float32Array(9);de(S,l);for(let w=0;w<a;w++){let D=b.getX(w),M=b.getY(w),d=b.getZ(w),C=S[0]*D+S[3]*M+S[6]*d,_=S[1]*D+S[4]*M+S[7]*d,T=S[2]*D+S[5]*M+S[8]*d,O=Math.hypot(C,_,T)||1;c[w*3]=C/O,c[w*3+1]=_/O,c[w*3+2]=T/O}}let o;if(i.attributes.uv){let b=i.attributes.uv;o=new Float32Array(a*2);for(let S=0;S<a;S++)o[S*2]=b.getX(S),o[S*2+1]=b.getY(S)}let h;if(i.index)h=i.index.array;else{h=a>65535?new Uint32Array(a):new Uint16Array(a);for(let b=0;b<a;b++)h[b]=b}let g="DefaultMaterial",R=[.8,.8,.8],f=.5,m=.1,p=0,L=0,F=1.5,A=1,I=[0,0,0];if(r.material){let b=r.material;g=b.name||`Material_${t.length}`,b.color&&(R=[b.color.r,b.color.g,b.color.b]),typeof b.roughness=="number"&&(f=b.roughness),typeof b.metalness=="number"&&(m=b.metalness),typeof b.clearcoat=="number"&&(p=b.clearcoat),typeof b.clearcoatRoughness=="number"&&(L=b.clearcoatRoughness),typeof b.ior=="number"&&(F=b.ior);let S=typeof b.opacity=="number"?b.opacity:1,w=typeof b.transmission=="number"?b.transmission:0;if(A=S*(1-w),b.emissive&&(b.emissive.r>0||b.emissive.g>0||b.emissive.b>0)){let D=b.emissiveIntensity??1;I=[b.emissive.r*D,b.emissive.g*D,b.emissive.b*D]}}let x,v=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 v=="function"){let b=e?.duration??4,S=e?.fps??4,w=Math.max(2,Math.round(b*S)+1),D=[],M=[],d=[],C=[],_=[r.position.x,r.position.y,r.position.z],T=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],O=[r.scale.x,r.scale.y,r.scale.z],U=!1;for(let $=0;$<w;$++){let B=$/(w-1)*b;D.push(B);try{v(B)}catch{}M.push([r.position.x,r.position.y,r.position.z]),d.push([r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w]),C.push([r.scale.x,r.scale.y,r.scale.z]),(Math.abs(r.position.x-_[0])>1e-4||Math.abs(r.position.y-_[1])>1e-4||Math.abs(r.position.z-_[2])>1e-4||Math.abs(r.quaternion.x-T[0])>1e-4||Math.abs(r.quaternion.y-T[1])>1e-4||Math.abs(r.quaternion.z-T[2])>1e-4||Math.abs(r.quaternion.w-T[3])>1e-4||Math.abs(r.scale.x-O[0])>1e-4)&&(U=!0)}r.position.set(_[0],_[1],_[2]),r.quaternion.set(T[0],T[1],T[2],T[3]),r.scale.set(O[0],O[1],O[2]),U&&(x={times:D,translations:M,rotations:d,scales:C})}let E=r;if(E.isInstancedMesh&&typeof E.count=="number"&&E.count>0&&E.instanceMatrix?.array){let b=Math.min(1e3,Math.floor(E.count)),S=E.instanceMatrix.array,w=E.instanceColor?.array,D=r.name||`Mesh_${t.length}`,M=new Float32Array(16),d=new Float32Array(9);for(let C=0;C<b;C++){let _=S.subarray(C*16,(C+1)*16);te(M,l,_);let T=new Float32Array(a*3);for(let B=0;B<a;B++){let H=s.getX(B),G=s.getY(B),X=s.getZ(B);T[B*3]=M[0]*H+M[4]*G+M[8]*X+M[12],T[B*3+1]=M[1]*H+M[5]*G+M[9]*X+M[13],T[B*3+2]=M[2]*H+M[6]*G+M[10]*X+M[14]}let O;if(i.attributes.normal){let B=i.attributes.normal;O=new Float32Array(a*3),de(d,M);for(let H=0;H<a;H++){let G=B.getX(H),X=B.getY(H),q=B.getZ(H),ee=d[0]*G+d[3]*X+d[6]*q,y=d[1]*G+d[4]*X+d[7]*q,P=d[2]*G+d[5]*X+d[8]*q,N=Math.hypot(ee,y,P)||1;O[H*3]=ee/N,O[H*3+1]=y/N,O[H*3+2]=P/N}}let U=R,$=g;w&&w.length>=(C+1)*3&&(U=[R[0]*w[C*3],R[1]*w[C*3+1],R[2]*w[C*3+2]],$=`${g}_inst_${C}`),t.push({name:`${D}_${C}`,positions:T,indices:h,normals:O,uvs:o,materialName:$,color:U,roughness:f,metallic:m,clearcoat:p,clearcoatRoughness:L,ior:F,opacity:A,emissiveColor:I,xrTraits:r.userData?.xr})}return}t.push({name:r.name||`Mesh_${t.length}`,positions:u,indices:h,normals:c,uvs:o,materialName:g,color:R,roughness:f,metallic:m,clearcoat:p,clearcoatRoughness:L,ior:F,opacity:A,emissiveColor:I,xrTraits:r.userData?.xr,timeSamples:x})}}),t}function st(n){let e=[],t=n.gltf,r=ge().decoders.get("meshopt");r&&typeof r.decodeBufferViews=="function"&&r.decodeBufferViews(t,n);let i=n.bin,s=i instanceof ArrayBuffer?i:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),a=t.accessors||[],u=t.bufferViews||[],l=t.materials||[],c=t.meshes||[],o=t.nodes||[];function h(f){let m=a[f];if(!m)throw new Error(`Accessor ${f} not found`);let p=u[m.bufferView||0],L=(p.byteOffset||0)+(m.byteOffset||0),F=p.byteLength||0,A=s.slice(L,L+F);return{acc:m,buffer:A}}let g=new Map;if(o.length>0){let f=Le(t);for(let m=0;m<f.length;m++)g.set(m,f[m])}function R(f,m,p,L){let F=c[f];if(!F)return;let A=new Float32Array(9);de(A,m);for(let I=0;I<(F.primitives||[]).length;I++){let x=F.primitives[I],v=x.attributes?.POSITION;if(v===void 0)continue;let{acc:E,buffer:b}=h(v),S=new Float32Array(b,0,E.count*3),w=new Float32Array(S.length);for(let y=0;y<E.count;y++){let P=S[y*3],N=S[y*3+1],V=S[y*3+2];w[y*3]=m[0]*P+m[4]*N+m[8]*V+m[12],w[y*3+1]=m[1]*P+m[5]*N+m[9]*V+m[13],w[y*3+2]=m[2]*P+m[6]*N+m[10]*V+m[14]}let D,M=x.attributes?.NORMAL;if(M!==void 0){let{acc:y,buffer:P}=h(M),N=new Float32Array(P,0,y.count*3);D=new Float32Array(N.length);for(let V=0;V<y.count;V++){let j=N[V*3],Q=N[V*3+1],z=N[V*3+2],K=A[0]*j+A[3]*Q+A[6]*z,se=A[1]*j+A[4]*Q+A[7]*z,k=A[2]*j+A[5]*Q+A[8]*z,ae=Math.hypot(K,se,k)||1;D[V*3]=K/ae,D[V*3+1]=se/ae,D[V*3+2]=k/ae}}let d,C=x.attributes?.TEXCOORD_0;if(C!==void 0){let{acc:y,buffer:P}=h(C);d=new Float32Array(P,0,y.count*2)}let _;if(x.indices!==void 0){let{acc:y,buffer:P}=h(x.indices);y.componentType===5125?_=new Uint32Array(P,0,y.count):_=new Uint16Array(P,0,y.count);let N=E.count;for(let V of _)if(V>=N)throw new Error(`SecurityError: Index buffer value (${V}) out of vertex bounds [0, ${N}).`)}else{let y=E.count;_=y>65535?new Uint32Array(y):new Uint16Array(y);for(let P=0;P<y;P++)_[P]=P}let T="DefaultMaterial",O=[.8,.8,.8],U=.5,$=.1,B=0,H=0,G=1.5,X=1,q=[0,0,0];if(x.material!==void 0&&l[x.material]){let y=l[x.material];T=y.name||`Material_${x.material}`;let P=y.pbrMetallicRoughness||{},N=1;Array.isArray(P.baseColorFactor)&&(O=[P.baseColorFactor[0],P.baseColorFactor[1],P.baseColorFactor[2]],typeof P.baseColorFactor[3]=="number"&&(N=P.baseColorFactor[3])),typeof P.roughnessFactor=="number"&&(U=P.roughnessFactor),typeof P.metallicFactor=="number"&&($=P.metallicFactor),Array.isArray(y.emissiveFactor)&&y.emissiveFactor.length>=3&&(q=[y.emissiveFactor[0],y.emissiveFactor[1],y.emissiveFactor[2]]);let V=y.extensions||{};V.KHR_materials_clearcoat&&(B=V.KHR_materials_clearcoat.clearcoatFactor??0,H=V.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),V.KHR_materials_ior&&typeof V.KHR_materials_ior.ior=="number"&&(G=V.KHR_materials_ior.ior);let j=V.KHR_materials_transmission?.transmissionFactor??0;X=N*(1-j)}let ee=(F.primitives||[]).length>1?`${p}_p${I}`:p;e.push({name:ee,positions:w,indices:_,normals:D,uvs:d,materialName:T,color:O,roughness:U,metallic:$,clearcoat:B,clearcoatRoughness:H,ior:G,opacity:X,emissiveColor:q,xrTraits:L?.xr||F.extras?.xr})}}if(o.length>0)for(let f=0;f<o.length;f++){let m=o[f];if(m.mesh!==void 0&&m.mesh<c.length){let p=g.get(f)||Z(),L=m.name||c[m.mesh].name||`Node_${f}`,F=m.extensions?.EXT_mesh_gpu_instancing?.attributes;if(F&&typeof F=="object"){let A=F.TRANSLATION,I=F.ROTATION,x=F.SCALE,v=A!==void 0?(()=>{let{acc:w,buffer:D}=h(A);return new Float32Array(D,0,w.count*3)})():null,E=I!==void 0?(()=>{let{acc:w,buffer:D}=h(I);return new Float32Array(D,0,w.count*4)})():null,b=x!==void 0?(()=>{let{acc:w,buffer:D}=h(x);return new Float32Array(D,0,w.count*3)})():null,S=Math.min(1e3,v?v.length/3:E?E.length/4:b?b.length/3:0);if(S>0){let w=new Float32Array(16),D=new Float32Array(16);for(let M=0;M<S;M++){let d=v?[v[M*3],v[M*3+1],v[M*3+2]]:[0,0,0],C=E?[E[M*4],E[M*4+1],E[M*4+2],E[M*4+3]]:[0,0,0,1],_=b?[b[M*3],b[M*3+1],b[M*3+2]]:[1,1,1];we(w,C,d,_),te(D,p,w),R(m.mesh,D,`${L}_${M}`,m.extras)}continue}}R(m.mesh,p,L,m.extras)}}else{let f=Z();for(let m=0;m<c.length;m++){let p=c[m].name||`Mesh_${m}`;R(m,f,p,c[m].extras)}}return e}function Ve(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 rt(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function W(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 it(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${W(n[r*3])}, ${W(n[r*3+1])}, ${W(n[r*3+2])})`;return t.join(", ")}function Dt(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${W(n[r*2])}, ${W(1-n[r*2+1])})`;return t.join(", ")}function Pt(n){return Array.from(n).join(", ")}function Oe(n){let e=new Map;for(let l of n){let c=Ve(l.materialName,"DefaultMaterial");e.has(c)||e.set(c,{color:l.color||[.8,.8,.8],roughness:l.roughness??.5,metallic:l.metallic??0,clearcoat:l.clearcoat??0,clearcoatRoughness:l.clearcoatRoughness??0,ior:l.ior??1.5,opacity:l.opacity??1,emissiveColor:l.emissiveColor||[0,0,0]})}let t=0,r=null;for(let l of n){if(l.timeSamples&&l.timeSamples.times.length>0){let c=l.timeSamples.times[l.timeSamples.times.length-1];c>t&&(t=c)}l.xrTraits?.anchor&&!r&&(r=l.xrTraits.anchor==="vertical"||l.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
233
+ endTimeCode = ${W(t)}
210
234
  timeCodesPerSecond = 1.0
211
- `);let s="";i&&(s=`uniform token preliminary:anchoring:type = "plane"
212
- uniform token preliminary:planeAnchoring:alignment = "${i}"
213
- `);let c=`#usda 1.0
235
+ `);let s="";r&&(s=`uniform token preliminary:anchoring:type = "plane"
236
+ uniform token preliminary:planeAnchoring:alignment = "${r}"
237
+ `);let a=`#usda 1.0
214
238
  (
215
239
  defaultPrim = "Root"
216
240
  metersPerUnit = 1.0
217
241
  upAxis = "Y"
218
- ${r})
242
+ ${i})
219
243
 
220
244
  def Xform "Root" (
221
245
  kind = "component"
@@ -223,55 +247,55 @@ kind = "component"
223
247
  {
224
248
  ${s}def Scope "Materials"
225
249
  {
226
- `;for(let[u,a]of e.entries()){let[o,f,d]=a.color,[p,m,x]=a.emissiveColor,b="";a.clearcoat>0&&(b+=`float inputs:clearcoat = ${V(a.clearcoat)}
227
- `,b+=`float inputs:clearcoatRoughness = ${V(a.clearcoatRoughness)}
228
- `),a.ior!==1.5&&(b+=`float inputs:ior = ${V(a.ior)}
229
- `),a.opacity<1&&(b+=`float inputs:opacity = ${V(a.opacity)}
230
- `),(p>0||m>0||x>0)&&(b+=`color3f inputs:emissiveColor = (${V(p)}, ${V(m)}, ${V(x)})
231
- `),c+=`def Material "${u}"
250
+ `;for(let[l,c]of e.entries()){let[o,h,g]=c.color,[R,f,m]=c.emissiveColor,p="";c.clearcoat>0&&(p+=`float inputs:clearcoat = ${W(c.clearcoat)}
251
+ `,p+=`float inputs:clearcoatRoughness = ${W(c.clearcoatRoughness)}
252
+ `),c.ior!==1.5&&(p+=`float inputs:ior = ${W(c.ior)}
253
+ `),c.opacity<1&&(p+=`float inputs:opacity = ${W(c.opacity)}
254
+ `),(R>0||f>0||m>0)&&(p+=`color3f inputs:emissiveColor = (${W(R)}, ${W(f)}, ${W(m)})
255
+ `),a+=`def Material "${l}"
232
256
  {
233
257
  def Shader "PBRShader"
234
258
  {
235
259
  uniform token info:id = "UsdPreviewSurface"
236
- color3f inputs:diffuseColor = (${V(o)}, ${V(f)}, ${V(d)})
237
- float inputs:metallic = ${V(a.metallic)}
238
- float inputs:roughness = ${V(a.roughness)}
239
- ${b}token outputs:surface
260
+ color3f inputs:diffuseColor = (${W(o)}, ${W(h)}, ${W(g)})
261
+ float inputs:metallic = ${W(c.metallic)}
262
+ float inputs:roughness = ${W(c.roughness)}
263
+ ${p}token outputs:surface
240
264
  }
241
- token outputs:surface.connect = </Root/Materials/${u}/PBRShader.outputs:surface>
265
+ token outputs:surface.connect = </Root/Materials/${l}/PBRShader.outputs:surface>
242
266
  }
243
- `}c+=`}
267
+ `}a+=`}
244
268
  def Scope "Meshes"
245
269
  {
246
- `;let l=new Set;for(let u=0;u<n.length;u++){let a=n[u],o=a.positions.length/3,f=1/0,d=1/0,p=1/0,m=-1/0,x=-1/0,b=-1/0;for(let h=0;h<o;h++){let v=a.positions[h*3],y=a.positions[h*3+1],T=a.positions[h*3+2];v<f&&(f=v),v>m&&(m=v),y<d&&(d=y),y>x&&(x=y),T<p&&(p=T),T>b&&(b=T)}isFinite(f)||(f=d=p=-1,m=x=b=1);let E=Math.floor(a.indices.length/3),P=Ie(a.materialName,"DefaultMaterial"),A=Ie(a.name,`Mesh_${u}`);l.has(A)&&(A=`${A}_${u}`),l.add(A);let R=E>0?E===1?"3":"3, ".repeat(E-1)+"3":"",g=a.xrTraits,M="";if(g){let h=[];g.physics&&g.physics!=="none"&&h.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let v=pe().xrTraitSerializer?.usdLines(g,je)??[];if(!v.length)for(let y of["grab","billboard","follow","anchor","physics"]){let T=y==="follow"&&typeof g.follow=="object"?g.follow.mode??"head":g[y];T!==void 0&&v.push(`string ${y} = "${je(T)}"`)}v.length>0&&h.push(`customData = {
270
+ `;let u=new Set;for(let l=0;l<n.length;l++){let c=n[l],o=c.positions.length/3,h=1/0,g=1/0,R=1/0,f=-1/0,m=-1/0,p=-1/0;for(let E=0;E<o;E++){let b=c.positions[E*3],S=c.positions[E*3+1],w=c.positions[E*3+2];b<h&&(h=b),b>f&&(f=b),S<g&&(g=S),S>m&&(m=S),w<R&&(R=w),w>p&&(p=w)}isFinite(h)||(h=g=R=-1,f=m=p=1);let L=Math.floor(c.indices.length/3),F=Ve(c.materialName,"DefaultMaterial"),A=Ve(c.name,`Mesh_${l}`);u.has(A)&&(A=`${A}_${l}`),u.add(A);let I=L>0?L===1?"3":"3, ".repeat(L-1)+"3":"",x=c.xrTraits,v="";if(x){let E=[];x.physics&&x.physics!=="none"&&E.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let b=ge().xrTraitSerializer?.usdLines(x,rt)??[];if(!b.length)for(let S of["grab","billboard","follow","anchor","physics"]){let w=S==="follow"&&typeof x.follow=="object"?x.follow.mode??"head":x[S];w!==void 0&&b.push(`string ${S} = "${rt(w)}"`)}b.length>0&&E.push(`customData = {
247
271
  dictionary xr = {
248
- ${v.join(`
272
+ ${b.join(`
249
273
  `)}
250
274
  }
251
- }`),h.length>0&&(M=` (
252
- ${h.join(`
275
+ }`),E.length>0&&(v=` (
276
+ ${E.join(`
253
277
  `)}
254
- )`)}if(c+=`def Mesh "${A}"${M}
278
+ )`)}if(a+=`def Mesh "${A}"${v}
255
279
  {
256
- `,g?.physics&&g.physics!=="none"){let h=g.physics==="static"?"true":"false";c+=`bool physics:rigidBodyEnabled = true
257
- bool physics:kinematicEnabled = ${h}
280
+ `,x?.physics&&x.physics!=="none"){let E=x.physics==="static"?"true":"false";a+=`bool physics:rigidBodyEnabled = true
281
+ bool physics:kinematicEnabled = ${E}
258
282
  bool physics:collisionEnabled = true
259
- `}if(a.timeSamples&&a.timeSamples.times.length>0){let h=a.timeSamples,v=h.times.map((F,C)=>{let w=h.translations?.[C]||[0,0,0];return`${V(F)}: (${V(w[0])}, ${V(w[1])}, ${V(w[2])})`}).join(", "),y=h.times.map((F,C)=>{let w=h.rotations?.[C]||[0,0,0,1];return`${V(F)}: (${V(w[3])}, ${V(w[0])}, ${V(w[1])}, ${V(w[2])})`}).join(", "),T=h.times.map((F,C)=>{let w=h.scales?.[C]||[1,1,1];return`${V(F)}: (${V(w[0])}, ${V(w[1])}, ${V(w[2])})`}).join(", ");c+=`double3 xformOp:translate.timeSamples = { ${v} }
260
- quatf xformOp:orient.timeSamples = { ${y} }
261
- double3 xformOp:scale.timeSamples = { ${T} }
283
+ `}if(c.timeSamples&&c.timeSamples.times.length>0){let E=c.timeSamples,b=E.times.map((D,M)=>{let d=E.translations?.[M]||[0,0,0];return`${W(D)}: (${W(d[0])}, ${W(d[1])}, ${W(d[2])})`}).join(", "),S=E.times.map((D,M)=>{let d=E.rotations?.[M]||[0,0,0,1];return`${W(D)}: (${W(d[3])}, ${W(d[0])}, ${W(d[1])}, ${W(d[2])})`}).join(", "),w=E.times.map((D,M)=>{let d=E.scales?.[M]||[1,1,1];return`${W(D)}: (${W(d[0])}, ${W(d[1])}, ${W(d[2])})`}).join(", ");a+=`double3 xformOp:translate.timeSamples = { ${b} }
284
+ quatf xformOp:orient.timeSamples = { ${S} }
285
+ double3 xformOp:scale.timeSamples = { ${w} }
262
286
  uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
263
- `}c+=`float3[] extent = [(${V(f)}, ${V(d)}, ${V(p)}), (${V(m)}, ${V(x)}, ${V(b)})]
264
- int[] faceVertexCounts = [${R}]
265
- int[] faceVertexIndices = [${xt(a.indices)}]
266
- point3f[] points = [${Qe(a.positions)}]
267
- `,a.normals&&a.normals.length===a.positions.length&&(c+=`normal3f[] normals = [${Qe(a.normals)}] (
287
+ `}a+=`float3[] extent = [(${W(h)}, ${W(g)}, ${W(R)}), (${W(f)}, ${W(m)}, ${W(p)})]
288
+ int[] faceVertexCounts = [${I}]
289
+ int[] faceVertexIndices = [${Pt(c.indices)}]
290
+ point3f[] points = [${it(c.positions)}]
291
+ `,c.normals&&c.normals.length===c.positions.length&&(a+=`normal3f[] normals = [${it(c.normals)}] (
268
292
  interpolation = "vertex"
269
293
  )
270
- `),a.uvs&&a.uvs.length===o*2&&(c+=`texCoord2f[] primvars:st = [${vt(a.uvs,o)}] (
294
+ `),c.uvs&&c.uvs.length===o*2&&(a+=`texCoord2f[] primvars:st = [${Dt(c.uvs,o)}] (
271
295
  interpolation = "vertex"
272
296
  )
273
- `),c+=`rel material:binding = </Root/Materials/${P}>
297
+ `),a+=`rel material:binding = </Root/Materials/${F}>
274
298
  }
275
- `}return c+=`}
299
+ `}return a+=`}
276
300
  }
277
- `,c}function et(n,e){if(n&&typeof n.traverse=="function"){let r=gt(n,e);return _e(r)}let t=ge(n),i=Je(t);return _e(i)}var Se=null;function tt(n){if(!Se){Se=new Uint32Array(256);for(let t=0;t<256;t++){let i=t;for(let r=0;r<8;r++)i=i&1?3988292384^i>>>1:i>>>1;Se[t]=i}}let e=4294967295;for(let t=0;t<n.length;t++)e=Se[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Be(n){let e=[],t=0,i=[];for(let o of n){let f=Ue(o.filename),d=tt(o.data),p=o.data.length,m=30+f.length,x=t+m,b=0,E=x%64;E!==0&&(b=64-E);let P=new Uint8Array(m+b),A=new DataView(P.buffer);A.setUint32(0,67324752,!0),A.setUint16(4,20,!0),A.setUint16(6,0,!0),A.setUint16(8,0,!0),A.setUint16(10,0,!0),A.setUint16(12,0,!0),A.setUint32(14,d,!0),A.setUint32(18,p,!0),A.setUint32(22,p,!0),A.setUint16(26,f.length,!0),A.setUint16(28,b,!0),P.set(f,30),b>0&&P.fill(0,30+f.length),e.push({offset:t,size:p,crc:d,filenameBytes:f,entry:o}),i.push(P),i.push(o.data),t+=P.length+o.data.length}let r=t;for(let o of e){let f=new Uint8Array(46+o.filenameBytes.length),d=new DataView(f.buffer);d.setUint32(0,33639248,!0),d.setUint16(4,20,!0),d.setUint16(6,20,!0),d.setUint16(8,0,!0),d.setUint16(10,0,!0),d.setUint16(12,0,!0),d.setUint16(14,0,!0),d.setUint32(16,o.crc,!0),d.setUint32(20,o.size,!0),d.setUint32(24,o.size,!0),d.setUint16(28,o.filenameBytes.length,!0),d.setUint16(30,0,!0),d.setUint16(32,0,!0),d.setUint16(34,0,!0),d.setUint16(36,0,!0),d.setUint32(38,0,!0),d.setUint32(42,o.offset,!0),f.set(o.filenameBytes,46),i.push(f),t+=f.length}let s=t-r,c=new Uint8Array(22),l=new DataView(c.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,r,!0),l.setUint16(20,0,!0),i.push(c),t+=22;let u=new Uint8Array(t),a=0;for(let o of i)u.set(o,a),a+=o.length;return u}function Mt(n){let e=et(n),t=Ue(e);return Be([{filename:"model.usda",data:t}])}function nt(n){let e=ge(n),t=Je(e),i=_e(t),r=Ue(i);return Be([{filename:"model.usda",data:r}])}function it(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?Mt(n):nt(n)}function rt(n){let e=it(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}function ot(){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 ct(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function ut(){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 Ot(){let n=[];return await ut()&&n.push("webxr"),ot()&&n.push("quick-look"),ct()&&n.push("scene-viewer"),n}async function Vt(){return(await lt()).bestMode}async function lt(){let[n,e,t]=await Promise.all([ut(),Promise.resolve(ot()),Promise.resolve(ct())]),i=[];e&&i.push("quick-look"),n&&i.push("webxr"),t&&i.push("scene-viewer");let r=null;return e?r="quick-look":n?r="webxr":t&&(r="scene-viewer"),{webxr:n,quickLook:e,sceneViewer:t,availableModes:i,bestMode:r}}function st(n,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let t,i=!1;if(typeof n=="string"){if(t=Rt(n),!t)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else t=URL.createObjectURL(n),i=!0;let r=[];if(e.allowScale===!1&&r.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let l=Pe(e.canonicalWebPageUrl,!1);l&&r.push(`canonicalWebPageURL=${encodeURIComponent(l)}`)}e.checkoutTitle&&r.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&r.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&r.push(`price=${encodeURIComponent(e.price)}`),r.length>0&&(t+=`#${r.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",t);let c=document.createElement("img");c.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),c.style.display="none",s.appendChild(c),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),i&&URL.revokeObjectURL(t.split("#")[0])},3e3)}function Pe(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 i=t.toLowerCase();if(i.startsWith("https://")||i.startsWith("http://")||e&&i.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 Rt(n){try{return Pe(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function wt(n,e={}){let t=Pe(n,!0),i=e.mode||"ar_preferred",r=new URLSearchParams({file:t,mode:i,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&r.set("title",e.title),e.link&&r.set("link",Pe(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${r.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function At(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=wt(n,e);window.location.href=t}var be=null;function Et(n,e){let i=new Float32Array(144),r=new Float32Array(24*6),s=new Float32Array(24*4),c=new Uint16Array(24*6);for(let f=0;f<24;f++){let d=f/24*Math.PI*2,p=Math.cos(d),m=Math.sin(d),x=f*2,b=x+1,E=(f+1)%24*2;i[x*3]=p*.11,i[x*3+1]=.002,i[x*3+2]=m*.11,i[b*3]=p*.145,i[b*3+1]=.002,i[b*3+2]=m*.145,r[x*3+1]=r[b*3+1]=1,c.set([x,E,b,b,E,E+1],f*6)}let l=n.createVertexArray();n.bindVertexArray(l);let u=(f,d,p)=>{let m=n.createBuffer();return n.bindBuffer(34962,m),n.bufferData(34962,f,35044),n.enableVertexAttribArray(d),n.vertexAttribPointer(d,p,5126,!1,0,0),m},a=[u(i,0,3),u(r,1,3),u(s,2,2)],o=n.createBuffer();return a.push(o),n.bindBuffer(34963,o),n.bufferData(34963,c,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:c.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:i,indices:c,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:a}]}}function at(n,e,t,i,r){let s=Math.cos(i),c=Math.sin(i),l=Math.max(.01,r);n.fill(0),n[0]=l*s,n[2]=-l*c,n[5]=l,n[8]=l*c,n[10]=l*s,n[12]=e[0]-l*(s*t[0]+c*t[2]),n[13]=e[1]-l*t[1],n[14]=e[2]-l*(-c*t[0]+s*t[2]),n[15]=1}var ke=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.");be&&be!==this&&be.isSessionActive()&&await be.stop().catch(()=>{});let i=navigator.xr,r=this.opts,s=t||e?.container,c=String(s?.tagName||"").toLowerCase()==="xr-live",l=e?.bounds,u=Number(l?.radius)||1,a=Array.isArray(l?.center)?l.center:[0,0,0],o=Array.isArray(l?.min)?l.min:[-.5,-.5,-.5],f=typeof navigator<"u"&&navigator.userAgent||"",d=/Android|iPhone|iPad|iPod/i.test(f)&&!/Quest|Oculus|Pico|Vision/i.test(f),p=c?r.arScale==="fixed"?1:d?.55:1:r.arScale==="fixed"?1:u>.45?.3/u:u<.05?.12/Math.max(u,.001):1,m=c?[0,-.25,0]:[a[0]||0,r.arPlacement==="wall"?a[1]:o[1]??0,a[2]||0],x="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(x="immersive-vr")}catch{x="immersive-vr"}let b=s?.querySelector?.('[slot="ar-overlay"]')||null,E=!1,P=null,A=()=>{E&&b?.parentNode&&b.parentNode.removeChild(b),b=null,P=null,E=!1};if(x==="immersive-ar"){if(b)b.addEventListener?.("beforexrselect",S=>S.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let S=document.createElement("div");S.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 U=document.createElement("button");U.type="button",U.textContent="\u2715 Exit AR",U.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",U.addEventListener("beforexrselect",_=>_.preventDefault()),U.addEventListener("click",_=>{_.stopPropagation(),this.stop().catch(()=>{})}),P=document.createElement("div"),P.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",P.textContent="Move phone to detect a surface \u2022 Tap to place",S.appendChild(U),S.appendChild(P),document.body.appendChild(S),b=S,E=!0}}let R=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),g={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(R)};b&&(R.add("dom-overlay"),g.optionalFeatures=Array.from(R),g.domOverlay={root:b});for(let S of K)S.onConfigureXRSessionInit?.(s,g);Array.isArray(g.optionalFeatures)&&g.optionalFeatures.includes("dom-overlay")&&!g.domOverlay?.root&&(g.optionalFeatures=g.optionalFeatures.filter(S=>S!=="dom-overlay"));let M=S=>{let U=String(S?.name||"");return U==="NotAllowedError"||U==="SecurityError"};try{this.s=await i.requestSession(x,g)}catch(S){if(A(),M(S))throw r.onError?.(S),S;try{this.s=await i.requestSession(x,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(U){if(M(U))throw r.onError?.(U),U;try{this.s=await i.requestSession(x)}catch(_){throw r.onError?.(_),_}}}let h=this.s;be=this,this.placed=!1;let v=null,y=null,T=null,F=null,C=null,w=[0,-.25,-1.2],D=[0,-.25,-1.2],B=new Float32Array(16),L=new Float32Array(16),q=!1,z=1,j=0,H=!1,$=null,G=null,N=0,W=null,I=()=>{be===this&&(be=null),W?.(),W=null;try{y?.cancel?.()}catch{}if(y=null,T){let S=e?.meshes;if(Array.isArray(S)){let _=S.indexOf(T);_!==-1&&S.splice(_,1)}let U=e.getGLContext?.()||e?.gl;if(U)for(let _ of T.primitives||[]){U.deleteVertexArray?.(_.vao);for(let ee of _.buffers||[])U.deleteBuffer?.(ee)}T=null}e?.setXRSessionActive?.(!1),A(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=I,h.addEventListener("end",()=>{I(),r.onExit?.()}),h.addEventListener("select",()=>{if(!this.placed){let S=C||w;D=[S[0],S[1],S[2]],at(this.placedMat,D,m,j,p*z),this.placed=!0,T&&(T.visible=!1),P&&(P.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let S=e.getGLContext?.()||e?.gl;S&&typeof S.makeXRCompatible=="function"&&await S.makeXRCompatible();let U=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;S&&typeof U=="function"&&typeof h.updateRenderState=="function"&&h.updateRenderState({baseLayer:new U(h,S,{alpha:!0})});try{v=await h.requestReferenceSpace("local")}catch{try{v=await h.requestReferenceSpace("local-floor")}catch{v=await h.requestReferenceSpace("viewer")}}let _=await h.requestReferenceSpace("viewer").catch(()=>v);if(typeof h.requestHitTestSource=="function"&&_&&(y=await h.requestHitTestSource({space:_}).catch(()=>null)),x==="immersive-ar"&&S&&typeof S.createVertexArray=="function"&&Array.isArray(e.meshes)&&(T=Et(S,r.reticleColor),e.meshes.push(T)),typeof window<"u"&&typeof window.addEventListener=="function"){let re=k=>Math.hypot(k.touches[1].clientX-k.touches[0].clientX,k.touches[1].clientY-k.touches[0].clientY),X=k=>Math.atan2(k.touches[1].clientY-k.touches[0].clientY,k.touches[1].clientX-k.touches[0].clientX),ce=k=>{this.s&&(k.touches.length===1&&this.placed?H=!0:k.touches.length>=2&&(H=!1,$=re(k),G=X(k)))},ie=k=>{if(!this.s||k.touches.length<2)return;let Q=re(k),Y=X(k);if($&&$>4&&r.arScale!=="fixed"&&(z=Math.max(.15,Math.min(6,z*(Q/$)))),G!==null){let ue=Y-G;ue>Math.PI&&(ue-=Math.PI*2),ue<-Math.PI&&(ue+=Math.PI*2),j-=ue}$=Q,G=Y},te=k=>{(!k.touches||k.touches.length===0)&&(H=!1),(!k.touches||k.touches.length<2)&&($=null,G=null)};window.addEventListener("touchstart",ce,{passive:!0}),window.addEventListener("touchmove",ie,{passive:!0}),window.addEventListener("touchend",te,{passive:!0}),window.addEventListener("touchcancel",te,{passive:!0}),W=()=>{window.removeEventListener("touchstart",ce),window.removeEventListener("touchmove",ie),window.removeEventListener("touchend",te),window.removeEventListener("touchcancel",te)}}e.setXRSessionActive?.(!0);let ee=(re,X)=>{if(this.s!==h)return;h.requestAnimationFrame(ee);let ce=N>0?Math.min(Math.max((re-N)/1e3,0),.1):1/60;N=re,e?.stepXRUpdate?.(ce);let ie=X.getViewerPose(v);if(!ie)return;let te=ie.views?.[0];if(!q&&te?.transform){let se=te.transform.position,J=te.transform.matrix,fe=se?.x??(J?J[12]:0),ae=se?.y??(J?J[13]:0),le=se?.z??(J?J[14]:0),O=J?-J[8]:0,ne=J?-J[10]:-1,me=Math.hypot(O,ne);me>1e-4?(O/=me,ne/=me):(O=0,ne=-1),w=[fe+O*1.2,ae-.25,le+ne*1.2],j=Math.atan2(-O,-ne),q=!0}if(y&&typeof X.getHitTestResults=="function"&&(!this.placed||H)){let se=X.getHitTestResults(y)||[],J=!1;for(let fe of se){let ae=fe.getPose(v);if(ae?.transform?.matrix){let le=ae.transform.matrix,O=le[5];if(r.arPlacement==="wall"&&Math.abs(O)>.35||r.arPlacement==="floor"&&Math.abs(O)<.65)continue;F||(F=new Float32Array(16)),F.set(le),C=[le[12],le[13],le[14]],this.placed&&H&&(D=[le[12],le[13],le[14]]),T&&(T.visible=!this.placed||H,T.transform.set(le)),!this.placed&&P&&(P.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(F),J=!0;break}}!J&&T&&(T.visible=!1)}at(B,this.placed?D:C||w,m,j,p*z),this.placed&&this.placedMat.set(B);let k=e.xrRigMatrix;k instanceof Float32Array&&k.length===16?oe(L,k,B):L.set(B),e.modelRootMatrix&&e.modelRootMatrix.set(L);for(let se of K)se.onXRFrame?.(e,h,X,v);let Q=e.getGLContext?.()||e?.gl,Y=h.renderState?.baseLayer;Q&&Y&&Y.framebuffer!==void 0&&Q.bindFramebuffer(36160,Y.framebuffer);let ue=x==="immersive-ar",ve=ie.views||[];for(let se=0;se<ve.length;se++){let J=ve[se];if(typeof e.renderXRView=="function"){let fe;if(Y&&typeof Y.getViewport=="function"){let ae=Y.getViewport(J);ae&&ae.width>0&&ae.height>0&&(fe=[ae.x,ae.y,ae.width,ae.height])}else Y?.framebufferWidth>0&&Y?.framebufferHeight>0&&(fe=[0,0,Y.framebufferWidth,Y.framebufferHeight]);e.renderXRView(J,L,this.placed,fe,ue,se)}}Q&&Y&&Y.framebuffer&&Q.bindFramebuffer(36160,null)};h.requestAnimationFrame(ee)}catch(S){throw typeof h.end=="function"&&await h.end().catch(()=>{}),I(),r.onError?.(S),S}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function Gt(n){let e=await lt(),t=n.preferredModes||["quick-look","webxr","scene-viewer"],i=null;for(let l of t)if(e.availableModes.includes(l)){i=l;break}if(i||(i=e.bestMode),!i)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let r={...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},c={...n.webXROptions,arScale:n.arScale||n.webXROptions?.arScale,arPlacement:n.arPlacement||n.webXROptions?.arPlacement};try{if(i==="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 st(n.model,r),{mode:"quick-look",success:!0};l=rt(n.model)}return st(l,r),{mode:"quick-look",success:!0}}if(i==="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 At(l,s),{mode:"scene-viewer",success:!0}}if(i==="webxr"){if(!n.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let l=new ke(c);return await l.start(n.view,n.element),{mode:"webxr",success:!0,session:l}}}catch(l){return{mode:i,success:!1,error:l}}return{mode:i,success:!1,error:new Error(`Unhandled AR mode: ${i}`)}}export{ke as WebXRSessionManager,Gt as activateAR,Be as buildUSDZZip,tt as calculateCRC32,wt as createSceneViewerIntent,rt as createUSDZBlob,et as generateUSDA,it as generateUSDZ,lt as getARCapabilities,Ot as getAvailableARModes,Vt as getBestARMode,nt as glbToUSDZ,ot as isQuickLookSupported,ct as isSceneViewerSupported,ut as isWebXRSupported,st as launchQuickLook,At as launchSceneViewer};
301
+ `,a}function at(n,e){if(n&&typeof n.traverse=="function"){let i=St(n,e);return Oe(i)}let t=Re(n),r=st(t);return Oe(r)}var Ie=null;function ot(n){if(!Ie){Ie=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;Ie[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=Ie[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function He(n){let e=[],t=0,r=[];for(let o of n){let h=Ge(o.filename),g=ot(o.data),R=o.data.length,f=30+h.length,m=t+f,p=0,L=m%64;L!==0&&(p=64-L);let F=new Uint8Array(f+p),A=new DataView(F.buffer);A.setUint32(0,67324752,!0),A.setUint16(4,20,!0),A.setUint16(6,0,!0),A.setUint16(8,0,!0),A.setUint16(10,0,!0),A.setUint16(12,0,!0),A.setUint32(14,g,!0),A.setUint32(18,R,!0),A.setUint32(22,R,!0),A.setUint16(26,h.length,!0),A.setUint16(28,p,!0),F.set(h,30),p>0&&F.fill(0,30+h.length),e.push({offset:t,size:R,crc:g,filenameBytes:h,entry:o}),r.push(F),r.push(o.data),t+=F.length+o.data.length}let i=t;for(let o of e){let h=new Uint8Array(46+o.filenameBytes.length),g=new DataView(h.buffer);g.setUint32(0,33639248,!0),g.setUint16(4,20,!0),g.setUint16(6,20,!0),g.setUint16(8,0,!0),g.setUint16(10,0,!0),g.setUint16(12,0,!0),g.setUint16(14,0,!0),g.setUint32(16,o.crc,!0),g.setUint32(20,o.size,!0),g.setUint32(24,o.size,!0),g.setUint16(28,o.filenameBytes.length,!0),g.setUint16(30,0,!0),g.setUint16(32,0,!0),g.setUint16(34,0,!0),g.setUint16(36,0,!0),g.setUint32(38,0,!0),g.setUint32(42,o.offset,!0),h.set(o.filenameBytes,46),r.push(h),t+=h.length}let s=t-i,a=new Uint8Array(22),u=new DataView(a.buffer);u.setUint32(0,101010256,!0),u.setUint16(4,0,!0),u.setUint16(6,0,!0),u.setUint16(8,e.length,!0),u.setUint16(10,e.length,!0),u.setUint32(12,s,!0),u.setUint32(16,i,!0),u.setUint16(20,0,!0),r.push(a),t+=22;let l=new Uint8Array(t),c=0;for(let o of r)l.set(o,c),c+=o.length;return l}function Lt(n){let e=at(n),t=Ge(e);return He([{filename:"model.usda",data:t}])}function ct(n){let e=Re(n),t=st(e),r=Oe(t),i=Ge(r);return He([{filename:"model.usda",data:i}])}function ut(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?Lt(n):ct(n)}function lt(n){let e=ut(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}function ft(){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 dt(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function pt(){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 Kt(){let n=[];return await pt()&&n.push("webxr"),ft()&&n.push("quick-look"),dt()&&n.push("scene-viewer"),n}async function Yt(){return(await bt()).bestMode}async function bt(){let[n,e,t]=await Promise.all([pt(),Promise.resolve(ft()),Promise.resolve(dt())]),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 mt(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=Ct(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 u=_e(e.canonicalWebPageUrl,!1);u&&i.push(`canonicalWebPageURL=${encodeURIComponent(u)}`)}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 _e(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 Ct(n){try{return _e(n,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(n||"").trim().slice(0,32)}`)}}function It(n,e={}){let t=_e(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",_e(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 _t(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=It(n,e);window.location.href=t}var xe=null;function Ut(n,e){let r=new Float32Array(144),i=new Float32Array(24*6),s=new Float32Array(24*4),a=new Uint16Array(24*6);for(let h=0;h<24;h++){let g=h/24*Math.PI*2,R=Math.cos(g),f=Math.sin(g),m=h*2,p=m+1,L=(h+1)%24*2;r[m*3]=R*.11,r[m*3+1]=.002,r[m*3+2]=f*.11,r[p*3]=R*.145,r[p*3+1]=.002,r[p*3+2]=f*.145,i[m*3+1]=i[p*3+1]=1,a.set([m,L,p,p,L,L+1],h*6)}let u=n.createVertexArray();n.bindVertexArray(u);let l=(h,g,R)=>{let f=n.createBuffer();return n.bindBuffer(34962,f),n.bufferData(34962,h,35044),n.enableVertexAttribArray(g),n.vertexAttribPointer(g,R,5126,!1,0,0),f},c=[l(r,0,3),l(i,1,3),l(s,2,2)],o=n.createBuffer();return c.push(o),n.bindBuffer(34963,o),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:u,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:c}]}}function ht(n,e,t,r,i){let s=Math.cos(r),a=Math.sin(r),u=Math.max(.01,i);n.fill(0),n[0]=u*s,n[2]=-u*a,n[5]=u,n[8]=u*a,n[10]=u*s,n[12]=e[0]-u*(s*t[0]+a*t[2]),n[13]=e[1]-u*t[1],n[14]=e[2]-u*(-a*t[0]+s*t[2]),n[15]=1}var ze=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.");xe&&xe!==this&&xe.isSessionActive()&&await xe.stop().catch(()=>{});let r=navigator.xr,i=this.opts,s=t||e?.container,a=String(s?.tagName||"").toLowerCase()==="xr-live",u=e?.bounds,l=Number(u?.radius)||1,c=Array.isArray(u?.center)?u.center:[0,0,0],o=Array.isArray(u?.min)?u.min:[-.5,-.5,-.5],h=typeof navigator<"u"&&navigator.userAgent||"",g=/Android|iPhone|iPad|iPod/i.test(h)&&!/Quest|Oculus|Pico|Vision/i.test(h),R=a?i.arScale==="fixed"?1:g?.55:1:i.arScale==="fixed"?1:l>.45?.3/l:l<.05?.12/Math.max(l,.001):1,f=a?[0,-.25,0]:[c[0]||0,i.arPlacement==="wall"?c[1]:o[1]??0,c[2]||0],m="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(m="immersive-vr")}catch{m="immersive-vr"}let p=s?.querySelector?.('[slot="ar-overlay"]')||null,L=!1,F=null,A=()=>{L&&p?.parentNode&&p.parentNode.removeChild(p),p=null,F=null,L=!1};if(m==="immersive-ar"){if(p)p.addEventListener?.("beforexrselect",y=>y.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let y=document.createElement("div");y.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 P=document.createElement("button");P.type="button",P.textContent="\u2715 Exit AR",P.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",P.addEventListener("beforexrselect",N=>N.preventDefault()),P.addEventListener("click",N=>{N.stopPropagation(),this.stop().catch(()=>{})}),F=document.createElement("div"),F.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",F.textContent="Move phone to detect a surface \u2022 Tap to place",y.appendChild(P),y.appendChild(F),document.body.appendChild(y),p=y,L=!0}}let I=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),x={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(I)};p&&(I.add("dom-overlay"),x.optionalFeatures=Array.from(I),x.domOverlay={root:p});for(let y of ne)y.onConfigureXRSessionInit?.(s,x);Array.isArray(x.optionalFeatures)&&x.optionalFeatures.includes("dom-overlay")&&!x.domOverlay?.root&&(x.optionalFeatures=x.optionalFeatures.filter(y=>y!=="dom-overlay"));let v=y=>{let P=String(y?.name||"");return P==="NotAllowedError"||P==="SecurityError"};try{this.s=await r.requestSession(m,x)}catch(y){if(A(),v(y))throw i.onError?.(y),y;try{this.s=await r.requestSession(m,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(P){if(v(P))throw i.onError?.(P),P;try{this.s=await r.requestSession(m)}catch(N){throw i.onError?.(N),N}}}let E=this.s;xe=this,this.placed=!1;let b=null,S=null,w=null,D=null,M=null,d=[0,-.25,-1.2],C=[0,-.25,-1.2],_=new Float32Array(16),T=new Float32Array(16),O=!1,U=1,$=0,B=!1,H=null,G=null,X=0,q=null,ee=()=>{xe===this&&(xe=null),q?.(),q=null;try{S?.cancel?.()}catch{}if(S=null,w){let y=e?.meshes;if(Array.isArray(y)){let N=y.indexOf(w);N!==-1&&y.splice(N,1)}let P=e.getGLContext?.()||e?.gl;if(P)for(let N of w.primitives||[]){P.deleteVertexArray?.(N.vao);for(let V of N.buffers||[])P.deleteBuffer?.(V)}w=null}e?.setXRSessionActive?.(!1),A(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=ee,E.addEventListener("end",()=>{ee(),i.onExit?.()}),E.addEventListener("select",()=>{if(!this.placed){let y=M||d;C=[y[0],y[1],y[2]],ht(this.placedMat,C,f,$,R*U),this.placed=!0,w&&(w.visible=!1),F&&(F.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let y=e.getGLContext?.()||e?.gl;y&&typeof y.makeXRCompatible=="function"&&await y.makeXRCompatible();let P=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;y&&typeof P=="function"&&typeof E.updateRenderState=="function"&&E.updateRenderState({baseLayer:new P(E,y,{alpha:!0})});try{b=await E.requestReferenceSpace("local")}catch{try{b=await E.requestReferenceSpace("local-floor")}catch{b=await E.requestReferenceSpace("viewer")}}let N=await E.requestReferenceSpace("viewer").catch(()=>b);if(typeof E.requestHitTestSource=="function"&&N&&(S=await E.requestHitTestSource({space:N}).catch(()=>null)),m==="immersive-ar"&&y&&typeof y.createVertexArray=="function"&&Array.isArray(e.meshes)&&(w=Ut(y,i.reticleColor),e.meshes.push(w)),typeof window<"u"&&typeof window.addEventListener=="function"){let j=k=>Math.hypot(k.touches[1].clientX-k.touches[0].clientX,k.touches[1].clientY-k.touches[0].clientY),Q=k=>Math.atan2(k.touches[1].clientY-k.touches[0].clientY,k.touches[1].clientX-k.touches[0].clientX),z=k=>{this.s&&(k.touches.length===1&&this.placed?B=!0:k.touches.length>=2&&(B=!1,H=j(k),G=Q(k)))},K=k=>{if(!this.s||k.touches.length<2)return;let ae=j(k),re=Q(k);if(H&&H>4&&i.arScale!=="fixed"&&(U=Math.max(.15,Math.min(6,U*(ae/H)))),G!==null){let le=re-G;le>Math.PI&&(le-=Math.PI*2),le<-Math.PI&&(le+=Math.PI*2),$-=le}H=ae,G=re},se=k=>{(!k.touches||k.touches.length===0)&&(B=!1),(!k.touches||k.touches.length<2)&&(H=null,G=null)};window.addEventListener("touchstart",z,{passive:!0}),window.addEventListener("touchmove",K,{passive:!0}),window.addEventListener("touchend",se,{passive:!0}),window.addEventListener("touchcancel",se,{passive:!0}),q=()=>{window.removeEventListener("touchstart",z),window.removeEventListener("touchmove",K),window.removeEventListener("touchend",se),window.removeEventListener("touchcancel",se)}}e.setXRSessionActive?.(!0);let V=(j,Q)=>{if(this.s!==E)return;E.requestAnimationFrame(V);let z=X>0?Math.min(Math.max((j-X)/1e3,0),.1):1/60;X=j,e?.stepXRUpdate?.(z);let K=Q.getViewerPose(b);if(!K)return;let se=K.views?.[0];if(!O&&se?.transform){let ie=se.transform.position,J=se.transform.matrix,he=ie?.x??(J?J[12]:0),ue=ie?.y??(J?J[13]:0),fe=ie?.z??(J?J[14]:0),be=J?-J[8]:0,ye=J?-J[10]:-1,Te=Math.hypot(be,ye);Te>1e-4?(be/=Te,ye/=Te):(be=0,ye=-1),d=[he+be*1.2,ue-.25,fe+ye*1.2],$=Math.atan2(-be,-ye),O=!0}if(S&&typeof Q.getHitTestResults=="function"&&(!this.placed||B)){let ie=Q.getHitTestResults(S)||[],J=!1;for(let he of ie){let ue=he.getPose(b);if(ue?.transform?.matrix){let fe=ue.transform.matrix,be=fe[5];if(i.arPlacement==="wall"&&Math.abs(be)>.35||i.arPlacement==="floor"&&Math.abs(be)<.65)continue;D||(D=new Float32Array(16)),D.set(fe),M=[fe[12],fe[13],fe[14]],this.placed&&B&&(C=[fe[12],fe[13],fe[14]]),w&&(w.visible=!this.placed||B,w.transform.set(fe)),!this.placed&&F&&(F.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(D),J=!0;break}}!J&&w&&(w.visible=!1)}ht(_,this.placed?C:M||d,f,$,R*U),this.placed&&this.placedMat.set(_);let k=e.xrRigMatrix;k instanceof Float32Array&&k.length===16?te(T,k,_):T.set(_),e.modelRootMatrix&&e.modelRootMatrix.set(T);for(let ie of ne)ie.onXRFrame?.(e,E,Q,b);let ae=e.getGLContext?.()||e?.gl,re=E.renderState?.baseLayer;ae&&re&&re.framebuffer!==void 0&&ae.bindFramebuffer(36160,re.framebuffer);let le=m==="immersive-ar",me=K.views||[];for(let ie=0;ie<me.length;ie++){let J=me[ie];if(typeof e.renderXRView=="function"){let he;if(re&&typeof re.getViewport=="function"){let ue=re.getViewport(J);ue&&ue.width>0&&ue.height>0&&(he=[ue.x,ue.y,ue.width,ue.height])}else re?.framebufferWidth>0&&re?.framebufferHeight>0&&(he=[0,0,re.framebufferWidth,re.framebufferHeight]);e.renderXRView(J,T,this.placed,he,le,ie)}}ae&&re&&re.framebuffer&&ae.bindFramebuffer(36160,null)};E.requestAnimationFrame(V)}catch(y){throw typeof E.end=="function"&&await E.end().catch(()=>{}),ee(),i.onError?.(y),y}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function Zt(n){let e=await bt(),t=n.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let u of t)if(e.availableModes.includes(u)){r=u;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 u;if(n.model instanceof Blob&&n.model.type==="model/vnd.usdz+zip")u=n.model;else{if(typeof n.model=="string")return mt(n.model,i),{mode:"quick-look",success:!0};u=lt(n.model)}return mt(u,i),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let u=n.glbUrl||(typeof n.model=="string"?n.model:null);if(!u)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return _t(u,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!n.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let u=new ze(a);return await u.start(n.view,n.element),{mode:"webxr",success:!0,session:u}}}catch(u){return{mode:r,success:!1,error:u}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}export{ze as WebXRSessionManager,Zt as activateAR,He as buildUSDZZip,ot as calculateCRC32,It as createSceneViewerIntent,lt as createUSDZBlob,at as generateUSDA,ut as generateUSDZ,bt as getARCapabilities,Kt as getAvailableARModes,Yt as getBestARMode,ct as glbToUSDZ,ft as isQuickLookSupported,dt as isSceneViewerSupported,pt as isWebXRSupported,mt as launchQuickLook,_t as launchSceneViewer};