three-live 1.3.0 → 1.3.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 (42) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.ts +37 -0
  3. package/dist/three-author-engine.js +112 -61
  4. package/dist/three-author.cjs +110 -59
  5. package/dist/three-author.d.ts +37 -0
  6. package/dist/three-author.js +109 -58
  7. package/dist/three-convert.cjs +106 -59
  8. package/dist/three-convert.d.ts +37 -0
  9. package/dist/three-convert.js +105 -58
  10. package/dist/three-live-animation.cjs +8 -9
  11. package/dist/three-live-animation.d.ts +37 -0
  12. package/dist/three-live-animation.js +7 -8
  13. package/dist/three-live-animation.min.js +6 -7
  14. package/dist/three-live-cad.cjs +3 -4
  15. package/dist/three-live-cad.d.ts +37 -0
  16. package/dist/three-live-cad.js +2 -3
  17. package/dist/three-live-cad.min.js +3 -4
  18. package/dist/three-live-cli.js +231 -0
  19. package/dist/three-live-element.cjs +17 -20
  20. package/dist/three-live-element.d.ts +37 -0
  21. package/dist/three-live-element.js +16 -19
  22. package/dist/three-live-full.cjs +138 -87
  23. package/dist/three-live-full.js +137 -86
  24. package/dist/three-live-full.min.js +138 -87
  25. package/dist/three-live-studio.cjs +19 -20
  26. package/dist/three-live-studio.d.ts +37 -0
  27. package/dist/three-live-studio.js +18 -19
  28. package/dist/three-live-studio.min.js +18 -19
  29. package/dist/three-live-viewer.cjs +17 -20
  30. package/dist/three-live-viewer.d.ts +37 -0
  31. package/dist/three-live-viewer.js +16 -19
  32. package/dist/three-live-viewer.min.js +17 -20
  33. package/dist/three-live.cjs +115 -64
  34. package/dist/three-live.js +113 -62
  35. package/dist/three-live.min.js +115 -64
  36. package/dist/three-view.cjs +17 -20
  37. package/dist/three-view.d.ts +37 -0
  38. package/dist/three-view.js +16 -19
  39. package/dist/three-xr.cjs +105 -58
  40. package/dist/three-xr.d.ts +37 -0
  41. package/dist/three-xr.js +104 -57
  42. package/package.json +25 -1
