three-live 1.3.2 → 1.4.0

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 (58) hide show
  1. package/README.md +4 -1
  2. package/dist/index.d.ts +190 -0
  3. package/dist/three-author-engine.js +171 -163
  4. package/dist/three-author.cjs +145 -163
  5. package/dist/three-author.d.ts +190 -0
  6. package/dist/three-author.js +145 -163
  7. package/dist/three-convert.cjs +142 -160
  8. package/dist/three-convert.d.ts +190 -0
  9. package/dist/three-convert.js +142 -160
  10. package/dist/three-live-ai.cjs +41 -0
  11. package/dist/three-live-ai.d.ts +759 -0
  12. package/dist/three-live-ai.js +41 -0
  13. package/dist/three-live-ai.min.js +41 -0
  14. package/dist/three-live-animation.cjs +6 -6
  15. package/dist/three-live-animation.d.ts +190 -0
  16. package/dist/three-live-animation.js +5 -5
  17. package/dist/three-live-animation.min.js +5 -5
  18. package/dist/three-live-cad.cjs +2 -2
  19. package/dist/three-live-cad.d.ts +190 -0
  20. package/dist/three-live-cad.js +2 -2
  21. package/dist/three-live-cad.min.js +2 -2
  22. package/dist/three-live-element.cjs +50 -85
  23. package/dist/three-live-element.d.ts +190 -0
  24. package/dist/three-live-element.js +50 -85
  25. package/dist/three-live-full.cjs +907 -189
  26. package/dist/three-live-full.js +907 -189
  27. package/dist/three-live-full.min.js +907 -189
  28. package/dist/three-live-procedural.cjs +16 -0
  29. package/dist/three-live-procedural.d.ts +759 -0
  30. package/dist/three-live-procedural.js +16 -0
  31. package/dist/three-live-procedural.min.js +16 -0
  32. package/dist/three-live-sandbox.html +11 -1
  33. package/dist/three-live-studio.cjs +72 -17
  34. package/dist/three-live-studio.d.ts +190 -0
  35. package/dist/three-live-studio.js +72 -17
  36. package/dist/three-live-studio.min.js +73 -18
  37. package/dist/three-live-tsl.cjs +103 -0
  38. package/dist/three-live-tsl.d.ts +759 -0
  39. package/dist/three-live-tsl.js +103 -0
  40. package/dist/three-live-tsl.min.js +103 -0
  41. package/dist/three-live-viewer.cjs +50 -85
  42. package/dist/three-live-viewer.d.ts +190 -0
  43. package/dist/three-live-viewer.js +50 -85
  44. package/dist/three-live-viewer.min.js +50 -85
  45. package/dist/three-live-webgpu.cjs +585 -0
  46. package/dist/three-live-webgpu.d.ts +759 -0
  47. package/dist/three-live-webgpu.js +585 -0
  48. package/dist/three-live-webgpu.min.js +585 -0
  49. package/dist/three-live.cjs +147 -165
  50. package/dist/three-live.js +147 -165
  51. package/dist/three-live.min.js +147 -165
  52. package/dist/three-view.cjs +49 -84
  53. package/dist/three-view.d.ts +190 -0
  54. package/dist/three-view.js +50 -85
  55. package/dist/three-xr.cjs +141 -159
  56. package/dist/three-xr.d.ts +190 -0
  57. package/dist/three-xr.js +140 -158
  58. package/package.json +21 -1
