three-live 0.0.1-alpha.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +58 -0
  3. package/dist/index.d.ts +224 -0
  4. package/dist/three-author-engine.js +297 -0
  5. package/dist/three-author.cjs +297 -0
  6. package/dist/three-author.d.ts +224 -0
  7. package/dist/three-author.js +297 -0
  8. package/dist/three-convert.cjs +291 -0
  9. package/dist/three-convert.d.ts +224 -0
  10. package/dist/three-convert.js +291 -0
  11. package/dist/three-live-animation.cjs +36 -0
  12. package/dist/three-live-animation.d.ts +224 -0
  13. package/dist/three-live-animation.js +36 -0
  14. package/dist/three-live-animation.min.js +36 -0
  15. package/dist/three-live-element.cjs +222 -0
  16. package/dist/three-live-element.d.ts +224 -0
  17. package/dist/three-live-element.js +222 -0
  18. package/dist/three-live-extras.cjs +42 -0
  19. package/dist/three-live-extras.d.ts +224 -0
  20. package/dist/three-live-extras.js +42 -0
  21. package/dist/three-live-extras.min.js +42 -0
  22. package/dist/three-live-full.cjs +341 -0
  23. package/dist/three-live-full.js +341 -0
  24. package/dist/three-live-full.min.js +341 -0
  25. package/dist/three-live-sandbox.html +157 -0
  26. package/dist/three-live-viewer.cjs +222 -0
  27. package/dist/three-live-viewer.d.ts +224 -0
  28. package/dist/three-live-viewer.js +222 -0
  29. package/dist/three-live-viewer.min.js +222 -0
  30. package/dist/three-live.cjs +299 -0
  31. package/dist/three-live.js +299 -0
  32. package/dist/three-live.min.js +299 -0
  33. package/dist/three-view.cjs +222 -0
  34. package/dist/three-view.d.ts +224 -0
  35. package/dist/three-view.js +222 -0
  36. package/dist/three-xr.cjs +291 -0
  37. package/dist/three-xr.d.ts +224 -0
  38. package/dist/three-xr.js +291 -0
  39. package/package.json +78 -6
  40. package/index.js +0 -1