package/dist/three-xr.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /**
1
+ "use strict";/**
2
2
  * @license
3
3
  * Copyright 2026 Google LLC
4
4
  *
@@ -13,8 +13,7 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */
17
- "use strict";var Ce=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var Mt=Object.getOwnPropertyNames;var Tt=Object.prototype.hasOwnProperty;var At=(n,e)=>{for(var t in e)Ce(n,t,{get:e[t],enumerable:!0})},wt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mt(e))!Tt.call(n,i)&&i!==t&&Ce(n,i,{get:()=>e[i],enumerable:!(r=vt(e,i))||r.enumerable});return n};var Rt=n=>wt(Ce({},"__esModule",{value:!0}),n);var Yt={};At(Yt,{WebXRSessionManager:()=>De,activateAR:()=>qt,buildUSDZZip:()=>Se,calculateCRC32:()=>He,createSceneViewerIntent:()=>gt,createUSDZBlob:()=>$e,generateUSDA:()=>ze,generateUSDZ:()=>Xe,getARCapabilities:()=>je,getAvailableARModes:()=>Ht,getBestARMode:()=>Wt,glbToUSDZ:()=>We,isQuickLookSupported:()=>Ye,isSceneViewerSupported:()=>Ke,isWebXRSupported:()=>Ze,launchQuickLook:()=>qe,launchSceneViewer:()=>xt});module.exports=Rt(Yt);function re(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function ve(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 Me(n,e,t,r){let[i,s,a]=e,[c,o,l]=r,[u,d,f]=t,T=i-u,g=s-d,m=a-f,p=Math.hypot(T,g,m);p<=1e-5?(T=0,g=0,m=1):(T/=p,g/=p,m/=p);let R=o*m-l*g,A=l*T-c*m,v=c*g-o*T;p=Math.hypot(R,A,v),p<=1e-5?(R=0,A=0,v=0):(R/=p,A/=p,v/=p);let D=g*v-m*A,y=m*R-T*v,P=T*A-g*R;return p=Math.hypot(D,y,P),p<=1e-5?(D=0,y=0,P=0):(D/=p,y/=p,P/=p),n[0]=R,n[1]=D,n[2]=T,n[3]=0,n[4]=A,n[5]=y,n[6]=g,n[7]=0,n[8]=v,n[9]=P,n[10]=m,n[11]=0,n[12]=-(R*i+A*s+v*a),n[13]=-(D*i+y*s+P*a),n[14]=-(T*i+g*s+m*a),n[15]=1,n}function se(n,e,t){let r=e[0],i=e[1],s=e[2],a=e[3],c=e[4],o=e[5],l=e[6],u=e[7],d=e[8],f=e[9],T=e[10],g=e[11],m=e[12],p=e[13],R=e[14],A=e[15],v=t[0],D=t[1],y=t[2],P=t[3];return n[0]=v*r+D*c+y*d+P*m,n[1]=v*i+D*o+y*f+P*p,n[2]=v*s+D*l+y*T+P*R,n[3]=v*a+D*u+y*g+P*A,v=t[4],D=t[5],y=t[6],P=t[7],n[4]=v*r+D*c+y*d+P*m,n[5]=v*i+D*o+y*f+P*p,n[6]=v*s+D*l+y*T+P*R,n[7]=v*a+D*u+y*g+P*A,v=t[8],D=t[9],y=t[10],P=t[11],n[8]=v*r+D*c+y*d+P*m,n[9]=v*i+D*o+y*f+P*p,n[10]=v*s+D*l+y*T+P*R,n[11]=v*a+D*u+y*g+P*A,v=t[12],D=t[13],y=t[14],P=t[15],n[12]=v*r+D*c+y*d+P*m,n[13]=v*i+D*o+y*f+P*p,n[14]=v*s+D*l+y*T+P*R,n[15]=v*a+D*u+y*g+P*A,n}function ye(n,e,t,r){let i=e[0],s=e[1],a=e[2],c=e[3],o=i+i,l=s+s,u=a+a,d=i*o,f=i*l,T=i*u,g=s*l,m=s*u,p=a*u,R=c*o,A=c*l,v=c*u,D=r[0],y=r[1],P=r[2];return n[0]=(1-(g+p))*D,n[1]=(f+v)*D,n[2]=(T-A)*D,n[3]=0,n[4]=(f-v)*y,n[5]=(1-(d+p))*y,n[6]=(m+R)*y,n[7]=0,n[8]=(T+A)*P,n[9]=(m-R)*P,n[10]=(1-(d+g))*P,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function me(n,e,t=0){let r=e[0],i=e[1],s=e[2],a=e[4],c=e[5],o=e[6],l=e[8],u=e[9],d=e[10],f=d*c-o*u,T=-d*a+o*l,g=u*a-c*l,m=r*f+i*T+s*g;return!m||t>0&&(!Number.isFinite(m)||Math.abs(m)<=t)||(m=1/m,n[0]=f*m,n[1]=T*m,n[2]=g*m,n[3]=(-d*i+s*u)*m,n[4]=(d*r-s*l)*m,n[5]=(-u*r+i*l)*m,n[6]=(o*i-s*c)*m,n[7]=(-o*r+s*a)*m,n[8]=(c*r-i*a)*m),n}function Qe(n,e){let t=e[0],r=e[1],i=e[2],s=e[3],a=e[4],c=e[5],o=e[6],l=e[7],u=e[8],d=e[9],f=e[10],T=e[11],g=e[12],m=e[13],p=e[14],R=e[15],A=t*c-r*a,v=t*o-i*a,D=t*l-s*a,y=r*o-i*c,P=r*l-s*c,E=i*l-s*o,b=u*m-d*g,F=u*p-f*g,L=u*R-T*g,C=d*p-f*m,h=d*R-T*m,w=f*R-T*p,S=A*w-v*h+D*C+y*L-P*F+E*b;return S?(S=1/S,n[0]=(c*w-o*h+l*C)*S,n[1]=(i*h-r*w-s*C)*S,n[2]=(m*E-p*P+R*y)*S,n[3]=(f*P-d*E-T*y)*S,n[4]=(o*L-a*w-l*F)*S,n[5]=(t*w-i*L+s*F)*S,n[6]=(p*D-g*E-R*v)*S,n[7]=(u*E-f*D+T*v)*S,n[8]=(a*h-c*L+l*b)*S,n[9]=(r*L-t*h-s*b)*S,n[10]=(g*P-m*D+R*A)*S,n[11]=(d*D-u*P-T*A)*S,n[12]=(c*F-a*C-o*b)*S,n[13]=(t*C-r*F+i*b)*S,n[14]=(m*v-g*y-p*A)*S,n[15]=(u*y-d*v+f*A)*S,n):null}function Ie(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],c=i[2]*e+i[6]*t+i[10]*r+i[14],o=i[3]*e+i[7]*t+i[11]*r+i[15],l=o!==0?1/o:1;n[0]=s*l,n[1]=a*l,n[2]=c*l}function Je(n,e,t,r,i,s,a,c,o,l,u,d,f,T,g,m,p=0){let R=l-a,A=u-c,v=d-o,D=f-a,y=T-c,P=g-o,E=i*P-s*y,b=s*D-r*P,F=r*y-i*D,L=R*E+A*b+v*F;if(L>-1e-7&&L<1e-7)return!1;let C=1/L,h=n-a,w=e-c,S=t-o,M=C*(h*E+w*b+S*F);if(M<-p||M>1+p)return!1;let k=w*v-S*A,_=S*R-h*v,K=h*A-w*R,U=C*(r*k+i*_+s*K);if(U<-p||M+U>1+p)return!1;let O=C*(D*k+y*_+P*K);if(O>1e-4&&O<m.distance){m.distance=O,m.point=[n+r*O,e+i*O,t+s*O];let B=A*P-v*y,q=v*D-R*P,Y=R*y-A*D,W=Math.hypot(B,q,Y)||1;return m.normal=[B/W,q/W,Y/W],!0}return!1}function Te(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let u=0;u<t;u++)r.push(re());if(t===0)return r;let i=new Set;for(let u of n.nodes)if(Array.isArray(u.children))for(let d of u.children)i.add(d);let s=new Set,a=128,c=(u,d,f=0)=>{if(f>a||u<0||u>=t||s.has(u))return;s.add(u);let T=n.nodes[u];if(!T)return;let g=re();if(e&&e[u])g.set(e[u]);else if(T.matrix&&T.matrix.length===16)g.set(T.matrix);else{let p=T.translation||[0,0,0],R=T.rotation||[0,0,0,1],A=T.scale||[1,1,1];ye(g,R,p,A)}let m=r[u];if(d?se(m,d,g):m.set(g),Array.isArray(T.children))for(let p of T.children)typeof p=="number"&&c(p,m,f+1)},o=[],l=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(l&&Array.isArray(l.nodes))o.push(...l.nodes);else for(let u=0;u<t;u++)i.has(u)||o.push(u);for(let u of o)c(u,null);for(let u=0;u<t;u++)!i.has(u)&&!o.includes(u)&&c(u,null);return r}var Ae="__THREE_LIVE_REGISTRY__";function he(){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 ae=he().plugins;function et(n){let e=he().plugins;e.some(t=>t.name===n.name)||e.push(n),n.onRegister?.()}function tt(){return he().plugins}function we(n,e,t,r=!0){let i=[],s=null;try{for(let[a,c]of[[35633,e],[35632,t]]){let o=n.createShader(a);if(!o){if(r)throw new Error("Shader allocation failed");return null}if(i.push(o),n.shaderSource(o,c),n.compileShader(o),n.getShaderParameter&&!n.getShaderParameter(o,35713)){if(r)throw new Error(`Shader compile error: ${n.getShaderInfoLog(o)}`);return null}}if(s=n.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let a of i)n.attachShader(s,a);if(n.linkProgram(s),n.getProgramParameter&&!n.getProgramParameter(s,35714)){let a=r?n.getProgramInfoLog(s):null;if(n.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${a}`);return null}return s}finally{for(let a of i)s&&n.detachShader?.(s,a),n.deleteShader?.(a)}}var Et={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function _e(n,e,t,r){if(!t||t.bufferView===void 0)return null;let i=n.bufferViews?.[t.bufferView];if(!i)return null;let s=Number(t.count??0);if(!Number.isInteger(s)||s<=0)return null;let a=t.componentType??5126,c=Et[a];if(!c)throw new RangeError(`glTF accessor has unsupported componentType ${a}`);let o=c*r,l=i.byteStride&&i.byteStride>0?i.byteStride:o,u=(i.byteOffset||0)+(t.byteOffset||0);if(!Number.isInteger(u)||u<0||l<o||u+(s-1)*l+o>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(a===5126&&l===o&&u%4===0)return new Float32Array(e,u,s*r);let d=new DataView(e),f=t.normalized===!0,T=new Float32Array(s*r);for(let g=0;g<s;g++){let m=u+g*l;for(let p=0;p<r;p++){let R=m+p*c,A;switch(a){case 5126:A=d.getFloat32(R,!0);break;case 5120:A=d.getInt8(R),f&&(A=Math.max(A/127,-1));break;case 5121:A=d.getUint8(R),f&&(A/=255);break;case 5122:A=d.getInt16(R,!0),f&&(A=Math.max(A/32767,-1));break;case 5123:A=d.getUint16(R,!0),f&&(A/=65535);break;default:A=d.getUint32(R,!0),f&&(A/=4294967295)}T[g*r+p]=A}}return T}function nt(n,e){let t=Number(e.offset?.[0]??0)||0,r=Number(e.offset?.[1]??0)||0,i=Number(e.scale?.[0]??1),s=Number(e.scale?.[1]??1),a=Number(e.rotation??0)||0,c=Math.cos(a),o=Math.sin(a),l=(Number.isFinite(i)?i:1)*c,u=(Number.isFinite(i)?i:1)*o,d=-(Number.isFinite(s)?s:1)*o,f=(Number.isFinite(s)?s:1)*c;for(let T=0;T+1<n.length;T+=2){let g=n[T],m=n[T+1];n[T]=l*g+u*m+t,n[T+1]=d*g+f*m+r}}var st=["neutral","reinhard","none","aces","agx"];function ke(n){let e=String(n??"").trim().toLowerCase();return st.includes(e)?e:"neutral"}function Lt(n){return st.indexOf(ke(n))}function St(n){return new TextDecoder().decode(n)}var at=he().decoders;function Pt(n,e){at.set(n.toLowerCase(),e)}function pe(n){return at.get(n.toLowerCase())}function ot(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 f=t.getUint8(0);throw f===123||f===32||f===10||f===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${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,c=null,o=null;for(;a+8<=s&&a+8<=e.byteLength;){let f=t.getUint32(a,!0),T=t.getUint32(a+4,!0),g=a+8;if(g+f>e.byteLength)throw new Error(`Truncated GLB chunk: required ${g+f} bytes, buffer has ${e.byteLength}`);if(T===1313821514){let m=new Uint8Array(e,g,f),p=St(m);c=JSON.parse(p,(R,A)=>R==="__proto__"||R==="constructor"||R==="prototype"?void 0:A)}else T===5130562&&(o=e.slice(g,g+f));a=g+f}if(!c)throw new Error("Missing JSON chunk in GLB");let l=c.extensionsRequired||[];if(l.includes("KHR_draco_mesh_compression")&&!pe("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let f of["EXT_meshopt_compression","KHR_meshopt_compression"])if(l.includes(f)&&!pe("meshopt"))throw new Error(`Model requires ${f}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(l.includes("KHR_texture_basisu")&&!pe("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let u=o||new ArrayBuffer(0),d={gltf:c,bin:u,animations:[]};for(let f of ae)f.onParseGLB?.(d);return d}function Dt(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 xe(n){if(Dt(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return ot(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var ct=`#version 300 es
16
+ */var Ve=Object.defineProperty,It=Object.getOwnPropertyDescriptor,_t=Object.getOwnPropertyNames,kt=Object.prototype.hasOwnProperty,Ut=(e,t)=>{for(var i in t)Ve(e,i,{get:t[i],enumerable:!0})},Nt=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of _t(t))!kt.call(e,a)&&a!==i&&Ve(e,a,{get:()=>t[a],enumerable:!(r=It(t,a))||r.enumerable});return e},Bt=e=>Nt(Ve({},"__esModule",{value:!0}),e),mn={};Ut(mn,{WebXRSessionManager:()=>Be,activateAR:()=>ln,buildUSDZZip:()=>Ze,calculateCRC32:()=>Ye,createSceneViewerIntent:()=>Ct,createUSDZBlob:()=>et,generateUSDA:()=>Dt,generateUSDZ:()=>Je,getARCapabilities:()=>st,getAvailableARModes:()=>on,getBestARMode:()=>an,glbToUSDZ:()=>Qe,isQuickLookSupported:()=>nt,isSceneViewerSupported:()=>rt,isWebXRSupported:()=>it,launchQuickLook:()=>tt,launchSceneViewer:()=>Ft}),module.exports=Bt(mn);function le(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function Ee(e,t,i,r,a){let s=1/Math.tan(t/2);e.fill(0),e[0]=s/i,e[5]=s,e[11]=-1;let c=1/(r-a);return e[10]=(a+r)*c,e[14]=2*a*r*c,e}function Le(e,t,i,r){let[a,s,c]=t,[l,g,d]=r,[v,M,I]=i,D=a-v,u=s-M,x=c-I,C=Math.hypot(D,u,x);C<=1e-5?(D=0,u=0,x=1):(D/=C,u/=C,x/=C);let R=g*x-d*u,T=d*D-l*x,m=l*u-g*D;C=Math.hypot(R,T,m),C<=1e-5?(R=0,T=0,m=0):(R/=C,T/=C,m/=C);let h=u*m-x*T,w=x*R-D*m,y=D*T-u*R;return C=Math.hypot(h,w,y),C<=1e-5?(h=0,w=0,y=0):(h/=C,w/=C,y/=C),e[0]=R,e[1]=h,e[2]=D,e[3]=0,e[4]=T,e[5]=w,e[6]=u,e[7]=0,e[8]=m,e[9]=y,e[10]=x,e[11]=0,e[12]=-(R*a+T*s+m*c),e[13]=-(h*a+w*s+y*c),e[14]=-(D*a+u*s+x*c),e[15]=1,e}function fe(e,t,i){let r=t[0],a=t[1],s=t[2],c=t[3],l=t[4],g=t[5],d=t[6],v=t[7],M=t[8],I=t[9],D=t[10],u=t[11],x=t[12],C=t[13],R=t[14],T=t[15],m=i[0],h=i[1],w=i[2],y=i[3];return e[0]=m*r+h*l+w*M+y*x,e[1]=m*a+h*g+w*I+y*C,e[2]=m*s+h*d+w*D+y*R,e[3]=m*c+h*v+w*u+y*T,m=i[4],h=i[5],w=i[6],y=i[7],e[4]=m*r+h*l+w*M+y*x,e[5]=m*a+h*g+w*I+y*C,e[6]=m*s+h*d+w*D+y*R,e[7]=m*c+h*v+w*u+y*T,m=i[8],h=i[9],w=i[10],y=i[11],e[8]=m*r+h*l+w*M+y*x,e[9]=m*a+h*g+w*I+y*C,e[10]=m*s+h*d+w*D+y*R,e[11]=m*c+h*v+w*u+y*T,m=i[12],h=i[13],w=i[14],y=i[15],e[12]=m*r+h*l+w*M+y*x,e[13]=m*a+h*g+w*I+y*C,e[14]=m*s+h*d+w*D+y*R,e[15]=m*c+h*v+w*u+y*T,e}function Ge(e,t,i,r){let a=t[0],s=t[1],c=t[2],l=t[3],g=a+a,d=s+s,v=c+c,M=a*g,I=a*d,D=a*v,u=s*d,x=s*v,C=c*v,R=l*g,T=l*d,m=l*v,h=r[0],w=r[1],y=r[2];return e[0]=(1-(u+C))*h,e[1]=(I+m)*h,e[2]=(D-T)*h,e[3]=0,e[4]=(I-m)*w,e[5]=(1-(M+C))*w,e[6]=(x+R)*w,e[7]=0,e[8]=(D+T)*y,e[9]=(x-R)*y,e[10]=(1-(M+u))*y,e[11]=0,e[12]=i[0],e[13]=i[1],e[14]=i[2],e[15]=1,e}function ve(e,t,i=0){let r=t[0],a=t[1],s=t[2],c=t[4],l=t[5],g=t[6],d=t[8],v=t[9],M=t[10],I=M*l-g*v,D=-M*c+g*d,u=v*c-l*d,x=r*I+a*D+s*u;return!x||i>0&&(!Number.isFinite(x)||Math.abs(x)<=i)||(x=1/x,e[0]=I*x,e[1]=D*x,e[2]=u*x,e[3]=(-M*a+s*v)*x,e[4]=(M*r-s*d)*x,e[5]=(-v*r+a*d)*x,e[6]=(g*a-s*l)*x,e[7]=(-g*r+s*c)*x,e[8]=(l*r-a*c)*x),e}function ot(e,t){let i=t[0],r=t[1],a=t[2],s=t[3],c=t[4],l=t[5],g=t[6],d=t[7],v=t[8],M=t[9],I=t[10],D=t[11],u=t[12],x=t[13],C=t[14],R=t[15],T=i*l-r*c,m=i*g-a*c,h=i*d-s*c,w=r*g-a*l,y=r*d-s*l,F=a*d-s*g,U=v*x-M*u,_=v*C-I*u,k=v*R-D*u,P=M*C-I*x,N=M*R-D*x,S=I*R-D*C,o=T*S-m*N+h*P+w*k-y*_+F*U;return o?(o=1/o,e[0]=(l*S-g*N+d*P)*o,e[1]=(a*N-r*S-s*P)*o,e[2]=(x*F-C*y+R*w)*o,e[3]=(I*y-M*F-D*w)*o,e[4]=(g*k-c*S-d*_)*o,e[5]=(i*S-a*k+s*_)*o,e[6]=(C*h-u*F-R*m)*o,e[7]=(v*F-I*h+D*m)*o,e[8]=(c*N-l*k+d*U)*o,e[9]=(r*k-i*N-s*U)*o,e[10]=(u*y-x*h+R*T)*o,e[11]=(M*h-v*y-D*T)*o,e[12]=(l*_-c*P-g*U)*o,e[13]=(i*P-r*_+a*U)*o,e[14]=(x*m-u*w-C*T)*o,e[15]=(v*w-M*m+I*T)*o,e):null}function $e(e,t,i,r,a){let s=a[0]*t+a[4]*i+a[8]*r+a[12],c=a[1]*t+a[5]*i+a[9]*r+a[13],l=a[2]*t+a[6]*i+a[10]*r+a[14],g=a[3]*t+a[7]*i+a[11]*r+a[15],d=g!==0?1/g:1;e[0]=s*d,e[1]=c*d,e[2]=l*d}function at(e,t,i,r,a,s,c,l,g,d,v,M,I,D,u,x,C=0){let R=d-c,T=v-l,m=M-g,h=I-c,w=D-l,y=u-g,F=a*y-s*w,U=s*h-r*y,_=r*w-a*h,k=R*F+T*U+m*_;if(k>-1e-7&&k<1e-7)return!1;let P=1/k,N=e-c,S=t-l,o=i-g,V=P*(N*F+S*U+o*_);if(V<-C||V>1+C)return!1;let K=S*m-o*T,f=o*R-N*m,b=N*T-S*R,n=P*(r*K+a*f+s*b);if(n<-C||V+n>1+C)return!1;let p=P*(h*K+w*f+y*b);if(p>1e-4&&p<x.distance){x.distance=p,x.point=[e+r*p,t+a*p,i+s*p];let B=T*y-m*w,z=m*h-R*y,j=R*w-T*h,ee=Math.hypot(B,z,j)||1;return x.normal=[B/ee,z/ee,j/ee],!0}return!1}function ut(e,t){let i=Array.isArray(e?.nodes)?e.nodes.length:0,r=[];for(let v=0;v<i;v++)r.push(le());if(i===0)return r;let a=new Set;for(let v of e.nodes)if(Array.isArray(v.children))for(let M of v.children)a.add(M);let s=new Set,c=128,l=(v,M,I=0)=>{if(I>c||v<0||v>=i||s.has(v))return;s.add(v);let D=e.nodes[v];if(!D)return;let u=le();if(t&&t[v])u.set(t[v]);else if(D.matrix&&D.matrix.length===16)u.set(D.matrix);else{let C=D.translation||[0,0,0],R=D.rotation||[0,0,0,1],T=D.scale||[1,1,1];Ge(u,R,C,T)}let x=r[v];if(M?fe(x,M,u):x.set(u),Array.isArray(D.children))for(let C of D.children)typeof C=="number"&&l(C,x,I+1)},g=[],d=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(d&&Array.isArray(d.nodes))g.push(...d.nodes);else for(let v=0;v<i;v++)a.has(v)||g.push(v);for(let v of g)l(v,null);for(let v=0;v<i;v++)!a.has(v)&&!g.includes(v)&&l(v,null);return r}var De="__THREE_LIVE_REGISTRY__";function be(){let e=typeof globalThis<"u"?globalThis:{};if(!e[De]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,De,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[De]=t}}return e[De]}var ce=be().plugins;function ct(e){let t=be().plugins;t.some(i=>i.name===e.name)||t.push(e),e.onRegister?.()}function lt(){return be().plugins}function mt(e,t,i){let r=[],a=new Map,s=[],c=[],l=[],g=new Map,d=m=>{let h=a.get(m);return h===void 0&&(h=r.length,r.push({op:m}),a.set(m,h)),h},v=m=>{let h=g.get(m);return h===void 0&&(h=l.length,l.push({id:m}),g.set(m,h)),h},M=(m,h={})=>s.push({declaration:d(m),...h})-1,I=(m,h,w)=>c.push({id:m,type:h,value:w})-1,D=m=>({node:m,socket:"value"}),u=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(u&&typeof u=="object"){let m=Array.isArray(u.graphs)?u.graphs[u.graph??0]:u;if(m&&Array.isArray(m.nodes)){let h=Array.isArray(m.declarations)?m.declarations:[];for(let w of h)w?.op&&d(w.op);Array.isArray(m.variables)&&c.push(...m.variables);for(let w of m.events||[])w?.id&&v(w.id);for(let w of m.nodes){if(!w||typeof w!="object")continue;let y=w.op||(typeof w.declaration=="number"?h[w.declaration]?.op:"");s.push(y?{...w,declaration:d(y)}:{...w})}}}let x=(m,h,w="translation")=>w==="baseColorFactor"||w==="metallicFactor"||w==="roughnessFactor"?`/materials/${Math.max(0,h)}/pbrMetallicRoughness/${w}`:w==="emissiveFactor"||w==="alphaCutoff"?`/materials/${Math.max(0,h)}/${w}`:w==="visible"?`/nodes/${m}/extensions/KHR_node_visibility/visible`:`/nodes/${m}/${w}`,C=new Map;e.forEach((m,h)=>{typeof m?.name=="string"&&!C.has(m.name)&&C.set(m.name,h)});let R=(m,h)=>typeof m.target=="string"&&C.has(m.target)?C.get(m.target):typeof m.targetNode=="number"?m.targetNode:h,T=m=>{let h=e[m];return(typeof h?.mesh=="number"?t[h.mesh]?.primitives?.[0]?.material:0)??0};for(let m=0;m<e.length;m++){let h=e[m],w=h?.extras?.interactivity;if(!w||typeof w!="object")continue;let y=(typeof h.mesh=="number"?t[h.mesh]?.primitives?.[0]?.material:0)??0,F=_=>{let k=Array.isArray(_)?_:[_],P=[];for(let S=0;S<k.length;S++){let o=k[S];if(!o||typeof o!="object")continue;let V=o.action||"interpolate",K=typeof o.duration=="number"?o.duration:.35;if(V==="toggleTransform"){let f=o.property==="rotation"||o.property==="scale"?o.property:"translation",b=f==="rotation"?h.rotation||[0,0,0,1]:f==="scale"?h.scale||[1,1,1]:h.translation||[0,0,0],n=`/nodes/${m}/${f}`,p=I(`__toggle_${m}_${S}`,"bool",!1),B=M("variable/get",{configuration:{variable:p}}),z=M("math/not",{values:{a:D(B)}}),j=M("variable/set",{configuration:{variable:p},values:{value:D(z)}}),ee=M("pointer/interpolate",{configuration:{pointer:n},values:{value:{value:Array.isArray(o.to)?o.to:b},duration:{value:K}}}),L=M("pointer/interpolate",{configuration:{pointer:n},values:{value:{value:Array.isArray(o.from)?o.from:b},duration:{value:K}}});s[j].flows={out:{node:M("flow/branch",{values:{condition:D(B)},flows:{true:{node:ee},false:{node:L}}})}},P.push(j)}else if(V==="interpolate"){let f=o.to??o.value;if(f===void 0)continue;let b={value:{value:f},duration:{value:K}};o.from!==void 0&&(b.from={value:o.from}),P.push(M("pointer/interpolate",{configuration:{pointer:typeof o.pointer=="string"?o.pointer:x(R(o,m),T(R(o,m)),o.property)},values:b}))}else if(V==="setProperty"){if(o.value===void 0)continue;P.push(M("pointer/set",{configuration:{pointer:typeof o.pointer=="string"?o.pointer:x(R(o,m),T(R(o,m)),o.property)},values:{value:{value:o.value}}}))}else if(V==="toggleVisibility"){let f=R(o,m),b=I(`__vis_${f}_${S}`,"bool",!0),n=M("variable/get",{configuration:{variable:b}}),p=M("math/not",{values:{a:D(n)}}),B=M("variable/set",{configuration:{variable:b},values:{value:D(p)}});s[B].flows={out:{node:M("pointer/set",{configuration:{pointer:`/nodes/${f}/extensions/KHR_node_visibility/visible`},values:{value:D(n)}})}},P.push(B)}else if(V==="cycleMaterialColor"&&Array.isArray(o.colors)&&o.colors.length>0){let f=typeof o.duration=="number"?o.duration:.25,b=`/materials/${Math.max(0,y)}/pbrMetallicRoughness/baseColorFactor`,n=I(`__color_idx_${m}_${S}`,"int",0),p=M("variable/get",{configuration:{variable:n}}),B=M("math/add",{values:{a:D(p),b:{value:1}}}),z=M("math/rem",{values:{a:D(B),b:{value:o.colors.length}}}),j=M("variable/set",{configuration:{variable:n},values:{value:D(z)}}),ee={};for(let L=0;L<o.colors.length;L++){let X=o.colors[L],J=Array.isArray(X)&&X.length>=3?[X[0],X[1],X[2],X[3]??1]:[1,1,1,1];ee[String(L)]={node:f>0?M("pointer/interpolate",{configuration:{pointer:b},values:{value:{value:J},duration:{value:f}}}):M("pointer/set",{configuration:{pointer:b},values:{value:{value:J}}})}}s[j].flows={out:{node:M("flow/switch",{values:{selection:D(p)},flows:ee})}},P.push(j)}else if(V==="playAnimation")P.push(M("animation/start",{configuration:{animation:o.animation??o.clip??0}}));else if(V==="stopAnimation")P.push(M("animation/stop"));else if(V==="sendEvent"){let f={};for(let[b,n]of Object.entries(o.values||{}))f[b]={value:n};P.push(M("event/send",{configuration:{event:v(String(o.event??o.id??"custom"))},values:f}))}}if(!P.length)return null;if(P.length===1)return P[0];let N={};return P.forEach((S,o)=>{N[String(o)]={node:S}}),M("flow/sequence",{flows:N})},U=(_,k,P)=>{let N=F(k);N!==null&&M(_,{...P?{configuration:P}:{},flows:{out:{node:N}}})};if(w.onSelect&&U("pointer/onSelect",w.onSelect,{nodeIndex:m}),w.onHoverIn&&U("pointer/onHoverIn",w.onHoverIn,{nodeIndex:m}),w.onHoverOut&&U("pointer/onHoverOut",w.onHoverOut,{nodeIndex:m}),w.onStart&&U("event/onStart",w.onStart),w.onReceive&&typeof w.onReceive=="object")for(let[_,k]of Object.entries(w.onReceive))U("event/receive",k,{event:v(_)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:c,events:l}],graph:0}:null}var Ot={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function He(e,t,i,r){if(!i||i.bufferView===void 0)return null;let a=e.bufferViews?.[i.bufferView];if(!a)return null;let s=Number(i.count??0);if(!Number.isInteger(s)||s<=0)return null;let c=i.componentType??5126,l=Ot[c];if(!l)throw new RangeError(`glTF accessor has unsupported componentType ${c}`);let g=l*r,d=a.byteStride&&a.byteStride>0?a.byteStride:g,v=(a.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(v)||v<0||d<g||v+(s-1)*d+g>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(c===5126&&d===g&&v%4===0)return new Float32Array(t,v,s*r);let M=new DataView(t),I=i.normalized===!0,D=new Float32Array(s*r);for(let u=0;u<s;u++){let x=v+u*d;for(let C=0;C<r;C++){let R=x+C*l,T;switch(c){case 5126:T=M.getFloat32(R,!0);break;case 5120:T=M.getInt8(R),I&&(T=Math.max(T/127,-1));break;case 5121:T=M.getUint8(R),I&&(T/=255);break;case 5122:T=M.getInt16(R,!0),I&&(T=Math.max(T/32767,-1));break;case 5123:T=M.getUint16(R,!0),I&&(T/=65535);break;default:T=M.getUint32(R,!0),I&&(T/=4294967295)}D[u*r+C]=T}}return D}function ht(e,t){let i=Number(t.offset?.[0]??0)||0,r=Number(t.offset?.[1]??0)||0,a=Number(t.scale?.[0]??1),s=Number(t.scale?.[1]??1),c=Number(t.rotation??0)||0,l=Math.cos(c),g=Math.sin(c),d=(Number.isFinite(a)?a:1)*l,v=(Number.isFinite(a)?a:1)*g,M=-(Number.isFinite(s)?s:1)*g,I=(Number.isFinite(s)?s:1)*l;for(let D=0;D+1<e.length;D+=2){let u=e[D],x=e[D+1];e[D]=d*u+v*x+i,e[D+1]=M*u+I*x+r}}function Pe(e,t,i,r=!0){let a=[],s=null;try{for(let[c,l]of[[35633,t],[35632,i]]){let g=e.createShader(c);if(!g){if(r)throw new Error("Shader allocation failed");return null}if(a.push(g),e.shaderSource(g,l),e.compileShader(g),e.getShaderParameter&&!e.getShaderParameter(g,35713)){if(r)throw new Error(`Shader compile error: ${e.getShaderInfoLog(g)}`);return null}}if(s=e.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let c of a)e.attachShader(s,c);if(e.linkProgram(s),e.getProgramParameter&&!e.getProgramParameter(s,35714)){let c=r?e.getProgramInfoLog(s):null;if(e.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${c}`);return null}return s}finally{for(let c of a)s&&e.detachShader?.(s,c),e.deleteShader?.(c)}}var pt=["neutral","reinhard","none","aces","agx"];function Xe(e){let t=String(e??"").trim().toLowerCase();return pt.includes(t)?t:"neutral"}function Vt(e){return pt.indexOf(Xe(e))}function Gt(e){return new TextDecoder().decode(e)}var bt=be().decoders;function $t(e,t){bt.set(e.toLowerCase(),t)}function we(e){return bt.get(e.toLowerCase())}function gt(e){let t=ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e,i=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let r=i.getUint32(0,!0);if(r!==1179937895){let I=i.getUint8(0);throw I===123||I===32||I===10||I===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 a=i.getUint32(4,!0);if(a!==2)throw new Error(`Unsupported GLB version: ${a}`);let s=i.getUint32(8,!0),c=12,l=null,g=null;for(;c+8<=s&&c+8<=t.byteLength;){let I=i.getUint32(c,!0),D=i.getUint32(c+4,!0),u=c+8;if(u+I>t.byteLength)throw new Error(`Truncated GLB chunk: required ${u+I} bytes, buffer has ${t.byteLength}`);if(D===1313821514){let x=new Uint8Array(t,u,I),C=Gt(x);l=JSON.parse(C,(R,T)=>R==="__proto__"||R==="constructor"||R==="prototype"?void 0:T)}else D===5130562&&(g=t.slice(u,u+I));c=u+I}if(!l)throw new Error("Missing JSON chunk in GLB");let d=l.extensionsRequired||[];if(d.includes("KHR_draco_mesh_compression")&&!we("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let I of["EXT_meshopt_compression","KHR_meshopt_compression"])if(d.includes(I)&&!we("meshopt"))throw new Error(`Model requires ${I}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(d.includes("KHR_texture_basisu")&&!we("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let v=g||new ArrayBuffer(0),M={gltf:l,bin:v,animations:[]};for(let I of ce)I.onParseGLB?.(M);return M}function Ht(e){return typeof e=="object"&&e!==null&&"gltf"in e&&typeof e.gltf=="object"&&e.gltf!==null&&"bin"in e&&(e.bin instanceof ArrayBuffer||ArrayBuffer.isView(e.bin))}function Se(e){if(Ht(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return gt(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var yt=`#version 300 es
18
17
  layout(location=0) in vec3 aPos;
19
18
  layout(location=3) in vec3 aOff;
20
19
  layout(location=1) in vec3 aNormal;
@@ -49,7 +48,7 @@ vec2 scaleUV=uUvTransform.zw;
49
48
  if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
50
49
  vUV=aUV*scaleUV+uUvTransform.xy;
51
50
  gl_Position=uMVP*vec4(aPosition,1.0);
52
- }`,Ft=`#version 300 es
51
+ }`,zt=`#version 300 es
53
52
  precision highp float;
54
53
  in vec3 vNormal,vWorldPos;
55
54
  in vec2 vUV;
@@ -66,7 +65,8 @@ uniform float uNormalScale,uOcclusionStrength;
66
65
  uniform vec2 uViewportSize;
67
66
  uniform vec4 uSectionPlane;
68
67
  uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
69
- uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2];
68
+ uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2],uPointLightSpotDir[2];
69
+ uniform vec2 uPointLightSpotCone[2];
70
70
  out vec4 fragColor;
71
71
 
72
72
  vec2 envBRDF(float r,float n){
@@ -157,6 +157,11 @@ if(mode==4)return agxToneMapping(color);
157
157
  return color;
158
158
  }
159
159
 
160
+ vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 base,float specExp,float specWeight){
161
+ float NoH=max(dot(N,normalize(L+V)),0.0);
162
+ return base*max(dot(N,L),0.0)*0.75+vec3(pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
163
+ }
164
+
160
165
  void main(){
161
166
  if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
162
167
  vec4 base=uBaseColor;
@@ -194,24 +199,16 @@ float specWeight=mix(0.22*gloss,1.0,metallic);
194
199
  vec3 directLight=vec3(0.0);
195
200
  for(int i=0;i<2;i++){
196
201
  if(i>=uNumDirLights)break;
197
- vec3 L=normalize(uDirLightDir[i]);
198
- float NdotL=max(dot(N,L),0.0);
199
- vec3 H=normalize(L+V);
200
- float NoH=max(dot(N,H),0.0);
201
- float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
202
- directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uDirLightColor[i];
202
+ directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i];
203
203
  }
204
204
  for(int i=0;i<2;i++){
205
205
  if(i>=uNumPointLights)break;
206
206
  vec3 toLight=uPointLightPos[i]-vWorldPos;
207
207
  float dist=length(toLight);
208
208
  vec3 L=toLight/max(dist,0.0001);
209
- float atten=1.0/(1.0+0.09*dist+0.032*dist*dist);
210
- float NdotL=max(dot(N,L),0.0);
211
- vec3 H=normalize(L+V);
212
- float NoH=max(dot(N,H),0.0);
213
- float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
214
- directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uPointLightColor[i]*atten;
209
+ float spotAtt=clamp((dot(-L,uPointLightSpotDir[i])-uPointLightSpotCone[i].y)/max(uPointLightSpotCone[i].x-uPointLightSpotCone[i].y,0.0001),0.0,1.0);
210
+ spotAtt*=spotAtt;
211
+ directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist);
215
212
  }
216
213
 
217
214
  vec3 R=reflect(-V,N);
@@ -242,80 +239,130 @@ color=applyToneMapping(color,uToneMapping);
242
239
  float outAlpha=base.a;
243
240
  /*XRD_O*/
244
241
  fragColor=vec4(color,outAlpha);
245
- }`;var Ct=`#version 300 es
242
+ }`,Wt=`#version 300 es
246
243
  layout(location=0) in vec3 aPosition;
247
244
  uniform mat4 uMVP;
248
- void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,It=`#version 300 es
245
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Xt=`#version 300 es
249
246
  precision highp float;
250
247
  uniform vec4 uColorId;
251
248
  out vec4 fragColor;
252
- void main(){fragColor=uColorId;}`;function Be(n,e,t){let r={};for(let i of t)r[i]=n.getUniformLocation(e,i);return r}var rt=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function ut(){let n=he().xrDepthShader;return{fs:Ft.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...rt,...n.uniformNames]:rt}}function _t(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,c){if(r===void 0||!e.accessors?.[r])return null;let o=_e(e,t,e.accessors[r],s);if(!o)return null;c&&(o=o.slice(),nt(o,c));let l=n.createBuffer();return a.push(l),n.bindBuffer(34962,l),n.bufferData(34962,o,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),o}function Ue(n){let e=Number(n);return Number.isFinite(e)?Math.max(0,e):1}function lt(n,e,t){let r=ut(),i=ct,s=r.fs,a=!1;for(let o of ae)if(o.onResolveShader){let l=o.onResolveShader(e,t,i,s);l&&(i=l.vs,s=l.fs,a=!0)}let c=a?we(n,i,s):null;return{program:c,uniforms:c?Be(n,c,r.uniforms):null}}function Nt(n,e,t){let r=e.instanceMatrices;if(!r||r.length<16||typeof n.vertexAttribDivisor!="function"||typeof n.drawElementsInstanced!="function")return!1;let i=r.length>>4,s=e.instanceColors,a=new Float32Array(i*20);for(let o=0;o<i;o++)a.set(r.subarray(o*16,o*16+16),o*20),a[o*20+16]=s?s[o*3]:1,a[o*20+17]=s?s[o*3+1]:1,a[o*20+18]=s?s[o*3+2]:1,a[o*20+19]=1;let c=n.createBuffer();t.push(c),n.bindBuffer(34962,c),n.bufferData(34962,a,35044);for(let o=0;o<5;o++)n.enableVertexAttribArray(8+o),n.vertexAttribPointer(8+o,4,5126,!1,80,o*16),n.vertexAttribDivisor(8+o,1);return!0}function Ut(n,e){let t=n.materials?.[e?.material];if(!t)return null;let r=[t.pbrMetallicRoughness?.baseColorTexture,t.pbrMetallicRoughness?.metallicRoughnessTexture,t.normalTexture,t.occlusionTexture,t.emissiveTexture];for(let i of r){let s=i?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var sn=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),mt=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Re(n,e){e.indices?n.drawElements(4,e.indexCount,e.indexType,0):n.drawArrays(4,0,e.indexCount)}function ht(n,e){let t=n?.pbrMetallicRoughness,r=t?.baseColorFactor,i=n?.extensions?.KHR_materials_clearcoat,s=a=>a!==void 0&&e[a.index]?e[a.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:t?.metallicFactor??.1,roughness:t?.roughnessFactor??.5,clearcoat:i?i.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,i?.clearcoatRoughnessFactor??.04),texture:s(t?.baseColorTexture),metallicRoughnessTexture:s(t?.metallicRoughnessTexture),normalTexture:s(n?.normalTexture),normalScale:n?.normalTexture?.scale??1,occlusionTexture:s(n?.occlusionTexture),occlusionStrength:n?.occlusionTexture?.strength??1,isTransmissive:(n?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function ft(n,e,t){let r=new Set,i=s=>{s&&!r.has(s)&&(r.add(s),n.deleteTexture(s))};for(let s of e)for(let a of s.primitives){if(a.vao&&n.deleteVertexArray(a.vao),a.buffers)for(let o of a.buffers)n.deleteBuffer(o);i(a.texture),i(a.metallicRoughnessTexture),i(a.normalTexture),i(a.occlusionTexture);let c=new Set;a.customProgram&&c.add(a.customProgram);for(let o of a.programCache?.values()??[])o.program&&c.add(o.program);for(let o of c)n.deleteProgram(o)}if(t)for(let s of t)i(s)}function it(n,e,t=mt,r){let i={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return kt(n,e,t,r,i)}catch(s){let a=i.mesh&&!i.meshes.includes(i.mesh)?[...i.meshes,i.mesh]:i.meshes;ft(n,a,i.gpuTextures),i.vao&&n.deleteVertexArray(i.vao);for(let c of i.buffers)n.deleteBuffer(c);throw s}}function kt(n,e,t,r,i){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=e,a=pe("meshopt");a?.decodeBufferViews&&a.decodeBufferViews(s,e);let c=e.bin,o=[];i.meshes=o;let l=[],u=s.extensions?.KHR_materials_variants;u&&Array.isArray(u.variants)&&u.variants.forEach((h,w)=>{l.push(typeof h?.name=="string"&&h.name?h.name:`Variant_${w}`)});let d=Te(s),f=[];if(Array.isArray(s.nodes))for(let h=0;h<s.nodes.length;h++){let w=s.nodes[h];w.mesh!==void 0&&s.meshes&&s.meshes[w.mesh]&&f.push({node:w,nodeIdx:h,meshIdx:w.mesh})}let T=f.length>0?f:(s.meshes||[]).map((h,w)=>({node:h,nodeIdx:-1,meshIdx:w})),g=[];if(Array.isArray(e.lights)&&e.lights.length>0)g.push(...e.lights);else if(s.extensions?.KHR_lights_punctual?.lights){let h=s.extensions.KHR_lights_punctual.lights;for(let w of h){let S=w.type==="directional"?"directional":w.type==="point"?"point":"ambient";g.push({type:S,color:w.color||[1,1,1],intensity:w.intensity!==void 0?w.intensity:1})}}if(g.length===0&&(g.push({type:"ambient",color:[1,1,1],intensity:.35}),g.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),T.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${T.length}`);let m=[];if(i.gpuTextures=m,s.textures&&s.images){if(s.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${s.textures.length}`);for(let h=0;h<s.textures.length;h++){let w=s.textures[h],S=s.images[w.source];if(S){let M=n.createTexture();if(n.bindTexture(3553,M),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),S.bufferView!==void 0){let k=s.bufferViews[S.bufferView],_=c.slice(k.byteOffset||0,(k.byteOffset||0)+k.byteLength),K=new Blob([_],{type:S.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(K).then(U=>{n.bindTexture(3553,M),n.texImage2D(3553,0,6408,6408,5121,U),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(S.uri){let k=_t(S.uri);if(k){let _=new Image;_.crossOrigin="anonymous",_.referrerPolicy="no-referrer",_.onload=()=>{n.bindTexture(3553,M),n.texImage2D(3553,0,6408,6408,5121,_),n.generateMipmap(3553),r?.()},_.src=k}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",S.uri)}m.push(M)}else m.push(null)}}let p=[1/0,1/0,1/0],R=[-1/0,-1/0,-1/0],A=0,v=0;for(let h=0;h<T.length;h++){let w=T[h],S=s.meshes[w.meshIdx],M=w.nodeIdx>=0?d[w.nodeIdx]:re(),k=new Float32Array(9);me(k,M);let _={name:w.node.name||S.name||`Mesh_${w.meshIdx}`,nodeIndex:w.nodeIdx,transform:M,normalMatrix:k,primitives:[],extras:w.node.extras||S.extras};i.mesh=_;let K=w.node?.extensions?.EXT_mesh_gpu_instancing;if(K&&K.attributes&&typeof K.attributes=="object"){let U=K.attributes,O=U.TRANSLATION!==void 0?s.accessors?.[U.TRANSLATION]:null,B=U.ROTATION!==void 0?s.accessors?.[U.ROTATION]:null,q=U.SCALE!==void 0?s.accessors?.[U.SCALE]:null,Y=U._COLOR_0!==void 0?s.accessors?.[U._COLOR_0]:null,W=Number(O?.count??B?.count??q?.count??0);if(!Number.isFinite(W)||W<0||W>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${W}`);if(W>0){let j=(H,$)=>{if(!H||H.bufferView===void 0||!s.bufferViews?.[H.bufferView])return null;let G=H.componentType??5126,te=J=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${J})`),null);if(G!==5120&&G!==5121&&G!==5122&&G!==5123&&G!==5126)return te(`componentType ${G}`);if(!(Number(H.count)>=W))return te(`count ${H.count} < ${W}`);let V=null;try{V=_e(s,c,{...H,count:W},$)}catch{return te("out of bounds")}return!V||!V.every(Number.isFinite)?te("non-finite value"):V},x=j(O,3),I=j(B,4),N=j(q,3),z=Y?.type==="VEC4"?4:3,ee=j(Y,z),ie=new Float32Array(W*16),oe=re();for(let H=0;H<W;H++){let $=x?[x[H*3],x[H*3+1],x[H*3+2]]:[0,0,0],G=I?[I[H*4],I[H*4+1],I[H*4+2],I[H*4+3]]:[0,0,0,1],te=N?[N[H*3],N[H*3+1],N[H*3+2]]:[1,1,1];ye(oe,G,$,te),ie.set(oe,H*16)}if(_.instanceMatrices=ie,ee){let H=new Float32Array(W*3);for(let $=0;$<W;$++)H[$*3]=ee[$*z],H[$*3+1]=ee[$*z+1],H[$*3+2]=ee[$*z+2];_.instanceColors=H}}}for(let U of S.primitives||[]){if(U.extensions?.KHR_draco_mesh_compression){let V=pe("draco");V&&V.decodePrimitive(s,U,c)}let O=[],B=n.createVertexArray();i.vao=B,i.buffers=O,n.bindVertexArray(B);let q=Nt(n,_,O),Y=s.accessors[U.attributes.POSITION],W=Number(Y?.count??0);if(!Number.isFinite(W)||W<0||A+W>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(A+=W,Y?.min&&Y?.max){let V=J=>{for(let Q=0;Q<3;Q++){let Z=J[12+Q],ne=J[12+Q];for(let le=0;le<3;le++){let ce=J[le*4+Q]*Y.min[le],ue=J[le*4+Q]*Y.max[le];Z+=ce<ue?ce:ue,ne+=ce>ue?ce:ue}Z<p[Q]&&(p[Q]=Z),ne>R[Q]&&(R[Q]=ne)}};if(_.instanceMatrices&&_.instanceMatrices.length>=16){let J=_.instanceMatrices.length>>4,Q=re();for(let Z=0;Z<J;Z++){let ne=_.instanceMatrices.subarray(Z*16,Z*16+16);se(Q,M,ne),V(Q)}}else V(M)}let j=Ne(n,s,c,U.attributes.POSITION,0,3,O);Ne(n,s,c,U.attributes.NORMAL,1,3,O),Ne(n,s,c,U.attributes.TEXCOORD_0,2,2,O,Ut(s,U));let x=0,I=5123,N=null;if(U.indices!==void 0){let V=s.accessors[U.indices],Q=(s.bufferViews[V.bufferView].byteOffset||0)+(V.byteOffset||0);if(x=Number(V.count??0),!Number.isFinite(x)||x<0||v+x>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);v+=x,I=V.componentType===5125?5125||5125:5123||5123;let Z=n.createBuffer();O.push(Z),n.bindBuffer(34963,Z),V.componentType===5125?(N=new Uint32Array(c,Q,V.count),n.bufferData(34963,N,35044)):V.componentType===5121?(N=Uint16Array.from(new Uint8Array(c,Q,V.count)),n.bufferData(34963,N,35044)):(N=Q%2===0?new Uint16Array(c,Q,V.count):new Uint16Array(c.slice(Q,Q+V.count*2)),n.bufferData(34963,N,35044))}else x=Y.count;let z={};for(let V of ae)if(V.onBuildPrimitiveVAO){let J=V.onBuildPrimitiveVAO(n,B,U,s,c);J&&(z[V.name]=J)}n.bindVertexArray(null);let ee=s.materials&&U.material!==void 0?s.materials[U.material]:null,{program:ie,uniforms:oe}=lt(n,U,ee),H=ht(ee,m),$=!!(ee?.extensions?.KHR_materials_transmission||z.materials?.isTransmissive),G=U.extensions?.KHR_materials_variants?.mappings,te=Array.isArray(G)?G.filter(V=>V&&typeof V.material=="number"&&Array.isArray(V.variants)).map(V=>({material:V.material|0,variants:V.variants.map(J=>Number(J)|0)})):void 0;_.primitives.push({vao:B,instanced:q,indexCount:x,indexType:I,...H,positions:j,indices:N,buffers:O,materialIndex:U.material,defaultMaterialIndex:U.material,variantMappings:te,primitiveDef:U,programCache:new Map([[U.material??-1,{program:ie,uniforms:oe}]]),pluginData:z,customProgram:ie,customUniforms:oe,isTransmissive:$})}o.push(_)}isFinite(p[0])||(p=[-1,-1,-1]),isFinite(R[0])||(R=[1,1,1]);let D=[(p[0]+R[0])/2,(p[1]+R[1])/2,(p[2]+R[2])/2],y=R[0]-p[0],P=R[1]-p[1],E=R[2]-p[2],b=Math.max(Math.hypot(y,P,E)/2,.5),F=[p[0],p[1],p[2]],L=[R[0],R[1],R[2]],C=e.animations;if(!C){for(let h of ae)if(h.onParseGLB?.(e),e.animations){C=e.animations;break}}return C||(C=[]),{meshes:o,bounds:{center:D,radius:b,min:F,max:L},lights:g,animations:C,worldMatrices:d,gpuTextures:m,availableVariants:l}}function ge(n){let e=n.customTarget||n.bounds.center,t=n.currDistance*Math.cos(n.currPhi);return[e[0]+t*Math.sin(n.currTheta),e[1]+n.currDistance*Math.sin(n.currPhi),e[2]+t*Math.cos(n.currTheta)]}var Ee=class{constructor(e,t,r){this.supportsInstanceOffsets=!0;this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=re();this.clearColor=[0,0,0,0];this.envIntensity=1;this.exposure=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gpuTextures=[];this.availableVariants=[];this.activeVariantName=null;this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=re();this.viewMatrix=re();this.activeViewMatrix=null;this.modelMatrix=re();this.mvpMatrix=re();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.contextLost=!1;this.lastGlbData=null;this.boundContextLost=null;this.boundContextRestored=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:re(),rawValueToMeters:.001,format:0};this.container=e;let i,s;if(t&&typeof t.getContext=="function"?(i=t,s=r):(s=t,i=s?.canvas),!i){let o=e.querySelector("canvas");o||(o=document.createElement("canvas"),o.style.width="100%",o.style.height="100%",o.style.display="block",o.style.touchAction="none",e.prepend(o)),i=o}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!a:a&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=Ue(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=ke(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 c=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!c)throw new Error("WebGL2 not supported");this.gl=c,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){Pt(e,t)}static getDecoder(e){return pe(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=ut();this.renderProg=we(e,ct,t.fs),this.pickProg=we(e,Ct,It),this.uRender=Be(e,this.renderProg,t.uniforms),this.uPick=Be(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of ae)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=r,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,r,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,r),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),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){this.lastGlbData=e,this.lastLimits=t;let{meshes:r,bounds:i,lights:s,animations:a,worldMatrices:c,gpuTextures:o,availableVariants:l}=it(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=c||[],this.gpuTextures=o||[],this.availableVariants=l||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let f of e.gltf.nodes)this.initialNodeTransforms.push({t:f.translation?[f.translation[0],f.translation[1],f.translation[2]]:[0,0,0],r:f.rotation?[f.rotation[0],f.rotation[1],f.rotation[2],f.rotation[3]]:[0,0,0,1],s:f.scale?[f.scale[0],f.scale[1],f.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let f of ae)f.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let u=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;u!==void 0&&(this.exposure=Ue(u));let d=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;d!==void 0&&(this.envIntensity=Math.max(0,Number(d)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(ot(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(xe(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=xe(e),{meshes:i}=it(this.gl,r,mt,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],me(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),me(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],a=[],c=[];for(let o of this.lights){let l=o.color||[1,1,1],u=o.intensity!==void 0?o.intensity:1;if(o.type==="ambient")r=[l[0]*u,l[1]*u,l[2]*u];else if(o.type==="directional"&&i.length<6){let d=o.direction||[.5,1,.8];i.push(d[0],d[1],d[2]),s.push(l[0]*u,l[1]*u,l[2]*u)}else if(o.type==="point"&&a.length<6){let d=o.position||[0,0,0];a.push(d[0],d[1],d[2]),c.push(l[0]*u,l[1]*u,l[2]*u)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),t.uniform1i(e.uNumDirLights,i.length/3),i.length>0&&(t.uniform3fv(e.uDirLightDir,i),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,a.length/3),a.length>0&&(t.uniform3fv(e.uPointLightPos,a),t.uniform3fv(e.uPointLightColor,c)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Ue(e)}getExposure(){return this.exposure}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=ke(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of ae)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ae)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,r=this.currDistance;return{theta:e,phi:t,radius:r,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${r.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,r)=>{let i=this.meshes.flatMap(u=>u.primitives.filter(d=>d.materialIndex===r||e.length===1&&d.materialIndex===void 0)),s=i[0],a=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],c=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,o=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,l={baseColorFactor:a,metallicFactor:c,roughnessFactor:o,setBaseColorFactor:u=>{let d=[u[0],u[1],u[2],u[3]??1];l.baseColorFactor=d,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=d);for(let f of i)f.baseColor=d;this.render()},setMetallicFactor:u=>{l.metallicFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=u);for(let d of i)d.metallic=u;this.render()},setRoughnessFactor:u=>{l.roughnessFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=u);for(let d of i)d.roughness=u;this.render()}};return{name:t.name||`Material_${r}`,pbrMetallicRoughness:l}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let s of this.meshes)for(let a of s.primitives){let c=a.defaultMaterialIndex;if(!t&&Array.isArray(a.variantMappings)){for(let l of a.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(r)){c=l.material;break}}let o=c!==void 0?i[c]:void 0;a.materialIndex=o?c:void 0,Object.assign(a,ht(o,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,o??null)}return!0}applyPrimitiveProgram(e,t,r){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let i=t??-1,s=e.programCache.get(i);s||(s=lt(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,s)),e.customProgram=s.program,e.customUniforms=s.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of ae)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=re();se(r,this.projMatrix,this.viewMatrix);let[i,s,a]=e,c=t?t[0]:0,o=t?t[1]:0,l=t?t[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*e[0]+u[4]*e[1]+u[8]*e[2]+u[12],s=u[1]*e[0]+u[5]*e[1]+u[9]*e[2]+u[13],a=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]+u[14],t&&(c=u[0]*t[0]+u[4]*t[1]+u[8]*t[2],o=u[1]*t[0]+u[5]*t[1]+u[9]*t[2],l=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]));let d=r[0]*i+r[4]*s+r[8]*a+r[12],f=r[1]*i+r[5]*s+r[9]*a+r[13],T=r[2]*i+r[6]*s+r[10]*a+r[14],g=r[3]*i+r[7]*s+r[11]*a+r[15];if(g<=1e-4)return{x:0,y:0,z:1,visible:!1};let m=d/g,p=f/g,R=T/g,A=this.canvas.getBoundingClientRect(),v=A.width||this.canvas.clientWidth||this.canvas.width||300,D=A.height||this.canvas.clientHeight||this.canvas.height||150,y=(m*.5+.5)*v,P=(-p*.5+.5)*D,E=m>=-1.1&&m<=1.1&&p>=-1.1&&p<=1.1&&R>=-1&&R<=1;if(E&&t){let[b,F,L]=ge(this),C=[i-b,s-F,a-L];c*C[0]+o*C[1]+l*C[2]>.05&&(E=!1)}return{x:y,y:P,z:R,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]],c=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],o=this.customTarget?[...this.customTarget]:[...this.bounds.center],l=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;o[0]+=(-i*a[0]+s*c[0])*l,o[1]+=(-i*a[1]+s*c[1])*l,o[2]+=(-i*a[2]+s*c[2])*l,this.customTarget=o}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.boundContextLost&&(e.removeEventListener("webglcontextlost",this.boundContextLost),this.boundContextLost=null),this.boundContextRestored&&(e.removeEventListener("webglcontextrestored",this.boundContextRestored),this.boundContextRestored=null),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,c=i.width>0?Math.floor((e-i.left)*(s/i.width)):Math.floor(e),o=i.height>0?Math.floor((t-i.top)*(a/i.height)):Math.floor(t);return this.performMeshPick(c,o,!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 c=re();se(c,this.projMatrix,this.viewMatrix);let o=[],l=Math.max(0,Math.min(s-1,e)),u=Math.max(0,Math.min(a-1,a-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==a)&&this.resizePickingFbo(s,a),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,a),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let E=0;E<this.meshes.length;E++){let b=this.meshes[E];if(b.visible===!1||b.isPluginMesh)continue;let F=E+1,L=(F&255)/255,C=(F>>8&255)/255,h=(F>>16&255)/255;i.uniform4f(this.uPick.uColorId,L,C,h,1),se(this.modelMatrix,this.modelRootMatrix,b.transform);let w=b.instanceMatrices;if(w&&w.length>=16){let S=w.length>>4,M=re();for(let k of b.primitives){i.bindVertexArray(k.vao);for(let _=0;_<S;_++)se(M,this.modelMatrix,w.subarray(_*16,_*16+16)),se(this.mvpMatrix,c,M),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Re(i,k)}}else{se(this.mvpMatrix,c,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let S of b.primitives)i.bindVertexArray(S.vao),Re(i,S)}}let y=new Uint8Array(4);i.readPixels(l,u,1,1,6408,5121,y),i.bindFramebuffer(36160,null);let P=y[0]+(y[1]<<8)+(y[2]<<16);P>0&&P<=this.meshes.length&&(o=[this.meshes[P-1]])}o.length===0&&(o=this.meshes.filter(y=>y.visible!==!1));let d=null,f=1/0,T=[0,0,0],g=[0,1,0],[m,p,R]=ge(this),A=re();for(let y of o){se(A,this.modelRootMatrix,y.transform);let P=y.instanceMatrices,E=P&&P.length>=16?P.length>>4:1;for(let b=0;b<E;b++){P&&P.length>=16?se(this.modelMatrix,A,P.subarray(b*16,b*16+16)):this.modelMatrix.set(A),se(this.mvpMatrix,c,this.modelMatrix);let F=re();if(!Qe(F,this.mvpMatrix))continue;let L=(l+.5)/s*2-1,C=(u+.5)/a*2-1,h=[0,0,0],w=[0,0,0];Ie(h,L,C,-1,F),Ie(w,L,C,1,F);let S=w[0]-h[0],M=w[1]-h[1],k=w[2]-h[2],_=Math.hypot(S,M,k)||1,K=S/_,U=M/_,O=k/_,B={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((Y=>{for(let W of y.primitives){if(!W.positions)continue;let j=W.positions,x=W.indices,I=Math.floor(x?x.length/3:j.length/9);for(let N=0;N<I;N++){let z=x?x[N*3]:N*3,ee=x?x[N*3+1]:N*3+1,ie=x?x[N*3+2]:N*3+2;Je(h[0],h[1],h[2],K,U,O,j[z*3],j[z*3+1],j[z*3+2],j[ee*3],j[ee*3+1],j[ee*3+2],j[ie*3],j[ie*3+1],j[ie*3+2],B,Y)}}})(1e-4),isFinite(B.distance)){let Y=B.point[0],W=B.point[1],j=B.point[2],x=this.modelMatrix,I=x[0]*Y+x[4]*W+x[8]*j+x[12],N=x[1]*Y+x[5]*W+x[9]*j+x[13],z=x[2]*Y+x[6]*W+x[10]*j+x[14],ee=I-m,ie=N-p,oe=z-R,H=Math.hypot(ee,ie,oe);if(H<f){me(this.normalMatrix,this.modelMatrix);let $=this.normalMatrix,G=B.normal[0],te=B.normal[1],V=B.normal[2],J=$[0]*G+$[3]*te+$[6]*V,Q=$[1]*G+$[4]*te+$[7]*V,Z=$[2]*G+$[5]*te+$[8]*V,ne=Math.hypot(J,Q,Z)||1;J/=ne,Q/=ne,Z/=ne,J*ee+Q*ie+Z*oe>0&&(J=-J,Q=-Q,Z=-Z),d=y,f=Math.round(H*1e3)/1e3,T=[Math.round(I*1e3)/1e3,Math.round(N*1e3)/1e3,Math.round(z*1e3)/1e3],g=[Math.round(J*1e3)/1e3,Math.round(Q*1e3)/1e3,Math.round(Z*1e3)/1e3]}}}}if(!d)return null;let D={meshIndex:this.meshes.indexOf(d),meshName:d.name,nodeIndex:d.nodeIndex,distance:f,hitPoint:T,normal:g,screenX:e,screenY:t};if(r){for(let y of ae)y.onMeshSelect?.(this,D);this.opts.onMeshClick&&this.opts.onMeshClick(D),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:D}))}return D}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,c=(s+.5)/a*2-1;return Math.floor((c*.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);ve(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;Me(this.viewMatrix,ge(this),r,[0,1,0]),se(this.mvpMatrix,this.projMatrix,this.viewMatrix),me(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 ae)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 ae)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 ae)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 ae)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 c=e?.transform?.inverse?.matrix||this.viewMatrix,o=e?.projectionMatrix||this.projMatrix,l=e?.transform?.position,u=l?[l.x,l.y,l.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:c,projMatrix:o,eyePos:u,viewport:i,eye:e?.eye||"none",clear:a>0?!1:e?.eye!=="right",isAR:s})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),D=Math.max(1,this.canvas.height||1),y=Math.max(1,Math.floor(v*.5)),P=Math.max(1,v-y),E=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),b=this.customTarget||this.bounds.center,[F,L,C]=ge(this),h=Math.cos(this.currTheta),w=-Math.sin(this.currTheta),S=.032,M=re(),k=re(),_=[F-h*S,L,C-w*S],K=[b[0]-h*S*.25,b[1],b[2]-w*S*.25];ve(M,this.fov,y/D,.1,E),Me(k,_,K,[0,1,0]);let U=re(),O=re(),B=[F+h*S,L,C+w*S],q=[b[0]+h*S*.25,b[1],b[2]+w*S*.25];ve(U,this.fov,P/D,.1,E),Me(O,B,q,[0,1,0]),this.render({viewMatrix:k,projMatrix:M,eyePos:_,viewport:[0,0,y,D],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:O,projMatrix:U,eyePos:B,viewport:[y,0,P,D],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,D);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 c=re(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o,se(c,e?.projMatrix??this.projMatrix,o);let l=he().xrDepthShader,u=Lt(this.toneMapping),[d,f,T]=e?e.eyePos:ge(this);for(let v of ae)v.onBeforeDrawScene?.(this,t,c,[d,f,T],u);let g=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&g===0)return;let m=e?.eye||"none",p=!1,R=g>0?[...this.backdropMeshes,...this.meshes]:this.meshes,A=v=>{for(let D=0;D<R.length;D++){let y=R[D];if(y.visible===!1)continue;let P=this.selectedMeshName!==""&&y.name===this.selectedMeshName;D<g||y.worldSpace===!0||y.name==="__xr_reticle__"?this.modelMatrix.set(y.transform):se(this.modelMatrix,this.modelRootMatrix,y.transform),se(this.mvpMatrix,c,this.modelMatrix),me(y.normalMatrix,this.modelMatrix);let E=y.extras?.xr?.stereo||y.userData?.xr?.stereo,b=0,F=0,L=1,C=1;E==="sbs"?(L=.5,b=m==="right"?.5:0):E==="ou"&&(C=.5,F=m==="right"?.5:0);for(let h of y.primitives){let w=!!h.isTransmissive;if(!v&&w){p=!0;continue}if(v&&!w)continue;let S=h.customProgram||this.renderProg,M=h.customUniforms||this.uRender;t.useProgram(S),t.vertexAttrib3f(3,0,0,0),M.uInstanced&&t.uniform1i(M.uInstanced,0),t.uniform1i(M.uToneMapping,u),t.uniform1f(M.uEnvIntensity,this.envIntensity),M.uExposure&&t.uniform1f(M.uExposure,this.exposure),t.uniform3f(M.uCameraPos,d,f,T),t.uniform1f(M.uEmissive,P?1:0),t.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(M.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(M.uNormalMatrix,!1,y.normalMatrix),M.uUvTransform&&t.uniform4f(M.uUvTransform,b,F,L,C),M.uViewportSize&&t.uniform2f(M.uViewportSize,Math.max(1,s),Math.max(1,a)),l?.bind(t,M,this.xrDepthState,o,[r,i,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(M.uEnvironmentMap,4),t.uniform1i(M.uHasEnvironmentMap,1)):t.uniform1i(M.uHasEnvironmentMap,0),this.bindLights(M),M.uSectionEnabled&&t.uniform1i(M.uSectionEnabled,0);for(let _ of ae)_.onBeforeDrawPrimitive?.(t,S,h,y,this.worldMatrices||[],this.gltf);t.uniform4fv(M.uBaseColor,h.baseColor),t.uniform1f(M.uMetallic,h.metallic),t.uniform1f(M.uRoughness,h.roughness),M.uClearcoat&&t.uniform2f(M.uClearcoat,h.clearcoat??0,h.clearcoatRoughness??.04),h.texture?(t.activeTexture(33984),t.bindTexture(3553,h.texture),t.uniform1i(M.uBaseColorTexture,0),t.uniform1i(M.uHasTexture,1)):t.uniform1i(M.uHasTexture,0),h.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,h.metallicRoughnessTexture),t.uniform1i(M.uMetallicRoughnessTexture,1),t.uniform1i(M.uHasMetallicRoughnessTexture,1)):t.uniform1i(M.uHasMetallicRoughnessTexture,0),h.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,h.normalTexture),t.uniform1i(M.uNormalTexture,2),t.uniform1i(M.uHasNormalTexture,1),t.uniform1f(M.uNormalScale,h.normalScale)):t.uniform1i(M.uHasNormalTexture,0),h.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,h.occlusionTexture),t.uniform1i(M.uOcclusionTexture,3),t.uniform1i(M.uHasOcclusionTexture,1),t.uniform1f(M.uOcclusionStrength,h.occlusionStrength)):t.uniform1i(M.uHasOcclusionTexture,0),t.bindVertexArray(h.vao);let k=y.instanceMatrices;if(h.instanceCount!==void 0)t.drawElementsInstanced(4,h.indexCount,h.indexType,0,h.instanceCount);else if(k&&k.length>=16&&h.instanced&&M.uInstanced&&M.uViewProj){let _=k.length>>4;t.uniform1i(M.uInstanced,1),t.uniformMatrix4fv(M.uViewProj,!1,c),h.indices?t.drawElementsInstanced(4,h.indexCount,h.indexType,0,_):t.drawArraysInstanced(4,0,h.indexCount,_),t.uniform1i(M.uInstanced,0)}else if(k&&k.length>=16){let _=k.length>>4,K=y.instanceColors,U=re(),O=new Float32Array(9),B=[h.baseColor[0],h.baseColor[1],h.baseColor[2],h.baseColor[3]];for(let q=0;q<_;q++)se(U,this.modelMatrix,k.subarray(q*16,q*16+16)),se(this.mvpMatrix,c,U),me(O,U),t.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(M.uModel,!1,U),t.uniformMatrix3fv(M.uNormalMatrix,!1,O),K&&(B[0]=h.baseColor[0]*K[q*3],B[1]=h.baseColor[1]*K[q*3+1],B[2]=h.baseColor[2]*K[q*3+2],B[3]=h.baseColor[3],t.uniform4fv(M.uBaseColor,B)),Re(t,h)}else Re(t,h)}}};if(A(!1),p){for(let v of ae)v.onBeforeTransmissivePass?.(t,this);A(!0)}for(let v of ae)v.onAfterRender?.(t,this,c,e?.eye??"none",[r,i,s,a],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){ft(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of ae)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=et,Ee.getRegisteredPlugins=tt;function Ge(n){return new TextEncoder().encode(n)}function Bt(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,c=new Float32Array(a*3),o=r.matrixWorld.elements;for(let b=0;b<a;b++){let F=s.getX(b),L=s.getY(b),C=s.getZ(b);c[b*3]=o[0]*F+o[4]*L+o[8]*C+o[12],c[b*3+1]=o[1]*F+o[5]*L+o[9]*C+o[13],c[b*3+2]=o[2]*F+o[6]*L+o[10]*C+o[14]}let l;if(i.attributes.normal){let b=i.attributes.normal;l=new Float32Array(a*3);let F=new Float32Array(9);me(F,o);for(let L=0;L<a;L++){let C=b.getX(L),h=b.getY(L),w=b.getZ(L),S=F[0]*C+F[3]*h+F[6]*w,M=F[1]*C+F[4]*h+F[7]*w,k=F[2]*C+F[5]*h+F[8]*w,_=Math.hypot(S,M,k)||1;l[L*3]=S/_,l[L*3+1]=M/_,l[L*3+2]=k/_}}let u;if(i.attributes.uv){let b=i.attributes.uv;u=new Float32Array(a*2);for(let F=0;F<a;F++)u[F*2]=b.getX(F),u[F*2+1]=b.getY(F)}let d;if(i.index)d=i.index.array;else{d=a>65535?new Uint32Array(a):new Uint16Array(a);for(let b=0;b<a;b++)d[b]=b}let f="DefaultMaterial",T=[.8,.8,.8],g=.5,m=.1,p=0,R=0,A=1.5,v=1,D=[0,0,0];if(r.material){let b=r.material;f=b.name||`Material_${t.length}`,b.color&&(T=[b.color.r,b.color.g,b.color.b]),typeof b.roughness=="number"&&(g=b.roughness),typeof b.metalness=="number"&&(m=b.metalness),typeof b.clearcoat=="number"&&(p=b.clearcoat),typeof b.clearcoatRoughness=="number"&&(R=b.clearcoatRoughness),typeof b.ior=="number"&&(A=b.ior);let F=typeof b.opacity=="number"?b.opacity:1,L=typeof b.transmission=="number"?b.transmission:0;if(v=F*(1-L),b.emissive&&(b.emissive.r>0||b.emissive.g>0||b.emissive.b>0)){let C=b.emissiveIntensity??1;D=[b.emissive.r*C,b.emissive.g*C,b.emissive.b*C]}}let y,P=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 P=="function"){let b=e?.duration??4,F=e?.fps??4,L=Math.max(2,Math.round(b*F)+1),C=[],h=[],w=[],S=[],M=[r.position.x,r.position.y,r.position.z],k=[r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w],_=[r.scale.x,r.scale.y,r.scale.z],K=!1;for(let U=0;U<L;U++){let O=U/(L-1)*b;C.push(O);try{P(O)}catch{}h.push([r.position.x,r.position.y,r.position.z]),w.push([r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w]),S.push([r.scale.x,r.scale.y,r.scale.z]),(Math.abs(r.position.x-M[0])>1e-4||Math.abs(r.position.y-M[1])>1e-4||Math.abs(r.position.z-M[2])>1e-4||Math.abs(r.quaternion.x-k[0])>1e-4||Math.abs(r.quaternion.y-k[1])>1e-4||Math.abs(r.quaternion.z-k[2])>1e-4||Math.abs(r.quaternion.w-k[3])>1e-4||Math.abs(r.scale.x-_[0])>1e-4)&&(K=!0)}r.position.set(M[0],M[1],M[2]),r.quaternion.set(k[0],k[1],k[2],k[3]),r.scale.set(_[0],_[1],_[2]),K&&(y={times:C,translations:h,rotations:w,scales:S})}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)),F=E.instanceMatrix.array,L=E.instanceColor?.array,C=r.name||`Mesh_${t.length}`,h=new Float32Array(16),w=new Float32Array(9);for(let S=0;S<b;S++){let M=F.subarray(S*16,(S+1)*16);se(h,o,M);let k=new Float32Array(a*3);for(let O=0;O<a;O++){let B=s.getX(O),q=s.getY(O),Y=s.getZ(O);k[O*3]=h[0]*B+h[4]*q+h[8]*Y+h[12],k[O*3+1]=h[1]*B+h[5]*q+h[9]*Y+h[13],k[O*3+2]=h[2]*B+h[6]*q+h[10]*Y+h[14]}let _;if(i.attributes.normal){let O=i.attributes.normal;_=new Float32Array(a*3),me(w,h);for(let B=0;B<a;B++){let q=O.getX(B),Y=O.getY(B),W=O.getZ(B),j=w[0]*q+w[3]*Y+w[6]*W,x=w[1]*q+w[4]*Y+w[7]*W,I=w[2]*q+w[5]*Y+w[8]*W,N=Math.hypot(j,x,I)||1;_[B*3]=j/N,_[B*3+1]=x/N,_[B*3+2]=I/N}}let K=T,U=f;L&&L.length>=(S+1)*3&&(K=[T[0]*L[S*3],T[1]*L[S*3+1],T[2]*L[S*3+2]],U=`${f}_inst_${S}`),t.push({name:`${C}_${S}`,positions:k,indices:d,normals:_,uvs:u,materialName:U,color:K,roughness:g,metallic:m,clearcoat:p,clearcoatRoughness:R,ior:A,opacity:v,emissiveColor:D,xrTraits:r.userData?.xr})}return}t.push({name:r.name||`Mesh_${t.length}`,positions:c,indices:d,normals:l,uvs:u,materialName:f,color:T,roughness:g,metallic:m,clearcoat:p,clearcoatRoughness:R,ior:A,opacity:v,emissiveColor:D,xrTraits:r.userData?.xr,timeSamples:y})}}),t}function bt(n){let e=[],t=n.gltf,r=he().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||[],c=t.bufferViews||[],o=t.materials||[],l=t.meshes||[],u=t.nodes||[];function d(g){let m=a[g];if(!m)throw new Error(`Accessor ${g} not found`);let p=c[m.bufferView||0],R=(p.byteOffset||0)+(m.byteOffset||0),A=p.byteLength||0,v=s.slice(R,R+A);return{acc:m,buffer:v}}let f=new Map;if(u.length>0){let g=Te(t);for(let m=0;m<g.length;m++)f.set(m,g[m])}function T(g,m,p,R){let A=l[g];if(!A)return;let v=new Float32Array(9);me(v,m);for(let D=0;D<(A.primitives||[]).length;D++){let y=A.primitives[D],P=y.attributes?.POSITION;if(P===void 0)continue;let{acc:E,buffer:b}=d(P),F=new Float32Array(b,0,E.count*3),L=new Float32Array(F.length);for(let x=0;x<E.count;x++){let I=F[x*3],N=F[x*3+1],z=F[x*3+2];L[x*3]=m[0]*I+m[4]*N+m[8]*z+m[12],L[x*3+1]=m[1]*I+m[5]*N+m[9]*z+m[13],L[x*3+2]=m[2]*I+m[6]*N+m[10]*z+m[14]}let C,h=y.attributes?.NORMAL;if(h!==void 0){let{acc:x,buffer:I}=d(h),N=new Float32Array(I,0,x.count*3);C=new Float32Array(N.length);for(let z=0;z<x.count;z++){let ee=N[z*3],ie=N[z*3+1],oe=N[z*3+2],H=v[0]*ee+v[3]*ie+v[6]*oe,$=v[1]*ee+v[4]*ie+v[7]*oe,G=v[2]*ee+v[5]*ie+v[8]*oe,te=Math.hypot(H,$,G)||1;C[z*3]=H/te,C[z*3+1]=$/te,C[z*3+2]=G/te}}let w,S=y.attributes?.TEXCOORD_0;if(S!==void 0){let{acc:x,buffer:I}=d(S);w=new Float32Array(I,0,x.count*2)}let M;if(y.indices!==void 0){let{acc:x,buffer:I}=d(y.indices);x.componentType===5125?M=new Uint32Array(I,0,x.count):M=new Uint16Array(I,0,x.count);let N=E.count;for(let z of M)if(z>=N)throw new Error(`SecurityError: Index buffer value (${z}) out of vertex bounds [0, ${N}).`)}else{let x=E.count;M=x>65535?new Uint32Array(x):new Uint16Array(x);for(let I=0;I<x;I++)M[I]=I}let k="DefaultMaterial",_=[.8,.8,.8],K=.5,U=.1,O=0,B=0,q=1.5,Y=1,W=[0,0,0];if(y.material!==void 0&&o[y.material]){let x=o[y.material];k=x.name||`Material_${y.material}`;let I=x.pbrMetallicRoughness||{},N=1;Array.isArray(I.baseColorFactor)&&(_=[I.baseColorFactor[0],I.baseColorFactor[1],I.baseColorFactor[2]],typeof I.baseColorFactor[3]=="number"&&(N=I.baseColorFactor[3])),typeof I.roughnessFactor=="number"&&(K=I.roughnessFactor),typeof I.metallicFactor=="number"&&(U=I.metallicFactor),Array.isArray(x.emissiveFactor)&&x.emissiveFactor.length>=3&&(W=[x.emissiveFactor[0],x.emissiveFactor[1],x.emissiveFactor[2]]);let z=x.extensions||{};z.KHR_materials_clearcoat&&(O=z.KHR_materials_clearcoat.clearcoatFactor??0,B=z.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),z.KHR_materials_ior&&typeof z.KHR_materials_ior.ior=="number"&&(q=z.KHR_materials_ior.ior);let ee=z.KHR_materials_transmission?.transmissionFactor??0;Y=N*(1-ee)}let j=(A.primitives||[]).length>1?`${p}_p${D}`:p;e.push({name:j,positions:L,indices:M,normals:C,uvs:w,materialName:k,color:_,roughness:K,metallic:U,clearcoat:O,clearcoatRoughness:B,ior:q,opacity:Y,emissiveColor:W,xrTraits:R?.xr||A.extras?.xr})}}if(u.length>0)for(let g=0;g<u.length;g++){let m=u[g];if(m.mesh!==void 0&&m.mesh<l.length){let p=f.get(g)||re(),R=m.name||l[m.mesh].name||`Node_${g}`,A=m.extensions?.EXT_mesh_gpu_instancing?.attributes;if(A&&typeof A=="object"){let v=A.TRANSLATION,D=A.ROTATION,y=A.SCALE,P=v!==void 0?(()=>{let{acc:L,buffer:C}=d(v);return new Float32Array(C,0,L.count*3)})():null,E=D!==void 0?(()=>{let{acc:L,buffer:C}=d(D);return new Float32Array(C,0,L.count*4)})():null,b=y!==void 0?(()=>{let{acc:L,buffer:C}=d(y);return new Float32Array(C,0,L.count*3)})():null,F=Math.min(1e3,P?P.length/3:E?E.length/4:b?b.length/3:0);if(F>0){let L=new Float32Array(16),C=new Float32Array(16);for(let h=0;h<F;h++){let w=P?[P[h*3],P[h*3+1],P[h*3+2]]:[0,0,0],S=E?[E[h*4],E[h*4+1],E[h*4+2],E[h*4+3]]:[0,0,0,1],M=b?[b[h*3],b[h*3+1],b[h*3+2]]:[1,1,1];ye(L,S,w,M),se(C,p,L),T(m.mesh,C,`${R}_${h}`,m.extras)}continue}}T(m.mesh,p,R,m.extras)}}else{let g=re();for(let m=0;m<l.length;m++){let p=l[m].name||`Mesh_${m}`;T(m,g,p,l[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 dt(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function X(n){if(!Number.isFinite(n)||Math.abs(n)<1e-7)return"0";let e=Number(n.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}function pt(n){let e=n.length/3,t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${X(n[r*3])}, ${X(n[r*3+1])}, ${X(n[r*3+2])})`;return t.join(", ")}function Vt(n,e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=`(${X(n[r*2])}, ${X(1-n[r*2+1])})`;return t.join(", ")}function Ot(n){return Array.from(n).join(", ")}function Oe(n){let e=new Map;for(let o of n){let l=Ve(o.materialName,"DefaultMaterial");e.has(l)||e.set(l,{color:o.color||[.8,.8,.8],roughness:o.roughness??.5,metallic:o.metallic??0,clearcoat:o.clearcoat??0,clearcoatRoughness:o.clearcoatRoughness??0,ior:o.ior??1.5,opacity:o.opacity??1,emissiveColor:o.emissiveColor||[0,0,0]})}let t=0,r=null;for(let o of n){if(o.timeSamples&&o.timeSamples.times.length>0){let l=o.timeSamples.times[o.timeSamples.times.length-1];l>t&&(t=l)}o.xrTraits?.anchor&&!r&&(r=o.xrTraits.anchor==="vertical"||o.xrTraits.anchor==="wall"?"vertical":"horizontal")}let i="";t>0&&(i=`startTimeCode = 0
253
- endTimeCode = ${X(t)}
249
+ void main(){fragColor=uColorId;}`;function je(e,t,i){let r={};for(let a of i)r[a]=e.getUniformLocation(t,a);return r}var ft=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uPointLightSpotDir","uPointLightSpotCone","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function xt(){let e=be().xrDepthShader;return{fs:zt.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...ft,...e.uniformNames]:ft}}function jt(e){if(typeof e!="string")return null;let t=e.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let i=t.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:i.startsWith("https://")||i.startsWith("blob:")?t:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function ze(e,t,i,r,a,s,c,l){if(r===void 0||!t.accessors?.[r])return null;let g=He(t,i,t.accessors[r],s);if(!g)return null;l&&(g=g.slice(),ht(g,l));let d=e.createBuffer();return c.push(d),e.bindBuffer(34962,d),e.bufferData(34962,g,35044),e.enableVertexAttribArray(a),e.vertexAttribPointer(a,s,5126,!1,0,0),g}function We(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function vt(e,t,i){let r=xt(),a=yt,s=r.fs,c=!1;for(let g of ce)if(g.onResolveShader){let d=g.onResolveShader(t,i,a,s);d&&(a=d.vs,s=d.fs,c=!0)}let l=c?Pe(e,a,s):null;return{program:l,uniforms:l?je(e,l,r.uniforms):null}}function qt(e,t,i){let r=t.instanceMatrices;if(!r||r.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let a=r.length>>4,s=t.instanceColors,c=new Float32Array(a*20);for(let g=0;g<a;g++)c.set(r.subarray(g*16,g*16+16),g*20),c[g*20+16]=s?s[g*3]:1,c[g*20+17]=s?s[g*3+1]:1,c[g*20+18]=s?s[g*3+2]:1,c[g*20+19]=1;let l=e.createBuffer();i.push(l),e.bindBuffer(34962,l),e.bufferData(34962,c,35044);for(let g=0;g<5;g++)e.enableVertexAttribArray(8+g),e.vertexAttribPointer(8+g,4,5126,!1,80,g*16),e.vertexAttribDivisor(8+g,1);return!0}function Kt(e,t){let i=e.materials?.[t?.material];if(!i)return null;let r=[i.pbrMetallicRoughness?.baseColorTexture,i.pbrMetallicRoughness?.metallicRoughnessTexture,i.normalTexture,i.occlusionTexture,i.emissiveTexture];for(let a of r){let s=a?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var An=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Mt=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Ce(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function At(e,t){let i=e?.pbrMetallicRoughness,r=i?.baseColorFactor,a=e?.extensions?.KHR_materials_clearcoat,s=c=>c!==void 0&&t[c.index]?t[c.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:i?.metallicFactor??.1,roughness:i?.roughnessFactor??.5,clearcoat:a?a.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,a?.clearcoatRoughnessFactor??.04),texture:s(i?.baseColorTexture),metallicRoughnessTexture:s(i?.metallicRoughnessTexture),normalTexture:s(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:s(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Tt(e,t,i){let r=new Set,a=s=>{s&&!r.has(s)&&(r.add(s),e.deleteTexture(s))};for(let s of t)for(let c of s.primitives){if(c.vao&&e.deleteVertexArray(c.vao),c.buffers)for(let g of c.buffers)e.deleteBuffer(g);a(c.texture),a(c.metallicRoughnessTexture),a(c.normalTexture),a(c.occlusionTexture);let l=new Set;c.customProgram&&l.add(c.customProgram);for(let g of c.programCache?.values()??[])g.program&&l.add(g.program);for(let g of l)e.deleteProgram(g)}if(i)for(let s of i)a(s)}function dt(e,t,i=Mt,r){let a={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Yt(e,t,i,r,a)}catch(s){let c=a.mesh&&!a.meshes.includes(a.mesh)?[...a.meshes,a.mesh]:a.meshes;Tt(e,c,a.gpuTextures),a.vao&&e.deleteVertexArray(a.vao);for(let l of a.buffers)e.deleteBuffer(l);throw s}}function Yt(e,t,i,r,a){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=t,c=we("meshopt");c?.decodeBufferViews&&c.decodeBufferViews(s,t);let l=t.bin,g=[];a.meshes=g;let d=[],v=s.extensions?.KHR_materials_variants;v&&Array.isArray(v.variants)&&v.variants.forEach((S,o)=>{d.push(typeof S?.name=="string"&&S.name?S.name:`Variant_${o}`)});let M=ut(s),I=[];if(Array.isArray(s.nodes))for(let S=0;S<s.nodes.length;S++){let o=s.nodes[S];o.mesh!==void 0&&s.meshes&&s.meshes[o.mesh]&&I.push({node:o,nodeIdx:S,meshIdx:o.mesh})}let D=I.length>0?I:(s.meshes||[]).map((S,o)=>({node:S,nodeIdx:-1,meshIdx:o})),u=[],x=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(s.asset?.extras?.lights)&&s.asset.extras.lights.length>0?s.asset.extras.lights:null;if(x)for(let S of x)u.push({...S,type:S.type||S.light_type||"point",innerConeAngle:S.innerConeAngle??S.inner_cone_angle,outerConeAngle:S.outerConeAngle??S.outer_cone_angle});else if(s.extensions?.KHR_lights_punctual?.lights){let S=s.extensions.KHR_lights_punctual.lights;for(let o of S){let V=o.type==="directional"?"directional":o.type==="point"?"point":o.type==="spot"?"spot":"ambient";u.push({type:V,color:o.color||[1,1,1],intensity:o.intensity!==void 0?o.intensity:1})}}if(u.length===0&&(u.push({type:"ambient",color:[1,1,1],intensity:.35}),u.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),D.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${D.length}`);let C=[];if(a.gpuTextures=C,s.textures&&s.images){if(s.textures.length>i.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${i.maxTextures}). Found: ${s.textures.length}`);for(let S=0;S<s.textures.length;S++){let o=s.textures[S],V=s.images[o.source];if(V){let K=e.createTexture();e.bindTexture(3553,K),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),e.texParameteri(3553,10242,10497),e.texParameteri(3553,10243,10497),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729);let f=b=>{e.bindTexture(3553,K),e.texImage2D(3553,0,6408,6408,5121,b),e.generateMipmap(3553),r?.()};if(V.bufferView!==void 0){let b=s.bufferViews[V.bufferView],n=b.byteOffset||0,p=new Blob([l.slice(n,n+b.byteLength)],{type:V.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(p).then(f).catch(()=>{})}else if(V.uri){let b=jt(V.uri);if(b){let n=new Image;n.crossOrigin="anonymous",n.referrerPolicy="no-referrer",n.onload=()=>f(n),n.src=b}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",V.uri)}C.push(K)}else C.push(null)}}let R=[1/0,1/0,1/0],T=[-1/0,-1/0,-1/0],m=0,h=0;for(let S=0;S<D.length;S++){let o=D[S],V=s.meshes[o.meshIdx],K=o.nodeIdx>=0?M[o.nodeIdx]:le(),f=new Float32Array(9);ve(f,K);let b={name:o.node.name||V.name||`Mesh_${o.meshIdx}`,nodeIndex:o.nodeIdx,transform:K,normalMatrix:f,primitives:[],extras:o.node.extras||V.extras,...o.node?.visible===!1||o.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};a.mesh=b;let n=o.node?.extensions?.EXT_mesh_gpu_instancing;if(n&&n.attributes&&typeof n.attributes=="object"){let p=n.attributes,B=p.TRANSLATION!==void 0?s.accessors?.[p.TRANSLATION]:null,z=p.ROTATION!==void 0?s.accessors?.[p.ROTATION]:null,j=p.SCALE!==void 0?s.accessors?.[p.SCALE]:null,ee=p._COLOR_0!==void 0?s.accessors?.[p._COLOR_0]:null,L=Number(B?.count??z?.count??j?.count??0);if(!Number.isFinite(L)||L<0||L>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${L}`);if(L>0){let X=(A,E)=>{if(!A||A.bufferView===void 0||!s.bufferViews?.[A.bufferView])return null;let H=A.componentType??5126,W=Q=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${Q})`),null);if(H!==5120&&H!==5121&&H!==5122&&H!==5123&&H!==5126)return W(`componentType ${H}`);if(!(Number(A.count)>=L))return W(`count ${A.count} < ${L}`);let Z=null;try{Z=He(s,l,{...A,count:L},E)}catch{return W("out of bounds")}return!Z||!Z.every(Number.isFinite)?W("non-finite value"):Z},J=X(B,3),re=X(z,4),$=X(j,3),te=ee?.type==="VEC4"?4:3,O=X(ee,te),G=new Float32Array(L*16),q=le();for(let A=0;A<L;A++){let E=J?[J[A*3],J[A*3+1],J[A*3+2]]:[0,0,0],H=re?[re[A*4],re[A*4+1],re[A*4+2],re[A*4+3]]:[0,0,0,1],W=$?[$[A*3],$[A*3+1],$[A*3+2]]:[1,1,1];Ge(q,H,E,W),G.set(q,A*16)}if(b.instanceMatrices=G,O){let A=new Float32Array(L*3);for(let E=0;E<L;E++)A[E*3]=O[E*te],A[E*3+1]=O[E*te+1],A[E*3+2]=O[E*te+2];b.instanceColors=A}}}for(let p of V.primitives||[]){if(p.extensions?.KHR_draco_mesh_compression){let Z=we("draco");Z&&Z.decodePrimitive(s,p,l)}let B=[],z=e.createVertexArray();a.vao=z,a.buffers=B,e.bindVertexArray(z);let j=qt(e,b,B),ee=s.accessors[p.attributes.POSITION],L=Number(ee?.count??0);if(!Number.isFinite(L)||L<0||m+L>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(m+=L,ee?.min&&ee?.max){let Z=Q=>{for(let Y=0;Y<3;Y++){let ue=Q[12+Y],ie=Q[12+Y];for(let ae=0;ae<3;ae++){let ne=Q[ae*4+Y]*ee.min[ae],oe=Q[ae*4+Y]*ee.max[ae];ue+=ne<oe?ne:oe,ie+=ne>oe?ne:oe}ue<R[Y]&&(R[Y]=ue),ie>T[Y]&&(T[Y]=ie)}};if(b.instanceMatrices&&b.instanceMatrices.length>=16){let Q=b.instanceMatrices.length>>4,Y=le();for(let ue=0;ue<Q;ue++){let ie=b.instanceMatrices.subarray(ue*16,ue*16+16);fe(Y,K,ie),Z(Y)}}else Z(K)}let X=ze(e,s,l,p.attributes.POSITION,0,3,B);ze(e,s,l,p.attributes.NORMAL,1,3,B),ze(e,s,l,p.attributes.TEXCOORD_0,2,2,B,Kt(s,p));let J=0,re=5123,$=null;if(p.indices!==void 0){let Z=s.accessors[p.indices],Q=(s.bufferViews[Z.bufferView].byteOffset||0)+(Z.byteOffset||0);if(J=Number(Z.count??0),!Number.isFinite(J)||J<0||h+J>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);h+=J,re=Z.componentType===5125?5125:5123;let Y=e.createBuffer();B.push(Y),e.bindBuffer(34963,Y),Z.componentType===5125?$=new Uint32Array(l,Q,Z.count):Z.componentType===5121?$=Uint16Array.from(new Uint8Array(l,Q,Z.count)):$=Q%2===0?new Uint16Array(l,Q,Z.count):new Uint16Array(l.slice(Q,Q+Z.count*2)),e.bufferData(34963,$,35044)}else J=ee.count;let te={};for(let Z of ce)if(Z.onBuildPrimitiveVAO){let Q=Z.onBuildPrimitiveVAO(e,z,p,s,l);Q&&(te[Z.name]=Q)}e.bindVertexArray(null);let O=s.materials&&p.material!==void 0?s.materials[p.material]:null,{program:G,uniforms:q}=vt(e,p,O),A=At(O,C),E=!!(O?.extensions?.KHR_materials_transmission||te.materials?.isTransmissive),H=p.extensions?.KHR_materials_variants?.mappings,W=Array.isArray(H)?H.filter(Z=>Z&&typeof Z.material=="number"&&Array.isArray(Z.variants)).map(Z=>({material:Z.material|0,variants:Z.variants.map(Q=>Number(Q)|0)})):void 0;b.primitives.push({vao:z,instanced:j,indexCount:J,indexType:re,...A,positions:X,indices:$,buffers:B,materialIndex:p.material,defaultMaterialIndex:p.material,variantMappings:W,primitiveDef:p,programCache:new Map([[p.material??-1,{program:G,uniforms:q}]]),pluginData:te,customProgram:G,customUniforms:q,isTransmissive:E})}g.push(b)}isFinite(R[0])||(R=[-1,-1,-1]),isFinite(T[0])||(T=[1,1,1]);let w=[(R[0]+T[0])/2,(R[1]+T[1])/2,(R[2]+T[2])/2],y=T[0]-R[0],F=T[1]-R[1],U=T[2]-R[2],_=Math.max(Math.hypot(y,F,U)/2,.5),k=[R[0],R[1],R[2]],P=[T[0],T[1],T[2]],N=t.animations;if(!N){for(let S of ce)if(S.onParseGLB?.(t),t.animations){N=t.animations;break}}return N||(N=[]),{meshes:g,bounds:{center:w,radius:_,min:k,max:P},lights:u,animations:N,worldMatrices:M,gpuTextures:C,availableVariants:d}}function Re(e){let t=e.customTarget||e.bounds.center,i=e.currDistance*Math.cos(e.currPhi);return[t[0]+i*Math.sin(e.currTheta),t[1]+e.currDistance*Math.sin(e.currPhi),t[2]+i*Math.cos(e.currTheta)]}var Fe=class{constructor(e,t,i){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=le(),this.clearColor=[0,0,0,0],this.envIntensity=1,this.exposure=1,this.shadowIntensity=0,this.shadowSoftness=.5,this.toneMapping="neutral",this.environmentTexture=null,this.animations=[],this.currentClip=null,this.animationTime=0,this.isPlayingAnimation=!1,this.autoplay=!1,this.animationName="",this.gpuTextures=[],this.availableVariants=[],this.activeVariantName=null,this.gltf=null,this.worldMatrices=[],this.initialNodeTransforms=[],this.projMatrix=le(),this.viewMatrix=le(),this.activeViewMatrix=null,this.modelMatrix=le(),this.mvpMatrix=le(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshName="",this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:le(),rawValueToMeters:.001,format:0},this.container=e;let r,a;if(t&&typeof t.getContext=="function"?(r=t,a=i):(a=t,r=a?.canvas),!r){let l=e.querySelector("canvas");l||(l=document.createElement("canvas"),l.style.width="100%",l.style.height="100%",l.style.display="block",l.style.touchAction="none",e.prepend(l)),r=l}this.canvas=r,this.opts=a||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!s:s&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=We(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=Xe(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 c=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!c)throw new Error("WebGL2 not supported");this.gl=c,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){$t(e,t)}static getDecoder(e){return we(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=xt();this.renderProg=Pe(e,yt,t.fs),this.pickProg=Pe(e,Wt,Xt),this.uRender=je(e,this.renderProg,t.uniforms),this.uPick=je(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of ce)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),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),a=Math.max(1,t);this.pickFboWidth=r,this.pickFboHeight=a,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,a,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,a)}loadGLBData(e,t){let{meshes:i,bounds:r,lights:a,animations:s,worldMatrices:c,gpuTextures:l,availableVariants:g}=dt(this.gl,e,t,()=>this.render());if(this.lastGlbData=e,this.lastLimits=t,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=a,this.animations=s||[],this.worldMatrices=c||[],this.gpuTextures=l||[],this.availableVariants=g||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let M of e.gltf.nodes)this.initialNodeTransforms.push({t:M.translation?[M.translation[0],M.translation[1],M.translation[2]]:[0,0,0],r:M.rotation?[M.rotation[0],M.rotation[1],M.rotation[2],M.rotation[3]]:[0,0,0,1],s:M.scale?[M.scale[0],M.scale[1],M.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let M of ce)M.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 d=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;d!==void 0&&(this.exposure=We(d));let v=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;v!==void 0&&(this.envIntensity=Math.max(0,Number(v)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(gt(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of ce)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Se(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=Se(e),{meshes:r}=dt(this.gl,i,Mt,()=>this.render());if(t)for(let a of r)a.transform[12]+=t[0],a.transform[13]+=t[1],a.transform[14]+=t[2],ve(a.normalMatrix,a.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),ve(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[],a=[],s=[],c=[],l=[],g=[];for(let d of this.lights){let v=d.color||[1,1,1],M=d.intensity!==void 0?d.intensity:1;if(d.type==="ambient")i=[v[0]*M,v[1]*M,v[2]*M];else if(d.type==="directional"&&r.length<6){let I=d.direction||[.5,1,.8];r.push(I[0],I[1],I[2]),a.push(v[0]*M,v[1]*M,v[2]*M)}else if((d.type==="point"||d.type==="spot")&&s.length<6){let I=d.position||[0,0,0];if(s.push(I[0],I[1],I[2]),c.push(v[0]*M,v[1]*M,v[2]*M),d.type==="spot"){let D=d.direction||[0,-1,0],u=Math.max(.01,Math.min(Math.PI/2,d.outerConeAngle??Math.PI/3)),x=Math.max(0,Math.min(u-1e-4,d.innerConeAngle??0));l.push(D[0],D[1],D[2]),g.push(Math.cos(x),Math.cos(u))}else l.push(0,-1,0),g.push(-2,-3)}}r.length===0&&(r.push(.5,1,.8),a.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,a)),t.uniform1i(e.uNumPointLights,s.length/3),s.length>0&&(t.uniform3fv(e.uPointLightPos,s),t.uniform3fv(e.uPointLightColor,c),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,l),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,g)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=We(e)}getExposure(){return this.exposure}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=Xe(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of ce)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ce)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(d=>d.primitives.filter(v=>v.materialIndex===i||e.length===1&&v.materialIndex===void 0)),a=r[0],s=a?[...a.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],c=a?a.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,l=a?a.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,g={baseColorFactor:s,metallicFactor:c,roughnessFactor:l,setBaseColorFactor:d=>{let v=[d[0],d[1],d[2],d[3]??1];g.baseColorFactor=v,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=v);for(let M of r)M.baseColor=v;this.render()},setMetallicFactor:d=>{g.metallicFactor=d,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=d);for(let v of r)v.metallic=d;this.render()},setRoughnessFactor:d=>{g.roughnessFactor=d,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=d);for(let v of r)v.roughness=d;this.render()}};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:g}})}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)}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==="",i=-1;if(t)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(e),i<0)return!1;this.activeVariantName=e}let r=this.gltf?.materials;if(!Array.isArray(r))return t;for(let a of this.meshes)for(let s of a.primitives){let c=s.defaultMaterialIndex;if(!t&&Array.isArray(s.variantMappings)){for(let g of s.variantMappings)if(Array.isArray(g.variants)&&g.variants.includes(i)){c=g.material;break}}let l=c!==void 0?r[c]:void 0;s.materialIndex=l?c:void 0,Object.assign(s,At(l,this.gpuTextures)),this.applyPrimitiveProgram(s,s.materialIndex,l??null)}return!0}applyPrimitiveProgram(e,t,i){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let r=t??-1,a=e.programCache.get(r);a||(a=vt(this.gl,{...e.primitiveDef,material:t},i),e.programCache.set(r,a)),e.customProgram=a.program,e.customUniforms=a.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of ce)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 a=this.clampDistance(i);this.initialDistance=a,this.customDistance=!0,this.targetDistance=a,this.currDistance=a}else if(r!==void 0&&r>0){let a=this.clampDistance(this.bounds.radius*2.5/r);this.initialDistance=a,this.customDistance=!0,this.targetDistance=a,this.currDistance=a}else{this.customDistance=!1;let a=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=a,this.targetDistance=a,this.currDistance=a}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=le();fe(i,this.projMatrix,this.viewMatrix);let[r,a,s]=e,c=t?t[0]:0,l=t?t[1]:0,g=t?t[2]:0,d=this.modelRootMatrix;d&&(r=d[0]*e[0]+d[4]*e[1]+d[8]*e[2]+d[12],a=d[1]*e[0]+d[5]*e[1]+d[9]*e[2]+d[13],s=d[2]*e[0]+d[6]*e[1]+d[10]*e[2]+d[14],t&&(c=d[0]*t[0]+d[4]*t[1]+d[8]*t[2],l=d[1]*t[0]+d[5]*t[1]+d[9]*t[2],g=d[2]*t[0]+d[6]*t[1]+d[10]*t[2]));let v=i[0]*r+i[4]*a+i[8]*s+i[12],M=i[1]*r+i[5]*a+i[9]*s+i[13],I=i[2]*r+i[6]*a+i[10]*s+i[14],D=i[3]*r+i[7]*a+i[11]*s+i[15];if(D<=1e-4)return{x:0,y:0,z:1,visible:!1};let u=v/D,x=M/D,C=I/D,R=this.canvas.getBoundingClientRect(),T=R.width||this.canvas.clientWidth||this.canvas.width||300,m=R.height||this.canvas.clientHeight||this.canvas.height||150,h=(u*.5+.5)*T,w=(-x*.5+.5)*m,y=u>=-1.1&&u<=1.1&&x>=-1.1&&x<=1.1&&C>=-1&&C<=1;if(y&&t){let[F,U,_]=Re(this),k=[r-F,a-U,s-_];c*k[0]+l*k[1]+g*k[2]>.05&&(y=!1)}return{x:h,y:w,z:C,visible:y}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas,t=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=i=>{i.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=t(),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist=0,this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.isPanning=i.button===2||i.shiftKey||this.activePointers.size===2,e.setPointerCapture(i.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=t();let r=this.activePointers.get(i.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},a=i.clientX-r.x,s=i.clientY-r.y;if(this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist+=Math.hypot(a,s),this.isPanning||i.button===2||i.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]],g=this.customTarget?[...this.customTarget]:[...this.bounds.center],d=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;g[0]+=(-a*c[0]+s*l[0])*d,g[1]+=(-a*c[1]+s*l[1])*d,g[2]+=(-a*c[2]+s*l[2])*d,this.customTarget=g}else this.targetTheta=this.clampTheta(this.targetTheta-a*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=t(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=e.getBoundingClientRect(),a=Math.floor((i.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((i.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(a,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=t();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=i=>{let r=i.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=i=>{if(this.interactive){switch(i.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=t(),i.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(i,r,a)=>{this[a]&&(i.removeEventListener(r,this[a]),this[a]=null)},t=this.canvas;e(t,"webglcontextlost","boundContextLost"),e(t,"webglcontextrestored","boundContextRestored"),e(t,"contextmenu","boundContextMenu"),e(t,"pointerdown","boundPointerDown"),e(t,"pointermove","boundPointerMove"),e(t,"pointerup","boundPointerUp"),e(t,"wheel","boundWheel"),e(t,"keydown","boundKeyDown"),e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let i=this.canvas,r=i.getBoundingClientRect(),a=i.width||300,s=i.height||300,c=r.width>0?Math.floor((e-r.left)*(a/r.width)):Math.floor(e),l=r.height>0?Math.floor((t-r.top)*(s/r.height)):Math.floor(t);return this.performMeshPick(c,l,!1)}performMeshPick(e,t,i=!0){if(this.meshes.length===0)return null;let r=this.gl,a=Math.max(1,this.canvas.width||300),s=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,a);let c=le();fe(c,this.projMatrix,this.viewMatrix);let l=[],g=Math.max(0,Math.min(a-1,e)),d=Math.max(0,Math.min(s-1,s-1-t));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==a||this.pickFboHeight!==s)&&this.resizePickingFbo(a,s),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,a,s),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16640),r.useProgram(this.pickProg);for(let w=0;w<this.meshes.length;w++){let y=this.meshes[w];if(y.visible===!1||y.isPluginMesh)continue;let F=w+1,U=(F&255)/255,_=(F>>8&255)/255,k=(F>>16&255)/255;r.uniform4f(this.uPick.uColorId,U,_,k,1),fe(this.modelMatrix,this.modelRootMatrix,y.transform);let P=y.instanceMatrices;if(P&&P.length>=16){let N=P.length>>4,S=le();for(let o of y.primitives){r.bindVertexArray(o.vao);for(let V=0;V<N;V++)fe(S,this.modelMatrix,P.subarray(V*16,V*16+16)),fe(this.mvpMatrix,c,S),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Ce(r,o)}}else{fe(this.mvpMatrix,c,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let N of y.primitives)r.bindVertexArray(N.vao),Ce(r,N)}}let m=new Uint8Array(4);r.readPixels(g,d,1,1,6408,5121,m),r.bindFramebuffer(36160,null);let h=m[0]+(m[1]<<8)+(m[2]<<16);h>0&&h<=this.meshes.length&&(l=[this.meshes[h-1]])}l.length===0&&(l=this.meshes.filter(m=>m.visible!==!1));let v=null,M=1/0,I=[0,0,0],D=[0,1,0],[u,x,C]=Re(this),R=le();for(let m of l){fe(R,this.modelRootMatrix,m.transform);let h=m.instanceMatrices,w=h&&h.length>=16?h.length>>4:1;for(let y=0;y<w;y++){h&&h.length>=16?fe(this.modelMatrix,R,h.subarray(y*16,y*16+16)):this.modelMatrix.set(R),fe(this.mvpMatrix,c,this.modelMatrix);let F=le();if(!ot(F,this.mvpMatrix))continue;let U=(g+.5)/a*2-1,_=(d+.5)/s*2-1,k=[0,0,0],P=[0,0,0];$e(k,U,_,-1,F),$e(P,U,_,1,F);let N=P[0]-k[0],S=P[1]-k[1],o=P[2]-k[2],V=Math.hypot(N,S,o)||1,K=N/V,f=S/V,b=o/V,n={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((p=>{for(let B of m.primitives){if(!B.positions)continue;let z=B.positions,j=B.indices,ee=Math.floor(j?j.length/3:z.length/9);for(let L=0;L<ee;L++){let X=j?j[L*3]:L*3,J=j?j[L*3+1]:L*3+1,re=j?j[L*3+2]:L*3+2;at(k[0],k[1],k[2],K,f,b,z[X*3],z[X*3+1],z[X*3+2],z[J*3],z[J*3+1],z[J*3+2],z[re*3],z[re*3+1],z[re*3+2],n,p)}}})(1e-4),isFinite(n.distance)){let p=n.point[0],B=n.point[1],z=n.point[2],j=this.modelMatrix,ee=j[0]*p+j[4]*B+j[8]*z+j[12],L=j[1]*p+j[5]*B+j[9]*z+j[13],X=j[2]*p+j[6]*B+j[10]*z+j[14],J=ee-u,re=L-x,$=X-C,te=Math.hypot(J,re,$);if(te<M){ve(this.normalMatrix,this.modelMatrix);let O=this.normalMatrix,G=n.normal[0],q=n.normal[1],A=n.normal[2],E=O[0]*G+O[3]*q+O[6]*A,H=O[1]*G+O[4]*q+O[7]*A,W=O[2]*G+O[5]*q+O[8]*A,Z=Math.hypot(E,H,W)||1;E/=Z,H/=Z,W/=Z,E*J+H*re+W*$>0&&(E=-E,H=-H,W=-W),v=m,M=Math.round(te*1e3)/1e3,I=[Math.round(ee*1e3)/1e3,Math.round(L*1e3)/1e3,Math.round(X*1e3)/1e3],D=[Math.round(E*1e3)/1e3,Math.round(H*1e3)/1e3,Math.round(W*1e3)/1e3]}}}}if(!v)return null;let T={meshIndex:this.meshes.indexOf(v),meshName:v.name,nodeIndex:v.nodeIndex,distance:M,hitPoint:I,normal:D,screenX:e,screenY:t};if(i){for(let m of ce)m.onMeshSelect?.(this,T);this.opts.onMeshClick&&this.opts.onMeshClick(T),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:T}))}return T}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,a=r?e-i:e,s=r?Math.max(1,t-i):i,c=(a+.5)/s*2-1;return Math.floor((c*.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);Ee(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center;Le(this.viewMatrix,Re(this),i,[0,1,0]),fe(this.mvpMatrix,this.projMatrix,this.viewMatrix),ve(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 ce)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 ce)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],a=this.modelRootMatrix;a[0]=e,a[1]=0,a[2]=-t,a[3]=0,a[4]=0,a[5]=1,a[6]=0,a[7]=0,a[8]=t,a[9]=0,a[10]=e,a[11]=0,a[12]=i-(e*i+t*r),a[13]=0,a[14]=r-(-t*i+e*r),a[15]=1}setVisible(e){this.isVisible=e}update(e){for(let s of ce)s.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let s of ce)s.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let i=Math.round((this.currTheta*180/Math.PI%360+360)%360),r=Math.round(this.currPhi*180/Math.PI),a=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(a-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=a;let s={theta:i,phi:r,zoom:a,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(s),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:s}))}}renderXRView(e,t,i,r,a=!0,s=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let c=e?.transform?.inverse?.matrix||this.viewMatrix,l=e?.projectionMatrix||this.projMatrix,g=e?.transform?.position,d=g?[g.x,g.y,g.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):i&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:c,projMatrix:l,eyePos:d,viewport:r,eye:e?.eye||"none",clear:s>0?!1:e?.eye!=="right",isAR:a})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let T=Math.max(2,this.canvas.width||2),m=Math.max(1,this.canvas.height||1),h=Math.max(1,Math.floor(T*.5)),w=Math.max(1,T-h),y=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),F=this.customTarget||this.bounds.center,[U,_,k]=Re(this),P=Math.cos(this.currTheta),N=-Math.sin(this.currTheta),S=.032,o=le(),V=le(),K=[U-P*S,_,k-N*S],f=[F[0]-P*S*.25,F[1],F[2]-N*S*.25];Ee(o,this.fov,h/m,.1,y),Le(V,K,f,[0,1,0]);let b=le(),n=le(),p=[U+P*S,_,k+N*S],B=[F[0]+P*S*.25,F[1],F[2]+N*S*.25];Ee(b,this.fov,w/m,.1,y),Le(n,p,B,[0,1,0]),this.render({viewMatrix:V,projMatrix:o,eyePos:K,viewport:[0,0,h,m],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:n,projMatrix:b,eyePos:p,viewport:[h,0,w,m],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,T,m);return}let t=this.gl,i=0,r=0,a=this.canvas.width,s=this.canvas.height;e?.viewport?(i=e.viewport[0],r=e.viewport[1],a=e.viewport[2],s=e.viewport[3],t.viewport(i,r,a,s)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16640));let c=le(),l=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=l,fe(c,e?.projMatrix??this.projMatrix,l);let g=be().xrDepthShader,d=Vt(this.toneMapping),[v,M,I]=e?e.eyePos:Re(this);for(let T of ce)T.onBeforeDrawScene?.(this,t,c,[v,M,I],d);let D=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&D===0)return;let u=e?.eye||"none",x=!1,C=D>0?[...this.backdropMeshes,...this.meshes]:this.meshes,R=T=>{for(let m=0;m<C.length;m++){let h=C[m];if(h.visible===!1)continue;let w=this.selectedMeshName!==""&&h.name===this.selectedMeshName;m<D||h.worldSpace===!0||h.name==="__xr_reticle__"?this.modelMatrix.set(h.transform):fe(this.modelMatrix,this.modelRootMatrix,h.transform),fe(this.mvpMatrix,c,this.modelMatrix),ve(h.normalMatrix,this.modelMatrix);let y=h.extras?.xr?.stereo||h.userData?.xr?.stereo,F=0,U=0,_=1,k=1;y==="sbs"?(_=.5,F=u==="right"?.5:0):y==="ou"&&(k=.5,U=u==="right"?.5:0);for(let P of h.primitives){let N=!!P.isTransmissive;if(!T&&N){x=!0;continue}if(T&&!N)continue;let S=P.customProgram||this.renderProg,o=P.customUniforms||this.uRender;t.useProgram(S),t.vertexAttrib3f(3,0,0,0),o.uInstanced&&t.uniform1i(o.uInstanced,0),t.uniform1i(o.uToneMapping,d),t.uniform1f(o.uEnvIntensity,this.envIntensity),o.uExposure&&t.uniform1f(o.uExposure,this.exposure),t.uniform3f(o.uCameraPos,v,M,I),t.uniform1f(o.uEmissive,w?1:0),t.uniformMatrix4fv(o.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(o.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(o.uNormalMatrix,!1,h.normalMatrix),o.uUvTransform&&t.uniform4f(o.uUvTransform,F,U,_,k),o.uViewportSize&&t.uniform2f(o.uViewportSize,Math.max(1,a),Math.max(1,s)),g?.bind(t,o,this.xrDepthState,l,[i,r,Math.max(1,a),Math.max(1,s)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(o.uEnvironmentMap,4),t.uniform1i(o.uHasEnvironmentMap,1)):t.uniform1i(o.uHasEnvironmentMap,0),this.bindLights(o),o.uSectionEnabled&&t.uniform1i(o.uSectionEnabled,0);for(let K of ce)K.onBeforeDrawPrimitive?.(t,S,P,h,this.worldMatrices||[],this.gltf);t.uniform4fv(o.uBaseColor,P.baseColor),t.uniform1f(o.uMetallic,P.metallic),t.uniform1f(o.uRoughness,P.roughness),o.uClearcoat&&t.uniform2f(o.uClearcoat,P.clearcoat??0,P.clearcoatRoughness??.04),P.texture?(t.activeTexture(33984),t.bindTexture(3553,P.texture),t.uniform1i(o.uBaseColorTexture,0),t.uniform1i(o.uHasTexture,1)):t.uniform1i(o.uHasTexture,0),P.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,P.metallicRoughnessTexture),t.uniform1i(o.uMetallicRoughnessTexture,1),t.uniform1i(o.uHasMetallicRoughnessTexture,1)):t.uniform1i(o.uHasMetallicRoughnessTexture,0),P.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,P.normalTexture),t.uniform1i(o.uNormalTexture,2),t.uniform1i(o.uHasNormalTexture,1),t.uniform1f(o.uNormalScale,P.normalScale)):t.uniform1i(o.uHasNormalTexture,0),P.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,P.occlusionTexture),t.uniform1i(o.uOcclusionTexture,3),t.uniform1i(o.uHasOcclusionTexture,1),t.uniform1f(o.uOcclusionStrength,P.occlusionStrength)):t.uniform1i(o.uHasOcclusionTexture,0),t.bindVertexArray(P.vao);let V=h.instanceMatrices;if(P.instanceCount!==void 0)t.drawElementsInstanced(4,P.indexCount,P.indexType,0,P.instanceCount);else if(V&&V.length>=16&&P.instanced&&o.uInstanced&&o.uViewProj){let K=V.length>>4;t.uniform1i(o.uInstanced,1),t.uniformMatrix4fv(o.uViewProj,!1,c),P.indices?t.drawElementsInstanced(4,P.indexCount,P.indexType,0,K):t.drawArraysInstanced(4,0,P.indexCount,K),t.uniform1i(o.uInstanced,0)}else if(V&&V.length>=16){let K=V.length>>4,f=h.instanceColors,b=le(),n=new Float32Array(9),p=[P.baseColor[0],P.baseColor[1],P.baseColor[2],P.baseColor[3]];for(let B=0;B<K;B++)fe(b,this.modelMatrix,V.subarray(B*16,B*16+16)),fe(this.mvpMatrix,c,b),ve(n,b),t.uniformMatrix4fv(o.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(o.uModel,!1,b),t.uniformMatrix3fv(o.uNormalMatrix,!1,n),f&&(p[0]=P.baseColor[0]*f[B*3],p[1]=P.baseColor[1]*f[B*3+1],p[2]=P.baseColor[2]*f[B*3+2],p[3]=P.baseColor[3],t.uniform4fv(o.uBaseColor,p)),Ce(t,P)}else Ce(t,P)}}};if(R(!1),x){for(let T of ce)T.onBeforeTransmissivePass?.(t,this);R(!0)}for(let T of ce)T.onAfterRender?.(t,this,c,e?.eye??"none",[i,r,a,s],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){Tt(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of ce)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()}};Fe.registerPlugin=ct,Fe.getRegisteredPlugins=lt;function Zt(e){return e+3&-4}var se=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function Rt(e,t){let i=t,r=1;for(;e.has(i);)i=`${t}_${r++}`;return e.add(i),i}function St(e,t=0){let[i,r,a,,s,c,l,,g,d,v,,M,I,D]=Array.from({length:15},(n,p)=>se(e[t+p],p%5===0?1:0)),u=Math.hypot(i,r,a),x=Math.hypot(s,c,l),C=Math.hypot(g,d,v);i*(c*v-d*l)-s*(r*v-d*a)+g*(r*l-c*a)<0&&(u=-u);let R=Math.abs(u)>1e-8?1/u:0,T=Math.abs(x)>1e-8?1/x:0,m=Math.abs(C)>1e-8?1/C:0,h=i*R,w=r*R,y=a*R,F=s*T,U=c*T,_=l*T,k=g*m,P=d*m,N=v*m,S=h+U+N,o=0,V=0,K=0,f=1;if(S>0){let n=.5/Math.sqrt(S+1);f=.25/n,o=(_-P)*n,V=(k-y)*n,K=(w-F)*n}else if(h>U&&h>N){let n=2*Math.sqrt(Math.max(0,1+h-U-N));n>1e-8&&(f=(_-P)/n,o=.25*n,V=(F+w)/n,K=(k+y)/n)}else if(U>N){let n=2*Math.sqrt(Math.max(0,1+U-h-N));n>1e-8&&(f=(k-y)/n,o=(F+w)/n,V=.25*n,K=(_+P)/n)}else{let n=2*Math.sqrt(Math.max(0,1+N-h-U));n>1e-8&&(f=(w-F)/n,o=(k+y)/n,V=(_+P)/n,K=.25*n)}let b=Math.hypot(o,V,K,f);return b>1e-8&&Number.isFinite(b)?(o/=b,V/=b,K/=b,f/=b):(o=0,V=0,K=0,f=1),{t:[M,I,D],r:[o,V,K,f],s:[u,x,C]}}function Qt(e){let t={};return e.grab&&(t.interactable={mode:typeof e.grab=="string"?e.grab:"2-hand"},t.movable={scaleInZ:!!e.scale,minScale:typeof e.scale=="object"?e.scale.min??.1:.1,maxScale:typeof e.scale=="object"?e.scale.max??10:10}),e.billboard&&(t.billboard={mode:typeof e.billboard=="string"?e.billboard:"capsule"}),e.follow&&(t.follow={target:typeof e.follow=="object"?e.follow.mode??"head":e.follow}),e.anchor&&(t.anchor={plane:e.anchor}),e.physics&&e.physics!=="none"&&(t.rigidbody={type:e.physics}),t}var Me=(e,t,i,r)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(i,e)):r;function Et(e){let t=e?.audioEmitter??e?.spatialAudio??(typeof e?.audio=="object"&&e.audio&&("preset"in e.audio||"distanceModel"in e.audio||"coneInnerAngle"in e.audio||"maxDistance"in e.audio||"volume"in e.audio)?e.audio:typeof e?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(e.audio)?{preset:e.audio}:void 0);if(!t||typeof t=="object"&&t.enabled===!1)return null;let i=typeof t=="string"?{preset:t}:t,r=typeof i.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(i.src)?i.src:void 0,a=typeof i.preset=="string"?i.preset:void 0;return!r&&!a?null:{ae:i,src:r,preset:a,volume:Me(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function Jt(e,t){e.updateMatrixWorld(!0);let i=[],r=0,a=[],s=[],c=[],l=[],g=new Set,d=[],v=[],M=new Map,I=[],D=[],u=[],x=new Map,C=[],R=[];function T(f){let b=M.get(f);if(b!==void 0)return b;b=v.length,M.set(f,b);let n=f,p=n.color?.r??1,B=n.color?.g??1,z=n.color?.b??1,j=n.opacity??1,ee={baseColorFactor:[p,B,z,j],metallicFactor:n.metalness??0,roughnessFactor:n.roughness??.5},L={},X=E=>{if(!E)return;let H=(typeof E=="string"?E:typeof E.source=="string"?E.source:typeof E.image=="string"?E.image:"").trim();if(!H||/[\x00-\x1f\x7f\\]|\.\./.test(H)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(H)||!H.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(H)))return;let W=x.get(H);if(W===void 0){let Z=I.length;I.push({uri:H}),D.length===0&&D.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),W=u.length,u.push({sampler:0,source:Z}),x.set(H,W)}return{index:W}},J=X(n.map);J&&(ee.baseColorTexture=J);let re=X(n.roughnessMap||n.metalnessMap);re&&(ee.metallicRoughnessTexture=re);let $=n.map?.avgColor;Array.isArray($)&&$.length>=3&&(L.avgColor=[$[0],$[1],$[2]]);let te=X(n.normalMap),O=X(n.emissiveMap),G=X(n.aoMap),q={name:n.name||"",pbrMetallicRoughness:ee,doubleSided:n.side===2||!!n.doubleSided,...te?{normalTexture:te}:{},...O?{emissiveTexture:O}:{},...G?{occlusionTexture:G}:{},...Object.keys(L).length>0?{extras:L}:{}};if(n.emissive&&(n.emissive.r>0||n.emissive.g>0||n.emissive.b>0)){let E=n.emissiveIntensity??1;q.emissiveFactor=[n.emissive.r*E,n.emissive.g*E,n.emissive.b*E]}let A={};return n.clearcoat&&n.clearcoat>0&&(A.KHR_materials_clearcoat={clearcoatFactor:n.clearcoat,clearcoatRoughnessFactor:n.clearcoatRoughness||0}),n.sheen&&n.sheen>0&&(A.KHR_materials_sheen={sheenColorFactor:n.sheenColor?[n.sheenColor.r,n.sheenColor.g,n.sheenColor.b]:[1,1,1],sheenRoughnessFactor:n.sheenRoughness||0}),n.transmission&&n.transmission>0&&(A.KHR_materials_transmission={transmissionFactor:n.transmission}),n.thickness&&n.thickness>0&&(A.KHR_materials_volume={thicknessFactor:n.thickness,attenuationDistance:n.attenuationDistance??1/0,attenuationColor:n.attenuationColor?[n.attenuationColor.r,n.attenuationColor.g,n.attenuationColor.b]:[1,1,1]}),n.ior!==void 0&&n.ior!==1.5&&(A.KHR_materials_ior={ior:n.ior}),n.dispersion&&n.dispersion>0&&(A.KHR_materials_dispersion={dispersion:n.dispersion}),n.iridescence&&n.iridescence>0&&(A.KHR_materials_iridescence={iridescenceFactor:n.iridescence,iridescenceIor:n.iridescenceIOR??1.3}),Object.keys(A).length>0&&(q.extensions=A),v.push(q),b}function m(f,b){let n=new Uint8Array(f.buffer,f.byteOffset,f.byteLength),p=Zt(n.byteLength),B=new Uint8Array(p);B.set(n),i.push(B);let z=a.length;return a.push({buffer:0,byteOffset:r,byteLength:n.byteLength,target:b}),r+=p,z}function h(f,b,n,p,B,z,j){let ee=m(f,n),L=s.length,X={bufferView:ee,byteOffset:0,componentType:p,count:B,type:b};return z&&(X.min=z),j&&(X.max=j),s.push(X),L}e.traverse(f=>{if(f.isLight||f.color&&f.intensity!==void 0){let b=f.matrixWorld?.elements,n=se(b?b[12]:f.position?.x,0),p=se(b?b[13]:f.position?.y,0),B=se(b?b[14]:f.position?.z,0),z=f.target,j=z?.parent?z?.matrixWorld?.elements:void 0,ee=se(j?j[12]:z?.position?.x,0),L=se(j?j[13]:z?.position?.y,0),X=se(j?j[14]:z?.position?.z,0),J=ee-n,re=L-p,$=X-B,te=Math.hypot(J,re,$),O=Math.max(.01,Math.min(Math.PI/2,se(f.angle,Math.PI/3))),G=Math.max(0,Math.min(1,se(f.penumbra,0)));R.push({type:f.type,color:[f.color.r,f.color.g,f.color.b],intensity:f.intensity,position:[n,p,B],...f.type==="spot"?{direction:te>1e-6?[J/te,re/te,$/te]:[0,-1,0],outerConeAngle:O,innerConeAngle:Math.max(0,O*(1-G)),range:Math.max(0,se(f.distance,0))}:f.type==="point"?{range:Math.max(0,se(f.distance,0))}:{}})}});let w=[],y=new Set([e]),F=[];if(Array.isArray(e.children))for(let f=e.children.length-1;f>=0;f--)F.push({obj:e.children[f],parentKids:w});for(;F.length>0;){let{obj:f,parentKids:b}=F.pop();if(!f||typeof f!="object"||y.has(f))continue;y.add(f),f._bakeAuthorGeometry?.(),be().materializeDeclarativeGeometry?.(f);let n=!!(f.userData&&(f.userData.xr&&typeof f.userData.xr=="object"&&Object.keys(f.userData.xr).length>0||f.userData.interactivity&&typeof f.userData.interactivity=="object"&&Object.keys(f.userData.interactivity).length>0)),p={name:f.name||(n?`Node_${l.length}`:"")},B=se(f.position?.x,0),z=se(f.position?.y,0),j=se(f.position?.z,0),ee=se(f.quaternion?.x,0),L=se(f.quaternion?.y,0),X=se(f.quaternion?.z,0),J=se(f.quaternion?.w,1),re=se(f.scale?.x,1),$=se(f.scale?.y,1),te=se(f.scale?.z,1);if((B||z||j)&&(p.translation=[B,z,j]),(ee||L||X||J!==1)&&(p.rotation=[ee,L,X,J]),(re!==1||$!==1||te!==1)&&(p.scale=[re,$,te]),f.visible===!1&&(p.extensions={...p.extensions||{},KHR_node_visibility:{visible:!1}},g.add("KHR_node_visibility")),f.userData&&Object.keys(f.userData).length>0&&(p.extras=JSON.parse(JSON.stringify(f.userData,(q,A)=>{if(!(q==="__proto__"||q==="prototype"||q==="constructor"))return typeof A=="function"?void 0:A})),f.userData.xr)){let q=Qt(f.userData.xr);p.extensions={...p.extensions||{},MOZ_hubs_components:q,ANDROID_xr_scenecore:q},be().xrTraitSerializer?.gltfNode(p,f.userData.xr),g.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(f.geometry){let q=f.geometry,A=q.attributes.position;if(A&&A.count>0){let E=[1/0,1/0,1/0],H=[-1/0,-1/0,-1/0];for(let ie=0;ie<A.count;ie++){let ae=A.getX(ie),ne=A.getY(ie),oe=A.getZ(ie);ae<E[0]&&(E[0]=ae),ae>H[0]&&(H[0]=ae),ne<E[1]&&(E[1]=ne),ne>H[1]&&(H[1]=ne),oe<E[2]&&(E[2]=oe),oe>H[2]&&(H[2]=oe)}let W={attributes:{POSITION:h(A.array,"VEC3",34962,5126,A.count,E,H)}};if(q.attributes.normal&&(W.attributes.NORMAL=h(q.attributes.normal.array,"VEC3",34962,5126,q.attributes.normal.count)),q.attributes.uv&&(W.attributes.TEXCOORD_0=h(q.attributes.uv.array,"VEC2",34962,5126,q.attributes.uv.count)),q.index){let ie=q.index.array instanceof Uint32Array;W.indices=h(q.index.array,"SCALAR",34963,ie?5125:5123,q.index.count)}let Z=Array.isArray(f.material)?f.material[0]:f.material;Z&&(W.material=T(Z));let Q=f.userData?.variants;if(Q&&typeof Q=="object"){let ie=new Map;for(let ae of Object.keys(Q)){if(!ae||ae==="__proto__"||ae==="constructor"||ae==="prototype")continue;let ne=Q[ae];if(!ne||typeof ne!="object")continue;let oe=C.indexOf(ae);if(oe===-1&&C.length<256&&(oe=C.length,C.push(ae)),oe===-1)continue;let me=T(ne),pe=ie.get(me);pe||(pe=[],ie.set(me,pe)),pe.push(oe)}if(ie.size>0){let ae=[];for(let[ne,oe]of ie.entries())ae.push({material:ne,variants:oe});W.extensions={...W.extensions||{},KHR_materials_variants:{mappings:ae}},g.add("KHR_materials_variants")}}let Y=f;if(Y.isInstancedMesh&&typeof Y.count=="number"&&Y.count>0&&Y.instanceMatrix?.array){let ie=Math.min(1e4,Math.floor(Y.count)),ae=Y.instanceMatrix.array,ne=new Float32Array(ie*3),oe=new Float32Array(ie*4),me=new Float32Array(ie*3);for(let he=0;he<ie;he++){let{t:ge,r:ye,s:Te}=St(ae,he*16);ne[he*3]=ge[0],ne[he*3+1]=ge[1],ne[he*3+2]=ge[2],oe[he*4]=ye[0],oe[he*4+1]=ye[1],oe[he*4+2]=ye[2],oe[he*4+3]=ye[3],me[he*3]=Te[0],me[he*3+1]=Te[1],me[he*3+2]=Te[2]}let pe={TRANSLATION:h(ne,"VEC3",0,5126,ie),ROTATION:h(oe,"VEC4",0,5126,ie),SCALE:h(me,"VEC3",0,5126,ie)};if(Y.instanceColor?.array&&Y.instanceColor.array.length>=ie*3){let he=new Float32Array(Y.instanceColor.array.subarray(0,ie*3));pe._COLOR_0=h(he,"VEC3",0,5126,ie)}p.extensions={...p.extensions||{},EXT_mesh_gpu_instancing:{attributes:pe}},g.add("EXT_mesh_gpu_instancing")}let ue=c.length;c.push({primitives:[W],name:f.name,...p.extras?{extras:p.extras}:{}}),p.mesh=ue}}let O=l.length;l.push(p),d.push(f),b.push(O);let G=f.children;if(Array.isArray(G)&&G.length>0){let q=[];p.children=q;for(let A=G.length-1;A>=0;A--)F.push({obj:G[A],parentKids:q})}}for(let f=0;f<l.length;f++){let b=l[f];b.children&&b.children.length===0?delete b.children:b.children&&b.children.length>0&&(b.extras?.xr?.lod||b.extensions?.ANDROID_xr_scenecore?.lod||d[f]?.isLOD)&&(b.extensions={...b.extensions||{},MSFT_lod:{ids:[...b.children]}},g.add("MSFT_lod"))}let U=t?.animateCallback||t?.animateFn||(typeof e.userData?.animate=="function"?e.userData.animate:typeof e.__animateFn=="function"?e.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),_=[];if(typeof U=="function"&&d.length>0){let f=t?.duration??4,b=t?.fps??15,n=Math.max(2,Math.round(f*b)+1),p=new Float32Array(n),B=d.map($=>[se($.position?.x,0),se($.position?.y,0),se($.position?.z,0),se($.quaternion?.x,0),se($.quaternion?.y,0),se($.quaternion?.z,0),se($.quaternion?.w,1),se($.scale?.x,1),se($.scale?.y,1),se($.scale?.z,1)]),z=d.map(()=>new Float32Array(n*3)),j=d.map(()=>new Float32Array(n*4)),ee=d.map(()=>new Float32Array(n*3));for(let $=0;$<n;$++){let te=$/(n-1)*f;p[$]=te;try{U(te)}catch{}for(let O=0;O<d.length;O++){let G=d[O];z[O][$*3]=se(G.position?.x,0),z[O][$*3+1]=se(G.position?.y,0),z[O][$*3+2]=se(G.position?.z,0);let q=se(G.quaternion?.x,0),A=se(G.quaternion?.y,0),E=se(G.quaternion?.z,0),H=se(G.quaternion?.w,1),W=Math.hypot(q,A,E,H)||1;if(q/=W,A/=W,E/=W,H/=W,$>0){let Z=($-1)*4,Q=j[O];Q[Z]*q+Q[Z+1]*A+Q[Z+2]*E+Q[Z+3]*H<0&&(q=-q,A=-A,E=-E,H=-H)}j[O][$*4]=q,j[O][$*4+1]=A,j[O][$*4+2]=E,j[O][$*4+3]=H,ee[O][$*3]=se(G.scale?.x,1),ee[O][$*3+1]=se(G.scale?.y,1),ee[O][$*3+2]=se(G.scale?.z,1)}}for(let $=0;$<d.length;$++){let te=d[$],O=B[$];te.position?.set(O[0],O[1],O[2]),te.quaternion?.set(O[3],O[4],O[5],O[6]),te.scale?.set(O[7],O[8],O[9])}e.updateMatrixWorld(!0);let L=null,X=()=>(L===null&&(L=h(p,"SCALAR",0,5126,n,[0],[f])),L),J=[],re=[];for(let $=0;$<d.length;$++){let te=B[$],O=(q,A,E)=>q.some((H,W)=>Math.abs(H-te[E+W%A])>1e-4),G=(q,A,E,H)=>{q&&re.push({sampler:J.push({input:X(),interpolation:"LINEAR",output:h(A,E,0,5126,n)})-1,target:{node:$,path:H}})};G(O(z[$],3,0),z[$],"VEC3","translation"),G(O(j[$],4,3),j[$],"VEC4","rotation"),G(O(ee[$],3,7),ee[$],"VEC3","scale")}re.length>0&&_.push({name:"ProceduralLoop",samplers:J,channels:re})}let k=mt(l,c,e.userData),P=[],N=[],S=[];for(let f=0;f<l.length;f++){let b=l[f],n=Et(b.extras?.xr);if(!n)continue;let{ae:p,src:B,preset:z,volume:j,loop:ee,isGlobal:L}=n,X=b.name||`Node_${f}`,J=N.length;N.push({name:`${X}_source`,gain:j,loop:ee,autoPlay:typeof p.autoplay=="boolean"?p.autoplay:!0,...B!==void 0?{audio:P.push({uri:B})-1}:{},...z?{extras:{preset:z,pitch:Me(p.pitch,.25,4,1)}}:{}});let re=S.length,$=Me(p.refDistance,.05,100,1),te=Me(p.coneInnerAngle,0,360,360),O=Me(p.coneOuterAngle,te,360,360);S.push({name:`${X}_emitter`,type:L?"global":"positional",gain:j,sources:[J],...L?{}:{positional:{distanceModel:p.distanceModel==="linear"||p.distanceModel==="exponential"?p.distanceModel:"inverse",refDistance:$,maxDistance:Me(p.maxDistance,$,500,Math.max($,25)),rolloffFactor:Me(p.rolloffFactor,0,10,1),coneInnerAngle:+(te*Math.PI/180).toFixed(6),coneOuterAngle:+(O*Math.PI/180).toFixed(6),coneOuterGain:Me(p.coneOuterGain,0,1,0)}}}),b.extensions={...b.extensions||{},KHR_audio_emitter:{emitter:re}},g.add("KHR_audio_emitter")}let o={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity}},scenes:[{nodes:w}],scene:0,nodes:l,meshes:c,materials:v,...I.length>0?{images:I}:{},...D.length>0?{samplers:D}:{},...u.length>0?{textures:u}:{},accessors:s,bufferViews:a,buffers:[{byteLength:r}],..._.length>0?{animations:_}:{},...k||g.size>0?{extensionsUsed:[...k?["KHR_interactivity"]:[],...g]}:{},...k||C.length>0||S.length>0?{extensions:{...k?{KHR_interactivity:k}:{},...C.length>0?{KHR_materials_variants:{variants:C.map(f=>({name:f}))}}:{},...S.length>0?{KHR_audio_emitter:{...P.length>0?{audio:P}:{},sources:N,emitters:S}}:{}}}:{}},V=new Uint8Array(r),K=0;for(let f of i)V.set(f,K),K+=f.byteLength;return[{gltf:o,bin:V.buffer,lights:R,environmentIntensity:e.environmentIntensity},d]}function Lt(e){return new TextEncoder().encode(e)}function en(e,t){let[i,r]=Jt(e,t);return Ke(i,r)}function Ke(e,t){let i=[],r=e.gltf,a=be().decoders.get("meshopt");a&&typeof a.decodeBufferViews=="function"&&a.decodeBufferViews(r,e);let s=e.bin,c=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),l=r.accessors||[],g=r.bufferViews||[],d=r.materials||[],v=r.meshes||[],M=r.nodes||[],I=r.textures||[],D=r.images||[],u=r.samplers||[],x=new Set,C=d.map((y,F)=>Rt(x,Ue(y?.name,`Material_${F}`))),R=new Map;function T(y){let F=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(y);if(!F)return null;let U=F[2].replace(/\s+/g,""),_=U.endsWith("==")?2:U.endsWith("=")?1:0,k=new Uint8Array((U.length*3>>2)-_),P=S=>{let o=U.charCodeAt(S);return o>96?o-71:o>64?o-65:o>47?o+4:o===43?62:o===47?63:0},N=0;for(let S=0;S<U.length;S+=4){let o=P(S)<<18|P(S+1)<<12|P(S+2)<<6|P(S+3);k[N++]=o>>16&255,N<k.length&&(k[N++]=o>>8&255),N<k.length&&(k[N++]=o&255)}return k}function m(y,F,U){let _=y?.index;if(typeof _!="number")return;let k=I[_],P=k?.source;if(typeof P!="number"||!D[P])return;let N=R.get(P);if(N===void 0){N=null;let V=D[P],K=null;if(typeof V.bufferView=="number"){let f=g[V.bufferView],b=f?.byteOffset||0,n=f?.byteLength||0;f&&n>0&&b>=0&&b+n<=c.byteLength&&(K=new Uint8Array(c,b,n))}else typeof V.uri=="string"&&(K=T(V.uri));if(K&&K.byteLength>0){let f=K[0]===255&&K[1]===216&&K[2]===255||!(K[0]===137&&K[1]===80)&&/jpe?g/i.test(V.mimeType||V.uri||"");N={file:`texture_${P}.${f?"jpg":"png"}`,data:K}}R.set(P,N)}if(!N)return;let S=typeof k.sampler=="number"?u[k.sampler]:void 0,o=V=>V===33071?"clamp":V===33648?"mirror":"repeat";return{file:N.file,data:N.data,wrapS:o(S?.wrapS),wrapT:o(S?.wrapT),...F?{scale:F}:{},...U?{bias:U}:{}}}function h(y){let F=l[y];if(!F)throw new Error(`Accessor ${y} not found`);let U=g[F.bufferView||0],_=(U.byteOffset||0)+(F.byteOffset||0),k=U.byteLength||0;return{acc:F,buffer:c.slice(_,_+k)}}function w(y,F,U,_){let k=[],P=v[y];if(!P)return k;let N=P.primitives||[];for(let S=0;S<N.length;S++){let o=N[S],V=o.attributes?.POSITION;if(V===void 0)continue;let{acc:K,buffer:f}=h(V),b=new Float32Array(f,0,K.count*3),n,p=o.attributes?.NORMAL;if(p!==void 0){let{acc:A,buffer:E}=h(p),H=new Float32Array(E,0,A.count*3);n=new Float32Array(H.length);for(let W=0;W<A.count;W++){let Z=H[W*3],Q=H[W*3+1],Y=H[W*3+2],ue=Math.hypot(Z,Q,Y)||1;n[W*3]=Z/ue,n[W*3+1]=Q/ue,n[W*3+2]=Y/ue}}let B,z=o.attributes?.TEXCOORD_0;if(z!==void 0){let{acc:A,buffer:E}=h(z);B=new Float32Array(E,0,A.count*2)}let j;if(o.indices!==void 0){let{acc:A,buffer:E}=h(o.indices);j=A.componentType===5125?new Uint32Array(E,0,A.count):new Uint16Array(E,0,A.count);let H=K.count;for(let W of j)if(W>=H)throw new Error(`SecurityError: Index buffer value (${W}) out of vertex bounds [0, ${H}).`)}else{let A=K.count;j=A>65535?new Uint32Array(A):new Uint16Array(A);for(let E=0;E<A;E++)j[E]=E}let ee="DefaultMaterial",L=[1,1,1],X=.5,J=0,re=0,$=0,te=1.5,O=1,G=[0,0,0],q;if(o.material!==void 0&&d[o.material]){let A=d[o.material];ee=C[o.material]||`Material_${o.material}`;let E=A.pbrMetallicRoughness||{},H=(ge,ye)=>Array.isArray(ge)&&ge.length>=3?[ge[0],ge[1],ge[2]]:ye;L=H(E.baseColorFactor,[1,1,1]);let W=Array.isArray(E.baseColorFactor)&&typeof E.baseColorFactor[3]=="number"?E.baseColorFactor[3]:1,Z=L[0]!==1||L[1]!==1||L[2]!==1||W!==1,Q=m(E.baseColorTexture,Z?[L[0],L[1],L[2],W]:void 0),Y=A.extras?.avgColor;!Q&&Array.isArray(Y)&&Y.length>=3&&(L=[L[0]*Y[0],L[1]*Y[1],L[2]*Y[2]]),typeof E.roughnessFactor=="number"&&(X=E.roughnessFactor),typeof E.metallicFactor=="number"&&(J=E.metallicFactor);let ue=typeof E.roughnessFactor=="number"?E.roughnessFactor:1,ie=typeof E.metallicFactor=="number"?E.metallicFactor:1,ae=m(E.metallicRoughnessTexture,ue!==1||ie!==1?[1,ue,ie,1]:void 0);G=H(A.emissiveFactor,[0,0,0]);let ne=(G[0]>0||G[1]>0||G[2]>0)&&(G[0]!==1||G[1]!==1||G[2]!==1)?[G[0],G[1],G[2],1]:void 0,oe=m(A.emissiveTexture,ne),me=m(A.normalTexture,[2,2,2,1],[-1,-1,-1,0]),pe=m(A.occlusionTexture);(Q||ae||me||oe||pe)&&(q=[Q,ae,me,oe,pe]);let he=A.extensions||{};he.KHR_materials_clearcoat&&(re=he.KHR_materials_clearcoat.clearcoatFactor??0,$=he.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof he.KHR_materials_ior?.ior=="number"&&(te=he.KHR_materials_ior.ior),O=W*(1-(he.KHR_materials_transmission?.transmissionFactor??0))}k.push({name:N.length>1?`${F}_p${S}`:F,positions:b,indices:j,normals:n,uvs:B,materialName:ee,color:L,roughness:X,metallic:J,clearcoat:re,clearcoatRoughness:$,ior:te,opacity:O,emissiveColor:G,...q?{textures:q}:{},xrTraits:U||P.extras?.xr,..._?{invisible:!0}:{}})}return k}if(M.length>0){let y=new Float32Array(0),F=new Uint16Array(0),U=(b,n)=>{if(b===void 0)return null;let{acc:p,buffer:B}=h(b);return new Float32Array(B,0,p.count*n)},_=(b,n)=>Array.isArray(b)&&b.length>=3?[se(b[0],n),se(b[1],n),se(b[2],n)]:[n,n,n],k=(b,n,p)=>b&&b.length>=(n+1)*3?[b[n*3],b[n*3+1],b[n*3+2]]:p,P=(b,n,p)=>b&&b.length>=(n+1)*4?[b[n*4],b[n*4+1],b[n*4+2],b[n*4+3]]:p,N=new Map,S=r.animations?.[0];if(S&&Array.isArray(S.channels)&&Array.isArray(S.samplers))for(let b of S.channels){let n=S.samplers[b?.sampler],p=b?.target?.node,B=b?.target?.path;if(!n||typeof p!="number"||n.input===void 0)continue;let z=N.get(p);z||(z={input:n.input},N.set(p,z)),B==="translation"?z.t=n.output:B==="rotation"?z.r=n.output:B==="scale"&&(z.s=n.output)}let o=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(o)||o.length===0){let b=new Set;for(let n of M)if(Array.isArray(n?.children))for(let p of n.children)b.add(p);o=[];for(let n=0;n<M.length;n++)b.has(n)||o.push(n);o.length===0&&(o=[0])}let V=new Set,K=[],f=(b,n)=>{if(Array.isArray(b))for(let p=b.length-1;p>=0;p--)K.push({idx:b[p],out:n})};for(f(o,i);K.length>0;){let{idx:b,out:n}=K.pop();if(typeof b!="number"||b<0||b>=M.length||V.has(b))continue;V.add(b);let p=M[b];if(!p)continue;let B=[0,0,0],z=[0,0,0,1],j=[1,1,1];if(Array.isArray(p.matrix)&&p.matrix.length===16){let O=St(p.matrix);B=O.t,z=O.r,j=O.s}else B=_(p.translation,0),Array.isArray(p.rotation)&&p.rotation.length>=4&&(z=[se(p.rotation[0],0),se(p.rotation[1],0),se(p.rotation[2],0),se(p.rotation[3],1)]),j=_(p.scale,1);let ee,L=N.get(b);if(L){let O=U(L.input,1);if(O&&O.length>0){let G=U(L.t,3),q=U(L.r,4),A=U(L.s,3),E=Array.from(O),H=[],W=[],Z=[];for(let Q=0;Q<O.length;Q++)H.push(k(G,Q,B)),W.push(P(q,Q,z)),Z.push(k(A,Q,j));ee={times:E,translations:H,rotations:W,scales:Z}}}let X=Array.isArray(p.children)?p.children:[],J=typeof p.mesh=="number"&&p.mesh>=0&&p.mesh<v.length,re=t?.[b]?.userData?.xr??p.extras?.xr;if(!J&&X.length===0&&(p.camera!==void 0||p.extensions?.KHR_lights_punctual||!p.name&&!p.extras&&!re&&!ee))continue;let $=(O,G,q)=>({name:O,positions:y,indices:F,isXform:!0,xrTraits:re,timeSamples:ee,translation:B,rotation:z,scale:j,children:G,...q?{invisible:!0}:{}}),te=p.visible===!1||p.extensions?.KHR_node_visibility?.visible===!1||t?.[b]?.visible===!1;if(J){let O=p.name||v[p.mesh]?.name||`Mesh_${b}`,G=w(p.mesh,O,re,te),q=p.extensions?.EXT_mesh_gpu_instancing?.attributes;if(q&&typeof q=="object"&&G.length>0){let A=U(q.TRANSLATION,3),E=U(q.ROTATION,4),H=U(q.SCALE,3),W=U(q._COLOR_0,3),Z=Math.min(1e3,A?A.length/3:E?E.length/4:H?H.length/3:0);if(Z>0){let Q=[];for(let Y=0;Y<Z;Y++){let ue=k(A,Y,[0,0,0]),ie=P(E,Y,[0,0,0,1]),ae=k(H,Y,[1,1,1]);for(let ne of G){let oe=ne.color||[.8,.8,.8],me=W&&W.length>=(Y+1)*3;Q.push({...ne,name:`${ne.name}_${Y}`,materialName:me?`${ne.materialName}_inst_${Y}`:ne.materialName,color:me?[oe[0]*W[Y*3],oe[1]*W[Y*3+1],oe[2]*W[Y*3+2]]:ne.color,translation:ue,rotation:ie,scale:ae})}}f(X,Q),n.push($(O,Q,te));continue}}if(G.length===1)G[0].translation=B,G[0].rotation=z,G[0].scale=j,G[0].timeSamples=ee,X.length>0&&(G[0].children=[],f(X,G[0].children)),n.push(G[0]);else{let A=[...G];f(X,A),n.push($(O,A,te))}}else{let O=[];f(X,O),n.push($(p.name||`Group_${b}`,O,te))}}}else for(let y=0;y<v.length;y++){let F=v[y].name||`Mesh_${y}`;i.push(...w(y,F,v[y].extras?.xr))}return i}function Ue(e,t){if(!e||typeof e!="string")return t;let i=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(i)&&(i="_"+i),i||t}function Ie(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function de(e){if(!Number.isFinite(e)||Math.abs(e)<1e-7)return"0";let t=Number(e.toFixed(5)).toString();return t.indexOf(".")===-1?`${t}.0`:t}var xe=(e,t,i)=>`(${de(e)}, ${de(t)}, ${de(i)})`,_e=(e,t,i,r)=>`(${de(e)}, ${de(t)}, ${de(i)}, ${de(r)})`;function wt(e){let t=e.length/3,i=new Array(t);for(let r=0;r<t;r++)i[r]=xe(e[r*3],e[r*3+1],e[r*3+2]);return i.join(", ")}function tn(e,t){let i=new Array(t);for(let r=0;r<t;r++)i[r]=`(${de(e[r*2])}, ${de(1-e[r*2+1])})`;return i.join(", ")}function nn(e){return Array.from(e).join(", ")}function qe(e){let t=new Map,i=0,r=null,a=[...e];for(;a.length>0;){let u=a.pop();if(!u.isXform&&u.positions&&u.positions.length>0){let x=Ue(u.materialName,"DefaultMaterial");t.has(x)||t.set(x,{color:u.color||[1,1,1],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],textures:u.textures})}if(u.timeSamples&&u.timeSamples.times.length>0){let x=u.timeSamples.times[u.timeSamples.times.length-1];x>i&&(i=x)}if(u.xrTraits?.anchor&&!r&&(r=u.xrTraits.anchor==="vertical"||u.xrTraits.anchor==="wall"?"vertical":"horizontal"),u.children)for(let x=u.children.length-1;x>=0;x--)a.push(u.children[x])}let s="";i>0&&(s=`startTimeCode = 0
250
+ endTimeCode = ${de(i)}
254
251
  timeCodesPerSecond = 1.0
255
- `);let s="";r&&(s=`uniform token preliminary:anchoring:type = "plane"
252
+ `);let c="";r&&(c=`uniform token preliminary:anchoring:type = "plane"
256
253
  uniform token preliminary:planeAnchoring:alignment = "${r}"
257
- `);let a=`#usda 1.0
254
+ `);let l=`#usda 1.0
258
255
  (
259
256
  defaultPrim = "Root"
260
257
  metersPerUnit = 1.0
261
258
  upAxis = "Y"
262
- ${i})
259
+ ${s})
263
260
 
264
261
  def Xform "Root" (
265
262
  kind = "component"
266
263
  )
267
264
  {
268
- ${s}def Scope "Materials"
265
+ ${c}def Scope "Materials"
266
+ {
267
+ `;for(let[u,x]of t.entries()){let[C,R,T]=x.color,[m,h,w]=x.emissiveColor,y=`/Root/Materials/${u}`,[F,U,_,k,P]=x.textures||[],N=(f,b)=>`.connect = <${y}/${f}.outputs:${b}>`,S=F?`color3f inputs:diffuseColor${N("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${xe(C,R,T)}`,o=U?`float inputs:metallic${N("MetallicRoughnessTexture","b")}
268
+ float inputs:roughness${N("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${de(x.metallic)}
269
+ float inputs:roughness = ${de(x.roughness)}`,V="";x.clearcoat>0&&(V+=`float inputs:clearcoat = ${de(x.clearcoat)}
270
+ `,V+=`float inputs:clearcoatRoughness = ${de(x.clearcoatRoughness)}
271
+ `),x.ior!==1.5&&(V+=`float inputs:ior = ${de(x.ior)}
272
+ `),x.opacity<1&&(V+=`float inputs:opacity = ${de(x.opacity)}
273
+ `),k?V+=`color3f inputs:emissiveColor${N("EmissiveTexture","rgb")}
274
+ `:(m>0||h>0||w>0)&&(V+=`color3f inputs:emissiveColor = ${xe(m,h,w)}
275
+ `),_&&(V+=`normal3f inputs:normal${N("NormalTexture","rgb")}
276
+ `),P&&(V+=`float inputs:occlusion${N("OcclusionTexture","r")}
277
+ `);let K="";if(F||U||_||k||P){K+=`def Shader "PrimvarReader"
278
+ {
279
+ uniform token info:id = "UsdPrimvarReader_float2"
280
+ string inputs:varname = "st"
281
+ float2 outputs:result
282
+ }
283
+ `;let f=(b,n,p,B)=>{if(!n)return;let z=n.scale?`float4 inputs:scale = ${_e(n.scale[0],n.scale[1],n.scale[2],n.scale[3])}
284
+ `:"",j=n.bias?`float4 inputs:bias = ${_e(n.bias[0],n.bias[1],n.bias[2],n.bias[3])}
285
+ `:"";K+=`def Shader "${b}"
269
286
  {
270
- `;for(let[o,l]of e.entries()){let[u,d,f]=l.color,[T,g,m]=l.emissiveColor,p="";l.clearcoat>0&&(p+=`float inputs:clearcoat = ${X(l.clearcoat)}
271
- `,p+=`float inputs:clearcoatRoughness = ${X(l.clearcoatRoughness)}
272
- `),l.ior!==1.5&&(p+=`float inputs:ior = ${X(l.ior)}
273
- `),l.opacity<1&&(p+=`float inputs:opacity = ${X(l.opacity)}
274
- `),(T>0||g>0||m>0)&&(p+=`color3f inputs:emissiveColor = (${X(T)}, ${X(g)}, ${X(m)})
275
- `),a+=`def Material "${o}"
287
+ uniform token info:id = "UsdUVTexture"
288
+ asset inputs:file = @${Ie(n.file)}@
289
+ float2 inputs:st${N("PrimvarReader","result")}
290
+ token inputs:sourceColorSpace = "${p}"
291
+ token inputs:wrapS = "${n.wrapS||"repeat"}"
292
+ token inputs:wrapT = "${n.wrapT||"repeat"}"
293
+ ${z}${j}${B}}
294
+ `};f("DiffuseTexture",F,"sRGB",`float3 outputs:rgb
295
+ `),f("MetallicRoughnessTexture",U,"raw",`float outputs:g
296
+ float outputs:b
297
+ `),f("NormalTexture",_,"raw",`float3 outputs:rgb
298
+ `),f("EmissiveTexture",k,"sRGB",`float3 outputs:rgb
299
+ `),f("OcclusionTexture",P,"raw",`float outputs:r
300
+ `)}l+=`def Material "${u}"
276
301
  {
277
302
  def Shader "PBRShader"
278
303
  {
279
304
  uniform token info:id = "UsdPreviewSurface"
280
- color3f inputs:diffuseColor = (${X(u)}, ${X(d)}, ${X(f)})
281
- float inputs:metallic = ${X(l.metallic)}
282
- float inputs:roughness = ${X(l.roughness)}
283
- ${p}token outputs:surface
284
- }
285
- token outputs:surface.connect = </Root/Materials/${o}/PBRShader.outputs:surface>
305
+ ${S}
306
+ ${o}
307
+ ${V}token outputs:surface
286
308
  }
287
- `}a+=`}
309
+ token outputs:surface${N("PBRShader","surface")}
310
+ ${K}}
311
+ `}l+=`}
288
312
  def Scope "Meshes"
289
313
  {
290
- `;let c=new Set;for(let o=0;o<n.length;o++){let l=n[o],u=l.positions.length/3,d=1/0,f=1/0,T=1/0,g=-1/0,m=-1/0,p=-1/0;for(let E=0;E<u;E++){let b=l.positions[E*3],F=l.positions[E*3+1],L=l.positions[E*3+2];b<d&&(d=b),b>g&&(g=b),F<f&&(f=F),F>m&&(m=F),L<T&&(T=L),L>p&&(p=L)}isFinite(d)||(d=f=T=-1,g=m=p=1);let R=Math.floor(l.indices.length/3),A=Ve(l.materialName,"DefaultMaterial"),v=Ve(l.name,`Mesh_${o}`);c.has(v)&&(v=`${v}_${o}`),c.add(v);let D=R>0?R===1?"3":"3, ".repeat(R-1)+"3":"",y=l.xrTraits,P="";if(y){let E=[];y.physics&&y.physics!=="none"&&E.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let b=he().xrTraitSerializer?.usdLines(y,dt)??[];if(!b.length)for(let F of["grab","billboard","follow","anchor","physics"]){let L=F==="follow"&&typeof y.follow=="object"?y.follow.mode??"head":y[F];L!==void 0&&b.push(`string ${F} = "${dt(L)}"`)}b.length>0&&E.push(`customData = {
314
+ `;let g=(u,x,C)=>{let R=[];x&&R.push('"MaterialBindingAPI"');let T=!!(u?.rigidBody&&u.rigidBody!=="none"&&(typeof u.rigidBody!="object"||u.rigidBody.enabled!==!1)),m=!!(u?.physics&&u.physics!=="none"||T);m&&R.push(...T?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let h=[];if(R.length>0&&h.push(`prepend apiSchemas = [${R.join(", ")}]`),u){let _=be().xrTraitSerializer?.usdLines(u,Ie)??[];if(!_.length)for(let k of["grab","billboard","follow","anchor","physics"]){let P=k==="follow"&&typeof u.follow=="object"?u.follow.mode??"head":u[k];P!==void 0&&_.push(`string ${k} = "${Ie(P)}"`)}_.length>0&&h.push(`customData = {
291
315
  dictionary xr = {
292
- ${b.join(`
316
+ ${_.join(`
293
317
  `)}
294
318
  }
295
- }`),E.length>0&&(P=` (
296
- ${E.join(`
319
+ }`)}let w=h.length>0?` (
320
+ ${h.join(`
297
321
  `)}
298
- )`)}if(a+=`def Mesh "${v}"${P}
299
- {
300
- `,y?.physics&&y.physics!=="none"){let E=y.physics==="static"?"true":"false";a+=`bool physics:rigidBodyEnabled = true
301
- bool physics:kinematicEnabled = ${E}
322
+ )`:"",y=C?`uniform token visibility = "invisible"
323
+ `:"";if(m){let _=u?.rigidBody??u?.physics,k=_?.body??_?.mode??_;y+=`bool physics:rigidBodyEnabled = true
324
+ bool physics:kinematicEnabled = ${k==="static"||k==="kinematic"}
302
325
  bool physics:collisionEnabled = true
303
- `}if(l.timeSamples&&l.timeSamples.times.length>0){let E=l.timeSamples,b=E.times.map((C,h)=>{let w=E.translations?.[h]||[0,0,0];return`${X(C)}: (${X(w[0])}, ${X(w[1])}, ${X(w[2])})`}).join(", "),F=E.times.map((C,h)=>{let w=E.rotations?.[h]||[0,0,0,1];return`${X(C)}: (${X(w[3])}, ${X(w[0])}, ${X(w[1])}, ${X(w[2])})`}).join(", "),L=E.times.map((C,h)=>{let w=E.scales?.[h]||[1,1,1];return`${X(C)}: (${X(w[0])}, ${X(w[1])}, ${X(w[2])})`}).join(", ");a+=`double3 xformOp:translate.timeSamples = { ${b} }
326
+ `,_?.mass>0&&Number.isFinite(_.mass)&&(y+=`float physics:mass = ${de(_.mass)}
327
+ `)}let F=Et(u),U=F?`def SpatialAudio "AudioEmitter"
328
+ {
329
+ ${F.src?`asset inputs:file = @${Ie(F.src)}@
330
+ `:""}uniform token inputs:auralMode = "${F.isGlobal?"nonSpatial":"spatial"}"
331
+ uniform token inputs:playbackMode = "${F.loop?"loopFromStart":"onceFromStart"}"
332
+ double gain = ${de(F.volume)}
333
+ }
334
+ `:"";return{header:w,body:y,tail:U}},d=u=>{if(u.timeSamples&&u.timeSamples.times.length>0){let h=u.timeSamples,w=(_,k,P)=>h.times.map((N,S)=>`${de(N)}: ${P(_?.[S]||k)}`).join(", "),y=w(h.translations,[0,0,0],_=>xe(_[0],_[1],_[2])),F=w(h.rotations,[0,0,0,1],_=>{let k=Math.hypot(_[0],_[1],_[2],_[3])||1;return _e(_[3]/k,_[0]/k,_[1]/k,_[2]/k)}),U=w(h.scales,[1,1,1],_=>xe(_[0],_[1],_[2]));return`double3 xformOp:translate.timeSamples = { ${y} }
304
335
  quatf xformOp:orient.timeSamples = { ${F} }
305
- double3 xformOp:scale.timeSamples = { ${L} }
336
+ double3 xformOp:scale.timeSamples = { ${U} }
306
337
  uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
307
- `}a+=`float3[] extent = [(${X(d)}, ${X(f)}, ${X(T)}), (${X(g)}, ${X(m)}, ${X(p)})]
308
- int[] faceVertexCounts = [${D}]
309
- int[] faceVertexIndices = [${Ot(l.indices)}]
310
- point3f[] points = [${pt(l.positions)}]
311
- `,l.normals&&l.normals.length===l.positions.length&&(a+=`normal3f[] normals = [${pt(l.normals)}] (
338
+ `}let x=[],C="",R=u.translation;R&&(Math.abs(R[0])>1e-7||Math.abs(R[1])>1e-7||Math.abs(R[2])>1e-7)&&(C+=`double3 xformOp:translate = ${xe(R[0],R[1],R[2])}
339
+ `,x.push('"xformOp:translate"'));let T=u.rotation;if(T){let h=Math.hypot(T[0],T[1],T[2],T[3])||1,w=T[0]/h,y=T[1]/h,F=T[2]/h,U=T[3]/h;(1-Math.abs(U)>1e-7||Math.hypot(w,y,F)>1e-7)&&(C+=`quatf xformOp:orient = ${_e(U,w,y,F)}
340
+ `,x.push('"xformOp:orient"'))}let m=u.scale;return m&&(Math.abs(m[0]-1)>1e-7||Math.abs(m[1]-1)>1e-7||Math.abs(m[2]-1)>1e-7)&&(C+=`float3 xformOp:scale = ${xe(m[0],m[1],m[2])}
341
+ `,x.push('"xformOp:scale"')),x.length>0&&(C+=`uniform token[] xformOpOrder = [${x.join(", ")}]
342
+ `),C},v=u=>{let x=u.positions.length/3,C=1/0,R=1/0,T=1/0,m=-1/0,h=-1/0,w=-1/0;for(let k=0;k<x;k++){let P=u.positions[k*3],N=u.positions[k*3+1],S=u.positions[k*3+2];P<C&&(C=P),P>m&&(m=P),N<R&&(R=N),N>h&&(h=N),S<T&&(T=S),S>w&&(w=S)}isFinite(C)||(C=R=T=-1,m=h=w=1);let y=Math.floor(u.indices.length/3),F=Ue(u.materialName,"DefaultMaterial"),U=y>0?y===1?"3":"3, ".repeat(y-1)+"3":"",_=`float3[] extent = [${xe(C,R,T)}, ${xe(m,h,w)}]
343
+ int[] faceVertexCounts = [${U}]
344
+ int[] faceVertexIndices = [${nn(u.indices)}]
345
+ point3f[] points = [${wt(u.positions)}]
346
+ `;return u.normals&&u.normals.length===u.positions.length&&(_+=`normal3f[] normals = [${wt(u.normals)}] (
312
347
  interpolation = "vertex"
313
348
  )
314
- `),l.uvs&&l.uvs.length===u*2&&(a+=`texCoord2f[] primvars:st = [${Vt(l.uvs,u)}] (
349
+ `),u.uvs&&u.uvs.length===x*2&&(_+=`texCoord2f[] primvars:st = [${tn(u.uvs,x)}] (
315
350
  interpolation = "vertex"
316
351
  )
317
- `),a+=`rel material:binding = </Root/Materials/${A}>
318
- }
319
- `}return a+=`}
352
+ `),_+=`rel material:binding = </Root/Materials/${F}>
353
+ `,_},M=new Set,I=[];for(let u=e.length-1;u>=0;u--)I.push({node:e[u],siblings:M});let D=0;for(;I.length>0;){let u=I.pop();if(u.close){l+=`}
354
+ `;continue}let{node:x,siblings:C}=u,R=!!(x.isXform||x.positions.length===0),T=Rt(C,Ue(x.name,R?`Group_${D}`:`Mesh_${D}`));D++;let m=x.children||[];if(R){let h=g(x.xrTraits,!1,x.invisible);l+=`def Xform "${T}"${h.header}
355
+ {
356
+ ${h.body}${d(x)}${h.tail}`,I.push({close:!0});let w=new Set;for(let y=m.length-1;y>=0;y--)I.push({node:m[y],siblings:w})}else if(m.length>0){let h=g(x.xrTraits,!1,x.invisible),w=`${T}_mesh`;l+=`def Xform "${T}"${h.header}
357
+ {
358
+ ${h.body}${d(x)}${h.tail}`,l+=`def Mesh "${w}" (
359
+ prepend apiSchemas = ["MaterialBindingAPI"]
360
+ )
361
+ {
362
+ ${v(x)}}
363
+ `,I.push({close:!0});let y=new Set([w]);for(let F=m.length-1;F>=0;F--)I.push({node:m[F],siblings:y})}else{let h=g(x.xrTraits,!0,x.invisible);l+=`def Mesh "${T}"${h.header}
364
+ {
365
+ ${h.body}${d(x)}${v(x)}${h.tail}}
366
+ `}}return l+=`}
320
367
  }
321
- `,a}function ze(n,e){if(n&&typeof n.traverse=="function"){let i=Bt(n,e);return Oe(i)}let t=xe(n),r=bt(t);return Oe(r)}var Le=null;function He(n){if(!Le){Le=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;Le[t]=r}}let e=4294967295;for(let t=0;t<n.length;t++)e=Le[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Se(n){let e=[],t=0,r=[];for(let u of n){let d=Ge(u.filename),f=He(u.data),T=u.data.length,g=30+d.length,m=t+g,p=0,R=m%64;R!==0&&(p=64-R);let A=new Uint8Array(g+p),v=new DataView(A.buffer);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint16(6,0,!0),v.setUint16(8,0,!0),v.setUint16(10,0,!0),v.setUint16(12,0,!0),v.setUint32(14,f,!0),v.setUint32(18,T,!0),v.setUint32(22,T,!0),v.setUint16(26,d.length,!0),v.setUint16(28,p,!0),A.set(d,30),p>0&&A.fill(0,30+d.length),e.push({offset:t,size:T,crc:f,filenameBytes:d,entry:u}),r.push(A),r.push(u.data),t+=A.length+u.data.length}let i=t;for(let u of e){let d=new Uint8Array(46+u.filenameBytes.length),f=new DataView(d.buffer);f.setUint32(0,33639248,!0),f.setUint16(4,20,!0),f.setUint16(6,20,!0),f.setUint16(8,0,!0),f.setUint16(10,0,!0),f.setUint16(12,0,!0),f.setUint16(14,0,!0),f.setUint32(16,u.crc,!0),f.setUint32(20,u.size,!0),f.setUint32(24,u.size,!0),f.setUint16(28,u.filenameBytes.length,!0),f.setUint16(30,0,!0),f.setUint16(32,0,!0),f.setUint16(34,0,!0),f.setUint16(36,0,!0),f.setUint32(38,0,!0),f.setUint32(42,u.offset,!0),d.set(u.filenameBytes,46),r.push(d),t+=d.length}let s=t-i,a=new Uint8Array(22),c=new DataView(a.buffer);c.setUint32(0,101010256,!0),c.setUint16(4,0,!0),c.setUint16(6,0,!0),c.setUint16(8,e.length,!0),c.setUint16(10,e.length,!0),c.setUint32(12,s,!0),c.setUint32(16,i,!0),c.setUint16(20,0,!0),r.push(a),t+=22;let o=new Uint8Array(t),l=0;for(let u of r)o.set(u,l),l+=u.length;return o}function Gt(n){let e=ze(n),t=Ge(e);return Se([{filename:"model.usda",data:t}])}function We(n){let e=xe(n),t=bt(e),r=Oe(t),i=Ge(r);return Se([{filename:"model.usda",data:i}])}function Xe(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?Gt(n):We(n)}function $e(n){let e=Xe(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}function Ye(){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 Ke(){if(typeof navigator>"u")return!1;let n=navigator.userAgent||"";return/android/i.test(n)}async function Ze(){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 Ht(){let n=[];return await Ze()&&n.push("webxr"),Ye()&&n.push("quick-look"),Ke()&&n.push("scene-viewer"),n}async function Wt(){return(await je()).bestMode}async function je(){let[n,e,t]=await Promise.all([Ze(),Promise.resolve(Ye()),Promise.resolve(Ke())]),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 qe(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=Xt(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 c=Pe(e.canonicalWebPageUrl,!1);c&&i.push(`canonicalWebPageURL=${encodeURIComponent(c)}`)}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 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 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 Xt(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 gt(n,e={}){let t=Pe(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",Pe(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 xt(n,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let t=gt(n,e);window.location.href=t}var de=null;function $t(n,e){let r=new Float32Array(144),i=new Float32Array(144),s=new Float32Array(96),a=new Uint16Array(144);for(let d=0;d<24;d++){let f=d/24*Math.PI*2,T=Math.cos(f),g=Math.sin(f),m=d*2,p=m+1,R=(d+1)%24*2;r[m*3]=T*.11,r[m*3+1]=.002,r[m*3+2]=g*.11,r[p*3]=T*.145,r[p*3+1]=.002,r[p*3+2]=g*.145,i[m*3+1]=i[p*3+1]=1,a.set([m,R,p,p,R,R+1],d*6)}let c=n.createVertexArray();n.bindVertexArray(c);let o=(d,f,T)=>{let g=n.createBuffer();return n.bindBuffer(34962,g),n.bufferData(34962,d,35044),n.enableVertexAttribArray(f),n.vertexAttribPointer(f,T,5126,!1,0,0),g},l=[o(r,0,3),o(i,1,3),o(s,2,2)],u=n.createBuffer();return l.push(u),n.bindBuffer(34963,u),n.bufferData(34963,a,35044),n.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:c,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:l}]}}function yt(n,e,t,r,i){let s=Math.cos(r),a=Math.sin(r),c=Math.max(.01,i);n.fill(0),n[0]=c*s,n[2]=-c*a,n[5]=c,n[8]=c*a,n[10]=c*s,n[12]=e[0]-c*(s*t[0]+a*t[2]),n[13]=e[1]-c*t[1],n[14]=e[2]-c*(-a*t[0]+s*t[2]),n[15]=1}var De=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.");de&&de!==this&&de.isSessionActive()&&await de.stop().catch(()=>{});let r=navigator.xr,i=this.opts,s=t||e?.container,a=String(s?.tagName||"").toLowerCase()==="xr-live",c=e?.bounds,o=Number(c?.radius)||1,l=Array.isArray(c?.center)?c.center:[0,0,0],u=Array.isArray(c?.min)?c.min:[-.5,-.5,-.5],d=typeof navigator<"u"&&navigator.userAgent||"",f=/Android|iPhone|iPad|iPod/i.test(d)&&!/Quest|Oculus|Pico|Vision/i.test(d),T=a?i.arScale==="fixed"?1:f?.55:1:i.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,g=a?[0,-.25,0]:[l[0]||0,i.arPlacement==="wall"?l[1]:u[1]??0,l[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,R=!1,A=null,v=()=>{R&&p?.parentNode&&p.parentNode.removeChild(p),p=null,A=null,R=!1};if(m==="immersive-ar"){if(p)p.addEventListener?.("beforexrselect",x=>x.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let x=document.createElement("div");x.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 I=document.createElement("button");I.type="button",I.textContent="\u2715 Exit AR",I.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",I.addEventListener("beforexrselect",N=>N.preventDefault()),I.addEventListener("click",N=>{N.stopPropagation(),this.stop().catch(()=>{})}),A=document.createElement("div"),A.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",A.textContent="Move phone to detect a surface \u2022 Tap to place",x.appendChild(I),x.appendChild(A),document.body.appendChild(x),p=x,R=!0}}let D=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),y={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(D)};p&&(D.add("dom-overlay"),y.optionalFeatures=Array.from(D),y.domOverlay={root:p});for(let x of ae)x.onConfigureXRSessionInit?.(s,y);Array.isArray(y.optionalFeatures)&&y.optionalFeatures.includes("dom-overlay")&&!y.domOverlay?.root&&(y.optionalFeatures=y.optionalFeatures.filter(x=>x!=="dom-overlay"));let P=x=>{let I=String(x?.name||"");return I==="NotAllowedError"||I==="SecurityError"};try{this.s=await r.requestSession(m,y)}catch(x){if(v(),P(x))throw i.onError?.(x),x;try{this.s=await r.requestSession(m,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(I){if(P(I))throw i.onError?.(I),I;try{this.s=await r.requestSession(m)}catch(N){throw i.onError?.(N),N}}}let E=this.s;de=this,this.placed=!1;let b=null,F=null,L=null,C=null,h=null,w=[0,-.25,-1.2],S=[0,-.25,-1.2],M=new Float32Array(16),k=new Float32Array(16),_=!1,K=1,U=0,O=!1,B=null,q=null,Y=0,W=null,j=()=>{de===this&&(de=null),W?.(),W=null;try{F?.cancel?.()}catch{}if(F=null,L){let x=e?.meshes;if(Array.isArray(x)){let N=x.indexOf(L);N!==-1&&x.splice(N,1)}let I=e.getGLContext?.()||e?.gl;if(I)for(let N of L.primitives||[]){I.deleteVertexArray?.(N.vao);for(let z of N.buffers||[])I.deleteBuffer?.(z)}L=null}e?.setXRSessionActive?.(!1),v(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=j,E.addEventListener("end",()=>{j(),i.onExit?.()}),E.addEventListener("select",()=>{if(!this.placed){let x=h||w;S=[x[0],x[1],x[2]],yt(this.placedMat,S,g,U,T*K),this.placed=!0,L&&(L.visible=!1),A&&(A.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let x=e.getGLContext?.()||e?.gl;x&&typeof x.makeXRCompatible=="function"&&await x.makeXRCompatible();let I=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;x&&typeof I=="function"&&typeof E.updateRenderState=="function"&&E.updateRenderState({baseLayer:new I(E,x,{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&&(F=await E.requestHitTestSource({space:N}).catch(()=>null)),m==="immersive-ar"&&x&&typeof x.createVertexArray=="function"&&Array.isArray(e.meshes)&&(L=$t(x,i.reticleColor),e.meshes.push(L)),typeof window<"u"&&typeof window.addEventListener=="function"){let ee=G=>Math.hypot(G.touches[1].clientX-G.touches[0].clientX,G.touches[1].clientY-G.touches[0].clientY),ie=G=>Math.atan2(G.touches[1].clientY-G.touches[0].clientY,G.touches[1].clientX-G.touches[0].clientX),oe=G=>{this.s&&(G.touches.length===1&&this.placed?O=!0:G.touches.length>=2&&(O=!1,B=ee(G),q=ie(G)))},H=G=>{if(!this.s||G.touches.length<2)return;let te=ee(G),V=ie(G);if(B&&B>4&&i.arScale!=="fixed"&&(K=Math.max(.15,Math.min(6,K*(te/B)))),q!==null){let J=V-q;J>Math.PI&&(J-=Math.PI*2),J<-Math.PI&&(J+=Math.PI*2),U-=J}B=te,q=V},$=G=>{(!G.touches||G.touches.length===0)&&(O=!1),(!G.touches||G.touches.length<2)&&(B=null,q=null)};window.addEventListener("touchstart",oe,{passive:!0}),window.addEventListener("touchmove",H,{passive:!0}),window.addEventListener("touchend",$,{passive:!0}),window.addEventListener("touchcancel",$,{passive:!0}),W=()=>{window.removeEventListener("touchstart",oe),window.removeEventListener("touchmove",H),window.removeEventListener("touchend",$),window.removeEventListener("touchcancel",$)}}e.setXRSessionActive?.(!0);let z=(ee,ie)=>{if(this.s!==E)return;E.requestAnimationFrame(z);let oe=Y>0?Math.min(Math.max((ee-Y)/1e3,0),.1):1/60;Y=ee,e?.stepXRUpdate?.(oe);let H=ie.getViewerPose(b);if(!H)return;let $=H.views?.[0];if(!_&&$?.transform){let Z=$.transform.position,ne=$.transform.matrix,le=Z?.x??(ne?ne[12]:0),ce=Z?.y??(ne?ne[13]:0),ue=Z?.z??(ne?ne[14]:0),fe=ne?-ne[8]:0,be=ne?-ne[10]:-1,Fe=Math.hypot(fe,be);Fe>1e-4?(fe/=Fe,be/=Fe):(fe=0,be=-1),w=[le+fe*1.2,ce-.25,ue+be*1.2],U=Math.atan2(-fe,-be),_=!0}if(F&&typeof ie.getHitTestResults=="function"&&(!this.placed||O)){let Z=ie.getHitTestResults(F)||[],ne=!1;for(let le of Z){let ce=le.getPose(b);if(ce?.transform?.matrix){let ue=ce.transform.matrix,fe=ue[5];if(i.arPlacement==="wall"&&Math.abs(fe)>.35||i.arPlacement==="floor"&&Math.abs(fe)<.65)continue;C||(C=new Float32Array(16)),C.set(ue),h=[ue[12],ue[13],ue[14]],this.placed&&O&&(S=[ue[12],ue[13],ue[14]]),L&&(L.visible=!this.placed||O,L.transform.set(ue)),!this.placed&&A&&(A.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(C),ne=!0;break}}!ne&&L&&(L.visible=!1)}yt(M,this.placed?S:h||w,g,U,T*K),this.placed&&this.placedMat.set(M);let G=e.xrRigMatrix;G instanceof Float32Array&&G.length===16?se(k,G,M):k.set(M),e.modelRootMatrix&&e.modelRootMatrix.set(k);for(let Z of ae)Z.onXRFrame?.(e,E,ie,b);let te=e.getGLContext?.()||e?.gl,V=E.renderState?.baseLayer;te&&V&&V.framebuffer!==void 0&&te.bindFramebuffer(36160,V.framebuffer);let J=m==="immersive-ar",Q=H.views||[];for(let Z=0;Z<Q.length;Z++){let ne=Q[Z];if(typeof e.renderXRView=="function"){let le;if(V&&typeof V.getViewport=="function"){let ce=V.getViewport(ne);ce&&ce.width>0&&ce.height>0&&(le=[ce.x,ce.y,ce.width,ce.height])}else V?.framebufferWidth>0&&V?.framebufferHeight>0&&(le=[0,0,V.framebufferWidth,V.framebufferHeight]);e.renderXRView(ne,k,this.placed,le,J,Z)}}te&&V&&V.framebuffer&&te.bindFramebuffer(36160,null)};E.requestAnimationFrame(z)}catch(x){throw typeof E.end=="function"&&await E.end().catch(()=>{}),j(),i.onError?.(x),x}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function qt(n){let e=await je(),t=n.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let c of t)if(e.availableModes.includes(c)){r=c;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 c;if(n.model instanceof Blob&&n.model.type==="model/vnd.usdz+zip")c=n.model;else{if(typeof n.model=="string")return qe(n.model,i),{mode:"quick-look",success:!0};c=$e(n.model)}return qe(c,i),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let c=n.glbUrl||(typeof n.model=="string"?n.model:null);if(!c)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return xt(c,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!n.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let c=new De(a);return await c.start(n.view,n.element),{mode:"webxr",success:!0,session:c}}}catch(c){return{mode:r,success:!1,error:c}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}
368
+ `,l}function Dt(e,t){if(e&&typeof e.traverse=="function"){let a=en(e,t);return qe(a)}let i=Se(e),r=Ke(i);return qe(r)}var ke=null;function Ye(e){if(!ke){ke=new Uint32Array(256);for(let i=0;i<256;i++){let r=i;for(let a=0;a<8;a++)r=r&1?3988292384^r>>>1:r>>>1;ke[i]=r}}let t=4294967295;for(let i=0;i<e.length;i++)t=ke[(t^e[i])&255]^t>>>8;return(t^4294967295)>>>0}function Ze(e){let t=[],i=0,r=[];for(let v of e){let M=Lt(v.filename),I=Ye(v.data),D=v.data.length,u=30+M.length,x=(i+u)%64,C=x!==0?64-x:0;C>0&&C<4&&(C+=64);let R=new Uint8Array(u+C),T=new DataView(R.buffer);T.setUint32(0,67324752,!0),T.setUint16(4,20,!0),T.setUint32(14,I,!0),T.setUint32(18,D,!0),T.setUint32(22,D,!0),T.setUint16(26,M.length,!0),T.setUint16(28,C,!0),R.set(M,30),C>=4&&(T.setUint16(u,6534,!0),T.setUint16(u+2,C-4,!0)),t.push({offset:i,size:D,crc:I,filenameBytes:M,entry:v}),r.push(R,v.data),i+=R.length+v.data.length}let a=i;for(let v of t){let M=new Uint8Array(46+v.filenameBytes.length),I=new DataView(M.buffer);I.setUint32(0,33639248,!0),I.setUint16(4,20,!0),I.setUint16(6,20,!0),I.setUint32(16,v.crc,!0),I.setUint32(20,v.size,!0),I.setUint32(24,v.size,!0),I.setUint16(28,v.filenameBytes.length,!0),I.setUint32(42,v.offset,!0),M.set(v.filenameBytes,46),r.push(M),i+=M.length}let s=i-a,c=new Uint8Array(22),l=new DataView(c.buffer);l.setUint32(0,101010256,!0),l.setUint16(8,t.length,!0),l.setUint16(10,t.length,!0),l.setUint32(12,s,!0),l.setUint32(16,a,!0),r.push(c),i+=22;let g=new Uint8Array(i),d=0;for(let v of r)g.set(v,d),d+=v.length;return g}function rn(e){let t=[{filename:"model.usda",data:Lt(qe(e))}],i=new Set(["model.usda"]),r=[...e];for(;r.length>0;){let a=r.pop();for(let s of a.textures||[])s?.file&&s.data?.byteLength&&!i.has(s.file)&&(i.add(s.file),t.push({filename:s.file,data:s.data}));if(a.children)for(let s=a.children.length-1;s>=0;s--)r.push(a.children[s])}return Ze(t)}function Qe(e){return rn(Ke(Se(e)))}function Je(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():Qe(e)}function et(e){let t=Je(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function nt(){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function rt(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function it(){if(typeof navigator>"u")return!1;let e=navigator;if(!e.xr||typeof e.xr.isSessionSupported!="function")return!1;try{return await e.xr.isSessionSupported("immersive-ar")?!0:await e.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function on(){let e=[];return await it()&&e.push("webxr"),nt()&&e.push("quick-look"),rt()&&e.push("scene-viewer"),e}async function an(){return(await st()).bestMode}async function st(){let[e,t,i]=await Promise.all([it(),Promise.resolve(nt()),Promise.resolve(rt())]),r=[];t&&r.push("quick-look"),e&&r.push("webxr"),i&&r.push("scene-viewer");let a=null;return t?a="quick-look":e?a="webxr":i&&(a="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:i,availableModes:r,bestMode:a}}function tt(e,t={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let i,r=!1;if(typeof e=="string"){if(i=un(e),!i)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else i=URL.createObjectURL(e),r=!0;let a=[];if(t.allowScale===!1&&a.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let l=Ne(t.canonicalWebPageUrl,!1);l&&a.push(`canonicalWebPageURL=${encodeURIComponent(l)}`)}t.checkoutTitle&&a.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&a.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&a.push(`price=${encodeURIComponent(t.price)}`),a.length>0&&(i+=`#${a.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",i);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),r&&URL.revokeObjectURL(i.split("#")[0])},3e3)}function Ne(e,t=!1){if(typeof e!="string")return"";let i=e.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!i)return"";if(/^[\\/]{2}/.test(i))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${i.slice(0,32)}`);let r=i.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||t&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(i))return i;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${i.slice(0,32)}`)}function un(e){try{return Ne(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function Ct(e,t={}){let i=Ne(e,!0),r=t.mode||"ar_preferred",a=new URLSearchParams({file:i,mode:r,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&a.set("title",t.title),t.link&&a.set("link",Ne(t.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${a.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function Ft(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let i=Ct(e,t);window.location.href=i}var Ae=null;function cn(e,t){let i=new Float32Array(144),r=new Float32Array(144),a=new Float32Array(96),s=new Uint16Array(144);for(let v=0;v<24;v++){let M=v/24*Math.PI*2,I=Math.cos(M),D=Math.sin(M),u=v*2,x=u+1,C=(v+1)%24*2;i[u*3]=I*.11,i[u*3+1]=.002,i[u*3+2]=D*.11,i[x*3]=I*.145,i[x*3+1]=.002,i[x*3+2]=D*.145,r[u*3+1]=r[x*3+1]=1,s.set([u,C,x,x,C,C+1],v*6)}let c=e.createVertexArray();e.bindVertexArray(c);let l=(v,M,I)=>{let D=e.createBuffer();return e.bindBuffer(34962,D),e.bufferData(34962,v,35044),e.enableVertexAttribArray(M),e.vertexAttribPointer(M,I,5126,!1,0,0),D},g=[l(i,0,3),l(r,1,3),l(a,2,2)],d=e.createBuffer();return g.push(d),e.bindBuffer(34963,d),e.bufferData(34963,s,35044),e.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:c,indexCount:s.length,indexType:5123,baseColor:t&&t.length>=3?[t[0],t[1],t[2],t[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:i,indices:s,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:g}]}}function Pt(e,t,i,r,a){let s=Math.cos(r),c=Math.sin(r),l=Math.max(.01,a);e.fill(0),e[0]=l*s,e[2]=-l*c,e[5]=l,e[8]=l*c,e[10]=l*s,e[12]=t[0]-l*(s*i[0]+c*i[2]),e[13]=t[1]-l*i[1],e[14]=t[2]-l*(-c*i[0]+s*i[2]),e[15]=1}var Be=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.");Ae&&Ae!==this&&Ae.isSessionActive()&&await Ae.stop().catch(()=>{});let i=navigator.xr,r=this.opts,a=t||e?.container,s=String(a?.tagName||"").toLowerCase()==="xr-live",c=e?.bounds,l=Number(c?.radius)||1,g=Array.isArray(c?.center)?c.center:[0,0,0],d=Array.isArray(c?.min)?c.min:[-.5,-.5,-.5],v=typeof navigator<"u"&&navigator.userAgent||"",M=/Android|iPhone|iPad|iPod/i.test(v)&&!/Quest|Oculus|Pico|Vision/i.test(v),I=s?r.arScale==="fixed"?1:M?.55:1:r.arScale==="fixed"?1:l>.45?.3/l:l<.05?.12/Math.max(l,.001):1,D=s?[0,-.25,0]:[g[0]||0,r.arPlacement==="wall"?g[1]:d[1]??0,g[2]||0],u="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(u="immersive-vr")}catch{u="immersive-vr"}let x=a?.querySelector?.('[slot="ar-overlay"]')||null,C=!1,R=null,T=()=>{C&&x?.parentNode&&x.parentNode.removeChild(x),x=null,R=null,C=!1};if(u==="immersive-ar"){if(x)x.addEventListener?.("beforexrselect",L=>L.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let L=document.createElement("div");L.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let X=document.createElement("button");X.type="button",X.textContent="\u2715 Exit AR",X.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",X.addEventListener("beforexrselect",J=>J.preventDefault()),X.addEventListener("click",J=>{J.stopPropagation(),this.stop().catch(()=>{})}),R=document.createElement("div"),R.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",R.textContent="Move phone to detect a surface \u2022 Tap to place",L.appendChild(X),L.appendChild(R),document.body.appendChild(L),x=L,C=!0}}let m=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),h={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(m)};x&&(m.add("dom-overlay"),h.optionalFeatures=Array.from(m),h.domOverlay={root:x});for(let L of ce)L.onConfigureXRSessionInit?.(a,h);Array.isArray(h.optionalFeatures)&&h.optionalFeatures.includes("dom-overlay")&&!h.domOverlay?.root&&(h.optionalFeatures=h.optionalFeatures.filter(L=>L!=="dom-overlay"));let w=L=>{let X=String(L?.name||"");return X==="NotAllowedError"||X==="SecurityError"};try{this.s=await i.requestSession(u,h)}catch(L){if(T(),w(L))throw r.onError?.(L),L;try{this.s=await i.requestSession(u,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(X){if(w(X))throw r.onError?.(X),X;try{this.s=await i.requestSession(u)}catch(J){throw r.onError?.(J),J}}}let y=this.s;Ae=this,this.placed=!1;let F=null,U=null,_=null,k=null,P=null,N=[0,-.25,-1.2],S=[0,-.25,-1.2],o=new Float32Array(16),V=new Float32Array(16),K=!1,f=1,b=0,n=!1,p=null,B=null,z=0,j=null,ee=()=>{Ae===this&&(Ae=null),j?.(),j=null;try{U?.cancel?.()}catch{}if(U=null,_){let L=e?.meshes;if(Array.isArray(L)){let J=L.indexOf(_);J!==-1&&L.splice(J,1)}let X=e.getGLContext?.()||e?.gl;if(X)for(let J of _.primitives||[]){X.deleteVertexArray?.(J.vao);for(let re of J.buffers||[])X.deleteBuffer?.(re)}_=null}e?.setXRSessionActive?.(!1),T(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=ee,y.addEventListener("end",()=>{ee(),r.onExit?.()}),y.addEventListener("select",()=>{if(!this.placed){let L=P||N;S=[L[0],L[1],L[2]],Pt(this.placedMat,S,D,b,I*f),this.placed=!0,_&&(_.visible=!1),R&&(R.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let L=e.getGLContext?.()||e?.gl;L&&typeof L.makeXRCompatible=="function"&&await L.makeXRCompatible();let X=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;L&&typeof X=="function"&&typeof y.updateRenderState=="function"&&y.updateRenderState({baseLayer:new X(y,L,{alpha:!0})});try{F=await y.requestReferenceSpace("local")}catch{try{F=await y.requestReferenceSpace("local-floor")}catch{F=await y.requestReferenceSpace("viewer")}}let J=await y.requestReferenceSpace("viewer").catch(()=>F);if(typeof y.requestHitTestSource=="function"&&J&&(U=await y.requestHitTestSource({space:J}).catch(()=>null)),u==="immersive-ar"&&L&&typeof L.createVertexArray=="function"&&Array.isArray(e.meshes)&&(_=cn(L,r.reticleColor),e.meshes.push(_)),typeof window<"u"&&typeof window.addEventListener=="function"){let $=A=>Math.hypot(A.touches[1].clientX-A.touches[0].clientX,A.touches[1].clientY-A.touches[0].clientY),te=A=>Math.atan2(A.touches[1].clientY-A.touches[0].clientY,A.touches[1].clientX-A.touches[0].clientX),O=A=>{this.s&&(A.touches.length===1&&this.placed?n=!0:A.touches.length>=2&&(n=!1,p=$(A),B=te(A)))},G=A=>{if(!this.s||A.touches.length<2)return;let E=$(A),H=te(A);if(p&&p>4&&r.arScale!=="fixed"&&(f=Math.max(.15,Math.min(6,f*(E/p)))),B!==null){let W=H-B;W>Math.PI&&(W-=Math.PI*2),W<-Math.PI&&(W+=Math.PI*2),b-=W}p=E,B=H},q=A=>{(!A.touches||A.touches.length===0)&&(n=!1),(!A.touches||A.touches.length<2)&&(p=null,B=null)};window.addEventListener("touchstart",O,{passive:!0}),window.addEventListener("touchmove",G,{passive:!0}),window.addEventListener("touchend",q,{passive:!0}),window.addEventListener("touchcancel",q,{passive:!0}),j=()=>{window.removeEventListener("touchstart",O),window.removeEventListener("touchmove",G),window.removeEventListener("touchend",q),window.removeEventListener("touchcancel",q)}}e.setXRSessionActive?.(!0);let re=($,te)=>{if(this.s!==y)return;y.requestAnimationFrame(re);let O=z>0?Math.min(Math.max(($-z)/1e3,0),.1):1/60;z=$,e?.stepXRUpdate?.(O);let G=te.getViewerPose(F);if(!G)return;let q=G.views?.[0];if(!K&&q?.transform){let Q=q.transform.position,Y=q.transform.matrix,ue=Q?.x??(Y?Y[12]:0),ie=Q?.y??(Y?Y[13]:0),ae=Q?.z??(Y?Y[14]:0),ne=Y?-Y[8]:0,oe=Y?-Y[10]:-1,me=Math.hypot(ne,oe);me>1e-4?(ne/=me,oe/=me):(ne=0,oe=-1),N=[ue+ne*1.2,ie-.25,ae+oe*1.2],b=Math.atan2(-ne,-oe),K=!0}if(U&&typeof te.getHitTestResults=="function"&&(!this.placed||n)){let Q=te.getHitTestResults(U)||[],Y=!1;for(let ue of Q){let ie=ue.getPose(F);if(ie?.transform?.matrix){let ae=ie.transform.matrix,ne=ae[5];if(r.arPlacement==="wall"&&Math.abs(ne)>.35||r.arPlacement==="floor"&&Math.abs(ne)<.65)continue;k||(k=new Float32Array(16)),k.set(ae),P=[ae[12],ae[13],ae[14]],this.placed&&n&&(S=[ae[12],ae[13],ae[14]]),_&&(_.visible=!this.placed||n,_.transform.set(ae)),!this.placed&&R&&(R.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(k),Y=!0;break}}!Y&&_&&(_.visible=!1)}Pt(o,this.placed?S:P||N,D,b,I*f),this.placed&&this.placedMat.set(o);let A=e.xrRigMatrix;A instanceof Float32Array&&A.length===16?fe(V,A,o):V.set(o),e.modelRootMatrix&&e.modelRootMatrix.set(V);for(let Q of ce)Q.onXRFrame?.(e,y,te,F);let E=e.getGLContext?.()||e?.gl,H=y.renderState?.baseLayer;E&&H&&H.framebuffer!==void 0&&E.bindFramebuffer(36160,H.framebuffer);let W=u==="immersive-ar",Z=G.views||[];for(let Q=0;Q<Z.length;Q++){let Y=Z[Q];if(typeof e.renderXRView=="function"){let ue;if(H&&typeof H.getViewport=="function"){let ie=H.getViewport(Y);ie&&ie.width>0&&ie.height>0&&(ue=[ie.x,ie.y,ie.width,ie.height])}else H?.framebufferWidth>0&&H?.framebufferHeight>0&&(ue=[0,0,H.framebufferWidth,H.framebufferHeight]);e.renderXRView(Y,V,this.placed,ue,W,Q)}}E&&H&&H.framebuffer&&E.bindFramebuffer(36160,null)};y.requestAnimationFrame(re)}catch(L){throw typeof y.end=="function"&&await y.end().catch(()=>{}),ee(),r.onError?.(L),L}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function ln(e){let t=await st(),i=e.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let l of i)if(t.availableModes.includes(l)){r=l;break}if(r||(r=t.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let a={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},s={...e.sceneViewerOptions,resizable:e.arScale==="fixed"?!1:e.sceneViewerOptions?.resizable,enableVerticalPlacement:e.arPlacement==="wall"?!0:e.sceneViewerOptions?.enableVerticalPlacement},c={...e.webXROptions,arScale:e.arScale||e.webXROptions?.arScale,arPlacement:e.arPlacement||e.webXROptions?.arPlacement};try{if(r==="quick-look"){let l;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")l=e.model;else{if(typeof e.model=="string")return tt(e.model,a),{mode:"quick-look",success:!0};l=et(e.model)}return tt(l,a),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let l=e.glbUrl||(typeof e.model=="string"?e.model:null);if(!l)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return Ft(l,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let l=new Be(c);return await l.start(e.view,e.element),{mode:"webxr",success:!0,session:l}}}catch(l){return{mode:r,success:!1,error:l}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}