three-live 1.3.0 → 1.3.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 (42) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.ts +36 -0
  3. package/dist/three-author-engine.js +86 -62
  4. package/dist/three-author.cjs +84 -60
  5. package/dist/three-author.d.ts +36 -0
  6. package/dist/three-author.js +83 -59
  7. package/dist/three-convert.cjs +78 -58
  8. package/dist/three-convert.d.ts +36 -0
  9. package/dist/three-convert.js +77 -57
  10. package/dist/three-live-animation.cjs +8 -9
  11. package/dist/three-live-animation.d.ts +36 -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 +36 -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 +36 -0
  21. package/dist/three-live-element.js +16 -19
  22. package/dist/three-live-full.cjs +110 -86
  23. package/dist/three-live-full.js +107 -83
  24. package/dist/three-live-full.min.js +110 -86
  25. package/dist/three-live-studio.cjs +19 -20
  26. package/dist/three-live-studio.d.ts +36 -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 +36 -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 +87 -63
  34. package/dist/three-live.js +86 -62
  35. package/dist/three-live.min.js +86 -62
  36. package/dist/three-view.cjs +17 -20
  37. package/dist/three-view.d.ts +36 -0
  38. package/dist/three-view.js +16 -19
  39. package/dist/three-xr.cjs +78 -58
  40. package/dist/three-xr.d.ts +36 -0
  41. package/dist/three-xr.js +77 -57
  42. package/package.json +7 -1
