three-live 1.2.0 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/index.d.ts +182 -6
- package/dist/three-author-engine.js +66 -41
- package/dist/three-author.cjs +63 -39
- package/dist/three-author.d.ts +182 -6
- package/dist/three-author.js +63 -39
- package/dist/three-convert.cjs +61 -37
- package/dist/three-convert.d.ts +182 -6
- package/dist/three-convert.js +61 -37
- package/dist/three-live-animation.cjs +7 -7
- package/dist/three-live-animation.d.ts +182 -6
- package/dist/three-live-animation.js +7 -7
- package/dist/three-live-animation.min.js +7 -7
- package/dist/three-live-cad.cjs +18 -0
- package/dist/{three-live-extras.d.ts → three-live-cad.d.ts} +182 -6
- package/dist/three-live-cad.js +18 -0
- package/dist/three-live-cad.min.js +18 -0
- package/dist/three-live-element.cjs +29 -5
- package/dist/three-live-element.d.ts +182 -6
- package/dist/three-live-element.js +29 -5
- package/dist/three-live-full.cjs +159 -56
- package/dist/three-live-full.js +159 -56
- package/dist/three-live-full.min.js +159 -56
- package/dist/three-live-studio.cjs +120 -0
- package/dist/three-live-studio.d.ts +509 -0
- package/dist/three-live-studio.js +120 -0
- package/dist/three-live-studio.min.js +120 -0
- package/dist/three-live-viewer.cjs +29 -5
- package/dist/three-live-viewer.d.ts +182 -6
- package/dist/three-live-viewer.js +29 -5
- package/dist/three-live-viewer.min.js +29 -5
- package/dist/three-live.cjs +66 -42
- package/dist/three-live.js +66 -42
- package/dist/three-live.min.js +66 -42
- package/dist/three-view.cjs +29 -5
- package/dist/three-view.d.ts +182 -6
- package/dist/three-view.js +29 -5
- package/dist/three-xr.cjs +65 -41
- package/dist/three-xr.d.ts +182 -6
- package/dist/three-xr.js +65 -41
- package/package.json +10 -5
- package/dist/three-live-extras.cjs +0 -42
- package/dist/three-live-extras.js +0 -42
- package/dist/three-live-extras.min.js +0 -42
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
"use strict";var
|
|
17
|
+
"use strict";var Ee=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var st=(n,t)=>{for(var e in t)Ee(n,e,{get:t[e],enumerable:!0})},at=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rt(t))!nt.call(n,i)&&i!==e&&Ee(n,i,{get:()=>t[i],enumerable:!(r=it(t,i))||r.enumerable});return n};var ot=n=>at(Ee({},"__esModule",{value:!0}),n);var gt={};st(gt,{ThreeLiveElement:()=>Ae});module.exports=ot(gt);var Ie='SecurityError: Client-modified script compilation (Use Case 1) is disabled by default to satisfy strict CSP and Trusted Types requirements. Use script-src="..." or loadScriptFromSrc(url) for server-generated scripts (Use Case 2), or explicitly opt in via ThreeLiveElement.allowClientScripts = true (or the allow-client-scripts attribute).',Ne="Security Error: client-side scripts require allow-client-scripts opt-in.";var Me="__THREE_LIVE_REGISTRY__";function K(){let n=typeof globalThis<"u"?globalThis:{};if(!n[Me]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(n,Me,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{n[Me]=t}}return n[Me]}var Z=K().plugins;function Be(n){let t=K().plugins;t.some(e=>e.name===n.name)||t.push(n),n.onRegister?.()}function ke(){return K().plugins}function W(){let n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n}function Te(n,t,e,r,i){let s=1/Math.tan(t/2);n.fill(0),n[0]=s/e,n[5]=s,n[11]=-1;let a=1/(r-i);return n[10]=(i+r)*a,n[14]=2*i*r*a,n}function we(n,t,e,r){let[i,s,a]=t,[l,o,c]=r,[u,h,x]=e,y=i-u,d=s-h,b=a-x,g=Math.hypot(y,d,b);g<=1e-5?(y=0,d=0,b=1):(y/=g,d/=g,b/=g);let w=o*b-c*d,S=c*y-l*b,T=l*d-o*y;g=Math.hypot(w,S,T),g<=1e-5?(w=0,S=0,T=0):(w/=g,S/=g,T/=g);let M=d*T-b*S,v=b*w-y*T,m=y*S-d*w;return g=Math.hypot(M,v,m),g<=1e-5?(M=0,v=0,m=0):(M/=g,v/=g,m/=g),n[0]=w,n[1]=M,n[2]=y,n[3]=0,n[4]=S,n[5]=v,n[6]=d,n[7]=0,n[8]=T,n[9]=m,n[10]=b,n[11]=0,n[12]=-(w*i+S*s+T*a),n[13]=-(M*i+v*s+m*a),n[14]=-(y*i+d*s+b*a),n[15]=1,n}function Q(n,t,e){let r=t[0],i=t[1],s=t[2],a=t[3],l=t[4],o=t[5],c=t[6],u=t[7],h=t[8],x=t[9],y=t[10],d=t[11],b=t[12],g=t[13],w=t[14],S=t[15],T=e[0],M=e[1],v=e[2],m=e[3];return n[0]=T*r+M*l+v*h+m*b,n[1]=T*i+M*o+v*x+m*g,n[2]=T*s+M*c+v*y+m*w,n[3]=T*a+M*u+v*d+m*S,T=e[4],M=e[5],v=e[6],m=e[7],n[4]=T*r+M*l+v*h+m*b,n[5]=T*i+M*o+v*x+m*g,n[6]=T*s+M*c+v*y+m*w,n[7]=T*a+M*u+v*d+m*S,T=e[8],M=e[9],v=e[10],m=e[11],n[8]=T*r+M*l+v*h+m*b,n[9]=T*i+M*o+v*x+m*g,n[10]=T*s+M*c+v*y+m*w,n[11]=T*a+M*u+v*d+m*S,T=e[12],M=e[13],v=e[14],m=e[15],n[12]=T*r+M*l+v*h+m*b,n[13]=T*i+M*o+v*x+m*g,n[14]=T*s+M*c+v*y+m*w,n[15]=T*a+M*u+v*d+m*S,n}function Pe(n,t,e,r){let i=t[0],s=t[1],a=t[2],l=t[3],o=i+i,c=s+s,u=a+a,h=i*o,x=i*c,y=i*u,d=s*c,b=s*u,g=a*u,w=l*o,S=l*c,T=l*u,M=r[0],v=r[1],m=r[2];return n[0]=(1-(d+g))*M,n[1]=(x+T)*M,n[2]=(y-S)*M,n[3]=0,n[4]=(x-T)*v,n[5]=(1-(h+g))*v,n[6]=(b+w)*v,n[7]=0,n[8]=(y+S)*m,n[9]=(b-w)*m,n[10]=(1-(h+d))*m,n[11]=0,n[12]=e[0],n[13]=e[1],n[14]=e[2],n[15]=1,n}function ce(n,t){let e=t[0],r=t[1],i=t[2],s=t[4],a=t[5],l=t[6],o=t[8],c=t[9],u=t[10],h=u*a-l*c,x=-u*s+l*o,y=c*s-a*o,d=e*h+r*x+i*y;return d&&(d=1/d,n[0]=h*d,n[1]=x*d,n[2]=y*d,n[3]=(-u*r+i*c)*d,n[4]=(u*e-i*o)*d,n[5]=(-c*e+r*o)*d,n[6]=(l*r-i*a)*d,n[7]=(-l*e+i*s)*d,n[8]=(a*e-r*s)*d),n}function Ge(n,t){let e=t[0],r=t[1],i=t[2],s=t[3],a=t[4],l=t[5],o=t[6],c=t[7],u=t[8],h=t[9],x=t[10],y=t[11],d=t[12],b=t[13],g=t[14],w=t[15],S=e*l-r*a,T=e*o-i*a,M=e*c-s*a,v=r*o-i*l,m=r*c-s*l,I=i*c-s*o,k=u*b-h*d,C=u*g-x*d,F=u*w-y*d,E=h*g-x*b,A=h*w-y*b,p=x*w-y*g,R=S*p-T*A+M*E+v*F-m*C+I*k;return R?(R=1/R,n[0]=(l*p-o*A+c*E)*R,n[1]=(i*A-r*p-s*E)*R,n[2]=(b*I-g*m+w*v)*R,n[3]=(x*m-h*I-y*v)*R,n[4]=(o*F-a*p-c*C)*R,n[5]=(e*p-i*F+s*C)*R,n[6]=(g*M-d*I-w*T)*R,n[7]=(u*I-x*M+y*T)*R,n[8]=(a*A-l*F+c*k)*R,n[9]=(r*F-e*A-s*k)*R,n[10]=(d*m-b*M+w*S)*R,n[11]=(h*M-u*m-y*S)*R,n[12]=(l*C-a*E-o*k)*R,n[13]=(e*E-r*C+i*k)*R,n[14]=(b*T-d*v-g*S)*R,n[15]=(u*v-h*T+x*S)*R,n):null}function Se(n,t,e,r,i){let s=i[0]*t+i[4]*e+i[8]*r+i[12],a=i[1]*t+i[5]*e+i[9]*r+i[13],l=i[2]*t+i[6]*e+i[10]*r+i[14],o=i[3]*t+i[7]*e+i[11]*r+i[15],c=o!==0?1/o:1;n[0]=s*c,n[1]=a*c,n[2]=l*c}function _e(n,t,e,r,i,s,a,l,o,c,u,h,x,y,d,b,g=0){let w=c-a,S=u-l,T=h-o,M=x-a,v=y-l,m=d-o,I=i*m-s*v,k=s*M-r*m,C=r*v-i*M,F=w*I+S*k+T*C;if(F>-1e-7&&F<1e-7)return!1;let E=1/F,A=n-a,p=t-l,R=e-o,D=E*(A*I+p*k+R*C);if(D<-g||D>1+g)return!1;let f=p*T-R*S,_=R*w-A*T,P=A*S-p*w,j=E*(r*f+i*_+s*P);if(j<-g||D+j>1+g)return!1;let V=E*(M*f+v*_+m*P);if(V>1e-4&&V<b.distance){b.distance=V,b.point=[n+r*V,t+i*V,e+s*V];let Y=S*m-T*v,B=T*M-w*m,O=w*v-S*M,X=Math.hypot(Y,B,O)||1;return b.normal=[Y/X,B/X,O/X],!0}return!1}function Oe(n,t){let e=Array.isArray(n?.nodes)?n.nodes.length:0,r=[];for(let u=0;u<e;u++)r.push(W());if(e===0)return r;let i=new Set;for(let u of n.nodes)if(Array.isArray(u.children))for(let h of u.children)i.add(h);let s=new Set,a=128,l=(u,h,x=0)=>{if(x>a||u<0||u>=e||s.has(u))return;s.add(u);let y=n.nodes[u];if(!y)return;let d=W();if(t&&t[u])d.set(t[u]);else if(y.matrix&&y.matrix.length===16)d.set(y.matrix);else{let g=y.translation||[0,0,0],w=y.rotation||[0,0,0,1],S=y.scale||[1,1,1];Pe(d,w,g,S)}let b=r[u];if(h?Q(b,h,d):b.set(d),Array.isArray(y.children))for(let g of y.children)typeof g=="number"&&l(g,b,x+1)},o=[],c=n.scenes&&n.scenes[n.scene!==void 0?n.scene:0];if(c&&Array.isArray(c.nodes))o.push(...c.nodes);else for(let u=0;u<e;u++)i.has(u)||o.push(u);for(let u of o)l(u,null);for(let u=0;u<e;u++)!i.has(u)&&!o.includes(u)&&l(u,null);return r}function ut(n){return new TextDecoder().decode(n)}var We=K().decoders;function lt(n,t){We.set(n.toLowerCase(),t)}function de(n){return We.get(n.toLowerCase())}function Xe(n){let t=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n,e=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let r=e.getUint32(0,!0);if(r!==1179937895){let x=e.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${r.toString(16)}`)}let i=e.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);let s=e.getUint32(8,!0),a=12,l=null,o=null;for(;a+8<=s&&a+8<=t.byteLength;){let x=e.getUint32(a,!0),y=e.getUint32(a+4,!0),d=a+8;if(d+x>t.byteLength)throw new Error(`Truncated GLB chunk: required ${d+x} bytes, buffer has ${t.byteLength}`);if(y===1313821514){let b=new Uint8Array(t,d,x),g=ut(b);l=JSON.parse(g,(w,S)=>w==="__proto__"||w==="constructor"||w==="prototype"?void 0:S)}else y===5130562&&(o=t.slice(d,d+x));a=d+x}if(!l)throw new Error("Missing JSON chunk in GLB");let c=l.extensionsRequired||[];if(c.includes("KHR_draco_mesh_compression")&&!de("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");if(c.includes("EXT_meshopt_compression")&&!de("meshopt"))throw new Error("Model requires EXT_meshopt_compression. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).");if(c.includes("KHR_texture_basisu")&&!de("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let u=o||new ArrayBuffer(0),h={gltf:l,bin:u,animations:[]};for(let x of Z)x.onParseGLB?.(h);return h}function ct(n,t,e){return t%4===0?new Float32Array(n,t,e):new Float32Array(n.slice(t,t+e*4))}function ht(n){return typeof n=="object"&&n!==null&&"gltf"in n&&typeof n.gltf=="object"&&n.gltf!==null&&"bin"in n&&(n.bin instanceof ArrayBuffer||ArrayBuffer.isView(n.bin))}function Re(n){if(ht(n))return n;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return Xe(n);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var ze=`#version 300 es
|
|
18
18
|
layout(location=0) in vec3 aPosition;
|
|
19
19
|
layout(location=1) in vec3 aNormal;
|
|
20
20
|
layout(location=2) in vec2 aUV;
|
|
@@ -32,7 +32,7 @@ vec2 scaleUV=uUvTransform.zw;
|
|
|
32
32
|
if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
|
|
33
33
|
vUV=aUV*scaleUV+uUvTransform.xy;
|
|
34
34
|
gl_Position=uMVP*vec4(aPosition,1.0);
|
|
35
|
-
}`,
|
|
35
|
+
}`,mt=`#version 300 es
|
|
36
36
|
precision highp float;
|
|
37
37
|
in vec3 vNormal,vWorldPos;
|
|
38
38
|
in vec2 vUV;
|
|
@@ -108,9 +108,33 @@ float g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);
|
|
|
108
108
|
return mix(color,newPeak*vec3(1.0),g);
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
vec3 acesToneMapping(vec3 color){
|
|
112
|
+
color*=0.6;
|
|
113
|
+
return clamp((color*(2.51*color+0.03))/(color*(2.43*color+0.59)+0.14),0.0,1.0);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
vec3 agxToneMapping(vec3 color){
|
|
117
|
+
color=max(color,vec3(0.0));
|
|
118
|
+
vec3 inset=vec3(
|
|
119
|
+
0.84247906*color.r+0.0784336*color.g+0.07922375*color.b,
|
|
120
|
+
0.04232824*color.r+0.87846864*color.g+0.07916613*color.b,
|
|
121
|
+
0.04237565*color.r+0.0784336*color.g+0.87914297*color.b);
|
|
122
|
+
vec3 ev=clamp((log2(max(inset,vec3(1e-6)))+12.47393)/16.5,0.0,1.0);
|
|
123
|
+
vec3 x2=ev*ev;
|
|
124
|
+
vec3 x4=x2*x2;
|
|
125
|
+
vec3 s=15.5*x4*x2-40.14*x4*ev+31.96*x4-6.868*x2*ev+0.4298*x2+0.1191*ev-0.00232;
|
|
126
|
+
vec3 outset=vec3(
|
|
127
|
+
1.196879*s.r-0.09802088*s.g-0.09902974*s.b,
|
|
128
|
+
-0.05289685*s.r+1.15190313*s.g-0.09896118*s.b,
|
|
129
|
+
-0.05297164*s.r-0.09804345*s.g+1.15107367*s.b);
|
|
130
|
+
return clamp(pow(max(outset,vec3(0.0)),vec3(2.2)),0.0,1.0);
|
|
131
|
+
}
|
|
132
|
+
|
|
111
133
|
vec3 applyToneMapping(vec3 color,int mode){
|
|
112
134
|
if(mode==0)return neutralToneMapping(color);
|
|
113
135
|
if(mode==1)return color/(color+vec3(1.0));
|
|
136
|
+
if(mode==3)return acesToneMapping(color);
|
|
137
|
+
if(mode==4)return agxToneMapping(color);
|
|
114
138
|
return color;
|
|
115
139
|
}
|
|
116
140
|
|
|
@@ -198,11 +222,11 @@ color=applyToneMapping(color,uToneMapping);
|
|
|
198
222
|
float outAlpha=base.a;
|
|
199
223
|
/*XRD_O*/
|
|
200
224
|
fragColor=vec4(color,outAlpha);
|
|
201
|
-
}
|
|
225
|
+
}`;var dt=`#version 300 es
|
|
202
226
|
layout(location=0) in vec3 aPosition;
|
|
203
227
|
uniform mat4 uMVP;
|
|
204
|
-
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,
|
|
228
|
+
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,pt=`#version 300 es
|
|
205
229
|
precision highp float;
|
|
206
230
|
uniform vec4 uColorId;
|
|
207
231
|
out vec4 fragColor;
|
|
208
|
-
void main(){fragColor=uColorId;}`;function Le(n,t,e){let r=n.createShader(t);if(n.shaderSource(r,e),n.compileShader(r),!n.getShaderParameter(r,35713)){let i=n.getShaderInfoLog(r);throw n.deleteShader(r),new Error(`Shader compile error: ${i}`)}return r}function we(n,t,e){let r=Le(n,35633,t),i=Le(n,35632,e),s=n.createProgram();if(n.attachShader(s,r),n.attachShader(s,i),n.linkProgram(s),!n.getProgramParameter(s,35714)){let o=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${o}`)}return s}function Re(n,t,e){let r={};for(let i of e)r[i]=n.getUniformLocation(t,i);return r}var Fe=["uMVP","uModel","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uViewportSize","uSectionPlane","uSectionEnabled"];function Ue(){let n=_().xrDepthShader;return{fs:rt.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Fe,...n.uniformNames]:Fe}}function at(n){if(typeof n!="string")return null;let t=n.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let e=t.toLowerCase();return e.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:e.startsWith("https://")||e.startsWith("blob:")?t:e.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function Me(n,t,e,r,i,s,o){if(r===void 0||!t.accessors?.[r])return null;let l=t.accessors[r],u=t.bufferViews[l.bufferView],c=(u.byteOffset||0)+(l.byteOffset||0),a=u.byteStride&&u.byteStride>s*4?u.byteStride>>2:s,h;if(a===s)h=new Float32Array(e,c,l.count*s);else{h=new Float32Array(l.count*s);let b=new Float32Array(e,u.byteOffset||0,Math.floor(u.byteLength/4)),f=(l.byteOffset||0)>>2;for(let y=0;y<l.count;y++){let T=f+y*a;for(let w=0;w<s;w++)h[y*s+w]=b[T+w]}}let p=n.createBuffer();return o.push(p),n.bindBuffer(34962,p),n.bufferData(34962,h,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),h}var Ge=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Oe=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Ie(n,t,e=Oe,r){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:i,bin:s}=t,o=[],l=Ce(i),u=[];if(Array.isArray(i.nodes))for(let E=0;E<i.nodes.length;E++){let g=i.nodes[E];g.mesh!==void 0&&i.meshes&&i.meshes[g.mesh]&&u.push({node:g,nodeIdx:E,meshIdx:g.mesh})}let c=u.length>0?u:(i.meshes||[]).map((E,g)=>({node:E,nodeIdx:-1,meshIdx:g})),a=[];if(Array.isArray(t.lights)&&t.lights.length>0)a.push(...t.lights);else if(i.extensions?.KHR_lights_punctual?.lights){let E=i.extensions.KHR_lights_punctual.lights;for(let g of E){let S=g.type==="directional"?"directional":g.type==="point"?"point":"ambient";a.push({type:S,color:g.color||[1,1,1],intensity:g.intensity!==void 0?g.intensity:1})}}if(a.length===0&&(a.push({type:"ambient",color:[1,1,1],intensity:.35}),a.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),c.length>e.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${e.maxMeshes}). Found: ${c.length}`);let h=[];if(i.textures&&i.images){if(i.textures.length>e.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${e.maxTextures}). Found: ${i.textures.length}`);for(let E=0;E<i.textures.length;E++){let g=i.textures[E],S=i.images[g.source];if(S){let D=n.createTexture();if(n.bindTexture(3553,D),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),S.bufferView!==void 0){let C=i.bufferViews[S.bufferView],x=s.slice(C.byteOffset||0,(C.byteOffset||0)+C.byteLength),M=new Blob([x],{type:S.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(M).then(k=>{n.bindTexture(3553,D),n.texImage2D(3553,0,6408,6408,5121,k),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(S.uri){let C=at(S.uri);if(C){let x=new Image;x.crossOrigin="anonymous",x.referrerPolicy="no-referrer",x.onload=()=>{n.bindTexture(3553,D),n.texImage2D(3553,0,6408,6408,5121,x),n.generateMipmap(3553),r?.()},x.src=C}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",S.uri)}h.push(D)}else h.push(null)}}let p=[1/0,1/0,1/0],b=[-1/0,-1/0,-1/0],f=0,y=0;for(let E=0;E<c.length;E++){let g=c[E],S=i.meshes[g.meshIdx],D=g.nodeIdx>=0?l[g.nodeIdx]:W(),C=new Float32Array(9);ne(C,D);let x={name:g.node.name||S.name||`Mesh_${g.meshIdx}`,nodeIndex:g.nodeIdx,transform:D,normalMatrix:C,primitives:[],extras:g.node.extras||S.extras};for(let M of S.primitives||[]){if(M.extensions?.KHR_draco_mesh_compression){let I=he("draco");I&&I.decodePrimitive(i,M,s)}let k=[],A=n.createVertexArray();n.bindVertexArray(A);let X=i.accessors[M.attributes.POSITION],G=Number(X?.count??0);if(!Number.isFinite(G)||G<0||f+G>e.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${e.maxVertices}).`);if(f+=G,X?.min&&X?.max)for(let I=0;I<3;I++){let q=D[12+I],ae=D[12+I];for(let ee=0;ee<3;ee++){let de=D[ee*4+I]*X.min[ee],pe=D[ee*4+I]*X.max[ee];q+=de<pe?de:pe,ae+=de>pe?de:pe}q<p[I]&&(p[I]=q),ae>b[I]&&(b[I]=ae)}let re=Me(n,i,s,M.attributes.POSITION,0,3,k);Me(n,i,s,M.attributes.NORMAL,1,3,k),Me(n,i,s,M.attributes.TEXCOORD_0,2,2,k);let N=0,z=5123,B=null;if(M.indices!==void 0){let I=i.accessors[M.indices],ae=(i.bufferViews[I.bufferView].byteOffset||0)+(I.byteOffset||0);if(N=Number(I.count??0),!Number.isFinite(N)||N<0||y+N>e.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${e.maxIndices}).`);y+=N,z=I.componentType===5125?5125||5125:5123||5123;let ee=n.createBuffer();k.push(ee),n.bindBuffer(34963,ee),I.componentType===5125?(B=new Uint32Array(s,ae,I.count),n.bufferData(34963,B,35044)):(B=new Uint16Array(s,ae,I.count),n.bufferData(34963,B,35044))}else N=X.count;let F={};for(let I of H)if(I.onBuildPrimitiveVAO){let q=I.onBuildPrimitiveVAO(n,A,M,i,s);q&&(F[I.name]=q)}n.bindVertexArray(null);let U=i.materials&&M.material!==void 0?i.materials[M.material]:null,Y=Ue(),K=Ne,Z=Y.fs,Q=!1;for(let I of H)if(I.onResolveShader){let q=I.onResolveShader(M,U,K,Z);q&&(K=q.vs,Z=q.fs,Q=!0)}let se=Q?we(n,K,Z):null,me=se?Re(n,se,Y.uniforms):null,O=U?.pbrMetallicRoughness,oe=O?.baseColorFactor||[.8,.8,.8,1],ue=O?.metallicFactor??.1,ce=O?.roughnessFactor??.5,J=U?.extensions?.KHR_materials_clearcoat,te=J?J.clearcoatFactor??1:0,ie=Math.max(.04,J?.clearcoatRoughnessFactor??.04),le=O?.baseColorTexture!==void 0&&h[O.baseColorTexture.index]?h[O.baseColorTexture.index]:null,Ve=O?.metallicRoughnessTexture!==void 0&&h[O.metallicRoughnessTexture.index]?h[O.metallicRoughnessTexture.index]:null,We=U?.normalTexture!==void 0&&h[U.normalTexture.index]?h[U.normalTexture.index]:null,Xe=U?.normalTexture?.scale??1,ze=U?.occlusionTexture!==void 0&&h[U.occlusionTexture.index]?h[U.occlusionTexture.index]:null,je=U?.occlusionTexture?.strength??1,Ye=!!(U?.extensions?.KHR_materials_transmission||F.materials?.isTransmissive);x.primitives.push({vao:A,indexCount:N,indexType:z,baseColor:oe,metallic:ue,roughness:ce,clearcoat:te,clearcoatRoughness:ie,positions:re,indices:B,texture:le,metallicRoughnessTexture:Ve,normalTexture:We,occlusionTexture:ze,normalScale:Xe,occlusionStrength:je,buffers:k,materialIndex:M.material,pluginData:F,customProgram:se,customUniforms:me,isTransmissive:Ye})}o.push(x)}isFinite(p[0])||(p=[-1,-1,-1]),isFinite(b[0])||(b=[1,1,1]);let T=[(p[0]+b[0])/2,(p[1]+b[1])/2,(p[2]+b[2])/2],w=b[0]-p[0],P=b[1]-p[1],R=b[2]-p[2],v=Math.max(Math.hypot(w,P,R)/2,.5),d=[p[0],p[1],p[2]],m=[b[0],b[1],b[2]],L=t.animations;if(!L){for(let E of H)if(E.onParseGLB?.(t),t.animations){L=t.animations;break}}return L||(L=[]),{meshes:o,bounds:{center:T,radius:v,min:d,max:m},lights:a,animations:L,worldMatrices:l}}var j=class{constructor(t,e,r){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=W();this.clearColor=[0,0,0,0];this.envIntensity=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=W();this.viewMatrix=W();this.modelMatrix=W();this.mvpMatrix=W();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:W(),rawValueToMeters:.001,format:0};this.container=t;let i,s;if(e&&typeof e.getContext=="function"?(i=e,s=r):(s=e,i=s?.canvas),!i){let c=t.querySelector("canvas");c||(c=document.createElement("canvas"),c.style.width="100%",c.style.height="100%",c.style.display="block",c.style.touchAction="none",t.prepend(c)),i=c}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let o=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!o:o&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.envIntensity=Math.max(0,Number(this.opts.exposure))),this.opts.camera&&this.setInitialCamera(this.opts.camera.theta,this.opts.camera.phi,this.opts.camera.distance,this.opts.camera.zoom),this.opts.shadowIntensity!==void 0&&(this.shadowIntensity=Math.max(0,Math.min(1,Number(this.opts.shadowIntensity)||0))),this.opts.shadowSoftness!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(this.opts.shadowSoftness)||0))),this.opts.toneMapping!==void 0&&(this.toneMapping=this.opts.toneMapping),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let l=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!l)throw new Error("WebGL2 not supported");this.gl=l;let u=Ue();this.renderProg=we(l,Ne,u.fs),this.pickProg=we(l,nt,st),this.uRender=Re(l,this.renderProg,u.uniforms),this.uPick=Re(l,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo(),this.setupEvents(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(t,e){tt(t,e)}static getDecoder(t){return he(t)}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),r=Math.max(1,this.canvas.height);this.pickFboWidth=e,this.pickFboHeight=r,t.bindTexture(3553,this.pickTexture),t.texImage2D(3553,0,6408,e,r,0,6408,5121,null),t.texParameteri(3553,10241,9728),t.texParameteri(3553,10240,9728),t.bindRenderbuffer(36161,this.pickDepth),t.renderbufferStorage(36161,33189,e,r),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 r=this.gl,i=Math.max(1,t),s=Math.max(1,e);this.pickFboWidth=i,this.pickFboHeight=s,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,s,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,s)}loadGLBData(t,e){let{meshes:r,bounds:i,lights:s,animations:o,worldMatrices:l}=Ie(this.gl,t,e,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=o||[],this.worldMatrices=l||[],this.gltf=t.gltf,this.initialNodeTransforms=[],Array.isArray(t.gltf?.nodes))for(let c of t.gltf.nodes)this.initialNodeTransforms.push({t:c.translation?[c.translation[0],c.translation[1],c.translation[2]]:[0,0,0],r:c.rotation?[c.rotation[0],c.rotation[1],c.rotation[2],c.rotation[3]]:[0,0,0,1],s:c.scale?[c.scale[0],c.scale[1],c.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let c of H)c.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let u=t.exposure??t.environmentIntensity??t.gltf?.extras?.exposure??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.exposure??t.gltf?.asset?.extras?.environmentIntensity;u!==void 0&&(this.envIntensity=Math.max(0,Number(u))),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(t){this.loadGLBData(ke(t))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(t){this.loadGLBData(ge(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let r=ge(t),{meshes:i}=Ie(this.gl,r,Oe,()=>this.render());if(e)for(let s of i)s.transform[12]+=e[0],s.transform[13]+=e[1],s.transform[14]+=e[2],ne(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(t,e,r,i=1){this.clearColor=[t,e,r,i]}updateMeshTransforms(t){for(let e=0;e<this.meshes.length;e++){let r=this.meshes[e],i;t instanceof Map?i=t.get(r.name)??t.get(e):Array.isArray(t)?i=t[e]:t&&typeof t=="object"&&(Object.prototype.hasOwnProperty.call(t,r.name)?i=t[r.name]:Object.prototype.hasOwnProperty.call(t,e)&&(i=t[e])),i&&i.length===16&&(r.transform.set(i),ne(r.normalMatrix,r.transform))}}bindLights(t=this.uRender){let e=this.gl,r=[.28,.28,.28],i=[],s=[],o=[],l=[];for(let u of this.lights){let c=u.color||[1,1,1],a=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")r=[c[0]*a,c[1]*a,c[2]*a];else if(u.type==="directional"&&i.length<6){let h=u.direction||[.5,1,.8];i.push(h[0],h[1],h[2]),s.push(c[0]*a,c[1]*a,c[2]*a)}else if(u.type==="point"&&o.length<6){let h=u.position||[0,0,0];o.push(h[0],h[1],h[2]),l.push(c[0]*a,c[1]*a,c[2]*a)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),e.uniform3fv(t.uAmbientColor,r),e.uniform1i(t.uNumDirLights,i.length/3),i.length>0&&(e.uniform3fv(t.uDirLightDir,i),e.uniform3fv(t.uDirLightColor,s)),e.uniform1i(t.uNumPointLights,o.length/3),o.length>0&&(e.uniform3fv(t.uPointLightPos,o),e.uniform3fv(t.uPointLightColor,l)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.envIntensity=Math.max(0,Number(t))}getExposure(){return this.envIntensity}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=t}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of H)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of H)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,r=this.currDistance;return{theta:t,phi:e,radius:r,toString(){return`${t.toFixed(4)}rad ${e.toFixed(4)}rad ${r.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,r)=>{let i=this.meshes.flatMap(a=>a.primitives.filter(h=>h.materialIndex===r||t.length===1&&h.materialIndex===void 0)),s=i[0],o=s?[...s.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=s?s.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,u=s?s.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,c={baseColorFactor:o,metallicFactor:l,roughnessFactor:u,setBaseColorFactor:a=>{let h=[a[0],a[1],a[2],a[3]??1];c.baseColorFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=h);for(let p of i)p.baseColor=h;this.render()},setMetallicFactor:a=>{c.metallicFactor=a,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=a);for(let h of i)h.metallic=a;this.render()},setRoughnessFactor:a=>{c.roughnessFactor=a,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=a);for(let h of i)h.roughness=a;this.render()}};return{name:e.name||`Material_${r}`,pbrMetallicRoughness:c}})}playAnimation(t){if(this.animations.length!==0){if(t){let e=this.animations.find(r=>r.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)}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 H)if(e.evaluateAnimation){e.evaluateAnimation(this,t);return}}setTarget(t,e,r){this.customTarget=[t,e,r],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,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(e,Math.min(r,t))}setCamera(t,e,r,i){t!==void 0&&(this.targetTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.targetPhi=this.clampPhi(e*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(t,e,r,i){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),r!==void 0&&r>0){let s=this.clampDistance(r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(i!==void 0&&i>0){let s=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(t,e){let r=W();$(r,this.projMatrix,this.viewMatrix);let[i,s,o]=t,l=e?e[0]:0,u=e?e[1]:0,c=e?e[2]:0,a=this.modelRootMatrix;a&&(i=a[0]*t[0]+a[4]*t[1]+a[8]*t[2]+a[12],s=a[1]*t[0]+a[5]*t[1]+a[9]*t[2]+a[13],o=a[2]*t[0]+a[6]*t[1]+a[10]*t[2]+a[14],e&&(l=a[0]*e[0]+a[4]*e[1]+a[8]*e[2],u=a[1]*e[0]+a[5]*e[1]+a[9]*e[2],c=a[2]*e[0]+a[6]*e[1]+a[10]*e[2]));let h=r[0]*i+r[4]*s+r[8]*o+r[12],p=r[1]*i+r[5]*s+r[9]*o+r[13],b=r[2]*i+r[6]*s+r[10]*o+r[14],f=r[3]*i+r[7]*s+r[11]*o+r[15];if(f<=1e-4)return{x:0,y:0,z:1,visible:!1};let y=h/f,T=p/f,w=b/f,P=this.canvas.getBoundingClientRect(),R=P.width||this.canvas.clientWidth||this.canvas.width||300,v=P.height||this.canvas.clientHeight||this.canvas.height||150,d=(y*.5+.5)*R,m=(-T*.5+.5)*v,L=y>=-1.1&&y<=1.1&&T>=-1.1&&T<=1.1&&w>=-1&&w<=1;if(L&&e){let E=this.customTarget||this.bounds.center,g=E[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),S=E[1]+this.currDistance*Math.sin(this.currPhi),D=E[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),C=[i-g,s-S,o-D];l*C[0]+u*C[1]+c*C[2]>.05&&(L=!1)}return{x:d,y:m,z:w,visible:L}}setSelectedMesh(t){this.selectedMeshName=t||""}setupEvents(){let t=this.canvas;this.boundContextMenu=e=>{e.preventDefault()},t.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=e=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.totalDragDist=0,this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.isPanning=e.button===2||e.shiftKey||this.activePointers.size===2,t.setPointerCapture(e.pointerId))},t.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=e=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(e.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=e.clientX-r.x,s=e.clientY-r.y;if(this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||e.button===2||e.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],l=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],u=this.customTarget?[...this.customTarget]:[...this.bounds.center],c=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;u[0]+=(-i*o[0]+s*l[0])*c,u[1]+=(-i*o[1]+s*l[1])*c,u[2]+=(-i*o[2]+s*l[2])*c,this.customTarget=u}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},t.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=e=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(e.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{t.releasePointerCapture(e.pointerId)}catch{}if(this.totalDragDist<5&&e.button===0){let r=t.getBoundingClientRect(),i=Math.floor((e.clientX-r.left)*(t.width/Math.max(r.width,1))),s=Math.floor((e.clientY-r.top)*(t.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},t.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=e=>{if(!this.interactive)return;e.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(e.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},t.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=e=>{let r=e.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),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=e=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(e.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),e.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),e.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),e.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),e.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),e.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),e.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),e.preventDefault();break}},t.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let t=this.canvas;this.boundContextMenu&&(t.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(t.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(t.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(t.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(t.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(t.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(t,e){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,o=r.height||300,l=i.width>0?Math.floor((t-i.left)*(s/i.width)):Math.floor(t),u=i.height>0?Math.floor((e-i.top)*(o/i.height)):Math.floor(e);return this.performMeshPick(l,u,!1)}performMeshPick(t,e,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),o=Math.max(1,this.canvas.height||300);t=this.mapStereoPickX(t,s);let l=W();$(l,this.projMatrix,this.viewMatrix);let u=[],c=Math.max(0,Math.min(s-1,t)),a=Math.max(0,Math.min(o-1,o-1-e));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==o)&&this.resizePickingFbo(s,o),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,o),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let L=0;L<this.meshes.length;L++){let E=this.meshes[L];if(E.visible===!1||E.isPluginMesh)continue;let g=L+1,S=(g&255)/255,D=(g>>8&255)/255,C=(g>>16&255)/255;i.uniform4f(this.uPick.uColorId,S,D,C,1),$(this.modelMatrix,this.modelRootMatrix,E.transform),$(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let x of E.primitives)i.bindVertexArray(x.vao),i.drawElements(4,x.indexCount,x.indexType,0)}let d=new Uint8Array(4);i.readPixels(c,a,1,1,6408,5121,d),i.bindFramebuffer(36160,null);let m=d[0]+(d[1]<<8)+(d[2]<<16);m>0&&m<=this.meshes.length&&(u=[this.meshes[m-1]])}u.length===0&&(u=this.meshes.filter(d=>d.visible!==!1));let h=null,p=1/0,b=[0,0,0],f=[0,1,0],y=this.customTarget||this.bounds.center,T=y[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),w=y[1]+this.currDistance*Math.sin(this.currPhi),P=y[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let d of u){$(this.modelMatrix,this.modelRootMatrix,d.transform),$(this.mvpMatrix,l,this.modelMatrix);let m=W();if(!Se(m,this.mvpMatrix))continue;let L=(c+.5)/s*2-1,E=(a+.5)/o*2-1,g=[0,0,0],S=[0,0,0];Te(g,L,E,-1,m),Te(S,L,E,1,m);let D=S[0]-g[0],C=S[1]-g[1],x=S[2]-g[2],M=Math.hypot(D,C,x)||1,k=D/M,A=C/M,X=x/M,G={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((N=>{for(let z of d.primitives){if(!z.positions)continue;let B=z.positions,F=z.indices,U=Math.floor(F?F.length/3:B.length/9);for(let Y=0;Y<U;Y++){let K=F?F[Y*3]:Y*3,Z=F?F[Y*3+1]:Y*3+1,Q=F?F[Y*3+2]:Y*3+2;De(g[0],g[1],g[2],k,A,X,B[K*3],B[K*3+1],B[K*3+2],B[Z*3],B[Z*3+1],B[Z*3+2],B[Q*3],B[Q*3+1],B[Q*3+2],G,N)}}})(1e-4),isFinite(G.distance)){let N=G.point[0],z=G.point[1],B=G.point[2],F=this.modelMatrix,U=F[0]*N+F[4]*z+F[8]*B+F[12],Y=F[1]*N+F[5]*z+F[9]*B+F[13],K=F[2]*N+F[6]*z+F[10]*B+F[14],Z=U-T,Q=Y-w,se=K-P,me=Math.hypot(Z,Q,se);if(me<p){ne(this.normalMatrix,this.modelMatrix);let O=this.normalMatrix,oe=G.normal[0],ue=G.normal[1],ce=G.normal[2],J=O[0]*oe+O[3]*ue+O[6]*ce,te=O[1]*oe+O[4]*ue+O[7]*ce,ie=O[2]*oe+O[5]*ue+O[8]*ce,le=Math.hypot(J,te,ie)||1;J/=le,te/=le,ie/=le,J*Z+te*Q+ie*se>0&&(J=-J,te=-te,ie=-ie),h=d,p=Math.round(me*1e3)/1e3,b=[Math.round(U*1e3)/1e3,Math.round(Y*1e3)/1e3,Math.round(K*1e3)/1e3],f=[Math.round(J*1e3)/1e3,Math.round(te*1e3)/1e3,Math.round(ie*1e3)/1e3]}}}if(!h)return null;let v={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:p,hitPoint:b,normal:f,screenX:t,screenY:e};if(r){for(let d of H)d.onMeshSelect?.(this,v);this.opts.onMeshClick&&this.opts.onMeshClick(v),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:v}))}return v}mapStereoPickX(t,e){if(!this.stereoSBS||this.xrSessionActive||e<2)return t;let r=Math.max(1,Math.floor(e*.5)),i=t>=r,s=i?t-r:t,o=i?Math.max(1,e-r):r,l=(s+.5)/o*2-1;return Math.floor((l*.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);be(this.projMatrix,this.fov,t,.1,e);let r=this.customTarget||this.bounds.center,i=r[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),s=r[1]+this.currDistance*Math.sin(this.currPhi),o=r[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);ve(this.viewMatrix,[i,s,o],r,[0,1,0]),$(this.mvpMatrix,this.projMatrix,this.viewMatrix),ne(this.normalMatrix,this.modelMatrix)}resize(){let t=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),e=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(e.width*t)),i=Math.max(1,Math.floor(e.height*t));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(t){let e=this.xrSessionActive;if(this.xrSessionActive=t,e&&!t){this.xrDepthState.enabled=!1;for(let r of H)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(t){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",t))}stepXRUpdate(t){for(let e of H)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 r=Math.min(Math.max((e-this.lastTime)/1e3,0),.1);if(this.lastTime=e,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}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),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=t,s[1]=0,s[2]=-e,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=e,s[9]=0,s[10]=t,s[11]=0,s[12]=r-(t*r+e*i),s[13]=0,s[14]=i-(-e*r+t*i),s[15]=1}setVisible(t){this.isVisible=t}update(t){for(let o of H)o.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 o of H)o.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=s;let o={theta:r,phi:i,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(o),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:o}))}}renderXRView(t,e,r,i,s=!0,o=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let l=t?.transform?.inverse?.matrix||this.viewMatrix,u=t?.projectionMatrix||this.projMatrix,c=t?.transform?.position,a=c?[c.x,c.y,c.z]:[0,1.6,0];e?this.modelRootMatrix.set(e):r&&e&&this.modelRootMatrix.set(e),this.render({viewMatrix:l,projMatrix:u,eyePos:a,viewport:i,eye:t?.eye||"none",clear:o>0?!1:t?.eye!=="right",isAR:s})}render(t){if(!t&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),d=Math.max(1,this.canvas.height||1),m=Math.max(1,Math.floor(v*.5)),L=Math.max(1,v-m),E=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),g=this.customTarget||this.bounds.center,S=g[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),D=g[1]+this.currDistance*Math.sin(this.currPhi),C=g[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),x=Math.cos(this.currTheta),M=-Math.sin(this.currTheta),k=.032,A=W(),X=W(),G=[S-x*k,D,C-M*k],re=[g[0]-x*k*.25,g[1],g[2]-M*k*.25];be(A,this.fov,m/d,.1,E),ve(X,G,re,[0,1,0]);let N=W(),z=W(),B=[S+x*k,D,C+M*k],F=[g[0]+x*k*.25,g[1],g[2]+M*k*.25];be(N,this.fov,L/d,.1,E),ve(z,B,F,[0,1,0]),this.render({viewMatrix:X,projMatrix:A,eyePos:G,viewport:[0,0,m,d],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:z,projMatrix:N,eyePos:B,viewport:[m,0,L,d],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,d);return}let e=this.gl,r=0,i=0,s=this.canvas.width,o=this.canvas.height;t?.viewport?(r=t.viewport[0],i=t.viewport[1],s=t.viewport[2],o=t.viewport[3],e.viewport(r,i,s,o)):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(16384|256));let l=W(),u=t?.viewMatrix??this.viewMatrix;$(l,t?.projMatrix??this.projMatrix,u);let c=_().xrDepthShader,a=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:0,h=this.customTarget||this.bounds.center,p=t?t.eyePos[0]:h[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),b=t?t.eyePos[1]:h[1]+this.currDistance*Math.sin(this.currPhi),f=t?t.eyePos[2]:h[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let v of H)v.onBeforeDrawScene?.(this,e,l,[p,b,f],a);let y=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&y===0)return;let T=t?.eye||"none",w=!1,P=y>0?[...this.backdropMeshes,...this.meshes]:this.meshes,R=v=>{for(let d=0;d<P.length;d++){let m=P[d];if(m.visible===!1)continue;let L=this.selectedMeshName!==""&&m.name===this.selectedMeshName;d<y||m.worldSpace===!0||m.name==="__xr_reticle__"?this.modelMatrix.set(m.transform):$(this.modelMatrix,this.modelRootMatrix,m.transform),$(this.mvpMatrix,l,this.modelMatrix),ne(m.normalMatrix,this.modelMatrix);let E=m.extras?.xr?.stereo||m.userData?.xr?.stereo,g=0,S=0,D=1,C=1;E==="sbs"?(D=.5,g=T==="right"?.5:0):E==="ou"&&(C=.5,S=T==="right"?.5:0);for(let x of m.primitives){let M=!!x.isTransmissive;if(!v&&M){w=!0;continue}if(v&&!M)continue;let k=x.customProgram||this.renderProg,A=x.customUniforms||this.uRender;e.useProgram(k),e.uniform1i(A.uToneMapping,a),e.uniform1f(A.uEnvIntensity,this.envIntensity),e.uniform3f(A.uCameraPos,p,b,f),e.uniform1f(A.uEmissive,L?1:0),e.uniformMatrix4fv(A.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(A.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(A.uNormalMatrix,!1,m.normalMatrix),A.uUvTransform&&e.uniform4f(A.uUvTransform,g,S,D,C),A.uViewportSize&&e.uniform2f(A.uViewportSize,Math.max(1,s),Math.max(1,o)),c?.bind(e,A,this.xrDepthState,u,[r,i,Math.max(1,s),Math.max(1,o)]),this.environmentTexture?(e.activeTexture(33988),e.bindTexture(3553,this.environmentTexture),e.uniform1i(A.uEnvironmentMap,4),e.uniform1i(A.uHasEnvironmentMap,1)):e.uniform1i(A.uHasEnvironmentMap,0),this.bindLights(A),A.uSectionEnabled&&e.uniform1i(A.uSectionEnabled,0);for(let X of H)X.onBeforeDrawPrimitive?.(e,k,x,m,this.worldMatrices||[],this.gltf);e.uniform4fv(A.uBaseColor,x.baseColor),e.uniform1f(A.uMetallic,x.metallic),e.uniform1f(A.uRoughness,x.roughness),A.uClearcoat&&e.uniform2f(A.uClearcoat,x.clearcoat??0,x.clearcoatRoughness??.04),x.texture?(e.activeTexture(33984),e.bindTexture(3553,x.texture),e.uniform1i(A.uBaseColorTexture,0),e.uniform1i(A.uHasTexture,1)):e.uniform1i(A.uHasTexture,0),x.metallicRoughnessTexture?(e.activeTexture(33985),e.bindTexture(3553,x.metallicRoughnessTexture),e.uniform1i(A.uMetallicRoughnessTexture,1),e.uniform1i(A.uHasMetallicRoughnessTexture,1)):e.uniform1i(A.uHasMetallicRoughnessTexture,0),x.normalTexture?(e.activeTexture(33986),e.bindTexture(3553,x.normalTexture),e.uniform1i(A.uNormalTexture,2),e.uniform1i(A.uHasNormalTexture,1),e.uniform1f(A.uNormalScale,x.normalScale)):e.uniform1i(A.uHasNormalTexture,0),x.occlusionTexture?(e.activeTexture(33987),e.bindTexture(3553,x.occlusionTexture),e.uniform1i(A.uOcclusionTexture,3),e.uniform1i(A.uHasOcclusionTexture,1),e.uniform1f(A.uOcclusionStrength,x.occlusionStrength)):e.uniform1i(A.uHasOcclusionTexture,0),e.bindVertexArray(x.vao),e.drawElements(4,x.indexCount,x.indexType,0)}}};if(R(!1),w){for(let v of H)v.onBeforeTransmissivePass?.(e,this);R(!0)}for(let v of H)v.onAfterRender?.(e,this,l)}disposeMeshListGpuResources(t){let e=this.gl;for(let r of t)for(let i of r.primitives){if(i.vao&&e.deleteVertexArray(i.vao),i.buffers)for(let s of i.buffers)e.deleteBuffer(s);i.texture&&e.deleteTexture(i.texture),i.metallicRoughnessTexture&&e.deleteTexture(i.metallicRoughnessTexture),i.normalTexture&&e.deleteTexture(i.normalTexture),i.occlusionTexture&&e.deleteTexture(i.occlusionTexture),i.customProgram&&e.deleteProgram(i.customProgram)}}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes),this.meshes=[]}disposeGpuResources(){let t=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let e of H)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()}};j.registerPlugin=Ae,j.getRegisteredPlugins=Ee;var _e='SecurityError: Client-modified script compilation (Use Case 1) is disabled by default to satisfy strict CSP and Trusted Types requirements. Use script-src="..." or loadScriptFromSrc(url) for server-generated scripts (Use Case 2), or explicitly opt in via ThreeLiveElement.allowClientScripts = true (or the allow-client-scripts attribute).',He="Security Error: client-side scripts require allow-client-scripts opt-in.";var ot=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(n,t){super(n,t),this.detail=t?.detail??null}});var V=class V extends ot{constructor(){super(...arguments);this.viewer=null;this.canvas=null;this.posterEl=null;this.arButton=null;this.currentModel=null;this.activeXRSession=null;this.toastTimer=null;this.currentModelLimits=void 0;this.isModelLoaded=!1;this.scriptHandle=null;this.resizeObserver=null;this.mutationObserver=null}static get arProvider(){return _().arProvider}static set arProvider(e){_().arProvider=e}static get scriptRunner(){return _().scriptRunner}static set scriptRunner(e){_().scriptRunner=e}static get sandboxEngineSrc(){return _().sandboxEngineSrc??null}static set sandboxEngineSrc(e){_().sandboxEngineSrc=e}static get sandboxIframeSrc(){return _().sandboxIframeSrc??null}static set sandboxIframeSrc(e){_().sandboxIframeSrc=e}static get allowClientScripts(){return!!_().allowClientScripts}static set allowClientScripts(e){_().allowClientScripts=e}static registerScriptRunner(e){V.scriptRunner=e}static registerDecoder(e,r){j.registerDecoder(e,r)}static getDecoder(e){return j.getDecoder(e)}static registerAR(e){typeof e=="function"?V.arProvider={activateAR:e}:V.arProvider=e,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof V&&i.updateARButtonVisibility()})}static isARSupported(){return!!V.arProvider}getLoadedModel(){return this.currentModel}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let e=this.getAttribute("src"),r=this.getAttribute("script-src");if(e)this.loadModelFromSrc(e).catch(()=>{});else if(r)this.loadScriptFromSrc(r).catch(()=>{});else{let i=this.querySelector('script[type="text/three"], script[type="text/three-live"]');i&&i.textContent&&this.executeScript(i.textContent).catch(()=>{})}for(let i of j.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let e of j.getRegisteredPlugins())e.onElementDisconnected?.(this);this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.activeXRSession&&(this.activeXRSession.stop?.().catch?.(()=>{}),this.activeXRSession=null),this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),this.viewer&&(this.viewer.destroy(),this.viewer=null),this.isModelLoaded=!1}attributeChangedCallback(e,r,i){if(r!==i){switch(e){case"src":i&&this.loadModelFromSrc(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer&&i&&this.viewer.setToneMapping(i);break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(i!==null&&i!=="false");break;case"animation-name":this.viewer&&i!==null&&this.viewer.setAnimationName(i);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(i!==null&&i!=="false");break;case"auto-rotate-delay":this.viewer&&this.viewer.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":this.viewer&&this.viewer.setAutoRotateSpeed(this.parseRotationPerSecond(i));break;case"ar":this.updateARButtonVisibility();break}for(let s of j.getRegisteredPlugins())s.onAttributeChanged?.(this,e,r,i)}}getAttr(e){return this.getAttribute(e)}setAttr(e,r){r!==null?this.setAttribute(e,r):this.removeAttribute(e)}getBoolAttr(e){return this.hasAttribute(e)&&this.getAttribute(e)!=="false"}setBoolAttr(e,r){r?this.setAttribute(e,""):this.removeAttribute(e)}getFloatAttr(e,r){let i=this.getAttribute(e);return i!==null?parseFloat(i):r}get src(){return this.getAttr("src")}set src(e){this.setAttr("src",e)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(e){this.setBoolAttr("camera-controls",e)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(e){this.setAttr("camera-orbit",e)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(e){this.setAttr("camera-target",e)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(e){this.setAttr("min-camera-orbit",e)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(e){this.setAttr("max-camera-orbit",e)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(e){this.setAttr("field-of-view",e)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(e){this.setAttr("ios-src",e)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(e){this.setAttr("script-src",e)}get sandbox(){return this.getAttribute("sandbox")||(_().sandboxIframeSrc?"iframe":"worker")}set sandbox(e){this.setAttribute("sandbox",e)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||V.allowClientScripts}set allowClientScripts(e){this.setBoolAttr("allow-client-scripts",e)}get poster(){return this.getAttr("poster")}set poster(e){this.setAttr("poster",e)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(e){this.setAttr("selected-mesh",e)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(e){this.setAttribute("exposure",String(e))}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(e){this.setBoolAttr("auto-rotate",e)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(e){this.setAttribute("auto-rotate-delay",String(e))}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(e){this.setAttr("rotation-per-second",e)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(e){this.setBoolAttr("ar",e)}get arScale(){return this.getAttribute("ar-scale")||"auto"}set arScale(e){this.setAttribute("ar-scale",e)}get arPlacement(){return this.getAttribute("ar-placement")||"floor"}set arPlacement(e){this.setAttribute("ar-placement",e)}get canActivateAR(){return V.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(e){this.setAttribute("shadow-intensity",String(e))}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(e){this.setAttribute("shadow-softness",String(e))}get toneMapping(){return this.getAttribute("tone-mapping")||"neutral"}set toneMapping(e){this.setAttribute("tone-mapping",e)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(e){this.setAttr("environment-image",e)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(e){this.setAttr("skybox-image",e)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(e){this.setBoolAttr("autoplay",e)}get animationName(){return this.getAttr("animation-name")}set animationName(e){this.setAttr("animation-name",e)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get model(){let e=this.viewer?this.viewer.getModelMaterials():[];return{materials:e,getMaterialByName(r){return e.find(i=>i.name===r)??null}}}play(){this.viewer&&this.viewer.playAnimation(this.animationName||void 0)}pause(){this.viewer&&this.viewer.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(e=0){this.viewer?.resetTurntableRotation(e)}setCamera(e,r,i,s){this.viewer&&this.viewer.setCamera(e,r,i,s)}getCameraOrbit(){return this.viewer?this.viewer.getCameraOrbit():{theta:0,phi:0,radius:3,toString(){return"0rad 0rad 3m"}}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():{x:0,y:0,z:0,toString(){return"0m 0m 0m"}}}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(e,r){return this.viewer&&this.viewer.render?.(),this.canvas?this.canvas.toDataURL(e,r):""}toBlob(e){return this.viewer&&this.viewer.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(s=>{s?r(s):i(new Error("Failed to capture canvas blob."))},e?.mimeType,e?.qualityArgument)})}positionAndNormalFromPoint(e,r){if(!this.viewer)return null;let i=this.viewer.raycastFromScreenPoint(e,r);if(!i)return null;let[s,o,l]=i.hitPoint||i.point,[u,c,a]=i.normal;return{position:{x:s,y:o,z:l,toString(){return`${s}m ${o}m ${l}m`}},normal:{x:u,y:c,z:a,toString(){return`${u}m ${c}m ${a}m`}}}}async loadModel(e){return this.loadModelWithLimits(e)}async loadModelWithLimits(e,r){if(!this.viewer){this.currentModel=e,this.currentModelLimits=r;return}try{let i;if(typeof e=="string"){this.isModelLoaded=!1,this.viewer?.clearScene?.();let l=await fetch(e);if(!l.ok)throw new Error(`Failed to load 3D model from "${e}": HTTP ${l.status}`);i=await l.arrayBuffer()}else i=e;let s=ge(i);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.updateHotspots();let o=this.getAttribute("selected-mesh");o&&this.viewer.setSelectedMesh(o),this.dispatchEvent(new CustomEvent("load",{bubbles:!0,composed:!0,detail:{model:s}}))}catch(i){throw this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),i}}showToast(e,r=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=e,this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")}):(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)"),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){if(this.activeXRSession&&typeof this.activeXRSession.isSessionActive=="function"&&this.activeXRSession.isSessionActive()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null),!this.currentModel){let i=new Error("No 3D model is loaded in <three-live>.");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}if(!V.arProvider){let i=new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR().");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}let e=this.getAttribute("ios-src"),r=(this.getAttribute("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"session-started"}}));let i=await V.arProvider.activateAR({model:e||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"not-presenting"}}))},onError:s=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:s}})),this.showToast(`AR error: ${s.message}`,6e3)}}});if(i.success)i.session&&(this.activeXRSession=i.session),i.mode==="quick-look"?this.showToast("Opening Apple AR Quick Look..."):i.mode==="scene-viewer"?this.showToast("Opening Google Scene Viewer..."):i.mode==="webxr"&&this.showToast("WebXR AR session started.");else{let s=typeof navigator<"u"&&navigator.userAgent||"",o=/Macintosh/i.test(s)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),l=/Android|iPhone|iPad|iPod/i.test(s);if(o&&!l&&typeof document<"u"&&this.currentModel&&V.arProvider.createUSDZBlob)try{let u=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:V.arProvider.createUSDZBlob(this.currentModel),c=URL.createObjectURL(u),a=document.createElement("a");a.href=c,a.download="three_live_model.usdz",document.body.appendChild(a),a.click(),document.body.removeChild(a),setTimeout(()=>URL.revokeObjectURL(c),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3)}else this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3);i.error&&this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i.error}}))}return i}catch(i){throw this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(`AR error: ${i.message||String(i)}`,6e3),i}}setupDOM(){let e=this.querySelector("canvas");e||(e=document.createElement("canvas"),e.style.width="100%",e.style.height="100%",e.style.display="block",e.style.touchAction=this.cameraControls?"none":"auto",e.style.outline="none",this.appendChild(e)),this.canvas=e;let r=this.getAttribute("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;let e=this.autoRotate,r=this.exposure,i=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttribute("max-camera-orbit")),o=this.parseCameraTarget(this.getAttribute("camera-target")),l=this.parseFieldOfView(this.getAttribute("field-of-view"));this.viewer=new j(this,this.canvas,{autoRotate:e,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttribute("rotation-per-second")),exposure:r,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,fieldOfView:l,cameraTarget:o,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:c=>{this.dispatchEvent(new CustomEvent("meshclick",{bubbles:!0,composed:!0,detail:c}))},onCameraChange:c=>{this.updateHotspots();for(let a of j.getRegisteredPlugins())a.onCameraChange?.(this.viewer,this);this.dispatchEvent(new CustomEvent("camera-change",{bubbles:!0,composed:!0,detail:c}))}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let u=this.getAttribute("camera-orbit");u&&this.applyCameraOrbit(u),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(e){if(!(typeof document>"u")){if(!e){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.setAttribute("alt","3D Scene Preview"),this.posterEl.style.position="absolute",this.posterEl.style.inset="0",this.posterEl.style.width="100%",this.posterEl.style.height="100%",this.posterEl.style.objectFit="cover",this.posterEl.style.transition="opacity 0.35s ease-out",this.posterEl.style.pointerEvents="none",this.posterEl.style.zIndex="1",this.appendChild(this.posterEl)),this.posterEl.src=e,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let e=document.createElement("button");e.setAttribute("type","button"),e.setAttribute("aria-label","View in Augmented Reality"),e.className="three-live-ar-button",e.setAttribute("part","default-ar-button");let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let s=document.createElementNS(r,"svg");s.setAttribute("width","20"),s.setAttribute("height","20"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","currentColor"),s.setAttribute("stroke-width","2"),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.style.marginRight="6px";let o=document.createElementNS(r,"path");o.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z");let l=document.createElementNS(r,"polyline");l.setAttribute("points","3.27 6.96 12 12.01 20.73 6.96");let u=document.createElementNS(r,"line");u.setAttribute("x1","12"),u.setAttribute("y1","22.08"),u.setAttribute("x2","12"),u.setAttribute("y2","12"),s.appendChild(o),s.appendChild(l),s.appendChild(u),e.appendChild(s)}let i=document.createElement("span");i.textContent="View in AR",e.appendChild(i),e.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",e.addEventListener("mouseenter",()=>{e.style.backgroundColor="rgba(30, 41, 59, 0.95)",e.style.transform="scale(1.04)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="rgba(15, 23, 42, 0.85)",e.style.transform="scale(1)"}),e.addEventListener("click",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=e,this.appendChild(e)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let e=this.hasAttribute("ar")&&!!V.arProvider,r=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;r?(this.arButton&&(this.arButton.style.display="none"),r.__tlARBound||(r.__tlARBound=!0,r.addEventListener("click",i=>{i.stopPropagation(),this.activateAR()})),r.dataset.tlOrigDisplay===void 0&&(r.dataset.tlOrigDisplay=r.style.display==="none"?"":r.style.display),r.style.display=e?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.arButton.style.display=e?"flex":"none")}applyCameraOrbit(e){if(!(!e||!this.viewer))try{let r=JSON.parse(e);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=e.trim().split(/\s+/);if(r.length>=2){let i=u=>u.endsWith("rad")?parseFloat(u)*180/Math.PI:parseFloat(u.replace(/deg$/,"")),s=r[0]==="auto"?void 0:i(r[0]),o=r[1]==="auto"?void 0:i(r[1]),l;r.length>=3&&r[2]!=="auto"&&(l=parseFloat(r[2].replace(/m$/,""))),(s!==void 0&&!isNaN(s)||o!==void 0&&!isNaN(o))&&this.viewer.setInitialCamera(s!==void 0&&!isNaN(s)?s:void 0,o!==void 0&&!isNaN(o)?o:void 0,l!==void 0&&!isNaN(l)?l:void 0)}}}parseOrbitLimit(e){if(!e)return{};let r=e.trim().split(/\s+/),i={};if(r.length>0&&r[0]!=="auto"){let s=r[0].endsWith("rad")?parseFloat(r[0])*180/Math.PI:parseFloat(r[0].replace(/deg$/,""));isNaN(s)||(i.theta=s)}if(r.length>1&&r[1]!=="auto"){let s=r[1].endsWith("rad")?parseFloat(r[1])*180/Math.PI:parseFloat(r[1].replace(/deg$/,""));isNaN(s)||(i.phi=s)}if(r.length>2&&r[2]!=="auto"){let s=parseFloat(r[2].replace(/m$/,""));isNaN(s)||(i.distance=s)}return i}applyOrbitLimits(){if(!this.viewer)return;let e=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttribute("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:e.theta,maxTheta:r.theta,minPhi:e.phi,maxPhi:r.phi,minDistance:e.distance,maxDistance:r.distance})}parseCameraTarget(e){if(!e)return;let r=e.trim().split(/\s+/).map(i=>parseFloat(i.replace(/m$/,"")));return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(e){if(!e)return;let r=e.endsWith("rad")?parseFloat(e)*180/Math.PI:parseFloat(e.replace(/deg$/,""));return isNaN(r)?void 0:r}parseRotationPerSecond(e){if(!e)return Math.PI/6;let r=e.trim(),i=parseFloat(r);return isNaN(i)?Math.PI/6:r.endsWith("rad")?i:r.endsWith("%")?i/100*Math.PI*2:i*Math.PI/180}applyCameraTarget(e){let r=this.parseCameraTarget(e);this.viewer&&r&&this.viewer.setTarget(r[0],r[1],r[2])}applyFieldOfView(e){let r=this.parseFieldOfView(e);this.viewer&&r!==void 0&&this.viewer.setFieldOfView(r)}updateHotspot(e){let r=this.querySelector(`[slot="${e.name}"]`);r&&(e.position!==void 0&&r.setAttribute("data-position",e.position),e.normal!==void 0&&r.setAttribute("data-normal",e.normal)),this.updateHotspots()}updateHotspots(){for(let e of j.getRegisteredPlugins())if(e.updateHotspotsForElement){e.updateHotspotsForElement(this,this.viewer);return}}async loadModelFromSrc(e){await this.loadModel(e)}runWithScriptRunner(e){let r=V.scriptRunner;if(!r){let i=new Error('Procedural script execution requires "three-live/full" or ThreeLiveElement.registerScriptRunner().');return this.showToast(i.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),Promise.reject(i)}return this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.isModelLoaded=!1,this.viewer?.clearScene?.(),new Promise((i,s)=>{let o=!1;e(r,{onModelReady:u=>{this.loadModelWithLimits(u,Ge).then(()=>{o||(o=!0,i(u))},c=>{let a=c instanceof Error?c.message:String(c);this.showToast(a),o||(o=!0,s(c))})},onUpdateTransforms:u=>this.viewer?.updateMeshTransforms(u),onError:u=>{this.showToast(u.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:u}})),o||(o=!0,s(u))},onToast:u=>this.showToast(u)}).then(u=>{u&&(this.scriptHandle=u)},u=>{u instanceof Error&&u.message&&this.showToast(u.message),o||(o=!0,s(u))})})}loadScriptFromSrc(e){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(s),Promise.reject(s)}return r.executeUrl(e,this.sandbox,i)})}executeScript(e){if(!V.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(_e);return this.showToast(He),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:r}})),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(e,this.sandbox,i,{allowClientScripts:!0}))}};V.observedAttributes=["src","ios-src","script-src","sandbox","allow-client-scripts","poster","camera-controls","camera-orbit","camera-target","min-camera-orbit","max-camera-orbit","field-of-view","selected-mesh","ar","ar-modes","ar-scale","ar-placement","exposure","shadow-intensity","shadow-softness","tone-mapping","environment-image","skybox-image","autoplay","animation-name","auto-rotate","auto-rotate-delay","rotation-per-second"],V.registerPlugin=j.registerPlugin,V.getRegisteredPlugins=j.getRegisteredPlugins;var xe=V;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",xe);
|
|
232
|
+
void main(){fragColor=uColorId;}`;function Ue(n,t,e){let r=n.createShader(t);if(n.shaderSource(r,e),n.compileShader(r),!n.getShaderParameter(r,35713)){let i=n.getShaderInfoLog(r);throw n.deleteShader(r),new Error(`Shader compile error: ${i}`)}return r}function De(n,t,e){let r=Ue(n,35633,t),i=Ue(n,35632,e),s=n.createProgram();if(n.attachShader(s,r),n.attachShader(s,i),n.linkProgram(s),!n.getProgramParameter(s,35714)){let a=n.getProgramInfoLog(s);throw n.deleteProgram(s),new Error(`Program link error: ${a}`)}return s}function Le(n,t,e){let r={};for(let i of e)r[i]=n.getUniformLocation(t,i);return r}var Ve=["uMVP","uModel","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uEnvIntensity","uViewportSize","uSectionPlane","uSectionEnabled"];function je(){let n=K().xrDepthShader;return{fs:mt.replace("/*XRD_U*/",n?.uniformsGLSL||"").replace("/*XRD_O*/",n?.occlusionGLSL||""),uniforms:n?[...Ve,...n.uniformNames]:Ve}}function ft(n){if(typeof n!="string")return null;let t=n.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let e=t.toLowerCase();return e.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:e.startsWith("https://")||e.startsWith("blob:")?t:e.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function Ce(n,t,e,r,i,s,a){if(r===void 0||!t.accessors?.[r])return null;let l=t.accessors[r],o=t.bufferViews[l.bufferView],c=(o.byteOffset||0)+(l.byteOffset||0),u=o.byteStride&&o.byteStride>s*4?o.byteStride>>2:s,h;if(u===s)h=new Float32Array(e,c,l.count*s);else{h=new Float32Array(l.count*s);let y=new Float32Array(e,o.byteOffset||0,Math.floor(o.byteLength/4)),d=(l.byteOffset||0)>>2;for(let b=0;b<l.count;b++){let g=d+b*u;for(let w=0;w<s;w++)h[b*s+w]=y[g+w]}}let x=n.createBuffer();return a.push(x),n.bindBuffer(34962,x),n.bufferData(34962,h,35044),n.enableVertexAttribArray(i),n.vertexAttribPointer(i,s,5126,!1,0,0),h}var Ye=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),$e=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function He(n,t,e=$e,r){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:i}=t,s=de("meshopt");s?.decodeBufferViews&&s.decodeBufferViews(i,t);let a=t.bin,l=[],o=[],c=i.extensions?.KHR_materials_variants;if(c&&Array.isArray(c.variants))for(let E of c.variants)E&&typeof E.name=="string"&&o.push(E.name);let u=Oe(i),h=[];if(Array.isArray(i.nodes))for(let E=0;E<i.nodes.length;E++){let A=i.nodes[E];A.mesh!==void 0&&i.meshes&&i.meshes[A.mesh]&&h.push({node:A,nodeIdx:E,meshIdx:A.mesh})}let x=h.length>0?h:(i.meshes||[]).map((E,A)=>({node:E,nodeIdx:-1,meshIdx:A})),y=[];if(Array.isArray(t.lights)&&t.lights.length>0)y.push(...t.lights);else if(i.extensions?.KHR_lights_punctual?.lights){let E=i.extensions.KHR_lights_punctual.lights;for(let A of E){let p=A.type==="directional"?"directional":A.type==="point"?"point":"ambient";y.push({type:p,color:A.color||[1,1,1],intensity:A.intensity!==void 0?A.intensity:1})}}if(y.length===0&&(y.push({type:"ambient",color:[1,1,1],intensity:.35}),y.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),x.length>e.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${e.maxMeshes}). Found: ${x.length}`);let d=[];if(i.textures&&i.images){if(i.textures.length>e.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${e.maxTextures}). Found: ${i.textures.length}`);for(let E=0;E<i.textures.length;E++){let A=i.textures[E],p=i.images[A.source];if(p){let R=n.createTexture();if(n.bindTexture(3553,R),n.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),n.texParameteri(3553,10242,10497),n.texParameteri(3553,10243,10497),n.texParameteri(3553,10241,9729),n.texParameteri(3553,10240,9729),p.bufferView!==void 0){let D=i.bufferViews[p.bufferView],f=a.slice(D.byteOffset||0,(D.byteOffset||0)+D.byteLength),_=new Blob([f],{type:p.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(_).then(P=>{n.bindTexture(3553,R),n.texImage2D(3553,0,6408,6408,5121,P),n.generateMipmap(3553),r?.()}).catch(()=>{})}else if(p.uri){let D=ft(p.uri);if(D){let f=new Image;f.crossOrigin="anonymous",f.referrerPolicy="no-referrer",f.onload=()=>{n.bindTexture(3553,R),n.texImage2D(3553,0,6408,6408,5121,f),n.generateMipmap(3553),r?.()},f.src=D}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",p.uri)}d.push(R)}else d.push(null)}}let b=[1/0,1/0,1/0],g=[-1/0,-1/0,-1/0],w=0,S=0;for(let E=0;E<x.length;E++){let A=x[E],p=i.meshes[A.meshIdx],R=A.nodeIdx>=0?u[A.nodeIdx]:W(),D=new Float32Array(9);ce(D,R);let f={name:A.node.name||p.name||`Mesh_${A.meshIdx}`,nodeIndex:A.nodeIdx,transform:R,normalMatrix:D,primitives:[],extras:A.node.extras||p.extras},_=A.node?.extensions?.EXT_mesh_gpu_instancing;if(_&&_.attributes&&typeof _.attributes=="object"){let P=_.attributes,j=P.TRANSLATION!==void 0?i.accessors?.[P.TRANSLATION]:null,V=P.ROTATION!==void 0?i.accessors?.[P.ROTATION]:null,Y=P.SCALE!==void 0?i.accessors?.[P.SCALE]:null,B=P._COLOR_0!==void 0?i.accessors?.[P._COLOR_0]:null,O=Number(j?.count??V?.count??Y?.count??0);if(!Number.isFinite(O)||O<0||O>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${O}`);if(O>0){let X=(L,q)=>{if(!L||L.bufferView===void 0||!i.bufferViews?.[L.bufferView])return null;let H=(i.bufferViews[L.bufferView].byteOffset||0)+(L.byteOffset||0);return ct(a,H,O*q)},ie=X(j,3),U=X(V,4),N=X(Y,3),z=B?.type==="VEC4"?4:3,$=X(B,z),ne=new Float32Array(O*16),se=W();for(let L=0;L<O;L++){let q=ie?[ie[L*3],ie[L*3+1],ie[L*3+2]]:[0,0,0],he=U?[U[L*4],U[L*4+1],U[L*4+2],U[L*4+3]]:[0,0,0,1],H=N?[N[L*3],N[L*3+1],N[L*3+2]]:[1,1,1];Pe(se,he,q,H),ne.set(se,L*16)}if(f.instanceMatrices=ne,$){let L=new Float32Array(O*3);for(let q=0;q<O;q++)L[q*3]=$[q*z],L[q*3+1]=$[q*z+1],L[q*3+2]=$[q*z+2];f.instanceColors=L}}}for(let P of p.primitives||[]){if(P.extensions?.KHR_draco_mesh_compression){let G=de("draco");G&&G.decodePrimitive(i,P,a)}let j=[],V=n.createVertexArray();n.bindVertexArray(V);let Y=i.accessors[P.attributes.POSITION],B=Number(Y?.count??0);if(!Number.isFinite(B)||B<0||w+B>e.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${e.maxVertices}).`);if(w+=B,Y?.min&&Y?.max){let G=ee=>{for(let te=0;te<3;te++){let ae=ee[12+te],ve=ee[12+te];for(let me=0;me<3;me++){let xe=ee[me*4+te]*Y.min[me],ye=ee[me*4+te]*Y.max[me];ae+=xe<ye?xe:ye,ve+=xe>ye?xe:ye}ae<b[te]&&(b[te]=ae),ve>g[te]&&(g[te]=ve)}};if(f.instanceMatrices&&f.instanceMatrices.length>=16){let ee=f.instanceMatrices.length>>4,te=W();for(let ae=0;ae<ee;ae++){let ve=f.instanceMatrices.subarray(ae*16,ae*16+16);Q(te,R,ve),G(te)}}else G(R)}let O=Ce(n,i,a,P.attributes.POSITION,0,3,j);Ce(n,i,a,P.attributes.NORMAL,1,3,j),Ce(n,i,a,P.attributes.TEXCOORD_0,2,2,j);let X=0,ie=5123,U=null;if(P.indices!==void 0){let G=i.accessors[P.indices],te=(i.bufferViews[G.bufferView].byteOffset||0)+(G.byteOffset||0);if(X=Number(G.count??0),!Number.isFinite(X)||X<0||S+X>e.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${e.maxIndices}).`);S+=X,ie=G.componentType===5125?5125||5125:5123||5123;let ae=n.createBuffer();j.push(ae),n.bindBuffer(34963,ae),G.componentType===5125?(U=new Uint32Array(a,te,G.count),n.bufferData(34963,U,35044)):(U=new Uint16Array(a,te,G.count),n.bufferData(34963,U,35044))}else X=Y.count;let N={};for(let G of Z)if(G.onBuildPrimitiveVAO){let ee=G.onBuildPrimitiveVAO(n,V,P,i,a);ee&&(N[G.name]=ee)}n.bindVertexArray(null);let z=i.materials&&P.material!==void 0?i.materials[P.material]:null,$=je(),ne=ze,se=$.fs,L=!1;for(let G of Z)if(G.onResolveShader){let ee=G.onResolveShader(P,z,ne,se);ee&&(ne=ee.vs,se=ee.fs,L=!0)}let q=L?De(n,ne,se):null,he=q?Le(n,q,$.uniforms):null,H=z?.pbrMetallicRoughness,pe=H?.baseColorFactor||[.8,.8,.8,1],fe=H?.metallicFactor??.1,be=H?.roughnessFactor??.5,oe=z?.extensions?.KHR_materials_clearcoat,ue=oe?oe.clearcoatFactor??1:0,le=Math.max(.04,oe?.clearcoatRoughnessFactor??.04),ge=H?.baseColorTexture!==void 0&&d[H.baseColorTexture.index]?d[H.baseColorTexture.index]:null,qe=H?.metallicRoughnessTexture!==void 0&&d[H.metallicRoughnessTexture.index]?d[H.metallicRoughnessTexture.index]:null,Ke=z?.normalTexture!==void 0&&d[z.normalTexture.index]?d[z.normalTexture.index]:null,Ze=z?.normalTexture?.scale??1,Je=z?.occlusionTexture!==void 0&&d[z.occlusionTexture.index]?d[z.occlusionTexture.index]:null,Qe=z?.occlusionTexture?.strength??1,et=!!(z?.extensions?.KHR_materials_transmission||N.materials?.isTransmissive),Fe=P.extensions?.KHR_materials_variants?.mappings,tt=Array.isArray(Fe)?Fe.filter(G=>G&&typeof G.material=="number"&&Array.isArray(G.variants)).map(G=>({material:G.material|0,variants:G.variants.map(ee=>Number(ee)|0)})):void 0;f.primitives.push({vao:V,indexCount:X,indexType:ie,baseColor:pe,metallic:fe,roughness:be,clearcoat:ue,clearcoatRoughness:le,positions:O,indices:U,texture:ge,metallicRoughnessTexture:qe,normalTexture:Ke,occlusionTexture:Je,normalScale:Ze,occlusionStrength:Qe,buffers:j,materialIndex:P.material,defaultMaterialIndex:P.material,variantMappings:tt,pluginData:N,customProgram:q,customUniforms:he,isTransmissive:et})}l.push(f)}isFinite(b[0])||(b=[-1,-1,-1]),isFinite(g[0])||(g=[1,1,1]);let T=[(b[0]+g[0])/2,(b[1]+g[1])/2,(b[2]+g[2])/2],M=g[0]-b[0],v=g[1]-b[1],m=g[2]-b[2],I=Math.max(Math.hypot(M,v,m)/2,.5),k=[b[0],b[1],b[2]],C=[g[0],g[1],g[2]],F=t.animations;if(!F){for(let E of Z)if(E.onParseGLB?.(t),t.animations){F=t.animations;break}}return F||(F=[]),{meshes:l,bounds:{center:T,radius:I,min:k,max:C},lights:y,animations:F,worldMatrices:u,gpuTextures:d,availableVariants:o}}var re=class{constructor(t,e,r){this.meshes=[];this.backdropMeshes=[];this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]};this.lights=[];this.modelRootMatrix=W();this.clearColor=[0,0,0,0];this.envIntensity=1;this.shadowIntensity=0;this.shadowSoftness=.5;this.toneMapping="neutral";this.environmentTexture=null;this.animations=[];this.currentClip=null;this.animationTime=0;this.isPlayingAnimation=!1;this.autoplay=!1;this.animationName="";this.gpuTextures=[];this.availableVariants=[];this.activeVariantName=null;this.gltf=null;this.worldMatrices=[];this.initialNodeTransforms=[];this.projMatrix=W();this.viewMatrix=W();this.modelMatrix=W();this.mvpMatrix=W();this.normalMatrix=new Float32Array(9);this.initialTheta=.6;this.initialPhi=.35;this.initialDistance=null;this.customDistance=!1;this.distanceMode="auto";this.initialCustomTarget=null;this.customTarget=null;this.fov=Math.PI/4;this.minTheta=-1/0;this.maxTheta=1/0;this.minPhi=-Math.PI*.48;this.maxPhi=Math.PI*.48;this.minDistanceLimit=null;this.maxDistanceLimit=null;this.activePointers=new Map;this.isPanning=!1;this.targetTheta=.6;this.currTheta=.6;this.targetPhi=.35;this.currPhi=.35;this.targetDistance=3;this.currDistance=3;this.autoRotate=!1;this.autoRotateSpeed=Math.PI/6;this.autoRotateDelay=3e3;this.lastInteractionTime=-1/0;this.turntableRotation=0;this.isPointerDown=!1;this.interactive=!0;this.skyboxTexture=null;this.lastPointerX=0;this.lastPointerY=0;this.totalDragDist=0;this.selectedMeshName="";this.pickFbo=null;this.pickTexture=null;this.pickDepth=null;this.pickFboWidth=0;this.pickFboHeight=0;this.animFrameId=null;this.isVisible=!0;this.xrSessionActive=!1;this.lastTime=0;this.lastReportedTheta=-999;this.lastReportedPhi=-999;this.lastReportedZoom=-999;this.boundPointerDown=null;this.boundPointerMove=null;this.boundPointerUp=null;this.boundWheel=null;this.boundKeyDown=null;this.boundContextMenu=null;this.boundSetCamera=null;this.boundResetCamera=null;this.stereoSBS=!1;this.renderErrorReported=!1;this.xrDepthState={enabled:!1,texture:null,uvTransform:W(),rawValueToMeters:.001,format:0};this.container=t;let i,s;if(e&&typeof e.getContext=="function"?(i=e,s=r):(s=e,i=s?.canvas),!i){let c=t.querySelector("canvas");c||(c=document.createElement("canvas"),c.style.width="100%",c.style.height="100%",c.style.display="block",c.style.touchAction="none",t.prepend(c)),i=c}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!a:a&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.envIntensity=Math.max(0,Number(this.opts.exposure))),this.opts.camera&&this.setInitialCamera(this.opts.camera.theta,this.opts.camera.phi,this.opts.camera.distance,this.opts.camera.zoom),this.opts.shadowIntensity!==void 0&&(this.shadowIntensity=Math.max(0,Math.min(1,Number(this.opts.shadowIntensity)||0))),this.opts.shadowSoftness!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(this.opts.shadowSoftness)||0))),this.opts.toneMapping!==void 0&&(this.toneMapping=this.opts.toneMapping),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let l=i.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!l)throw new Error("WebGL2 not supported");this.gl=l;let o=je();this.renderProg=De(l,ze,o.fs),this.pickProg=De(l,dt,pt),this.uRender=Le(l,this.renderProg,o.uniforms),this.uPick=Le(l,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo(),this.setupEvents(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(t,e){lt(t,e)}static getDecoder(t){return de(t)}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),r=Math.max(1,this.canvas.height);this.pickFboWidth=e,this.pickFboHeight=r,t.bindTexture(3553,this.pickTexture),t.texImage2D(3553,0,6408,e,r,0,6408,5121,null),t.texParameteri(3553,10241,9728),t.texParameteri(3553,10240,9728),t.bindRenderbuffer(36161,this.pickDepth),t.renderbufferStorage(36161,33189,e,r),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 r=this.gl,i=Math.max(1,t),s=Math.max(1,e);this.pickFboWidth=i,this.pickFboHeight=s,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,s,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,s)}loadGLBData(t,e){let{meshes:r,bounds:i,lights:s,animations:a,worldMatrices:l,gpuTextures:o,availableVariants:c}=He(this.gl,t,e,()=>this.render());if(this.disposeMeshGpuResources(),this.meshes=r,this.bounds=i,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=a||[],this.worldMatrices=l||[],this.gpuTextures=o||[],this.availableVariants=c||[],this.gltf=t.gltf,this.activeVariantName&&this.applyVariantMaterial(this.activeVariantName),this.initialNodeTransforms=[],Array.isArray(t.gltf?.nodes))for(let h of t.gltf.nodes)this.initialNodeTransforms.push({t:h.translation?[h.translation[0],h.translation[1],h.translation[2]]:[0,0,0],r:h.rotation?[h.rotation[0],h.rotation[1],h.rotation[2],h.rotation[3]]:[0,0,0,1],s:h.scale?[h.scale[0],h.scale[1],h.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let h of Z)h.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:i.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let u=t.exposure??t.environmentIntensity??t.gltf?.extras?.exposure??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.exposure??t.gltf?.asset?.extras?.environmentIntensity;u!==void 0&&(this.envIntensity=Math.max(0,Number(u))),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(t){this.loadGLBData(Xe(t))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(t){this.loadGLBData(Re(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let r=Re(t),{meshes:i}=He(this.gl,r,$e,()=>this.render());if(e)for(let s of i)s.transform[12]+=e[0],s.transform[13]+=e[1],s.transform[14]+=e[2],ce(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(t,e,r,i=1){this.clearColor=[t,e,r,i]}updateMeshTransforms(t){for(let e=0;e<this.meshes.length;e++){let r=this.meshes[e],i;t instanceof Map?i=t.get(r.name)??t.get(e):Array.isArray(t)?i=t[e]:t&&typeof t=="object"&&(Object.prototype.hasOwnProperty.call(t,r.name)?i=t[r.name]:Object.prototype.hasOwnProperty.call(t,e)&&(i=t[e])),i&&i.length===16&&(r.transform.set(i),ce(r.normalMatrix,r.transform))}}bindLights(t=this.uRender){let e=this.gl,r=[.28,.28,.28],i=[],s=[],a=[],l=[];for(let o of this.lights){let c=o.color||[1,1,1],u=o.intensity!==void 0?o.intensity:1;if(o.type==="ambient")r=[c[0]*u,c[1]*u,c[2]*u];else if(o.type==="directional"&&i.length<6){let h=o.direction||[.5,1,.8];i.push(h[0],h[1],h[2]),s.push(c[0]*u,c[1]*u,c[2]*u)}else if(o.type==="point"&&a.length<6){let h=o.position||[0,0,0];a.push(h[0],h[1],h[2]),l.push(c[0]*u,c[1]*u,c[2]*u)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),e.uniform3fv(t.uAmbientColor,r),e.uniform1i(t.uNumDirLights,i.length/3),i.length>0&&(e.uniform3fv(t.uDirLightDir,i),e.uniform3fv(t.uDirLightColor,s)),e.uniform1i(t.uNumPointLights,a.length/3),a.length>0&&(e.uniform3fv(t.uPointLightPos,a),e.uniform3fv(t.uPointLightColor,l)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.envIntensity=Math.max(0,Number(t))}getExposure(){return this.envIntensity}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=t}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of Z)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of Z)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,r=this.currDistance;return{theta:t,phi:e,radius:r,toString(){return`${t.toFixed(4)}rad ${e.toFixed(4)}rad ${r.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,r)=>{let i=this.meshes.flatMap(u=>u.primitives.filter(h=>h.materialIndex===r||t.length===1&&h.materialIndex===void 0)),s=i[0],a=s?[...s.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=s?s.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,o=s?s.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,c={baseColorFactor:a,metallicFactor:l,roughnessFactor:o,setBaseColorFactor:u=>{let h=[u[0],u[1],u[2],u[3]??1];c.baseColorFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=h);for(let x of i)x.baseColor=h;this.render()},setMetallicFactor:u=>{c.metallicFactor=u,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=u);for(let h of i)h.metallic=u;this.render()},setRoughnessFactor:u=>{c.roughnessFactor=u,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=u);for(let h of i)h.roughness=u;this.render()}};return{name:e.name||`Material_${r}`,pbrMetallicRoughness:c}})}playAnimation(t){if(this.animations.length!==0){if(t){let e=this.animations.find(r=>r.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===""||t==="default",r=-1;if(e)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(t),r<0)return!1;this.activeVariantName=t}let i=this.gltf?.materials;if(!Array.isArray(i))return e;for(let s of this.meshes)for(let a of s.primitives){let l=a.defaultMaterialIndex;if(!e&&Array.isArray(a.variantMappings)){for(let h of a.variantMappings)if(Array.isArray(h.variants)&&h.variants.includes(r)){l=h.material;break}}if(l===void 0||!i[l]){a.materialIndex=void 0,a.baseColor=[.8,.8,.8,1],a.metallic=.1,a.roughness=.5,a.clearcoat=0,a.clearcoatRoughness=.04,a.texture=null,a.metallicRoughnessTexture=null,a.normalTexture=null,a.normalScale=1,a.occlusionTexture=null,a.occlusionStrength=1,a.isTransmissive=!1;continue}let o=i[l];a.materialIndex=l;let c=o.pbrMetallicRoughness;a.baseColor=c?.baseColorFactor?[c.baseColorFactor[0],c.baseColorFactor[1],c.baseColorFactor[2],c.baseColorFactor[3]??1]:[.8,.8,.8,1],a.metallic=c?.metallicFactor??.1,a.roughness=c?.roughnessFactor??.5;let u=o.extensions?.KHR_materials_clearcoat;a.clearcoat=u?u.clearcoatFactor??1:0,a.clearcoatRoughness=Math.max(.04,u?.clearcoatRoughnessFactor??.04),a.texture=c?.baseColorTexture!==void 0&&this.gpuTextures[c.baseColorTexture.index]?this.gpuTextures[c.baseColorTexture.index]:null,a.metallicRoughnessTexture=c?.metallicRoughnessTexture!==void 0&&this.gpuTextures[c.metallicRoughnessTexture.index]?this.gpuTextures[c.metallicRoughnessTexture.index]:null,a.normalTexture=o.normalTexture!==void 0&&this.gpuTextures[o.normalTexture.index]?this.gpuTextures[o.normalTexture.index]:null,a.normalScale=o.normalTexture?.scale??1,a.occlusionTexture=o.occlusionTexture!==void 0&&this.gpuTextures[o.occlusionTexture.index]?this.gpuTextures[o.occlusionTexture.index]:null,a.occlusionStrength=o.occlusionTexture?.strength??1,a.isTransmissive=!!(o.extensions?.KHR_materials_transmission||a.pluginData?.materials?.isTransmissive)}return!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 Z)if(e.evaluateAnimation){e.evaluateAnimation(this,t);return}}setTarget(t,e,r){this.customTarget=[t,e,r],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,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(e,Math.min(r,t))}setCamera(t,e,r,i){t!==void 0&&(this.targetTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.targetPhi=this.clampPhi(e*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(t,e,r,i){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),r!==void 0&&r>0){let s=this.clampDistance(r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(i!==void 0&&i>0){let s=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(t,e){let r=W();Q(r,this.projMatrix,this.viewMatrix);let[i,s,a]=t,l=e?e[0]:0,o=e?e[1]:0,c=e?e[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*t[0]+u[4]*t[1]+u[8]*t[2]+u[12],s=u[1]*t[0]+u[5]*t[1]+u[9]*t[2]+u[13],a=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]+u[14],e&&(l=u[0]*e[0]+u[4]*e[1]+u[8]*e[2],o=u[1]*e[0]+u[5]*e[1]+u[9]*e[2],c=u[2]*e[0]+u[6]*e[1]+u[10]*e[2]));let h=r[0]*i+r[4]*s+r[8]*a+r[12],x=r[1]*i+r[5]*s+r[9]*a+r[13],y=r[2]*i+r[6]*s+r[10]*a+r[14],d=r[3]*i+r[7]*s+r[11]*a+r[15];if(d<=1e-4)return{x:0,y:0,z:1,visible:!1};let b=h/d,g=x/d,w=y/d,S=this.canvas.getBoundingClientRect(),T=S.width||this.canvas.clientWidth||this.canvas.width||300,M=S.height||this.canvas.clientHeight||this.canvas.height||150,v=(b*.5+.5)*T,m=(-g*.5+.5)*M,I=b>=-1.1&&b<=1.1&&g>=-1.1&&g<=1.1&&w>=-1&&w<=1;if(I&&e){let k=this.customTarget||this.bounds.center,C=k[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),F=k[1]+this.currDistance*Math.sin(this.currPhi),E=k[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),A=[i-C,s-F,a-E];l*A[0]+o*A[1]+c*A[2]>.05&&(I=!1)}return{x:v,y:m,z:w,visible:I}}setSelectedMesh(t){this.selectedMeshName=t||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let t=this.canvas;this.boundContextMenu=e=>{e.preventDefault()},t.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=e=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.totalDragDist=0,this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.isPanning=e.button===2||e.shiftKey||this.activePointers.size===2,t.setPointerCapture(e.pointerId))},t.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=e=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=this.activePointers.get(e.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},i=e.clientX-r.x,s=e.clientY-r.y;if(this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.totalDragDist+=Math.hypot(i,s),this.isPanning||e.button===2||e.shiftKey||this.activePointers.size===2){let a=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],l=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],o=this.customTarget?[...this.customTarget]:[...this.bounds.center],c=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;o[0]+=(-i*a[0]+s*l[0])*c,o[1]+=(-i*a[1]+s*l[1])*c,o[2]+=(-i*a[2]+s*l[2])*c,this.customTarget=o}else this.targetTheta=this.clampTheta(this.targetTheta-i*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},t.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=e=>{this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now(),this.activePointers.delete(e.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{t.releasePointerCapture(e.pointerId)}catch{}if(this.totalDragDist<5&&e.button===0){let r=t.getBoundingClientRect(),i=Math.floor((e.clientX-r.left)*(t.width/Math.max(r.width,1))),s=Math.floor((e.clientY-r.top)*(t.height/Math.max(r.height,1)));this.performMeshPick(i,s,!0)}},t.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=e=>{if(!this.interactive)return;e.preventDefault(),this.lastInteractionTime=typeof performance<"u"?performance.now():Date.now();let r=Math.exp(e.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},t.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=e=>{let r=e.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),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=e=>{if(!this.interactive)return;let r=typeof performance<"u"?performance.now():Date.now();switch(e.key){case"ArrowLeft":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta-.1),e.preventDefault();break;case"ArrowRight":this.lastInteractionTime=r,this.targetTheta=this.clampTheta(this.targetTheta+.1),e.preventDefault();break;case"ArrowUp":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi+.08),e.preventDefault();break;case"ArrowDown":this.lastInteractionTime=r,this.targetPhi=this.clampPhi(this.targetPhi-.08),e.preventDefault();break;case"+":case"=":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*.9),e.preventDefault();break}case"-":case"_":{this.lastInteractionTime=r,this.targetDistance=this.clampDistance(this.targetDistance*1.1),e.preventDefault();break}case"Home":this.lastInteractionTime=r,this.resetCamera(),e.preventDefault();break}},t.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let t=this.canvas;this.boundContextMenu&&(t.removeEventListener("contextmenu",this.boundContextMenu),this.boundContextMenu=null),this.boundPointerDown&&(t.removeEventListener("pointerdown",this.boundPointerDown),this.boundPointerDown=null),this.boundPointerMove&&(t.removeEventListener("pointermove",this.boundPointerMove),this.boundPointerMove=null),this.boundPointerUp&&(t.removeEventListener("pointerup",this.boundPointerUp),this.boundPointerUp=null),this.boundWheel&&(t.removeEventListener("wheel",this.boundWheel),this.boundWheel=null),this.boundKeyDown&&(t.removeEventListener("keydown",this.boundKeyDown),this.boundKeyDown=null),this.boundSetCamera&&(this.container.removeEventListener("setCamera",this.boundSetCamera),this.boundSetCamera=null),this.boundResetCamera&&(this.container.removeEventListener("resetCamera",this.boundResetCamera),this.boundResetCamera=null)}raycastFromScreenPoint(t,e){let r=this.canvas,i=r.getBoundingClientRect(),s=r.width||300,a=r.height||300,l=i.width>0?Math.floor((t-i.left)*(s/i.width)):Math.floor(t),o=i.height>0?Math.floor((e-i.top)*(a/i.height)):Math.floor(e);return this.performMeshPick(l,o,!1)}performMeshPick(t,e,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);t=this.mapStereoPickX(t,s);let l=W();Q(l,this.projMatrix,this.viewMatrix);let o=[],c=Math.max(0,Math.min(s-1,t)),u=Math.max(0,Math.min(a-1,a-1-e));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==a)&&this.resizePickingFbo(s,a),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,a),i.enable(2929),i.clearColor(0,0,0,0),i.clear(16384|256),i.useProgram(this.pickProg);for(let k=0;k<this.meshes.length;k++){let C=this.meshes[k];if(C.visible===!1||C.isPluginMesh)continue;let F=k+1,E=(F&255)/255,A=(F>>8&255)/255,p=(F>>16&255)/255;i.uniform4f(this.uPick.uColorId,E,A,p,1),Q(this.modelMatrix,this.modelRootMatrix,C.transform);let R=C.instanceMatrices;if(R&&R.length>=16){let D=R.length>>4,f=W();for(let _ of C.primitives){i.bindVertexArray(_.vao);for(let P=0;P<D;P++)Q(f,this.modelMatrix,R.subarray(P*16,P*16+16)),Q(this.mvpMatrix,l,f),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),_.indices?i.drawElements(4,_.indexCount,_.indexType,0):i.drawArrays(4,0,_.indexCount)}}else{Q(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let D of C.primitives)i.bindVertexArray(D.vao),D.indices?i.drawElements(4,D.indexCount,D.indexType,0):i.drawArrays(4,0,D.indexCount)}}let m=new Uint8Array(4);i.readPixels(c,u,1,1,6408,5121,m),i.bindFramebuffer(36160,null);let I=m[0]+(m[1]<<8)+(m[2]<<16);I>0&&I<=this.meshes.length&&(o=[this.meshes[I-1]])}o.length===0&&(o=this.meshes.filter(m=>m.visible!==!1));let h=null,x=1/0,y=[0,0,0],d=[0,1,0],b=this.customTarget||this.bounds.center,g=b[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),w=b[1]+this.currDistance*Math.sin(this.currPhi),S=b[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),T=W();for(let m of o){Q(T,this.modelRootMatrix,m.transform);let I=m.instanceMatrices,k=I&&I.length>=16?I.length>>4:1;for(let C=0;C<k;C++){I&&I.length>=16?Q(this.modelMatrix,T,I.subarray(C*16,C*16+16)):this.modelMatrix.set(T),Q(this.mvpMatrix,l,this.modelMatrix);let F=W();if(!Ge(F,this.mvpMatrix))continue;let E=(c+.5)/s*2-1,A=(u+.5)/a*2-1,p=[0,0,0],R=[0,0,0];Se(p,E,A,-1,F),Se(R,E,A,1,F);let D=R[0]-p[0],f=R[1]-p[1],_=R[2]-p[2],P=Math.hypot(D,f,_)||1,j=D/P,V=f/P,Y=_/P,B={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((X=>{for(let ie of m.primitives){if(!ie.positions)continue;let U=ie.positions,N=ie.indices,z=Math.floor(N?N.length/3:U.length/9);for(let $=0;$<z;$++){let ne=N?N[$*3]:$*3,se=N?N[$*3+1]:$*3+1,L=N?N[$*3+2]:$*3+2;_e(p[0],p[1],p[2],j,V,Y,U[ne*3],U[ne*3+1],U[ne*3+2],U[se*3],U[se*3+1],U[se*3+2],U[L*3],U[L*3+1],U[L*3+2],B,X)}}})(1e-4),isFinite(B.distance)){let X=B.point[0],ie=B.point[1],U=B.point[2],N=this.modelMatrix,z=N[0]*X+N[4]*ie+N[8]*U+N[12],$=N[1]*X+N[5]*ie+N[9]*U+N[13],ne=N[2]*X+N[6]*ie+N[10]*U+N[14],se=z-g,L=$-w,q=ne-S,he=Math.hypot(se,L,q);if(he<x){ce(this.normalMatrix,this.modelMatrix);let H=this.normalMatrix,pe=B.normal[0],fe=B.normal[1],be=B.normal[2],oe=H[0]*pe+H[3]*fe+H[6]*be,ue=H[1]*pe+H[4]*fe+H[7]*be,le=H[2]*pe+H[5]*fe+H[8]*be,ge=Math.hypot(oe,ue,le)||1;oe/=ge,ue/=ge,le/=ge,oe*se+ue*L+le*q>0&&(oe=-oe,ue=-ue,le=-le),h=m,x=Math.round(he*1e3)/1e3,y=[Math.round(z*1e3)/1e3,Math.round($*1e3)/1e3,Math.round(ne*1e3)/1e3],d=[Math.round(oe*1e3)/1e3,Math.round(ue*1e3)/1e3,Math.round(le*1e3)/1e3]}}}}if(!h)return null;let v={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:x,hitPoint:y,normal:d,screenX:t,screenY:e};if(r){for(let m of Z)m.onMeshSelect?.(this,v);this.opts.onMeshClick&&this.opts.onMeshClick(v),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:v}))}return v}mapStereoPickX(t,e){if(!this.stereoSBS||this.xrSessionActive||e<2)return t;let r=Math.max(1,Math.floor(e*.5)),i=t>=r,s=i?t-r:t,a=i?Math.max(1,e-r):r,l=(s+.5)/a*2-1;return Math.floor((l*.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);Te(this.projMatrix,this.fov,t,.1,e);let r=this.customTarget||this.bounds.center,i=r[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),s=r[1]+this.currDistance*Math.sin(this.currPhi),a=r[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);we(this.viewMatrix,[i,s,a],r,[0,1,0]),Q(this.mvpMatrix,this.projMatrix,this.viewMatrix),ce(this.normalMatrix,this.modelMatrix)}resize(){let t=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),e=this.canvas.getBoundingClientRect(),r=Math.max(1,Math.floor(e.width*t)),i=Math.max(1,Math.floor(e.height*t));this.canvas.width!==r||this.canvas.height!==i?(this.canvas.width=r,this.canvas.height=i,this.resizePickingFbo(r,i),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(t){let e=this.xrSessionActive;if(this.xrSessionActive=t,e&&!t){this.xrDepthState.enabled=!1;for(let r of Z)r.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(r){this.reportRenderError(r)}}}reportRenderError(t){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",t))}stepXRUpdate(t){for(let e of Z)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 r=Math.min(Math.max((e-this.lastTime)/1e3,0),.1);if(this.lastTime=e,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}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),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=t,s[1]=0,s[2]=-e,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=e,s[9]=0,s[10]=t,s[11]=0,s[12]=r-(t*r+e*i),s[13]=0,s[14]=i-(-e*r+t*i),s[15]=1}setVisible(t){this.isVisible=t}update(t){for(let a of Z)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 Z)a.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=s;let a={theta:r,phi:i,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(a),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:a}))}}renderXRView(t,e,r,i,s=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let l=t?.transform?.inverse?.matrix||this.viewMatrix,o=t?.projectionMatrix||this.projMatrix,c=t?.transform?.position,u=c?[c.x,c.y,c.z]:[0,1.6,0];e?this.modelRootMatrix.set(e):r&&e&&this.modelRootMatrix.set(e),this.render({viewMatrix:l,projMatrix:o,eyePos:u,viewport:i,eye:t?.eye||"none",clear:a>0?!1:t?.eye!=="right",isAR:s})}render(t){if(!t&&this.stereoSBS){let M=Math.max(2,this.canvas.width||2),v=Math.max(1,this.canvas.height||1),m=Math.max(1,Math.floor(M*.5)),I=Math.max(1,M-m),k=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),C=this.customTarget||this.bounds.center,F=C[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),E=C[1]+this.currDistance*Math.sin(this.currPhi),A=C[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta),p=Math.cos(this.currTheta),R=-Math.sin(this.currTheta),D=.032,f=W(),_=W(),P=[F-p*D,E,A-R*D],j=[C[0]-p*D*.25,C[1],C[2]-R*D*.25];Te(f,this.fov,m/v,.1,k),we(_,P,j,[0,1,0]);let V=W(),Y=W(),B=[F+p*D,E,A+R*D],O=[C[0]+p*D*.25,C[1],C[2]+R*D*.25];Te(V,this.fov,I/v,.1,k),we(Y,B,O,[0,1,0]),this.render({viewMatrix:_,projMatrix:f,eyePos:P,viewport:[0,0,m,v],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:Y,projMatrix:V,eyePos:B,viewport:[m,0,I,v],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,M,v);return}let e=this.gl,r=0,i=0,s=this.canvas.width,a=this.canvas.height;t?.viewport?(r=t.viewport[0],i=t.viewport[1],s=t.viewport[2],a=t.viewport[3],e.viewport(r,i,s,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(16384|256));let l=W(),o=t?.viewMatrix??this.viewMatrix;Q(l,t?.projMatrix??this.projMatrix,o);let c=K().xrDepthShader,u=this.toneMapping==="reinhard"?1:this.toneMapping==="none"?2:this.toneMapping==="aces"?3:this.toneMapping==="agx"?4:0,h=this.customTarget||this.bounds.center,x=t?t.eyePos[0]:h[0]+this.currDistance*Math.cos(this.currPhi)*Math.sin(this.currTheta),y=t?t.eyePos[1]:h[1]+this.currDistance*Math.sin(this.currPhi),d=t?t.eyePos[2]:h[2]+this.currDistance*Math.cos(this.currPhi)*Math.cos(this.currTheta);for(let M of Z)M.onBeforeDrawScene?.(this,e,l,[x,y,d],u);let b=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&b===0)return;let g=t?.eye||"none",w=!1,S=b>0?[...this.backdropMeshes,...this.meshes]:this.meshes,T=M=>{for(let v=0;v<S.length;v++){let m=S[v];if(m.visible===!1)continue;let I=this.selectedMeshName!==""&&m.name===this.selectedMeshName;v<b||m.worldSpace===!0||m.name==="__xr_reticle__"?this.modelMatrix.set(m.transform):Q(this.modelMatrix,this.modelRootMatrix,m.transform),Q(this.mvpMatrix,l,this.modelMatrix),ce(m.normalMatrix,this.modelMatrix);let k=m.extras?.xr?.stereo||m.userData?.xr?.stereo,C=0,F=0,E=1,A=1;k==="sbs"?(E=.5,C=g==="right"?.5:0):k==="ou"&&(A=.5,F=g==="right"?.5:0);for(let p of m.primitives){let R=!!p.isTransmissive;if(!M&&R){w=!0;continue}if(M&&!R)continue;let D=p.customProgram||this.renderProg,f=p.customUniforms||this.uRender;e.useProgram(D),e.uniform1i(f.uToneMapping,u),e.uniform1f(f.uEnvIntensity,this.envIntensity),e.uniform3f(f.uCameraPos,x,y,d),e.uniform1f(f.uEmissive,I?1:0),e.uniformMatrix4fv(f.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(f.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(f.uNormalMatrix,!1,m.normalMatrix),f.uUvTransform&&e.uniform4f(f.uUvTransform,C,F,E,A),f.uViewportSize&&e.uniform2f(f.uViewportSize,Math.max(1,s),Math.max(1,a)),c?.bind(e,f,this.xrDepthState,o,[r,i,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(e.activeTexture(33988),e.bindTexture(3553,this.environmentTexture),e.uniform1i(f.uEnvironmentMap,4),e.uniform1i(f.uHasEnvironmentMap,1)):e.uniform1i(f.uHasEnvironmentMap,0),this.bindLights(f),f.uSectionEnabled&&e.uniform1i(f.uSectionEnabled,0);for(let P of Z)P.onBeforeDrawPrimitive?.(e,D,p,m,this.worldMatrices||[],this.gltf);e.uniform4fv(f.uBaseColor,p.baseColor),e.uniform1f(f.uMetallic,p.metallic),e.uniform1f(f.uRoughness,p.roughness),f.uClearcoat&&e.uniform2f(f.uClearcoat,p.clearcoat??0,p.clearcoatRoughness??.04),p.texture?(e.activeTexture(33984),e.bindTexture(3553,p.texture),e.uniform1i(f.uBaseColorTexture,0),e.uniform1i(f.uHasTexture,1)):e.uniform1i(f.uHasTexture,0),p.metallicRoughnessTexture?(e.activeTexture(33985),e.bindTexture(3553,p.metallicRoughnessTexture),e.uniform1i(f.uMetallicRoughnessTexture,1),e.uniform1i(f.uHasMetallicRoughnessTexture,1)):e.uniform1i(f.uHasMetallicRoughnessTexture,0),p.normalTexture?(e.activeTexture(33986),e.bindTexture(3553,p.normalTexture),e.uniform1i(f.uNormalTexture,2),e.uniform1i(f.uHasNormalTexture,1),e.uniform1f(f.uNormalScale,p.normalScale)):e.uniform1i(f.uHasNormalTexture,0),p.occlusionTexture?(e.activeTexture(33987),e.bindTexture(3553,p.occlusionTexture),e.uniform1i(f.uOcclusionTexture,3),e.uniform1i(f.uHasOcclusionTexture,1),e.uniform1f(f.uOcclusionStrength,p.occlusionStrength)):e.uniform1i(f.uHasOcclusionTexture,0),e.bindVertexArray(p.vao);let _=m.instanceMatrices;if(_&&_.length>=16){let P=_.length>>4,j=m.instanceColors,V=W(),Y=new Float32Array(9),B=[p.baseColor[0],p.baseColor[1],p.baseColor[2],p.baseColor[3]];for(let O=0;O<P;O++)Q(V,this.modelMatrix,_.subarray(O*16,O*16+16)),Q(this.mvpMatrix,l,V),ce(Y,V),e.uniformMatrix4fv(f.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(f.uModel,!1,V),e.uniformMatrix3fv(f.uNormalMatrix,!1,Y),j&&(B[0]=p.baseColor[0]*j[O*3],B[1]=p.baseColor[1]*j[O*3+1],B[2]=p.baseColor[2]*j[O*3+2],B[3]=p.baseColor[3],e.uniform4fv(f.uBaseColor,B)),p.indices?e.drawElements(4,p.indexCount,p.indexType,0):e.drawArrays(4,0,p.indexCount)}else p.indices?e.drawElements(4,p.indexCount,p.indexType,0):e.drawArrays(4,0,p.indexCount)}}};if(T(!1),w){for(let M of Z)M.onBeforeTransmissivePass?.(e,this);T(!0)}for(let M of Z)M.onAfterRender?.(e,this,l)}disposeMeshListGpuResources(t,e){let r=this.gl,i=new Set,s=a=>{a&&!i.has(a)&&(i.add(a),r.deleteTexture(a))};for(let a of t)for(let l of a.primitives){if(l.vao&&r.deleteVertexArray(l.vao),l.buffers)for(let o of l.buffers)r.deleteBuffer(o);s(l.texture),s(l.metallicRoughnessTexture),s(l.normalTexture),s(l.occlusionTexture),l.customProgram&&r.deleteProgram(l.customProgram)}if(e)for(let a of e)s(a)}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 Z)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()}};re.registerPlugin=Be,re.getRegisteredPlugins=ke;var bt=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(n,t){super(n,t),this.detail=t?.detail??null}});var J=class J extends bt{constructor(){super(...arguments);this.viewer=null;this.canvas=null;this.posterEl=null;this.arButton=null;this.currentModel=null;this.activeXRSession=null;this.toastTimer=null;this.currentModelLimits=void 0;this.isModelLoaded=!1;this.scriptHandle=null;this.resizeObserver=null;this.mutationObserver=null}static get arProvider(){return K().arProvider}static set arProvider(e){K().arProvider=e}static get scriptRunner(){return K().scriptRunner}static set scriptRunner(e){K().scriptRunner=e}static get sandboxEngineSrc(){return K().sandboxEngineSrc??null}static set sandboxEngineSrc(e){K().sandboxEngineSrc=e}static get sandboxIframeSrc(){return K().sandboxIframeSrc??null}static set sandboxIframeSrc(e){K().sandboxIframeSrc=e}static get allowClientScripts(){return!!K().allowClientScripts}static set allowClientScripts(e){K().allowClientScripts=e}static registerScriptRunner(e){J.scriptRunner=e}static registerDecoder(e,r){re.registerDecoder(e,r)}static getDecoder(e){return re.getDecoder(e)}static registerAR(e){typeof e=="function"?J.arProvider={activateAR:e}:J.arProvider=e,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof J&&i.updateARButtonVisibility()})}static isARSupported(){return!!J.arProvider}getLoadedModel(){return this.currentModel}connectedCallback(){if(typeof document>"u")return;(!this.style.display||this.style.display==="inline")&&(this.style.display="block"),getComputedStyle(this).position==="static"&&(this.style.position="relative"),this.style.overflow="hidden",this.setupDOM(),this.initViewer(),this.setupResizeObserver();let e=this.getAttribute("src"),r=this.getAttribute("script-src");if(e)this.loadModelFromSrc(e).catch(()=>{});else if(r)this.loadScriptFromSrc(r).catch(()=>{});else{let i=this.querySelector('script[type="text/three"], script[type="text/three-live"]');i&&i.textContent&&this.executeScript(i.textContent).catch(()=>{})}for(let i of re.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let e of re.getRegisteredPlugins())e.onElementDisconnected?.(this);this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.activeXRSession&&(this.activeXRSession.stop?.().catch?.(()=>{}),this.activeXRSession=null),this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),this.viewer&&(this.viewer.destroy(),this.viewer=null),this.isModelLoaded=!1}attributeChangedCallback(e,r,i){if(r!==i){switch(e){case"src":i&&this.loadModelFromSrc(i).catch(()=>{});break;case"camera-target":this.applyCameraTarget(i);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(i);break;case"script-src":i&&this.loadScriptFromSrc(i).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(i);break;case"camera-orbit":this.applyCameraOrbit(i);break;case"selected-mesh":this.viewer&&i!==null&&this.viewer.setSelectedMesh(i);break;case"exposure":if(this.viewer&&i!==null){let s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer&&i&&this.viewer.setToneMapping(i);break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(i).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(i)?.catch?.(()=>{});break;case"camera-controls":{let s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"none":"auto");break}case"autoplay":this.viewer&&this.viewer.setAutoplay(i!==null&&i!=="false");break;case"animation-name":this.viewer&&i!==null&&this.viewer.setAnimationName(i);break;case"variant-name":this.viewer&&this.selectVariant(i);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(i!==null&&i!=="false");break;case"auto-rotate-delay":this.viewer&&this.viewer.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":this.viewer&&this.viewer.setAutoRotateSpeed(this.parseRotationPerSecond(i));break;case"ar":this.updateARButtonVisibility();break}for(let s of re.getRegisteredPlugins())s.onAttributeChanged?.(this,e,r,i)}}getAttr(e){return this.getAttribute(e)}setAttr(e,r){r!==null?this.setAttribute(e,r):this.removeAttribute(e)}getBoolAttr(e){return this.hasAttribute(e)&&this.getAttribute(e)!=="false"}setBoolAttr(e,r){r?this.setAttribute(e,""):this.removeAttribute(e)}getFloatAttr(e,r){let i=this.getAttribute(e);return i!==null?parseFloat(i):r}get src(){return this.getAttr("src")}set src(e){this.setAttr("src",e)}get cameraControls(){return this.getBoolAttr("camera-controls")}set cameraControls(e){this.setBoolAttr("camera-controls",e)}get cameraOrbit(){return this.getAttr("camera-orbit")}set cameraOrbit(e){this.setAttr("camera-orbit",e)}get cameraTarget(){return this.getAttr("camera-target")}set cameraTarget(e){this.setAttr("camera-target",e)}get minCameraOrbit(){return this.getAttr("min-camera-orbit")}set minCameraOrbit(e){this.setAttr("min-camera-orbit",e)}get maxCameraOrbit(){return this.getAttr("max-camera-orbit")}set maxCameraOrbit(e){this.setAttr("max-camera-orbit",e)}get fieldOfView(){return this.getAttr("field-of-view")}set fieldOfView(e){this.setAttr("field-of-view",e)}get iosSrc(){return this.getAttr("ios-src")}set iosSrc(e){this.setAttr("ios-src",e)}get scriptSrc(){return this.getAttr("script-src")}set scriptSrc(e){this.setAttr("script-src",e)}get sandbox(){return this.getAttribute("sandbox")||(K().sandboxIframeSrc?"iframe":"worker")}set sandbox(e){this.setAttribute("sandbox",e)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||J.allowClientScripts}set allowClientScripts(e){this.setBoolAttr("allow-client-scripts",e)}get poster(){return this.getAttr("poster")}set poster(e){this.setAttr("poster",e)}get selectedMesh(){return this.getAttr("selected-mesh")}set selectedMesh(e){this.setAttr("selected-mesh",e)}get exposure(){return this.getFloatAttr("exposure",1)}set exposure(e){this.setAttribute("exposure",String(e))}get autoRotate(){return this.getBoolAttr("auto-rotate")}set autoRotate(e){this.setBoolAttr("auto-rotate",e)}get autoRotateDelay(){return this.getFloatAttr("auto-rotate-delay",3e3)}set autoRotateDelay(e){this.setAttribute("auto-rotate-delay",String(e))}get rotationPerSecond(){return this.getAttr("rotation-per-second")||"30deg"}set rotationPerSecond(e){this.setAttr("rotation-per-second",e)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(e){this.setBoolAttr("ar",e)}get arScale(){return this.getAttribute("ar-scale")||"auto"}set arScale(e){this.setAttribute("ar-scale",e)}get arPlacement(){return this.getAttribute("ar-placement")||"floor"}set arPlacement(e){this.setAttribute("ar-placement",e)}get canActivateAR(){return J.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(e){this.setAttribute("shadow-intensity",String(e))}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(e){this.setAttribute("shadow-softness",String(e))}get toneMapping(){return this.getAttribute("tone-mapping")||"neutral"}set toneMapping(e){this.setAttribute("tone-mapping",e)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(e){this.setAttribute("bloom",String(e))}get bloomThreshold(){return this.getFloatAttr("bloom-threshold",.8)}set bloomThreshold(e){this.setAttribute("bloom-threshold",String(e))}get bloomRadius(){return this.getFloatAttr("bloom-radius",.5)}set bloomRadius(e){this.setAttribute("bloom-radius",String(e))}get outlineSelected(){return this.getBoolAttr("outline-selected")}set outlineSelected(e){this.setBoolAttr("outline-selected",e)}get outlineColor(){return this.getAttr("outline-color")||"#38bdf8"}set outlineColor(e){this.setAttr("outline-color",e)}get environmentImage(){return this.getAttr("environment-image")}set environmentImage(e){this.setAttr("environment-image",e)}get skyboxImage(){return this.getAttr("skybox-image")}set skyboxImage(e){this.setAttr("skybox-image",e)}get autoplay(){return this.getBoolAttr("autoplay")}set autoplay(e){this.setBoolAttr("autoplay",e)}get animationName(){return this.getAttr("animation-name")}set animationName(e){this.setAttr("animation-name",e)}get availableAnimations(){return this.viewer?this.viewer.getAvailableAnimations():[]}get variantName(){return this.viewer?this.viewer.getVariantName():this.getAttr("variant-name")}set variantName(e){this.setAttr("variant-name",e)}get availableVariants(){return this.viewer?this.viewer.getAvailableVariants():[]}selectVariant(e){if(!this.viewer)return!1;let r=this.viewer.selectVariant(e);return r&&this.dispatchEvent(new CustomEvent("variant-applied",{bubbles:!0,composed:!0,detail:{variantName:this.viewer.getVariantName()}})),r}get model(){let e=this.viewer?this.viewer.getModelMaterials():[];return{materials:e,getMaterialByName(r){return e.find(i=>i.name===r)??null}}}play(){this.viewer&&this.viewer.playAnimation(this.animationName||void 0)}pause(){this.viewer&&this.viewer.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(e=0){this.viewer?.resetTurntableRotation(e)}setCamera(e,r,i,s){this.viewer&&this.viewer.setCamera(e,r,i,s)}getCameraOrbit(){return this.viewer?this.viewer.getCameraOrbit():{theta:0,phi:0,radius:3,toString(){return"0rad 0rad 3m"}}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():{x:0,y:0,z:0,toString(){return"0m 0m 0m"}}}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(e,r){return this.viewer&&this.viewer.render?.(),this.canvas?this.canvas.toDataURL(e,r):""}toBlob(e){return this.viewer&&this.viewer.render?.(),new Promise((r,i)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){i(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(s=>{s?r(s):i(new Error("Failed to capture canvas blob."))},e?.mimeType,e?.qualityArgument)})}positionAndNormalFromPoint(e,r){if(!this.viewer)return null;let i=this.viewer.raycastFromScreenPoint(e,r);if(!i)return null;let[s,a,l]=i.hitPoint||i.point,[o,c,u]=i.normal;return{position:{x:s,y:a,z:l,toString(){return`${s}m ${a}m ${l}m`}},normal:{x:o,y:c,z:u,toString(){return`${o}m ${c}m ${u}m`}}}}async loadModel(e){return this.loadModelWithLimits(e)}async loadModelWithLimits(e,r){if(!this.viewer){this.currentModel=e,this.currentModelLimits=r;return}try{let i;if(typeof e=="string"){this.isModelLoaded=!1,this.viewer?.clearScene?.();let o=await fetch(e);if(!o.ok)throw new Error(`Failed to load 3D model from "${e}": HTTP ${o.status}`);i=await o.arrayBuffer()}else i=e;let s=Re(i);this.viewer.loadGLBData(s,r),this.currentModel=s,this.currentModelLimits=r,this.isModelLoaded=!0,this.hidePoster(),this.updateHotspots();let a=this.getAttribute("selected-mesh");a&&this.viewer.setSelectedMesh(a);let l=this.getAttribute("variant-name");l&&this.selectVariant(l),this.dispatchEvent(new CustomEvent("load",{bubbles:!0,composed:!0,detail:{model:s}}))}catch(i){throw this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),i}}showToast(e,r=4500){if(typeof document>"u")return;let i=this.querySelector(".three-live-toast");i||(i=document.createElement("div"),i.className="three-live-toast",i.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background-color:rgba(15,23,42,0.94);color:#f8fafc;border:1px solid rgba(56,189,248,0.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,0.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s ease,transform .25s ease;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(i)),i.textContent=e,this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")}):(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)"),this.toastTimer=setTimeout(()=>{i&&(i.style.opacity="0",i.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},r)}async activateAR(){if(this.activeXRSession&&typeof this.activeXRSession.isSessionActive=="function"&&this.activeXRSession.isSessionActive()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null),!this.currentModel){let i=new Error("No 3D model is loaded in <three-live>.");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}if(!J.arProvider){let i=new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR().");throw this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(i.message,6e3),i}let e=this.getAttribute("ios-src"),r=(this.getAttribute("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"session-started"}}));let i=await J.arProvider.activateAR({model:e||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:r.length>0?r:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"not-presenting"}}))},onError:s=>{this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:s}})),this.showToast(`AR error: ${s.message}`,6e3)}}});if(i.success)i.session&&(this.activeXRSession=i.session),i.mode==="quick-look"?this.showToast("Opening Apple AR Quick Look..."):i.mode==="scene-viewer"?this.showToast("Opening Google Scene Viewer..."):i.mode==="webxr"&&this.showToast("WebXR AR session started.");else{let s=typeof navigator<"u"&&navigator.userAgent||"",a=/Macintosh/i.test(s)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),l=/Android|iPhone|iPad|iPod/i.test(s);if(a&&!l&&typeof document<"u"&&this.currentModel&&J.arProvider.createUSDZBlob)try{let o=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:J.arProvider.createUSDZBlob(this.currentModel),c=URL.createObjectURL(o),u=document.createElement("a");u.href=c,u.download="three_live_model.usdz",document.body.appendChild(u),u.click(),document.body.removeChild(u),setTimeout(()=>URL.revokeObjectURL(c),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3)}else this.showToast(i.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.",6e3);i.error&&this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i.error}}))}return i}catch(i){throw this.activeXRSession=null,this.dispatchEvent(new CustomEvent("ar-status",{bubbles:!0,composed:!0,detail:{status:"failed",error:i}})),this.showToast(`AR error: ${i.message||String(i)}`,6e3),i}}setupDOM(){let e=this.querySelector("canvas");e||(e=document.createElement("canvas"),e.style.width="100%",e.style.height="100%",e.style.display="block",e.style.touchAction=this.cameraControls?"none":"auto",e.style.outline="none",this.appendChild(e)),this.canvas=e;let r=this.getAttribute("poster");r&&this.updatePoster(r),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;let e=this.autoRotate,r=this.exposure,i=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttribute("max-camera-orbit")),a=this.parseCameraTarget(this.getAttribute("camera-target")),l=this.parseFieldOfView(this.getAttribute("field-of-view"));this.viewer=new re(this,this.canvas,{autoRotate:e,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttribute("rotation-per-second")),exposure:r,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttribute("variant-name")||void 0,fieldOfView:l,cameraTarget:a,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:c=>{this.dispatchEvent(new CustomEvent("meshclick",{bubbles:!0,composed:!0,detail:c}))},onCameraChange:c=>{this.updateHotspots();for(let u of re.getRegisteredPlugins())u.onCameraChange?.(this.viewer,this);this.dispatchEvent(new CustomEvent("camera-change",{bubbles:!0,composed:!0,detail:c}))}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let o=this.getAttribute("camera-orbit");o&&this.applyCameraOrbit(o),this.currentModel&&this.loadModelWithLimits(this.currentModel,this.currentModelLimits)}setupResizeObserver(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.viewer&&(this.viewer.resize(),this.viewer.render(),this.updateHotspots())}),this.resizeObserver.observe(this))}updatePoster(e){if(!(typeof document>"u")){if(!e){this.posterEl&&(this.posterEl.remove(),this.posterEl=null);return}this.posterEl||(this.posterEl=document.createElement("img"),this.posterEl.setAttribute("alt","3D Scene Preview"),this.posterEl.style.position="absolute",this.posterEl.style.inset="0",this.posterEl.style.width="100%",this.posterEl.style.height="100%",this.posterEl.style.objectFit="cover",this.posterEl.style.transition="opacity 0.35s ease-out",this.posterEl.style.pointerEvents="none",this.posterEl.style.zIndex="1",this.appendChild(this.posterEl)),this.posterEl.src=e,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let e=document.createElement("button");e.setAttribute("type","button"),e.setAttribute("aria-label","View in Augmented Reality"),e.className="three-live-ar-button",e.setAttribute("part","default-ar-button");let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let s=document.createElementNS(r,"svg");s.setAttribute("width","20"),s.setAttribute("height","20"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","currentColor"),s.setAttribute("stroke-width","2"),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.style.marginRight="6px";let a=document.createElementNS(r,"path");a.setAttribute("d","M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z");let l=document.createElementNS(r,"polyline");l.setAttribute("points","3.27 6.96 12 12.01 20.73 6.96");let o=document.createElementNS(r,"line");o.setAttribute("x1","12"),o.setAttribute("y1","22.08"),o.setAttribute("x2","12"),o.setAttribute("y2","12"),s.appendChild(a),s.appendChild(l),s.appendChild(o),e.appendChild(s)}let i=document.createElement("span");i.textContent="View in AR",e.appendChild(i),e.style.cssText="position:absolute;right:16px;bottom:16px;z-index:2;align-items:center;justify-content:center;padding:8px 16px;background-color:rgba(15,23,42,0.85);color:#fff;border:1px solid rgba(255,255,255,0.15);border-radius:9999px;font:600 13px system-ui,-apple-system,sans-serif;cursor:pointer;backdrop-filter:blur(8px);box-shadow:0 4px 12px rgba(0,0,0,0.25);transition:transform .15s ease,background-color .15s ease;display:none",e.addEventListener("mouseenter",()=>{e.style.backgroundColor="rgba(30, 41, 59, 0.95)",e.style.transform="scale(1.04)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="rgba(15, 23, 42, 0.85)",e.style.transform="scale(1)"}),e.addEventListener("click",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=e,this.appendChild(e)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let e=this.hasAttribute("ar")&&!!J.arProvider,r=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;r?(this.arButton&&(this.arButton.style.display="none"),r.__tlARBound||(r.__tlARBound=!0,r.addEventListener("click",i=>{i.stopPropagation(),this.activateAR()})),r.dataset.tlOrigDisplay===void 0&&(r.dataset.tlOrigDisplay=r.style.display==="none"?"":r.style.display),r.style.display=e?r.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.arButton.style.display=e?"flex":"none")}applyCameraOrbit(e){if(!(!e||!this.viewer))try{let r=JSON.parse(e);this.viewer.setInitialCamera(r.theta,r.phi,r.distance,r.zoom)}catch{let r=e.trim().split(/\s+/);if(r.length>=2){let i=o=>o.endsWith("rad")?parseFloat(o)*180/Math.PI:parseFloat(o.replace(/deg$/,"")),s=r[0]==="auto"?void 0:i(r[0]),a=r[1]==="auto"?void 0:i(r[1]),l;r.length>=3&&r[2]!=="auto"&&(l=parseFloat(r[2].replace(/m$/,""))),(s!==void 0&&!isNaN(s)||a!==void 0&&!isNaN(a))&&this.viewer.setInitialCamera(s!==void 0&&!isNaN(s)?s:void 0,a!==void 0&&!isNaN(a)?a:void 0,l!==void 0&&!isNaN(l)?l:void 0)}}}parseOrbitLimit(e){if(!e)return{};let r=e.trim().split(/\s+/),i={};if(r.length>0&&r[0]!=="auto"){let s=r[0].endsWith("rad")?parseFloat(r[0])*180/Math.PI:parseFloat(r[0].replace(/deg$/,""));isNaN(s)||(i.theta=s)}if(r.length>1&&r[1]!=="auto"){let s=r[1].endsWith("rad")?parseFloat(r[1])*180/Math.PI:parseFloat(r[1].replace(/deg$/,""));isNaN(s)||(i.phi=s)}if(r.length>2&&r[2]!=="auto"){let s=parseFloat(r[2].replace(/m$/,""));isNaN(s)||(i.distance=s)}return i}applyOrbitLimits(){if(!this.viewer)return;let e=this.parseOrbitLimit(this.getAttribute("min-camera-orbit")),r=this.parseOrbitLimit(this.getAttribute("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:e.theta,maxTheta:r.theta,minPhi:e.phi,maxPhi:r.phi,minDistance:e.distance,maxDistance:r.distance})}parseCameraTarget(e){if(!e)return;let r=e.trim().split(/\s+/).map(i=>parseFloat(i.replace(/m$/,"")));return r.length>=3&&!r.some(isNaN)?[r[0],r[1],r[2]]:void 0}parseFieldOfView(e){if(!e)return;let r=e.endsWith("rad")?parseFloat(e)*180/Math.PI:parseFloat(e.replace(/deg$/,""));return isNaN(r)?void 0:r}parseRotationPerSecond(e){if(!e)return Math.PI/6;let r=e.trim(),i=parseFloat(r);return isNaN(i)?Math.PI/6:r.endsWith("rad")?i:r.endsWith("%")?i/100*Math.PI*2:i*Math.PI/180}applyCameraTarget(e){let r=this.parseCameraTarget(e);this.viewer&&r&&this.viewer.setTarget(r[0],r[1],r[2])}applyFieldOfView(e){let r=this.parseFieldOfView(e);this.viewer&&r!==void 0&&this.viewer.setFieldOfView(r)}updateHotspot(e){let r=this.querySelector(`[slot="${e.name}"]`);r&&(e.position!==void 0&&r.setAttribute("data-position",e.position),e.normal!==void 0&&r.setAttribute("data-normal",e.normal)),this.updateHotspots()}updateHotspots(){for(let e of re.getRegisteredPlugins())if(e.updateHotspotsForElement){e.updateHotspotsForElement(this,this.viewer);return}}async loadModelFromSrc(e){await this.loadModel(e)}runWithScriptRunner(e){let r=J.scriptRunner;if(!r){let i=new Error('Procedural script execution requires "three-live/full" or ThreeLiveElement.registerScriptRunner().');return this.showToast(i.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:i}})),Promise.reject(i)}return this.scriptHandle&&(this.scriptHandle.terminate(),this.scriptHandle=null),this.isModelLoaded=!1,this.viewer?.clearScene?.(),new Promise((i,s)=>{let a=!1;e(r,{onModelReady:o=>{this.loadModelWithLimits(o,Ye).then(()=>{a||(a=!0,i(o))},c=>{let u=c instanceof Error?c.message:String(c);this.showToast(u),a||(a=!0,s(c))})},onUpdateTransforms:o=>this.viewer?.updateMeshTransforms(o),onError:o=>{this.showToast(o.message),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:o}})),a||(a=!0,s(o))},onToast:o=>this.showToast(o)}).then(o=>{o&&(this.scriptHandle=o)},o=>{o instanceof Error&&o.message&&this.showToast(o.message),a||(a=!0,s(o))})})}loadScriptFromSrc(e){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(s),Promise.reject(s)}return r.executeUrl(e,this.sandbox,i)})}executeScript(e){if(!J.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Ie);return this.showToast(Ne),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,composed:!0,detail:{error:r}})),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(e,this.sandbox,i,{allowClientScripts:!0}))}};J.observedAttributes=["src","ios-src","script-src","sandbox","allow-client-scripts","poster","camera-controls","camera-orbit","camera-target","min-camera-orbit","max-camera-orbit","field-of-view","selected-mesh","ar","ar-modes","ar-scale","ar-placement","exposure","shadow-intensity","shadow-softness","tone-mapping","bloom","bloom-threshold","bloom-radius","outline","outline-selected","outline-color","environment-image","skybox-image","autoplay","animation-name","variant-name","auto-rotate","auto-rotate-delay","rotation-per-second"],J.registerPlugin=re.registerPlugin,J.getRegisteredPlugins=re.getRegisteredPlugins;var Ae=J;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",Ae);
|