@@ -0,0 +1,291 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ "use strict";var Ae=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var at=Object.getOwnPropertyNames;var ot=Object.prototype.hasOwnProperty;var ut=(n,e)=>{for(var t in e)Ae(n,t,{get:e[t],enumerable:!0})},ct=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of at(e))!ot.call(n,r)&&r!==t&&Ae(n,r,{get:()=>e[r],enumerable:!(i=st(e,r))||i.enumerable});return n};var lt=n=>ct(Ae({},"__esModule",{value:!0}),n);var Rt={};ut(Rt,{buildUSDZZip:()=>Le,calculateCRC32:()=>Ze,compileInteractivityGraph:()=>we,createUSDZBlob:()=>Mt,encodeUtf8:()=>fe,extractMeshesFromGLB:()=>Ce,extractMeshesFromScene:()=>qe,generateUSDA:()=>Ye,generateUSDAFromMeshes:()=>Re,generateUSDZ:()=>Qe,glbToUSDZ:()=>Je,sanitizeUsdIdentifier:()=>Me,sanitizeUsdStringLiteral:()=>Se,sceneToCanvas3D:()=>Ke,sceneToGLB:()=>vt,sceneToUSDZ:()=>je});module.exports=lt(Rt);function we(n,e,t){let i=[],r=new Map,s=[],l=[],y=[],c=new Map,o=f=>{let v=r.get(f);return v===void 0&&(v=i.length,i.push({op:f}),r.set(f,v)),v},a=f=>{let v=c.get(f);return v===void 0&&(v=y.length,y.push({id:f}),c.set(f,v)),v},h=(f,v={})=>s.push({declaration:o(f),...v})-1,T=(f,v,p)=>l.push({id:f,type:v,value:p})-1,M=f=>({node:f,socket:"value"}),m=t?.interactivity??t?.gltfExtensions?.KHR_interactivity;if(m&&typeof m=="object"){let f=Array.isArray(m.graphs)?m.graphs[m.graph??0]:m;if(f&&Array.isArray(f.nodes)){let v=Array.isArray(f.declarations)?f.declarations:[];for(let p of v)p?.op&&o(p.op);Array.isArray(f.variables)&&l.push(...f.variables);for(let p of f.events||[])p?.id&&a(p.id);for(let p of f.nodes){if(!p||typeof p!="object")continue;let D=p.op||(typeof p.declaration=="number"?v[p.declaration]?.op:"");s.push(D?{...p,declaration:o(D)}:{...p})}}}let P=(f,v,p="translation")=>p==="baseColorFactor"||p==="metallicFactor"||p==="roughnessFactor"?`/materials/${Math.max(0,v)}/pbrMetallicRoughness/${p}`:p==="emissiveFactor"||p==="alphaCutoff"?`/materials/${Math.max(0,v)}/${p}`:p==="visible"?`/nodes/${f}/extensions/KHR_node_visibility/visible`:`/nodes/${f}/${p}`,E=new Map;n.forEach((f,v)=>{typeof f?.name=="string"&&!E.has(f.name)&&E.set(f.name,v)});let S=(f,v)=>typeof f.target=="string"&&E.has(f.target)?E.get(f.target):typeof f.targetNode=="number"?f.targetNode:v,L=f=>{let v=n[f];return(typeof v?.mesh=="number"?e[v.mesh]?.primitives?.[0]?.material:0)??0};for(let f=0;f<n.length;f++){let v=n[f],p=v?.extras?.interactivity;if(!p||typeof p!="object")continue;let D=(typeof v.mesh=="number"?e[v.mesh]?.primitives?.[0]?.material:0)??0,u=b=>{let w=Array.isArray(b)?b:[b],F=[];for(let g=0;g<w.length;g++){let d=w[g];if(!d||typeof d!="object")continue;let U=d.action||"interpolate",A=typeof d.duration=="number"?d.duration:.35;if(U==="toggleTransform"){let O=d.property==="rotation"||d.property==="scale"?d.property:"translation",k=O==="rotation"?v.rotation||[0,0,0,1]:O==="scale"?v.scale||[1,1,1]:v.translation||[0,0,0],C=`/nodes/${f}/${O}`,_=T(`__toggle_${f}_${g}`,"bool",!1),R=h("variable/get",{configuration:{variable:_}}),V=h("math/not",{values:{a:M(R)}}),N=h("variable/set",{configuration:{variable:_},values:{value:M(V)}}),G=h("pointer/interpolate",{configuration:{pointer:C},values:{value:{value:Array.isArray(d.to)?d.to:k},duration:{value:A}}}),B=h("pointer/interpolate",{configuration:{pointer:C},values:{value:{value:Array.isArray(d.from)?d.from:k},duration:{value:A}}});s[N].flows={out:{node:h("flow/branch",{values:{condition:M(R)},flows:{true:{node:G},false:{node:B}}})}},F.push(N)}else if(U==="interpolate"){let O=d.to??d.value;if(O===void 0)continue;let k={value:{value:O},duration:{value:A}};d.from!==void 0&&(k.from={value:d.from}),F.push(h("pointer/interpolate",{configuration:{pointer:typeof d.pointer=="string"?d.pointer:P(S(d,f),L(S(d,f)),d.property)},values:k}))}else if(U==="setProperty"){if(d.value===void 0)continue;F.push(h("pointer/set",{configuration:{pointer:typeof d.pointer=="string"?d.pointer:P(S(d,f),L(S(d,f)),d.property)},values:{value:{value:d.value}}}))}else if(U==="toggleVisibility"){let O=S(d,f),k=T(`__vis_${O}_${g}`,"bool",!0),C=h("variable/get",{configuration:{variable:k}}),_=h("math/not",{values:{a:M(C)}}),R=h("variable/set",{configuration:{variable:k},values:{value:M(_)}});s[R].flows={out:{node:h("pointer/set",{configuration:{pointer:`/nodes/${O}/extensions/KHR_node_visibility/visible`},values:{value:M(C)}})}},F.push(R)}else if(U==="cycleMaterialColor"&&Array.isArray(d.colors)&&d.colors.length>0){let O=typeof d.duration=="number"?d.duration:.25,k=`/materials/${Math.max(0,D)}/pbrMetallicRoughness/baseColorFactor`,C=T(`__color_idx_${f}_${g}`,"int",0),_=h("variable/get",{configuration:{variable:C}}),R=h("math/add",{values:{a:M(_),b:{value:1}}}),V=h("math/rem",{values:{a:M(R),b:{value:d.colors.length}}}),N=h("variable/set",{configuration:{variable:C},values:{value:M(V)}}),G={};for(let B=0;B<d.colors.length;B++){let H=d.colors[B],W=Array.isArray(H)&&H.length>=3?[H[0],H[1],H[2],H[3]??1]:[1,1,1,1];G[String(B)]={node:O>0?h("pointer/interpolate",{configuration:{pointer:k},values:{value:{value:W},duration:{value:O}}}):h("pointer/set",{configuration:{pointer:k},values:{value:{value:W}}})}}s[N].flows={out:{node:h("flow/switch",{values:{selection:M(_)},flows:G})}},F.push(N)}else if(U==="playAnimation")F.push(h("animation/start",{configuration:{animation:d.animation??d.clip??0}}));else if(U==="stopAnimation")F.push(h("animation/stop"));else if(U==="sendEvent"){let O={};for(let[k,C]of Object.entries(d.values||{}))O[k]={value:C};F.push(h("event/send",{configuration:{event:a(String(d.event??d.id??"custom"))},values:O}))}}if(!F.length)return null;if(F.length===1)return F[0];let I={};return F.forEach((g,d)=>{I[String(d)]={node:g}}),h("flow/sequence",{flows:I})},x=(b,w,F)=>{let I=u(w);I!==null&&h(b,{...F?{configuration:F}:{},flows:{out:{node:I}}})};if(p.onSelect&&x("pointer/onSelect",p.onSelect,{nodeIndex:f}),p.onHoverIn&&x("pointer/onHoverIn",p.onHoverIn,{nodeIndex:f}),p.onHoverOut&&x("pointer/onHoverOut",p.onHoverOut,{nodeIndex:f}),p.onStart&&x("event/onStart",p.onStart),p.onReceive&&typeof p.onReceive=="object")for(let[b,w]of Object.entries(p.onReceive))x("event/receive",w,{event:a(b)})}return s.length?{graphs:[{declarations:i,nodes:s,variables:l,events:y}],graph:0}:null}var be="__THREE_LIVE_REGISTRY__";function ue(){let n=typeof globalThis<"u"?globalThis:{};if(!n[be]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,be,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[be]=e}}return n[be]}var q=ue().plugins;function Ie(n){let e=ue().plugins;e.some(t=>t.name===n.name)||e.push(n)}function _e(){return ue().plugins}function K(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function ge(n,e,t,i,r){let s=1/Math.tan(e/2);n.fill(0),n[0]=s/t,n[5]=s,n[11]=-1;let l=1/(i-r);return n[10]=(r+i)*l,n[14]=2*r*i*l,n}function ye(n,e,t,i){let[r,s,l]=e,[y,c,o]=i,[a,h,T]=t,M=r-a,m=s-h,P=l-T,E=Math.hypot(M,m,P);E<=1e-5?(M=0,m=0,P=1):(M/=E,m/=E,P/=E);let S=c*P-o*m,L=o*M-y*P,f=y*m-c*M;E=Math.hypot(S,L,f),E<=1e-5?(S=0,L=0,f=0):(S/=E,L/=E,f/=E);let v=m*f-P*L,p=P*S-M*f,D=M*L-m*S;return E=Math.hypot(v,p,D),E<=1e-5?(v=0,p=0,D=0):(v/=E,p/=E,D/=E),n[0]=S,n[1]=v,n[2]=M,n[3]=0,n[4]=L,n[5]=p,n[6]=m,n[7]=0,n[8]=f,n[9]=D,n[10]=P,n[11]=0,n[12]=-(S*r+L*s+f*l),n[13]=-(v*r+p*s+D*l),n[14]=-(M*r+m*s+P*l),n[15]=1,n}function J(n,e,t){let i=e[0],r=e[1],s=e[2],l=e[3],y=e[4],c=e[5],o=e[6],a=e[7],h=e[8],T=e[9],M=e[10],m=e[11],P=e[12],E=e[13],S=e[14],L=e[15],f=t[0],v=t[1],p=t[2],D=t[3];return n[0]=f*i+v*y+p*h+D*P,n[1]=f*r+v*c+p*T+D*E,n[2]=f*s+v*o+p*M+D*S,n[3]=f*l+v*a+p*m+D*L,f=t[4],v=t[5],p=t[6],D=t[7],n[4]=f*i+v*y+p*h+D*P,n[5]=f*r+v*c+p*T+D*E,n[6]=f*s+v*o+p*M+D*S,n[7]=f*l+v*a+p*m+D*L,f=t[8],v=t[9],p=t[10],D=t[11],n[8]=f*i+v*y+p*h+D*P,n[9]=f*r+v*c+p*T+D*E,n[10]=f*s+v*o+p*M+D*S,n[11]=f*l+v*a+p*m+D*L,f=t[12],v=t[13],p=t[14],D=t[15],n[12]=f*i+v*y+p*h+D*P,n[13]=f*r+v*c+p*T+D*E,n[14]=f*s+v*o+p*M+D*S,n[15]=f*l+v*a+p*m+D*L,n}function Ue(n,e,t,i){let r=e[0],s=e[1],l=e[2],y=e[3],c=r+r,o=s+s,a=l+l,h=r*c,T=r*o,M=r*a,m=s*o,P=s*a,E=l*a,S=y*c,L=y*o,f=y*a,v=i[0],p=i[1],D=i[2];return n[0]=(1-(m+E))*v,n[1]=(T+f)*v,n[2]=(M-L)*v,n[3]=0,n[4]=(T-f)*p,n[5]=(1-(h+E))*p,n[6]=(P+S)*p,n[7]=0,n[8]=(M+L)*D,n[9]=(P-S)*D,n[10]=(1-(h+m))*D,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function ne(n,e){let t=e[0],i=e[1],r=e[2],s=e[4],l=e[5],y=e[6],c=e[8],o=e[9],a=e[10],h=a*l-y*o,T=-a*s+y*c,M=o*s-l*c,m=t*h+i*T+r*M;return m&&(m=1/m,n[0]=h*m,n[1]=(-a*i+r*o)*m,n[2]=(y*i-r*l)*m,n[3]=T*m,n[4]=(a*t-r*c)*m,n[5]=(-y*t+r*s)*m,n[6]=M*m,n[7]=(-o*t+i*c)*m,n[8]=(l*t-i*s)*m),n}function Be(n,e){let t=e[0],i=e[1],r=e[2],s=e[3],l=e[4],y=e[5],c=e[6],o=e[7],a=e[8],h=e[9],T=e[10],M=e[11],m=e[12],P=e[13],E=e[14],S=e[15],L=t*y-i*l,f=t*c-r*l,v=t*o-s*l,p=i*c-r*y,D=i*o-s*y,u=r*o-s*c,x=a*P-h*m,b=a*E-T*m,w=a*S-M*m,F=h*E-T*P,I=h*S-M*P,g=T*S-M*E,d=L*g-f*I+v*F+p*w-D*b+u*x;return d?(d=1/d,n[0]=(y*g-c*I+o*F)*d,n[1]=(r*I-i*g-s*F)*d,n[2]=(P*u-E*D+S*p)*d,n[3]=(T*D-h*u-M*p)*d,n[4]=(c*w-l*g-o*b)*d,n[5]=(t*g-r*w+s*b)*d,n[6]=(E*v-m*u-S*f)*d,n[7]=(a*u-T*v+M*f)*d,n[8]=(l*I-y*w+o*x)*d,n[9]=(i*w-t*I-s*x)*d,n[10]=(m*D-P*v+S*L)*d,n[11]=(h*v-a*D-M*L)*d,n[12]=(y*b-l*F-c*x)*d,n[13]=(t*F-i*b+r*x)*d,n[14]=(P*f-m*p-E*L)*d,n[15]=(a*p-h*f+T*L)*d,n):null}function De(n,e,t,i,r){let s=r[0]*e+r[4]*t+r[8]*i+r[12],l=r[1]*e+r[5]*t+r[9]*i+r[13],y=r[2]*e+r[6]*t+r[10]*i+r[14],c=r[3]*e+r[7]*t+r[11]*i+r[15],o=c!==0?1/c:1;n[0]=s*o,n[1]=l*o,n[2]=y*o}function Ne(n,e,t,i,r,s,l,y,c,o,a,h,T,M,m,P,E=0){let S=o-l,L=a-y,f=h-c,v=T-l,p=M-y,D=m-c,u=r*D-s*p,x=s*v-i*D,b=i*p-r*v,w=S*u+L*x+f*b;if(w>-1e-7&&w<1e-7)return!1;let F=1/w,I=n-l,g=e-y,d=t-c,U=F*(I*u+g*x+d*b);if(U<-E||U>1+E)return!1;let A=g*f-d*L,O=d*S-I*f,k=I*L-g*S,C=F*(i*A+r*O+s*k);if(C<-E||U+C>1+E)return!1;let _=F*(v*A+p*O+D*k);if(_>1e-4&&_<P.distance){P.distance=_,P.point=[n+i*_,e+r*_,t+s*_];let R=L*D-f*p,V=f*v-S*D,N=S*p-L*v,G=Math.hypot(R,V,N)||1;return P.normal=[R/G,V/G,N/G],!0}return!1}function ve(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,i=[];for(let a=0;a<t;a++)i.push(K());if(t===0)return i;let r=new Set;for(let a of n.nodes)if(Array.isArray(a.children))for(let h of a.children)r.add(h);let s=new Set,l=128,y=(a,h,T=0)=>{if(T>l||a<0||a>=t||s.has(a))return;s.add(a);let M=n.nodes[a];if(!M)return;let m=K();if(e&&e[a])m.set(e[a]);else if(M.matrix&&M.matrix.length===16)m.set(M.matrix);else{let E=M.translation||[0,0,0],S=M.rotation||[0,0,0,1],L=M.scale||[1,1,1];Ue(m,S,E,L)}let P=i[a];if(h?J(P,h,m):P.set(m),Array.isArray(M.children))for(let E of M.children)typeof E=="number"&&y(E,P,T+1)},c=[],o=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(o&&Array.isArray(o.nodes))c.push(...o.nodes);else for(let a=0;a<t;a++)r.has(a)||c.push(a);for(let a of c)y(a,null);for(let a=0;a<t;a++)!r.has(a)&&!c.includes(a)&&y(a,null);return i}function ht(n){return new TextDecoder().decode(n)}var Ge=ue().decoders;function mt(n,e){Ge.set(n.toLowerCase(),e)}function he(n){return Ge.get(n.toLowerCase())}function Oe(n){let e=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,t=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let i=t.getUint32(0,!0);if(i!==1179937895){let T=t.getUint8(0);throw T===123||T===32||T===10||T===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${i.toString(16)}`)}let r=t.getUint32(4,!0);if(r!==2)throw new Error(`Unsupported GLB version: ${r}`);let s=t.getUint32(8,!0),l=12,y=null,c=null;for(;l+8<=s&&l+8<=e.byteLength;){let T=t.getUint32(l,!0),M=t.getUint32(l+4,!0),m=l+8;if(m+T>e.byteLength)throw new Error(`Truncated GLB chunk: required ${m+T} bytes, buffer has ${e.byteLength}`);if(M===1313821514){let P=new Uint8Array(e,m,T),E=ht(P);y=JSON.parse(E,(S,L)=>S==="__proto__"||S==="constructor"||S==="prototype"?void 0:L)}else M===5130562&&(c=e.slice(m,m+T));l=m+T}if(!y)throw new Error("Missing JSON chunk in GLB");let o=y.extensionsRequired||[];if(o.includes("KHR_draco_mesh_compression")&&!he("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(o.includes("EXT_meshopt_compression")&&!he("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(o.includes("KHR_texture_basisu")&&!he("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let a=c||new ArrayBuffer(0),h={gltf:y,bin:a,animations:[]};for(let T of q)T.onParseGLB?.(h);return h}function ft(n){return typeof n=="object"&&n!==null&&"gltf"in n&&typeof n.gltf=="object"&&n.gltf!==null&&"bin"in n&&(n.bin instanceof ArrayBuffer||ArrayBuffer.isView(n.bin))}function me(n){if(ft(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return Oe(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var He=`#version 300 es
18
+ layout(location=0) in vec3 aPosition;
19
+ layout(location=1) in vec3 aNormal;
20
+ layout(location=2) in vec2 aUV;
21
+ uniform mat4 uMVP,uModel;
22
+ uniform mat3 uNormalMatrix;
23
+ uniform vec4 uUvTransform;
24
+ out vec3 vNormal,vWorldPos;
25
+ out vec2 vUV;
26
+ void main(){
27
+ vec3 rawN=uNormalMatrix*aNormal;
28
+ vNormal=length(rawN)>1e-5?normalize(rawN):vec3(0.0);
29
+ vec4 world=uModel*vec4(aPosition,1.0);
30
+ vWorldPos=world.xyz;
31
+ vec2 scaleUV=uUvTransform.zw;
32
+ if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
33
+ vUV=aUV*scaleUV+uUvTransform.xy;
34
+ gl_Position=uMVP*vec4(aPosition,1.0);
35
+ }`,ze=`#version 300 es
36
+ precision highp float;
37
+ in vec3 vNormal,vWorldPos;
38
+ in vec2 vUV;
39
+ uniform vec4 uBaseColor;
40
+ uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity;
41
+ uniform vec2 uClearcoat;
42
+ uniform vec3 uCameraPos,uAmbientColor;
43
+ uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap,uXrDepthTex;
44
+ uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap,uXrDepthEnabled,uXrDepthFormat;
45
+ uniform float uNormalScale,uOcclusionStrength,uXrRawValueToMeters;
46
+ uniform mat4 uXrDepthUVTransform;
47
+ uniform vec2 uViewportSize;
48
+ uniform vec4 uViewport;
49
+ uniform vec3 uCameraFwd;
50
+ uniform int uToneMapping,uNumDirLights,uNumPointLights;
51
+ uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2];
52
+ out vec4 fragColor;
53
+
54
+ vec2 envBRDF(float r,float n){
55
+ vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04);
56
+ vec4 rv=r*c0+c1;
57
+ float a=min(rv.x*rv.x,exp2(-9.28*n))*rv.x+rv.y;
58
+ return vec2(-1.04,1.04)*a+rv.zw;
59
+ }
60
+
61
+ vec3 F_SchlickRoughness(vec3 F0,float r,float n){
62
+ return F0+(max(vec3(1.0-r),F0)-F0)*pow(clamp(1.0-n,0.0,1.0),5.0);
63
+ }
64
+
65
+ vec3 getStudioRadiance(vec3 R,float r){
66
+ vec3 kd=normalize(vec3(0.0,1.0,0.35));
67
+ float ki=pow(max(dot(R,kd),0.0),mix(96.0,1.5,r))*mix(2.4,0.5,r);
68
+ vec3 fd=normalize(vec3(-0.85,0.45,-0.35));
69
+ float fi=pow(max(dot(R,fd),0.0),mix(36.0,1.2,r))*mix(1.3,0.35,r);
70
+ float ri=pow(clamp(1.0-abs(R.y),0.0,1.0),3.5)*mix(0.55,0.22,r);
71
+ vec3 ag=mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5);
72
+ return ag+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
73
+ }
74
+
75
+ vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D normalMap,float scale){
76
+ vec3 mapNormal=texture(normalMap,uv).xyz*2.0-1.0;
77
+ mapNormal.xy*=scale;
78
+ vec3 dp1=dFdx(vWorldPos);
79
+ vec3 dp2=dFdy(vWorldPos);
80
+ vec2 duv1=dFdx(uv);
81
+ vec2 duv2=dFdy(uv);
82
+ vec3 dp2perp=cross(dp2,N);
83
+ vec3 dp1perp=cross(N,dp1);
84
+ vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;
85
+ vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;
86
+ float invmax=inversesqrt(max(dot(T,T),dot(B,B)));
87
+ return normalize(mat3(T*invmax,B*invmax,N)*normalize(mapNormal));
88
+ }
89
+
90
+ vec2 equirectangularUV(vec3 dir){
91
+ vec3 d=normalize(dir);
92
+ float u=atan(d.z,d.x)*0.15915494309+0.5;
93
+ float v=asin(clamp(d.y,-1.0,1.0))*0.31830988618+0.5;
94
+ return vec2(u,1.0-v);
95
+ }
96
+
97
+ vec3 neutralToneMapping(vec3 color){
98
+ const float startCompression=0.76;
99
+ const float desaturation=0.15;
100
+ float x=min(color.r,min(color.g,color.b));
101
+ float offset=x<0.08?x-6.25*x*x:0.04;
102
+ color-=offset;
103
+ float peak=max(color.r,max(color.g,color.b));
104
+ if(peak<startCompression)return color;
105
+ const float d=1.0-startCompression;
106
+ float newPeak=1.0-d*d/(peak+d-startCompression);
107
+ color*=newPeak/peak;
108
+ float g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);
109
+ return mix(color,newPeak*vec3(1.0),g);
110
+ }
111
+
112
+ vec3 applyToneMapping(vec3 color,int mode){
113
+ if(mode==0)return neutralToneMapping(color);
114
+ if(mode==1)return color/(color+vec3(1.0));
115
+ return color;
116
+ }
117
+
118
+ void main(){
119
+ vec4 base=uBaseColor;
120
+ if(uHasTexture==1)base*=texture(uBaseColorTexture,vUV);
121
+ if(length(vNormal)<1e-4&&uHasTexture==1){
122
+ vec3 unlit=base.rgb+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
123
+ fragColor=vec4(unlit,base.a);
124
+ return;
125
+ }
126
+ vec3 N=length(vNormal)<1e-4?normalize(cross(dFdx(vWorldPos),dFdy(vWorldPos))):normalize(vNormal);
127
+ if(!gl_FrontFacing)N=-N;
128
+ vec3 V=normalize(uCameraPos-vWorldPos);
129
+ if(uHasNormalTexture==1){
130
+ N=perturbNormal(N,V,vUV,uNormalTexture,uNormalScale);
131
+ }
132
+
133
+ float metallic=uMetallic;
134
+ float roughness=uRoughness;
135
+ if(uHasMetallicRoughnessTexture==1){
136
+ vec4 mr=texture(uMetallicRoughnessTexture,vUV);
137
+ roughness*=mr.g;
138
+ metallic*=mr.b;
139
+ }
140
+ roughness=clamp(roughness,0.04,1.0);
141
+ metallic=clamp(metallic,0.0,1.0);
142
+
143
+ float occ=1.0;
144
+ if(uHasOcclusionTexture==1){
145
+ occ=mix(1.0,texture(uOcclusionTexture,vUV).r,uOcclusionStrength);
146
+ }
147
+
148
+ float gloss=1.0-roughness;
149
+ float specExp=mix(16.0,256.0,gloss*gloss);
150
+ float specWeight=mix(0.22*gloss,1.0,metallic);
151
+ vec3 directLight=vec3(0.0);
152
+ for(int i=0;i<2;i++){
153
+ if(i>=uNumDirLights)break;
154
+ vec3 L=normalize(uDirLightDir[i]);
155
+ float NdotL=max(dot(N,L),0.0);
156
+ vec3 H=normalize(L+V);
157
+ float NoH=max(dot(N,H),0.0);
158
+ float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
159
+ directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uDirLightColor[i];
160
+ }
161
+ for(int i=0;i<2;i++){
162
+ if(i>=uNumPointLights)break;
163
+ vec3 toLight=uPointLightPos[i]-vWorldPos;
164
+ float dist=length(toLight);
165
+ vec3 L=toLight/max(dist,0.0001);
166
+ float atten=1.0/(1.0+0.09*dist+0.032*dist*dist);
167
+ float NdotL=max(dot(N,L),0.0);
168
+ vec3 H=normalize(L+V);
169
+ float NoH=max(dot(N,H),0.0);
170
+ float spec=pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35;
171
+ directLight+=(base.rgb*NdotL*0.75+vec3(spec))*uPointLightColor[i]*atten;
172
+ }
173
+
174
+ vec3 R=reflect(-V,N);
175
+ float NoV=clamp(dot(N,V),0.001,1.0);
176
+ vec3 F0=mix(vec3(0.04),base.rgb,metallic);
177
+ vec3 F=F_SchlickRoughness(F0,roughness,NoV);
178
+ vec2 brdf=envBRDF(roughness,NoV);
179
+
180
+ vec3 specularIBL;
181
+ vec3 envDiffuse;
182
+ if(uHasEnvironmentMap==1){
183
+ specularIBL=texture(uEnvironmentMap,equirectangularUV(R)).rgb*(F*brdf.x+brdf.y);
184
+ envDiffuse=texture(uEnvironmentMap,equirectangularUV(N)).rgb;
185
+ }else{
186
+ specularIBL=getStudioRadiance(R,roughness)*(F*brdf.x+brdf.y);
187
+ envDiffuse=mix(vec3(0.10,0.10,0.12),vec3(0.52,0.54,0.58),N.y*0.5+0.5);
188
+ }
189
+
190
+ vec3 kD=(vec3(1.0)-F)*(1.0-metallic);
191
+ vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
192
+ vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
193
+ if(uClearcoat.x>0.0){
194
+ vec3 ccF=F_SchlickRoughness(vec3(0.04),uClearcoat.y,NoV)*uClearcoat.x;
195
+ color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
196
+ }
197
+ color=applyToneMapping(color,uToneMapping);
198
+ float outAlpha=base.a;
199
+ if(uXrDepthEnabled==1){
200
+ vec2 normViewUV=vec2((gl_FragCoord.x-uViewport.x)/max(uViewport.z,1.0),1.0-(gl_FragCoord.y-uViewport.y)/max(uViewport.w,1.0));
201
+ vec2 depthUV=(uXrDepthUVTransform*vec4(normViewUV,0.0,1.0)).xy;
202
+ if(depthUV.x>=0.0&&depthUV.x<=1.0&&depthUV.y>=0.0&&depthUV.y<=1.0){
203
+ vec4 depthSample=texture(uXrDepthTex,depthUV);
204
+ float rawDepth=uXrDepthFormat==1?depthSample.r:(depthSample.r*255.0+depthSample.a*65280.0);
205
+ float realDepth=rawDepth*uXrRawValueToMeters;
206
+ float virtDepth=dot(uCameraFwd,uCameraFwd)>0.5?dot(vWorldPos-uCameraPos,uCameraFwd):length(uCameraPos-vWorldPos);
207
+ if(rawDepth>0.0&&(uXrDepthFormat==1||rawDepth<65500.0)&&realDepth>0.15&&realDepth<20.0&&virtDepth>realDepth+0.02){
208
+ float occAlpha=1.0-smoothstep(0.0,0.035,virtDepth-realDepth-0.02);
209
+ outAlpha*=occAlpha;
210
+ if(outAlpha<0.01)discard;
211
+ }
212
+ }
213
+ }
214
+ fragColor=vec4(color,outAlpha);
215
+ }`,dt=`#version 300 es
216
+ layout(location=0) in vec3 aPosition;
217
+ uniform mat4 uMVP;
218
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,pt=`#version 300 es
219
+ precision highp float;
220
+ uniform vec4 uColorId;
221
+ out vec4 fragColor;
222
+ void main(){fragColor=uColorId;}`;function Ve(n,e,t){let i=n.createShader(e);if(n.shaderSource(i,t),n.compileShader(i),!n.getShaderParameter(i,35713)){let r=n.getShaderInfoLog(i);throw n.deleteShader(i),new Error(`Shader compile error: ${r}`)}return i}function Pe(n,e,t){let i=Ve(n,35633,e),r=Ve(n,35632,t),s=n.createProgram();if(n.attachShader(s,i),n.attachShader(s,r),n.linkProgram(s),!n.getProgramParameter(s,35714)){let l=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${l}`)}return s}function Fe(n,e,t){let i={};for(let r of t)i[r]=n.getUniformLocation(e,r);return i}var Xe=["uMVP","uModel","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uXrDepthTex","uXrDepthEnabled","uXrDepthFormat","uXrRawValueToMeters","uXrDepthUVTransform","uViewportSize","uViewport","uCameraFwd"];function bt(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 Ee(n,e,t,i,r,s,l){if(i===void 0||!e.accessors?.[i])return null;let y=e.accessors[i],c=e.bufferViews[y.bufferView],o=(c.byteOffset||0)+(y.byteOffset||0),a=c.byteStride&&c.byteStride>s*4?c.byteStride>>2:s,h;if(a===s)h=new Float32Array(t,o,y.count*s);else{h=new Float32Array(y.count*s);let M=new Float32Array(t,c.byteOffset||0,Math.floor(c.byteLength/4)),m=(y.byteOffset||0)>>2;for(let P=0;P<y.count;P++){let E=m+P*a;for(let S=0;S<s;S++)h[P*s+S]=M[E+S]}}let T=n.createBuffer();return l.push(T),n.bindBuffer(34962,T),n.bufferData(34962,h,35044),n.enableVertexAttribArray(r),n.vertexAttribPointer(r,s,5126,!1,0,0),h}var St=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),$e=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function ke(n,e,t=$e,i){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:r,bin:s}=e,l=[],y=ve(r),c=[];if(Array.isArray(r.nodes))for(let x=0;x<r.nodes.length;x++){let b=r.nodes[x];b.mesh!==void 0&&r.meshes&&r.meshes[b.mesh]&&c.push({node:b,nodeIdx:x,meshIdx:b.mesh})}let o=c.length>0?c:(r.meshes||[]).map((x,b)=>({node:x,nodeIdx:-1,meshIdx:b})),a=[];if(Array.isArray(e.lights)&&e.lights.length>0)a.push(...e.lights);else if(r.extensions?.KHR_lights_punctual?.lights){let x=r.extensions.KHR_lights_punctual.lights;for(let b of x){let w=b.type==="directional"?"directional":b.type==="point"?"point":"ambient";a.push({type:w,color:b.color||[1,1,1],intensity:b.intensity!==void 0?b.intensity:1})}}if(a.length===0&&(a.push({type:"ambient",color:[1,1,1],intensity:.35}),a.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),o.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${o.length}`);let h=[];if(r.textures&&r.images){if(r.textures.length>t.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${t.maxTextures}). Found: ${r.textures.length}`);for(let x=0;x<r.textures.length;x++){let b=r.textures[x],w=r.images[b.source];if(w){let F=n.createTexture();if(n.bindTexture(3553,F),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),w.bufferView!==void 0){let I=r.bufferViews[w.bufferView],g=s.slice(I.byteOffset||0,(I.byteOffset||0)+I.byteLength),d=new Blob([g],{type:w.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(d).then(U=>{n.bindTexture(3553,F),n.texImage2D(3553,0,6408,6408,5121,U),n.generateMipmap(3553),i?.()}).catch(()=>{})}else if(w.uri){let I=bt(w.uri);if(I){let g=new Image;g.crossOrigin="anonymous",g.referrerPolicy="no-referrer",g.onload=()=>{n.bindTexture(3553,F),n.texImage2D(3553,0,6408,6408,5121,g),n.generateMipmap(3553),i?.()},g.src=I}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",w.uri)}h.push(F)}else h.push(null)}}let T=[1/0,1/0,1/0],M=[-1/0,-1/0,-1/0],m=0,P=0;for(let x=0;x<o.length;x++){let b=o[x],w=r.meshes[b.meshIdx],F=b.nodeIdx>=0?y[b.nodeIdx]:K(),I=new Float32Array(9);ne(I,F);let g={name:b.node.name||w.name||`Mesh_${b.meshIdx}`,nodeIndex:b.nodeIdx,transform:F,normalMatrix:I,primitives:[],extras:b.node.extras||w.extras};for(let d of w.primitives||[]){if(d.extensions?.KHR_draco_mesh_compression){let $=he("draco");$&&$.decodePrimitive(r,d,s)}let U=[],A=n.createVertexArray();n.bindVertexArray(A);let O=r.accessors[d.attributes.POSITION],k=Number(O?.count??0);if(!Number.isFinite(k)||k<0||m+k>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(m+=k,O?.min&&O?.max)for(let $=0;$<3;$++){let Q=F[12+$],ce=F[12+$];for(let ie=0;ie<3;ie++){let de=F[ie*4+$]*O.min[ie],pe=F[ie*4+$]*O.max[ie];Q+=de<pe?de:pe,ce+=de>pe?de:pe}Q<T[$]&&(T[$]=Q),ce>M[$]&&(M[$]=ce)}let C=Ee(n,r,s,d.attributes.POSITION,0,3,U);Ee(n,r,s,d.attributes.NORMAL,1,3,U),Ee(n,r,s,d.attributes.TEXCOORD_0,2,2,U);let _=0,R=5123,V=null;if(d.indices!==void 0){let $=r.accessors[d.indices],ce=(r.bufferViews[$.bufferView].byteOffset||0)+($.byteOffset||0);if(_=Number($.count??0),!Number.isFinite(_)||_<0||P+_>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);P+=_,R=$.componentType===5125?5125||5125:5123||5123;let ie=n.createBuffer();U.push(ie),n.bindBuffer(34963,ie),$.componentType===5125?(V=new Uint32Array(s,ce,$.count),n.bufferData(34963,V,35044)):(V=new Uint16Array(s,ce,$.count),n.bufferData(34963,V,35044))}else _=O.count;let N={};for(let $ of q)if($.onBuildPrimitiveVAO){let Q=$.onBuildPrimitiveVAO(n,A,d,r,s);Q&&(N[$.name]=Q)}n.bindVertexArray(null);let G=r.materials&&d.material!==void 0?r.materials[d.material]:null,B=He,H=ze,W=!1;for(let $ of q)if($.onResolveShader){let Q=$.onResolveShader(d,G,B,H);Q&&(B=Q.vs,H=Q.fs,W=!0)}let X=W?Pe(n,B,H):null,ee=X?Fe(n,X,Xe):null,Y=G?.pbrMetallicRoughness,Z=Y?.baseColorFactor||[.8,.8,.8,1],re=Y?.metallicFactor??.1,se=Y?.roughnessFactor??.5,te=G?.extensions?.KHR_materials_clearcoat,j=te?te.clearcoatFactor??1:0,ae=Math.max(.04,te?.clearcoatRoughnessFactor??.04),oe=Y?.baseColorTexture!==void 0&&h[Y.baseColorTexture.index]?h[Y.baseColorTexture.index]:null,le=Y?.metallicRoughnessTexture!==void 0&&h[Y.metallicRoughnessTexture.index]?h[Y.metallicRoughnessTexture.index]:null,et=G?.normalTexture!==void 0&&h[G.normalTexture.index]?h[G.normalTexture.index]:null,tt=G?.normalTexture?.scale??1,nt=G?.occlusionTexture!==void 0&&h[G.occlusionTexture.index]?h[G.occlusionTexture.index]:null,it=G?.occlusionTexture?.strength??1,rt=!!(G?.extensions?.KHR_materials_transmission||N.materials?.isTransmissive);g.primitives.push({vao:A,indexCount:_,indexType:R,baseColor:Z,metallic:re,roughness:se,clearcoat:j,clearcoatRoughness:ae,positions:C,indices:V,texture:oe,metallicRoughnessTexture:le,normalTexture:et,occlusionTexture:nt,normalScale:tt,occlusionStrength:it,buffers:U,materialIndex:d.material,pluginData:N,customProgram:X,customUniforms:ee,isTransmissive:rt})}l.push(g)}isFinite(T[0])||(T=[-1,-1,-1]),isFinite(M[0])||(M=[1,1,1]);let E=[(T[0]+M[0])/2,(T[1]+M[1])/2,(T[2]+M[2])/2],S=M[0]-T[0],L=M[1]-T[1],f=M[2]-T[2],v=Math.max(Math.hypot(S,L,f)/2,.5),p=[T[0],T[1],T[2]],D=[M[0],M[1],M[2]],u=e.animations;if(!u){for(let x of q)if(x.onParseGLB?.(e),e.animations){u=e.animations;break}}return u||(u=[]),{meshes:l,bounds:{center:E,radius:v,min:p,max:D},lights:a,animations:u,worldMatrices:y}}var xe=class{constructor(e,t,i){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=K();this.clearColor=[0,0,0,0];this.envIntensity=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=K();this.viewMatrix=K();this.modelMatrix=K();this.mvpMatrix=K();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:K(),rawValueToMeters:.001,format:0};this.container=e;let r,s;if(t&&typeof t.getContext=="function"?(r=t,s=i):(s=t,r=s?.canvas),!r){let c=e.querySelector("canvas");c||(c=document.createElement("canvas"),c.style.width="100%",c.style.height="100%",c.style.display="block",c.style.touchAction="none",e.prepend(c)),r=c}this.canvas=r,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let l=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!l:l&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.envIntensity=Math.max(0,Number(this.opts.exposure))),this.opts.camera&&this.setInitialCamera(this.opts.camera.theta,this.opts.camera.phi,this.opts.camera.distance,this.opts.camera.zoom),this.opts.shadowIntensity!==void 0&&(this.shadowIntensity=Math.max(0,Math.min(1,Number(this.opts.shadowIntensity)||0))),this.opts.shadowSoftness!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(this.opts.shadowSoftness)||0))),this.opts.toneMapping!==void 0&&(this.toneMapping=this.opts.toneMapping),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let y=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!y)throw new Error("WebGL2 not supported");this.gl=y,this.renderProg=Pe(y,He,ze),this.pickProg=Pe(y,dt,pt),this.uRender=Fe(y,this.renderProg,Xe),this.uPick=Fe(y,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo(),this.setupEvents(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){mt(e,t)}static getDecoder(e){return he(e)}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),i=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=i,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,i,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,i),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let i=this.gl,r=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=r,this.pickFboHeight=s,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,s,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,s)}loadGLBData(e,t){let{meshes:i,bounds:r,lights:s,animations:l,worldMatrices:y}=ke(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=l||[],this.worldMatrices=y||[],this.gltf=e.gltf,this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let o of e.gltf.nodes)this.initialNodeTransforms.push({t:o.translation?[o.translation[0],o.translation[1],o.translation[2]]:[0,0,0],r:o.rotation?[o.rotation[0],o.rotation[1],o.rotation[2],o.rotation[3]]:[0,0,0,1],s:o.scale?[o.scale[0],o.scale[1],o.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let o of q)o.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:r.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let c=e.exposure??e.environmentIntensity??e.gltf?.extras?.exposure??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.exposure??e.gltf?.asset?.extras?.environmentIntensity;c!==void 0&&(this.envIntensity=Math.max(0,Number(c))),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(Oe(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(me(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=me(e),{meshes:r}=ke(this.gl,i,$e,()=>this.render());if(t)for(let s of r)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],ne(s.normalMatrix,s.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(e,t,i,r=1){this.clearColor=[e,t,i,r]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let i=this.meshes[t],r;e instanceof Map?r=e.get(i.name)??e.get(t):Array.isArray(e)?r=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,i.name)?r=e[i.name]:Object.prototype.hasOwnProperty.call(e,t)&&(r=e[t])),r&&r.length===16&&(i.transform.set(r),ne(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[],s=[],l=[],y=[];for(let c of this.lights){let o=c.color||[1,1,1],a=c.intensity!==void 0?c.intensity:1;if(c.type==="ambient")i=[o[0]*a,o[1]*a,o[2]*a];else if(c.type==="directional"&&r.length<6){let h=c.direction||[.5,1,.8];r.push(h[0],h[1],h[2]),s.push(o[0]*a,o[1]*a,o[2]*a)}else if(c.type==="point"&&l.length<6){let h=c.position||[0,0,0];l.push(h[0],h[1],h[2]),y.push(o[0]*a,o[1]*a,o[2]*a)}}r.length===0&&(r.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,i),t.uniform1i(e.uNumDirLights,r.length/3),r.length>0&&(t.uniform3fv(e.uDirLightDir,r),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,l.length/3),l.length>0&&(t.uniform3fv(e.uPointLightPos,l),t.uniform3fv(e.uPointLightColor,y)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.envIntensity=Math.max(0,Number(e))}getExposure(){return this.envIntensity}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=e}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of q)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of q)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,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(a=>a.primitives.filter(h=>h.materialIndex===i||e.length===1&&h.materialIndex===void 0)),s=r[0],l=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],y=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,c=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,o={baseColorFactor:l,metallicFactor:y,roughnessFactor:c,setBaseColorFactor:a=>{let h=[a[0],a[1],a[2],a[3]??1];o.baseColorFactor=h,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=h);for(let T of r)T.baseColor=h;this.render()},setMetallicFactor:a=>{o.metallicFactor=a,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=a);for(let h of r)h.metallic=a;this.render()},setRoughnessFactor:a=>{o.roughnessFactor=a,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=a);for(let h of r)h.roughness=a;this.render()}};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:o}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(i=>i.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of q)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,i){this.customTarget=[e,t,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(i,e))}setCamera(e,t,i,r){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(e,t,i,r){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),i!==void 0&&i>0){let s=this.clampDistance(i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(r!==void 0&&r>0){let s=this.clampDistance(this.bounds.radius*2.5/r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let i=K();J(i,this.projMatrix,this.viewMatrix);let[r,s,l]=e,y=t?t[0]:0,c=t?t[1]:0,o=t?t[2]:0,a=this.modelRootMatrix;a&&(r=a[0]*e[0]+a[4]*e[1]+a[8]*e[2]+a[12],s=a[1]*e[0]+a[5]*e[1]+a[9]*e[2]+a[13],l=a[2]*e[0]+a[6]*e[1]+a[10]*e[2]+a[14],t&&(y=a[0]*t[0]+a[4]*t[1]+a[8]*t[2],c=a[1]*t[0]+a[5]*t[1]+a[9]*t[2],o=a[2]*t[0]+a[6]*t[1]+a[10]*t[2]));let h=i[0]*r+i[4]*s+i[8]*l+i[12],T=i[1]*r+i[5]*s+i[9]*l+i[13],M=i[2]*r+i[6]*s+i[10]*l+i[14],m=i[3]*r+i[7]*s+i[11]*l+i[15];if(m<=1e-4)return{x:0,y:0,z:1,visible:!1};let P=h/m,E=T/m,S=M/m,L=this.canvas.getBoundingClientRect(),f=L.width||this.canvas.clientWidth||this.canvas.width||300,v=L.height||this.canvas.clientHeight||this.canvas.height||150,p=(P*.5+.5)*f,D=(-E*.5+.5)*v,u=P>=-1.1&&P<=1.1&&E>=-1.1&&E<=1.1&&S>=-1&&S<=1;if(u&&t){let x=this.customTarget||this.bounds.center,b=x[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),w=x[1]+this.currDistance*Math.sin(this.currPhi),F=x[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),I=[r-b,s-w,l-F];y*I[0]+c*I[1]+o*I[2]>.05&&(u=!1)}return{x:p,y:D,z:S,visible:u}}setSelectedMesh(e){this.selectedMeshName=e||""}setupEvents(){let e=this.canvas;this.boundContextMenu=t=>{t.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=t=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist=0,this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.isPanning=t.button===2||t.shiftKey||this.activePointers.size===2,e.setPointerCapture(t.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=t=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let i=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},r=t.clientX-i.x,s=t.clientY-i.y;if(this.activePointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.lastPointerX=t.clientX,this.lastPointerY=t.clientY,this.totalDragDist+=Math.hypot(r,s),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let l=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],y=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],c=this.customTarget?[...this.customTarget]:[...this.bounds.center],o=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;c[0]+=(-r*l[0]+s*y[0])*o,c[1]+=(-r*l[1]+s*y[1])*o,c[2]+=(-r*l[2]+s*y[2])*o,this.customTarget=c}else this.targetTheta=this.clampTheta(this.targetTheta-r*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=t=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(t.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(t.pointerId)}catch{}if(this.totalDragDist<5&&t.button===0){let i=e.getBoundingClientRect(),r=Math.floor((t.clientX-i.left)*(e.width/Math.max(i.width,1))),s=Math.floor((t.clientY-i.top)*(e.height/Math.max(i.height,1)));this.performMeshPick(r,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=t=>{if(!this.interactive)return;t.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let i=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*i)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let i=t.detail||{};i.reset?this.resetCamera():this.setCamera(i.theta,i.phi,i.distance,i.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=t=>{if(!this.interactive)return;let i=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=i,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=i,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=i,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=i,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=i,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=i,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=i,this.resetCamera(),t.preventDefault();break}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=this.canvas;this.boundContextMenu&&(e.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(e.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(e.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(e.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(e.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(e.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(e,t){let i=this.canvas,r=i.getBoundingClientRect(),s=i.width||300,l=i.height||300,y=r.width>0?Math.floor((e-r.left)*(s/r.width)):Math.floor(e),c=r.height>0?Math.floor((t-r.top)*(l/r.height)):Math.floor(t);return this.performMeshPick(y,c,!1)}performMeshPick(e,t,i=!0){if(this.meshes.length===0)return null;let r=this.gl,s=Math.max(1,this.canvas.width||300),l=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let y=K();J(y,this.projMatrix,this.viewMatrix);let c=[],o=Math.max(0,Math.min(s-1,e)),a=Math.max(0,Math.min(l-1,l-1-t));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==l)&&this.resizePickingFbo(s,l),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,s,l),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16384|256),r.useProgram(this.pickProg);for(let u=0;u<this.meshes.length;u++){let x=this.meshes[u];if(x.visible===!1||x.isPluginMesh)continue;let b=u+1,w=(b&255)/255,F=(b>>8&255)/255,I=(b>>16&255)/255;r.uniform4f(this.uPick.uColorId,w,F,I,1),J(this.modelMatrix,this.modelRootMatrix,x.transform),J(this.mvpMatrix,y,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let g of x.primitives)r.bindVertexArray(g.vao),r.drawElements(4,g.indexCount,g.indexType,0)}let p=new Uint8Array(4);r.readPixels(o,a,1,1,6408,5121,p),r.bindFramebuffer(36160,null);let D=p[0]+(p[1]<<8)+(p[2]<<16);D>0&&D<=this.meshes.length&&(c=[this.meshes[D-1]])}c.length===0&&(c=this.meshes.filter(p=>p.visible!==!1));let h=null,T=1/0,M=[0,0,0],m=[0,1,0],P=this.customTarget||this.bounds.center,E=P[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),S=P[1]+this.currDistance*Math.sin(this.currPhi),L=P[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let p of c){J(this.modelMatrix,this.modelRootMatrix,p.transform),J(this.mvpMatrix,y,this.modelMatrix);let D=K();if(!Be(D,this.mvpMatrix))continue;let u=(o+.5)/s*2-1,x=(a+.5)/l*2-1,b=[0,0,0],w=[0,0,0];De(b,u,x,-1,D),De(w,u,x,1,D);let F=w[0]-b[0],I=w[1]-b[1],g=w[2]-b[2],d=Math.hypot(F,I,g)||1,U=F/d,A=I/d,O=g/d,k={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((_=>{for(let R of p.primitives){if(!R.positions)continue;let V=R.positions,N=R.indices,G=Math.floor(N?N.length/3:V.length/9);for(let B=0;B<G;B++){let H=N?N[B*3]:B*3,W=N?N[B*3+1]:B*3+1,X=N?N[B*3+2]:B*3+2;Ne(b[0],b[1],b[2],U,A,O,V[H*3],V[H*3+1],V[H*3+2],V[W*3],V[W*3+1],V[W*3+2],V[X*3],V[X*3+1],V[X*3+2],k,_)}}})(1e-4),isFinite(k.distance)){let _=k.point[0],R=k.point[1],V=k.point[2],N=this.modelMatrix,G=N[0]*_+N[4]*R+N[8]*V+N[12],B=N[1]*_+N[5]*R+N[9]*V+N[13],H=N[2]*_+N[6]*R+N[10]*V+N[14],W=G-E,X=B-S,ee=H-L,Y=Math.hypot(W,X,ee);if(Y<T){ne(this.normalMatrix,this.modelMatrix);let Z=this.normalMatrix,re=k.normal[0],se=k.normal[1],te=k.normal[2],j=Z[0]*re+Z[3]*se+Z[6]*te,ae=Z[1]*re+Z[4]*se+Z[7]*te,oe=Z[2]*re+Z[5]*se+Z[8]*te,le=Math.hypot(j,ae,oe)||1;j/=le,ae/=le,oe/=le,j*W+ae*X+oe*ee>0&&(j=-j,ae=-ae,oe=-oe),h=p,T=Math.round(Y*1e3)/1e3,M=[Math.round(G*1e3)/1e3,Math.round(B*1e3)/1e3,Math.round(H*1e3)/1e3],m=[Math.round(j*1e3)/1e3,Math.round(ae*1e3)/1e3,Math.round(oe*1e3)/1e3]}}}if(!h)return null;let v={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:T,hitPoint:M,normal:m,screenX:e,screenY:t};if(i){for(let p of q)p.onMeshSelect?.(this,v);this.opts.onMeshClick&&this.opts.onMeshClick(v),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:v}))}return v}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,s=r?e-i:e,l=r?Math.max(1,t-i):i,y=(s+.5)/l*2-1;return Math.floor((y*.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);ge(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center,r=i[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),s=i[1]+this.currDistance*Math.sin(this.currPhi),l=i[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);ye(this.viewMatrix,[r,s,l],i,[0,1,0]),J(this.mvpMatrix,this.projMatrix,this.viewMatrix),ne(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 q)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 q)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),i=this.bounds.center[0],r=this.bounds.center[2],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=i-(e*i+t*r),s[13]=0,s[14]=r-(-t*i+e*r),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let l of q)l.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 l of q)l.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let i=Math.round((this.currTheta*180/Math.PI%360+360)%360),r=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(i-this.lastReportedTheta)>=1||Math.abs(r-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=s;let l={theta:i,phi:r,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(l),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:l}))}}renderXRView(e,t,i,r,s=!0,l=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let y=e?.transform?.inverse?.matrix||this.viewMatrix,c=e?.projectionMatrix||this.projMatrix,o=e?.transform?.position,a=o?[o.x,o.y,o.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):i&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:y,projMatrix:c,eyePos:a,viewport:r,eye:e?.eye||"none",clear:l>0?!1:e?.eye!=="right",isAR:s})}render(e){if(!e&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),p=Math.max(1,this.canvas.height||1),D=Math.max(1,Math.floor(v*.5)),u=Math.max(1,v-D),x=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),b=this.customTarget||this.bounds.center,w=b[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),F=b[1]+this.currDistance*Math.sin(this.currPhi),I=b[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),g=Math.cos(this.currTheta),d=-Math.sin(this.currTheta),U=.032,A=K(),O=K(),k=[w-g*U,F,I-d*U],C=[b[0]-g*U*.25,b[1],b[2]-d*U*.25];ge(A,this.fov,D/p,.1,x),ye(O,k,C,[0,1,0]);let _=K(),R=K(),V=[w+g*U,F,I+d*U],N=[b[0]+g*U*.25,b[1],b[2]+d*U*.25];ge(_,this.fov,u/p,.1,x),ye(R,V,N,[0,1,0]),this.render({viewMatrix:O,projMatrix:A,eyePos:k,viewport:[0,0,D,p],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:R,projMatrix:_,eyePos:V,viewport:[D,0,u,p],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,p);return}let t=this.gl,i=0,r=0,s=this.canvas.width,l=this.canvas.height;e?.viewport?(i=e.viewport[0],r=e.viewport[1],s=e.viewport[2],l=e.viewport[3],t.viewport(i,r,s,l)):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 y=K(),c=e?.viewMatrix??this.viewMatrix;J(y,e?.projMatrix??this.projMatrix,c);let o=[-c[2],-c[6],-c[10]],a=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:0,h=this.customTarget||this.bounds.center,T=e?e.eyePos[0]:h[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),M=e?e.eyePos[1]:h[1]+this.currDistance*Math.sin(this.currPhi),m=e?e.eyePos[2]:h[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let v of q)v.onBeforeDrawScene?.(this,t,y,[T,M,m],a);let P=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&P===0)return;let E=e?.eye||"none",S=!1,L=P>0?[...this.backdropMeshes,...this.meshes]:this.meshes,f=v=>{for(let p=0;p<L.length;p++){let D=L[p];if(D.visible===!1)continue;let u=this.selectedMeshName!==""&&D.name===this.selectedMeshName;p<P||D.worldSpace===!0||D.name==="__xr_reticle__"?this.modelMatrix.set(D.transform):J(this.modelMatrix,this.modelRootMatrix,D.transform),J(this.mvpMatrix,y,this.modelMatrix),ne(D.normalMatrix,this.modelMatrix);let x=D.extras?.xr?.stereo||D.userData?.xr?.stereo,b=0,w=0,F=1,I=1;x==="sbs"?(F=.5,b=E==="right"?.5:0):x==="ou"&&(I=.5,w=E==="right"?.5:0);for(let g of D.primitives){let d=!!g.isTransmissive;if(!v&&d){S=!0;continue}if(v&&!d)continue;let U=g.customProgram||this.renderProg,A=g.customUniforms||this.uRender;t.useProgram(U),t.uniform1i(A.uToneMapping,a),t.uniform1f(A.uEnvIntensity,this.envIntensity),t.uniform3f(A.uCameraPos,T,M,m),A.uCameraFwd&&t.uniform3f(A.uCameraFwd,o[0],o[1],o[2]),t.uniform1f(A.uEmissive,u?1:0),t.uniformMatrix4fv(A.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(A.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(A.uNormalMatrix,!1,D.normalMatrix),A.uUvTransform&&t.uniform4f(A.uUvTransform,b,w,F,I),A.uViewportSize&&t.uniform2f(A.uViewportSize,Math.max(1,s),Math.max(1,l)),A.uViewport&&t.uniform4f(A.uViewport,i,r,Math.max(1,s),Math.max(1,l)),this.xrDepthState.enabled&&this.xrDepthState.texture?(t.activeTexture(33989),t.bindTexture(3553,this.xrDepthState.texture),A.uXrDepthTex&&t.uniform1i(A.uXrDepthTex,5),A.uXrDepthEnabled&&t.uniform1i(A.uXrDepthEnabled,1),A.uXrDepthFormat&&t.uniform1i(A.uXrDepthFormat,this.xrDepthState.format||0),A.uXrRawValueToMeters&&t.uniform1f(A.uXrRawValueToMeters,this.xrDepthState.rawValueToMeters),A.uXrDepthUVTransform&&t.uniformMatrix4fv(A.uXrDepthUVTransform,!1,this.xrDepthState.uvTransform)):A.uXrDepthEnabled&&t.uniform1i(A.uXrDepthEnabled,0),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(A.uEnvironmentMap,4),t.uniform1i(A.uHasEnvironmentMap,1)):t.uniform1i(A.uHasEnvironmentMap,0),this.bindLights(A);for(let O of q)O.onBeforeDrawPrimitive?.(t,U,g,D,this.worldMatrices||[],this.gltf);t.uniform4fv(A.uBaseColor,g.baseColor),t.uniform1f(A.uMetallic,g.metallic),t.uniform1f(A.uRoughness,g.roughness),A.uClearcoat&&t.uniform2f(A.uClearcoat,g.clearcoat??0,g.clearcoatRoughness??.04),g.texture?(t.activeTexture(33984),t.bindTexture(3553,g.texture),t.uniform1i(A.uBaseColorTexture,0),t.uniform1i(A.uHasTexture,1)):t.uniform1i(A.uHasTexture,0),g.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,g.metallicRoughnessTexture),t.uniform1i(A.uMetallicRoughnessTexture,1),t.uniform1i(A.uHasMetallicRoughnessTexture,1)):t.uniform1i(A.uHasMetallicRoughnessTexture,0),g.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,g.normalTexture),t.uniform1i(A.uNormalTexture,2),t.uniform1i(A.uHasNormalTexture,1),t.uniform1f(A.uNormalScale,g.normalScale)):t.uniform1i(A.uHasNormalTexture,0),g.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,g.occlusionTexture),t.uniform1i(A.uOcclusionTexture,3),t.uniform1i(A.uHasOcclusionTexture,1),t.uniform1f(A.uOcclusionStrength,g.occlusionStrength)):t.uniform1i(A.uHasOcclusionTexture,0),t.bindVertexArray(g.vao),t.drawElements(4,g.indexCount,g.indexType,0)}}};if(f(!1),S){for(let v of q)v.onBeforeTransmissivePass?.(t,this);f(!0)}for(let v of q)v.onAfterRender?.(t,this,y)}disposeMeshListGpuResources(e){let t=this.gl;for(let i of e)for(let r of i.primitives){if(r.vao&&t.deleteVertexArray(r.vao),r.buffers)for(let s of r.buffers)t.deleteBuffer(s);r.texture&&t.deleteTexture(r.texture),r.metallicRoughnessTexture&&t.deleteTexture(r.metallicRoughnessTexture),r.normalTexture&&t.deleteTexture(r.normalTexture),r.occlusionTexture&&t.deleteTexture(r.occlusionTexture),r.customProgram&&t.deleteProgram(r.customProgram)}}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes),this.meshes=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of q)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};xe.registerPlugin=Ie,xe.getRegisteredPlugins=_e;function gt(n){return n+3&-4}function yt(n){let e={};return n.grab&&(e.interactable={mode:typeof n.grab=="string"?n.grab:"2-hand"},e.movable={scaleInZ:!!n.scale,minScale:typeof n.scale=="object"?n.scale.min??.1:.1,maxScale:typeof n.scale=="object"?n.scale.max??10:10}),n.billboard&&(e.billboard={mode:typeof n.billboard=="string"?n.billboard:"capsule"}),n.follow&&(e.follow={target:typeof n.follow=="object"?n.follow.mode??"head":n.follow}),n.anchor&&(e.anchor={plane:n.anchor}),n.physics&&n.physics!=="none"&&(e.rigidbody={type:n.physics}),e}function Ke(n,e){n.updateMatrixWorld(!0);let t=[],i=0,r=[],s=[],l=[],y=[],c=new Set,o=[],a=[],h=new Map,T=[];function M(u,x){let b=new Uint8Array(u.buffer,u.byteOffset,u.byteLength),w=gt(b.byteLength),F=new Uint8Array(w);F.set(b),t.push(F);let I=r.length;return r.push({buffer:0,byteOffset:i,byteLength:b.byteLength,target:x}),i+=w,I}function m(u,x,b,w,F,I,g){let d=M(u,b),U=s.length,A={bufferView:d,byteOffset:0,componentType:w,count:F,type:x};return I&&(A.min=I),g&&(A.max=g),s.push(A),U}n.traverse(u=>{(u.isLight||u.color&&u.intensity!==void 0)&&T.push({type:u.type,color:[u.color.r,u.color.g,u.color.b],intensity:u.intensity,position:[u.position.x,u.position.y,u.position.z]})});let P=[];function E(u){let x={name:u.name||""},b=u.position,w=u.quaternion,F=u.scale;if((b.x||b.y||b.z)&&(x.translation=[b.x,b.y,b.z]),(w.x||w.y||w.z||w.w!==1)&&(x.rotation=[w.x,w.y,w.z,w.w]),(F.x!==1||F.y!==1||F.z!==1)&&(x.scale=[F.x,F.y,F.z]),u.userData&&Object.keys(u.userData).length>0&&(x.extras=JSON.parse(JSON.stringify(u.userData,(g,d)=>{if(!(g==="__proto__"||g==="prototype"||g==="constructor"))return typeof d=="function"?void 0:d})),u.userData.xr)){let g=yt(u.userData.xr);x.extensions={...x.extensions||{},MOZ_hubs_components:g,ANDROID_xr_scenecore:g},ue().xrTraitSerializer?.gltfNode(x,u.userData.xr),c.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(u.geometry){let g=u.geometry,d=g.attributes.position;if(d&&d.count>0){let U=[1/0,1/0,1/0],A=[-1/0,-1/0,-1/0];for(let _=0;_<d.count;_++){let R=d.getX(_),V=d.getY(_),N=d.getZ(_);R<U[0]&&(U[0]=R),R>A[0]&&(A[0]=R),V<U[1]&&(U[1]=V),V>A[1]&&(A[1]=V),N<U[2]&&(U[2]=N),N>A[2]&&(A[2]=N)}let k={attributes:{POSITION:m(d.array,"VEC3",34962,5126,d.count,U,A)}};if(g.attributes.normal&&(k.attributes.NORMAL=m(g.attributes.normal.array,"VEC3",34962,5126,g.attributes.normal.count)),g.attributes.uv&&(k.attributes.TEXCOORD_0=m(g.attributes.uv.array,"VEC2",34962,5126,g.attributes.uv.count)),g.index){let _=g.index.array instanceof Uint32Array;k.indices=m(g.index.array,"SCALAR",34963,_?5125:5123,g.index.count)}if(u.material){let _=h.get(u.material);if(_===void 0){_=a.length,h.set(u.material,_);let R=u.material,V={name:R.name||"",pbrMetallicRoughness:{baseColorFactor:[R.color.r,R.color.g,R.color.b,R.opacity],metallicFactor:R.metalness,roughnessFactor:R.roughness},doubleSided:R.side===2||R.doubleSided};if(R.emissive&&(R.emissive.r>0||R.emissive.g>0||R.emissive.b>0)){let G=R.emissiveIntensity??1;V.emissiveFactor=[R.emissive.r*G,R.emissive.g*G,R.emissive.b*G]}let N={};R.clearcoat>0&&(N.KHR_materials_clearcoat={clearcoatFactor:R.clearcoat,clearcoatRoughnessFactor:R.clearcoatRoughness||0}),R.sheen>0&&(N.KHR_materials_sheen={sheenColorFactor:R.sheenColor?[R.sheenColor.r,R.sheenColor.g,R.sheenColor.b]:[1,1,1],sheenRoughnessFactor:R.sheenRoughness||0}),R.transmission>0&&(N.KHR_materials_transmission={transmissionFactor:R.transmission}),R.thickness>0&&(N.KHR_materials_volume={thicknessFactor:R.thickness,attenuationDistance:R.attenuationDistance??1/0,attenuationColor:R.attenuationColor?[R.attenuationColor.r,R.attenuationColor.g,R.attenuationColor.b]:[1,1,1]}),R.ior!==void 0&&R.ior!==1.5&&(N.KHR_materials_ior={ior:R.ior}),R.dispersion>0&&(N.KHR_materials_dispersion={dispersion:R.dispersion}),R.iridescence>0&&(N.KHR_materials_iridescence={iridescenceFactor:R.iridescence,iridescenceIor:R.iridescenceIOR??1.3}),Object.keys(N).length>0&&(V.extensions=N),a.push(V)}k.material=_}let C=l.length;l.push({primitives:[k],name:u.name,...x.extras?{extras:x.extras}:{}}),x.mesh=C}}let I=y.length;if(y.push(x),o.push(u),u.children.length>0){x.children=[];for(let g of u.children)x.children.push(E(g))}return I}for(let u of n.children)P.push(E(u));let S=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),L=[];if(typeof S=="function"&&o.length>0){let u=e?.duration??4,x=e?.fps??15,b=Math.max(2,Math.round(u*x)+1),w=new Float32Array(b),F=o.map(C=>({px:C.position.x,py:C.position.y,pz:C.position.z,qx:C.quaternion.x,qy:C.quaternion.y,qz:C.quaternion.z,qw:C.quaternion.w,sx:C.scale.x,sy:C.scale.y,sz:C.scale.z})),I=o.map(()=>new Float32Array(b*3)),g=o.map(()=>new Float32Array(b*4)),d=o.map(()=>new Float32Array(b*3));for(let C=0;C<b;C++){let _=C/(b-1)*u;w[C]=_;try{S(_)}catch{}for(let R=0;R<o.length;R++){let V=o[R];I[R][C*3]=V.position.x,I[R][C*3+1]=V.position.y,I[R][C*3+2]=V.position.z,g[R][C*4]=V.quaternion.x,g[R][C*4+1]=V.quaternion.y,g[R][C*4+2]=V.quaternion.z,g[R][C*4+3]=V.quaternion.w,d[R][C*3]=V.scale.x,d[R][C*3+1]=V.scale.y,d[R][C*3+2]=V.scale.z}}for(let C=0;C<o.length;C++){let _=o[C],R=F[C];_.position.set(R.px,R.py,R.pz),_.quaternion.set(R.qx,R.qy,R.qz,R.qw),_.scale.set(R.sx,R.sy,R.sz)}n.updateMatrixWorld(!0);let U=null,A=()=>(U===null&&(U=m(w,"SCALAR",0,5126,b,[0],[u])),U),O=[],k=[];for(let C=0;C<o.length;C++){let _=F[C],R=!1,V=!1,N=!1;for(let G=0;G<b;G++)(Math.abs(I[C][G*3]-_.px)>1e-4||Math.abs(I[C][G*3+1]-_.py)>1e-4||Math.abs(I[C][G*3+2]-_.pz)>1e-4)&&(R=!0),(Math.abs(g[C][G*4]-_.qx)>1e-4||Math.abs(g[C][G*4+1]-_.qy)>1e-4||Math.abs(g[C][G*4+2]-_.qz)>1e-4||Math.abs(g[C][G*4+3]-_.qw)>1e-4)&&(V=!0),(Math.abs(d[C][G*3]-_.sx)>1e-4||Math.abs(d[C][G*3+1]-_.sy)>1e-4||Math.abs(d[C][G*3+2]-_.sz)>1e-4)&&(N=!0);if(R){let G=m(I[C],"VEC3",0,5126,b),B=O.length;O.push({input:A(),interpolation:"LINEAR",output:G}),k.push({sampler:B,target:{node:C,path:"translation"}})}if(V){let G=m(g[C],"VEC4",0,5126,b),B=O.length;O.push({input:A(),interpolation:"LINEAR",output:G}),k.push({sampler:B,target:{node:C,path:"rotation"}})}if(N){let G=m(d[C],"VEC3",0,5126,b),B=O.length;O.push({input:A(),interpolation:"LINEAR",output:G}),k.push({sampler:B,target:{node:C,path:"scale"}})}}k.length>0&&L.push({name:"ProceduralLoop",samplers:O,channels:k})}let f=we(y,l,n.userData),v={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:n.environmentIntensity}},scenes:[{nodes:P}],scene:0,nodes:y,meshes:l,materials:a,accessors:s,bufferViews:r,buffers:[{byteLength:i}],...L.length>0?{animations:L}:{},...f||c.size>0?{extensionsUsed:[...f?["KHR_interactivity"]:[],...c]}:{},...f?{extensions:{KHR_interactivity:f}}:{}},p=new Uint8Array(i),D=0;for(let u of t)p.set(u,D),D+=u.byteLength;return{gltf:v,bin:p.buffer,lights:T,environmentIntensity:n.environmentIntensity}}function fe(n){return new TextEncoder().encode(n)}function vt(n,e){let{gltf:t,bin:i}=Ke(n,e),r=JSON.stringify(t),s=fe(r),l=(4-s.byteLength%4)%4,y=s.byteLength+l,c=20+y+8+i.byteLength,o=new Uint8Array(c),a=new DataView(o.buffer);a.setUint32(0,1179937895,!0),a.setUint32(4,2,!0),a.setUint32(8,c,!0),a.setUint32(12,y,!0),a.setUint32(16,1313821514,!0),o.set(s,20);for(let T=0;T<l;T++)o[20+s.byteLength+T]=32;let h=20+y;return a.setUint32(h,i.byteLength,!0),a.setUint32(h+4,5130562,!0),o.set(new Uint8Array(i),h+8),o}function qe(n,e){n.updateMatrixWorld(!0);let t=[];return n.traverse(i=>{if(i.geometry){let r=i.geometry,s=r.attributes.position;if(!s||s.count===0)return;let l=s.count,y=new Float32Array(l*3),c=i.matrixWorld.elements;for(let u=0;u<l;u++){let x=s.getX(u),b=s.getY(u),w=s.getZ(u);y[u*3]=c[0]*x+c[4]*b+c[8]*w+c[12],y[u*3+1]=c[1]*x+c[5]*b+c[9]*w+c[13],y[u*3+2]=c[2]*x+c[6]*b+c[10]*w+c[14]}let o;if(r.attributes.normal){let u=r.attributes.normal;o=new Float32Array(l*3);let x=new Float32Array(9);ne(x,c);for(let b=0;b<l;b++){let w=u.getX(b),F=u.getY(b),I=u.getZ(b),g=x[0]*w+x[3]*F+x[6]*I,d=x[1]*w+x[4]*F+x[7]*I,U=x[2]*w+x[5]*F+x[8]*I,A=Math.hypot(g,d,U)||1;o[b*3]=g/A,o[b*3+1]=d/A,o[b*3+2]=U/A}}let a;if(r.attributes.uv){let u=r.attributes.uv;a=new Float32Array(l*2);for(let x=0;x<l;x++)a[x*2]=u.getX(x),a[x*2+1]=u.getY(x)}let h;if(r.index)h=r.index.array;else{h=l>65535?new Uint32Array(l):new Uint16Array(l);for(let u=0;u<l;u++)h[u]=u}let T="DefaultMaterial",M=[.8,.8,.8],m=.5,P=.1,E=0,S=0,L=1.5,f=1,v=[0,0,0];if(i.material){let u=i.material;T=u.name||`Material_${t.length}`,u.color&&(M=[u.color.r,u.color.g,u.color.b]),typeof u.roughness=="number"&&(m=u.roughness),typeof u.metalness=="number"&&(P=u.metalness),typeof u.clearcoat=="number"&&(E=u.clearcoat),typeof u.clearcoatRoughness=="number"&&(S=u.clearcoatRoughness),typeof u.ior=="number"&&(L=u.ior);let x=typeof u.opacity=="number"?u.opacity:1,b=typeof u.transmission=="number"?u.transmission:0;if(f=x*(1-b),u.emissive&&(u.emissive.r>0||u.emissive.g>0||u.emissive.b>0)){let w=u.emissiveIntensity??1;v=[u.emissive.r*w,u.emissive.g*w,u.emissive.b*w]}}let p,D=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 D=="function"){let u=e?.duration??4,x=e?.fps??4,b=Math.max(2,Math.round(u*x)+1),w=[],F=[],I=[],g=[],d=[i.position.x,i.position.y,i.position.z],U=[i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w],A=[i.scale.x,i.scale.y,i.scale.z],O=!1;for(let k=0;k<b;k++){let C=k/(b-1)*u;w.push(C);try{D(C)}catch{}F.push([i.position.x,i.position.y,i.position.z]),I.push([i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w]),g.push([i.scale.x,i.scale.y,i.scale.z]),(Math.abs(i.position.x-d[0])>1e-4||Math.abs(i.position.y-d[1])>1e-4||Math.abs(i.position.z-d[2])>1e-4||Math.abs(i.quaternion.x-U[0])>1e-4||Math.abs(i.quaternion.y-U[1])>1e-4||Math.abs(i.quaternion.z-U[2])>1e-4||Math.abs(i.quaternion.w-U[3])>1e-4||Math.abs(i.scale.x-A[0])>1e-4)&&(O=!0)}i.position.set(d[0],d[1],d[2]),i.quaternion.set(U[0],U[1],U[2],U[3]),i.scale.set(A[0],A[1],A[2]),O&&(p={times:w,translations:F,rotations:I,scales:g})}t.push({name:i.name||`Mesh_${t.length}`,positions:y,indices:h,normals:o,uvs:a,materialName:T,color:M,roughness:m,metallic:P,clearcoat:E,clearcoatRoughness:S,ior:L,opacity:f,emissiveColor:v,xrTraits:i.userData?.xr,timeSamples:p})}}),t}function Ce(n){let e=[],t=n.gltf,i=n.bin,r=i instanceof ArrayBuffer?i:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),s=t.accessors||[],l=t.bufferViews||[],y=t.materials||[],c=t.meshes||[],o=t.nodes||[];function a(M){let m=s[M];if(!m)throw new Error(`Accessor ${M} not found`);let P=l[m.bufferView||0],E=(P.byteOffset||0)+(m.byteOffset||0),S=P.byteLength||0,L=r.slice(E,E+S);return{acc:m,buffer:L}}let h=new Map;if(o.length>0){let M=ve(t);for(let m=0;m<M.length;m++)h.set(m,M[m])}function T(M,m,P,E){let S=c[M];if(!S)return;let L=new Float32Array(9);ne(L,m);for(let f=0;f<(S.primitives||[]).length;f++){let v=S.primitives[f],p=v.attributes?.POSITION;if(p===void 0)continue;let{acc:D,buffer:u}=a(p),x=new Float32Array(u,0,D.count*3),b=new Float32Array(x.length);for(let B=0;B<D.count;B++){let H=x[B*3],W=x[B*3+1],X=x[B*3+2];b[B*3]=m[0]*H+m[4]*W+m[8]*X+m[12],b[B*3+1]=m[1]*H+m[5]*W+m[9]*X+m[13],b[B*3+2]=m[2]*H+m[6]*W+m[10]*X+m[14]}let w,F=v.attributes?.NORMAL;if(F!==void 0){let{acc:B,buffer:H}=a(F),W=new Float32Array(H,0,B.count*3);w=new Float32Array(W.length);for(let X=0;X<B.count;X++){let ee=W[X*3],Y=W[X*3+1],Z=W[X*3+2],re=L[0]*ee+L[3]*Y+L[6]*Z,se=L[1]*ee+L[4]*Y+L[7]*Z,te=L[2]*ee+L[5]*Y+L[8]*Z,j=Math.hypot(re,se,te)||1;w[X*3]=re/j,w[X*3+1]=se/j,w[X*3+2]=te/j}}let I,g=v.attributes?.TEXCOORD_0;if(g!==void 0){let{acc:B,buffer:H}=a(g);I=new Float32Array(H,0,B.count*2)}let d;if(v.indices!==void 0){let{acc:B,buffer:H}=a(v.indices);B.componentType===5125?d=new Uint32Array(H,0,B.count):d=new Uint16Array(H,0,B.count);let W=D.count;for(let X of d)if(X>=W)throw new Error(`SecurityError: Index buffer value (${X}) out of vertex bounds [0, ${W}).`)}else{let B=D.count;d=B>65535?new Uint32Array(B):new Uint16Array(B);for(let H=0;H<B;H++)d[H]=H}let U="DefaultMaterial",A=[.8,.8,.8],O=.5,k=.1,C=0,_=0,R=1.5,V=1,N=[0,0,0];if(v.material!==void 0&&y[v.material]){let B=y[v.material];U=B.name||`Material_${v.material}`;let H=B.pbrMetallicRoughness||{},W=1;Array.isArray(H.baseColorFactor)&&(A=[H.baseColorFactor[0],H.baseColorFactor[1],H.baseColorFactor[2]],typeof H.baseColorFactor[3]=="number"&&(W=H.baseColorFactor[3])),typeof H.roughnessFactor=="number"&&(O=H.roughnessFactor),typeof H.metallicFactor=="number"&&(k=H.metallicFactor),Array.isArray(B.emissiveFactor)&&B.emissiveFactor.length>=3&&(N=[B.emissiveFactor[0],B.emissiveFactor[1],B.emissiveFactor[2]]);let X=B.extensions||{};X.KHR_materials_clearcoat&&(C=X.KHR_materials_clearcoat.clearcoatFactor??0,_=X.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),X.KHR_materials_ior&&typeof X.KHR_materials_ior.ior=="number"&&(R=X.KHR_materials_ior.ior);let ee=X.KHR_materials_transmission?.transmissionFactor??0;V=W*(1-ee)}let G=(S.primitives||[]).length>1?`${P}_p${f}`:P;e.push({name:G,positions:b,indices:d,normals:w,uvs:I,materialName:U,color:A,roughness:O,metallic:k,clearcoat:C,clearcoatRoughness:_,ior:R,opacity:V,emissiveColor:N,xrTraits:E?.xr||S.extras?.xr})}}if(o.length>0)for(let M=0;M<o.length;M++){let m=o[M];if(m.mesh!==void 0&&m.mesh<c.length){let P=h.get(M)||K(),E=m.name||c[m.mesh].name||`Node_${M}`;T(m.mesh,P,E,m.extras)}}else{let M=K();for(let m=0;m<c.length;m++){let P=c[m].name||`Mesh_${m}`;T(m,M,P,c[m].extras)}}return e}function Me(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 Se(n){return String(n??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function z(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 We(n){let e=n.length/3,t=new Array(e);for(let i=0;i<e;i++)t[i]=`(${z(n[i*3])}, ${z(n[i*3+1])}, ${z(n[i*3+2])})`;return t.join(", ")}function xt(n,e){let t=new Array(e);for(let i=0;i<e;i++)t[i]=`(${z(n[i*2])}, ${z(1-n[i*2+1])})`;return t.join(", ")}function Tt(n){return Array.from(n).join(", ")}function Re(n){let e=new Map;for(let c of n){let o=Me(c.materialName,"DefaultMaterial");e.has(o)||e.set(o,{color:c.color||[.8,.8,.8],roughness:c.roughness??.5,metallic:c.metallic??0,clearcoat:c.clearcoat??0,clearcoatRoughness:c.clearcoatRoughness??0,ior:c.ior??1.5,opacity:c.opacity??1,emissiveColor:c.emissiveColor||[0,0,0]})}let t=0,i=null;for(let c of n){if(c.timeSamples&&c.timeSamples.times.length>0){let o=c.timeSamples.times[c.timeSamples.times.length-1];o>t&&(t=o)}c.xrTraits?.anchor&&!i&&(i=c.xrTraits.anchor==="vertical"||c.xrTraits.anchor==="wall"?"vertical":"horizontal")}let r="";t>0&&(r=`startTimeCode = 0
223
+ endTimeCode = ${z(t)}
224
+ timeCodesPerSecond = 1.0
225
+ `);let s="";i&&(s=`uniform token preliminary:anchoring:type = "plane"
226
+ uniform token preliminary:planeAnchoring:alignment = "${i}"
227
+ `);let l=`#usda 1.0
228
+ (
229
+ defaultPrim = "Root"
230
+ metersPerUnit = 1.0
231
+ upAxis = "Y"
232
+ ${r})
233
+
234
+ def Xform "Root" (
235
+ kind = "component"
236
+ )
237
+ {
238
+ ${s}def Scope "Materials"
239
+ {
240
+ `;for(let[c,o]of e.entries()){let[a,h,T]=o.color,[M,m,P]=o.emissiveColor,E="";o.clearcoat>0&&(E+=`float inputs:clearcoat = ${z(o.clearcoat)}
241
+ `,E+=`float inputs:clearcoatRoughness = ${z(o.clearcoatRoughness)}
242
+ `),o.ior!==1.5&&(E+=`float inputs:ior = ${z(o.ior)}
243
+ `),o.opacity<1&&(E+=`float inputs:opacity = ${z(o.opacity)}
244
+ `),(M>0||m>0||P>0)&&(E+=`color3f inputs:emissiveColor = (${z(M)}, ${z(m)}, ${z(P)})
245
+ `),l+=`def Material "${c}"
246
+ {
247
+ def Shader "PBRShader"
248
+ {
249
+ uniform token info:id = "UsdPreviewSurface"
250
+ color3f inputs:diffuseColor = (${z(a)}, ${z(h)}, ${z(T)})
251
+ float inputs:metallic = ${z(o.metallic)}
252
+ float inputs:roughness = ${z(o.roughness)}
253
+ ${E}token outputs:surface
254
+ }
255
+ token outputs:surface.connect = </Root/Materials/${c}/PBRShader.outputs:surface>
256
+ }
257
+ `}l+=`}
258
+ def Scope "Meshes"
259
+ {
260
+ `;let y=new Set;for(let c=0;c<n.length;c++){let o=n[c],a=o.positions.length/3,h=1/0,T=1/0,M=1/0,m=-1/0,P=-1/0,E=-1/0;for(let u=0;u<a;u++){let x=o.positions[u*3],b=o.positions[u*3+1],w=o.positions[u*3+2];x<h&&(h=x),x>m&&(m=x),b<T&&(T=b),b>P&&(P=b),w<M&&(M=w),w>E&&(E=w)}isFinite(h)||(h=T=M=-1,m=P=E=1);let S=Math.floor(o.indices.length/3),L=Me(o.materialName,"DefaultMaterial"),f=Me(o.name,`Mesh_${c}`);y.has(f)&&(f=`${f}_${c}`),y.add(f);let v=S>0?S===1?"3":"3, ".repeat(S-1)+"3":"",p=o.xrTraits,D="";if(p){let u=[];p.physics&&p.physics!=="none"&&u.push('prepend apiSchemas = ["PhysicsBodyAPI", "PhysicsCollisionAPI"]');let x=ue().xrTraitSerializer?.usdLines(p,Se)??[];if(!x.length)for(let b of["grab","billboard","follow","anchor","physics"]){let w=b==="follow"&&typeof p.follow=="object"?p.follow.mode??"head":p[b];w!==void 0&&x.push(`string ${b} = "${Se(w)}"`)}x.length>0&&u.push(`customData = {
261
+ dictionary xr = {
262
+ ${x.join(`
263
+ `)}
264
+ }
265
+ }`),u.length>0&&(D=` (
266
+ ${u.join(`
267
+ `)}
268
+ )`)}if(l+=`def Mesh "${f}"${D}
269
+ {
270
+ `,p?.physics&&p.physics!=="none"){let u=p.physics==="static"?"true":"false";l+=`bool physics:rigidBodyEnabled = true
271
+ bool physics:kinematicEnabled = ${u}
272
+ bool physics:collisionEnabled = true
273
+ `}if(o.timeSamples&&o.timeSamples.times.length>0){let u=o.timeSamples,x=u.times.map((F,I)=>{let g=u.translations?.[I]||[0,0,0];return`${z(F)}: (${z(g[0])}, ${z(g[1])}, ${z(g[2])})`}).join(", "),b=u.times.map((F,I)=>{let g=u.rotations?.[I]||[0,0,0,1];return`${z(F)}: (${z(g[3])}, ${z(g[0])}, ${z(g[1])}, ${z(g[2])})`}).join(", "),w=u.times.map((F,I)=>{let g=u.scales?.[I]||[1,1,1];return`${z(F)}: (${z(g[0])}, ${z(g[1])}, ${z(g[2])})`}).join(", ");l+=`double3 xformOp:translate.timeSamples = { ${x} }
274
+ quatf xformOp:orient.timeSamples = { ${b} }
275
+ double3 xformOp:scale.timeSamples = { ${w} }
276
+ uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
277
+ `}l+=`float3[] extent = [(${z(h)}, ${z(T)}, ${z(M)}), (${z(m)}, ${z(P)}, ${z(E)})]
278
+ int[] faceVertexCounts = [${v}]
279
+ int[] faceVertexIndices = [${Tt(o.indices)}]
280
+ point3f[] points = [${We(o.positions)}]
281
+ `,o.normals&&o.normals.length===o.positions.length&&(l+=`normal3f[] normals = [${We(o.normals)}] (
282
+ interpolation = "vertex"
283
+ )
284
+ `),o.uvs&&o.uvs.length===a*2&&(l+=`texCoord2f[] primvars:st = [${xt(o.uvs,a)}] (
285
+ interpolation = "vertex"
286
+ )
287
+ `),l+=`rel material:binding = </Root/Materials/${L}>
288
+ }
289
+ `}return l+=`}
290
+ }
291
+ `,l}function Ye(n,e){if(n&&typeof n.traverse=="function"){let r=qe(n,e);return Re(r)}let t=me(n),i=Ce(t);return Re(i)}var Te=null;function Ze(n){if(!Te){Te=new Uint32Array(256);for(let t=0;t<256;t++){let i=t;for(let r=0;r<8;r++)i=i&1?3988292384^i>>>1:i>>>1;Te[t]=i}}let e=4294967295;for(let t=0;t<n.length;t++)e=Te[(e^n[t])&255]^e>>>8;return(e^4294967295)>>>0}function Le(n){let e=[],t=0,i=[];for(let a of n){let h=fe(a.filename),T=Ze(a.data),M=a.data.length,m=30+h.length,P=t+m,E=0,S=P%64;S!==0&&(E=64-S);let L=new Uint8Array(m+E),f=new DataView(L.buffer);f.setUint32(0,67324752,!0),f.setUint16(4,20,!0),f.setUint16(6,0,!0),f.setUint16(8,0,!0),f.setUint16(10,0,!0),f.setUint16(12,0,!0),f.setUint32(14,T,!0),f.setUint32(18,M,!0),f.setUint32(22,M,!0),f.setUint16(26,h.length,!0),f.setUint16(28,E,!0),L.set(h,30),E>0&&L.fill(0,30+h.length),e.push({offset:t,size:M,crc:T,filenameBytes:h,entry:a}),i.push(L),i.push(a.data),t+=L.length+a.data.length}let r=t;for(let a of e){let h=new Uint8Array(46+a.filenameBytes.length),T=new DataView(h.buffer);T.setUint32(0,33639248,!0),T.setUint16(4,20,!0),T.setUint16(6,20,!0),T.setUint16(8,0,!0),T.setUint16(10,0,!0),T.setUint16(12,0,!0),T.setUint16(14,0,!0),T.setUint32(16,a.crc,!0),T.setUint32(20,a.size,!0),T.setUint32(24,a.size,!0),T.setUint16(28,a.filenameBytes.length,!0),T.setUint16(30,0,!0),T.setUint16(32,0,!0),T.setUint16(34,0,!0),T.setUint16(36,0,!0),T.setUint32(38,0,!0),T.setUint32(42,a.offset,!0),h.set(a.filenameBytes,46),i.push(h),t+=h.length}let s=t-r,l=new Uint8Array(22),y=new DataView(l.buffer);y.setUint32(0,101010256,!0),y.setUint16(4,0,!0),y.setUint16(6,0,!0),y.setUint16(8,e.length,!0),y.setUint16(10,e.length,!0),y.setUint32(12,s,!0),y.setUint32(16,r,!0),y.setUint16(20,0,!0),i.push(l),t+=22;let c=new Uint8Array(t),o=0;for(let a of i)c.set(a,o),o+=a.length;return c}function je(n){let e=Ye(n),t=fe(e);return Le([{filename:"model.usda",data:t}])}function Je(n){let e=me(n),t=Ce(e),i=Re(t),r=fe(i);return Le([{filename:"model.usda",data:r}])}function Qe(n){return n&&typeof n.toUSDZ=="function"?n.toUSDZ():n&&typeof n.traverse=="function"?je(n):Je(n)}function Mt(n){let e=Qe(n);return new Blob([e],{type:"model/vnd.usdz+zip"})}