@@ -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
- function pe(n,e,t,s=!0){let i=[],r=null;try{for(let[o,c]of[[35633,e],[35632,t]]){let a=n.createShader(o);if(!a){if(s)throw new Error("Shader allocation failed");return null}if(i.push(a),n.shaderSource(a,c),n.compileShader(a),n.getShaderParameter&&!n.getShaderParameter(a,35713)){if(s)throw new Error(`Shader compile error: ${n.getShaderInfoLog(a)}`);return null}}if(r=n.createProgram(),!r){if(s)throw new Error("Program allocation failed");return null}for(let o of i)n.attachShader(r,o);if(n.linkProgram(r),n.getProgramParameter&&!n.getProgramParameter(r,35714)){let o=s?n.getProgramInfoLog(r):null;if(n.deleteProgram?.(r),r=null,s)throw new Error(`Program link error: ${o}`);return null}return r}finally{for(let o of i)r&&n.detachShader?.(r,o),n.deleteShader?.(o)}}var ze={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Me(n,e,t,s){if(!t||t.bufferView===void 0)return null;let i=n.bufferViews?.[t.bufferView];if(!i)return null;let r=Number(t.count??0);if(!Number.isInteger(r)||r<=0)return null;let o=t.componentType??5126,c=ze[o];if(!c)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let a=c*s,l=i.byteStride&&i.byteStride>0?i.byteStride:a,u=(i.byteOffset||0)+(t.byteOffset||0);if(!Number.isInteger(u)||u<0||l<a||u+(r-1)*l+a>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(o===5126&&l===a&&u%4===0)return new Float32Array(e,u,r*s);let d=new DataView(e),m=t.normalized===!0,y=new Float32Array(r*s);for(let p=0;p<r;p++){let b=u+p*l;for(let x=0;x<s;x++){let g=b+x*c,w;switch(o){case 5126:w=d.getFloat32(g,!0);break;case 5120:w=d.getInt8(g),m&&(w=Math.max(w/127,-1));break;case 5121:w=d.getUint8(g),m&&(w/=255);break;case 5122:w=d.getInt16(g,!0),m&&(w=Math.max(w/32767,-1));break;case 5123:w=d.getUint16(g,!0),m&&(w/=65535);break;default:w=d.getUint32(g,!0),m&&(w/=4294967295)}y[p*s+x]=w}}return y}function Ae(n,e){let t=Number(e.offset?.[0]??0)||0,s=Number(e.offset?.[1]??0)||0,i=Number(e.scale?.[0]??1),r=Number(e.scale?.[1]??1),o=Number(e.rotation??0)||0,c=Math.cos(o),a=Math.sin(o),l=(Number.isFinite(i)?i:1)*c,u=(Number.isFinite(i)?i:1)*a,d=-(Number.isFinite(r)?r:1)*a,m=(Number.isFinite(r)?r:1)*c;for(let y=0;y+1<n.length;y+=2){let p=n[y],b=n[y+1];n[y]=l*p+u*b+t,n[y+1]=d*p+m*b+s}}function X(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function be(n,e,t,s,i){let r=1/Math.tan(e/2);n.fill(0),n[0]=r/t,n[5]=r,n[11]=-1;let o=1/(s-i);return n[10]=(i+s)*o,n[14]=2*i*s*o,n}function xe(n,e,t,s){let[i,r,o]=e,[c,a,l]=s,[u,d,m]=t,y=i-u,p=r-d,b=o-m,x=Math.hypot(y,p,b);x<=1e-5?(y=0,p=0,b=1):(y/=x,p/=x,b/=x);let g=a*b-l*p,w=l*y-c*b,M=c*p-a*y;x=Math.hypot(g,w,M),x<=1e-5?(g=0,w=0,M=0):(g/=x,w/=x,M/=x);let T=p*M-b*w,f=b*g-y*M,R=y*w-p*g;return x=Math.hypot(T,f,R),x<=1e-5?(T=0,f=0,R=0):(T/=x,f/=x,R/=x),n[0]=g,n[1]=T,n[2]=y,n[3]=0,n[4]=w,n[5]=f,n[6]=p,n[7]=0,n[8]=M,n[9]=R,n[10]=b,n[11]=0,n[12]=-(g*i+w*r+M*o),n[13]=-(T*i+f*r+R*o),n[14]=-(y*i+p*r+b*o),n[15]=1,n}function J(n,e,t){let s=e[0],i=e[1],r=e[2],o=e[3],c=e[4],a=e[5],l=e[6],u=e[7],d=e[8],m=e[9],y=e[10],p=e[11],b=e[12],x=e[13],g=e[14],w=e[15],M=t[0],T=t[1],f=t[2],R=t[3];return n[0]=M*s+T*c+f*d+R*b,n[1]=M*i+T*a+f*m+R*x,n[2]=M*r+T*l+f*y+R*g,n[3]=M*o+T*u+f*p+R*w,M=t[4],T=t[5],f=t[6],R=t[7],n[4]=M*s+T*c+f*d+R*b,n[5]=M*i+T*a+f*m+R*x,n[6]=M*r+T*l+f*y+R*g,n[7]=M*o+T*u+f*p+R*w,M=t[8],T=t[9],f=t[10],R=t[11],n[8]=M*s+T*c+f*d+R*b,n[9]=M*i+T*a+f*m+R*x,n[10]=M*r+T*l+f*y+R*g,n[11]=M*o+T*u+f*p+R*w,M=t[12],T=t[13],f=t[14],R=t[15],n[12]=M*s+T*c+f*d+R*b,n[13]=M*i+T*a+f*m+R*x,n[14]=M*r+T*l+f*y+R*g,n[15]=M*o+T*u+f*p+R*w,n}function Te(n,e,t,s){let i=e[0],r=e[1],o=e[2],c=e[3],a=i+i,l=r+r,u=o+o,d=i*a,m=i*l,y=i*u,p=r*l,b=r*u,x=o*u,g=c*a,w=c*l,M=c*u,T=s[0],f=s[1],R=s[2];return n[0]=(1-(p+x))*T,n[1]=(m+M)*T,n[2]=(y-w)*T,n[3]=0,n[4]=(m-M)*f,n[5]=(1-(d+x))*f,n[6]=(b+g)*f,n[7]=0,n[8]=(y+w)*R,n[9]=(b-g)*R,n[10]=(1-(d+p))*R,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}function ae(n,e,t=0){let s=e[0],i=e[1],r=e[2],o=e[4],c=e[5],a=e[6],l=e[8],u=e[9],d=e[10],m=d*c-a*u,y=-d*o+a*l,p=u*o-c*l,b=s*m+i*y+r*p;return!b||t>0&&(!Number.isFinite(b)||Math.abs(b)<=t)||(b=1/b,n[0]=m*b,n[1]=y*b,n[2]=p*b,n[3]=(-d*i+r*u)*b,n[4]=(d*s-r*l)*b,n[5]=(-u*s+i*l)*b,n[6]=(a*i-r*c)*b,n[7]=(-a*s+r*o)*b,n[8]=(c*s-i*o)*b),n}function De(n,e){let t=e[0],s=e[1],i=e[2],r=e[3],o=e[4],c=e[5],a=e[6],l=e[7],u=e[8],d=e[9],m=e[10],y=e[11],p=e[12],b=e[13],x=e[14],g=e[15],w=t*c-s*o,M=t*a-i*o,T=t*l-r*o,f=s*a-i*c,R=s*l-r*c,S=i*l-r*a,L=u*b-d*p,k=u*x-m*p,U=u*g-y*p,F=d*x-m*b,h=d*g-y*b,P=m*g-y*x,E=w*P-M*h+T*F+f*U-R*k+S*L;return E?(E=1/E,n[0]=(c*P-a*h+l*F)*E,n[1]=(i*h-s*P-r*F)*E,n[2]=(b*S-x*R+g*f)*E,n[3]=(m*R-d*S-y*f)*E,n[4]=(a*U-o*P-l*k)*E,n[5]=(t*P-i*U+r*k)*E,n[6]=(x*T-p*S-g*M)*E,n[7]=(u*S-m*T+y*M)*E,n[8]=(o*h-c*U+l*L)*E,n[9]=(s*U-t*h-r*L)*E,n[10]=(p*R-b*T+g*w)*E,n[11]=(d*T-u*R-y*w)*E,n[12]=(c*k-o*F-a*L)*E,n[13]=(t*F-s*k+i*L)*E,n[14]=(b*M-p*f-x*w)*E,n[15]=(u*f-d*M+m*w)*E,n):null}function Re(n,e,t,s,i){let r=i[0]*e+i[4]*t+i[8]*s+i[12],o=i[1]*e+i[5]*t+i[9]*s+i[13],c=i[2]*e+i[6]*t+i[10]*s+i[14],a=i[3]*e+i[7]*t+i[11]*s+i[15],l=a!==0?1/a:1;n[0]=r*l,n[1]=o*l,n[2]=c*l}function Le(n,e,t,s,i,r,o,c,a,l,u,d,m,y,p,b,x=0){let g=l-o,w=u-c,M=d-a,T=m-o,f=y-c,R=p-a,S=i*R-r*f,L=r*T-s*R,k=s*f-i*T,U=g*S+w*L+M*k;if(U>-1e-7&&U<1e-7)return!1;let F=1/U,h=n-o,P=e-c,E=t-a,v=F*(h*S+P*L+E*k);if(v<-x||v>1+x)return!1;let B=P*M-E*w,D=E*g-h*M,$=h*w-P*g,A=F*(s*B+i*D+r*$);if(A<-x||v+A>1+x)return!1;let W=F*(T*B+f*D+R*$);if(W>1e-4&&W<b.distance){b.distance=W,b.point=[n+s*W,e+i*W,t+r*W];let _=w*R-M*f,K=M*T-g*R,q=g*f-w*T,G=Math.hypot(_,K,q)||1;return b.normal=[_/G,K/G,q/G],!0}return!1}function Ce(n,e){let t=Array.isArray(n?.nodes)?n.nodes.length:0,s=[];for(let u=0;u<t;u++)s.push(X());if(t===0)return s;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 r=new Set,o=128,c=(u,d,m=0)=>{if(m>o||u<0||u>=t||r.has(u))return;r.add(u);let y=n.nodes[u];if(!y)return;let p=X();if(e&&e[u])p.set(e[u]);else if(y.matrix&&y.matrix.length===16)p.set(y.matrix);else{let x=y.translation||[0,0,0],g=y.rotation||[0,0,0,1],w=y.scale||[1,1,1];Te(p,g,x,w)}let b=s[u];if(d?J(b,d,p):b.set(p),Array.isArray(y.children))for(let x of y.children)typeof x=="number"&&c(x,b,m+1)},a=[],l=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(l&&Array.isArray(l.nodes))a.push(...l.nodes);else for(let u=0;u<t;u++)i.has(u)||a.push(u);for(let u of a)c(u,null);for(let u=0;u<t;u++)!i.has(u)&&!a.includes(u)&&c(u,null);return s}var ve="__THREE_LIVE_REGISTRY__";function ue(){let n=typeof globalThis<"u"?globalThis:{};if(!n[ve]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(n,ve,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{n[ve]=e}}return n[ve]}var Y=ue().plugins;function Ie(n){let e=ue().plugins;e.some(t=>t.name===n.name)||e.push(n),n.onRegister?.()}function Fe(){return ue().plugins}var Ge=["neutral","reinhard","none","aces","agx"];function ye(n){let e=String(n??"").trim().toLowerCase();return Ge.includes(e)?e:"neutral"}function je(n){return Ge.indexOf(ye(n))}function Ye(n){return new TextDecoder().decode(n)}var ke=ue().decoders;function $e(n,e){ke.set(n.toLowerCase(),e)}function le(n){return ke.get(n.toLowerCase())}function _e(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 s=t.getUint32(0,!0);if(s!==1179937895){let m=t.getUint8(0);throw m===123||m===32||m===10||m===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${s.toString(16)}`)}let i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let r=t.getUint32(8,!0),o=12,c=null,a=null;for(;o+8<=r&&o+8<=e.byteLength;){let m=t.getUint32(o,!0),y=t.getUint32(o+4,!0),p=o+8;if(p+m>e.byteLength)throw new Error(`Truncated GLB chunk: required ${p+m} bytes, buffer has ${e.byteLength}`);if(y===1313821514){let b=new Uint8Array(e,p,m),x=Ye(b);c=JSON.parse(x,(g,w)=>g==="__proto__"||g==="constructor"||g==="prototype"?void 0:w)}else y===5130562&&(a=e.slice(p,p+m));o=p+m}if(!c)throw new Error("Missing JSON chunk in GLB");let l=c.extensionsRequired||[];if(l.includes("KHR_draco_mesh_compression")&&!le("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let m of["EXT_meshopt_compression","KHR_meshopt_compression"])if(l.includes(m)&&!le("meshopt"))throw new Error(`Model requires ${m}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(l.includes("KHR_texture_basisu")&&!le("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let u=a||new ArrayBuffer(0),d={gltf:c,bin:u,animations:[]};for(let m of Y)m.onParseGLB?.(d);return d}function ht(n,e,t){return e%4===0?new Float32Array(n,e,t):new Float32Array(n.slice(e,e+t*4))}function Ke(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 Se(n){if(Ke(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return _e(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Ve=`#version 300 es
16
+ */var Yt={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function At(t,e,i,s){if(!i||i.bufferView===void 0)return null;let r=t.bufferViews?.[i.bufferView];if(!r)return null;let a=Number(i.count??0);if(!Number.isInteger(a)||a<=0)return null;let o=i.componentType??5126,l=Yt[o];if(!l)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let n=l*s,h=r.byteStride&&r.byteStride>0?r.byteStride:n,c=(r.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(c)||c<0||h<n||c+(a-1)*h+n>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(o===5126&&h===n&&c%4===0)return new Float32Array(e,c,a*s);let d=new DataView(e),v=i.normalized===!0,x=new Float32Array(a*s);for(let b=0;b<a;b++){let m=c+b*h;for(let M=0;M<s;M++){let y=m+M*l,f;switch(o){case 5126:f=d.getFloat32(y,!0);break;case 5120:f=d.getInt8(y),v&&(f=Math.max(f/127,-1));break;case 5121:f=d.getUint8(y),v&&(f/=255);break;case 5122:f=d.getInt16(y,!0),v&&(f=Math.max(f/32767,-1));break;case 5123:f=d.getUint16(y,!0),v&&(f/=65535);break;default:f=d.getUint32(y,!0),v&&(f/=4294967295)}x[b*s+M]=f}}return x}function Jt(t,e){let i=Number(e.offset?.[0]??0)||0,s=Number(e.offset?.[1]??0)||0,r=Number(e.scale?.[0]??1),a=Number(e.scale?.[1]??1),o=Number(e.rotation??0)||0,l=Math.cos(o),n=Math.sin(o),h=(Number.isFinite(r)?r:1)*l,c=(Number.isFinite(r)?r:1)*n,d=-(Number.isFinite(a)?a:1)*n,v=(Number.isFinite(a)?a:1)*l;for(let x=0;x+1<t.length;x+=2){let b=t[x],m=t[x+1];t[x]=h*b+c*m+i,t[x+1]=d*b+v*m+s}}function yt(t,e,i,s=!0){let r=[],a=null;try{for(let[o,l]of[[35633,e],[35632,i]]){let n=t.createShader(o);if(!n){if(s)throw new Error("Shader allocation failed");return null}if(r.push(n),t.shaderSource(n,l),t.compileShader(n),t.getShaderParameter&&!t.getShaderParameter(n,35713)){if(s)throw new Error(`Shader compile error: ${t.getShaderInfoLog(n)}`);return null}}if(a=t.createProgram(),!a){if(s)throw new Error("Program allocation failed");return null}for(let o of r)t.attachShader(a,o);if(t.linkProgram(a),t.getProgramParameter&&!t.getProgramParameter(a,35714)){let o=s?t.getProgramInfoLog(a):null;if(t.deleteProgram?.(a),a=null,s)throw new Error(`Program link error: ${o}`);return null}return a}finally{for(let o of r)a&&t.detachShader?.(a,o),t.deleteShader?.(o)}}function z(){let t=new Float32Array(16);return t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function xt(t,e,i,s,r){let a=1/Math.tan(e/2);t.fill(0),t[0]=a/i,t[5]=a,t[11]=-1;let o=1/(s-r);return t[10]=(r+s)*o,t[14]=2*r*s*o,t}function vt(t,e,i,s){let[r,a,o]=e,[l,n,h]=s,[c,d,v]=i,x=r-c,b=a-d,m=o-v,M=Math.hypot(x,b,m);M<=1e-5?(x=0,b=0,m=1):(x/=M,b/=M,m/=M);let y=n*m-h*b,f=h*x-l*m,g=l*b-n*x;M=Math.hypot(y,f,g),M<=1e-5?(y=0,f=0,g=0):(y/=M,f/=M,g/=M);let p=b*g-m*f,w=m*y-x*g,P=x*f-b*y;return M=Math.hypot(p,w,P),M<=1e-5?(p=0,w=0,P=0):(p/=M,w/=M,P/=M),t[0]=y,t[1]=p,t[2]=x,t[3]=0,t[4]=f,t[5]=w,t[6]=b,t[7]=0,t[8]=g,t[9]=P,t[10]=m,t[11]=0,t[12]=-(y*r+f*a+g*o),t[13]=-(p*r+w*a+P*o),t[14]=-(x*r+b*a+m*o),t[15]=1,t}function Y(t,e,i){let s=e[0],r=e[1],a=e[2],o=e[3],l=e[4],n=e[5],h=e[6],c=e[7],d=e[8],v=e[9],x=e[10],b=e[11],m=e[12],M=e[13],y=e[14],f=e[15],g=i[0],p=i[1],w=i[2],P=i[3];return t[0]=g*s+p*l+w*d+P*m,t[1]=g*r+p*n+w*v+P*M,t[2]=g*a+p*h+w*x+P*y,t[3]=g*o+p*c+w*b+P*f,g=i[4],p=i[5],w=i[6],P=i[7],t[4]=g*s+p*l+w*d+P*m,t[5]=g*r+p*n+w*v+P*M,t[6]=g*a+p*h+w*x+P*y,t[7]=g*o+p*c+w*b+P*f,g=i[8],p=i[9],w=i[10],P=i[11],t[8]=g*s+p*l+w*d+P*m,t[9]=g*r+p*n+w*v+P*M,t[10]=g*a+p*h+w*x+P*y,t[11]=g*o+p*c+w*b+P*f,g=i[12],p=i[13],w=i[14],P=i[15],t[12]=g*s+p*l+w*d+P*m,t[13]=g*r+p*n+w*v+P*M,t[14]=g*a+p*h+w*x+P*y,t[15]=g*o+p*c+w*b+P*f,t}function Tt(t,e,i,s){let r=e[0],a=e[1],o=e[2],l=e[3],n=r+r,h=a+a,c=o+o,d=r*n,v=r*h,x=r*c,b=a*h,m=a*c,M=o*c,y=l*n,f=l*h,g=l*c,p=s[0],w=s[1],P=s[2];return t[0]=(1-(b+M))*p,t[1]=(v+g)*p,t[2]=(x-f)*p,t[3]=0,t[4]=(v-g)*w,t[5]=(1-(d+M))*w,t[6]=(m+y)*w,t[7]=0,t[8]=(x+f)*P,t[9]=(m-y)*P,t[10]=(1-(d+b))*P,t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1,t}function nt(t,e,i=0){let s=e[0],r=e[1],a=e[2],o=e[4],l=e[5],n=e[6],h=e[8],c=e[9],d=e[10],v=d*l-n*c,x=-d*o+n*h,b=c*o-l*h,m=s*v+r*x+a*b;return!m||i>0&&(!Number.isFinite(m)||Math.abs(m)<=i)||(m=1/m,t[0]=v*m,t[1]=x*m,t[2]=b*m,t[3]=(-d*r+a*c)*m,t[4]=(d*s-a*h)*m,t[5]=(-c*s+r*h)*m,t[6]=(n*r-a*l)*m,t[7]=(-n*s+a*o)*m,t[8]=(l*s-r*o)*m),t}function St(t,e){let i=e[0],s=e[1],r=e[2],a=e[3],o=e[4],l=e[5],n=e[6],h=e[7],c=e[8],d=e[9],v=e[10],x=e[11],b=e[12],m=e[13],M=e[14],y=e[15],f=i*l-s*o,g=i*n-r*o,p=i*h-a*o,w=s*n-r*l,P=s*h-a*l,E=r*h-a*n,O=c*m-d*b,U=c*M-v*b,S=c*y-x*b,T=d*M-v*m,L=d*y-x*m,C=v*y-x*M,u=f*C-g*L+p*T+w*S-P*U+E*O;return u?(u=1/u,t[0]=(l*C-n*L+h*T)*u,t[1]=(r*L-s*C-a*T)*u,t[2]=(m*E-M*P+y*w)*u,t[3]=(v*P-d*E-x*w)*u,t[4]=(n*S-o*C-h*U)*u,t[5]=(i*C-r*S+a*U)*u,t[6]=(M*p-b*E-y*g)*u,t[7]=(c*E-v*p+x*g)*u,t[8]=(o*L-l*S+h*O)*u,t[9]=(s*S-i*L-a*O)*u,t[10]=(b*P-m*p+y*f)*u,t[11]=(d*p-c*P-x*f)*u,t[12]=(l*U-o*T-n*O)*u,t[13]=(i*T-s*U+r*O)*u,t[14]=(m*g-b*w-M*f)*u,t[15]=(c*w-d*g+v*f)*u,t):null}function Pt(t,e,i,s,r){let a=r[0]*e+r[4]*i+r[8]*s+r[12],o=r[1]*e+r[5]*i+r[9]*s+r[13],l=r[2]*e+r[6]*i+r[10]*s+r[14],n=r[3]*e+r[7]*i+r[11]*s+r[15],h=n!==0?1/n:1;t[0]=a*h,t[1]=o*h,t[2]=l*h}function Lt(t,e,i,s,r,a,o,l,n,h,c,d,v,x,b,m,M=0){let y=h-o,f=c-l,g=d-n,p=v-o,w=x-l,P=b-n,E=r*P-a*w,O=a*p-s*P,U=s*w-r*p,S=y*E+f*O+g*U;if(S>-1e-7&&S<1e-7)return!1;let T=1/S,L=t-o,C=e-l,u=i-n,R=T*(L*E+C*O+u*U);if(R<-M||R>1+M)return!1;let H=C*g-u*f,J=u*y-L*g,N=L*f-C*y,F=T*(s*H+r*J+a*N);if(F<-M||R+F>1+M)return!1;let D=T*(p*H+w*J+P*N);if(D>1e-4&&D<m.distance){m.distance=D,m.point=[t+s*D,e+r*D,i+a*D];let V=f*P-g*w,_=g*p-y*P,k=y*w-f*p,X=Math.hypot(V,_,k)||1;return m.normal=[V/X,_/X,k/X],!0}return!1}function Nt(t,e){let i=Array.isArray(t?.nodes)?t.nodes.length:0,s=[];for(let c=0;c<i;c++)s.push(z());if(i===0)return s;let r=new Set;for(let c of t.nodes)if(Array.isArray(c.children))for(let d of c.children)r.add(d);let a=new Set,o=128,l=(c,d,v=0)=>{if(v>o||c<0||c>=i||a.has(c))return;a.add(c);let x=t.nodes[c];if(!x)return;let b=z();if(e&&e[c])b.set(e[c]);else if(x.matrix&&x.matrix.length===16)b.set(x.matrix);else{let M=x.translation||[0,0,0],y=x.rotation||[0,0,0,1],f=x.scale||[1,1,1];Tt(b,y,M,f)}let m=s[c];if(d?Y(m,d,b):m.set(b),Array.isArray(x.children))for(let M of x.children)typeof M=="number"&&l(M,m,v+1)},n=[],h=t.scenes&&t.scenes[t.scene!==void 0?t.scene:0];if(h&&Array.isArray(h.nodes))n.push(...h.nodes);else for(let c=0;c<i;c++)r.has(c)||n.push(c);for(let c of n)l(c,null);for(let c=0;c<i;c++)!r.has(c)&&!n.includes(c)&&l(c,null);return s}var bt="__THREE_LIVE_REGISTRY__";function ut(){let t=typeof globalThis<"u"?globalThis:{};if(!t[bt]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(t,bt,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{t[bt]=e}}return t[bt]}var W=ut().plugins;function Ft(t){let e=ut().plugins;e.some(i=>i.name===t.name)||e.push(t),t.onRegister?.()}function Vt(){return ut().plugins}var Et=["neutral","reinhard","none","aces","agx"];function mt(t){let e=String(t??"").trim().toLowerCase();return Et.includes(e)?e:"neutral"}function kt(t){return Et.indexOf(mt(t))}function Bt(t){return new TextDecoder().decode(t)}var _t=ut().decoders;function Ot(t,e){_t.set(t.toLowerCase(),e)}function ht(t){return _t.get(t.toLowerCase())}function wt(t){let e=ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,i=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let s=i.getUint32(0,!0);if(s!==1179937895){let v=i.getUint8(0);throw v===123||v===32||v===10||v===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${s.toString(16)}`)}let r=i.getUint32(4,!0);if(r!==2)throw new Error(`Unsupported GLB version: ${r}`);let a=i.getUint32(8,!0),o=12,l=null,n=null;for(;o+8<=a&&o+8<=e.byteLength;){let v=i.getUint32(o,!0),x=i.getUint32(o+4,!0),b=o+8;if(b+v>e.byteLength)throw new Error(`Truncated GLB chunk: required ${b+v} bytes, buffer has ${e.byteLength}`);if(x===1313821514){let m=new Uint8Array(e,b,v),M=Bt(m);l=JSON.parse(M,(y,f)=>y==="__proto__"||y==="constructor"||y==="prototype"?void 0:f)}else x===5130562&&(n=e.slice(b,b+v));o=b+v}if(!l)throw new Error("Missing JSON chunk in GLB");let h=l.extensionsRequired||[];if(h.includes("KHR_draco_mesh_compression")&&!ht("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let v of["EXT_meshopt_compression","KHR_meshopt_compression"])if(h.includes(v)&&!ht("meshopt"))throw new Error(`Model requires ${v}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(h.includes("KHR_texture_basisu")&&!ht("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let c=n||new ArrayBuffer(0),d={gltf:l,bin:c,animations:[]};for(let v of W)v.onParseGLB?.(d);return d}function Zt(t,e,i){return e%4===0?new Float32Array(t,e,i):new Float32Array(t.slice(e,e+i*4))}function Ut(t){return typeof t=="object"&&t!==null&&"gltf"in t&&typeof t.gltf=="object"&&t.gltf!==null&&"bin"in t&&(t.bin instanceof ArrayBuffer||ArrayBuffer.isView(t.bin))}function Ct(t){if(Ut(t))return t;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return wt(t);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Ht=`#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
- }`,qe=`#version 300 es
51
+ }`,Qt=`#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,11 +239,11 @@ color=applyToneMapping(color,uToneMapping);
242
239
  float outAlpha=base.a;
243
240
  /*XRD_O*/
244
241
  fragColor=vec4(color,outAlpha);
245
- }`;function mt(n,e,t=1){e=ye(e);let s=Number.isFinite(t)?Math.max(0,t):1,i=Math.max(0,(Number(n[0])||0)*s),r=Math.max(0,(Number(n[1])||0)*s),o=Math.max(0,(Number(n[2])||0)*s),c=g=>Math.max(0,Math.min(1,g));if(e==="none")return[c(i),c(r),c(o)];if(e==="reinhard")return[i/(i+1),r/(r+1),o/(o+1)];if(e==="aces"){let g=w=>{let M=w*.6;return c(M*(2.51*M+.03)/(M*(2.43*M+.59)+.14))};return[g(i),g(r),g(o)]}if(e==="agx"){let g=.84247906*i+.0784336*r+.07922375*o,w=.04232824*i+.87846864*r+.07916613*o,M=.04237565*i+.0784336*r+.87914297*o,T=F=>{let h=c((Math.log2(Math.max(F,1e-6))+12.47393)/16.5),P=h*h,E=P*P;return 15.5*E*P-40.14*E*h+31.96*E-6.868*P*h+.4298*P+.1191*h-.00232},f=T(g),R=T(w),S=T(M),L=1.196879*f-.09802088*R-.09902974*S,k=-.05289685*f+1.15190313*R-.09896118*S,U=-.05297164*f-.09804345*R+1.15107367*S;return[c(Math.pow(Math.max(L,0),2.2)),c(Math.pow(Math.max(k,0),2.2)),c(Math.max(0,Math.pow(Math.max(U,0),2.2)))]}let a=.76,l=.15,u=Math.min(i,r,o),d=u<.08?u-6.25*u*u:.04;i-=d,r-=d,o-=d;let m=Math.max(i,r,o);if(m<a)return[c(i),c(r),c(o)];let y=1-a,p=1-y*y/(m+y-a),b=p/m;i*=b,r*=b,o*=b;let x=1-1/(l*(m-p)+1);return[c(i+(p-i)*x),c(r+(p-r)*x),c(o+(p-o)*x)]}var Ze=`#version 300 es
242
+ }`;function te(t,e,i=1){e=mt(e);let s=Number.isFinite(i)?Math.max(0,i):1,[r,a,o]=[0,1,2].map(m=>Math.max(0,(Number(t[m])||0)*s)),l=m=>Math.max(0,Math.min(1,m)),n=m=>[m(r),m(a),m(o)];if(e==="none")return n(l);if(e==="reinhard")return n(m=>m/(m+1));if(e==="aces")return n(m=>{let M=m*.6;return l(M*(2.51*M+.03)/(M*(2.43*M+.59)+.14))});if(e==="agx"){let[m,M,y]=[.84247906*r+.0784336*a+.07922375*o,.04232824*r+.87846864*a+.07916613*o,.04237565*r+.0784336*a+.87914297*o].map(f=>{let g=l((Math.log2(Math.max(f,1e-6))+12.47393)/16.5),p=g*g,w=p*p;return 15.5*w*p-40.14*w*g+31.96*w-6.868*p*g+.4298*p+.1191*g-.00232});return[1.196879*m-.09802088*M-.09902974*y,-.05289685*m+1.15190313*M-.09896118*y,-.05297164*m-.09804345*M+1.15107367*y].map(f=>l(Math.pow(Math.max(f,0),2.2)))}let h=Math.min(r,a,o),c=h<.08?h-6.25*h*h:.04;[r,a,o]=n(m=>m-c);let d=Math.max(r,a,o);if(d<.76)return n(l);let v=1-.0576/(d-.52),x=v/d,b=1-1/(.15*(d-v)+1);return n(m=>l(m*x+(v-m*x)*b))}var ee=`#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);}`,Je=`#version 300 es
245
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,ie=`#version 300 es
249
246
  precision highp float;
250
247
  uniform vec4 uColorId;
251
248
  out vec4 fragColor;
252
- void main(){fragColor=uColorId;}`;function Pe(n,e,t){let s={};for(let i of t)s[i]=n.getUniformLocation(e,i);return s}var Ne=["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 Ue(){let n=ue().xrDepthShader;return{fs:qe.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Ne,...n.uniformNames]:Ne}}function Qe(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 we(n,e,t,s,i,r,o,c){if(s===void 0||!e.accessors?.[s])return null;let a=Me(e,t,e.accessors[s],r);if(!a)return null;c&&(a=a.slice(),Ae(a,c));let l=n.createBuffer();return o.push(l),n.bindBuffer(34962,l),n.bufferData(34962,a,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,r,5126,!1,0,0),a}function Ee(n){let e=Number(n);return Number.isFinite(e)?Math.max(0,e):1}function We(n,e,t){let s=Ue(),i=Ve,r=s.fs,o=!1;for(let a of Y)if(a.onResolveShader){let l=a.onResolveShader(e,t,i,r);l&&(i=l.vs,r=l.fs,o=!0)}let c=o?pe(n,i,r):null;return{program:c,uniforms:c?Pe(n,c,s.uniforms):null}}function et(n,e,t){let s=e.instanceMatrices;if(!s||s.length<16||typeof n.vertexAttribDivisor!="function"||typeof n.drawElementsInstanced!="function")return!1;let i=s.length>>4,r=e.instanceColors,o=new Float32Array(i*20);for(let a=0;a<i;a++)o.set(s.subarray(a*16,a*16+16),a*20),o[a*20+16]=r?r[a*3]:1,o[a*20+17]=r?r[a*3+1]:1,o[a*20+18]=r?r[a*3+2]:1,o[a*20+19]=1;let c=n.createBuffer();t.push(c),n.bindBuffer(34962,c),n.bufferData(34962,o,35044);for(let a=0;a<5;a++)n.enableVertexAttribArray(8+a),n.vertexAttribPointer(8+a,4,5126,!1,80,a*16),n.vertexAttribDivisor(8+a,1);return!0}function tt(n,e){let t=n.materials?.[e?.material];if(!t)return null;let s=[t.pbrMetallicRoughness?.baseColorTexture,t.pbrMetallicRoughness?.metallicRoughnessTexture,t.normalTexture,t.occlusionTexture,t.emissiveTexture];for(let i of s){let r=i?.extensions?.KHR_texture_transform;if(r&&typeof r=="object")return r}return null}var ft=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),He=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function ge(n,e){e.indices?n.drawElements(4,e.indexCount,e.indexType,0):n.drawArrays(4,0,e.indexCount)}function Oe(n,e){let t=n?.pbrMetallicRoughness,s=t?.baseColorFactor,i=n?.extensions?.KHR_materials_clearcoat,r=o=>o!==void 0&&e[o.index]?e[o.index]:null;return{baseColor:s?[s[0],s[1],s[2],s[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:r(t?.baseColorTexture),metallicRoughnessTexture:r(t?.metallicRoughnessTexture),normalTexture:r(n?.normalTexture),normalScale:n?.normalTexture?.scale??1,occlusionTexture:r(n?.occlusionTexture),occlusionStrength:n?.occlusionTexture?.strength??1,isTransmissive:(n?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Xe(n,e,t){let s=new Set,i=r=>{r&&!s.has(r)&&(s.add(r),n.deleteTexture(r))};for(let r of e)for(let o of r.primitives){if(o.vao&&n.deleteVertexArray(o.vao),o.buffers)for(let a of o.buffers)n.deleteBuffer(a);i(o.texture),i(o.metallicRoughnessTexture),i(o.normalTexture),i(o.occlusionTexture);let c=new Set;o.customProgram&&c.add(o.customProgram);for(let a of o.programCache?.values()??[])a.program&&c.add(a.program);for(let a of c)n.deleteProgram(a)}if(t)for(let r of t)i(r)}function Be(n,e,t=He,s){let i={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return nt(n,e,t,s,i)}catch(r){let o=i.mesh&&!i.meshes.includes(i.mesh)?[...i.meshes,i.mesh]:i.meshes;Xe(n,o,i.gpuTextures),i.vao&&n.deleteVertexArray(i.vao);for(let c of i.buffers)n.deleteBuffer(c);throw r}}function nt(n,e,t,s,i){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:r}=e,o=le("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(r,e);let c=e.bin,a=[];i.meshes=a;let l=[],u=r.extensions?.KHR_materials_variants;u&&Array.isArray(u.variants)&&u.variants.forEach((h,P)=>{l.push(typeof h?.name=="string"&&h.name?h.name:`Variant_${P}`)});let d=Ce(r),m=[];if(Array.isArray(r.nodes))for(let h=0;h<r.nodes.length;h++){let P=r.nodes[h];P.mesh!==void 0&&r.meshes&&r.meshes[P.mesh]&&m.push({node:P,nodeIdx:h,meshIdx:P.mesh})}let y=m.length>0?m:(r.meshes||[]).map((h,P)=>({node:h,nodeIdx:-1,meshIdx:P})),p=[];if(Array.isArray(e.lights)&&e.lights.length>0)p.push(...e.lights);else if(r.extensions?.KHR_lights_punctual?.lights){let h=r.extensions.KHR_lights_punctual.lights;for(let P of h){let E=P.type==="directional"?"directional":P.type==="point"?"point":"ambient";p.push({type:E,color:P.color||[1,1,1],intensity:P.intensity!==void 0?P.intensity:1})}}if(p.length===0&&(p.push({type:"ambient",color:[1,1,1],intensity:.35}),p.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),y.length>t.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${t.maxMeshes}). Found: ${y.length}`);let b=[];if(i.gpuTextures=b,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 h=0;h<r.textures.length;h++){let P=r.textures[h],E=r.images[P.source];if(E){let v=n.createTexture();if(n.bindTexture(3553,v),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),E.bufferView!==void 0){let B=r.bufferViews[E.bufferView],D=c.slice(B.byteOffset||0,(B.byteOffset||0)+B.byteLength),$=new Blob([D],{type:E.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap($).then(A=>{n.bindTexture(3553,v),n.texImage2D(3553,0,6408,6408,5121,A),n.generateMipmap(3553),s?.()}).catch(()=>{})}else if(E.uri){let B=Qe(E.uri);if(B){let D=new Image;D.crossOrigin="anonymous",D.referrerPolicy="no-referrer",D.onload=()=>{n.bindTexture(3553,v),n.texImage2D(3553,0,6408,6408,5121,D),n.generateMipmap(3553),s?.()},D.src=B}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",E.uri)}b.push(v)}else b.push(null)}}let x=[1/0,1/0,1/0],g=[-1/0,-1/0,-1/0],w=0,M=0;for(let h=0;h<y.length;h++){let P=y[h],E=r.meshes[P.meshIdx],v=P.nodeIdx>=0?d[P.nodeIdx]:X(),B=new Float32Array(9);ae(B,v);let D={name:P.node.name||E.name||`Mesh_${P.meshIdx}`,nodeIndex:P.nodeIdx,transform:v,normalMatrix:B,primitives:[],extras:P.node.extras||E.extras};i.mesh=D;let $=P.node?.extensions?.EXT_mesh_gpu_instancing;if($&&$.attributes&&typeof $.attributes=="object"){let A=$.attributes,W=A.TRANSLATION!==void 0?r.accessors?.[A.TRANSLATION]:null,_=A.ROTATION!==void 0?r.accessors?.[A.ROTATION]:null,K=A.SCALE!==void 0?r.accessors?.[A.SCALE]:null,q=A._COLOR_0!==void 0?r.accessors?.[A._COLOR_0]:null,G=Number(W?.count??_?.count??K?.count??0);if(!Number.isFinite(G)||G<0||G>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${G}`);if(G>0){let z=(N,O)=>{if(!N||N.bufferView===void 0||!r.bufferViews?.[N.bufferView])return null;let te=N.componentType??5126,re=j=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${j})`),null);if(te!==5120&&te!==5121&&te!==5122&&te!==5123&&te!==5126)return re(`componentType ${te}`);if(!(Number(N.count)>=G))return re(`count ${N.count} < ${G}`);let C=null;try{C=Me(r,c,{...N,count:G},O)}catch{return re("out of bounds")}return!C||!C.every(Number.isFinite)?re("non-finite value"):C},I=z(W,3),ne=z(_,4),H=z(K,3),Q=q?.type==="VEC4"?4:3,ee=z(q,Q),ie=new Float32Array(G*16),oe=X();for(let N=0;N<G;N++){let O=I?[I[N*3],I[N*3+1],I[N*3+2]]:[0,0,0],te=ne?[ne[N*4],ne[N*4+1],ne[N*4+2],ne[N*4+3]]:[0,0,0,1],re=H?[H[N*3],H[N*3+1],H[N*3+2]]:[1,1,1];Te(oe,te,O,re),ie.set(oe,N*16)}if(D.instanceMatrices=ie,ee){let N=new Float32Array(G*3);for(let O=0;O<G;O++)N[O*3]=ee[O*Q],N[O*3+1]=ee[O*Q+1],N[O*3+2]=ee[O*Q+2];D.instanceColors=N}}}for(let A of E.primitives||[]){if(A.extensions?.KHR_draco_mesh_compression){let C=le("draco");C&&C.decodePrimitive(r,A,c)}let W=[],_=n.createVertexArray();i.vao=_,i.buffers=W,n.bindVertexArray(_);let K=et(n,D,W),q=r.accessors[A.attributes.POSITION],G=Number(q?.count??0);if(!Number.isFinite(G)||G<0||w+G>t.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${t.maxVertices}).`);if(w+=G,q?.min&&q?.max){let C=j=>{for(let V=0;V<3;V++){let Z=j[12+V],se=j[12+V];for(let ce=0;ce<3;ce++){let fe=j[ce*4+V]*q.min[ce],de=j[ce*4+V]*q.max[ce];Z+=fe<de?fe:de,se+=fe>de?fe:de}Z<x[V]&&(x[V]=Z),se>g[V]&&(g[V]=se)}};if(D.instanceMatrices&&D.instanceMatrices.length>=16){let j=D.instanceMatrices.length>>4,V=X();for(let Z=0;Z<j;Z++){let se=D.instanceMatrices.subarray(Z*16,Z*16+16);J(V,v,se),C(V)}}else C(v)}let z=we(n,r,c,A.attributes.POSITION,0,3,W);we(n,r,c,A.attributes.NORMAL,1,3,W),we(n,r,c,A.attributes.TEXCOORD_0,2,2,W,tt(r,A));let I=0,ne=5123,H=null;if(A.indices!==void 0){let C=r.accessors[A.indices],V=(r.bufferViews[C.bufferView].byteOffset||0)+(C.byteOffset||0);if(I=Number(C.count??0),!Number.isFinite(I)||I<0||M+I>t.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${t.maxIndices}).`);M+=I,ne=C.componentType===5125?5125||5125:5123||5123;let Z=n.createBuffer();W.push(Z),n.bindBuffer(34963,Z),C.componentType===5125?(H=new Uint32Array(c,V,C.count),n.bufferData(34963,H,35044)):C.componentType===5121?(H=Uint16Array.from(new Uint8Array(c,V,C.count)),n.bufferData(34963,H,35044)):(H=V%2===0?new Uint16Array(c,V,C.count):new Uint16Array(c.slice(V,V+C.count*2)),n.bufferData(34963,H,35044))}else I=q.count;let Q={};for(let C of Y)if(C.onBuildPrimitiveVAO){let j=C.onBuildPrimitiveVAO(n,_,A,r,c);j&&(Q[C.name]=j)}n.bindVertexArray(null);let ee=r.materials&&A.material!==void 0?r.materials[A.material]:null,{program:ie,uniforms:oe}=We(n,A,ee),N=Oe(ee,b),O=!!(ee?.extensions?.KHR_materials_transmission||Q.materials?.isTransmissive),te=A.extensions?.KHR_materials_variants?.mappings,re=Array.isArray(te)?te.filter(C=>C&&typeof C.material=="number"&&Array.isArray(C.variants)).map(C=>({material:C.material|0,variants:C.variants.map(j=>Number(j)|0)})):void 0;D.primitives.push({vao:_,instanced:K,indexCount:I,indexType:ne,...N,positions:z,indices:H,buffers:W,materialIndex:A.material,defaultMaterialIndex:A.material,variantMappings:re,primitiveDef:A,programCache:new Map([[A.material??-1,{program:ie,uniforms:oe}]]),pluginData:Q,customProgram:ie,customUniforms:oe,isTransmissive:O})}a.push(D)}isFinite(x[0])||(x=[-1,-1,-1]),isFinite(g[0])||(g=[1,1,1]);let T=[(x[0]+g[0])/2,(x[1]+g[1])/2,(x[2]+g[2])/2],f=g[0]-x[0],R=g[1]-x[1],S=g[2]-x[2],L=Math.max(Math.hypot(f,R,S)/2,.5),k=[x[0],x[1],x[2]],U=[g[0],g[1],g[2]],F=e.animations;if(!F){for(let h of Y)if(h.onParseGLB?.(e),e.animations){F=e.animations;break}}return F||(F=[]),{meshes:a,bounds:{center:T,radius:L,min:k,max:U},lights:p,animations:F,worldMatrices:d,gpuTextures:b,availableVariants:l}}function he(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 me=class{constructor(e,t,s){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=X();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=X();this.viewMatrix=X();this.activeViewMatrix=null;this.modelMatrix=X();this.mvpMatrix=X();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:X(),rawValueToMeters:.001,format:0};this.container=e;let i,r;if(t&&typeof t.getContext=="function"?(i=t,r=s):(r=t,i=r?.canvas),!i){let a=e.querySelector("canvas");a||(a=document.createElement("canvas"),a.style.width="100%",a.style.height="100%",a.style.display="block",a.style.touchAction="none",e.prepend(a)),i=a}this.canvas=i,this.opts=r||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let o=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!o:o&&(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=Ee(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=ye(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){$e(e,t)}static getDecoder(e){return le(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=Ue();this.renderProg=pe(e,Ve,t.fs),this.pickProg=pe(e,Ze,Je),this.uRender=Pe(e,this.renderProg,t.uniforms),this.uPick=Pe(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of Y)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),s=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=s,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,s,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,s),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 s=this.gl,i=Math.max(1,e),r=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=r,s.bindTexture(3553,this.pickTexture),s.texImage2D(3553,0,6408,i,r,0,6408,5121,null),s.bindRenderbuffer(36161,this.pickDepth),s.renderbufferStorage(36161,33189,i,r)}loadGLBData(e,t){this.lastGlbData=e,this.lastLimits=t;let{meshes:s,bounds:i,lights:r,animations:o,worldMatrices:c,gpuTextures:a,availableVariants:l}=Be(this.gl,e,t,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=s,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=r,this.animations=o||[],this.worldMatrices=c||[],this.gpuTextures=a||[],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 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 Y)m.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=Ee(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(_e(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(Se(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let s=Se(e),{meshes:i}=Be(this.gl,s,He,()=>this.render());if(t)for(let r of i)r.transform[12]+=t[0],r.transform[13]+=t[1],r.transform[14]+=t[2],ae(r.normalMatrix,r.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(e,t,s,i=1){this.clearColor=[e,t,s,i]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let s=this.meshes[t],i;e instanceof Map?i=e.get(s.name)??e.get(t):Array.isArray(e)?i=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,s.name)?i=e[s.name]:Object.prototype.hasOwnProperty.call(e,t)&&(i=e[t])),i&&i.length===16&&(s.transform.set(i),ae(s.normalMatrix,s.transform))}}bindLights(e=this.uRender){let t=this.gl,s=[.28,.28,.28],i=[],r=[],o=[],c=[];for(let a of this.lights){let l=a.color||[1,1,1],u=a.intensity!==void 0?a.intensity:1;if(a.type==="ambient")s=[l[0]*u,l[1]*u,l[2]*u];else if(a.type==="directional"&&i.length<6){let d=a.direction||[.5,1,.8];i.push(d[0],d[1],d[2]),r.push(l[0]*u,l[1]*u,l[2]*u)}else if(a.type==="point"&&o.length<6){let d=a.position||[0,0,0];o.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),r.push(1,1,1)),t.uniform3fv(e.uAmbientColor,s),t.uniform1i(e.uNumDirLights,i.length/3),i.length>0&&(t.uniform3fv(e.uDirLightDir,i),t.uniform3fv(e.uDirLightColor,r)),t.uniform1i(e.uNumPointLights,o.length/3),o.length>0&&(t.uniform3fv(e.uPointLightPos,o),t.uniform3fv(e.uPointLightColor,c)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Ee(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=ye(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of Y)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of Y)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,s=this.currDistance;return{theta:e,phi:t,radius:s,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${s.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,s)=>{let i=this.meshes.flatMap(u=>u.primitives.filter(d=>d.materialIndex===s||e.length===1&&d.materialIndex===void 0)),r=i[0],o=r?[...r.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],c=r?r.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,a=r?r.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,l={baseColorFactor:o,metallicFactor:c,roughnessFactor:a,setBaseColorFactor:u=>{let d=[u[0],u[1],u[2],u[3]??1];l.baseColorFactor=d,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=d);for(let m of i)m.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_${s}`,pbrMetallicRoughness:l}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(s=>s.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==="",s=-1;if(t)this.activeVariantName=null;else{if(s=this.availableVariants.indexOf(e),s<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let r of this.meshes)for(let o of r.primitives){let c=o.defaultMaterialIndex;if(!t&&Array.isArray(o.variantMappings)){for(let l of o.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(s)){c=l.material;break}}let a=c!==void 0?i[c]:void 0;o.materialIndex=a?c:void 0,Object.assign(o,Oe(a,this.gpuTextures)),this.applyPrimitiveProgram(o,o.materialIndex,a??null)}return!0}applyPrimitiveProgram(e,t,s){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let i=t??-1,r=e.programCache.get(i);r||(r=We(this.gl,{...e.primitiveDef,material:t},s),e.programCache.set(i,r)),e.customProgram=r.program,e.customUniforms=r.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 Y)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,s){this.customTarget=[e,t,s],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,s=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(s,e))}setCamera(e,t,s,i){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),s!==void 0&&s>0&&(this.targetDistance=this.clampDistance(s)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(e,t,s,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),s!==void 0&&s>0){let r=this.clampDistance(s);this.initialDistance=r,this.customDistance=!0,this.targetDistance=r,this.currDistance=r}else if(i!==void 0&&i>0){let r=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=r,this.customDistance=!0,this.targetDistance=r,this.currDistance=r}else{this.customDistance=!1;let r=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=r,this.targetDistance=r,this.currDistance=r}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 s=X();J(s,this.projMatrix,this.viewMatrix);let[i,r,o]=e,c=t?t[0]:0,a=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],r=u[1]*e[0]+u[5]*e[1]+u[9]*e[2]+u[13],o=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],a=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=s[0]*i+s[4]*r+s[8]*o+s[12],m=s[1]*i+s[5]*r+s[9]*o+s[13],y=s[2]*i+s[6]*r+s[10]*o+s[14],p=s[3]*i+s[7]*r+s[11]*o+s[15];if(p<=1e-4)return{x:0,y:0,z:1,visible:!1};let b=d/p,x=m/p,g=y/p,w=this.canvas.getBoundingClientRect(),M=w.width||this.canvas.clientWidth||this.canvas.width||300,T=w.height||this.canvas.clientHeight||this.canvas.height||150,f=(b*.5+.5)*M,R=(-x*.5+.5)*T,S=b>=-1.1&&b<=1.1&&x>=-1.1&&x<=1.1&&g>=-1&&g<=1;if(S&&t){let[L,k,U]=he(this),F=[i-L,r-k,o-U];c*F[0]+a*F[1]+l*F[2]>.05&&(S=!1)}return{x:f,y:R,z:g,visible:S}}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 s=this.activePointers.get(t.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=t.clientX-s.x,r=t.clientY-s.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,r),this.isPanning||t.button===2||t.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],c=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],a=this.customTarget?[...this.customTarget]:[...this.bounds.center],l=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;a[0]+=(-i*o[0]+r*c[0])*l,a[1]+=(-i*o[1]+r*c[1])*l,a[2]+=(-i*o[2]+r*c[2])*l,this.customTarget=a}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+r*.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 s=e.getBoundingClientRect(),i=Math.floor((t.clientX-s.left)*(e.width/Math.max(s.width,1))),r=Math.floor((t.clientY-s.top)*(e.height/Math.max(s.height,1)));this.performMeshPick(i,r,!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 s=Math.exp(t.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*s)},e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=t=>{let s=t.detail||{};s.reset?this.resetCamera():this.setCamera(s.theta,s.phi,s.distance,s.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 s=typeof performance<"u"?performance.now():Date.now();switch(t.key){case"ArrowLeft":this.lastInteractionTime=s,this.targetTheta=this.clampTheta(this.targetTheta-.1),t.preventDefault();break;case"ArrowRight":this.lastInteractionTime=s,this.targetTheta=this.clampTheta(this.targetTheta+.1),t.preventDefault();break;case"ArrowUp":this.lastInteractionTime=s,this.targetPhi=this.clampPhi(this.targetPhi+.08),t.preventDefault();break;case"ArrowDown":this.lastInteractionTime=s,this.targetPhi=this.clampPhi(this.targetPhi-.08),t.preventDefault();break;case"+":case"=":{this.lastInteractionTime=s,this.targetDistance=this.clampDistance(this.targetDistance*.9),t.preventDefault();break}case"-":case"_":{this.lastInteractionTime=s,this.targetDistance=this.clampDistance(this.targetDistance*1.1),t.preventDefault();break}case"Home":this.lastInteractionTime=s,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 s=this.canvas,i=s.getBoundingClientRect(),r=s.width||300,o=s.height||300,c=i.width>0?Math.floor((e-i.left)*(r/i.width)):Math.floor(e),a=i.height>0?Math.floor((t-i.top)*(o/i.height)):Math.floor(t);return this.performMeshPick(c,a,!1)}performMeshPick(e,t,s=!0){if(this.meshes.length===0)return null;let i=this.gl,r=Math.max(1,this.canvas.width||300),o=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,r);let c=X();J(c,this.projMatrix,this.viewMatrix);let a=[],l=Math.max(0,Math.min(r-1,e)),u=Math.max(0,Math.min(o-1,o-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==r||this.pickFboHeight!==o)&&this.resizePickingFbo(r,o),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,r,o),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let S=0;S<this.meshes.length;S++){let L=this.meshes[S];if(L.visible===!1||L.isPluginMesh)continue;let k=S+1,U=(k&255)/255,F=(k>>8&255)/255,h=(k>>16&255)/255;i.uniform4f(this.uPick.uColorId,U,F,h,1),J(this.modelMatrix,this.modelRootMatrix,L.transform);let P=L.instanceMatrices;if(P&&P.length>=16){let E=P.length>>4,v=X();for(let B of L.primitives){i.bindVertexArray(B.vao);for(let D=0;D<E;D++)J(v,this.modelMatrix,P.subarray(D*16,D*16+16)),J(this.mvpMatrix,c,v),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),ge(i,B)}}else{J(this.mvpMatrix,c,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let E of L.primitives)i.bindVertexArray(E.vao),ge(i,E)}}let f=new Uint8Array(4);i.readPixels(l,u,1,1,6408,5121,f),i.bindFramebuffer(36160,null);let R=f[0]+(f[1]<<8)+(f[2]<<16);R>0&&R<=this.meshes.length&&(a=[this.meshes[R-1]])}a.length===0&&(a=this.meshes.filter(f=>f.visible!==!1));let d=null,m=1/0,y=[0,0,0],p=[0,1,0],[b,x,g]=he(this),w=X();for(let f of a){J(w,this.modelRootMatrix,f.transform);let R=f.instanceMatrices,S=R&&R.length>=16?R.length>>4:1;for(let L=0;L<S;L++){R&&R.length>=16?J(this.modelMatrix,w,R.subarray(L*16,L*16+16)):this.modelMatrix.set(w),J(this.mvpMatrix,c,this.modelMatrix);let k=X();if(!De(k,this.mvpMatrix))continue;let U=(l+.5)/r*2-1,F=(u+.5)/o*2-1,h=[0,0,0],P=[0,0,0];Re(h,U,F,-1,k),Re(P,U,F,1,k);let E=P[0]-h[0],v=P[1]-h[1],B=P[2]-h[2],D=Math.hypot(E,v,B)||1,$=E/D,A=v/D,W=B/D,_={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((q=>{for(let G of f.primitives){if(!G.positions)continue;let z=G.positions,I=G.indices,ne=Math.floor(I?I.length/3:z.length/9);for(let H=0;H<ne;H++){let Q=I?I[H*3]:H*3,ee=I?I[H*3+1]:H*3+1,ie=I?I[H*3+2]:H*3+2;Le(h[0],h[1],h[2],$,A,W,z[Q*3],z[Q*3+1],z[Q*3+2],z[ee*3],z[ee*3+1],z[ee*3+2],z[ie*3],z[ie*3+1],z[ie*3+2],_,q)}}})(1e-4),isFinite(_.distance)){let q=_.point[0],G=_.point[1],z=_.point[2],I=this.modelMatrix,ne=I[0]*q+I[4]*G+I[8]*z+I[12],H=I[1]*q+I[5]*G+I[9]*z+I[13],Q=I[2]*q+I[6]*G+I[10]*z+I[14],ee=ne-b,ie=H-x,oe=Q-g,N=Math.hypot(ee,ie,oe);if(N<m){ae(this.normalMatrix,this.modelMatrix);let O=this.normalMatrix,te=_.normal[0],re=_.normal[1],C=_.normal[2],j=O[0]*te+O[3]*re+O[6]*C,V=O[1]*te+O[4]*re+O[7]*C,Z=O[2]*te+O[5]*re+O[8]*C,se=Math.hypot(j,V,Z)||1;j/=se,V/=se,Z/=se,j*ee+V*ie+Z*oe>0&&(j=-j,V=-V,Z=-Z),d=f,m=Math.round(N*1e3)/1e3,y=[Math.round(ne*1e3)/1e3,Math.round(H*1e3)/1e3,Math.round(Q*1e3)/1e3],p=[Math.round(j*1e3)/1e3,Math.round(V*1e3)/1e3,Math.round(Z*1e3)/1e3]}}}}if(!d)return null;let T={meshIndex:this.meshes.indexOf(d),meshName:d.name,nodeIndex:d.nodeIndex,distance:m,hitPoint:y,normal:p,screenX:e,screenY:t};if(s){for(let f of Y)f.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 s=Math.max(1,Math.floor(t*.5)),i=e>=s,r=i?e-s:e,o=i?Math.max(1,t-s):s,c=(r+.5)/o*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);be(this.projMatrix,this.fov,e,.1,t);let s=this.customTarget||this.bounds.center;xe(this.viewMatrix,he(this),s,[0,1,0]),J(this.mvpMatrix,this.projMatrix,this.viewMatrix),ae(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),s=Math.max(1,Math.floor(t.width*e)),i=Math.max(1,Math.floor(t.height*e));this.canvas.width!==s||this.canvas.height!==i?(this.canvas.width=s,this.canvas.height=i,this.resizePickingFbo(s,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 s of Y)s.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(s){this.reportRenderError(s)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of Y)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 s=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(s),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),s=this.bounds.center[0],i=this.bounds.center[2],r=this.modelRootMatrix;r[0]=e,r[1]=0,r[2]=-t,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=t,r[9]=0,r[10]=e,r[11]=0,r[12]=s-(e*s+t*i),r[13]=0,r[14]=i-(-t*s+e*i),r[15]=1}setVisible(e){this.isVisible=e}update(e){for(let o of Y)o.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 o of Y)o.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 s=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),r=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(s-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(r-this.lastReportedZoom)>=.02){this.lastReportedTheta=s,this.lastReportedPhi=i,this.lastReportedZoom=r;let o={theta:s,phi:i,zoom:r,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(o),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:o}))}}renderXRView(e,t,s,i,r=!0,o=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let c=e?.transform?.inverse?.matrix||this.viewMatrix,a=e?.projectionMatrix||this.projMatrix,l=e?.transform?.position,u=l?[l.x,l.y,l.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):s&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:c,projMatrix:a,eyePos:u,viewport:i,eye:e?.eye||"none",clear:o>0?!1:e?.eye!=="right",isAR:r})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let M=Math.max(2,this.canvas.width||2),T=Math.max(1,this.canvas.height||1),f=Math.max(1,Math.floor(M*.5)),R=Math.max(1,M-f),S=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),L=this.customTarget||this.bounds.center,[k,U,F]=he(this),h=Math.cos(this.currTheta),P=-Math.sin(this.currTheta),E=.032,v=X(),B=X(),D=[k-h*E,U,F-P*E],$=[L[0]-h*E*.25,L[1],L[2]-P*E*.25];be(v,this.fov,f/T,.1,S),xe(B,D,$,[0,1,0]);let A=X(),W=X(),_=[k+h*E,U,F+P*E],K=[L[0]+h*E*.25,L[1],L[2]+P*E*.25];be(A,this.fov,R/T,.1,S),xe(W,_,K,[0,1,0]),this.render({viewMatrix:B,projMatrix:v,eyePos:D,viewport:[0,0,f,T],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:W,projMatrix:A,eyePos:_,viewport:[f,0,R,T],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,M,T);return}let t=this.gl,s=0,i=0,r=this.canvas.width,o=this.canvas.height;e?.viewport?(s=e.viewport[0],i=e.viewport[1],r=e.viewport[2],o=e.viewport[3],t.viewport(s,i,r,o)):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=X(),a=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=a,J(c,e?.projMatrix??this.projMatrix,a);let l=ue().xrDepthShader,u=je(this.toneMapping),[d,m,y]=e?e.eyePos:he(this);for(let M of Y)M.onBeforeDrawScene?.(this,t,c,[d,m,y],u);let p=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&p===0)return;let b=e?.eye||"none",x=!1,g=p>0?[...this.backdropMeshes,...this.meshes]:this.meshes,w=M=>{for(let T=0;T<g.length;T++){let f=g[T];if(f.visible===!1)continue;let R=this.selectedMeshName!==""&&f.name===this.selectedMeshName;T<p||f.worldSpace===!0||f.name==="__xr_reticle__"?this.modelMatrix.set(f.transform):J(this.modelMatrix,this.modelRootMatrix,f.transform),J(this.mvpMatrix,c,this.modelMatrix),ae(f.normalMatrix,this.modelMatrix);let S=f.extras?.xr?.stereo||f.userData?.xr?.stereo,L=0,k=0,U=1,F=1;S==="sbs"?(U=.5,L=b==="right"?.5:0):S==="ou"&&(F=.5,k=b==="right"?.5:0);for(let h of f.primitives){let P=!!h.isTransmissive;if(!M&&P){x=!0;continue}if(M&&!P)continue;let E=h.customProgram||this.renderProg,v=h.customUniforms||this.uRender;t.useProgram(E),t.vertexAttrib3f(3,0,0,0),v.uInstanced&&t.uniform1i(v.uInstanced,0),t.uniform1i(v.uToneMapping,u),t.uniform1f(v.uEnvIntensity,this.envIntensity),v.uExposure&&t.uniform1f(v.uExposure,this.exposure),t.uniform3f(v.uCameraPos,d,m,y),t.uniform1f(v.uEmissive,R?1:0),t.uniformMatrix4fv(v.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(v.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(v.uNormalMatrix,!1,f.normalMatrix),v.uUvTransform&&t.uniform4f(v.uUvTransform,L,k,U,F),v.uViewportSize&&t.uniform2f(v.uViewportSize,Math.max(1,r),Math.max(1,o)),l?.bind(t,v,this.xrDepthState,a,[s,i,Math.max(1,r),Math.max(1,o)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(v.uEnvironmentMap,4),t.uniform1i(v.uHasEnvironmentMap,1)):t.uniform1i(v.uHasEnvironmentMap,0),this.bindLights(v),v.uSectionEnabled&&t.uniform1i(v.uSectionEnabled,0);for(let D of Y)D.onBeforeDrawPrimitive?.(t,E,h,f,this.worldMatrices||[],this.gltf);t.uniform4fv(v.uBaseColor,h.baseColor),t.uniform1f(v.uMetallic,h.metallic),t.uniform1f(v.uRoughness,h.roughness),v.uClearcoat&&t.uniform2f(v.uClearcoat,h.clearcoat??0,h.clearcoatRoughness??.04),h.texture?(t.activeTexture(33984),t.bindTexture(3553,h.texture),t.uniform1i(v.uBaseColorTexture,0),t.uniform1i(v.uHasTexture,1)):t.uniform1i(v.uHasTexture,0),h.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,h.metallicRoughnessTexture),t.uniform1i(v.uMetallicRoughnessTexture,1),t.uniform1i(v.uHasMetallicRoughnessTexture,1)):t.uniform1i(v.uHasMetallicRoughnessTexture,0),h.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,h.normalTexture),t.uniform1i(v.uNormalTexture,2),t.uniform1i(v.uHasNormalTexture,1),t.uniform1f(v.uNormalScale,h.normalScale)):t.uniform1i(v.uHasNormalTexture,0),h.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,h.occlusionTexture),t.uniform1i(v.uOcclusionTexture,3),t.uniform1i(v.uHasOcclusionTexture,1),t.uniform1f(v.uOcclusionStrength,h.occlusionStrength)):t.uniform1i(v.uHasOcclusionTexture,0),t.bindVertexArray(h.vao);let B=f.instanceMatrices;if(h.instanceCount!==void 0)t.drawElementsInstanced(4,h.indexCount,h.indexType,0,h.instanceCount);else if(B&&B.length>=16&&h.instanced&&v.uInstanced&&v.uViewProj){let D=B.length>>4;t.uniform1i(v.uInstanced,1),t.uniformMatrix4fv(v.uViewProj,!1,c),h.indices?t.drawElementsInstanced(4,h.indexCount,h.indexType,0,D):t.drawArraysInstanced(4,0,h.indexCount,D),t.uniform1i(v.uInstanced,0)}else if(B&&B.length>=16){let D=B.length>>4,$=f.instanceColors,A=X(),W=new Float32Array(9),_=[h.baseColor[0],h.baseColor[1],h.baseColor[2],h.baseColor[3]];for(let K=0;K<D;K++)J(A,this.modelMatrix,B.subarray(K*16,K*16+16)),J(this.mvpMatrix,c,A),ae(W,A),t.uniformMatrix4fv(v.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(v.uModel,!1,A),t.uniformMatrix3fv(v.uNormalMatrix,!1,W),$&&(_[0]=h.baseColor[0]*$[K*3],_[1]=h.baseColor[1]*$[K*3+1],_[2]=h.baseColor[2]*$[K*3+2],_[3]=h.baseColor[3],t.uniform4fv(v.uBaseColor,_)),ge(t,h)}else ge(t,h)}}};if(w(!1),x){for(let M of Y)M.onBeforeTransmissivePass?.(t,this);w(!0)}for(let M of Y)M.onAfterRender?.(t,this,c,e?.eye??"none",[s,i,r,o],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){Xe(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 Y)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()}};me.registerPlugin=Ie,me.getRegisteredPlugins=Fe;var dt=me;export{me as MicroViewer,ft as SANDBOX_HOST_SCENE_LIMITS,me as ThreeView,Ye as decodeUtf8,dt as default,mt as evaluateToneMapping,le as getDecoder,Fe as getRegisteredPlugins,Ke as isGLBData,ae as mat3NormalFromMat4,X as mat4Create,Te as mat4FromRotationTranslationScale,De as mat4Invert,xe as mat4LookAt,J as mat4Multiply,be as mat4Perspective,ye as normalizeToneMapping,_e as parseGLB,Le as rayIntersectsTriangle,ht as readFloat32Array,$e as registerDecoder,Ie as registerPlugin,Ce as resolveNodeWorldMatrices,Qe as sanitizeTextureUri,Se as toGLBData,je as toneMappingShaderIndex,Re as unprojectPoint};
249
+ void main(){fragColor=uColorId;}`;function Dt(t,e,i){let s={};for(let r of i)s[r]=t.getUniformLocation(e,r);return s}var zt=["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 Gt(){let t=ut().xrDepthShader;return{fs:Qt.replace("/*XRD_U*/",t?.uniformsGLSL||"").replace("/*XRD_O*/",t?.occlusionGLSL||""),uniforms:t?[...zt,...t.uniformNames]:zt}}function jt(t){if(typeof t!="string")return null;let e=t.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let i=e.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:i.startsWith("https://")||i.startsWith("blob:")?e:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function Rt(t,e,i,s,r,a,o,l){if(s===void 0||!e.accessors?.[s])return null;let n=At(e,i,e.accessors[s],a);if(!n)return null;l&&(n=n.slice(),Jt(n,l));let h=t.createBuffer();return o.push(h),t.bindBuffer(34962,h),t.bufferData(34962,n,35044),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,a,5126,!1,0,0),n}function It(t){let e=Number(t);return Number.isFinite(e)?Math.max(0,e):1}function Wt(t,e,i){let s=Gt(),r=Ht,a=s.fs,o=!1;for(let n of W)if(n.onResolveShader){let h=n.onResolveShader(e,i,r,a);h&&(r=h.vs,a=h.fs,o=!0)}let l=o?yt(t,r,a):null;return{program:l,uniforms:l?Dt(t,l,s.uniforms):null}}function re(t,e,i){let s=e.instanceMatrices;if(!s||s.length<16||typeof t.vertexAttribDivisor!="function"||typeof t.drawElementsInstanced!="function")return!1;let r=s.length>>4,a=e.instanceColors,o=new Float32Array(r*20);for(let n=0;n<r;n++)o.set(s.subarray(n*16,n*16+16),n*20),o[n*20+16]=a?a[n*3]:1,o[n*20+17]=a?a[n*3+1]:1,o[n*20+18]=a?a[n*3+2]:1,o[n*20+19]=1;let l=t.createBuffer();i.push(l),t.bindBuffer(34962,l),t.bufferData(34962,o,35044);for(let n=0;n<5;n++)t.enableVertexAttribArray(8+n),t.vertexAttribPointer(8+n,4,5126,!1,80,n*16),t.vertexAttribDivisor(8+n,1);return!0}function se(t,e){let i=t.materials?.[e?.material];if(!i)return null;let s=[i.pbrMetallicRoughness?.baseColorTexture,i.pbrMetallicRoughness?.metallicRoughnessTexture,i.normalTexture,i.occlusionTexture,i.emissiveTexture];for(let r of s){let a=r?.extensions?.KHR_texture_transform;if(a&&typeof a=="object")return a}return null}var ae=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),$t=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Mt(t,e){e.indices?t.drawElements(4,e.indexCount,e.indexType,0):t.drawArrays(4,0,e.indexCount)}function Xt(t,e){let i=t?.pbrMetallicRoughness,s=i?.baseColorFactor,r=t?.extensions?.KHR_materials_clearcoat,a=o=>o!==void 0&&e[o.index]?e[o.index]:null;return{baseColor:s?[s[0],s[1],s[2],s[3]??1]:[.8,.8,.8,1],metallic:i?.metallicFactor??.1,roughness:i?.roughnessFactor??.5,clearcoat:r?r.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,r?.clearcoatRoughnessFactor??.04),texture:a(i?.baseColorTexture),metallicRoughnessTexture:a(i?.metallicRoughnessTexture),normalTexture:a(t?.normalTexture),normalScale:t?.normalTexture?.scale??1,occlusionTexture:a(t?.occlusionTexture),occlusionStrength:t?.occlusionTexture?.strength??1,isTransmissive:(t?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Kt(t,e,i){let s=new Set,r=a=>{a&&!s.has(a)&&(s.add(a),t.deleteTexture(a))};for(let a of e)for(let o of a.primitives){if(o.vao&&t.deleteVertexArray(o.vao),o.buffers)for(let n of o.buffers)t.deleteBuffer(n);r(o.texture),r(o.metallicRoughnessTexture),r(o.normalTexture),r(o.occlusionTexture);let l=new Set;o.customProgram&&l.add(o.customProgram);for(let n of o.programCache?.values()??[])n.program&&l.add(n.program);for(let n of l)t.deleteProgram(n)}if(i)for(let a of i)r(a)}function qt(t,e,i=$t,s){let r={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return oe(t,e,i,s,r)}catch(a){let o=r.mesh&&!r.meshes.includes(r.mesh)?[...r.meshes,r.mesh]:r.meshes;Kt(t,o,r.gpuTextures),r.vao&&t.deleteVertexArray(r.vao);for(let l of r.buffers)t.deleteBuffer(l);throw a}}function oe(t,e,i,s,r){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:a}=e,o=ht("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(a,e);let l=e.bin,n=[];r.meshes=n;let h=[],c=a.extensions?.KHR_materials_variants;c&&Array.isArray(c.variants)&&c.variants.forEach((C,u)=>{h.push(typeof C?.name=="string"&&C.name?C.name:`Variant_${u}`)});let d=Nt(a),v=[];if(Array.isArray(a.nodes))for(let C=0;C<a.nodes.length;C++){let u=a.nodes[C];u.mesh!==void 0&&a.meshes&&a.meshes[u.mesh]&&v.push({node:u,nodeIdx:C,meshIdx:u.mesh})}let x=v.length>0?v:(a.meshes||[]).map((C,u)=>({node:C,nodeIdx:-1,meshIdx:u})),b=[],m=Array.isArray(e.lights)&&e.lights.length>0?e.lights:Array.isArray(a.asset?.extras?.lights)&&a.asset.extras.lights.length>0?a.asset.extras.lights:null;if(m)for(let C of m)b.push({...C,type:C.type||C.light_type||"point",innerConeAngle:C.innerConeAngle??C.inner_cone_angle,outerConeAngle:C.outerConeAngle??C.outer_cone_angle});else if(a.extensions?.KHR_lights_punctual?.lights){let C=a.extensions.KHR_lights_punctual.lights;for(let u of C){let R=u.type==="directional"?"directional":u.type==="point"?"point":u.type==="spot"?"spot":"ambient";b.push({type:R,color:u.color||[1,1,1],intensity:u.intensity!==void 0?u.intensity:1})}}if(b.length===0&&(b.push({type:"ambient",color:[1,1,1],intensity:.35}),b.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),x.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${x.length}`);let M=[];if(r.gpuTextures=M,a.textures&&a.images){if(a.textures.length>i.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${i.maxTextures}). Found: ${a.textures.length}`);for(let C=0;C<a.textures.length;C++){let u=a.textures[C],R=a.images[u.source];if(R){let H=t.createTexture();t.bindTexture(3553,H),t.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),t.texParameteri(3553,10242,10497),t.texParameteri(3553,10243,10497),t.texParameteri(3553,10241,9729),t.texParameteri(3553,10240,9729);let J=N=>{t.bindTexture(3553,H),t.texImage2D(3553,0,6408,6408,5121,N),t.generateMipmap(3553),s?.()};if(R.bufferView!==void 0){let N=a.bufferViews[R.bufferView],F=N.byteOffset||0,D=new Blob([l.slice(F,F+N.byteLength)],{type:R.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(D).then(J).catch(()=>{})}else if(R.uri){let N=jt(R.uri);if(N){let F=new Image;F.crossOrigin="anonymous",F.referrerPolicy="no-referrer",F.onload=()=>J(F),F.src=N}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",R.uri)}M.push(H)}else M.push(null)}}let y=[1/0,1/0,1/0],f=[-1/0,-1/0,-1/0],g=0,p=0;for(let C=0;C<x.length;C++){let u=x[C],R=a.meshes[u.meshIdx],H=u.nodeIdx>=0?d[u.nodeIdx]:z(),J=new Float32Array(9);nt(J,H);let N={name:u.node.name||R.name||`Mesh_${u.meshIdx}`,nodeIndex:u.nodeIdx,transform:H,normalMatrix:J,primitives:[],extras:u.node.extras||R.extras,...u.node?.visible===!1||u.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};r.mesh=N;let F=u.node?.extensions?.EXT_mesh_gpu_instancing;if(F&&F.attributes&&typeof F.attributes=="object"){let D=F.attributes,V=D.TRANSLATION!==void 0?a.accessors?.[D.TRANSLATION]:null,_=D.ROTATION!==void 0?a.accessors?.[D.ROTATION]:null,k=D.SCALE!==void 0?a.accessors?.[D.SCALE]:null,X=D._COLOR_0!==void 0?a.accessors?.[D._COLOR_0]:null,B=Number(V?.count??_?.count??k?.count??0);if(!Number.isFinite(B)||B<0||B>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${B}`);if(B>0){let et=(A,G)=>{if(!A||A.bufferView===void 0||!a.bufferViews?.[A.bufferView])return null;let q=A.componentType??5126,tt=j=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${j})`),null);if(q!==5120&&q!==5121&&q!==5122&&q!==5123&&q!==5126)return tt(`componentType ${q}`);if(!(Number(A.count)>=B))return tt(`count ${A.count} < ${B}`);let I=null;try{I=At(a,l,{...A,count:B},G)}catch{return tt("out of bounds")}return!I||!I.every(Number.isFinite)?tt("non-finite value"):I},$=et(V,3),Q=et(_,4),it=et(k,3),rt=X?.type==="VEC4"?4:3,K=et(X,rt),st=new Float32Array(B*16),at=z();for(let A=0;A<B;A++){let G=$?[$[A*3],$[A*3+1],$[A*3+2]]:[0,0,0],q=Q?[Q[A*4],Q[A*4+1],Q[A*4+2],Q[A*4+3]]:[0,0,0,1],tt=it?[it[A*3],it[A*3+1],it[A*3+2]]:[1,1,1];Tt(at,q,G,tt),st.set(at,A*16)}if(N.instanceMatrices=st,K){let A=new Float32Array(B*3);for(let G=0;G<B;G++)A[G*3]=K[G*rt],A[G*3+1]=K[G*rt+1],A[G*3+2]=K[G*rt+2];N.instanceColors=A}}}for(let D of R.primitives||[]){if(D.extensions?.KHR_draco_mesh_compression){let I=ht("draco");I&&I.decodePrimitive(a,D,l)}let V=[],_=t.createVertexArray();r.vao=_,r.buffers=V,t.bindVertexArray(_);let k=re(t,N,V),X=a.accessors[D.attributes.POSITION],B=Number(X?.count??0);if(!Number.isFinite(B)||B<0||g+B>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(g+=B,X?.min&&X?.max){let I=j=>{for(let Z=0;Z<3;Z++){let ot=j[12+Z],ct=j[12+Z];for(let lt=0;lt<3;lt++){let pt=j[lt*4+Z]*X.min[lt],gt=j[lt*4+Z]*X.max[lt];ot+=pt<gt?pt:gt,ct+=pt>gt?pt:gt}ot<y[Z]&&(y[Z]=ot),ct>f[Z]&&(f[Z]=ct)}};if(N.instanceMatrices&&N.instanceMatrices.length>=16){let j=N.instanceMatrices.length>>4,Z=z();for(let ot=0;ot<j;ot++){let ct=N.instanceMatrices.subarray(ot*16,ot*16+16);Y(Z,H,ct),I(Z)}}else I(H)}let et=Rt(t,a,l,D.attributes.POSITION,0,3,V);Rt(t,a,l,D.attributes.NORMAL,1,3,V),Rt(t,a,l,D.attributes.TEXCOORD_0,2,2,V,se(a,D));let $=0,Q=5123,it=null;if(D.indices!==void 0){let I=a.accessors[D.indices],j=(a.bufferViews[I.bufferView].byteOffset||0)+(I.byteOffset||0);if($=Number(I.count??0),!Number.isFinite($)||$<0||p+$>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);p+=$,Q=I.componentType===5125?5125:5123;let Z=t.createBuffer();V.push(Z),t.bindBuffer(34963,Z),I.componentType===5125?it=new Uint32Array(l,j,I.count):I.componentType===5121?it=Uint16Array.from(new Uint8Array(l,j,I.count)):it=j%2===0?new Uint16Array(l,j,I.count):new Uint16Array(l.slice(j,j+I.count*2)),t.bufferData(34963,it,35044)}else $=X.count;let rt={};for(let I of W)if(I.onBuildPrimitiveVAO){let j=I.onBuildPrimitiveVAO(t,_,D,a,l);j&&(rt[I.name]=j)}t.bindVertexArray(null);let K=a.materials&&D.material!==void 0?a.materials[D.material]:null,{program:st,uniforms:at}=Wt(t,D,K),A=Xt(K,M),G=!!(K?.extensions?.KHR_materials_transmission||rt.materials?.isTransmissive),q=D.extensions?.KHR_materials_variants?.mappings,tt=Array.isArray(q)?q.filter(I=>I&&typeof I.material=="number"&&Array.isArray(I.variants)).map(I=>({material:I.material|0,variants:I.variants.map(j=>Number(j)|0)})):void 0;N.primitives.push({vao:_,instanced:k,indexCount:$,indexType:Q,...A,positions:et,indices:it,buffers:V,materialIndex:D.material,defaultMaterialIndex:D.material,variantMappings:tt,primitiveDef:D,programCache:new Map([[D.material??-1,{program:st,uniforms:at}]]),pluginData:rt,customProgram:st,customUniforms:at,isTransmissive:G})}n.push(N)}isFinite(y[0])||(y=[-1,-1,-1]),isFinite(f[0])||(f=[1,1,1]);let w=[(y[0]+f[0])/2,(y[1]+f[1])/2,(y[2]+f[2])/2],P=f[0]-y[0],E=f[1]-y[1],O=f[2]-y[2],U=Math.max(Math.hypot(P,E,O)/2,.5),S=[y[0],y[1],y[2]],T=[f[0],f[1],f[2]],L=e.animations;if(!L){for(let C of W)if(C.onParseGLB?.(e),e.animations){L=e.animations;break}}return L||(L=[]),{meshes:n,bounds:{center:w,radius:U,min:S,max:T},lights:b,animations:L,worldMatrices:d,gpuTextures:M,availableVariants:h}}function dt(t){let e=t.customTarget||t.bounds.center,i=t.currDistance*Math.cos(t.currPhi);return[e[0]+i*Math.sin(t.currTheta),e[1]+t.currDistance*Math.sin(t.currPhi),e[2]+i*Math.cos(t.currTheta)]}var ft=class{constructor(t,e,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=z(),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=z(),this.viewMatrix=z(),this.activeViewMatrix=null,this.modelMatrix=z(),this.mvpMatrix=z(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshName="",this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:z(),rawValueToMeters:.001,format:0},this.container=t;let s,r;if(e&&typeof e.getContext=="function"?(s=e,r=i):(r=e,s=r?.canvas),!s){let l=t.querySelector("canvas");l||(l=document.createElement("canvas"),l.style.width="100%",l.style.height="100%",l.style.display="block",l.style.touchAction="none",t.prepend(l)),s=l}this.canvas=s,this.opts=r||{},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=It(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=mt(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 o=s.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!o)throw new Error("WebGL2 not supported");this.gl=o,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(t,e){Ot(t,e)}static getDecoder(t){return ht(t)}setupContextLossHandling(){let t=this.canvas;typeof t?.addEventListener=="function"&&(this.boundContextLost=e=>{e.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),t.addEventListener("webglcontextlost",this.boundContextLost),t.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let t=this.gl,e=Gt();this.renderProg=yt(t,Ht,e.fs),this.pickProg=yt(t,ee,ie),this.uRender=Dt(t,this.renderProg,e.uniforms),this.uPick=Dt(t,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let t=this.gl;this.contextLost=!1,this.initGlState();for(let e of W)e.onContextRestored?.(t,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 t=this.gl;if(typeof t.createFramebuffer!="function")return;this.pickFbo=t.createFramebuffer(),this.pickTexture=t.createTexture(),this.pickDepth=t.createRenderbuffer();let e=Math.max(1,this.canvas.width),i=Math.max(1,this.canvas.height);this.pickFboWidth=e,this.pickFboHeight=i,t.bindTexture(3553,this.pickTexture),t.texImage2D(3553,0,6408,e,i,0,6408,5121,null),t.texParameteri(3553,10241,9728),t.texParameteri(3553,10240,9728),t.bindRenderbuffer(36161,this.pickDepth),t.renderbufferStorage(36161,33189,e,i),t.bindFramebuffer(36160,this.pickFbo),t.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),t.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),t.bindFramebuffer(36160,null)}resizePickingFbo(t,e){if(!this.pickFbo)return;let i=this.gl,s=Math.max(1,t),r=Math.max(1,e);this.pickFboWidth=s,this.pickFboHeight=r,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,s,r,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,s,r)}loadGLBData(t,e){let{meshes:i,bounds:s,lights:r,animations:a,worldMatrices:o,gpuTextures:l,availableVariants:n}=qt(this.gl,t,e,()=>this.render());if(this.lastGlbData=t,this.lastLimits=e,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=i,this.bounds=s,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=r,this.animations=a||[],this.worldMatrices=o||[],this.gpuTextures=l||[],this.availableVariants=n||[],this.gltf=t.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(t.gltf?.nodes))for(let d of t.gltf.nodes)this.initialNodeTransforms.push({t:d.translation?[d.translation[0],d.translation[1],d.translation[2]]:[0,0,0],r:d.rotation?[d.rotation[0],d.rotation[1],d.rotation[2],d.rotation[3]]:[0,0,0,1],s:d.scale?[d.scale[0],d.scale[1],d.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let d of W)d.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:s.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let h=t.exposure??t.gltf?.extras?.exposure??t.gltf?.asset?.extras?.exposure;h!==void 0&&(this.exposure=It(h));let c=t.environmentIntensity??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.environmentIntensity;c!==void 0&&(this.envIntensity=Math.max(0,Number(c)||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(t){this.loadGLBData(wt(t))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let t of W)t.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(t){this.loadGLBData(Ct(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let i=Ct(t),{meshes:s}=qt(this.gl,i,$t,()=>this.render());if(e)for(let r of s)r.transform[12]+=e[0],r.transform[13]+=e[1],r.transform[14]+=e[2],nt(r.normalMatrix,r.transform);this.backdropMeshes=s,this.update(0),this.render()}setClearColor(t,e,i,s=1){this.clearColor=[t,e,i,s]}updateMeshTransforms(t){for(let e=0;e<this.meshes.length;e++){let i=this.meshes[e],s;t instanceof Map?s=t.get(i.name)??t.get(e):Array.isArray(t)?s=t[e]:t&&typeof t=="object"&&(Object.prototype.hasOwnProperty.call(t,i.name)?s=t[i.name]:Object.prototype.hasOwnProperty.call(t,e)&&(s=t[e])),s&&s.length===16&&(i.transform.set(s),nt(i.normalMatrix,i.transform))}}bindLights(t=this.uRender){let e=this.gl,i=[.28,.28,.28],s=[],r=[],a=[],o=[],l=[],n=[];for(let h of this.lights){let c=h.color||[1,1,1],d=h.intensity!==void 0?h.intensity:1;if(h.type==="ambient")i=[c[0]*d,c[1]*d,c[2]*d];else if(h.type==="directional"&&s.length<6){let v=h.direction||[.5,1,.8];s.push(v[0],v[1],v[2]),r.push(c[0]*d,c[1]*d,c[2]*d)}else if((h.type==="point"||h.type==="spot")&&a.length<6){let v=h.position||[0,0,0];if(a.push(v[0],v[1],v[2]),o.push(c[0]*d,c[1]*d,c[2]*d),h.type==="spot"){let x=h.direction||[0,-1,0],b=Math.max(.01,Math.min(Math.PI/2,h.outerConeAngle??Math.PI/3)),m=Math.max(0,Math.min(b-1e-4,h.innerConeAngle??0));l.push(x[0],x[1],x[2]),n.push(Math.cos(m),Math.cos(b))}else l.push(0,-1,0),n.push(-2,-3)}}s.length===0&&(s.push(.5,1,.8),r.push(1,1,1)),e.uniform3fv(t.uAmbientColor,i),e.uniform1i(t.uNumDirLights,s.length/3),s.length>0&&(e.uniform3fv(t.uDirLightDir,s),e.uniform3fv(t.uDirLightColor,r)),e.uniform1i(t.uNumPointLights,a.length/3),a.length>0&&(e.uniform3fv(t.uPointLightPos,a),e.uniform3fv(t.uPointLightColor,o),t.uPointLightSpotDir&&e.uniform3fv(t.uPointLightSpotDir,l),t.uPointLightSpotCone&&e.uniform2fv(t.uPointLightSpotCone,n)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.exposure=It(t)}getExposure(){return this.exposure}setShadow(t,e){this.shadowIntensity=Math.max(0,Math.min(1,Number(t)||0)),e!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(e)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(t){this.toneMapping=mt(t)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of W)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of W)if(e.setSkyboxImage){await e.setSkyboxImage(this,t);return}}setInteractive(t){this.interactive=t}isInteractive(){return this.interactive}getCameraOrbit(){let t=this.currTheta,e=this.currPhi,i=this.currDistance;return{theta:t,phi:e,radius:i,toString(){return`${t.toFixed(4)}rad ${e.toFixed(4)}rad ${i.toFixed(4)}m`}}}getCameraTarget(){let t=this.customTarget||this.bounds.center;return{x:t[0],y:t[1],z:t[2],toString(){return`${t[0].toFixed(4)}m ${t[1].toFixed(4)}m ${t[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let t=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return t.map((e,i)=>{let s=this.meshes.flatMap(h=>h.primitives.filter(c=>c.materialIndex===i||t.length===1&&c.materialIndex===void 0)),r=s[0],a=r?[...r.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],o=r?r.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,l=r?r.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,n={baseColorFactor:a,metallicFactor:o,roughnessFactor:l,setBaseColorFactor:h=>{let c=[h[0],h[1],h[2],h[3]??1];n.baseColorFactor=c,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=c);for(let d of s)d.baseColor=c;this.render()},setMetallicFactor:h=>{n.metallicFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=h);for(let c of s)c.metallic=h;this.render()},setRoughnessFactor:h=>{n.roughnessFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=h);for(let c of s)c.roughness=h;this.render()}};return{name:e.name||`Material_${i}`,pbrMetallicRoughness:n}})}playAnimation(t){if(this.animations.length!==0){if(t){let e=this.animations.find(i=>i.name===t);e&&(this.currentClip=e)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(t=>t.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(t){let e=this.applyVariantMaterial(t);return e&&this.gl&&this.render(),e}applyVariantMaterial(t){let e=t===null||t==="",i=-1;if(e)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(t),i<0)return!1;this.activeVariantName=t}let s=this.gltf?.materials;if(!Array.isArray(s))return e;for(let r of this.meshes)for(let a of r.primitives){let o=a.defaultMaterialIndex;if(!e&&Array.isArray(a.variantMappings)){for(let n of a.variantMappings)if(Array.isArray(n.variants)&&n.variants.includes(i)){o=n.material;break}}let l=o!==void 0?s[o]:void 0;a.materialIndex=l?o:void 0,Object.assign(a,Xt(l,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,l??null)}return!0}applyPrimitiveProgram(t,e,i){if(!this.gl||!t.primitiveDef)return;t.programCache??(t.programCache=new Map);let s=e??-1,r=t.programCache.get(s);r||(r=Wt(this.gl,{...t.primitiveDef,material:e},i),t.programCache.set(s,r)),t.customProgram=r.program,t.customUniforms=r.uniforms,t.pluginData&&(t.pluginData.materials=t.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(t){this.autoplay=t,t?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(t){this.animationName=t,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(t)}evaluateAnimation(t){for(let e of W)if(e.evaluateAnimation){e.evaluateAnimation(this,t);return}}setTarget(t,e,i){this.customTarget=[t,e,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(t){let e=Math.max(10,Math.min(90,t));this.fov=e*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(t){if(this.distanceMode=t,!this.customDistance){let e=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=e,this.targetDistance=e,this.currDistance=e,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(t){t.minTheta!==void 0&&(this.minTheta=t.minTheta*Math.PI/180),t.maxTheta!==void 0&&(this.maxTheta=t.maxTheta*Math.PI/180),t.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,t.minPhi*Math.PI/180)),t.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,t.maxPhi*Math.PI/180)),t.minDistance!==void 0&&(this.minDistanceLimit=t.minDistance),t.maxDistance!==void 0&&(this.maxDistanceLimit=t.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(t){return Math.max(this.minTheta,Math.min(this.maxTheta,t))}clampPhi(t){return Math.max(this.minPhi,Math.min(this.maxPhi,t))}clampDistance(t){let e=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(e,Math.min(i,t))}setCamera(t,e,i,s){t!==void 0&&(this.targetTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.targetPhi=this.clampPhi(e*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),s!==void 0&&s>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/s))}setInitialCamera(t,e,i,s){if(t!==void 0&&(this.initialTheta=this.clampTheta(t*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),e!==void 0&&(this.initialPhi=this.clampPhi(e*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),i!==void 0&&i>0){let r=this.clampDistance(i);this.initialDistance=r,this.customDistance=!0,this.targetDistance=r,this.currDistance=r}else if(s!==void 0&&s>0){let r=this.clampDistance(this.bounds.radius*2.5/s);this.initialDistance=r,this.customDistance=!0,this.targetDistance=r,this.currDistance=r}else{this.customDistance=!1;let r=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=r,this.targetDistance=r,this.currDistance=r}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(t,e){let i=z();Y(i,this.projMatrix,this.viewMatrix);let[s,r,a]=t,o=e?e[0]:0,l=e?e[1]:0,n=e?e[2]:0,h=this.modelRootMatrix;h&&(s=h[0]*t[0]+h[4]*t[1]+h[8]*t[2]+h[12],r=h[1]*t[0]+h[5]*t[1]+h[9]*t[2]+h[13],a=h[2]*t[0]+h[6]*t[1]+h[10]*t[2]+h[14],e&&(o=h[0]*e[0]+h[4]*e[1]+h[8]*e[2],l=h[1]*e[0]+h[5]*e[1]+h[9]*e[2],n=h[2]*e[0]+h[6]*e[1]+h[10]*e[2]));let c=i[0]*s+i[4]*r+i[8]*a+i[12],d=i[1]*s+i[5]*r+i[9]*a+i[13],v=i[2]*s+i[6]*r+i[10]*a+i[14],x=i[3]*s+i[7]*r+i[11]*a+i[15];if(x<=1e-4)return{x:0,y:0,z:1,visible:!1};let b=c/x,m=d/x,M=v/x,y=this.canvas.getBoundingClientRect(),f=y.width||this.canvas.clientWidth||this.canvas.width||300,g=y.height||this.canvas.clientHeight||this.canvas.height||150,p=(b*.5+.5)*f,w=(-m*.5+.5)*g,P=b>=-1.1&&b<=1.1&&m>=-1.1&&m<=1.1&&M>=-1&&M<=1;if(P&&e){let[E,O,U]=dt(this),S=[s-E,r-O,a-U];o*S[0]+l*S[1]+n*S[2]>.05&&(P=!1)}return{x:p,y:w,z:M,visible:P}}setSelectedMesh(t){this.selectedMeshName=t||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let t=this.canvas,e=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=i=>{i.preventDefault()},t.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=e(),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,t.setPointerCapture(i.pointerId))},t.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=e();let s=this.activePointers.get(i.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},r=i.clientX-s.x,a=i.clientY-s.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(r,a),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],l=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],n=this.customTarget?[...this.customTarget]:[...this.bounds.center],h=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;n[0]+=(-r*o[0]+a*l[0])*h,n[1]+=(-r*o[1]+a*l[1])*h,n[2]+=(-r*o[2]+a*l[2])*h,this.customTarget=n}else this.targetTheta=this.clampTheta(this.targetTheta-r*.008),this.targetPhi=this.clampPhi(this.targetPhi+a*.008)},t.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=e(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{t.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let s=t.getBoundingClientRect(),r=Math.floor((i.clientX-s.left)*(t.width/Math.max(s.width,1))),a=Math.floor((i.clientY-s.top)*(t.height/Math.max(s.height,1)));this.performMeshPick(r,a,!0)}},t.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=e();let s=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*s)},t.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=i=>{let s=i.detail||{};s.reset?this.resetCamera():this.setCamera(s.theta,s.phi,s.distance,s.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),t.tabIndex!==void 0&&t.tabIndex<0&&(t.tabIndex=0),t.getAttribute?.("role")||t.setAttribute?.("role","region"),t.getAttribute?.("aria-label")||t.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=e(),i.preventDefault()}},t.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let t=(i,s,r)=>{this[r]&&(i.removeEventListener(s,this[r]),this[r]=null)},e=this.canvas;t(e,"webglcontextlost","boundContextLost"),t(e,"webglcontextrestored","boundContextRestored"),t(e,"contextmenu","boundContextMenu"),t(e,"pointerdown","boundPointerDown"),t(e,"pointermove","boundPointerMove"),t(e,"pointerup","boundPointerUp"),t(e,"wheel","boundWheel"),t(e,"keydown","boundKeyDown"),t(this.container,"setCamera","boundSetCamera"),t(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(t,e){let i=this.canvas,s=i.getBoundingClientRect(),r=i.width||300,a=i.height||300,o=s.width>0?Math.floor((t-s.left)*(r/s.width)):Math.floor(t),l=s.height>0?Math.floor((e-s.top)*(a/s.height)):Math.floor(e);return this.performMeshPick(o,l,!1)}performMeshPick(t,e,i=!0){if(this.meshes.length===0)return null;let s=this.gl,r=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);t=this.mapStereoPickX(t,r);let o=z();Y(o,this.projMatrix,this.viewMatrix);let l=[],n=Math.max(0,Math.min(r-1,t)),h=Math.max(0,Math.min(a-1,a-1-e));if(this.pickFbo&&s&&!this.xrSessionActive){(this.pickFboWidth!==r||this.pickFboHeight!==a)&&this.resizePickingFbo(r,a),s.bindFramebuffer(36160,this.pickFbo),s.viewport(0,0,r,a),s.enable(2929),s.clearColor(0,0,0,0),s.clear(16640),s.useProgram(this.pickProg);for(let w=0;w<this.meshes.length;w++){let P=this.meshes[w];if(P.visible===!1||P.isPluginMesh)continue;let E=w+1,O=(E&255)/255,U=(E>>8&255)/255,S=(E>>16&255)/255;s.uniform4f(this.uPick.uColorId,O,U,S,1),Y(this.modelMatrix,this.modelRootMatrix,P.transform);let T=P.instanceMatrices;if(T&&T.length>=16){let L=T.length>>4,C=z();for(let u of P.primitives){s.bindVertexArray(u.vao);for(let R=0;R<L;R++)Y(C,this.modelMatrix,T.subarray(R*16,R*16+16)),Y(this.mvpMatrix,o,C),s.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Mt(s,u)}}else{Y(this.mvpMatrix,o,this.modelMatrix),s.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let L of P.primitives)s.bindVertexArray(L.vao),Mt(s,L)}}let g=new Uint8Array(4);s.readPixels(n,h,1,1,6408,5121,g),s.bindFramebuffer(36160,null);let p=g[0]+(g[1]<<8)+(g[2]<<16);p>0&&p<=this.meshes.length&&(l=[this.meshes[p-1]])}l.length===0&&(l=this.meshes.filter(g=>g.visible!==!1));let c=null,d=1/0,v=[0,0,0],x=[0,1,0],[b,m,M]=dt(this),y=z();for(let g of l){Y(y,this.modelRootMatrix,g.transform);let p=g.instanceMatrices,w=p&&p.length>=16?p.length>>4:1;for(let P=0;P<w;P++){p&&p.length>=16?Y(this.modelMatrix,y,p.subarray(P*16,P*16+16)):this.modelMatrix.set(y),Y(this.mvpMatrix,o,this.modelMatrix);let E=z();if(!St(E,this.mvpMatrix))continue;let O=(n+.5)/r*2-1,U=(h+.5)/a*2-1,S=[0,0,0],T=[0,0,0];Pt(S,O,U,-1,E),Pt(T,O,U,1,E);let L=T[0]-S[0],C=T[1]-S[1],u=T[2]-S[2],R=Math.hypot(L,C,u)||1,H=L/R,J=C/R,N=u/R,F={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((D=>{for(let V of g.primitives){if(!V.positions)continue;let _=V.positions,k=V.indices,X=Math.floor(k?k.length/3:_.length/9);for(let B=0;B<X;B++){let et=k?k[B*3]:B*3,$=k?k[B*3+1]:B*3+1,Q=k?k[B*3+2]:B*3+2;Lt(S[0],S[1],S[2],H,J,N,_[et*3],_[et*3+1],_[et*3+2],_[$*3],_[$*3+1],_[$*3+2],_[Q*3],_[Q*3+1],_[Q*3+2],F,D)}}})(1e-4),isFinite(F.distance)){let D=F.point[0],V=F.point[1],_=F.point[2],k=this.modelMatrix,X=k[0]*D+k[4]*V+k[8]*_+k[12],B=k[1]*D+k[5]*V+k[9]*_+k[13],et=k[2]*D+k[6]*V+k[10]*_+k[14],$=X-b,Q=B-m,it=et-M,rt=Math.hypot($,Q,it);if(rt<d){nt(this.normalMatrix,this.modelMatrix);let K=this.normalMatrix,st=F.normal[0],at=F.normal[1],A=F.normal[2],G=K[0]*st+K[3]*at+K[6]*A,q=K[1]*st+K[4]*at+K[7]*A,tt=K[2]*st+K[5]*at+K[8]*A,I=Math.hypot(G,q,tt)||1;G/=I,q/=I,tt/=I,G*$+q*Q+tt*it>0&&(G=-G,q=-q,tt=-tt),c=g,d=Math.round(rt*1e3)/1e3,v=[Math.round(X*1e3)/1e3,Math.round(B*1e3)/1e3,Math.round(et*1e3)/1e3],x=[Math.round(G*1e3)/1e3,Math.round(q*1e3)/1e3,Math.round(tt*1e3)/1e3]}}}}if(!c)return null;let f={meshIndex:this.meshes.indexOf(c),meshName:c.name,nodeIndex:c.nodeIndex,distance:d,hitPoint:v,normal:x,screenX:t,screenY:e};if(i){for(let g of W)g.onMeshSelect?.(this,f);this.opts.onMeshClick&&this.opts.onMeshClick(f),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:f}))}return f}mapStereoPickX(t,e){if(!this.stereoSBS||this.xrSessionActive||e<2)return t;let i=Math.max(1,Math.floor(e*.5)),s=t>=i,r=s?t-i:t,a=s?Math.max(1,e-i):i,o=(r+.5)/a*2-1;return Math.floor((o*.5+1)*.5*e)}setStereoSBS(t){this.stereoSBS=!!t,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let t=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),e=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);xt(this.projMatrix,this.fov,t,.1,e);let i=this.customTarget||this.bounds.center;vt(this.viewMatrix,dt(this),i,[0,1,0]),Y(this.mvpMatrix,this.projMatrix,this.viewMatrix),nt(this.normalMatrix,this.modelMatrix)}resize(){let t=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),e=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.floor(e.width*t)),s=Math.max(1,Math.floor(e.height*t));this.canvas.width!==i||this.canvas.height!==s?(this.canvas.width=i,this.canvas.height=s,this.resizePickingFbo(i,s),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(t){let e=this.xrSessionActive;if(this.xrSessionActive=t,e&&!t){this.xrDepthState.enabled=!1;for(let i of W)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(t){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",t))}stepXRUpdate(t){for(let e of W)e.onUpdate?.(this,t)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let t=e=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((e-this.lastTime)/1e3,0),.1);if(this.lastTime=e,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(s){this.reportRenderError(s)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(t))};this.animFrameId=requestAnimationFrame(t)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(t){this.autoRotate=t}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(t){this.autoRotateSpeed=t}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(t){this.autoRotateDelay=Math.max(0,Number(t)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(t=0){this.turntableRotation=Number(t)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let t=Math.cos(this.turntableRotation),e=Math.sin(this.turntableRotation),i=this.bounds.center[0],s=this.bounds.center[2],r=this.modelRootMatrix;r[0]=t,r[1]=0,r[2]=-e,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=e,r[9]=0,r[10]=t,r[11]=0,r[12]=i-(t*i+e*s),r[13]=0,r[14]=s-(-e*i+t*s),r[15]=1}setVisible(t){this.isVisible=t}update(t){for(let a of W)a.onUpdate?.(this,t);let e=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&e-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*t,this.updateTurntableMatrix();for(let a of W)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 i=Math.round((this.currTheta*180/Math.PI%360+360)%360),s=Math.round(this.currPhi*180/Math.PI),r=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(i-this.lastReportedTheta)>=1||Math.abs(s-this.lastReportedPhi)>=1||Math.abs(r-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=s,this.lastReportedZoom=r;let a={theta:i,phi:s,zoom:r,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(t,e,i,s,r=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let o=t?.transform?.inverse?.matrix||this.viewMatrix,l=t?.projectionMatrix||this.projMatrix,n=t?.transform?.position,h=n?[n.x,n.y,n.z]:[0,1.6,0];e?this.modelRootMatrix.set(e):i&&e&&this.modelRootMatrix.set(e),this.render({viewMatrix:o,projMatrix:l,eyePos:h,viewport:s,eye:t?.eye||"none",clear:a>0?!1:t?.eye!=="right",isAR:r})}render(t){if(this.contextLost)return;if(!t&&this.stereoSBS){let f=Math.max(2,this.canvas.width||2),g=Math.max(1,this.canvas.height||1),p=Math.max(1,Math.floor(f*.5)),w=Math.max(1,f-p),P=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),E=this.customTarget||this.bounds.center,[O,U,S]=dt(this),T=Math.cos(this.currTheta),L=-Math.sin(this.currTheta),C=.032,u=z(),R=z(),H=[O-T*C,U,S-L*C],J=[E[0]-T*C*.25,E[1],E[2]-L*C*.25];xt(u,this.fov,p/g,.1,P),vt(R,H,J,[0,1,0]);let N=z(),F=z(),D=[O+T*C,U,S+L*C],V=[E[0]+T*C*.25,E[1],E[2]+L*C*.25];xt(N,this.fov,w/g,.1,P),vt(F,D,V,[0,1,0]),this.render({viewMatrix:R,projMatrix:u,eyePos:H,viewport:[0,0,p,g],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:F,projMatrix:N,eyePos:D,viewport:[p,0,w,g],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,f,g);return}let e=this.gl,i=0,s=0,r=this.canvas.width,a=this.canvas.height;t?.viewport?(i=t.viewport[0],s=t.viewport[1],r=t.viewport[2],a=t.viewport[3],e.viewport(i,s,r,a)):e.viewport(0,0,this.canvas.width,this.canvas.height),e.enable(2929),(!t||t.clear!==!1)&&(t?.isAR?e.clearColor(0,0,0,0):e.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),e.clear(16640));let o=z(),l=t?.viewMatrix??this.viewMatrix;this.activeViewMatrix=l,Y(o,t?.projMatrix??this.projMatrix,l);let n=ut().xrDepthShader,h=kt(this.toneMapping),[c,d,v]=t?t.eyePos:dt(this);for(let f of W)f.onBeforeDrawScene?.(this,e,o,[c,d,v],h);let x=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&x===0)return;let b=t?.eye||"none",m=!1,M=x>0?[...this.backdropMeshes,...this.meshes]:this.meshes,y=f=>{for(let g=0;g<M.length;g++){let p=M[g];if(p.visible===!1)continue;let w=this.selectedMeshName!==""&&p.name===this.selectedMeshName;g<x||p.worldSpace===!0||p.name==="__xr_reticle__"?this.modelMatrix.set(p.transform):Y(this.modelMatrix,this.modelRootMatrix,p.transform),Y(this.mvpMatrix,o,this.modelMatrix),nt(p.normalMatrix,this.modelMatrix);let P=p.extras?.xr?.stereo||p.userData?.xr?.stereo,E=0,O=0,U=1,S=1;P==="sbs"?(U=.5,E=b==="right"?.5:0):P==="ou"&&(S=.5,O=b==="right"?.5:0);for(let T of p.primitives){let L=!!T.isTransmissive;if(!f&&L){m=!0;continue}if(f&&!L)continue;let C=T.customProgram||this.renderProg,u=T.customUniforms||this.uRender;e.useProgram(C),e.vertexAttrib3f(3,0,0,0),u.uInstanced&&e.uniform1i(u.uInstanced,0),e.uniform1i(u.uToneMapping,h),e.uniform1f(u.uEnvIntensity,this.envIntensity),u.uExposure&&e.uniform1f(u.uExposure,this.exposure),e.uniform3f(u.uCameraPos,c,d,v),e.uniform1f(u.uEmissive,w?1:0),e.uniformMatrix4fv(u.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(u.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(u.uNormalMatrix,!1,p.normalMatrix),u.uUvTransform&&e.uniform4f(u.uUvTransform,E,O,U,S),u.uViewportSize&&e.uniform2f(u.uViewportSize,Math.max(1,r),Math.max(1,a)),n?.bind(e,u,this.xrDepthState,l,[i,s,Math.max(1,r),Math.max(1,a)]),this.environmentTexture?(e.activeTexture(33988),e.bindTexture(3553,this.environmentTexture),e.uniform1i(u.uEnvironmentMap,4),e.uniform1i(u.uHasEnvironmentMap,1)):e.uniform1i(u.uHasEnvironmentMap,0),this.bindLights(u),u.uSectionEnabled&&e.uniform1i(u.uSectionEnabled,0);for(let H of W)H.onBeforeDrawPrimitive?.(e,C,T,p,this.worldMatrices||[],this.gltf);e.uniform4fv(u.uBaseColor,T.baseColor),e.uniform1f(u.uMetallic,T.metallic),e.uniform1f(u.uRoughness,T.roughness),u.uClearcoat&&e.uniform2f(u.uClearcoat,T.clearcoat??0,T.clearcoatRoughness??.04),T.texture?(e.activeTexture(33984),e.bindTexture(3553,T.texture),e.uniform1i(u.uBaseColorTexture,0),e.uniform1i(u.uHasTexture,1)):e.uniform1i(u.uHasTexture,0),T.metallicRoughnessTexture?(e.activeTexture(33985),e.bindTexture(3553,T.metallicRoughnessTexture),e.uniform1i(u.uMetallicRoughnessTexture,1),e.uniform1i(u.uHasMetallicRoughnessTexture,1)):e.uniform1i(u.uHasMetallicRoughnessTexture,0),T.normalTexture?(e.activeTexture(33986),e.bindTexture(3553,T.normalTexture),e.uniform1i(u.uNormalTexture,2),e.uniform1i(u.uHasNormalTexture,1),e.uniform1f(u.uNormalScale,T.normalScale)):e.uniform1i(u.uHasNormalTexture,0),T.occlusionTexture?(e.activeTexture(33987),e.bindTexture(3553,T.occlusionTexture),e.uniform1i(u.uOcclusionTexture,3),e.uniform1i(u.uHasOcclusionTexture,1),e.uniform1f(u.uOcclusionStrength,T.occlusionStrength)):e.uniform1i(u.uHasOcclusionTexture,0),e.bindVertexArray(T.vao);let R=p.instanceMatrices;if(T.instanceCount!==void 0)e.drawElementsInstanced(4,T.indexCount,T.indexType,0,T.instanceCount);else if(R&&R.length>=16&&T.instanced&&u.uInstanced&&u.uViewProj){let H=R.length>>4;e.uniform1i(u.uInstanced,1),e.uniformMatrix4fv(u.uViewProj,!1,o),T.indices?e.drawElementsInstanced(4,T.indexCount,T.indexType,0,H):e.drawArraysInstanced(4,0,T.indexCount,H),e.uniform1i(u.uInstanced,0)}else if(R&&R.length>=16){let H=R.length>>4,J=p.instanceColors,N=z(),F=new Float32Array(9),D=[T.baseColor[0],T.baseColor[1],T.baseColor[2],T.baseColor[3]];for(let V=0;V<H;V++)Y(N,this.modelMatrix,R.subarray(V*16,V*16+16)),Y(this.mvpMatrix,o,N),nt(F,N),e.uniformMatrix4fv(u.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(u.uModel,!1,N),e.uniformMatrix3fv(u.uNormalMatrix,!1,F),J&&(D[0]=T.baseColor[0]*J[V*3],D[1]=T.baseColor[1]*J[V*3+1],D[2]=T.baseColor[2]*J[V*3+2],D[3]=T.baseColor[3],e.uniform4fv(u.uBaseColor,D)),Mt(e,T)}else Mt(e,T)}}};if(y(!1),m){for(let f of W)f.onBeforeTransmissivePass?.(e,this);y(!0)}for(let f of W)f.onAfterRender?.(e,this,o,t?.eye??"none",[i,s,r,a],t?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(t,e){Kt(this.gl,t,e)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let t=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let e of W)e.onDestroy?.(t,this);this.environmentTexture&&(t.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&t.deleteProgram(this.renderProg),this.pickProg&&t.deleteProgram(this.pickProg),this.pickFbo&&t.deleteFramebuffer(this.pickFbo),this.pickTexture&&t.deleteTexture(this.pickTexture),this.pickDepth&&t.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};ft.registerPlugin=Ft,ft.getRegisteredPlugins=Vt;var ne=ft;export{ft as MicroViewer,ae as SANDBOX_HOST_SCENE_LIMITS,ft as ThreeView,Bt as decodeUtf8,ne as default,te as evaluateToneMapping,ht as getDecoder,Vt as getRegisteredPlugins,Ut as isGLBData,nt as mat3NormalFromMat4,z as mat4Create,Tt as mat4FromRotationTranslationScale,St as mat4Invert,vt as mat4LookAt,Y as mat4Multiply,xt as mat4Perspective,mt as normalizeToneMapping,wt as parseGLB,Lt as rayIntersectsTriangle,Zt as readFloat32Array,Ot as registerDecoder,Ft as registerPlugin,Nt as resolveNodeWorldMatrices,jt as sanitizeTextureUri,Ct as toGLBData,kt as toneMappingShaderIndex,Pt as unprojectPoint};