@@ -13,7 +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
- */var we=Object.defineProperty,Je=Object.getOwnPropertyDescriptor,Qe=Object.getOwnPropertyNames,et=Object.prototype.hasOwnProperty,tt=(t,e)=>{for(var i in e)we(t,i,{get:e[i],enumerable:!0})},nt=(t,e,i,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qe(e))!et.call(t,r)&&r!==i&&we(t,r,{get:()=>e[r],enumerable:!(s=Je(e,r))||s.enumerable});return t},it=t=>nt(we({},"__esModule",{value:!0}),t),pt={};tt(pt,{MicroViewer:()=>he,SANDBOX_HOST_SCENE_LIMITS:()=>mt,ThreeView:()=>he,decodeUtf8:()=>We,default:()=>dt,evaluateToneMapping:()=>at,getDecoder:()=>ce,getRegisteredPlugins:()=>Ce,isGLBData:()=>ze,mat3NormalFromMat4:()=>se,mat4Create:()=>O,mat4FromRotationTranslationScale:()=>ye,mat4Invert:()=>Ae,mat4LookAt:()=>de,mat4Multiply:()=>K,mat4Perspective:()=>fe,normalizeToneMapping:()=>be,parseGLB:()=>Ge,rayIntersectsTriangle:()=>Ee,readFloat32Array:()=>st,registerDecoder:()=>Oe,registerPlugin:()=>De,resolveNodeWorldMatrices:()=>Le,sanitizeTextureUri:()=>Ye,toGLBData:()=>Se,toneMappingShaderIndex:()=>Ue,unprojectPoint:()=>Me}),module.exports=it(pt);var rt={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Pe(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,h=rt[o];if(!h)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let n=h*s,l=r.byteStride&&r.byteStride>0?r.byteStride:n,c=(r.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(c)||c<0||l<n||c+(a-1)*l+n>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(o===5126&&l===n&&c%4===0)return new Float32Array(e,c,a*s);let d=new DataView(e),x=i.normalized===!0,v=new Float32Array(a*s);for(let b=0;b<a;b++){let m=c+b*l;for(let M=0;M<s;M++){let y=m+M*h,f;switch(o){case 5126:f=d.getFloat32(y,!0);break;case 5120:f=d.getInt8(y),x&&(f=Math.max(f/127,-1));break;case 5121:f=d.getUint8(y),x&&(f/=255);break;case 5122:f=d.getInt16(y,!0),x&&(f=Math.max(f/32767,-1));break;case 5123:f=d.getUint16(y,!0),x&&(f/=65535);break;default:f=d.getUint32(y,!0),x&&(f/=4294967295)}v[b*s+M]=f}}return v}function Be(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,h=Math.cos(o),n=Math.sin(o),l=(Number.isFinite(r)?r:1)*h,c=(Number.isFinite(r)?r:1)*n,d=-(Number.isFinite(a)?a:1)*n,x=(Number.isFinite(a)?a:1)*h;for(let v=0;v+1<t.length;v+=2){let b=t[v],m=t[v+1];t[v]=l*b+c*m+i,t[v+1]=d*b+x*m+s}}function ve(t,e,i,s=!0){let r=[],a=null;try{for(let[o,h]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,h),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 O(){let t=new Float32Array(16);return t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function fe(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 de(t,e,i,s){let[r,a,o]=e,[h,n,l]=s,[c,d,x]=i,v=r-c,b=a-d,m=o-x,M=Math.hypot(v,b,m);M<=1e-5?(v=0,b=0,m=1):(v/=M,b/=M,m/=M);let y=n*m-l*b,f=l*v-h*m,g=h*b-n*v;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-v*g,P=v*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]=v,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]=-(v*r+b*a+m*o),t[15]=1,t}function K(t,e,i){let s=e[0],r=e[1],a=e[2],o=e[3],h=e[4],n=e[5],l=e[6],c=e[7],d=e[8],x=e[9],v=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*h+w*d+P*m,t[1]=g*r+p*n+w*x+P*M,t[2]=g*a+p*l+w*v+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*h+w*d+P*m,t[5]=g*r+p*n+w*x+P*M,t[6]=g*a+p*l+w*v+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*h+w*d+P*m,t[9]=g*r+p*n+w*x+P*M,t[10]=g*a+p*l+w*v+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*h+w*d+P*m,t[13]=g*r+p*n+w*x+P*M,t[14]=g*a+p*l+w*v+P*y,t[15]=g*o+p*c+w*b+P*f,t}function ye(t,e,i,s){let r=e[0],a=e[1],o=e[2],h=e[3],n=r+r,l=a+a,c=o+o,d=r*n,x=r*l,v=r*c,b=a*l,m=a*c,M=o*c,y=h*n,f=h*l,g=h*c,p=s[0],w=s[1],P=s[2];return t[0]=(1-(b+M))*p,t[1]=(x+g)*p,t[2]=(v-f)*p,t[3]=0,t[4]=(x-g)*w,t[5]=(1-(d+M))*w,t[6]=(m+y)*w,t[7]=0,t[8]=(v+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 se(t,e,i=0){let s=e[0],r=e[1],a=e[2],o=e[4],h=e[5],n=e[6],l=e[8],c=e[9],d=e[10],x=d*h-n*c,v=-d*o+n*l,b=c*o-h*l,m=s*x+r*v+a*b;return!m||i>0&&(!Number.isFinite(m)||Math.abs(m)<=i)||(m=1/m,t[0]=x*m,t[1]=v*m,t[2]=b*m,t[3]=(-d*r+a*c)*m,t[4]=(d*s-a*l)*m,t[5]=(-c*s+r*l)*m,t[6]=(n*r-a*h)*m,t[7]=(-n*s+a*o)*m,t[8]=(h*s-r*o)*m),t}function Ae(t,e){let i=e[0],s=e[1],r=e[2],a=e[3],o=e[4],h=e[5],n=e[6],l=e[7],c=e[8],d=e[9],x=e[10],v=e[11],b=e[12],m=e[13],M=e[14],y=e[15],f=i*h-s*o,g=i*n-r*o,p=i*l-a*o,w=s*n-r*h,P=s*l-a*h,E=r*l-a*n,U=c*m-d*b,H=c*M-x*b,S=c*y-v*b,T=d*M-x*m,L=d*y-v*m,C=x*y-v*M,u=f*C-g*L+p*T+w*S-P*H+E*U;return u?(u=1/u,t[0]=(h*C-n*L+l*T)*u,t[1]=(r*L-s*C-a*T)*u,t[2]=(m*E-M*P+y*w)*u,t[3]=(x*P-d*E-v*w)*u,t[4]=(n*S-o*C-l*H)*u,t[5]=(i*C-r*S+a*H)*u,t[6]=(M*p-b*E-y*g)*u,t[7]=(c*E-x*p+v*g)*u,t[8]=(o*L-h*S+l*U)*u,t[9]=(s*S-i*L-a*U)*u,t[10]=(b*P-m*p+y*f)*u,t[11]=(d*p-c*P-v*f)*u,t[12]=(h*H-o*T-n*U)*u,t[13]=(i*T-s*H+r*U)*u,t[14]=(m*g-b*w-M*f)*u,t[15]=(c*w-d*g+x*f)*u,t):null}function Me(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],h=r[2]*e+r[6]*i+r[10]*s+r[14],n=r[3]*e+r[7]*i+r[11]*s+r[15],l=n!==0?1/n:1;t[0]=a*l,t[1]=o*l,t[2]=h*l}function Ee(t,e,i,s,r,a,o,h,n,l,c,d,x,v,b,m,M=0){let y=l-o,f=c-h,g=d-n,p=x-o,w=v-h,P=b-n,E=r*P-a*w,U=a*p-s*P,H=s*w-r*p,S=y*E+f*U+g*H;if(S>-1e-7&&S<1e-7)return!1;let T=1/S,L=t-o,C=e-h,u=i-n,R=T*(L*E+C*U+u*H);if(R<-M||R>1+M)return!1;let z=C*g-u*f,J=u*y-L*g,N=L*f-C*y,F=T*(s*z+r*J+a*N);if(F<-M||R+F>1+M)return!1;let D=T*(p*z+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,$=Math.hypot(V,_,k)||1;return m.normal=[V/$,_/$,k/$],!0}return!1}function Le(t,e){let i=Array.isArray(t?.nodes)?t.nodes.length:0,s=[];for(let c=0;c<i;c++)s.push(O());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,h=(c,d,x=0)=>{if(x>o||c<0||c>=i||a.has(c))return;a.add(c);let v=t.nodes[c];if(!v)return;let b=O();if(e&&e[c])b.set(e[c]);else if(v.matrix&&v.matrix.length===16)b.set(v.matrix);else{let M=v.translation||[0,0,0],y=v.rotation||[0,0,0,1],f=v.scale||[1,1,1];ye(b,y,M,f)}let m=s[c];if(d?K(m,d,b):m.set(b),Array.isArray(v.children))for(let M of v.children)typeof M=="number"&&h(M,m,x+1)},n=[],l=t.scenes&&t.scenes[t.scene!==void 0?t.scene:0];if(l&&Array.isArray(l.nodes))n.push(...l.nodes);else for(let c=0;c<i;c++)r.has(c)||n.push(c);for(let c of n)h(c,null);for(let c=0;c<i;c++)!r.has(c)&&!n.includes(c)&&h(c,null);return s}var Te="__THREE_LIVE_REGISTRY__";function ue(){let t=typeof globalThis<"u"?globalThis:{};if(!t[Te]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(t,Te,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{t[Te]=e}}return t[Te]}var Y=ue().plugins;function De(t){let e=ue().plugins;e.some(i=>i.name===t.name)||e.push(t),t.onRegister?.()}function Ce(){return ue().plugins}var Ve=["neutral","reinhard","none","aces","agx"];function be(t){let e=String(t??"").trim().toLowerCase();return Ve.includes(e)?e:"neutral"}function Ue(t){return Ve.indexOf(be(t))}function We(t){return new TextDecoder().decode(t)}var He=ue().decoders;function Oe(t,e){He.set(t.toLowerCase(),e)}function ce(t){return He.get(t.toLowerCase())}function Ge(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 x=i.getUint8(0);throw x===123||x===32||x===10||x===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,h=null,n=null;for(;o+8<=a&&o+8<=e.byteLength;){let x=i.getUint32(o,!0),v=i.getUint32(o+4,!0),b=o+8;if(b+x>e.byteLength)throw new Error(`Truncated GLB chunk: required ${b+x} bytes, buffer has ${e.byteLength}`);if(v===1313821514){let m=new Uint8Array(e,b,x),M=We(m);h=JSON.parse(M,(y,f)=>y==="__proto__"||y==="constructor"||y==="prototype"?void 0:f)}else v===5130562&&(n=e.slice(b,b+x));o=b+x}if(!h)throw new Error("Missing JSON chunk in GLB");let l=h.extensionsRequired||[];if(l.includes("KHR_draco_mesh_compression")&&!ce("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let x of["EXT_meshopt_compression","KHR_meshopt_compression"])if(l.includes(x)&&!ce("meshopt"))throw new Error(`Model requires ${x}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(l.includes("KHR_texture_basisu")&&!ce("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:h,bin:c,animations:[]};for(let x of Y)x.onParseGLB?.(d);return d}function st(t,e,i){return e%4===0?new Float32Array(t,e,i):new Float32Array(t.slice(e,e+i*4))}function ze(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 Se(t){if(ze(t))return t;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return Ge(t);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Xe=`#version 300 es
16
+ */var Le=Object.defineProperty,Qe=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyNames,tt=Object.prototype.hasOwnProperty,nt=(t,e)=>{for(var i in e)Le(t,i,{get:e[i],enumerable:!0})},rt=(t,e,i,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of et(e))!tt.call(t,a)&&a!==i&&Le(t,a,{get:()=>e[a],enumerable:!(s=Qe(e,a))||s.enumerable});return t},it=t=>rt(Le({},"__esModule",{value:!0}),t),gt={};nt(gt,{MicroViewer:()=>le,SANDBOX_HOST_SCENE_LIMITS:()=>ft,ThreeView:()=>le,decodeUtf8:()=>Oe,default:()=>bt,evaluateToneMapping:()=>ut,extractKhrLights:()=>je,getDecoder:()=>pe,getRegisteredPlugins:()=>Fe,isGLBData:()=>Ye,mat3NormalFromMat4:()=>oe,mat4Create:()=>$,mat4FromRotationTranslationScale:()=>ye,mat4Invert:()=>Ee,mat4LookAt:()=>ve,mat4Multiply:()=>Z,mat4Perspective:()=>xe,normalizeToneMapping:()=>fe,parseGLB:()=>_e,rayIntersectsTriangle:()=>Ce,readFloat32Array:()=>at,registerDecoder:()=>Xe,registerPlugin:()=>De,resolveNodeWorldMatrices:()=>Te,sanitizeTextureUri:()=>$e,toGLBData:()=>Ne,toneMappingShaderIndex:()=>He,unprojectPoint:()=>Me}),module.exports=it(gt);var st={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Se(t,e,i,s){if(!i||i.bufferView===void 0)return null;let a=t.bufferViews?.[i.bufferView];if(!a)return null;let r=Number(i.count??0);if(!Number.isInteger(r)||r<=0)return null;let o=i.componentType??5126,n=st[o];if(!n)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let l=n*s,g=a.byteStride&&a.byteStride>0?a.byteStride:l,h=(a.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(h)||h<0||g<l||h+(r-1)*g+l>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(o===5126&&g===l&&h%4===0)return new Float32Array(e,h,r*s);let c=new DataView(e),x=i.normalized===!0,f=new Float32Array(r*s);for(let v=0;v<r;v++){let u=h+v*g;for(let p=0;p<s;p++){let M=u+p*n,d;switch(o){case 5126:d=c.getFloat32(M,!0);break;case 5120:d=c.getInt8(M),x&&(d=Math.max(d/127,-1));break;case 5121:d=c.getUint8(M),x&&(d/=255);break;case 5122:d=c.getInt16(M,!0),x&&(d=Math.max(d/32767,-1));break;case 5123:d=c.getUint16(M,!0),x&&(d/=65535);break;default:d=c.getUint32(M,!0),x&&(d/=4294967295)}f[v*s+p]=d}}return f}function Ve(t,e){let i=Number(e.offset?.[0]??0)||0,s=Number(e.offset?.[1]??0)||0,a=Number(e.scale?.[0]??1),r=Number(e.scale?.[1]??1),o=Number(e.rotation??0)||0,n=Math.cos(o),l=Math.sin(o),g=(Number.isFinite(a)?a:1)*n,h=(Number.isFinite(a)?a:1)*l,c=-(Number.isFinite(r)?r:1)*l,x=(Number.isFinite(r)?r:1)*n;for(let f=0;f+1<t.length;f+=2){let v=t[f],u=t[f+1];t[f]=g*v+h*u+i,t[f+1]=c*v+x*u+s}}function he(t,e,i,s=!0){let a=[],r=null;try{for(let[o,n]of[[35633,e],[35632,i]]){let l=t.createShader(o);if(!l){if(s)throw new Error("Shader allocation failed");return null}if(a.push(l),t.shaderSource(l,n),t.compileShader(l),t.getShaderParameter&&!t.getShaderParameter(l,35713)){if(s)throw new Error(`Shader compile error: ${t.getShaderInfoLog(l)}`);return null}}if(r=t.createProgram(),!r){if(s)throw new Error("Program allocation failed");return null}for(let o of a)t.attachShader(r,o);if(t.linkProgram(r),t.getProgramParameter&&!t.getProgramParameter(r,35714)){let o=s?t.getProgramInfoLog(r):null;if(t.deleteProgram?.(r),r=null,s)throw new Error(`Program link error: ${o}`);return null}return r}finally{for(let o of a)r&&t.detachShader?.(r,o),t.deleteShader?.(o)}}function $(){let t=new Float32Array(16);return t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function xe(t,e,i,s,a){let r=1/Math.tan(e/2);t.fill(0),t[0]=r/i,t[5]=r,t[11]=-1;let o=1/(s-a);return t[10]=(a+s)*o,t[14]=2*a*s*o,t}function ve(t,e,i,s){let[a,r,o]=e,[n,l,g]=s,[h,c,x]=i,f=a-h,v=r-c,u=o-x,p=Math.hypot(f,v,u);p<=1e-5?(f=0,v=0,u=1):(f/=p,v/=p,u/=p);let M=l*u-g*v,d=g*f-n*u,y=n*v-l*f;p=Math.hypot(M,d,y),p<=1e-5?(M=0,d=0,y=0):(M/=p,d/=p,y/=p);let T=v*y-u*d,C=u*M-f*y,b=f*d-v*M;return p=Math.hypot(T,C,b),p<=1e-5?(T=0,C=0,b=0):(T/=p,C/=p,b/=p),t[0]=M,t[1]=T,t[2]=f,t[3]=0,t[4]=d,t[5]=C,t[6]=v,t[7]=0,t[8]=y,t[9]=b,t[10]=u,t[11]=0,t[12]=-(M*a+d*r+y*o),t[13]=-(T*a+C*r+b*o),t[14]=-(f*a+v*r+u*o),t[15]=1,t}function Z(t,e,i){let s=e[0],a=e[1],r=e[2],o=e[3],n=e[4],l=e[5],g=e[6],h=e[7],c=e[8],x=e[9],f=e[10],v=e[11],u=e[12],p=e[13],M=e[14],d=e[15],y=i[0],T=i[1],C=i[2],b=i[3];return t[0]=y*s+T*n+C*c+b*u,t[1]=y*a+T*l+C*x+b*p,t[2]=y*r+T*g+C*f+b*M,t[3]=y*o+T*h+C*v+b*d,y=i[4],T=i[5],C=i[6],b=i[7],t[4]=y*s+T*n+C*c+b*u,t[5]=y*a+T*l+C*x+b*p,t[6]=y*r+T*g+C*f+b*M,t[7]=y*o+T*h+C*v+b*d,y=i[8],T=i[9],C=i[10],b=i[11],t[8]=y*s+T*n+C*c+b*u,t[9]=y*a+T*l+C*x+b*p,t[10]=y*r+T*g+C*f+b*M,t[11]=y*o+T*h+C*v+b*d,y=i[12],T=i[13],C=i[14],b=i[15],t[12]=y*s+T*n+C*c+b*u,t[13]=y*a+T*l+C*x+b*p,t[14]=y*r+T*g+C*f+b*M,t[15]=y*o+T*h+C*v+b*d,t}function ye(t,e,i,s){let a=e[0],r=e[1],o=e[2],n=e[3],l=a+a,g=r+r,h=o+o,c=a*l,x=a*g,f=a*h,v=r*g,u=r*h,p=o*h,M=n*l,d=n*g,y=n*h,T=s[0],C=s[1],b=s[2];return t[0]=(1-(v+p))*T,t[1]=(x+y)*T,t[2]=(f-d)*T,t[3]=0,t[4]=(x-y)*C,t[5]=(1-(c+p))*C,t[6]=(u+M)*C,t[7]=0,t[8]=(f+d)*b,t[9]=(u-M)*b,t[10]=(1-(c+v))*b,t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1,t}function oe(t,e,i=0){let s=e[0],a=e[1],r=e[2],o=e[4],n=e[5],l=e[6],g=e[8],h=e[9],c=e[10],x=c*n-l*h,f=-c*o+l*g,v=h*o-n*g,u=s*x+a*f+r*v;return!u||i>0&&(!Number.isFinite(u)||Math.abs(u)<=i)||(u=1/u,t[0]=x*u,t[1]=f*u,t[2]=v*u,t[3]=(-c*a+r*h)*u,t[4]=(c*s-r*g)*u,t[5]=(-h*s+a*g)*u,t[6]=(l*a-r*n)*u,t[7]=(-l*s+r*o)*u,t[8]=(n*s-a*o)*u),t}function Ee(t,e){let i=e[0],s=e[1],a=e[2],r=e[3],o=e[4],n=e[5],l=e[6],g=e[7],h=e[8],c=e[9],x=e[10],f=e[11],v=e[12],u=e[13],p=e[14],M=e[15],d=i*n-s*o,y=i*l-a*o,T=i*g-r*o,C=s*l-a*n,b=s*g-r*n,E=a*g-r*l,D=h*u-c*v,A=h*p-x*v,w=h*M-f*v,R=c*p-x*u,V=c*M-f*u,U=x*M-f*p,L=d*U-y*V+T*R+C*w-b*A+E*D;return L?(L=1/L,t[0]=(n*U-l*V+g*R)*L,t[1]=(a*V-s*U-r*R)*L,t[2]=(u*E-p*b+M*C)*L,t[3]=(x*b-c*E-f*C)*L,t[4]=(l*w-o*U-g*A)*L,t[5]=(i*U-a*w+r*A)*L,t[6]=(p*T-v*E-M*y)*L,t[7]=(h*E-x*T+f*y)*L,t[8]=(o*V-n*w+g*D)*L,t[9]=(s*w-i*V-r*D)*L,t[10]=(v*b-u*T+M*d)*L,t[11]=(c*T-h*b-f*d)*L,t[12]=(n*A-o*R-l*D)*L,t[13]=(i*R-s*A+a*D)*L,t[14]=(u*y-v*C-p*d)*L,t[15]=(h*C-c*y+x*d)*L,t):null}function Me(t,e,i,s,a){let r=a[0]*e+a[4]*i+a[8]*s+a[12],o=a[1]*e+a[5]*i+a[9]*s+a[13],n=a[2]*e+a[6]*i+a[10]*s+a[14],l=a[3]*e+a[7]*i+a[11]*s+a[15],g=l!==0?1/l:1;t[0]=r*g,t[1]=o*g,t[2]=n*g}function Ce(t,e,i,s,a,r,o,n,l,g,h,c,x,f,v,u,p=0){let M=g-o,d=h-n,y=c-l,T=x-o,C=f-n,b=v-l,E=a*b-r*C,D=r*T-s*b,A=s*C-a*T,w=M*E+d*D+y*A;if(w>-1e-7&&w<1e-7)return!1;let R=1/w,V=t-o,U=e-n,L=i-l,P=R*(V*E+U*D+L*A);if(P<-p||P>1+p)return!1;let S=U*y-L*d,H=L*M-V*y,m=V*d-U*M,F=R*(s*S+a*H+r*m);if(F<-p||P+F>1+p)return!1;let k=R*(T*S+C*H+b*m);if(k>1e-4&&k<u.distance){u.distance=k,u.point=[t+s*k,e+a*k,i+r*k];let _=d*b-y*C,N=y*T-M*b,I=M*C-d*T,B=Math.hypot(_,N,I)||1;return u.normal=[_/B,N/B,I/B],!0}return!1}function Te(t,e){let i=Array.isArray(t?.nodes)?t.nodes.length:0,s=[];for(let h=0;h<i;h++)s.push($());if(i===0)return s;let a=new Set;for(let h of t.nodes)if(Array.isArray(h.children))for(let c of h.children)a.add(c);let r=new Set,o=128,n=(h,c,x=0)=>{if(x>o||h<0||h>=i||r.has(h))return;r.add(h);let f=t.nodes[h];if(!f)return;let v=$();if(e&&e[h])v.set(e[h]);else if(f.matrix&&f.matrix.length===16)v.set(f.matrix);else{let p=f.translation||[0,0,0],M=f.rotation||[0,0,0,1],d=f.scale||[1,1,1];ye(v,M,p,d)}let u=s[h];if(c?Z(u,c,v):u.set(v),Array.isArray(f.children))for(let p of f.children)typeof p=="number"&&n(p,u,x+1)},l=[],g=t.scenes&&t.scenes[t.scene!==void 0?t.scene:0];if(g&&Array.isArray(g.nodes))l.push(...g.nodes);else for(let h=0;h<i;h++)a.has(h)||l.push(h);for(let h of l)n(h,null);for(let h=0;h<i;h++)!a.has(h)&&!l.includes(h)&&n(h,null);return s}var we="__THREE_LIVE_REGISTRY__";function ue(){let t=typeof globalThis<"u"?globalThis:{};if(!t[we]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(t,we,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{t[we]=e}}return t[we]}var K=ue().plugins;function De(t){let e=ue().plugins;e.some(i=>i.name===t.name)||e.push(t),t.onRegister?.()}function Fe(){return ue().plugins}var We=["neutral","reinhard","none","aces","agx"];function fe(t){let e=String(t??"").trim().toLowerCase();return We.includes(e)?e:"neutral"}function He(t){return We.indexOf(fe(t))}function Oe(t){return new TextDecoder().decode(t)}var ze=ue().decoders;function Xe(t,e){ze.set(t.toLowerCase(),e)}function pe(t){return ze.get(t.toLowerCase())}function _e(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 x=i.getUint8(0);throw x===123||x===32||x===10||x===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 a=i.getUint32(4,!0);if(a!==2)throw new Error(`Unsupported GLB version: ${a}`);let r=i.getUint32(8,!0),o=12,n=null,l=null;for(;o+8<=r&&o+8<=e.byteLength;){let x=i.getUint32(o,!0),f=i.getUint32(o+4,!0),v=o+8;if(v+x>e.byteLength)throw new Error(`Truncated GLB chunk: required ${v+x} bytes, buffer has ${e.byteLength}`);if(f===1313821514){let u=new Uint8Array(e,v,x),p=Oe(u);n=JSON.parse(p,(M,d)=>M==="__proto__"||M==="constructor"||M==="prototype"?void 0:d)}else f===5130562&&(l=e.slice(v,v+x));o=v+x}if(!n)throw new Error("Missing JSON chunk in GLB");let g=n.extensionsRequired||[];for(let[x,f]of[["KHR_draco_mesh_compression","draco"],["EXT_meshopt_compression","meshopt"],["KHR_meshopt_compression","meshopt"],["KHR_texture_basisu","ktx2"]])if(g.includes(x)&&!pe(f))throw new Error(`Model requires ${x}. Register a decoder via ThreeLiveElement.registerDecoder('${f}', decoder).`);let h=l||new ArrayBuffer(0),c={gltf:n,bin:h,animations:[],animationsParsed:!1};for(let x of K)x.onParseGLB?.(c);return c}function je(t,e=Te(t)){let i=t?.extensions?.KHR_lights_punctual?.lights;if(!Array.isArray(i))return[];let s=[],a=new Set,r=(o,n,l,g)=>{let h=o.type,c=h==="directional"||h==="point"||h==="spot"?h:"ambient",x=n?n[8]:-.5,f=n?n[9]:-1,v=n?n[10]:-.8,u=Math.hypot(x,f,v)||1,p=o.extras?.shadow??l,M=o.name||g,d={type:c,color:o.color||[1,1,1],intensity:o.intensity??1};M&&(d.name=M),n&&(d.position=[n[12],n[13],n[14]]),c==="directional"&&n?d.direction=[x/u,f/u,v/u]:(c==="spot"&&(d.direction=n?[-x/u,-f/u,-v/u]:[0,-1,0],d.innerConeAngle=o.spot?.innerConeAngle??0,d.outerConeAngle=o.spot?.outerConeAngle??Math.PI/4),d.range=o.range),p&&(d.shadow=p),s.push(d)};return(t.nodes||[]).forEach((o,n)=>{let l=o?.extensions?.KHR_lights_punctual?.light;typeof l=="number"&&i[l]&&(a.add(l),r(i[l],e[n],o.extras?.shadow,o.name))}),i.forEach((o,n)=>{a.has(n)||r(o)}),s}function at(t,e,i){return e%4===0?new Float32Array(t,e,i):new Float32Array(t.slice(e,e+i*4))}function Ye(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 Ne(t){if(Ye(t))return t;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return _e(t);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var ke=`#version 300 es
17
17
  layout(location=0) in vec3 aPos;
18
18
  layout(location=3) in vec3 aOff;
19
19
  layout(location=1) in vec3 aNormal;
@@ -57,117 +57,81 @@ in vec4 vInstTint;
57
57
  #define uBaseColor (uBaseColor*vInstTint)
58
58
  uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity,uExposure;
59
59
  uniform vec2 uClearcoat;
60
- uniform vec3 uCameraPos,uAmbientColor;
61
- uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap;
62
- uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap;
60
+ uniform vec3 uCameraPos,uAmbientColor,uEmissiveFactor;
61
+ uniform mat3 uHemi;
62
+ uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap,uEmissiveTexture;
63
+ uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap,uHasEmissiveTexture;
63
64
  uniform float uNormalScale,uOcclusionStrength;
64
- /*XRD_U*/
65
+ /*XRD_U*//*SHD_U*/
65
66
  uniform vec2 uViewportSize;
66
67
  uniform vec4 uSectionPlane;
67
68
  uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
68
69
  uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2],uPointLightSpotDir[2];
69
70
  uniform vec2 uPointLightSpotCone[2];
70
71
  out vec4 fragColor;
71
-
72
72
  vec2 envBRDF(float r,float n){
73
- vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04);
74
- vec4 rv=r*c0+c1;
73
+ vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04),rv=r*c0+c1;
75
74
  float a=min(rv.x*rv.x,exp2(-9.28*n))*rv.x+rv.y;
76
75
  return vec2(-1.04,1.04)*a+rv.zw;
77
76
  }
78
-
79
77
  vec3 F_SchlickRoughness(vec3 F0,float r,float n){
80
78
  return F0+(max(vec3(1.0-r),F0)-F0)*pow(clamp(1.0-n,0.0,1.0),5.0);
81
79
  }
82
-
83
80
  vec3 getStudioRadiance(vec3 R,float r){
84
- vec3 kd=normalize(vec3(0.0,1.0,0.35));
81
+ vec3 kd=normalize(vec3(0.0,1.0,0.35)),fd=normalize(vec3(-0.85,0.45,-0.35));
85
82
  float ki=pow(max(dot(R,kd),0.0),mix(96.0,1.5,r))*mix(2.4,0.5,r);
86
- vec3 fd=normalize(vec3(-0.85,0.45,-0.35));
87
83
  float fi=pow(max(dot(R,fd),0.0),mix(36.0,1.2,r))*mix(1.3,0.35,r);
88
84
  float ri=pow(clamp(1.0-abs(R.y),0.0,1.0),3.5)*mix(0.55,0.22,r);
89
- vec3 ag=mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5);
90
- return ag+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
85
+ return mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5)+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
91
86
  }
92
-
93
- vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D normalMap,float scale){
94
- vec3 mapNormal=texture(normalMap,uv).xyz*2.0-1.0;
95
- mapNormal.xy*=scale;
96
- vec3 dp1=dFdx(vWorldPos);
97
- vec3 dp2=dFdy(vWorldPos);
98
- vec2 duv1=dFdx(uv);
99
- vec2 duv2=dFdy(uv);
100
- vec3 dp2perp=cross(dp2,N);
101
- vec3 dp1perp=cross(N,dp1);
102
- vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;
103
- vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;
104
- float invmax=inversesqrt(max(dot(T,T),dot(B,B)));
105
- return normalize(mat3(T*invmax,B*invmax,N)*normalize(mapNormal));
87
+ vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D m,float s){
88
+ vec3 q=texture(m,uv).xyz*2.0-1.0;q.xy*=s;
89
+ vec3 p1=dFdx(vWorldPos),p2=dFdy(vWorldPos),c2=cross(p2,N),c1=cross(N,p1);
90
+ vec2 u1=dFdx(uv),u2=dFdy(uv);
91
+ vec3 T=c2*u1.x+c1*u2.x,B=c2*u1.y+c1*u2.y;
92
+ float k=inversesqrt(max(dot(T,T),dot(B,B)));
93
+ return normalize(mat3(T*k,B*k,N)*normalize(q));
106
94
  }
107
-
108
95
  vec2 equirectangularUV(vec3 dir){
109
96
  vec3 d=normalize(dir);
110
- float u=atan(d.z,d.x)*0.15915494309+0.5;
111
- float v=asin(clamp(d.y,-1.0,1.0))*0.31830988618+0.5;
112
- return vec2(u,1.0-v);
97
+ return vec2(atan(d.z,d.x)*0.15915494309+0.5,0.5-asin(clamp(d.y,-1.0,1.0))*0.31830988618);
113
98
  }
114
-
115
- vec3 neutralToneMapping(vec3 color){
116
- const float startCompression=0.76;
117
- const float desaturation=0.15;
118
- float x=min(color.r,min(color.g,color.b));
119
- float offset=x<0.08?x-6.25*x*x:0.04;
120
- color-=offset;
121
- float peak=max(color.r,max(color.g,color.b));
122
- if(peak<startCompression)return color;
123
- const float d=1.0-startCompression;
124
- float newPeak=1.0-d*d/(peak+d-startCompression);
125
- color*=newPeak/peak;
126
- float g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);
127
- return mix(color,newPeak*vec3(1.0),g);
99
+ vec3 neutralToneMapping(vec3 c){
100
+ float x=min(c.r,min(c.g,c.b));
101
+ c-=x<0.08?x-6.25*x*x:0.04;
102
+ float p=max(c.r,max(c.g,c.b));
103
+ if(p<0.76)return c;
104
+ float n=1.0-0.0576/(p-0.52);
105
+ c*=n/p;
106
+ return mix(c,vec3(n),1.0-1.0/(0.15*(p-n)+1.0));
128
107
  }
129
-
130
- vec3 acesToneMapping(vec3 color){
131
- color*=0.6;
132
- return clamp((color*(2.51*color+0.03))/(color*(2.43*color+0.59)+0.14),0.0,1.0);
108
+ vec3 acesToneMapping(vec3 c){
109
+ c*=0.6;return clamp((c*(2.51*c+0.03))/(c*(2.43*c+0.59)+0.14),0.0,1.0);
133
110
  }
134
-
135
- vec3 agxToneMapping(vec3 color){
136
- color=max(color,vec3(0.0));
137
- vec3 inset=vec3(
138
- 0.84247906*color.r+0.0784336*color.g+0.07922375*color.b,
139
- 0.04232824*color.r+0.87846864*color.g+0.07916613*color.b,
140
- 0.04237565*color.r+0.0784336*color.g+0.87914297*color.b);
141
- vec3 ev=clamp((log2(max(inset,vec3(1e-6)))+12.47393)/16.5,0.0,1.0);
142
- vec3 x2=ev*ev;
143
- vec3 x4=x2*x2;
144
- vec3 s=15.5*x4*x2-40.14*x4*ev+31.96*x4-6.868*x2*ev+0.4298*x2+0.1191*ev-0.00232;
145
- vec3 outset=vec3(
146
- 1.196879*s.r-0.09802088*s.g-0.09902974*s.b,
147
- -0.05289685*s.r+1.15190313*s.g-0.09896118*s.b,
148
- -0.05297164*s.r-0.09804345*s.g+1.15107367*s.b);
149
- return clamp(pow(max(outset,vec3(0.0)),vec3(2.2)),0.0,1.0);
111
+ vec3 agxToneMapping(vec3 c){
112
+ c=max(c,vec3(0.0));
113
+ vec3 i=mat3(0.84247906,0.04232824,0.04237565,0.0784336,0.87846864,0.0784336,0.07922375,0.07916613,0.87914297)*c;
114
+ vec3 e=clamp((log2(max(i,vec3(1e-6)))+12.47393)/16.5,0.0,1.0),x2=e*e,x4=x2*x2;
115
+ vec3 s=15.5*x4*x2-40.14*x4*e+31.96*x4-6.868*x2*e+0.4298*x2+0.1191*e-0.00232;
116
+ vec3 o=mat3(1.196879,-0.05289685,-0.05297164,-0.09802088,1.15190313,-0.09804345,-0.09902974,-0.09896118,1.15107367)*s;
117
+ return clamp(pow(max(o,vec3(0.0)),vec3(2.2)),0.0,1.0);
150
118
  }
151
-
152
- vec3 applyToneMapping(vec3 color,int mode){
153
- if(mode==0)return neutralToneMapping(color);
154
- if(mode==1)return color/(color+vec3(1.0));
155
- if(mode==3)return acesToneMapping(color);
156
- if(mode==4)return agxToneMapping(color);
157
- return color;
119
+ vec3 applyToneMapping(vec3 c,int m){
120
+ return m==0?neutralToneMapping(c):m==1?c/(c+vec3(1.0)):m==3?acesToneMapping(c):m==4?agxToneMapping(c):c;
158
121
  }
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);
122
+ vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 b,float e,float w){
123
+ float h=max(dot(N,normalize(L+V)),0.0);
124
+ return b*max(dot(N,L),0.0)*0.75+vec3(pow(h,e)*w+uClearcoat.x*pow(h,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
163
125
  }
164
126
 
165
127
  void main(){
166
128
  if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
167
129
  vec4 base=uBaseColor;
168
130
  if(uHasTexture==1)base*=texture(uBaseColorTexture,vUV);
131
+ if(base.a<0.004)discard;
132
+ vec3 em=uHasEmissiveTexture==1?uEmissiveFactor*texture(uEmissiveTexture,vUV).rgb:uEmissiveFactor;
169
133
  if(length(vNormal)<1e-4&&uHasTexture==1){
170
- vec3 unlit=base.rgb+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
134
+ vec3 unlit=base.rgb+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
171
135
  fragColor=vec4(unlit,base.a);
172
136
  return;
173
137
  }
@@ -199,7 +163,7 @@ float specWeight=mix(0.22*gloss,1.0,metallic);
199
163
  vec3 directLight=vec3(0.0);
200
164
  for(int i=0;i<2;i++){
201
165
  if(i>=uNumDirLights)break;
202
- directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i];
166
+ directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i]/*SHD_D*/;
203
167
  }
204
168
  for(int i=0;i<2;i++){
205
169
  if(i>=uNumPointLights)break;
@@ -208,7 +172,7 @@ float dist=length(toLight);
208
172
  vec3 L=toLight/max(dist,0.0001);
209
173
  float spotAtt=clamp((dot(-L,uPointLightSpotDir[i])-uPointLightSpotCone[i].y)/max(uPointLightSpotCone[i].x-uPointLightSpotCone[i].y,0.0001),0.0,1.0);
210
174
  spotAtt*=spotAtt;
211
- directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist);
175
+ directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist)/*SHD_P*/;
212
176
  }
213
177
 
214
178
  vec3 R=reflect(-V,N);
@@ -228,8 +192,9 @@ envDiffuse=mix(vec3(0.10,0.10,0.12),vec3(0.52,0.54,0.58),N.y*0.5+0.5);
228
192
  }
229
193
 
230
194
  vec3 kD=(vec3(1.0)-F)*(1.0-metallic);
195
+ directLight+=kD*base.rgb*mix(uHemi[1],uHemi[0],dot(N,uHemi[2])*0.5+0.5)*occ;
231
196
  vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
232
- vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
197
+ vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
233
198
  if(uClearcoat.x>0.0){
234
199
  vec3 ccF=F_SchlickRoughness(vec3(0.04),uClearcoat.y,NoV)*uClearcoat.x;
235
200
  color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
@@ -239,11 +204,11 @@ color=applyToneMapping(color,uToneMapping);
239
204
  float outAlpha=base.a;
240
205
  /*XRD_O*/
241
206
  fragColor=vec4(color,outAlpha);
242
- }`;function at(t,e,i=1){e=be(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)),h=m=>Math.max(0,Math.min(1,m)),n=m=>[m(r),m(a),m(o)];if(e==="none")return n(h);if(e==="reinhard")return n(m=>m/(m+1));if(e==="aces")return n(m=>{let M=m*.6;return h(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=h((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=>h(Math.pow(Math.max(f,0),2.2)))}let l=Math.min(r,a,o),c=l<.08?l-6.25*l*l:.04;[r,a,o]=n(m=>m-c);let d=Math.max(r,a,o);if(d<.76)return n(h);let x=1-.0576/(d-.52),v=x/d,b=1-1/(.15*(d-x)+1);return n(m=>h(m*v+(x-m*v)*b))}var ut=`#version 300 es
207
+ }`;function ut(t,e,i=1){e=fe(e);let s=Number.isFinite(i)?Math.max(0,i):1,[a,r,o]=[0,1,2].map(u=>Math.max(0,(Number(t[u])||0)*s)),n=u=>Math.max(0,Math.min(1,u)),l=u=>[u(a),u(r),u(o)];if(e==="none")return l(n);if(e==="reinhard")return l(u=>u/(u+1));if(e==="aces")return l(u=>{let p=u*.6;return n(p*(2.51*p+.03)/(p*(2.43*p+.59)+.14))});if(e==="agx"){let[u,p,M]=[.84247906*a+.0784336*r+.07922375*o,.04232824*a+.87846864*r+.07916613*o,.04237565*a+.0784336*r+.87914297*o].map(d=>{let y=n((Math.log2(Math.max(d,1e-6))+12.47393)/16.5),T=y*y,C=T*T;return 15.5*C*T-40.14*C*y+31.96*C-6.868*T*y+.4298*T+.1191*y-.00232});return[1.196879*u-.09802088*p-.09902974*M,-.05289685*u+1.15190313*p-.09896118*M,-.05297164*u-.09804345*p+1.15107367*M].map(d=>n(Math.pow(Math.max(d,0),2.2)))}let g=Math.min(a,r,o),h=g<.08?g-6.25*g*g:.04;[a,r,o]=l(u=>u-h);let c=Math.max(a,r,o);if(c<.76)return l(n);let x=1-.0576/(c-.52),f=x/c,v=1-1/(.15*(c-x)+1);return l(u=>n(u*f+(x-u*f)*v))}var ct=`#version 300 es
243
208
  layout(location=0) in vec3 aPosition;
244
209
  uniform mat4 uMVP;
245
- void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,ct=`#version 300 es
210
+ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,lt=`#version 300 es
246
211
  precision highp float;
247
212
  uniform vec4 uColorId;
248
213
  out vec4 fragColor;
249
- void main(){fragColor=uColorId;}`;function Ne(t,e,i){let s={};for(let r of i)s[r]=t.getUniformLocation(e,r);return s}var ke=["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 je(){let t=ue().xrDepthShader;return{fs:ot.replace("/*XRD_U*/",t?.uniformsGLSL||"").replace("/*XRD_O*/",t?.occlusionGLSL||""),uniforms:t?[...ke,...t.uniformNames]:ke}}function Ye(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 Ie(t,e,i,s,r,a,o,h){if(s===void 0||!e.accessors?.[s])return null;let n=Pe(e,i,e.accessors[s],a);if(!n)return null;h&&(n=n.slice(),Be(n,h));let l=t.createBuffer();return o.push(l),t.bindBuffer(34962,l),t.bufferData(34962,n,35044),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,a,5126,!1,0,0),n}function Fe(t){let e=Number(t);return Number.isFinite(e)?Math.max(0,e):1}function $e(t,e,i){let s=je(),r=Xe,a=s.fs,o=!1;for(let n of Y)if(n.onResolveShader){let l=n.onResolveShader(e,i,r,a);l&&(r=l.vs,a=l.fs,o=!0)}let h=o?ve(t,r,a):null;return{program:h,uniforms:h?Ne(t,h,s.uniforms):null}}function lt(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 h=t.createBuffer();i.push(h),t.bindBuffer(34962,h),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 ht(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 mt=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Ke=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Re(t,e){e.indices?t.drawElements(4,e.indexCount,e.indexType,0):t.drawArrays(4,0,e.indexCount)}function qe(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 Ze(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 h=new Set;o.customProgram&&h.add(o.customProgram);for(let n of o.programCache?.values()??[])n.program&&h.add(n.program);for(let n of h)t.deleteProgram(n)}if(i)for(let a of i)r(a)}function _e(t,e,i=Ke,s){let r={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return ft(t,e,i,s,r)}catch(a){let o=r.mesh&&!r.meshes.includes(r.mesh)?[...r.meshes,r.mesh]:r.meshes;Ze(t,o,r.gpuTextures),r.vao&&t.deleteVertexArray(r.vao);for(let h of r.buffers)t.deleteBuffer(h);throw a}}function ft(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=ce("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(a,e);let h=e.bin,n=[];r.meshes=n;let l=[],c=a.extensions?.KHR_materials_variants;c&&Array.isArray(c.variants)&&c.variants.forEach((C,u)=>{l.push(typeof C?.name=="string"&&C.name?C.name:`Variant_${u}`)});let d=Le(a),x=[];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]&&x.push({node:u,nodeIdx:C,meshIdx:u.mesh})}let v=x.length>0?x:(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]})),v.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${v.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 z=t.createTexture();t.bindTexture(3553,z),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,z),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([h.slice(F,F+N.byteLength)],{type:R.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(D).then(J).catch(()=>{})}else if(R.uri){let N=Ye(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(z)}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<v.length;C++){let u=v[C],R=a.meshes[u.meshIdx],z=u.nodeIdx>=0?d[u.nodeIdx]:O(),J=new Float32Array(9);se(J,z);let N={name:u.node.name||R.name||`Mesh_${u.meshIdx}`,nodeIndex:u.nodeIdx,transform:z,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,$=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 vt=(A,G)=>{if(!A||A.bufferView===void 0||!a.bufferViews?.[A.bufferView])return null;let q=A.componentType??5126,gt=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 gt(`componentType ${q}`);if(!(Number(A.count)>=B))return gt(`count ${A.count} < ${B}`);let I=null;try{I=Pe(a,h,{...A,count:B},G)}catch{return gt("out of bounds")}return!I||!I.every(Number.isFinite)?gt("non-finite value"):I},W=vt(V,3),Q=vt(_,4),xt=vt(k,3),bt=$?.type==="VEC4"?4:3,X=vt($,bt),Mt=new Float32Array(B*16),yt=O();for(let A=0;A<B;A++){let G=W?[W[A*3],W[A*3+1],W[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],gt=xt?[xt[A*3],xt[A*3+1],xt[A*3+2]]:[1,1,1];ye(yt,q,G,gt),Mt.set(yt,A*16)}if(N.instanceMatrices=Mt,X){let A=new Float32Array(B*3);for(let G=0;G<B;G++)A[G*3]=X[G*bt],A[G*3+1]=X[G*bt+1],A[G*3+2]=X[G*bt+2];N.instanceColors=A}}}for(let D of R.primitives||[]){if(D.extensions?.KHR_draco_mesh_compression){let I=ce("draco");I&&I.decodePrimitive(a,D,h)}let V=[],_=t.createVertexArray();r.vao=_,r.buffers=V,t.bindVertexArray(_);let k=lt(t,N,V),$=a.accessors[D.attributes.POSITION],B=Number($?.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,$?.min&&$?.max){let I=j=>{for(let Z=0;Z<3;Z++){let Tt=j[12+Z],wt=j[12+Z];for(let Pt=0;Pt<3;Pt++){let Ct=j[Pt*4+Z]*$.min[Pt],Dt=j[Pt*4+Z]*$.max[Pt];Tt+=Ct<Dt?Ct:Dt,wt+=Ct>Dt?Ct:Dt}Tt<y[Z]&&(y[Z]=Tt),wt>f[Z]&&(f[Z]=wt)}};if(N.instanceMatrices&&N.instanceMatrices.length>=16){let j=N.instanceMatrices.length>>4,Z=O();for(let Tt=0;Tt<j;Tt++){let wt=N.instanceMatrices.subarray(Tt*16,Tt*16+16);K(Z,z,wt),I(Z)}}else I(z)}let vt=Ie(t,a,h,D.attributes.POSITION,0,3,V);Ie(t,a,h,D.attributes.NORMAL,1,3,V),Ie(t,a,h,D.attributes.TEXCOORD_0,2,2,V,ht(a,D));let W=0,Q=5123,xt=null;if(D.indices!==void 0){let I=a.accessors[D.indices],j=(a.bufferViews[I.bufferView].byteOffset||0)+(I.byteOffset||0);if(W=Number(I.count??0),!Number.isFinite(W)||W<0||p+W>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);p+=W,Q=I.componentType===5125?5125:5123;let Z=t.createBuffer();V.push(Z),t.bindBuffer(34963,Z),I.componentType===5125?xt=new Uint32Array(h,j,I.count):I.componentType===5121?xt=Uint16Array.from(new Uint8Array(h,j,I.count)):xt=j%2===0?new Uint16Array(h,j,I.count):new Uint16Array(h.slice(j,j+I.count*2)),t.bufferData(34963,xt,35044)}else W=$.count;let bt={};for(let I of Y)if(I.onBuildPrimitiveVAO){let j=I.onBuildPrimitiveVAO(t,_,D,a,h);j&&(bt[I.name]=j)}t.bindVertexArray(null);let X=a.materials&&D.material!==void 0?a.materials[D.material]:null,{program:Mt,uniforms:yt}=$e(t,D,X),A=qe(X,M),G=!!(X?.extensions?.KHR_materials_transmission||bt.materials?.isTransmissive),q=D.extensions?.KHR_materials_variants?.mappings,gt=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:W,indexType:Q,...A,positions:vt,indices:xt,buffers:V,materialIndex:D.material,defaultMaterialIndex:D.material,variantMappings:gt,primitiveDef:D,programCache:new Map([[D.material??-1,{program:Mt,uniforms:yt}]]),pluginData:bt,customProgram:Mt,customUniforms:yt,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],U=f[2]-y[2],H=Math.max(Math.hypot(P,E,U)/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 Y)if(C.onParseGLB?.(e),e.animations){L=e.animations;break}}return L||(L=[]),{meshes:n,bounds:{center:w,radius:H,min:S,max:T},lights:b,animations:L,worldMatrices:d,gpuTextures:M,availableVariants:l}}function pe(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 he=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=O(),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=O(),this.viewMatrix=O(),this.activeViewMatrix=null,this.modelMatrix=O(),this.mvpMatrix=O(),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:O(),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 h=t.querySelector("canvas");h||(h=document.createElement("canvas"),h.style.width="100%",h.style.height="100%",h.style.display="block",h.style.touchAction="none",t.prepend(h)),s=h}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=Fe(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=be(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){Oe(t,e)}static getDecoder(t){return ce(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=je();this.renderProg=ve(t,Xe,e.fs),this.pickProg=ve(t,ut,ct),this.uRender=Ne(t,this.renderProg,e.uniforms),this.uPick=Ne(t,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let t=this.gl;this.contextLost=!1,this.initGlState();for(let e of Y)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:h,availableVariants:n}=_e(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=h||[],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 Y)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 l=t.exposure??t.gltf?.extras?.exposure??t.gltf?.asset?.extras?.exposure;l!==void 0&&(this.exposure=Fe(l));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(Ge(t))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let t of Y)t.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(t){this.loadGLBData(Se(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let i=Se(t),{meshes:s}=_e(this.gl,i,Ke,()=>this.render());if(e)for(let r of s)r.transform[12]+=e[0],r.transform[13]+=e[1],r.transform[14]+=e[2],se(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),se(i.normalMatrix,i.transform))}}bindLights(t=this.uRender){let e=this.gl,i=[.28,.28,.28],s=[],r=[],a=[],o=[],h=[],n=[];for(let l of this.lights){let c=l.color||[1,1,1],d=l.intensity!==void 0?l.intensity:1;if(l.type==="ambient")i=[c[0]*d,c[1]*d,c[2]*d];else if(l.type==="directional"&&s.length<6){let x=l.direction||[.5,1,.8];s.push(x[0],x[1],x[2]),r.push(c[0]*d,c[1]*d,c[2]*d)}else if((l.type==="point"||l.type==="spot")&&a.length<6){let x=l.position||[0,0,0];if(a.push(x[0],x[1],x[2]),o.push(c[0]*d,c[1]*d,c[2]*d),l.type==="spot"){let v=l.direction||[0,-1,0],b=Math.max(.01,Math.min(Math.PI/2,l.outerConeAngle??Math.PI/3)),m=Math.max(0,Math.min(b-1e-4,l.innerConeAngle??0));h.push(v[0],v[1],v[2]),n.push(Math.cos(m),Math.cos(b))}else h.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,h),t.uPointLightSpotCone&&e.uniform2fv(t.uPointLightSpotCone,n)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.exposure=Fe(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=be(t)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of Y)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of Y)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(l=>l.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,h=r?r.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,n={baseColorFactor:a,metallicFactor:o,roughnessFactor:h,setBaseColorFactor:l=>{let c=[l[0],l[1],l[2],l[3]??1];n.baseColorFactor=c,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=c);for(let d of s)d.baseColor=c;this.render()},setMetallicFactor:l=>{n.metallicFactor=l,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=l);for(let c of s)c.metallic=l;this.render()},setRoughnessFactor:l=>{n.roughnessFactor=l,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=l);for(let c of s)c.roughness=l;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 h=o!==void 0?s[o]:void 0;a.materialIndex=h?o:void 0,Object.assign(a,qe(h,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,h??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=$e(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 Y)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=O();K(i,this.projMatrix,this.viewMatrix);let[s,r,a]=t,o=e?e[0]:0,h=e?e[1]:0,n=e?e[2]:0,l=this.modelRootMatrix;l&&(s=l[0]*t[0]+l[4]*t[1]+l[8]*t[2]+l[12],r=l[1]*t[0]+l[5]*t[1]+l[9]*t[2]+l[13],a=l[2]*t[0]+l[6]*t[1]+l[10]*t[2]+l[14],e&&(o=l[0]*e[0]+l[4]*e[1]+l[8]*e[2],h=l[1]*e[0]+l[5]*e[1]+l[9]*e[2],n=l[2]*e[0]+l[6]*e[1]+l[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],x=i[2]*s+i[6]*r+i[10]*a+i[14],v=i[3]*s+i[7]*r+i[11]*a+i[15];if(v<=1e-4)return{x:0,y:0,z:1,visible:!1};let b=c/v,m=d/v,M=x/v,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,U,H]=pe(this),S=[s-E,r-U,a-H];o*S[0]+h*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]],h=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],n=this.customTarget?[...this.customTarget]:[...this.bounds.center],l=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;n[0]+=(-r*o[0]+a*h[0])*l,n[1]+=(-r*o[1]+a*h[1])*l,n[2]+=(-r*o[2]+a*h[2])*l,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),h=s.height>0?Math.floor((e-s.top)*(a/s.height)):Math.floor(e);return this.performMeshPick(o,h,!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=O();K(o,this.projMatrix,this.viewMatrix);let h=[],n=Math.max(0,Math.min(r-1,t)),l=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,U=(E&255)/255,H=(E>>8&255)/255,S=(E>>16&255)/255;s.uniform4f(this.uPick.uColorId,U,H,S,1),K(this.modelMatrix,this.modelRootMatrix,P.transform);let T=P.instanceMatrices;if(T&&T.length>=16){let L=T.length>>4,C=O();for(let u of P.primitives){s.bindVertexArray(u.vao);for(let R=0;R<L;R++)K(C,this.modelMatrix,T.subarray(R*16,R*16+16)),K(this.mvpMatrix,o,C),s.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Re(s,u)}}else{K(this.mvpMatrix,o,this.modelMatrix),s.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let L of P.primitives)s.bindVertexArray(L.vao),Re(s,L)}}let g=new Uint8Array(4);s.readPixels(n,l,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&&(h=[this.meshes[p-1]])}h.length===0&&(h=this.meshes.filter(g=>g.visible!==!1));let c=null,d=1/0,x=[0,0,0],v=[0,1,0],[b,m,M]=pe(this),y=O();for(let g of h){K(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?K(this.modelMatrix,y,p.subarray(P*16,P*16+16)):this.modelMatrix.set(y),K(this.mvpMatrix,o,this.modelMatrix);let E=O();if(!Ae(E,this.mvpMatrix))continue;let U=(n+.5)/r*2-1,H=(l+.5)/a*2-1,S=[0,0,0],T=[0,0,0];Me(S,U,H,-1,E),Me(T,U,H,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,z=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,$=Math.floor(k?k.length/3:_.length/9);for(let B=0;B<$;B++){let vt=k?k[B*3]:B*3,W=k?k[B*3+1]:B*3+1,Q=k?k[B*3+2]:B*3+2;Ee(S[0],S[1],S[2],z,J,N,_[vt*3],_[vt*3+1],_[vt*3+2],_[W*3],_[W*3+1],_[W*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,$=k[0]*D+k[4]*V+k[8]*_+k[12],B=k[1]*D+k[5]*V+k[9]*_+k[13],vt=k[2]*D+k[6]*V+k[10]*_+k[14],W=$-b,Q=B-m,xt=vt-M,bt=Math.hypot(W,Q,xt);if(bt<d){se(this.normalMatrix,this.modelMatrix);let X=this.normalMatrix,Mt=F.normal[0],yt=F.normal[1],A=F.normal[2],G=X[0]*Mt+X[3]*yt+X[6]*A,q=X[1]*Mt+X[4]*yt+X[7]*A,gt=X[2]*Mt+X[5]*yt+X[8]*A,I=Math.hypot(G,q,gt)||1;G/=I,q/=I,gt/=I,G*W+q*Q+gt*xt>0&&(G=-G,q=-q,gt=-gt),c=g,d=Math.round(bt*1e3)/1e3,x=[Math.round($*1e3)/1e3,Math.round(B*1e3)/1e3,Math.round(vt*1e3)/1e3],v=[Math.round(G*1e3)/1e3,Math.round(q*1e3)/1e3,Math.round(gt*1e3)/1e3]}}}}if(!c)return null;let f={meshIndex:this.meshes.indexOf(c),meshName:c.name,nodeIndex:c.nodeIndex,distance:d,hitPoint:x,normal:v,screenX:t,screenY:e};if(i){for(let g of Y)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);fe(this.projMatrix,this.fov,t,.1,e);let i=this.customTarget||this.bounds.center;de(this.viewMatrix,pe(this),i,[0,1,0]),K(this.mvpMatrix,this.projMatrix,this.viewMatrix),se(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 Y)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 Y)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 Y)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 Y)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,h=t?.projectionMatrix||this.projMatrix,n=t?.transform?.position,l=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:h,eyePos:l,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,[U,H,S]=pe(this),T=Math.cos(this.currTheta),L=-Math.sin(this.currTheta),C=.032,u=O(),R=O(),z=[U-T*C,H,S-L*C],J=[E[0]-T*C*.25,E[1],E[2]-L*C*.25];fe(u,this.fov,p/g,.1,P),de(R,z,J,[0,1,0]);let N=O(),F=O(),D=[U+T*C,H,S+L*C],V=[E[0]+T*C*.25,E[1],E[2]+L*C*.25];fe(N,this.fov,w/g,.1,P),de(F,D,V,[0,1,0]),this.render({viewMatrix:R,projMatrix:u,eyePos:z,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=O(),h=t?.viewMatrix??this.viewMatrix;this.activeViewMatrix=h,K(o,t?.projMatrix??this.projMatrix,h);let n=ue().xrDepthShader,l=Ue(this.toneMapping),[c,d,x]=t?t.eyePos:pe(this);for(let f of Y)f.onBeforeDrawScene?.(this,e,o,[c,d,x],l);let v=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&v===0)return;let b=t?.eye||"none",m=!1,M=v>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<v||p.worldSpace===!0||p.name==="__xr_reticle__"?this.modelMatrix.set(p.transform):K(this.modelMatrix,this.modelRootMatrix,p.transform),K(this.mvpMatrix,o,this.modelMatrix),se(p.normalMatrix,this.modelMatrix);let P=p.extras?.xr?.stereo||p.userData?.xr?.stereo,E=0,U=0,H=1,S=1;P==="sbs"?(H=.5,E=b==="right"?.5:0):P==="ou"&&(S=.5,U=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,l),e.uniform1f(u.uEnvIntensity,this.envIntensity),u.uExposure&&e.uniform1f(u.uExposure,this.exposure),e.uniform3f(u.uCameraPos,c,d,x),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,U,H,S),u.uViewportSize&&e.uniform2f(u.uViewportSize,Math.max(1,r),Math.max(1,a)),n?.bind(e,u,this.xrDepthState,h,[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 z of Y)z.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 z=R.length>>4;e.uniform1i(u.uInstanced,1),e.uniformMatrix4fv(u.uViewProj,!1,o),T.indices?e.drawElementsInstanced(4,T.indexCount,T.indexType,0,z):e.drawArraysInstanced(4,0,T.indexCount,z),e.uniform1i(u.uInstanced,0)}else if(R&&R.length>=16){let z=R.length>>4,J=p.instanceColors,N=O(),F=new Float32Array(9),D=[T.baseColor[0],T.baseColor[1],T.baseColor[2],T.baseColor[3]];for(let V=0;V<z;V++)K(N,this.modelMatrix,R.subarray(V*16,V*16+16)),K(this.mvpMatrix,o,N),se(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)),Re(e,T)}else Re(e,T)}}};if(y(!1),m){for(let f of Y)f.onBeforeTransmissivePass?.(e,this);y(!0)}for(let f of Y)f.onAfterRender?.(e,this,o,t?.eye??"none",[i,s,r,a],t?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(t,e){Ze(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 Y)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()}};he.registerPlugin=De,he.getRegisteredPlugins=Ce;var dt=he;
214
+ void main(){fragColor=uColorId;}`;function Ae(t,e,i){let s={};for(let a of i)s[a]=t.getUniformLocation(e,a);return s}var mt="uMVP uModel uInstanced uViewProj uNormalMatrix uUvTransform uBaseColor uMetallic uRoughness uClearcoat uEmissive uCameraPos uBaseColorTexture uHasTexture uMetallicRoughnessTexture uHasMetallicRoughnessTexture uNormalTexture uHasNormalTexture uNormalScale uOcclusionTexture uHasOcclusionTexture uOcclusionStrength uEmissiveFactor uEmissiveTexture uHasEmissiveTexture uToneMapping uEnvironmentMap uHasEnvironmentMap uAmbientColor uHemi uNumDirLights uDirLightDir uDirLightColor uNumPointLights uPointLightPos uPointLightColor uPointLightSpotDir uPointLightSpotCone uEnvIntensity uExposure uViewportSize uSectionPlane uSectionEnabled".split(" ");function Be(){let t=ue(),e=t.xrDepthShader,i=t.shadowMapShader;return{fs:ot.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||"").replace("/*SHD_U*/",i?.uniformsGLSL||"").replace("/*SHD_D*/",i?.dirGLSL||"").replace("/*SHD_P*/",i?.ptGLSL||""),uniforms:[...mt,...e?.uniformNames||[],...i?.uniformNames||[]]}}function $e(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 Ie(t,e,i,s,a,r,o,n){if(s===void 0||!e.accessors?.[s])return null;let l=Se(e,i,e.accessors[s],r);if(!l)return null;n&&(l=l.slice(),Ve(l,n));let g=t.createBuffer();return o.push(g),t.bindBuffer(34962,g),t.bufferData(34962,l,35044),t.enableVertexAttribArray(a),t.vertexAttribPointer(a,r,5126,!1,0,0),l}function Ge(t){let e=Number(t);return Number.isFinite(e)?Math.max(0,e):1}function Ke(t,e,i){let s=Be(),a=ke,r=s.fs,o=!1;for(let l of K)if(l.onResolveShader){let g=l.onResolveShader(e,i,a,r);g&&(a=g.vs,r=g.fs,o=!0)}let n=o?he(t,a,r):null;return{program:n,uniforms:n?Ae(t,n,s.uniforms):null}}function ht(t,e,i){let s=e.instanceMatrices;if(!s||s.length<16||typeof t.vertexAttribDivisor!="function"||typeof t.drawElementsInstanced!="function")return!1;let a=s.length>>4,r=e.instanceColors,o=new Float32Array(a*20);for(let l=0;l<a;l++)o.set(s.subarray(l*16,l*16+16),l*20),o[l*20+16]=r?r[l*3]:1,o[l*20+17]=r?r[l*3+1]:1,o[l*20+18]=r?r[l*3+2]:1,o[l*20+19]=1;let n=t.createBuffer();i.push(n),t.bindBuffer(34962,n),t.bufferData(34962,o,35044);for(let l=0;l<5;l++)t.enableVertexAttribArray(8+l),t.vertexAttribPointer(8+l,4,5126,!1,80,l*16),t.vertexAttribDivisor(8+l,1);return!0}function dt(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 a of s){let r=a?.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}),qe=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Pe(t,e){e.indices?t.drawElements(4,e.indexCount,e.indexType,0):t.drawArrays(4,0,e.indexCount)}function Ze(t,e){let i=t?.pbrMetallicRoughness,s=i?.baseColorFactor,a=t?.emissiveFactor,r=t?.extensions?.KHR_materials_clearcoat,o=n=>n!==void 0&&e[n.index]?e[n.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:o(i?.baseColorTexture),metallicRoughnessTexture:o(i?.metallicRoughnessTexture),normalTexture:o(t?.normalTexture),normalScale:t?.normalTexture?.scale??1,occlusionTexture:o(t?.occlusionTexture),occlusionStrength:t?.occlusionTexture?.strength??1,emissiveTexture:o(t?.emissiveTexture),emissiveFactor:Array.isArray(a)&&a.length>=3?[a[0],a[1],a[2]]:[0,0,0],isTransmissive:(t?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Je(t,e,i){let s=new Set,a=r=>{r&&!s.has(r)&&(s.add(r),t.deleteTexture(r))};for(let r of e)for(let o of r.primitives){if(o.vao&&t.deleteVertexArray(o.vao),o.buffers)for(let l of o.buffers)t.deleteBuffer(l);for(let l of[o.texture,o.metallicRoughnessTexture,o.normalTexture,o.occlusionTexture,o.emissiveTexture])a(l);let n=new Set;o.customProgram&&n.add(o.customProgram);for(let l of o.programCache?.values()??[])l.program&&n.add(l.program);for(let l of n)t.deleteProgram(l)}if(i)for(let r of i)a(r)}function Ue(t,e,i=qe,s){let a={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return pt(t,e,i,s,a)}catch(r){let o=a.mesh&&!a.meshes.includes(a.mesh)?[...a.meshes,a.mesh]:a.meshes;Je(t,o,a.gpuTextures),a.vao&&t.deleteVertexArray(a.vao);for(let n of a.buffers)t.deleteBuffer(n);throw r}}function pt(t,e,i,s,a){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:r}=e,o=pe("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(r,e);let n=e.bin,l=[];a.meshes=l;let g=[],h=r.extensions?.KHR_materials_variants;h&&Array.isArray(h.variants)&&h.variants.forEach((w,R)=>{g.push(typeof w?.name=="string"&&w.name?w.name:`Variant_${R}`)});let c=Te(r),x=[];if(Array.isArray(r.nodes))for(let w=0;w<r.nodes.length;w++){let R=r.nodes[w];R.mesh!==void 0&&r.meshes&&r.meshes[R.mesh]&&x.push({node:R,nodeIdx:w,meshIdx:R.mesh})}let f=x.length>0?x:(r.meshes||[]).map((w,R)=>({node:w,nodeIdx:-1,meshIdx:R})),v=[],u=Array.isArray(e.lights)&&e.lights.length>0?e.lights:Array.isArray(r.asset?.extras?.lights)&&r.asset.extras.lights.length>0?r.asset.extras.lights:null;if(u)for(let w of u)v.push({...w,type:w.type||w.light_type||"point",groundColor:w.groundColor??w.ground_color,innerConeAngle:w.innerConeAngle??w.inner_cone_angle,outerConeAngle:w.outerConeAngle??w.outer_cone_angle});else r.extensions?.KHR_lights_punctual?.lights&&v.push(...je(r,c));if(v.length===0&&(v.push({type:"ambient",color:[1,1,1],intensity:.35}),v.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),f.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${f.length}`);let p=[];if(a.gpuTextures=p,r.textures&&r.images){if(r.textures.length>i.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${i.maxTextures}). Found: ${r.textures.length}`);for(let w=0;w<r.textures.length;w++){let R=r.textures[w],V=r.images[R.source];if(V){let U=t.createTexture();t.bindTexture(3553,U),t.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255]));for(let[P,S]of[[10242,10497],[10243,10497],[10241,9729],[10240,9729]])t.texParameteri(3553,P,S);let L=P=>{U.__gpuImageSource=P,t.bindTexture(3553,U),t.texImage2D(3553,0,6408,6408,5121,P),t.generateMipmap(3553),s?.()};if(V.bufferView!==void 0){let P=r.bufferViews[V.bufferView],S=P.byteOffset||0,H=new Blob([n.slice(S,S+P.byteLength)],{type:V.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(H).then(L).catch(()=>{})}else if(V.uri){let P=$e(V.uri);if(P){let S=new Image;S.crossOrigin="anonymous",S.referrerPolicy="no-referrer",S.onload=()=>L(S),S.src=P}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",V.uri)}p.push(U)}else p.push(null)}}let M=[1/0,1/0,1/0],d=[-1/0,-1/0,-1/0],y=0,T=0;for(let w=0;w<f.length;w++){let R=f[w],V=r.meshes[R.meshIdx],U=R.nodeIdx>=0?c[R.nodeIdx]:$(),L=new Float32Array(9);oe(L,U);let P=R.node?.extras?.shadow,S={name:R.node.name||V.name||`Mesh_${R.meshIdx}`,nodeIndex:R.nodeIdx,transform:U,normalMatrix:L,primitives:[],extras:R.node.extras||V.extras,...R.node?.visible===!1||R.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{},...typeof P?.cast=="boolean"?{castShadow:P.cast}:{},...typeof P?.receive=="boolean"?{receiveShadow:P.receive}:{}};a.mesh=S;let H=R.node?.extensions?.EXT_mesh_gpu_instancing;if(H&&H.attributes&&typeof H.attributes=="object"){let m=H.attributes,F=m.TRANSLATION!==void 0?r.accessors?.[m.TRANSLATION]:null,k=m.ROTATION!==void 0?r.accessors?.[m.ROTATION]:null,_=m.SCALE!==void 0?r.accessors?.[m.SCALE]:null,N=m._COLOR_0!==void 0?r.accessors?.[m._COLOR_0]:null,I=Number(F?.count??k?.count??_?.count??0);if(!Number.isFinite(I)||I<0||I>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${I}`);if(I>0){let B=(G,j)=>{if(!G||G.bufferView===void 0||!r.bufferViews?.[G.bufferView])return null;let Y=G.componentType??5126,Mt=Tt=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${Tt})`),null);if(Y!==5120&&Y!==5121&&Y!==5122&&Y!==5123&&Y!==5126)return Mt(`componentType ${Y}`);if(!(Number(G.count)>=I))return Mt(`count ${G.count} < ${I}`);let xt=null;try{xt=Se(r,n,{...G,count:I},j)}catch{return Mt("out of bounds")}return!xt||!xt.every(Number.isFinite)?Mt("non-finite value"):xt},W=B(F,3),q=B(k,4),X=B(_,3),yt=N?.type==="VEC4"?4:3,vt=B(N,yt),Pt=new Float32Array(I*16),Q=$();for(let G=0;G<I;G++){let j=G*3,Y=G*4;ye(Q,q?[q[Y],q[Y+1],q[Y+2],q[Y+3]]:[0,0,0,1],W?[W[j],W[j+1],W[j+2]]:[0,0,0],X?[X[j],X[j+1],X[j+2]]:[1,1,1]),Pt.set(Q,G*16)}if(S.instanceMatrices=Pt,vt){let G=new Float32Array(I*3);for(let j=0;j<I;j++)G[j*3]=vt[j*yt],G[j*3+1]=vt[j*yt+1],G[j*3+2]=vt[j*yt+2];S.instanceColors=G}}}for(let m of V.primitives||[]){if(m.extensions?.KHR_draco_mesh_compression){let O=pe("draco");O&&O.decodePrimitive(r,m,n)}let F=[],k=t.createVertexArray();a.vao=k,a.buffers=F,t.bindVertexArray(k);let _=ht(t,S,F),N=r.accessors[m.attributes.POSITION],I=Number(N?.count??0);if(!Number.isFinite(I)||I<0||y+I>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(y+=I,N?.min&&N?.max){let O=z=>{for(let J=0;J<3;J++){let wt=z[12+J],St=wt;for(let Ct=0;Ct<3;Ct++){let Dt=z[Ct*4+J]*N.min[Ct],Rt=z[Ct*4+J]*N.max[Ct];wt+=Dt<Rt?Dt:Rt,St+=Dt>Rt?Dt:Rt}wt<M[J]&&(M[J]=wt),St>d[J]&&(d[J]=St)}};if(S.instanceMatrices&&S.instanceMatrices.length>=16){let z=S.instanceMatrices.length>>4,J=$();for(let wt=0;wt<z;wt++)Z(J,U,S.instanceMatrices.subarray(wt*16,wt*16+16)),O(J)}else O(U)}let B=Ie(t,r,n,m.attributes.POSITION,0,3,F),W=Ie(t,r,n,m.attributes.NORMAL,1,3,F),q=Ie(t,r,n,m.attributes.TEXCOORD_0,2,2,F,dt(r,m)),X=0,yt=5123,vt=null;if(m.indices!==void 0){let O=r.accessors[m.indices],z=(r.bufferViews[O.bufferView].byteOffset||0)+(O.byteOffset||0);if(X=Number(O.count??0),!Number.isFinite(X)||X<0||T+X>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);T+=X,yt=O.componentType===5125?5125:5123;let J=t.createBuffer();F.push(J),t.bindBuffer(34963,J),O.componentType===5125?vt=new Uint32Array(n,z,O.count):O.componentType===5121?vt=Uint16Array.from(new Uint8Array(n,z,O.count)):vt=z%2===0?new Uint16Array(n,z,O.count):new Uint16Array(n.slice(z,z+O.count*2)),t.bufferData(34963,vt,35044)}else X=N.count;let Pt={};for(let O of K)if(O.onBuildPrimitiveVAO){let z=O.onBuildPrimitiveVAO(t,k,m,r,n);z&&(Pt[O.name]=z)}t.bindVertexArray(null);let Q=r.materials&&m.material!==void 0?r.materials[m.material]:null,{program:G,uniforms:j}=Ke(t,m,Q),Y=Ze(Q,p),Mt=!!(Q?.extensions?.KHR_materials_transmission||Pt.materials?.isTransmissive),xt=m.extensions?.KHR_materials_variants?.mappings,Tt=Array.isArray(xt)?xt.filter(O=>O&&typeof O.material=="number"&&Array.isArray(O.variants)).map(O=>({material:O.material|0,variants:O.variants.map(z=>Number(z)|0)})):void 0;S.primitives.push({vao:k,instanced:_,indexCount:X,indexType:yt,...Y,positions:B,normals:W,uvs:q,indices:vt,buffers:F,materialIndex:m.material,defaultMaterialIndex:m.material,variantMappings:Tt,primitiveDef:m,programCache:new Map([[m.material??-1,{program:G,uniforms:j}]]),pluginData:Pt,customProgram:G,customUniforms:j,isTransmissive:Mt})}l.push(S)}isFinite(M[0])||(M=[-1,-1,-1]),isFinite(d[0])||(d=[1,1,1]);let C=[(M[0]+d[0])/2,(M[1]+d[1])/2,(M[2]+d[2])/2],b=Math.max(Math.hypot(d[0]-M[0],d[1]-M[1],d[2]-M[2])/2,.5),E=[...M],D=[...d],A=e.animations;if(e.animationsParsed===!1||!A){for(let w of K)if(w.onParseGLB?.(e),e.animations){A=e.animations;break}}return A||(A=[]),{meshes:l,bounds:{center:C,radius:b,min:E,max:D},lights:v,animations:A,worldMatrices:c,gpuTextures:p,availableVariants:g}}function Re(){return typeof performance<"u"?performance.now():Date.now()}function de(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 le=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=$(),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.environmentSource=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=$(),this.viewMatrix=$(),this.activeViewMatrix=null,this.modelMatrix=$(),this.mvpMatrix=$(),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.selectedMeshNames=new Set,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:$(),rawValueToMeters:.001,format:0},this.container=t;let s,a;if(e&&typeof e.getContext=="function"?(s=e,a=i):(a=e,s=a?.canvas),!s){let l=t.querySelector("canvas");l||(l=document.createElement("canvas"),l.style.cssText="width:100%;height:100%;display:block;touch-action:none",t.prepend(l)),s=l}this.canvas=s;let r=this.opts=a||{};r.clearColor&&(this.clearColor=r.clearColor);let o=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;r.autoRotate!==void 0?this.autoRotate=r.autoRotate&&!o:o&&(this.autoRotate=!1),r.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=r.autoRotateSpeed),r.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(r.autoRotateDelay)||0)),r.exposure!==void 0&&(this.exposure=Ge(r.exposure)),r.camera&&this.setInitialCamera(r.camera.theta,r.camera.phi,r.camera.distance,r.camera.zoom),(r.shadowIntensity!==void 0||r.shadowSoftness!==void 0)&&this.setShadow(r.shadowIntensity??0,r.shadowSoftness),r.shadowMaps!==void 0&&(this.shadowMaps=r.shadowMaps),r.toneMapping!==void 0&&(this.toneMapping=fe(r.toneMapping)),r.autoplay!==void 0&&(this.autoplay=r.autoplay),r.animationName!==void 0&&(this.animationName=r.animationName),r.variantName!==void 0&&(this.activeVariantName=r.variantName||null),r.fieldOfView!==void 0&&(this.fov=r.fieldOfView*Math.PI/180),r.distanceMode!==void 0&&(this.distanceMode=r.distanceMode),r.cameraTarget!==void 0&&(this.setTarget(r.cameraTarget[0],r.cameraTarget[1],r.cameraTarget[2]),this.initialCustomTarget=[...r.cameraTarget]),(r.minCameraOrbit||r.maxCameraOrbit)&&this.setOrbitLimits({minTheta:r.minCameraOrbit?.theta,maxTheta:r.maxCameraOrbit?.theta,minPhi:r.minCameraOrbit?.phi,maxPhi:r.maxCameraOrbit?.phi,minDistance:r.minCameraOrbit?.distance,maxDistance:r.maxCameraOrbit?.distance});let n=s.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!n)throw new Error("WebGL2 not supported");this.gl=n,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),r.environmentImage&&this.setEnvironmentImage(r.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&r.autoStart!==!1&&this.start()}static registerDecoder(t,e){Xe(t,e)}static getDecoder(t){return pe(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=Be();this.renderProg=he(t,ke,e.fs),this.pickProg=he(t,ct,lt),this.uRender=Ae(t,this.renderProg,e.uniforms),this.uPick=Ae(t,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}recompileRenderProgram(){if(this.contextLost)return;let t=this.gl,e=Be();this.renderProg&&t.deleteProgram(this.renderProg),this.renderProg=he(t,ke,e.fs),this.uRender=Ae(t,this.renderProg,e.uniforms);for(let i of this.meshes)for(let s of i.primitives)s.customProgram&&(t.deleteProgram(s.customProgram),s.programCache?.clear(),this.applyPrimitiveProgram(s,s.materialIndex,this.gltf?.materials?.[s.materialIndex??-1]??null))}restoreContext(){let t=this.gl;this.contextLost=!1,this.initGlState();for(let e of K)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;typeof t.createFramebuffer=="function"&&(this.pickFbo=t.createFramebuffer(),this.pickTexture=t.createTexture(),this.pickDepth=t.createRenderbuffer(),this.resizePickingFbo(this.canvas.width,this.canvas.height),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),a=Math.max(1,e);this.pickFboWidth=s,this.pickFboHeight=a,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,s,a,0,6408,5121,null),i.texParameteri(3553,10241,9728),i.texParameteri(3553,10240,9728),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,s,a)}loadGLBData(t,e){let{meshes:i,bounds:s,lights:a,animations:r,worldMatrices:o,gpuTextures:n,availableVariants:l}=Ue(this.gl,t,e,()=>this.render());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=a,this.animations=r||[],this.worldMatrices=o||[],this.gpuTextures=n||[],this.availableVariants=l||[],this.gltf=t.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=(t.gltf?.nodes||[]).map(c=>({t:[c.translation?.[0]??0,c.translation?.[1]??0,c.translation?.[2]??0],r:[c.rotation?.[0]??0,c.rotation?.[1]??0,c.rotation?.[2]??0,c.rotation?.[3]??1],s:[c.scale?.[0]??1,c.scale?.[1]??1,c.scale?.[2]??1]})),this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let c of K)c.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 g=t.exposure??t.gltf?.extras?.exposure??t.gltf?.asset?.extras?.exposure;g!==void 0&&(this.exposure=Ge(g));let h=t.environmentIntensity??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.environmentIntensity;h!==void 0&&(this.envIntensity=Math.max(0,Number(h)||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(_e(t))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let t of K)t.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(t){this.loadGLBData(Ne(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let i=Ne(t),{meshes:s}=Ue(this.gl,i,qe,()=>this.render());if(e)for(let a of s)a.transform[12]+=e[0],a.transform[13]+=e[1],a.transform[14]+=e[2],oe(a.normalMatrix,a.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?t.get(i.name)??t.get(e):Array.isArray(t)?t[e]:t&&typeof t=="object"?Object.prototype.hasOwnProperty.call(t,i.name)?t[i.name]:Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0:void 0;s&&s.length===16&&(i.transform.set(s),oe(i.normalMatrix,i.transform))}}bindLights(t=this.uRender){let e=this.gl,i=[.28,.28,.28],s=[0,0,0,0,0,0,0,1,0],a=!1,r=[],o=[],n=[],l=[],g=[],h=[];for(let c of this.lights){let x=c.color||[1,1,1],f=c.intensity!==void 0?c.intensity:1;if(c.type==="ambient")i=[x[0]*f,x[1]*f,x[2]*f];else if(c.type==="hemisphere"){a=!0;let v=c.groundColor||[.2,.2,.2],u=f*.65;for(let d=0;d<3;d++)s[d]+=x[d]*u,s[d+3]+=v[d]*u;let p=c.position||[0,1,0],M=Math.hypot(p[0],p[1],p[2]);M>1e-5&&(s[6]=p[0]/M,s[7]=p[1]/M,s[8]=p[2]/M)}else if(c.type==="directional"&&r.length<6){let v=c.direction||[.5,1,.8];r.push(v[0],v[1],v[2]),o.push(x[0]*f,x[1]*f,x[2]*f)}else if((c.type==="point"||c.type==="spot")&&n.length<6){let v=c.position||[0,0,0];if(n.push(v[0],v[1],v[2]),l.push(x[0]*f,x[1]*f,x[2]*f),c.type==="spot"){let u=c.direction||[0,-1,0],p=Math.max(.01,Math.min(Math.PI/2,c.outerConeAngle??Math.PI/3)),M=Math.max(0,Math.min(p-1e-4,c.innerConeAngle??0));g.push(u[0],u[1],u[2]),h.push(Math.cos(M),Math.cos(p))}else g.push(0,-1,0),h.push(-2,-3)}}r.length===0&&!a&&(r.push(.5,1,.8),o.push(1,1,1)),e.uniform3fv(t.uAmbientColor,i),t.uHemi&&e.uniformMatrix3fv(t.uHemi,!1,s),e.uniform1i(t.uNumDirLights,r.length/3),r.length>0&&(e.uniform3fv(t.uDirLightDir,r),e.uniform3fv(t.uDirLightColor,o)),e.uniform1i(t.uNumPointLights,n.length/3),n.length>0&&(e.uniform3fv(t.uPointLightPos,n),e.uniform3fv(t.uPointLightColor,l),t.uPointLightSpotDir&&e.uniform3fv(t.uPointLightSpotDir,g),t.uPointLightSpotCone&&e.uniform2fv(t.uPointLightSpotCone,h)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.exposure=Ge(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=fe(t)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){this.environmentSource=t&&typeof t=="object"?t:null;for(let e of K)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t),this.render();return}this.render()}async setSkyboxImage(t){for(let e of K)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)),a=s[0],r=a?[...a.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],o=a?a.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,n=a?a.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,l=(h,c,x)=>{g[h]=x,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness[h]=x);for(let f of s)f[c]=x;this.render()},g={baseColorFactor:r,metallicFactor:o,roughnessFactor:n,setBaseColorFactor:h=>l("baseColorFactor","baseColor",[h[0],h[1],h[2],h[3]??1]),setMetallicFactor:h=>l("metallicFactor","metallic",h),setRoughnessFactor:h=>l("roughnessFactor","roughness",h)};return{name:e.name||`Material_${i}`,pbrMetallicRoughness:g}})}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 a of this.meshes)for(let r of a.primitives){let o=r.defaultMaterialIndex;if(!e&&Array.isArray(r.variantMappings)){for(let l of r.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(i)){o=l.material;break}}let n=o!==void 0?s[o]:void 0;r.materialIndex=n?o:void 0,Object.assign(r,Ze(n,this.gpuTextures)),this.applyPrimitiveProgram(r,r.materialIndex,n??null)}return!0}applyPrimitiveProgram(t,e,i){if(!this.gl||!t.primitiveDef)return;t.programCache??(t.programCache=new Map);let s=e??-1,a=t.programCache.get(s);a||(a=Ke(this.gl,{...t.primitiveDef,material:e},i),t.programCache.set(s,a)),t.customProgram=a.program,t.customUniforms=a.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 K)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){let e=Math.PI/180,i=Math.PI*.48;t.minTheta!==void 0&&(this.minTheta=t.minTheta*e),t.maxTheta!==void 0&&(this.maxTheta=t.maxTheta*e),t.minPhi!==void 0&&(this.minPhi=Math.max(-i,t.minPhi*e)),t.maxPhi!==void 0&&(this.maxPhi=Math.min(i,t.maxPhi*e)),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(){let t=180/Math.PI;return{minTheta:isFinite(this.minTheta)?this.minTheta*t:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*t:void 0,minPhi:this.minPhi*t,maxPhi:this.maxPhi*t,minDistance:this.minDistanceLimit??void 0,maxDistance: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.bounds?.radius;return Math.max(this.minDistanceLimit??(e?e*.5:.1),Math.min(this.maxDistanceLimit??(e?e*8:100),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){t!==void 0&&(this.initialTheta=this.targetTheta=this.currTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.initialPhi=this.targetPhi=this.currPhi=this.clampPhi(e*Math.PI/180));let a=i!==void 0&&i>0?i:s!==void 0&&s>0?this.bounds.radius*2.5/s:null;this.customDistance=a!==null,this.initialDistance=this.targetDistance=this.currDistance=this.clampDistance(a??(this.distanceMode==="absolute"?3:this.bounds.radius*2.5)),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.targetDistance=this.clampDistance(this.initialDistance??this.bounds.radius*2.5),this.customTarget=this.initialCustomTarget?[...this.initialCustomTarget]:null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(t,e){let i=$();Z(i,this.projMatrix,this.viewMatrix);let s=(D,A,w=1)=>[D[0]*A[0]+D[4]*A[1]+D[8]*A[2]+D[12]*w,D[1]*A[0]+D[5]*A[1]+D[9]*A[2]+D[13]*w,D[2]*A[0]+D[6]*A[1]+D[10]*A[2]+D[14]*w,D[3]*A[0]+D[7]*A[1]+D[11]*A[2]+D[15]*w],a=this.modelRootMatrix,[r,o,n]=a?s(a,t):t,[l,g,h]=e?a?s(a,e,0):e:[0,0,0],[c,x,f,v]=s(i,[r,o,n]);if(v<=1e-4)return{x:0,y:0,z:1,visible:!1};let u=c/v,p=x/v,M=f/v,d=this.canvas.getBoundingClientRect(),y=d.width||this.canvas.clientWidth||this.canvas.width||300,T=d.height||this.canvas.clientHeight||this.canvas.height||150,C=(u*.5+.5)*y,b=(-p*.5+.5)*T,E=u>=-1.1&&u<=1.1&&p>=-1.1&&p<=1.1&&M>=-1&&M<=1;if(E&&e){let[D,A,w]=de(this),R=[r-D,o-A,n-w];l*R[0]+g*R[1]+h*R[2]>.05&&(E=!1)}return{x:C,y:b,z:M,visible:E}}setSelectedMesh(t){this.setSelectedMeshes([t])}setSelectedMeshes(t){this.selectedMeshNames=new Set(t.filter(Boolean))}getSelectedMesh(){return[...this.selectedMeshNames][0]||""}setupEvents(){let t=this.canvas,e=Re;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},a=i.clientX-s.x,r=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(a,r),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],n=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],l=this.customTarget?[...this.customTarget]:[...this.bounds.center],g=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;l[0]+=(-a*o[0]+r*n[0])*g,l[1]+=(-a*o[1]+r*n[1])*g,l[2]+=(-a*o[2]+r*n[2])*g,this.customTarget=l}else this.targetTheta=this.clampTheta(this.targetTheta-a*.008),this.targetPhi=this.clampPhi(this.targetPhi+r*.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(),a=Math.floor((i.clientX-s.left)*(t.width/Math.max(s.width,1))),r=Math.floor((i.clientY-s.top)*(t.height/Math.max(s.height,1)));this.performMeshPick(a,r,!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,a)=>{this[a]&&(i.removeEventListener(s,this[a]),this[a]=null)},e=this.canvas;for(let[i,s]of[["webglcontextlost","boundContextLost"],["webglcontextrestored","boundContextRestored"],["contextmenu","boundContextMenu"],["pointerdown","boundPointerDown"],["pointermove","boundPointerMove"],["pointerup","boundPointerUp"],["wheel","boundWheel"],["keydown","boundKeyDown"]])t(e,i,s);t(this.container,"setCamera","boundSetCamera"),t(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(t,e){let i=this.canvas,s=i.getBoundingClientRect(),a=i.width||300,r=i.height||300,o=s.width>0?Math.floor((t-s.left)*(a/s.width)):Math.floor(t),n=s.height>0?Math.floor((e-s.top)*(r/s.height)):Math.floor(e);return this.performMeshPick(o,n,!1)}performMeshPick(t,e,i=!0){if(this.meshes.length===0)return null;let s=this.gl,a=Math.max(1,this.canvas.width||300),r=Math.max(1,this.canvas.height||300);t=this.mapStereoPickX(t,a);let o=$();Z(o,this.projMatrix,this.viewMatrix);let n=[],l=Math.max(0,Math.min(a-1,t)),g=Math.max(0,Math.min(r-1,r-1-e));if(this.pickFbo&&s&&!this.xrSessionActive){(this.pickFboWidth!==a||this.pickFboHeight!==r)&&this.resizePickingFbo(a,r),s.bindFramebuffer(36160,this.pickFbo),s.viewport(0,0,a,r),s.enable(2929),s.clearColor(0,0,0,0),s.clear(16640),s.useProgram(this.pickProg);for(let C=0;C<this.meshes.length;C++){let b=this.meshes[C];if(b.visible===!1||b.isPluginMesh)continue;let E=C+1,D=(E&255)/255,A=(E>>8&255)/255,w=(E>>16&255)/255;s.uniform4f(this.uPick.uColorId,D,A,w,1),Z(this.modelMatrix,this.modelRootMatrix,b.transform);let R=b.instanceMatrices;if(R&&R.length>=16){let V=R.length>>4,U=$();for(let L of b.primitives){s.bindVertexArray(L.vao);for(let P=0;P<V;P++)Z(U,this.modelMatrix,R.subarray(P*16,P*16+16)),Z(this.mvpMatrix,o,U),s.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Pe(s,L)}}else{Z(this.mvpMatrix,o,this.modelMatrix),s.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let V of b.primitives)s.bindVertexArray(V.vao),Pe(s,V)}}let y=new Uint8Array(4);s.readPixels(l,g,1,1,6408,5121,y),s.bindFramebuffer(36160,null);let T=y[0]+(y[1]<<8)+(y[2]<<16);T>0&&T<=this.meshes.length&&(n=[this.meshes[T-1]])}n.length===0&&(n=this.meshes.filter(y=>y.visible!==!1));let h=null,c=1/0,x=[0,0,0],f=[0,1,0],[v,u,p]=de(this),M=$();for(let y of n){Z(M,this.modelRootMatrix,y.transform);let T=y.instanceMatrices,C=T&&T.length>=16?T.length>>4:1;for(let b=0;b<C;b++){T&&T.length>=16?Z(this.modelMatrix,M,T.subarray(b*16,b*16+16)):this.modelMatrix.set(M),Z(this.mvpMatrix,o,this.modelMatrix);let E=$();if(!Ee(E,this.mvpMatrix))continue;let D=(l+.5)/a*2-1,A=(g+.5)/r*2-1,w=[0,0,0],R=[0,0,0];Me(w,D,A,-1,E),Me(R,D,A,1,E);let V=R[0]-w[0],U=R[1]-w[1],L=R[2]-w[2],P=Math.hypot(V,U,L)||1,S=V/P,H=U/P,m=L/P,F={distance:1/0,point:[0,0,0],normal:[0,1,0]};for(let k of y.primitives){if(!k.positions)continue;let _=k.positions,N=k.indices,I=Math.floor(N?N.length/3:_.length/9);for(let B=0;B<I;B++){let W=(N?N[B*3]:B*3)*3,q=(N?N[B*3+1]:B*3+1)*3,X=(N?N[B*3+2]:B*3+2)*3;Ce(w[0],w[1],w[2],S,H,m,_[W],_[W+1],_[W+2],_[q],_[q+1],_[q+2],_[X],_[X+1],_[X+2],F,1e-4)}}if(isFinite(F.distance)){let k=F.point[0],_=F.point[1],N=F.point[2],I=this.modelMatrix,B=I[0]*k+I[4]*_+I[8]*N+I[12],W=I[1]*k+I[5]*_+I[9]*N+I[13],q=I[2]*k+I[6]*_+I[10]*N+I[14],X=B-v,yt=W-u,vt=q-p,Pt=Math.hypot(X,yt,vt);if(Pt<c){oe(this.normalMatrix,this.modelMatrix);let Q=this.normalMatrix,G=F.normal[0],j=F.normal[1],Y=F.normal[2],Mt=Q[0]*G+Q[3]*j+Q[6]*Y,xt=Q[1]*G+Q[4]*j+Q[7]*Y,Tt=Q[2]*G+Q[5]*j+Q[8]*Y,O=Math.hypot(Mt,xt,Tt)||1;Mt/=O,xt/=O,Tt/=O,Mt*X+xt*yt+Tt*vt>0&&(Mt=-Mt,xt=-xt,Tt=-Tt);let z=J=>Math.round(J*1e3)/1e3;h=y,c=z(Pt),x=[z(B),z(W),z(q)],f=[z(Mt),z(xt),z(Tt)]}}}}if(!h)return null;let d={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:c,hitPoint:x,normal:f,screenX:t,screenY:e};if(i){for(let y of K)y.onMeshSelect?.(this,d);this.opts.onMeshClick&&this.opts.onMeshClick(d),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:d}))}return d}mapStereoPickX(t,e){if(!this.stereoSBS||this.xrSessionActive||e<2)return t;let i=Math.max(1,Math.floor(e*.5)),s=t>=i,a=s?t-i:t,r=s?Math.max(1,e-i):i,o=(a+.5)/r*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);xe(this.projMatrix,this.fov,t,.1,e);let i=this.customTarget||this.bounds.center;ve(this.viewMatrix,de(this),i,[0,1,0]),Z(this.mvpMatrix,this.projMatrix,this.viewMatrix),oe(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 K)i.onXRSessionEnd?.(this);if(this.lastTime=Re(),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 K)e.onUpdate?.(this,t)}start(){if(this.animFrameId!==null)return;this.lastTime=Re();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,,s]=this.bounds.center;this.modelRootMatrix.set([t,0,-e,0,0,1,0,0,e,0,t,0,i-(t*i+e*s),0,s-(-e*i+t*s),1])}setVisible(t){this.isVisible=t}update(t){for(let r of K)r.onUpdate?.(this,t);let e=Re();if(!this.isPointerDown&&this.autoRotate&&e-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*t,this.updateTurntableMatrix();for(let r of K)r.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),a=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(a-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=s,this.lastReportedZoom=a;let r={theta:i,phi:s,zoom:a,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(r),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:r}))}}renderXRView(t,e,i,s,a=!0,r=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let o=t?.transform?.inverse?.matrix||this.viewMatrix,n=t?.projectionMatrix||this.projMatrix,l=t?.transform?.position,g=l?[l.x,l.y,l.z]:[0,1.6,0];e&&this.modelRootMatrix.set(e),this.render({viewMatrix:o,projMatrix:n,eyePos:g,viewport:s,eye:t?.eye||"none",clear:r>0?!1:t?.eye!=="right",isAR:a})}render(t){if(this.contextLost)return;if(!t&&this.stereoSBS){let b=Math.max(2,this.canvas.width||2),E=Math.max(1,this.canvas.height||1),D=Math.max(1,Math.floor(b*.5)),A=Math.max(1,b-D),w=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),R=this.customTarget||this.bounds.center,[V,U,L]=de(this),P=Math.cos(this.currTheta),S=-Math.sin(this.currTheta),H=.032;for(let m of[-1,1]){let F=$(),k=$(),_=m<0?D:A,N=[V+m*P*H,U,L+m*S*H];xe(F,this.fov,_/E,.1,w),ve(k,N,[R[0]+m*P*H*.25,R[1],R[2]+m*S*H*.25],[0,1,0]),this.render({viewMatrix:k,projMatrix:F,eyePos:N,viewport:[m<0?0:D,0,_,E],eye:m<0?"left":"right",clear:m<0,isAR:!1})}this.gl.viewport(0,0,b,E);return}let e=this.gl,[i,s,a,r]=t?.viewport||[0,0,this.canvas.width,this.canvas.height];if(e.viewport(i,s,a,r),e.enable(2929),!t||t.clear!==!1){let b=t?.isAR?[0,0,0,0]:this.clearColor;e.clearColor(b[0],b[1],b[2],b[3]),e.clear(16640)}let o=$(),n=t?.viewMatrix??this.viewMatrix;this.activeViewMatrix=n;let l=t?.projMatrix??this.projMatrix;Z(o,l,n);let g=ue(),h=g.xrDepthShader,c=He(this.toneMapping),[x,f,v]=t?t.eyePos:de(this);for(let b of K)b.onBeforeDrawScene?.(this,e,o,[x,f,v],c);let u=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&u===0){g.gpuSceneAccelerator?.hideLayer?.(this);return}let p=t?.eye||"none",M=!t||t.clear!==!1;if(!this.xrSessionActive&&g.gpuSceneAccelerator?.renderScene(this,o,l,n,[x,f,v],c,[i,s,a,r],p,M,!!t?.isAR)){M&&!this.skyboxTexture&&(e.clearColor(0,0,0,0),e.clear(16384));for(let b of K)b.name.includes("webgpu")&&b.onAfterRender?.(e,this,o,p,[i,s,a,r],l);return}let d=!1,y=u>0?[...this.backdropMeshes,...this.meshes]:this.meshes,T=(b,E,D,A)=>{E?(e.activeTexture(33984+b),e.bindTexture(3553,E),e.uniform1i(D,b),e.uniform1i(A,1)):e.uniform1i(A,0)},C=b=>{for(let E=0;E<y.length;E++){let D=y[E];if(D.visible===!1)continue;let A=this.selectedMeshNames.has(D.name);if(E<u||D.worldSpace===!0||D.name==="__xr_reticle__")this.modelMatrix.set(D.transform);else{Z(this.modelMatrix,this.modelRootMatrix,D.transform);let P=!t&&(D.extras?.xr?.billboard??D.userData?.xr?.billboard);if(P){let S=this.modelMatrix,H=Math.hypot(S[0],S[1],S[2])||1,m=Math.hypot(S[4],S[5],S[6])||1,F=Math.hypot(S[8],S[9],S[10])||1,k=P==="y"||P==="cylindrical"||P==="capsule",_=x-S[12],N=v-S[14],I=Math.hypot(_,N),B=I>1e-5?_/I:0,W=I>1e-5?N/I:1;S.set(k?[W*H,0,-B*H,0,0,m,0,0,B*F,0,W*F]:[n[0]*H,n[4]*H,n[8]*H,0,n[1]*m,n[5]*m,n[9]*m,0,n[2]*F,n[6]*F,n[10]*F])}}Z(this.mvpMatrix,o,this.modelMatrix),oe(D.normalMatrix,this.modelMatrix);let w=D.extras?.xr?.stereo||D.userData?.xr?.stereo,R=0,V=0,U=1,L=1;w==="sbs"?(U=.5,R=p==="right"?.5:0):w==="ou"&&(L=.5,V=p==="right"?.5:0);for(let P of D.primitives){let S=!!P.isTransmissive;if(!b&&S){d=!0;continue}if(b&&!S)continue;let H=P.customProgram||this.renderProg,m=P.customUniforms||this.uRender;e.useProgram(H),e.vertexAttrib3f(3,0,0,0),m.uInstanced&&e.uniform1i(m.uInstanced,0),e.uniform1i(m.uToneMapping,c),e.uniform1f(m.uEnvIntensity,this.envIntensity),m.uExposure&&e.uniform1f(m.uExposure,this.exposure),e.uniform3f(m.uCameraPos,x,f,v),e.uniform1f(m.uEmissive,A?1:0),e.uniformMatrix4fv(m.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(m.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(m.uNormalMatrix,!1,D.normalMatrix),m.uUvTransform&&e.uniform4f(m.uUvTransform,R,V,U,L),m.uViewportSize&&e.uniform2f(m.uViewportSize,Math.max(1,a),Math.max(1,r)),h?.bind(e,m,this.xrDepthState,n,[i,s,Math.max(1,a),Math.max(1,r)]),g.shadowMapShader?.bind(e,m,this,D),T(4,this.environmentTexture,m.uEnvironmentMap,m.uHasEnvironmentMap),this.bindLights(m),m.uSectionEnabled&&e.uniform1i(m.uSectionEnabled,0);for(let k of K)k.onBeforeDrawPrimitive?.(e,H,P,D,this.worldMatrices||[],this.gltf);e.uniform4fv(m.uBaseColor,P.baseColor),e.uniform1f(m.uMetallic,P.metallic),e.uniform1f(m.uRoughness,P.roughness),m.uClearcoat&&e.uniform2f(m.uClearcoat,P.clearcoat??0,P.clearcoatRoughness??.04),T(0,P.texture,m.uBaseColorTexture,m.uHasTexture),T(1,P.metallicRoughnessTexture,m.uMetallicRoughnessTexture,m.uHasMetallicRoughnessTexture),T(2,P.normalTexture,m.uNormalTexture,m.uHasNormalTexture),P.normalTexture&&e.uniform1f(m.uNormalScale,P.normalScale),T(3,P.occlusionTexture,m.uOcclusionTexture,m.uHasOcclusionTexture),P.occlusionTexture&&e.uniform1f(m.uOcclusionStrength,P.occlusionStrength),e.uniform3fv(m.uEmissiveFactor,P.emissiveFactor),T(8,P.emissiveTexture,m.uEmissiveTexture,m.uHasEmissiveTexture),e.bindVertexArray(P.vao);let F=D.instanceMatrices;if(P.instanceCount!==void 0)e.drawElementsInstanced(4,P.indexCount,P.indexType,0,P.instanceCount);else if(F&&F.length>=16&&P.instanced&&m.uInstanced&&m.uViewProj){let k=F.length>>4;e.uniform1i(m.uInstanced,1),e.uniformMatrix4fv(m.uViewProj,!1,o),P.indices?e.drawElementsInstanced(4,P.indexCount,P.indexType,0,k):e.drawArraysInstanced(4,0,P.indexCount,k),e.uniform1i(m.uInstanced,0)}else if(F&&F.length>=16){let k=F.length>>4,_=D.instanceColors,N=$(),I=new Float32Array(9);for(let B=0;B<k;B++){if(Z(N,this.modelMatrix,F.subarray(B*16,B*16+16)),Z(this.mvpMatrix,o,N),oe(I,N),e.uniformMatrix4fv(m.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(m.uModel,!1,N),e.uniformMatrix3fv(m.uNormalMatrix,!1,I),_){let W=P.baseColor,q=B*3;e.uniform4fv(m.uBaseColor,[W[0]*_[q],W[1]*_[q+1],W[2]*_[q+2],W[3]])}Pe(e,P)}}else Pe(e,P)}}};if(C(!1),d){for(let b of K)b.onBeforeTransmissivePass?.(e,this);C(!0)}for(let b of K)b.onAfterRender?.(e,this,o,p,[i,s,a,r],l)}disposeMeshListGpuResources(t,e){Je(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 K)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()}};le.registerPlugin=De,le.getRegisteredPlugins=Fe;var bt=le;