three-live 1.3.2 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/index.d.ts +190 -0
- package/dist/three-author-engine.js +171 -163
- package/dist/three-author.cjs +145 -163
- package/dist/three-author.d.ts +190 -0
- package/dist/three-author.js +145 -163
- package/dist/three-convert.cjs +142 -160
- package/dist/three-convert.d.ts +190 -0
- package/dist/three-convert.js +142 -160
- package/dist/three-live-ai.cjs +41 -0
- package/dist/three-live-ai.d.ts +759 -0
- package/dist/three-live-ai.js +41 -0
- package/dist/three-live-ai.min.js +41 -0
- package/dist/three-live-animation.cjs +6 -6
- package/dist/three-live-animation.d.ts +190 -0
- package/dist/three-live-animation.js +5 -5
- package/dist/three-live-animation.min.js +5 -5
- package/dist/three-live-cad.cjs +2 -2
- package/dist/three-live-cad.d.ts +190 -0
- package/dist/three-live-cad.js +2 -2
- package/dist/three-live-cad.min.js +2 -2
- package/dist/three-live-element.cjs +50 -85
- package/dist/three-live-element.d.ts +190 -0
- package/dist/three-live-element.js +50 -85
- package/dist/three-live-full.cjs +907 -189
- package/dist/three-live-full.js +907 -189
- package/dist/three-live-full.min.js +907 -189
- package/dist/three-live-procedural.cjs +16 -0
- package/dist/three-live-procedural.d.ts +759 -0
- package/dist/three-live-procedural.js +16 -0
- package/dist/three-live-procedural.min.js +16 -0
- package/dist/three-live-sandbox.html +11 -1
- package/dist/three-live-studio.cjs +72 -17
- package/dist/three-live-studio.d.ts +190 -0
- package/dist/three-live-studio.js +72 -17
- package/dist/three-live-studio.min.js +73 -18
- package/dist/three-live-tsl.cjs +103 -0
- package/dist/three-live-tsl.d.ts +759 -0
- package/dist/three-live-tsl.js +103 -0
- package/dist/three-live-tsl.min.js +103 -0
- package/dist/three-live-viewer.cjs +50 -85
- package/dist/three-live-viewer.d.ts +190 -0
- package/dist/three-live-viewer.js +50 -85
- package/dist/three-live-viewer.min.js +50 -85
- package/dist/three-live-webgpu.cjs +585 -0
- package/dist/three-live-webgpu.d.ts +759 -0
- package/dist/three-live-webgpu.js +585 -0
- package/dist/three-live-webgpu.min.js +585 -0
- package/dist/three-live.cjs +147 -165
- package/dist/three-live.js +147 -165
- package/dist/three-live.min.js +147 -165
- package/dist/three-view.cjs +49 -84
- package/dist/three-view.d.ts +190 -0
- package/dist/three-view.js +50 -85
- package/dist/three-xr.cjs +141 -159
- package/dist/three-xr.d.ts +190 -0
- package/dist/three-xr.js +140 -158
- package/package.json +21 -1
package/dist/three-live.cjs
CHANGED
|
@@ -13,9 +13,9 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/var
|
|
17
|
-
layout(location=0) in vec3 aPosition;layout(location=1) in vec2 aUV;uniform mat4 uMVP;out vec2 vUV;void main(){vUV=aUV;gl_Position=uMVP*vec4(aPosition,1.);}`,
|
|
18
|
-
precision highp float;in vec2 vUV;uniform float uShadowIntensity,uShadowSoftness;out vec4 fragColor;void main(){vec2 p=(vUV-.5)*2.;float d=clamp(length(p),0.,1.);fragColor=vec4(0.,0.,0.,pow(1.-d*d,mix(1.2,2.8,uShadowSoftness))*smoothstep(1.,.85-uShadowSoftness*.6,d)*uShadowIntensity);}`,tt=new WeakMap,rr=new Float32Array(20);function Jt(t,e){let[i,r,s,a,o,n]=e;return[t[0]*i+t[4]*r+t[8]*s+t[12],t[1]*i+t[5]*r+t[9]*s+t[13],t[2]*i+t[6]*r+t[10]*s+t[14],Math.abs(t[0])*a+Math.abs(t[4])*o+Math.abs(t[8])*n,Math.abs(t[1])*a+Math.abs(t[5])*o+Math.abs(t[9])*n,Math.abs(t[2])*a+Math.abs(t[6])*o+Math.abs(t[10])*n]}function li(t){if(t._lb!==void 0)return t._lb;let e=1e9,i=1e9,r=1e9,s=-1e9,a=-1e9,o=-1e9;for(let n of t.primitives||[]){let l=n.positions;if(l)for(let h=0;h<l.length;h+=3)l[h]<e&&(e=l[h]),l[h+1]<i&&(i=l[h+1]),l[h+2]<r&&(r=l[h+2]),l[h]>s&&(s=l[h]),l[h+1]>a&&(a=l[h+1]),l[h+2]>o&&(o=l[h+2])}return t._lb=e<=s?[(e+s)*.5,(i+a)*.5,(r+o)*.5,(s-e)*.5,(a-i)*.5,(o-r)*.5]:null}function mi(t){let e=tt.get(t);if(e)return e;let i=(n,l)=>{let h=t.createShader(n);return t.shaderSource(h,l),t.compileShader(h),h},r=t.createProgram();t.attachShader(r,i(35633,ci)),t.attachShader(r,i(35632,ui)),t.linkProgram(r);let s=t.createVertexArray(),a=t.createBuffer(),o=t.createBuffer();return t.bindVertexArray(s),t.bindBuffer(34962,a),t.bufferData(34962,80,35048),t.enableVertexAttribArray(0),t.vertexAttribPointer(0,3,5126,!1,20,0),t.enableVertexAttribArray(1),t.vertexAttribPointer(1,2,5126,!1,20,12),t.bindBuffer(34963,o),t.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),t.bindVertexArray(null),e={prog:r,vao:s,vbo:a,ibo:o,uMVP:t.getUniformLocation(r,"uMVP"),uIntensity:t.getUniformLocation(r,"uShadowIntensity"),uSoftness:t.getUniformLocation(r,"uShadowSoftness")},tt.set(t,e),e}var ir={name:"contact-shadow",onContextRestored(t){tt.delete(t)},onAfterRender(t,e,i){let r=e.shadowIntensity;if(r<=0||!e.bounds)return;let s=mi(t),a=!e.xrSessionActive&&(e.backdropMeshes?.length??0)>0,o=[],n=[];for(let d of e.meshes||[]){if(!d||d.visible===!1||d.isPluginMesh||d.name==="__xr_reticle__"||d.name?.startsWith("__xr_slot_"))continue;let p=li(d);if(!p)continue;d.transform&&(p=Jt(d.transform,p)),e.modelRootMatrix&&(p=Jt(e.modelRootMatrix,p));let[A,b,x,u,m,v]=p,S=[A,x,u,v,b-m,b+m];/floor|table|pedestal|ground|base|plane/i.test(d.name||"")||m<.14&&Math.min(u,v)>.45?n.push(S):o.push(S)}let l=[],h=e.bounds.center||[0,0,0],c=Math.max(.05,Number(e.bounds.radius)||.5),f=e.bounds.min,g=f?[h[0],h[1],h[2],c,Math.max(.01,h[1]-f[1]),c]:[h[0],h[1],h[2],c,c,c];e.modelRootMatrix&&(g=Jt(e.modelRootMatrix,g));let w=e.xrSessionActive&&n.length===0&&String(e.container?.tagName||"").toLowerCase()==="xr-live"?(e.modelRootMatrix?e.modelRootMatrix[5]*-.25+e.modelRootMatrix[13]:-.25)+.002:g[1]-g[4]+.002;for(let[d,p,A,b,x]of o){let u=-1/0;for(let[v,S,_,D,,P]of n)x>=P-.08&&Math.abs(d-v)<=_&&Math.abs(p-S)<=D&&P+.002>u&&(u=P+.002);a&&(u=Math.max(u,d>=.04&&d<=.36&&p>=-.34&&p<=-.04&&x>=.01?.036:Math.hypot(d,p)<=.66&&x>=-.06?.003:-.477)),isFinite(u)||(u=w);let m=l.find(v=>Math.hypot(d-v[0],p-v[1])<.06&&Math.abs(u-v[5])<.05);m?(m[2]=Math.max(m[2],A*.78),m[3]=Math.max(m[3],b*.78),m[4]=Math.min(m[4],x)):l.push([d,p,A,b,x,u])}if(l.length===0){let d=Math.max(.1,g[3]*1.5)/1.45;l.push([g[0],g[2],d,d,w,w])}t.useProgram(s.prog),t.uniformMatrix4fv(s.uMVP,!1,i),t.enable(3042),(t.blendFuncSeparate||t.blendFunc).call(t,770,771,1,771),t.depthMask(!1),t.bindVertexArray(s.vao),t.bindBuffer(34962,s.vbo);for(let[d,p,A,b,x,u]of l){let m=Math.max(0,x-u),v=r/(1+m*2);if(v<.02)continue;let S=1+Math.min(.75,m*.85),_=Math.max(.045,A*1.45*S),D=Math.max(.045,b*1.45*S);rr.set([d-_,u,p-D,0,0,d+_,u,p-D,1,0,d+_,u,p+D,1,1,d-_,u,p+D,0,1]),t.bufferSubData(34962,0,rr),t.uniform1f(s.uIntensity,v),t.uniform1f(s.uSoftness,Math.min(1,e.shadowSoftness+Math.min(.45,m*.6))),t.drawElements(4,6,5123,0)}t.bindVertexArray(null),t.depthMask(!0),t.disable(3042)},onDestroy(t){let e=tt.get(t);e&&(t.deleteVertexArray(e.vao),t.deleteBuffer(e.vbo),t.deleteBuffer(e.ibo),t.deleteProgram(e.prog),tt.delete(t))}};function sr(t,e,i){let r=[],s=new Map,a=[],o=[],n=[],l=new Map,h=u=>{let m=s.get(u);return m===void 0&&(m=r.length,r.push({op:u}),s.set(u,m)),m},c=u=>{let m=l.get(u);return m===void 0&&(m=n.length,n.push({id:u}),l.set(u,m)),m},f=(u,m={})=>a.push({declaration:h(u),...m})-1,g=(u,m,v)=>o.push({id:u,type:m,value:v})-1,w=u=>({node:u,socket:"value"}),d=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(d&&typeof d=="object"){let u=Array.isArray(d.graphs)?d.graphs[d.graph??0]:d;if(u&&Array.isArray(u.nodes)){let m=Array.isArray(u.declarations)?u.declarations:[];for(let v of m)v?.op&&h(v.op);Array.isArray(u.variables)&&o.push(...u.variables);for(let v of u.events||[])v?.id&&c(v.id);for(let v of u.nodes){if(!v||typeof v!="object")continue;let S=v.op||(typeof v.declaration=="number"?m[v.declaration]?.op:"");a.push(S?{...v,declaration:h(S)}:{...v})}}}let p=(u,m,v="translation")=>v==="baseColorFactor"||v==="metallicFactor"||v==="roughnessFactor"?`/materials/${Math.max(0,m)}/pbrMetallicRoughness/${v}`:v==="emissiveFactor"||v==="alphaCutoff"?`/materials/${Math.max(0,m)}/${v}`:v==="visible"?`/nodes/${u}/extensions/KHR_node_visibility/visible`:`/nodes/${u}/${v}`,A=new Map;t.forEach((u,m)=>{typeof u?.name=="string"&&!A.has(u.name)&&A.set(u.name,m)});let b=(u,m)=>typeof u.target=="string"&&A.has(u.target)?A.get(u.target):typeof u.targetNode=="number"?u.targetNode:m,x=u=>{let m=t[u];return(typeof m?.mesh=="number"?e[m.mesh]?.primitives?.[0]?.material:0)??0};for(let u=0;u<t.length;u++){let m=t[u],v=m?.extras?.interactivity;if(!v||typeof v!="object")continue;let S=(typeof m.mesh=="number"?e[m.mesh]?.primitives?.[0]?.material:0)??0,_=P=>{let N=Array.isArray(P)?P:[P],E=[];for(let L=0;L<N.length;L++){let M=N[L];if(!M||typeof M!="object")continue;let O=M.action||"interpolate",H=typeof M.duration=="number"?M.duration:.35;if(O==="toggleTransform"){let R=M.property==="rotation"||M.property==="scale"?M.property:"translation",C=R==="rotation"?m.rotation||[0,0,0,1]:R==="scale"?m.scale||[1,1,1]:m.translation||[0,0,0],y=`/nodes/${u}/${R}`,T=g(`__toggle_${u}_${L}`,"bool",!1),z=f("variable/get",{configuration:{variable:T}}),G=f("math/not",{values:{a:w(z)}}),B=f("variable/set",{configuration:{variable:T},values:{value:w(G)}}),te=f("pointer/interpolate",{configuration:{pointer:y},values:{value:{value:Array.isArray(M.to)?M.to:C},duration:{value:H}}}),I=f("pointer/interpolate",{configuration:{pointer:y},values:{value:{value:Array.isArray(M.from)?M.from:C},duration:{value:H}}});a[B].flows={out:{node:f("flow/branch",{values:{condition:w(z)},flows:{true:{node:te},false:{node:I}}})}},E.push(B)}else if(O==="interpolate"){let R=M.to??M.value;if(R===void 0)continue;let C={value:{value:R},duration:{value:H}};M.from!==void 0&&(C.from={value:M.from}),E.push(f("pointer/interpolate",{configuration:{pointer:typeof M.pointer=="string"?M.pointer:p(b(M,u),x(b(M,u)),M.property)},values:C}))}else if(O==="setProperty"){if(M.value===void 0)continue;E.push(f("pointer/set",{configuration:{pointer:typeof M.pointer=="string"?M.pointer:p(b(M,u),x(b(M,u)),M.property)},values:{value:{value:M.value}}}))}else if(O==="toggleVisibility"){let R=b(M,u),C=g(`__vis_${R}_${L}`,"bool",!0),y=f("variable/get",{configuration:{variable:C}}),T=f("math/not",{values:{a:w(y)}}),z=f("variable/set",{configuration:{variable:C},values:{value:w(T)}});a[z].flows={out:{node:f("pointer/set",{configuration:{pointer:`/nodes/${R}/extensions/KHR_node_visibility/visible`},values:{value:w(y)}})}},E.push(z)}else if(O==="cycleMaterialColor"&&Array.isArray(M.colors)&&M.colors.length>0){let R=typeof M.duration=="number"?M.duration:.25,C=`/materials/${Math.max(0,S)}/pbrMetallicRoughness/baseColorFactor`,y=g(`__color_idx_${u}_${L}`,"int",0),T=f("variable/get",{configuration:{variable:y}}),z=f("math/add",{values:{a:w(T),b:{value:1}}}),G=f("math/rem",{values:{a:w(z),b:{value:M.colors.length}}}),B=f("variable/set",{configuration:{variable:y},values:{value:w(G)}}),te={};for(let I=0;I<M.colors.length;I++){let W=M.colors[I],Z=Array.isArray(W)&&W.length>=3?[W[0],W[1],W[2],W[3]??1]:[1,1,1,1];te[String(I)]={node:R>0?f("pointer/interpolate",{configuration:{pointer:C},values:{value:{value:Z},duration:{value:R}}}):f("pointer/set",{configuration:{pointer:C},values:{value:{value:Z}}})}}a[B].flows={out:{node:f("flow/switch",{values:{selection:w(T)},flows:te})}},E.push(B)}else if(O==="playAnimation")E.push(f("animation/start",{configuration:{animation:M.animation??M.clip??0}}));else if(O==="stopAnimation")E.push(f("animation/stop"));else if(O==="sendEvent"){let R={};for(let[C,y]of Object.entries(M.values||{}))R[C]={value:y};E.push(f("event/send",{configuration:{event:c(String(M.event??M.id??"custom"))},values:R}))}}if(!E.length)return null;if(E.length===1)return E[0];let F={};return E.forEach((L,M)=>{F[String(M)]={node:L}}),f("flow/sequence",{flows:F})},D=(P,N,E)=>{let F=_(N);F!==null&&f(P,{...E?{configuration:E}:{},flows:{out:{node:F}}})};if(v.onSelect&&D("pointer/onSelect",v.onSelect,{nodeIndex:u}),v.onHoverIn&&D("pointer/onHoverIn",v.onHoverIn,{nodeIndex:u}),v.onHoverOut&&D("pointer/onHoverOut",v.onHoverOut,{nodeIndex:u}),v.onStart&&D("event/onStart",v.onStart),v.onReceive&&typeof v.onReceive=="object")for(let[P,N]of Object.entries(v.onReceive))D("event/receive",N,{event:c(P)})}return a.length?{graphs:[{declarations:r,nodes:a,variables:o,events:n}],graph:0}:null}var dt='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).',ft="Security Error: client-side scripts require allow-client-scripts opt-in.";function de(){let t=new Float32Array(16);return t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function pt(t,e,i,r,s){let a=1/Math.tan(e/2);t.fill(0),t[0]=a/i,t[5]=a,t[11]=-1;let o=1/(r-s);return t[10]=(s+r)*o,t[14]=2*s*r*o,t}function qe(t,e,i,r){let[s,a,o]=e,[n,l,h]=r,[c,f,g]=i,w=s-c,d=a-f,p=o-g,A=Math.hypot(w,d,p);A<=1e-5?(w=0,d=0,p=1):(w/=A,d/=A,p/=A);let b=l*p-h*d,x=h*w-n*p,u=n*d-l*w;A=Math.hypot(b,x,u),A<=1e-5?(b=0,x=0,u=0):(b/=A,x/=A,u/=A);let m=d*u-p*x,v=p*b-w*u,S=w*x-d*b;return A=Math.hypot(m,v,S),A<=1e-5?(m=0,v=0,S=0):(m/=A,v/=A,S/=A),t[0]=b,t[1]=m,t[2]=w,t[3]=0,t[4]=x,t[5]=v,t[6]=d,t[7]=0,t[8]=u,t[9]=S,t[10]=p,t[11]=0,t[12]=-(b*s+x*a+u*o),t[13]=-(m*s+v*a+S*o),t[14]=-(w*s+d*a+p*o),t[15]=1,t}function pe(t,e,i){let r=e[0],s=e[1],a=e[2],o=e[3],n=e[4],l=e[5],h=e[6],c=e[7],f=e[8],g=e[9],w=e[10],d=e[11],p=e[12],A=e[13],b=e[14],x=e[15],u=i[0],m=i[1],v=i[2],S=i[3];return t[0]=u*r+m*n+v*f+S*p,t[1]=u*s+m*l+v*g+S*A,t[2]=u*a+m*h+v*w+S*b,t[3]=u*o+m*c+v*d+S*x,u=i[4],m=i[5],v=i[6],S=i[7],t[4]=u*r+m*n+v*f+S*p,t[5]=u*s+m*l+v*g+S*A,t[6]=u*a+m*h+v*w+S*b,t[7]=u*o+m*c+v*d+S*x,u=i[8],m=i[9],v=i[10],S=i[11],t[8]=u*r+m*n+v*f+S*p,t[9]=u*s+m*l+v*g+S*A,t[10]=u*a+m*h+v*w+S*b,t[11]=u*o+m*c+v*d+S*x,u=i[12],m=i[13],v=i[14],S=i[15],t[12]=u*r+m*n+v*f+S*p,t[13]=u*s+m*l+v*g+S*A,t[14]=u*a+m*h+v*w+S*b,t[15]=u*o+m*c+v*d+S*x,t}function nt(t,e,i,r){let s=e[0],a=e[1],o=e[2],n=e[3],l=s+s,h=a+a,c=o+o,f=s*l,g=s*h,w=s*c,d=a*h,p=a*c,A=o*c,b=n*l,x=n*h,u=n*c,m=r[0],v=r[1],S=r[2];return t[0]=(1-(d+A))*m,t[1]=(g+u)*m,t[2]=(w-x)*m,t[3]=0,t[4]=(g-u)*v,t[5]=(1-(f+A))*v,t[6]=(p+b)*v,t[7]=0,t[8]=(w+x)*S,t[9]=(p-b)*S,t[10]=(1-(f+d))*S,t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1,t}function Ce(t,e,i=0){let r=e[0],s=e[1],a=e[2],o=e[4],n=e[5],l=e[6],h=e[8],c=e[9],f=e[10],g=f*n-l*c,w=-f*o+l*h,d=c*o-n*h,p=r*g+s*w+a*d;return!p||i>0&&(!Number.isFinite(p)||Math.abs(p)<=i)||(p=1/p,t[0]=g*p,t[1]=w*p,t[2]=d*p,t[3]=(-f*s+a*c)*p,t[4]=(f*r-a*h)*p,t[5]=(-c*r+s*h)*p,t[6]=(l*s-a*n)*p,t[7]=(-l*r+a*o)*p,t[8]=(n*r-s*o)*p),t}function or(t,e){let i=e[0],r=e[1],s=e[2],a=e[3],o=e[4],n=e[5],l=e[6],h=e[7],c=e[8],f=e[9],g=e[10],w=e[11],d=e[12],p=e[13],A=e[14],b=e[15],x=i*n-r*o,u=i*l-s*o,m=i*h-a*o,v=r*l-s*n,S=r*h-a*n,_=s*h-a*l,D=c*p-f*d,P=c*A-g*d,N=c*b-w*d,E=f*A-g*p,F=f*b-w*p,L=g*b-w*A,M=x*L-u*F+m*E+v*N-S*P+_*D;return M?(M=1/M,t[0]=(n*L-l*F+h*E)*M,t[1]=(s*F-r*L-a*E)*M,t[2]=(p*_-A*S+b*v)*M,t[3]=(g*S-f*_-w*v)*M,t[4]=(l*N-o*L-h*P)*M,t[5]=(i*L-s*N+a*P)*M,t[6]=(A*m-d*_-b*u)*M,t[7]=(c*_-g*m+w*u)*M,t[8]=(o*F-n*N+h*D)*M,t[9]=(r*N-i*F-a*D)*M,t[10]=(d*S-p*m+b*x)*M,t[11]=(f*m-c*S-w*x)*M,t[12]=(n*P-o*E-l*D)*M,t[13]=(i*E-r*P+s*D)*M,t[14]=(p*u-d*v-A*x)*M,t[15]=(c*v-f*u+g*x)*M,t):null}function en(t,e,i,r,s){let a=s[0]*e+s[4]*i+s[8]*r+s[12],o=s[1]*e+s[5]*i+s[9]*r+s[13],n=s[2]*e+s[6]*i+s[10]*r+s[14],l=s[3]*e+s[7]*i+s[11]*r+s[15],h=l!==0?1/l:1;t[0]=a*h,t[1]=o*h,t[2]=n*h}function ar(t,e,i,r,s,a,o,n,l,h,c,f,g,w,d,p,A=0){let b=h-o,x=c-n,u=f-l,m=g-o,v=w-n,S=d-l,_=s*S-a*v,D=a*m-r*S,P=r*v-s*m,N=b*_+x*D+u*P;if(N>-1e-7&&N<1e-7)return!1;let E=1/N,F=t-o,L=e-n,M=i-l,O=E*(F*_+L*D+M*P);if(O<-A||O>1+A)return!1;let H=L*u-M*x,R=M*b-F*u,C=F*x-L*b,y=E*(r*H+s*R+a*C);if(y<-A||O+y>1+A)return!1;let T=E*(m*H+v*R+S*C);if(T>1e-4&&T<p.distance){p.distance=T,p.point=[t+r*T,e+s*T,i+a*T];let z=x*S-u*v,G=u*m-b*S,B=b*v-x*m,te=Math.hypot(z,G,B)||1;return p.normal=[z/te,G/te,B/te],!0}return!1}function cr(t,e){let i=Array.isArray(t?.nodes)?t.nodes.length:0,r=[];for(let c=0;c<i;c++)r.push(de());if(i===0)return r;let s=new Set;for(let c of t.nodes)if(Array.isArray(c.children))for(let f of c.children)s.add(f);let a=new Set,o=128,n=(c,f,g=0)=>{if(g>o||c<0||c>=i||a.has(c))return;a.add(c);let w=t.nodes[c];if(!w)return;let d=de();if(e&&e[c])d.set(e[c]);else if(w.matrix&&w.matrix.length===16)d.set(w.matrix);else{let A=w.translation||[0,0,0],b=w.rotation||[0,0,0,1],x=w.scale||[1,1,1];nt(d,b,A,x)}let p=r[c];if(f?pe(p,f,d):p.set(d),Array.isArray(w.children))for(let A of w.children)typeof A=="number"&&n(A,p,g+1)},l=[],h=t.scenes&&t.scenes[t.scene!==void 0?t.scene:0];if(h&&Array.isArray(h.nodes))l.push(...h.nodes);else for(let c=0;c<i;c++)s.has(c)||l.push(c);for(let c of l)n(c,null);for(let c=0;c<i;c++)!s.has(c)&&!l.includes(c)&&n(c,null);return r}var hi={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function tn(t,e,i,r){if(!i||i.bufferView===void 0)return null;let s=t.bufferViews?.[i.bufferView];if(!s)return null;let a=Number(i.count??0);if(!Number.isInteger(a)||a<=0)return null;let o=i.componentType??5126,n=hi[o];if(!n)throw new RangeError(`glTF accessor has unsupported componentType ${o}`);let l=n*r,h=s.byteStride&&s.byteStride>0?s.byteStride:l,c=(s.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(c)||c<0||h<l||c+(a-1)*h+l>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(o===5126&&h===l&&c%4===0)return new Float32Array(e,c,a*r);let f=new DataView(e),g=i.normalized===!0,w=new Float32Array(a*r);for(let d=0;d<a;d++){let p=c+d*h;for(let A=0;A<r;A++){let b=p+A*n,x;switch(o){case 5126:x=f.getFloat32(b,!0);break;case 5120:x=f.getInt8(b),g&&(x=Math.max(x/127,-1));break;case 5121:x=f.getUint8(b),g&&(x/=255);break;case 5122:x=f.getInt16(b,!0),g&&(x=Math.max(x/32767,-1));break;case 5123:x=f.getUint16(b,!0),g&&(x/=65535);break;default:x=f.getUint32(b,!0),g&&(x/=4294967295)}w[d*r+A]=x}}return w}function ur(t,e){let i=Number(e.offset?.[0]??0)||0,r=Number(e.offset?.[1]??0)||0,s=Number(e.scale?.[0]??1),a=Number(e.scale?.[1]??1),o=Number(e.rotation??0)||0,n=Math.cos(o),l=Math.sin(o),h=(Number.isFinite(s)?s:1)*n,c=(Number.isFinite(s)?s:1)*l,f=-(Number.isFinite(a)?a:1)*l,g=(Number.isFinite(a)?a:1)*n;for(let w=0;w+1<t.length;w+=2){let d=t[w],p=t[w+1];t[w]=h*d+c*p+i,t[w+1]=f*d+g*p+r}}function bt(t,e,i,r=!0){let s=[],a=null;try{for(let[o,n]of[[35633,e],[35632,i]]){let l=t.createShader(o);if(!l){if(r)throw new Error("Shader allocation failed");return null}if(s.push(l),t.shaderSource(l,n),t.compileShader(l),t.getShaderParameter&&!t.getShaderParameter(l,35713)){if(r)throw new Error(`Shader compile error: ${t.getShaderInfoLog(l)}`);return null}}if(a=t.createProgram(),!a){if(r)throw new Error("Program allocation failed");return null}for(let o of s)t.attachShader(a,o);if(t.linkProgram(a),t.getProgramParameter&&!t.getProgramParameter(a,35714)){let o=r?t.getProgramInfoLog(a):null;if(t.deleteProgram?.(a),a=null,r)throw new Error(`Program link error: ${o}`);return null}return a}finally{for(let o of s)a&&t.detachShader?.(a,o),t.deleteShader?.(o)}}var hr=["neutral","reinhard","none","aces","agx"];function Ge(t){let e=String(t??"").trim().toLowerCase();return hr.includes(e)?e:"neutral"}function di(t){return hr.indexOf(Ge(t))}function fi(t){return new TextDecoder().decode(t)}var dr=ue().decoders;function pi(t,e){dr.set(t.toLowerCase(),e)}function Ke(t){return dr.get(t.toLowerCase())}function fr(t){let e=ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,i=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=i.getUint32(0,!0);if(r!==1179937895){let g=i.getUint8(0);throw g===123||g===32||g===10||g===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 s=i.getUint32(4,!0);if(s!==2)throw new Error(`Unsupported GLB version: ${s}`);let a=i.getUint32(8,!0),o=12,n=null,l=null;for(;o+8<=a&&o+8<=e.byteLength;){let g=i.getUint32(o,!0),w=i.getUint32(o+4,!0),d=o+8;if(d+g>e.byteLength)throw new Error(`Truncated GLB chunk: required ${d+g} bytes, buffer has ${e.byteLength}`);if(w===1313821514){let p=new Uint8Array(e,d,g),A=fi(p);n=JSON.parse(A,(b,x)=>b==="__proto__"||b==="constructor"||b==="prototype"?void 0:x)}else w===5130562&&(l=e.slice(d,d+g));o=d+g}if(!n)throw new Error("Missing JSON chunk in GLB");let h=n.extensionsRequired||[];if(h.includes("KHR_draco_mesh_compression")&&!Ke("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let g of["EXT_meshopt_compression","KHR_meshopt_compression"])if(h.includes(g)&&!Ke("meshopt"))throw new Error(`Model requires ${g}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(h.includes("KHR_texture_basisu")&&!Ke("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let c=l||new ArrayBuffer(0),f={gltf:n,bin:c,animations:[]};for(let g of he)g.onParseGLB?.(f);return f}function bi(t){return typeof t=="object"&&t!==null&&"gltf"in t&&typeof t.gltf=="object"&&t.gltf!==null&&"bin"in t&&(t.bin instanceof ArrayBuffer||ArrayBuffer.isView(t.bin))}function Ue(t){if(bi(t))return t;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return fr(t);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var pr=`#version 300 es
|
|
16
|
+
*/var ln=Object.defineProperty,xi=Object.getOwnPropertyDescriptor,vi=Object.getOwnPropertyNames,Si=Object.prototype.hasOwnProperty,wi=(t,e)=>{for(var i in e)ln(t,i,{get:e[i],enumerable:!0})},Mi=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vi(e))!Si.call(t,n)&&n!==i&&ln(t,n,{get:()=>e[n],enumerable:!(r=xi(e,n))||r.enumerable});return t},Ai=t=>Mi(ln({},"__esModule",{value:!0}),t),Ms={};wi(Ms,{THREE:()=>tt,ThreeLiveElement:()=>Be,ThreeView:()=>_e,activateAR:()=>on,createUSDZBlob:()=>rt,defineModelViewer:()=>pi,evaluateToneMapping:()=>kr,getARCapabilities:()=>sn,getBestARMode:()=>yi,isQuickLookSupported:()=>vr,isSceneViewerSupported:()=>Sr,isWebXRSupported:()=>wr,toGLBData:()=>Xe}),module.exports=Ai(Ms);var St="__THREE_LIVE_REGISTRY__";function ue(){let t=typeof globalThis<"u"?globalThis:{};if(!t[St]){let e={plugins:[],decoders:new Map};try{Object.defineProperty(t,St,{value:e,writable:!1,configurable:!1,enumerable:!1})}catch{t[St]=e}}return t[St]}var ge=ue().plugins;function wt(t){let e=ue().plugins;e.some(i=>i.name===t.name)||e.push(t),t.onRegister?.()}function Mr(){return ue().plugins}var Ri=`#version 300 es
|
|
17
|
+
layout(location=0) in vec3 aPosition;layout(location=1) in vec2 aUV;uniform mat4 uMVP;out vec2 vUV;void main(){vUV=aUV;gl_Position=uMVP*vec4(aPosition,1.);}`,Ti=`#version 300 es
|
|
18
|
+
precision highp float;in vec2 vUV;uniform float uShadowIntensity,uShadowSoftness;out vec4 fragColor;void main(){vec2 p=(vUV-.5)*2.;float d=clamp(length(p),0.,1.);fragColor=vec4(0.,0.,0.,pow(1.-d*d,mix(1.2,2.8,uShadowSoftness))*smoothstep(1.,.85-uShadowSoftness*.6,d)*uShadowIntensity);}`,ot=new WeakMap,Ar=new Float32Array(20);function mn(t,e){let[i,r,n,s,a,o]=e;return[t[0]*i+t[4]*r+t[8]*n+t[12],t[1]*i+t[5]*r+t[9]*n+t[13],t[2]*i+t[6]*r+t[10]*n+t[14],Math.abs(t[0])*s+Math.abs(t[4])*a+Math.abs(t[8])*o,Math.abs(t[1])*s+Math.abs(t[5])*a+Math.abs(t[9])*o,Math.abs(t[2])*s+Math.abs(t[6])*a+Math.abs(t[10])*o]}function _i(t){if(t._lb!==void 0)return t._lb;let e=1e9,i=1e9,r=1e9,n=-1e9,s=-1e9,a=-1e9;for(let o of t.primitives||[]){let l=o.positions;if(l)for(let m=0;m<l.length;m+=3)l[m]<e&&(e=l[m]),l[m+1]<i&&(i=l[m+1]),l[m+2]<r&&(r=l[m+2]),l[m]>n&&(n=l[m]),l[m+1]>s&&(s=l[m+1]),l[m+2]>a&&(a=l[m+2])}return t._lb=e<=n?[(e+n)*.5,(i+s)*.5,(r+a)*.5,(n-e)*.5,(s-i)*.5,(a-r)*.5]:null}function Ei(t){let e=ot.get(t);if(e)return e;let i=(o,l)=>{let m=t.createShader(o);return t.shaderSource(m,l),t.compileShader(m),m},r=t.createProgram();t.attachShader(r,i(35633,Ri)),t.attachShader(r,i(35632,Ti)),t.linkProgram(r);let n=t.createVertexArray(),s=t.createBuffer(),a=t.createBuffer();return t.bindVertexArray(n),t.bindBuffer(34962,s),t.bufferData(34962,80,35048),t.enableVertexAttribArray(0),t.vertexAttribPointer(0,3,5126,!1,20,0),t.enableVertexAttribArray(1),t.vertexAttribPointer(1,2,5126,!1,20,12),t.bindBuffer(34963,a),t.bufferData(34963,new Uint16Array([0,1,2,0,2,3]),35044),t.bindVertexArray(null),e={prog:r,vao:n,vbo:s,ibo:a,uMVP:t.getUniformLocation(r,"uMVP"),uIntensity:t.getUniformLocation(r,"uShadowIntensity"),uSoftness:t.getUniformLocation(r,"uShadowSoftness")},ot.set(t,e),e}var Rr={name:"contact-shadow",onContextRestored(t){ot.delete(t)},onAfterRender(t,e,i){let r=e.shadowIntensity;if(r<=0||!e.bounds)return;let n=Ei(t),s=!e.xrSessionActive&&(e.backdropMeshes?.length??0)>0,a=[],o=[];for(let x of e.meshes||[]){if(!x||x.visible===!1||x.isPluginMesh||x.name==="__xr_reticle__"||x.name?.startsWith("__xr_slot_"))continue;let g=_i(x);if(!g)continue;x.transform&&(g=mn(x.transform,g)),e.modelRootMatrix&&(g=mn(e.modelRootMatrix,g));let[c,u,y,f,w,M]=g,S=[c,y,f,M,u-w,u+w];/floor|table|pedestal|ground|base|plane/i.test(x.name||"")||w<.14&&Math.min(f,M)>.45?o.push(S):a.push(S)}let l=[],m=e.bounds.center||[0,0,0],p=Math.max(.05,Number(e.bounds.radius)||.5),v=e.bounds.min,h=v?[m[0],m[1],m[2],p,Math.max(.01,m[1]-v[1]),p]:[m[0],m[1],m[2],p,p,p];e.modelRootMatrix&&(h=mn(e.modelRootMatrix,h));let b=e.xrSessionActive&&o.length===0&&String(e.container?.tagName||"").toLowerCase()==="xr-live"?(e.modelRootMatrix?e.modelRootMatrix[5]*-.25+e.modelRootMatrix[13]:-.25)+.002:h[1]-h[4]+.002;for(let[x,g,c,u,y]of a){let f=-1/0;for(let[M,S,L,P,,C]of o)y>=C-.08&&Math.abs(x-M)<=L&&Math.abs(g-S)<=P&&C+.002>f&&(f=C+.002);s&&(f=Math.max(f,x>=.04&&x<=.36&&g>=-.34&&g<=-.04&&y>=.01?.036:Math.hypot(x,g)<=.66&&y>=-.06?.003:-.477)),isFinite(f)||(f=b);let w=l.find(M=>Math.hypot(x-M[0],g-M[1])<.06&&Math.abs(f-M[5])<.05);w?(w[2]=Math.max(w[2],c*.78),w[3]=Math.max(w[3],u*.78),w[4]=Math.min(w[4],y)):l.push([x,g,c,u,y,f])}if(l.length===0){let x=Math.max(.1,h[3]*1.5)/1.45;l.push([h[0],h[2],x,x,b,b])}t.useProgram(n.prog),t.uniformMatrix4fv(n.uMVP,!1,i),t.enable(3042),(t.blendFuncSeparate||t.blendFunc).call(t,770,771,1,771),t.depthMask(!1),t.bindVertexArray(n.vao),t.bindBuffer(34962,n.vbo);for(let[x,g,c,u,y,f]of l){let w=Math.max(0,y-f),M=r/(1+w*2);if(M<.02)continue;let S=1+Math.min(.75,w*.85),L=Math.max(.045,c*1.45*S),P=Math.max(.045,u*1.45*S);Ar.set([x-L,f,g-P,0,0,x+L,f,g-P,1,0,x+L,f,g+P,1,1,x-L,f,g+P,0,1]),t.bufferSubData(34962,0,Ar),t.uniform1f(n.uIntensity,M),t.uniform1f(n.uSoftness,Math.min(1,e.shadowSoftness+Math.min(.45,w*.6))),t.drawElements(4,6,5123,0)}t.bindVertexArray(null),t.depthMask(!0),t.disable(3042)},onDestroy(t){let e=ot.get(t);e&&(t.deleteVertexArray(e.vao),t.deleteBuffer(e.vbo),t.deleteBuffer(e.ibo),t.deleteProgram(e.prog),ot.delete(t))}};function Tr(t,e,i){let r=[],n=new Map,s=[],a=[],o=[],l=new Map,m=f=>{let w=n.get(f);return w===void 0&&(w=r.length,r.push({op:f}),n.set(f,w)),w},p=f=>{let w=l.get(f);return w===void 0&&(w=o.length,o.push({id:f}),l.set(f,w)),w},v=(f,w={})=>s.push({declaration:m(f),...w})-1,h=(f,w,M)=>a.push({id:f,type:w,value:M})-1,b=f=>({node:f,socket:"value"}),x=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(x&&typeof x=="object"){let f=Array.isArray(x.graphs)?x.graphs[x.graph??0]:x;if(f&&Array.isArray(f.nodes)){let w=Array.isArray(f.declarations)?f.declarations:[];for(let M of w)M?.op&&m(M.op);Array.isArray(f.variables)&&a.push(...f.variables);for(let M of f.events||[])M?.id&&p(M.id);for(let M of f.nodes){if(!M||typeof M!="object")continue;let S=M.op||(typeof M.declaration=="number"?w[M.declaration]?.op:"");s.push(S?{...M,declaration:m(S)}:{...M})}}}let g=(f,w,M="translation")=>M==="baseColorFactor"||M==="metallicFactor"||M==="roughnessFactor"?`/materials/${Math.max(0,w)}/pbrMetallicRoughness/${M}`:M==="emissiveFactor"||M==="alphaCutoff"?`/materials/${Math.max(0,w)}/${M}`:M==="visible"?`/nodes/${f}/extensions/KHR_node_visibility/visible`:`/nodes/${f}/${M}`,c=new Map;t.forEach((f,w)=>{typeof f?.name=="string"&&!c.has(f.name)&&c.set(f.name,w)});let u=(f,w)=>typeof f.target=="string"&&c.has(f.target)?c.get(f.target):typeof f.targetNode=="number"?f.targetNode:w,y=f=>{let w=t[f];return(typeof w?.mesh=="number"?e[w.mesh]?.primitives?.[0]?.material:0)??0};for(let f=0;f<t.length;f++){let w=t[f],M=w?.extras?.interactivity;if(!M||typeof M!="object")continue;let S=(typeof w.mesh=="number"?e[w.mesh]?.primitives?.[0]?.material:0)??0,L=C=>{let R=Array.isArray(C)?C:[C],A=[];for(let D=0;D<R.length;D++){let E=R[D];if(!E||typeof E!="object")continue;let k=E.action||"interpolate",I=typeof E.duration=="number"?E.duration:.35;if(k==="toggleTransform"){let $=E.property==="rotation"||E.property==="scale"?E.property:"translation",N=$==="rotation"?w.rotation||[0,0,0,1]:$==="scale"?w.scale||[1,1,1]:w.translation||[0,0,0],U=`/nodes/${f}/${$}`,d=h(`__toggle_${f}_${D}`,"bool",!1),F=v("variable/get",{configuration:{variable:d}}),_=v("math/not",{values:{a:b(F)}}),O=v("variable/set",{configuration:{variable:d},values:{value:b(_)}}),q=v("pointer/interpolate",{configuration:{pointer:U},values:{value:{value:Array.isArray(E.to)?E.to:N},duration:{value:I}}}),z=v("pointer/interpolate",{configuration:{pointer:U},values:{value:{value:Array.isArray(E.from)?E.from:N},duration:{value:I}}});s[O].flows={out:{node:v("flow/branch",{values:{condition:b(F)},flows:{true:{node:q},false:{node:z}}})}},A.push(O)}else if(k==="interpolate"){let $=E.to??E.value;if($===void 0)continue;let N={value:{value:$},duration:{value:I}};E.from!==void 0&&(N.from={value:E.from}),A.push(v("pointer/interpolate",{configuration:{pointer:typeof E.pointer=="string"?E.pointer:g(u(E,f),y(u(E,f)),E.property)},values:N}))}else if(k==="setProperty"){if(E.value===void 0)continue;A.push(v("pointer/set",{configuration:{pointer:typeof E.pointer=="string"?E.pointer:g(u(E,f),y(u(E,f)),E.property)},values:{value:{value:E.value}}}))}else if(k==="toggleVisibility"){let $=u(E,f),N=h(`__vis_${$}_${D}`,"bool",!0),U=v("variable/get",{configuration:{variable:N}}),d=v("math/not",{values:{a:b(U)}}),F=v("variable/set",{configuration:{variable:N},values:{value:b(d)}});s[F].flows={out:{node:v("pointer/set",{configuration:{pointer:`/nodes/${$}/extensions/KHR_node_visibility/visible`},values:{value:b(U)}})}},A.push(F)}else if(k==="cycleMaterialColor"&&Array.isArray(E.colors)&&E.colors.length>0){let $=typeof E.duration=="number"?E.duration:.25,N=`/materials/${Math.max(0,S)}/pbrMetallicRoughness/baseColorFactor`,U=h(`__color_idx_${f}_${D}`,"int",0),d=v("variable/get",{configuration:{variable:U}}),F=v("math/add",{values:{a:b(d),b:{value:1}}}),_=v("math/rem",{values:{a:b(F),b:{value:E.colors.length}}}),O=v("variable/set",{configuration:{variable:U},values:{value:b(_)}}),q={};for(let z=0;z<E.colors.length;z++){let W=E.colors[z],X=Array.isArray(W)&&W.length>=3?[W[0],W[1],W[2],W[3]??1]:[1,1,1,1];q[String(z)]={node:$>0?v("pointer/interpolate",{configuration:{pointer:N},values:{value:{value:X},duration:{value:$}}}):v("pointer/set",{configuration:{pointer:N},values:{value:{value:X}}})}}s[O].flows={out:{node:v("flow/switch",{values:{selection:b(d)},flows:q})}},A.push(O)}else if(k==="playAnimation")A.push(v("animation/start",{configuration:{animation:E.animation??E.clip??0}}));else if(k==="stopAnimation")A.push(v("animation/stop"));else if(k==="sendEvent"){let $={};for(let[N,U]of Object.entries(E.values||{}))$[N]={value:U};A.push(v("event/send",{configuration:{event:p(String(E.event??E.id??"custom"))},values:$}))}}if(!A.length)return null;if(A.length===1)return A[0];let T={};return A.forEach((D,E)=>{T[String(E)]={node:D}}),v("flow/sequence",{flows:T})},P=(C,R,A)=>{let T=L(R);T!==null&&v(C,{...A?{configuration:A}:{},flows:{out:{node:T}}})};if(M.onSelect&&P("pointer/onSelect",M.onSelect,{nodeIndex:f}),M.onHoverIn&&P("pointer/onHoverIn",M.onHoverIn,{nodeIndex:f}),M.onHoverOut&&P("pointer/onHoverOut",M.onHoverOut,{nodeIndex:f}),M.onStart&&P("event/onStart",M.onStart),M.onReceive&&typeof M.onReceive=="object")for(let[C,R]of Object.entries(M.onReceive))P("event/receive",R,{event:p(C)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:a,events:o}],graph:0}:null}var Mt='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).',At="Security Error: client-side scripts require allow-client-scripts opt-in.";function we(){let t=new Float32Array(16);return t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function dn(t,e,i,r,n){let s=1/Math.tan(e/2);t.fill(0),t[0]=s/i,t[5]=s,t[11]=-1;let a=1/(r-n);return t[10]=(n+r)*a,t[14]=2*n*r*a,t}function at(t,e,i,r){let[n,s,a]=e,[o,l,m]=r,[p,v,h]=i,b=n-p,x=s-v,g=a-h,c=Math.hypot(b,x,g);c<=1e-5?(b=0,x=0,g=1):(b/=c,x/=c,g/=c);let u=l*g-m*x,y=m*b-o*g,f=o*x-l*b;c=Math.hypot(u,y,f),c<=1e-5?(u=0,y=0,f=0):(u/=c,y/=c,f/=c);let w=x*f-g*y,M=g*u-b*f,S=b*y-x*u;return c=Math.hypot(w,M,S),c<=1e-5?(w=0,M=0,S=0):(w/=c,M/=c,S/=c),t[0]=u,t[1]=w,t[2]=b,t[3]=0,t[4]=y,t[5]=M,t[6]=x,t[7]=0,t[8]=f,t[9]=S,t[10]=g,t[11]=0,t[12]=-(u*n+y*s+f*a),t[13]=-(w*n+M*s+S*a),t[14]=-(b*n+x*s+g*a),t[15]=1,t}function xe(t,e,i){let r=e[0],n=e[1],s=e[2],a=e[3],o=e[4],l=e[5],m=e[6],p=e[7],v=e[8],h=e[9],b=e[10],x=e[11],g=e[12],c=e[13],u=e[14],y=e[15],f=i[0],w=i[1],M=i[2],S=i[3];return t[0]=f*r+w*o+M*v+S*g,t[1]=f*n+w*l+M*h+S*c,t[2]=f*s+w*m+M*b+S*u,t[3]=f*a+w*p+M*x+S*y,f=i[4],w=i[5],M=i[6],S=i[7],t[4]=f*r+w*o+M*v+S*g,t[5]=f*n+w*l+M*h+S*c,t[6]=f*s+w*m+M*b+S*u,t[7]=f*a+w*p+M*x+S*y,f=i[8],w=i[9],M=i[10],S=i[11],t[8]=f*r+w*o+M*v+S*g,t[9]=f*n+w*l+M*h+S*c,t[10]=f*s+w*m+M*b+S*u,t[11]=f*a+w*p+M*x+S*y,f=i[12],w=i[13],M=i[14],S=i[15],t[12]=f*r+w*o+M*v+S*g,t[13]=f*n+w*l+M*h+S*c,t[14]=f*s+w*m+M*b+S*u,t[15]=f*a+w*p+M*x+S*y,t}function ct(t,e,i,r){let n=e[0],s=e[1],a=e[2],o=e[3],l=n+n,m=s+s,p=a+a,v=n*l,h=n*m,b=n*p,x=s*m,g=s*p,c=a*p,u=o*l,y=o*m,f=o*p,w=r[0],M=r[1],S=r[2];return t[0]=(1-(x+c))*w,t[1]=(h+f)*w,t[2]=(b-y)*w,t[3]=0,t[4]=(h-f)*M,t[5]=(1-(v+c))*M,t[6]=(g+u)*M,t[7]=0,t[8]=(b+y)*S,t[9]=(g-u)*S,t[10]=(1-(v+x))*S,t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1,t}function Fe(t,e,i=0){let r=e[0],n=e[1],s=e[2],a=e[4],o=e[5],l=e[6],m=e[8],p=e[9],v=e[10],h=v*o-l*p,b=-v*a+l*m,x=p*a-o*m,g=r*h+n*b+s*x;return!g||i>0&&(!Number.isFinite(g)||Math.abs(g)<=i)||(g=1/g,t[0]=h*g,t[1]=b*g,t[2]=x*g,t[3]=(-v*n+s*p)*g,t[4]=(v*r-s*m)*g,t[5]=(-p*r+n*m)*g,t[6]=(l*n-s*o)*g,t[7]=(-l*r+s*a)*g,t[8]=(o*r-n*a)*g),t}function _r(t,e){let i=e[0],r=e[1],n=e[2],s=e[3],a=e[4],o=e[5],l=e[6],m=e[7],p=e[8],v=e[9],h=e[10],b=e[11],x=e[12],g=e[13],c=e[14],u=e[15],y=i*o-r*a,f=i*l-n*a,w=i*m-s*a,M=r*l-n*o,S=r*m-s*o,L=n*m-s*l,P=p*g-v*x,C=p*c-h*x,R=p*u-b*x,A=v*c-h*g,T=v*u-b*g,D=h*u-b*c,E=y*D-f*T+w*A+M*R-S*C+L*P;return E?(E=1/E,t[0]=(o*D-l*T+m*A)*E,t[1]=(n*T-r*D-s*A)*E,t[2]=(g*L-c*S+u*M)*E,t[3]=(h*S-v*L-b*M)*E,t[4]=(l*R-a*D-m*C)*E,t[5]=(i*D-n*R+s*C)*E,t[6]=(c*w-x*L-u*f)*E,t[7]=(p*L-h*w+b*f)*E,t[8]=(a*T-o*R+m*P)*E,t[9]=(r*R-i*T-s*P)*E,t[10]=(x*S-g*w+u*y)*E,t[11]=(v*w-p*S-b*y)*E,t[12]=(o*C-a*A-l*P)*E,t[13]=(i*A-r*C+n*P)*E,t[14]=(g*f-x*M-c*y)*E,t[15]=(p*M-v*f+h*y)*E,t):null}function fn(t,e,i,r,n){let s=n[0]*e+n[4]*i+n[8]*r+n[12],a=n[1]*e+n[5]*i+n[9]*r+n[13],o=n[2]*e+n[6]*i+n[10]*r+n[14],l=n[3]*e+n[7]*i+n[11]*r+n[15],m=l!==0?1/l:1;t[0]=s*m,t[1]=a*m,t[2]=o*m}function Er(t,e,i,r,n,s,a,o,l,m,p,v,h,b,x,g,c=0){let u=m-a,y=p-o,f=v-l,w=h-a,M=b-o,S=x-l,L=n*S-s*M,P=s*w-r*S,C=r*M-n*w,R=u*L+y*P+f*C;if(R>-1e-7&&R<1e-7)return!1;let A=1/R,T=t-a,D=e-o,E=i-l,k=A*(T*L+D*P+E*C);if(k<-c||k>1+c)return!1;let I=D*f-E*y,$=E*u-T*f,N=T*y-D*u,U=A*(r*I+n*$+s*N);if(U<-c||k+U>1+c)return!1;let d=A*(w*I+M*$+S*N);if(d>1e-4&&d<g.distance){g.distance=d,g.point=[t+r*d,e+n*d,i+s*d];let F=y*S-f*M,_=f*w-u*S,O=u*M-y*w,q=Math.hypot(F,_,O)||1;return g.normal=[F/q,_/q,O/q],!0}return!1}function pn(t,e){let i=Array.isArray(t?.nodes)?t.nodes.length:0,r=[];for(let p=0;p<i;p++)r.push(we());if(i===0)return r;let n=new Set;for(let p of t.nodes)if(Array.isArray(p.children))for(let v of p.children)n.add(v);let s=new Set,a=128,o=(p,v,h=0)=>{if(h>a||p<0||p>=i||s.has(p))return;s.add(p);let b=t.nodes[p];if(!b)return;let x=we();if(e&&e[p])x.set(e[p]);else if(b.matrix&&b.matrix.length===16)x.set(b.matrix);else{let c=b.translation||[0,0,0],u=b.rotation||[0,0,0,1],y=b.scale||[1,1,1];ct(x,u,c,y)}let g=r[p];if(v?xe(g,v,x):g.set(x),Array.isArray(b.children))for(let c of b.children)typeof c=="number"&&o(c,g,h+1)},l=[],m=t.scenes&&t.scenes[t.scene!==void 0?t.scene:0];if(m&&Array.isArray(m.nodes))l.push(...m.nodes);else for(let p=0;p<i;p++)n.has(p)||l.push(p);for(let p of l)o(p,null);for(let p=0;p<i;p++)!n.has(p)&&!l.includes(p)&&o(p,null);return r}function bn(t){if(typeof t!="function")return null;let e=new Uint32Array(256);for(let h=0;h<256;h++){let b=h;for(let x=0;x<8;x++)b=b&1?3988292384^b>>>1:b>>>1;e[h]=b>>>0}let i=(h,b,x)=>{let g=4294967295;for(let c=b;c<x;c++)g=e[(g^h[c])&255]^g>>>8;return(g^4294967295)>>>0},r=(h,b)=>(h[b]<<24|h[b+1]<<16|h[b+2]<<8|h[b+3])>>>0,n=(h,b,x)=>{h[b]=x>>>24,h[b+1]=x>>>16&255,h[b+2]=x>>>8&255,h[b+3]=x&255},s=h=>{let b=new t("deflate"),x=b.writable.getWriter();x.write(h).catch(()=>{}),x.close().catch(()=>{});let g=b.readable.getReader(),c=[],u=0,y=()=>g.read().then(f=>{if(f.done){let w=new Uint8Array(u),M=0;for(let S=0;S<c.length;S++)w.set(c[S],M),M+=c[S].length;return w}return f.value&&(c.push(f.value),u+=f.value.length),y()});return y()},a=h=>{if(h.length<45||r(h,0)!==2303741511||r(h,12)!==1229472850)return null;let b=r(h,16),x=r(h,20);if(h[24]!==8||h[25]!==6||h[28]!==0||!b||!x||b>4096||x>4096)return null;let g=1+b*4,c=new Uint8Array(g*x),u=0,y=33,f=-2,w=0,M=[],S=!1;for(;y+8<=h.length&&!S;){let L=r(h,y),P=r(h,y+4),C=y+8,R=C+L;if(R+4>h.length)return null;if(P===1229209940)for(let A=C;A<R&&!S;){if(f<0)f++,A++;else if(w>0){let T=Math.min(w,R-A);if(u+T>c.length)return null;c.set(h.subarray(A,A+T),u),u+=T,A+=T,w-=T,w===0&&M[0]&1&&(S=!0)}else{if(M.push(h[A++]),M.length===1&&M[0]>>1&3)return null;if(M.length===5){let T=M[1]|M[2]<<8;if((T^(M[3]|M[4]<<8))!==65535)return null;w=T,T===0&&(M[0]&1&&(S=!0),M=[])}}w===0&&M.length===5&&(M=[])}else if(P===1229278788)break;y=R+4}if(u!==c.length)return null;for(let L=0;L<x;L++)if(c[L*g]!==0)return null;return{w:b,h:x,raw:c}},o=(h,b,x)=>{let g=b*4,c=g+1,u=new Uint8Array(h.length),y=new Uint8Array(g),f=new Uint8Array(g);for(let w=0;w<x;w++){let M=w*c+1,S=M-c,L=0,P=1/0;for(let C=0;C<5;C++){if(C===3||(C===2||C===4)&&w===0)continue;let R=0;for(let A=0;A<g;A++){let T=A>=4?h[M+A-4]:0,D=w>0?h[S+A]:0,E=0;if(C===1)E=T;else if(C===2)E=D;else if(C===4){let I=A>=4&&w>0?h[S+A-4]:0,$=T+D-I,N=Math.abs($-T),U=Math.abs($-D),d=Math.abs($-I);E=N<=U&&N<=d?T:U<=d?D:I}let k=h[M+A]-E&255;y[A]=k,R+=k<128?k:256-k}R<P&&(P=R,L=C,f.set(y))}u[w*c]=L,u.set(f,M)}return u},l=h=>{let b=null;try{b=a(h)}catch{b=null}if(!b)return Promise.resolve(h);let{w:x,h:g,raw:c}=b;return s(o(c,x,g)).then(u=>{let y=45+u.length+12;if(y>=h.length)return h;let f=new Uint8Array(y);f.set(h.subarray(0,33),0),n(f,33,u.length),n(f,37,1229209940),f.set(u,41),n(f,41+u.length,i(f,37,41+u.length));let w=45+u.length;return n(f,w,0),n(f,w+4,1229278788),n(f,w+8,2923585666),f},()=>h)},m=new Int16Array(128).fill(-1),p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let h=0;h<64;h++)m[p.charCodeAt(h)]=h;let v=h=>{let b=h.length;for(;b>0&&h.charCodeAt(b-1)===61;)b--;let x=new Uint8Array(Math.floor(b*3/4)),g=0,c=0,u=0;for(let y=0;y<b;y++){let f=h.charCodeAt(y),w=f<128?m[f]:-1;if(w<0)return null;g=(g<<6|w)&16777215,c+=6,c>=8&&(c-=8,x[u++]=g>>c&255)}return u===x.length?x:null};return{png:l,glb:h=>{let b=(A,T)=>(A[T]|A[T+1]<<8|A[T+2]<<16|A[T+3]<<24)>>>0,x=(A,T,D)=>{A[T]=D&255,A[T+1]=D>>>8&255,A[T+2]=D>>>16&255,A[T+3]=D>>>24},g,c=new Uint8Array(0);try{if(h.length<20||b(h,0)!==1179937895)return Promise.resolve(h);let A=Math.min(h.length,b(h,8)),T=b(h,12);if(b(h,16)!==1313821514||20+T>A)return Promise.resolve(h);g=JSON.parse(new TextDecoder().decode(h.subarray(20,20+T)));let D=20+T;if(D+8<=A){let E=b(h,D);if(b(h,D+4)!==5130562||D+8+E>A)return Promise.resolve(h);c=h.subarray(D+8,D+8+E)}}catch{return Promise.resolve(h)}if(!g||typeof g!="object")return Promise.resolve(h);let u=Array.isArray(g.bufferViews)?g.bufferViews:[],y=Array.isArray(g.images)?g.images:[],f=[],w=[],M=[],S="data:image/png;base64,";for(let A=0;A<y.length;A++){let T=y[A];if(!T||typeof T!="object")continue;let D=u[T.bufferView];if(typeof T.uri=="string"&&T.uri.indexOf(S)===0){let E=v(T.uri.slice(S.length));E&&(w.push(A),M.push(E))}else T.mimeType==="image/png"&&D&&(D.buffer||0)===0&&f.indexOf(T.bufferView)<0&&f.push(T.bufferView)}if(!f.length&&!w.length)return Promise.resolve(h);let L=[];for(let A=0;A<u.length;A++)L.push(A);L.sort((A,T)=>(u[A].byteOffset||0)-(u[T].byteOffset||0));let P=0;for(let A=0;A<L.length;A++){let T=u[L[A]],D=T.byteOffset||0;if(typeof T.byteLength!="number"||(T.buffer||0)!==0||D<P||D+T.byteLength>c.length)return Promise.resolve(h);P=D+T.byteLength}let C=A=>{let T=u[A].byteOffset||0;return c.subarray(T,T+u[A].byteLength)},R=[];for(let A=0;A<f.length;A++)R.push(l(C(f[A])));for(let A=0;A<M.length;A++)R.push(l(M[A]));return Promise.all(R).then(A=>{let T=[];for(let d=0;d<u.length;d++){let F=f.indexOf(d);T.push(F>=0?A[F]:C(d))}let D=0;for(let d=0;d<L.length;d++)D=(D+3&-4)+T[L[d]].length;for(let d=0;d<w.length;d++)D=(D+3&-4)+A[f.length+d].length;let E=D+3&-4,k=new Uint8Array(E),I=0;for(let d=0;d<L.length;d++){let F=L[d];I=I+3&-4,k.set(T[F],I),u[F].byteOffset=I,u[F].byteLength=T[F].length,I+=T[F].length}for(let d=0;d<w.length;d++){let F=A[f.length+d];I=I+3&-4,k.set(F,I);let _=y[w[d]];delete _.uri,_.mimeType="image/png",_.bufferView=u.length,u.push({buffer:0,byteOffset:I,byteLength:F.length}),I+=F.length}g.bufferViews=u,!Array.isArray(g.buffers)||!g.buffers.length?g.buffers=[{byteLength:E}]:g.buffers[0].byteLength=E;let $=new TextEncoder().encode(JSON.stringify(g)),N=$.length+3&-4;if(N!==$.length){let d=new Uint8Array(N).fill(32);d.set($),$=d}let U=new Uint8Array(20+N+8+E);return x(U,0,1179937895),x(U,4,2),x(U,8,U.length),x(U,12,N),x(U,16,1313821514),U.set($,20),x(U,20+N,E),x(U,24+N,5130562),U.set(k,28+N),U.length<h.length?U:h})}}}var Li={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function gn(t,e,i,r){if(!i||i.bufferView===void 0)return null;let n=t.bufferViews?.[i.bufferView];if(!n)return null;let s=Number(i.count??0);if(!Number.isInteger(s)||s<=0)return null;let a=i.componentType??5126,o=Li[a];if(!o)throw new RangeError(`glTF accessor has unsupported componentType ${a}`);let l=o*r,m=n.byteStride&&n.byteStride>0?n.byteStride:l,p=(n.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(p)||p<0||m<l||p+(s-1)*m+l>e.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${e.byteLength} bytes)`);if(a===5126&&m===l&&p%4===0)return new Float32Array(e,p,s*r);let v=new DataView(e),h=i.normalized===!0,b=new Float32Array(s*r);for(let x=0;x<s;x++){let g=p+x*m;for(let c=0;c<r;c++){let u=g+c*o,y;switch(a){case 5126:y=v.getFloat32(u,!0);break;case 5120:y=v.getInt8(u),h&&(y=Math.max(y/127,-1));break;case 5121:y=v.getUint8(u),h&&(y/=255);break;case 5122:y=v.getInt16(u,!0),h&&(y=Math.max(y/32767,-1));break;case 5123:y=v.getUint16(u,!0),h&&(y/=65535);break;default:y=v.getUint32(u,!0),h&&(y/=4294967295)}b[x*r+c]=y}}return b}function Lr(t,e){let i=Number(e.offset?.[0]??0)||0,r=Number(e.offset?.[1]??0)||0,n=Number(e.scale?.[0]??1),s=Number(e.scale?.[1]??1),a=Number(e.rotation??0)||0,o=Math.cos(a),l=Math.sin(a),m=(Number.isFinite(n)?n:1)*o,p=(Number.isFinite(n)?n:1)*l,v=-(Number.isFinite(s)?s:1)*l,h=(Number.isFinite(s)?s:1)*o;for(let b=0;b+1<t.length;b+=2){let x=t[b],g=t[b+1];t[b]=m*x+p*g+i,t[b+1]=v*x+h*g+r}}function ut(t,e,i,r=!0){let n=[],s=null;try{for(let[a,o]of[[35633,e],[35632,i]]){let l=t.createShader(a);if(!l){if(r)throw new Error("Shader allocation failed");return null}if(n.push(l),t.shaderSource(l,o),t.compileShader(l),t.getShaderParameter&&!t.getShaderParameter(l,35713)){if(r)throw new Error(`Shader compile error: ${t.getShaderInfoLog(l)}`);return null}}if(s=t.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let a of n)t.attachShader(s,a);if(t.linkProgram(s),t.getProgramParameter&&!t.getProgramParameter(s,35714)){let a=r?t.getProgramInfoLog(s):null;if(t.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${a}`);return null}return s}finally{for(let a of n)s&&t.detachShader?.(s,a),t.deleteShader?.(a)}}var Dr=["neutral","reinhard","none","aces","agx"];function Ke(t){let e=String(t??"").trim().toLowerCase();return Dr.includes(e)?e:"neutral"}function Ci(t){return Dr.indexOf(Ke(t))}function Di(t){return new TextDecoder().decode(t)}var Pr=ue().decoders;function Pi(t,e){Pr.set(t.toLowerCase(),e)}function Et(t){return Pr.get(t.toLowerCase())}function Ir(t){let e=ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,i=new DataView(e);if(e.byteLength<12)throw new Error(`Invalid GLB buffer size: ${e.byteLength} bytes`);let r=i.getUint32(0,!0);if(r!==1179937895){let h=i.getUint8(0);throw h===123||h===32||h===10||h===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 n=i.getUint32(4,!0);if(n!==2)throw new Error(`Unsupported GLB version: ${n}`);let s=i.getUint32(8,!0),a=12,o=null,l=null;for(;a+8<=s&&a+8<=e.byteLength;){let h=i.getUint32(a,!0),b=i.getUint32(a+4,!0),x=a+8;if(x+h>e.byteLength)throw new Error(`Truncated GLB chunk: required ${x+h} bytes, buffer has ${e.byteLength}`);if(b===1313821514){let g=new Uint8Array(e,x,h),c=Di(g);o=JSON.parse(c,(u,y)=>u==="__proto__"||u==="constructor"||u==="prototype"?void 0:y)}else b===5130562&&(l=e.slice(x,x+h));a=x+h}if(!o)throw new Error("Missing JSON chunk in GLB");let m=o.extensionsRequired||[];for(let[h,b]of[["KHR_draco_mesh_compression","draco"],["EXT_meshopt_compression","meshopt"],["KHR_meshopt_compression","meshopt"],["KHR_texture_basisu","ktx2"]])if(m.includes(h)&&!Et(b))throw new Error(`Model requires ${h}. Register a decoder via ThreeLiveElement.registerDecoder('${b}', decoder).`);let p=l||new ArrayBuffer(0),v={gltf:o,bin:p,animations:[],animationsParsed:!1};for(let h of ge)h.onParseGLB?.(v);return v}function wn(t,e=pn(t)){let i=t?.extensions?.KHR_lights_punctual?.lights;if(!Array.isArray(i))return[];let r=[],n=new Set,s=(a,o,l,m)=>{let p=a.type,v=p==="directional"||p==="point"||p==="spot"?p:"ambient",h=o?o[8]:-.5,b=o?o[9]:-1,x=o?o[10]:-.8,g=Math.hypot(h,b,x)||1,c=a.extras?.shadow??l,u=a.name||m,y={type:v,color:a.color||[1,1,1],intensity:a.intensity??1};u&&(y.name=u),o&&(y.position=[o[12],o[13],o[14]]),v==="directional"&&o?y.direction=[h/g,b/g,x/g]:(v==="spot"&&(y.direction=o?[-h/g,-b/g,-x/g]:[0,-1,0],y.innerConeAngle=a.spot?.innerConeAngle??0,y.outerConeAngle=a.spot?.outerConeAngle??Math.PI/4),y.range=a.range),c&&(y.shadow=c),r.push(y)};return(t.nodes||[]).forEach((a,o)=>{let l=a?.extensions?.KHR_lights_punctual?.light;typeof l=="number"&&i[l]&&(n.add(l),s(i[l],e[o],a.extras?.shadow,a.name))}),i.forEach((a,o)=>{n.has(o)||s(a)}),r}function Ii(t){return typeof t=="object"&&t!==null&&"gltf"in t&&typeof t.gltf=="object"&&t.gltf!==null&&"bin"in t&&(t.bin instanceof ArrayBuffer||ArrayBuffer.isView(t.bin))}function Xe(t){if(Ii(t))return t;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return Ir(t);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var vn=`#version 300 es
|
|
19
19
|
layout(location=0) in vec3 aPos;
|
|
20
20
|
layout(location=3) in vec3 aOff;
|
|
21
21
|
layout(location=1) in vec3 aNormal;
|
|
@@ -50,7 +50,7 @@ vec2 scaleUV=uUvTransform.zw;
|
|
|
50
50
|
if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
|
|
51
51
|
vUV=aUV*scaleUV+uUvTransform.xy;
|
|
52
52
|
gl_Position=uMVP*vec4(aPosition,1.0);
|
|
53
|
-
}`,
|
|
53
|
+
}`,ki=`#version 300 es
|
|
54
54
|
precision highp float;
|
|
55
55
|
in vec3 vNormal,vWorldPos;
|
|
56
56
|
in vec2 vUV;
|
|
@@ -59,117 +59,81 @@ in vec4 vInstTint;
|
|
|
59
59
|
#define uBaseColor (uBaseColor*vInstTint)
|
|
60
60
|
uniform float uMetallic,uRoughness,uEmissive,uEnvIntensity,uExposure;
|
|
61
61
|
uniform vec2 uClearcoat;
|
|
62
|
-
uniform vec3 uCameraPos,uAmbientColor;
|
|
63
|
-
uniform
|
|
64
|
-
uniform
|
|
62
|
+
uniform vec3 uCameraPos,uAmbientColor,uEmissiveFactor;
|
|
63
|
+
uniform mat3 uHemi;
|
|
64
|
+
uniform sampler2D uBaseColorTexture,uMetallicRoughnessTexture,uNormalTexture,uOcclusionTexture,uEnvironmentMap,uEmissiveTexture;
|
|
65
|
+
uniform int uHasTexture,uHasMetallicRoughnessTexture,uHasNormalTexture,uHasOcclusionTexture,uHasEnvironmentMap,uHasEmissiveTexture;
|
|
65
66
|
uniform float uNormalScale,uOcclusionStrength;
|
|
66
|
-
/*XRD_U*/
|
|
67
|
+
/*XRD_U*//*SHD_U*/
|
|
67
68
|
uniform vec2 uViewportSize;
|
|
68
69
|
uniform vec4 uSectionPlane;
|
|
69
70
|
uniform int uToneMapping,uNumDirLights,uNumPointLights,uSectionEnabled;
|
|
70
71
|
uniform vec3 uDirLightDir[2],uDirLightColor[2],uPointLightPos[2],uPointLightColor[2],uPointLightSpotDir[2];
|
|
71
72
|
uniform vec2 uPointLightSpotCone[2];
|
|
72
73
|
out vec4 fragColor;
|
|
73
|
-
|
|
74
74
|
vec2 envBRDF(float r,float n){
|
|
75
|
-
vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04);
|
|
76
|
-
vec4 rv=r*c0+c1;
|
|
75
|
+
vec4 c0=vec4(-1.0,-0.0275,-0.572,0.022),c1=vec4(1.0,0.0425,1.04,-0.04),rv=r*c0+c1;
|
|
77
76
|
float a=min(rv.x*rv.x,exp2(-9.28*n))*rv.x+rv.y;
|
|
78
77
|
return vec2(-1.04,1.04)*a+rv.zw;
|
|
79
78
|
}
|
|
80
|
-
|
|
81
79
|
vec3 F_SchlickRoughness(vec3 F0,float r,float n){
|
|
82
80
|
return F0+(max(vec3(1.0-r),F0)-F0)*pow(clamp(1.0-n,0.0,1.0),5.0);
|
|
83
81
|
}
|
|
84
|
-
|
|
85
82
|
vec3 getStudioRadiance(vec3 R,float r){
|
|
86
|
-
vec3 kd=normalize(vec3(0.0,1.0,0.35));
|
|
83
|
+
vec3 kd=normalize(vec3(0.0,1.0,0.35)),fd=normalize(vec3(-0.85,0.45,-0.35));
|
|
87
84
|
float ki=pow(max(dot(R,kd),0.0),mix(96.0,1.5,r))*mix(2.4,0.5,r);
|
|
88
|
-
vec3 fd=normalize(vec3(-0.85,0.45,-0.35));
|
|
89
85
|
float fi=pow(max(dot(R,fd),0.0),mix(36.0,1.2,r))*mix(1.3,0.35,r);
|
|
90
86
|
float ri=pow(clamp(1.0-abs(R.y),0.0,1.0),3.5)*mix(0.55,0.22,r);
|
|
91
|
-
|
|
92
|
-
return ag+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
|
|
87
|
+
return mix(vec3(0.06,0.06,0.08),vec3(0.48,0.50,0.55),R.y*0.5+0.5)+vec3(1.0,0.98,0.94)*ki+vec3(0.85,0.92,1.0)*fi+vec3(0.65,0.72,0.85)*ri;
|
|
93
88
|
}
|
|
94
|
-
|
|
95
|
-
vec3
|
|
96
|
-
vec3
|
|
97
|
-
|
|
98
|
-
vec3
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
vec2 duv2=dFdy(uv);
|
|
102
|
-
vec3 dp2perp=cross(dp2,N);
|
|
103
|
-
vec3 dp1perp=cross(N,dp1);
|
|
104
|
-
vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;
|
|
105
|
-
vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;
|
|
106
|
-
float invmax=inversesqrt(max(dot(T,T),dot(B,B)));
|
|
107
|
-
return normalize(mat3(T*invmax,B*invmax,N)*normalize(mapNormal));
|
|
89
|
+
vec3 perturbNormal(vec3 N,vec3 V,vec2 uv,sampler2D m,float s){
|
|
90
|
+
vec3 q=texture(m,uv).xyz*2.0-1.0;q.xy*=s;
|
|
91
|
+
vec3 p1=dFdx(vWorldPos),p2=dFdy(vWorldPos),c2=cross(p2,N),c1=cross(N,p1);
|
|
92
|
+
vec2 u1=dFdx(uv),u2=dFdy(uv);
|
|
93
|
+
vec3 T=c2*u1.x+c1*u2.x,B=c2*u1.y+c1*u2.y;
|
|
94
|
+
float k=inversesqrt(max(dot(T,T),dot(B,B)));
|
|
95
|
+
return normalize(mat3(T*k,B*k,N)*normalize(q));
|
|
108
96
|
}
|
|
109
|
-
|
|
110
97
|
vec2 equirectangularUV(vec3 dir){
|
|
111
98
|
vec3 d=normalize(dir);
|
|
112
|
-
|
|
113
|
-
float v=asin(clamp(d.y,-1.0,1.0))*0.31830988618+0.5;
|
|
114
|
-
return vec2(u,1.0-v);
|
|
99
|
+
return vec2(atan(d.z,d.x)*0.15915494309+0.5,0.5-asin(clamp(d.y,-1.0,1.0))*0.31830988618);
|
|
115
100
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
float
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
if(peak<startCompression)return color;
|
|
125
|
-
const float d=1.0-startCompression;
|
|
126
|
-
float newPeak=1.0-d*d/(peak+d-startCompression);
|
|
127
|
-
color*=newPeak/peak;
|
|
128
|
-
float g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);
|
|
129
|
-
return mix(color,newPeak*vec3(1.0),g);
|
|
101
|
+
vec3 neutralToneMapping(vec3 c){
|
|
102
|
+
float x=min(c.r,min(c.g,c.b));
|
|
103
|
+
c-=x<0.08?x-6.25*x*x:0.04;
|
|
104
|
+
float p=max(c.r,max(c.g,c.b));
|
|
105
|
+
if(p<0.76)return c;
|
|
106
|
+
float n=1.0-0.0576/(p-0.52);
|
|
107
|
+
c*=n/p;
|
|
108
|
+
return mix(c,vec3(n),1.0-1.0/(0.15*(p-n)+1.0));
|
|
130
109
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
color*=0.6;
|
|
134
|
-
return clamp((color*(2.51*color+0.03))/(color*(2.43*color+0.59)+0.14),0.0,1.0);
|
|
110
|
+
vec3 acesToneMapping(vec3 c){
|
|
111
|
+
c*=0.6;return clamp((c*(2.51*c+0.03))/(c*(2.43*c+0.59)+0.14),0.0,1.0);
|
|
135
112
|
}
|
|
136
|
-
|
|
137
|
-
vec3
|
|
138
|
-
|
|
139
|
-
vec3
|
|
140
|
-
|
|
141
|
-
0.
|
|
142
|
-
0.
|
|
143
|
-
vec3 ev=clamp((log2(max(inset,vec3(1e-6)))+12.47393)/16.5,0.0,1.0);
|
|
144
|
-
vec3 x2=ev*ev;
|
|
145
|
-
vec3 x4=x2*x2;
|
|
146
|
-
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;
|
|
147
|
-
vec3 outset=vec3(
|
|
148
|
-
1.196879*s.r-0.09802088*s.g-0.09902974*s.b,
|
|
149
|
-
-0.05289685*s.r+1.15190313*s.g-0.09896118*s.b,
|
|
150
|
-
-0.05297164*s.r-0.09804345*s.g+1.15107367*s.b);
|
|
151
|
-
return clamp(pow(max(outset,vec3(0.0)),vec3(2.2)),0.0,1.0);
|
|
113
|
+
vec3 agxToneMapping(vec3 c){
|
|
114
|
+
c=max(c,vec3(0.0));
|
|
115
|
+
vec3 i=mat3(0.84247906,0.04232824,0.04237565,0.0784336,0.87846864,0.0784336,0.07922375,0.07916613,0.87914297)*c;
|
|
116
|
+
vec3 e=clamp((log2(max(i,vec3(1e-6)))+12.47393)/16.5,0.0,1.0),x2=e*e,x4=x2*x2;
|
|
117
|
+
vec3 s=15.5*x4*x2-40.14*x4*e+31.96*x4-6.868*x2*e+0.4298*x2+0.1191*e-0.00232;
|
|
118
|
+
vec3 o=mat3(1.196879,-0.05289685,-0.05297164,-0.09802088,1.15190313,-0.09804345,-0.09902974,-0.09896118,1.15107367)*s;
|
|
119
|
+
return clamp(pow(max(o,vec3(0.0)),vec3(2.2)),0.0,1.0);
|
|
152
120
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
if(mode==0)return neutralToneMapping(color);
|
|
156
|
-
if(mode==1)return color/(color+vec3(1.0));
|
|
157
|
-
if(mode==3)return acesToneMapping(color);
|
|
158
|
-
if(mode==4)return agxToneMapping(color);
|
|
159
|
-
return color;
|
|
121
|
+
vec3 applyToneMapping(vec3 c,int m){
|
|
122
|
+
return m==0?neutralToneMapping(c):m==1?c/(c+vec3(1.0)):m==3?acesToneMapping(c):m==4?agxToneMapping(c):c;
|
|
160
123
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
return base*max(dot(N,L),0.0)*0.75+vec3(pow(NoH,specExp)*specWeight+uClearcoat.x*pow(NoH,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
|
|
124
|
+
vec3 evalLight(vec3 L,vec3 V,vec3 N,vec3 b,float e,float w){
|
|
125
|
+
float h=max(dot(N,normalize(L+V)),0.0);
|
|
126
|
+
return b*max(dot(N,L),0.0)*0.75+vec3(pow(h,e)*w+uClearcoat.x*pow(h,mix(64.0,512.0,1.0-uClearcoat.y))*0.35);
|
|
165
127
|
}
|
|
166
128
|
|
|
167
129
|
void main(){
|
|
168
130
|
if(uSectionEnabled==1&&dot(vWorldPos,uSectionPlane.xyz)>uSectionPlane.w)discard;
|
|
169
131
|
vec4 base=uBaseColor;
|
|
170
132
|
if(uHasTexture==1)base*=texture(uBaseColorTexture,vUV);
|
|
133
|
+
if(base.a<0.004)discard;
|
|
134
|
+
vec3 em=uHasEmissiveTexture==1?uEmissiveFactor*texture(uEmissiveTexture,vUV).rgb:uEmissiveFactor;
|
|
171
135
|
if(length(vNormal)<1e-4&&uHasTexture==1){
|
|
172
|
-
vec3 unlit=base.rgb+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
|
|
136
|
+
vec3 unlit=base.rgb+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
|
|
173
137
|
fragColor=vec4(unlit,base.a);
|
|
174
138
|
return;
|
|
175
139
|
}
|
|
@@ -201,7 +165,7 @@ float specWeight=mix(0.22*gloss,1.0,metallic);
|
|
|
201
165
|
vec3 directLight=vec3(0.0);
|
|
202
166
|
for(int i=0;i<2;i++){
|
|
203
167
|
if(i>=uNumDirLights)break;
|
|
204
|
-
directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i]
|
|
168
|
+
directLight+=evalLight(normalize(uDirLightDir[i]),V,N,base.rgb,specExp,specWeight)*uDirLightColor[i]/*SHD_D*/;
|
|
205
169
|
}
|
|
206
170
|
for(int i=0;i<2;i++){
|
|
207
171
|
if(i>=uNumPointLights)break;
|
|
@@ -210,7 +174,7 @@ float dist=length(toLight);
|
|
|
210
174
|
vec3 L=toLight/max(dist,0.0001);
|
|
211
175
|
float spotAtt=clamp((dot(-L,uPointLightSpotDir[i])-uPointLightSpotCone[i].y)/max(uPointLightSpotCone[i].x-uPointLightSpotCone[i].y,0.0001),0.0,1.0);
|
|
212
176
|
spotAtt*=spotAtt;
|
|
213
|
-
directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist)
|
|
177
|
+
directLight+=evalLight(L,V,N,base.rgb,specExp,specWeight)*uPointLightColor[i]*spotAtt/(1.0+0.09*dist+0.032*dist*dist)/*SHD_P*/;
|
|
214
178
|
}
|
|
215
179
|
|
|
216
180
|
vec3 R=reflect(-V,N);
|
|
@@ -230,8 +194,9 @@ envDiffuse=mix(vec3(0.10,0.10,0.12),vec3(0.52,0.54,0.58),N.y*0.5+0.5);
|
|
|
230
194
|
}
|
|
231
195
|
|
|
232
196
|
vec3 kD=(vec3(1.0)-F)*(1.0-metallic);
|
|
197
|
+
directLight+=kD*base.rgb*mix(uHemi[1],uHemi[0],dot(N,uHemi[2])*0.5+0.5)*occ;
|
|
233
198
|
vec3 diffuseIBL=kD*base.rgb*(uAmbientColor+envDiffuse*0.5)*occ;
|
|
234
|
-
vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
|
|
199
|
+
vec3 color=directLight+(diffuseIBL+specularIBL)*uEnvIntensity+em+vec3(uEmissive*0.35,uEmissive*0.5,uEmissive*0.7);
|
|
235
200
|
if(uClearcoat.x>0.0){
|
|
236
201
|
vec3 ccF=F_SchlickRoughness(vec3(0.04),uClearcoat.y,NoV)*uClearcoat.x;
|
|
237
202
|
color=color*(vec3(1.0)-ccF)+getStudioRadiance(R,uClearcoat.y)*ccF*uEnvIntensity;
|
|
@@ -241,140 +206,157 @@ color=applyToneMapping(color,uToneMapping);
|
|
|
241
206
|
float outAlpha=base.a;
|
|
242
207
|
/*XRD_O*/
|
|
243
208
|
fragColor=vec4(color,outAlpha);
|
|
244
|
-
}`;function
|
|
209
|
+
}`;function kr(t,e,i=1){e=Ke(e);let r=Number.isFinite(i)?Math.max(0,i):1,[n,s,a]=[0,1,2].map(g=>Math.max(0,(Number(t[g])||0)*r)),o=g=>Math.max(0,Math.min(1,g)),l=g=>[g(n),g(s),g(a)];if(e==="none")return l(o);if(e==="reinhard")return l(g=>g/(g+1));if(e==="aces")return l(g=>{let c=g*.6;return o(c*(2.51*c+.03)/(c*(2.43*c+.59)+.14))});if(e==="agx"){let[g,c,u]=[.84247906*n+.0784336*s+.07922375*a,.04232824*n+.87846864*s+.07916613*a,.04237565*n+.0784336*s+.87914297*a].map(y=>{let f=o((Math.log2(Math.max(y,1e-6))+12.47393)/16.5),w=f*f,M=w*w;return 15.5*M*w-40.14*M*f+31.96*M-6.868*w*f+.4298*w+.1191*f-.00232});return[1.196879*g-.09802088*c-.09902974*u,-.05289685*g+1.15190313*c-.09896118*u,-.05297164*g-.09804345*c+1.15107367*u].map(y=>o(Math.pow(Math.max(y,0),2.2)))}let m=Math.min(n,s,a),p=m<.08?m-6.25*m*m:.04;[n,s,a]=l(g=>g-p);let v=Math.max(n,s,a);if(v<.76)return l(o);let h=1-.0576/(v-.52),b=h/v,x=1-1/(.15*(v-h)+1);return l(g=>o(g*b+(h-g*b)*x))}var Ni=`#version 300 es
|
|
245
210
|
layout(location=0) in vec3 aPosition;
|
|
246
211
|
uniform mat4 uMVP;
|
|
247
|
-
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,
|
|
212
|
+
void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Fi=`#version 300 es
|
|
248
213
|
precision highp float;
|
|
249
214
|
uniform vec4 uColorId;
|
|
250
215
|
out vec4 fragColor;
|
|
251
|
-
void main(){fragColor=uColorId;}`;function sn(t,e,i){let r={};for(let s of i)r[s]=t.getUniformLocation(e,s);return r}var lr=["uMVP","uModel","uInstanced","uViewProj","uNormalMatrix","uUvTransform","uBaseColor","uMetallic","uRoughness","uClearcoat","uEmissive","uCameraPos","uBaseColorTexture","uHasTexture","uMetallicRoughnessTexture","uHasMetallicRoughnessTexture","uNormalTexture","uHasNormalTexture","uNormalScale","uOcclusionTexture","uHasOcclusionTexture","uOcclusionStrength","uToneMapping","uEnvironmentMap","uHasEnvironmentMap","uAmbientColor","uNumDirLights","uDirLightDir","uDirLightColor","uNumPointLights","uPointLightPos","uPointLightColor","uPointLightSpotDir","uPointLightSpotCone","uEnvIntensity","uExposure","uViewportSize","uSectionPlane","uSectionEnabled"];function gr(){let t=ue().xrDepthShader;return{fs:gi.replace("/*XRD_U*/",t?.uniformsGLSL||"").replace("/*XRD_O*/",t?.occlusionGLSL||""),uniforms:t?[...lr,...t.uniformNames]:lr}}function vi(t){if(typeof t!="string")return null;let e=t.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let i=e.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:i.startsWith("https://")||i.startsWith("blob:")?e:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function nn(t,e,i,r,s,a,o,n){if(r===void 0||!e.accessors?.[r])return null;let l=tn(e,i,e.accessors[r],a);if(!l)return null;n&&(l=l.slice(),ur(l,n));let h=t.createBuffer();return o.push(h),t.bindBuffer(34962,h),t.bufferData(34962,l,35044),t.enableVertexAttribArray(s),t.vertexAttribPointer(s,a,5126,!1,0,0),l}function rn(t){let e=Number(t);return Number.isFinite(e)?Math.max(0,e):1}function yr(t,e,i){let r=gr(),s=pr,a=r.fs,o=!1;for(let l of he)if(l.onResolveShader){let h=l.onResolveShader(e,i,s,a);h&&(s=h.vs,a=h.fs,o=!0)}let n=o?bt(t,s,a):null;return{program:n,uniforms:n?sn(t,n,r.uniforms):null}}function Mi(t,e,i){let r=e.instanceMatrices;if(!r||r.length<16||typeof t.vertexAttribDivisor!="function"||typeof t.drawElementsInstanced!="function")return!1;let s=r.length>>4,a=e.instanceColors,o=new Float32Array(s*20);for(let l=0;l<s;l++)o.set(r.subarray(l*16,l*16+16),l*20),o[l*20+16]=a?a[l*3]:1,o[l*20+17]=a?a[l*3+1]:1,o[l*20+18]=a?a[l*3+2]:1,o[l*20+19]=1;let n=t.createBuffer();i.push(n),t.bindBuffer(34962,n),t.bufferData(34962,o,35044);for(let l=0;l<5;l++)t.enableVertexAttribArray(8+l),t.vertexAttribPointer(8+l,4,5126,!1,80,l*16),t.vertexAttribDivisor(8+l,1);return!0}function wi(t,e){let i=t.materials?.[e?.material];if(!i)return null;let r=[i.pbrMetallicRoughness?.baseColorTexture,i.pbrMetallicRoughness?.metallicRoughnessTexture,i.normalTexture,i.occlusionTexture,i.emissiveTexture];for(let s of r){let a=s?.extensions?.KHR_texture_transform;if(a&&typeof a=="object")return a}return null}var xr=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),vr=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function gt(t,e){e.indices?t.drawElements(4,e.indexCount,e.indexType,0):t.drawArrays(4,0,e.indexCount)}function Mr(t,e){let i=t?.pbrMetallicRoughness,r=i?.baseColorFactor,s=t?.extensions?.KHR_materials_clearcoat,a=o=>o!==void 0&&e[o.index]?e[o.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:i?.metallicFactor??.1,roughness:i?.roughnessFactor??.5,clearcoat:s?s.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,s?.clearcoatRoughnessFactor??.04),texture:a(i?.baseColorTexture),metallicRoughnessTexture:a(i?.metallicRoughnessTexture),normalTexture:a(t?.normalTexture),normalScale:t?.normalTexture?.scale??1,occlusionTexture:a(t?.occlusionTexture),occlusionStrength:t?.occlusionTexture?.strength??1,isTransmissive:(t?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function wr(t,e,i){let r=new Set,s=a=>{a&&!r.has(a)&&(r.add(a),t.deleteTexture(a))};for(let a of e)for(let o of a.primitives){if(o.vao&&t.deleteVertexArray(o.vao),o.buffers)for(let l of o.buffers)t.deleteBuffer(l);s(o.texture),s(o.metallicRoughnessTexture),s(o.normalTexture),s(o.occlusionTexture);let n=new Set;o.customProgram&&n.add(o.customProgram);for(let l of o.programCache?.values()??[])l.program&&n.add(l.program);for(let l of n)t.deleteProgram(l)}if(i)for(let a of i)s(a)}function mr(t,e,i=vr,r){let s={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Si(t,e,i,r,s)}catch(a){let o=s.mesh&&!s.meshes.includes(s.mesh)?[...s.meshes,s.mesh]:s.meshes;wr(t,o,s.gpuTextures),s.vao&&t.deleteVertexArray(s.vao);for(let n of s.buffers)t.deleteBuffer(n);throw a}}function Si(t,e,i,r,s){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:a}=e,o=Ke("meshopt");o?.decodeBufferViews&&o.decodeBufferViews(a,e);let n=e.bin,l=[];s.meshes=l;let h=[],c=a.extensions?.KHR_materials_variants;c&&Array.isArray(c.variants)&&c.variants.forEach((L,M)=>{h.push(typeof L?.name=="string"&&L.name?L.name:`Variant_${M}`)});let f=cr(a),g=[];if(Array.isArray(a.nodes))for(let L=0;L<a.nodes.length;L++){let M=a.nodes[L];M.mesh!==void 0&&a.meshes&&a.meshes[M.mesh]&&g.push({node:M,nodeIdx:L,meshIdx:M.mesh})}let w=g.length>0?g:(a.meshes||[]).map((L,M)=>({node:L,nodeIdx:-1,meshIdx:M})),d=[],p=Array.isArray(e.lights)&&e.lights.length>0?e.lights:Array.isArray(a.asset?.extras?.lights)&&a.asset.extras.lights.length>0?a.asset.extras.lights:null;if(p)for(let L of p)d.push({...L,type:L.type||L.light_type||"point",innerConeAngle:L.innerConeAngle??L.inner_cone_angle,outerConeAngle:L.outerConeAngle??L.outer_cone_angle});else if(a.extensions?.KHR_lights_punctual?.lights){let L=a.extensions.KHR_lights_punctual.lights;for(let M of L){let O=M.type==="directional"?"directional":M.type==="point"?"point":M.type==="spot"?"spot":"ambient";d.push({type:O,color:M.color||[1,1,1],intensity:M.intensity!==void 0?M.intensity:1})}}if(d.length===0&&(d.push({type:"ambient",color:[1,1,1],intensity:.35}),d.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),w.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${w.length}`);let A=[];if(s.gpuTextures=A,a.textures&&a.images){if(a.textures.length>i.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${i.maxTextures}). Found: ${a.textures.length}`);for(let L=0;L<a.textures.length;L++){let M=a.textures[L],O=a.images[M.source];if(O){let H=t.createTexture();t.bindTexture(3553,H),t.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),t.texParameteri(3553,10242,10497),t.texParameteri(3553,10243,10497),t.texParameteri(3553,10241,9729),t.texParameteri(3553,10240,9729);let R=C=>{t.bindTexture(3553,H),t.texImage2D(3553,0,6408,6408,5121,C),t.generateMipmap(3553),r?.()};if(O.bufferView!==void 0){let C=a.bufferViews[O.bufferView],y=C.byteOffset||0,T=new Blob([n.slice(y,y+C.byteLength)],{type:O.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(T).then(R).catch(()=>{})}else if(O.uri){let C=vi(O.uri);if(C){let y=new Image;y.crossOrigin="anonymous",y.referrerPolicy="no-referrer",y.onload=()=>R(y),y.src=C}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",O.uri)}A.push(H)}else A.push(null)}}let b=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0],u=0,m=0;for(let L=0;L<w.length;L++){let M=w[L],O=a.meshes[M.meshIdx],H=M.nodeIdx>=0?f[M.nodeIdx]:de(),R=new Float32Array(9);Ce(R,H);let C={name:M.node.name||O.name||`Mesh_${M.meshIdx}`,nodeIndex:M.nodeIdx,transform:H,normalMatrix:R,primitives:[],extras:M.node.extras||O.extras,...M.node?.visible===!1||M.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};s.mesh=C;let y=M.node?.extensions?.EXT_mesh_gpu_instancing;if(y&&y.attributes&&typeof y.attributes=="object"){let T=y.attributes,z=T.TRANSLATION!==void 0?a.accessors?.[T.TRANSLATION]:null,G=T.ROTATION!==void 0?a.accessors?.[T.ROTATION]:null,B=T.SCALE!==void 0?a.accessors?.[T.SCALE]:null,te=T._COLOR_0!==void 0?a.accessors?.[T._COLOR_0]:null,I=Number(z?.count??G?.count??B?.count??0);if(!Number.isFinite(I)||I<0||I>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${I}`);if(I>0){let W=(k,V)=>{if(!k||k.bufferView===void 0||!a.bufferViews?.[k.bufferView])return null;let j=k.componentType??5126,K=J=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${J})`),null);if(j!==5120&&j!==5121&&j!==5122&&j!==5123&&j!==5126)return K(`componentType ${j}`);if(!(Number(k.count)>=I))return K(`count ${k.count} < ${I}`);let Q=null;try{Q=tn(a,n,{...k,count:I},V)}catch{return K("out of bounds")}return!Q||!Q.every(Number.isFinite)?K("non-finite value"):Q},Z=W(z,3),se=W(G,4),U=W(B,3),ee=te?.type==="VEC4"?4:3,$=W(te,ee),q=new Float32Array(I*16),X=de();for(let k=0;k<I;k++){let V=Z?[Z[k*3],Z[k*3+1],Z[k*3+2]]:[0,0,0],j=se?[se[k*4],se[k*4+1],se[k*4+2],se[k*4+3]]:[0,0,0,1],K=U?[U[k*3],U[k*3+1],U[k*3+2]]:[1,1,1];nt(X,j,V,K),q.set(X,k*16)}if(C.instanceMatrices=q,$){let k=new Float32Array(I*3);for(let V=0;V<I;V++)k[V*3]=$[V*ee],k[V*3+1]=$[V*ee+1],k[V*3+2]=$[V*ee+2];C.instanceColors=k}}}for(let T of O.primitives||[]){if(T.extensions?.KHR_draco_mesh_compression){let Q=Ke("draco");Q&&Q.decodePrimitive(a,T,n)}let z=[],G=t.createVertexArray();s.vao=G,s.buffers=z,t.bindVertexArray(G);let B=Mi(t,C,z),te=a.accessors[T.attributes.POSITION],I=Number(te?.count??0);if(!Number.isFinite(I)||I<0||u+I>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(u+=I,te?.min&&te?.max){let Q=J=>{for(let Y=0;Y<3;Y++){let ce=J[12+Y],re=J[12+Y];for(let ae=0;ae<3;ae++){let ne=J[ae*4+Y]*te.min[ae],le=J[ae*4+Y]*te.max[ae];ce+=ne<le?ne:le,re+=ne>le?ne:le}ce<b[Y]&&(b[Y]=ce),re>x[Y]&&(x[Y]=re)}};if(C.instanceMatrices&&C.instanceMatrices.length>=16){let J=C.instanceMatrices.length>>4,Y=de();for(let ce=0;ce<J;ce++){let re=C.instanceMatrices.subarray(ce*16,ce*16+16);pe(Y,H,re),Q(Y)}}else Q(H)}let W=nn(t,a,n,T.attributes.POSITION,0,3,z);nn(t,a,n,T.attributes.NORMAL,1,3,z),nn(t,a,n,T.attributes.TEXCOORD_0,2,2,z,wi(a,T));let Z=0,se=5123,U=null;if(T.indices!==void 0){let Q=a.accessors[T.indices],J=(a.bufferViews[Q.bufferView].byteOffset||0)+(Q.byteOffset||0);if(Z=Number(Q.count??0),!Number.isFinite(Z)||Z<0||m+Z>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);m+=Z,se=Q.componentType===5125?5125:5123;let Y=t.createBuffer();z.push(Y),t.bindBuffer(34963,Y),Q.componentType===5125?U=new Uint32Array(n,J,Q.count):Q.componentType===5121?U=Uint16Array.from(new Uint8Array(n,J,Q.count)):U=J%2===0?new Uint16Array(n,J,Q.count):new Uint16Array(n.slice(J,J+Q.count*2)),t.bufferData(34963,U,35044)}else Z=te.count;let ee={};for(let Q of he)if(Q.onBuildPrimitiveVAO){let J=Q.onBuildPrimitiveVAO(t,G,T,a,n);J&&(ee[Q.name]=J)}t.bindVertexArray(null);let $=a.materials&&T.material!==void 0?a.materials[T.material]:null,{program:q,uniforms:X}=yr(t,T,$),k=Mr($,A),V=!!($?.extensions?.KHR_materials_transmission||ee.materials?.isTransmissive),j=T.extensions?.KHR_materials_variants?.mappings,K=Array.isArray(j)?j.filter(Q=>Q&&typeof Q.material=="number"&&Array.isArray(Q.variants)).map(Q=>({material:Q.material|0,variants:Q.variants.map(J=>Number(J)|0)})):void 0;C.primitives.push({vao:G,instanced:B,indexCount:Z,indexType:se,...k,positions:W,indices:U,buffers:z,materialIndex:T.material,defaultMaterialIndex:T.material,variantMappings:K,primitiveDef:T,programCache:new Map([[T.material??-1,{program:q,uniforms:X}]]),pluginData:ee,customProgram:q,customUniforms:X,isTransmissive:V})}l.push(C)}isFinite(b[0])||(b=[-1,-1,-1]),isFinite(x[0])||(x=[1,1,1]);let v=[(b[0]+x[0])/2,(b[1]+x[1])/2,(b[2]+x[2])/2],S=x[0]-b[0],_=x[1]-b[1],D=x[2]-b[2],P=Math.max(Math.hypot(S,_,D)/2,.5),N=[b[0],b[1],b[2]],E=[x[0],x[1],x[2]],F=e.animations;if(!F){for(let L of he)if(L.onParseGLB?.(e),e.animations){F=e.animations;break}}return F||(F=[]),{meshes:l,bounds:{center:v,radius:P,min:N,max:E},lights:d,animations:F,worldMatrices:f,gpuTextures:A,availableVariants:h}}function rt(t){let e=t.customTarget||t.bounds.center,i=t.currDistance*Math.cos(t.currPhi);return[e[0]+i*Math.sin(t.currTheta),e[1]+t.currDistance*Math.sin(t.currPhi),e[2]+i*Math.cos(t.currTheta)]}var Me=class{constructor(t,e,i){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=de(),this.clearColor=[0,0,0,0],this.envIntensity=1,this.exposure=1,this.shadowIntensity=0,this.shadowSoftness=.5,this.toneMapping="neutral",this.environmentTexture=null,this.animations=[],this.currentClip=null,this.animationTime=0,this.isPlayingAnimation=!1,this.autoplay=!1,this.animationName="",this.gpuTextures=[],this.availableVariants=[],this.activeVariantName=null,this.gltf=null,this.worldMatrices=[],this.initialNodeTransforms=[],this.projMatrix=de(),this.viewMatrix=de(),this.activeViewMatrix=null,this.modelMatrix=de(),this.mvpMatrix=de(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshName="",this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:de(),rawValueToMeters:.001,format:0},this.container=t;let r,s;if(e&&typeof e.getContext=="function"?(r=e,s=i):(s=e,r=s?.canvas),!r){let n=t.querySelector("canvas");n||(n=document.createElement("canvas"),n.style.width="100%",n.style.height="100%",n.style.display="block",n.style.touchAction="none",t.prepend(n)),r=n}this.canvas=r,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!a:a&&(this.autoRotate=!1),this.opts.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=this.opts.autoRotateSpeed),this.opts.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(this.opts.autoRotateDelay)||0)),this.opts.exposure!==void 0&&(this.exposure=rn(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=Ge(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let o=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!o)throw new Error("WebGL2 not supported");this.gl=o,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(t,e){pi(t,e)}static getDecoder(t){return Ke(t)}setupContextLossHandling(){let t=this.canvas;typeof t?.addEventListener=="function"&&(this.boundContextLost=e=>{e.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),t.addEventListener("webglcontextlost",this.boundContextLost),t.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let t=this.gl,e=gr();this.renderProg=bt(t,pr,e.fs),this.pickProg=bt(t,yi,xi),this.uRender=sn(t,this.renderProg,e.uniforms),this.uPick=sn(t,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let t=this.gl;this.contextLost=!1,this.initGlState();for(let e of he)e.onContextRestored?.(t,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let t=this.gl;if(typeof t.createFramebuffer!="function")return;this.pickFbo=t.createFramebuffer(),this.pickTexture=t.createTexture(),this.pickDepth=t.createRenderbuffer();let e=Math.max(1,this.canvas.width),i=Math.max(1,this.canvas.height);this.pickFboWidth=e,this.pickFboHeight=i,t.bindTexture(3553,this.pickTexture),t.texImage2D(3553,0,6408,e,i,0,6408,5121,null),t.texParameteri(3553,10241,9728),t.texParameteri(3553,10240,9728),t.bindRenderbuffer(36161,this.pickDepth),t.renderbufferStorage(36161,33189,e,i),t.bindFramebuffer(36160,this.pickFbo),t.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),t.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),t.bindFramebuffer(36160,null)}resizePickingFbo(t,e){if(!this.pickFbo)return;let i=this.gl,r=Math.max(1,t),s=Math.max(1,e);this.pickFboWidth=r,this.pickFboHeight=s,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,s,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,s)}loadGLBData(t,e){let{meshes:i,bounds:r,lights:s,animations:a,worldMatrices:o,gpuTextures:n,availableVariants:l}=mr(this.gl,t,e,()=>this.render());if(this.lastGlbData=t,this.lastLimits=e,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=s,this.animations=a||[],this.worldMatrices=o||[],this.gpuTextures=n||[],this.availableVariants=l||[],this.gltf=t.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(t.gltf?.nodes))for(let f of t.gltf.nodes)this.initialNodeTransforms.push({t:f.translation?[f.translation[0],f.translation[1],f.translation[2]]:[0,0,0],r:f.rotation?[f.rotation[0],f.rotation[1],f.rotation[2],f.rotation[3]]:[0,0,0,1],s:f.scale?[f.scale[0],f.scale[1],f.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let f of he)f.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:r.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let h=t.exposure??t.gltf?.extras?.exposure??t.gltf?.asset?.extras?.exposure;h!==void 0&&(this.exposure=rn(h));let c=t.environmentIntensity??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.environmentIntensity;c!==void 0&&(this.envIntensity=Math.max(0,Number(c)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(t){this.loadGLBData(fr(t))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let t of he)t.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(t){this.loadGLBData(Ue(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let i=Ue(t),{meshes:r}=mr(this.gl,i,vr,()=>this.render());if(e)for(let s of r)s.transform[12]+=e[0],s.transform[13]+=e[1],s.transform[14]+=e[2],Ce(s.normalMatrix,s.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(t,e,i,r=1){this.clearColor=[t,e,i,r]}updateMeshTransforms(t){for(let e=0;e<this.meshes.length;e++){let i=this.meshes[e],r;t instanceof Map?r=t.get(i.name)??t.get(e):Array.isArray(t)?r=t[e]:t&&typeof t=="object"&&(Object.prototype.hasOwnProperty.call(t,i.name)?r=t[i.name]:Object.prototype.hasOwnProperty.call(t,e)&&(r=t[e])),r&&r.length===16&&(i.transform.set(r),Ce(i.normalMatrix,i.transform))}}bindLights(t=this.uRender){let e=this.gl,i=[.28,.28,.28],r=[],s=[],a=[],o=[],n=[],l=[];for(let h of this.lights){let c=h.color||[1,1,1],f=h.intensity!==void 0?h.intensity:1;if(h.type==="ambient")i=[c[0]*f,c[1]*f,c[2]*f];else if(h.type==="directional"&&r.length<6){let g=h.direction||[.5,1,.8];r.push(g[0],g[1],g[2]),s.push(c[0]*f,c[1]*f,c[2]*f)}else if((h.type==="point"||h.type==="spot")&&a.length<6){let g=h.position||[0,0,0];if(a.push(g[0],g[1],g[2]),o.push(c[0]*f,c[1]*f,c[2]*f),h.type==="spot"){let w=h.direction||[0,-1,0],d=Math.max(.01,Math.min(Math.PI/2,h.outerConeAngle??Math.PI/3)),p=Math.max(0,Math.min(d-1e-4,h.innerConeAngle??0));n.push(w[0],w[1],w[2]),l.push(Math.cos(p),Math.cos(d))}else n.push(0,-1,0),l.push(-2,-3)}}r.length===0&&(r.push(.5,1,.8),s.push(1,1,1)),e.uniform3fv(t.uAmbientColor,i),e.uniform1i(t.uNumDirLights,r.length/3),r.length>0&&(e.uniform3fv(t.uDirLightDir,r),e.uniform3fv(t.uDirLightColor,s)),e.uniform1i(t.uNumPointLights,a.length/3),a.length>0&&(e.uniform3fv(t.uPointLightPos,a),e.uniform3fv(t.uPointLightColor,o),t.uPointLightSpotDir&&e.uniform3fv(t.uPointLightSpotDir,n),t.uPointLightSpotCone&&e.uniform2fv(t.uPointLightSpotCone,l)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.exposure=rn(t)}getExposure(){return this.exposure}setShadow(t,e){this.shadowIntensity=Math.max(0,Math.min(1,Number(t)||0)),e!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(e)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(t){this.toneMapping=Ge(t)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){for(let e of he)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t);return}}async setSkyboxImage(t){for(let e of he)if(e.setSkyboxImage){await e.setSkyboxImage(this,t);return}}setInteractive(t){this.interactive=t}isInteractive(){return this.interactive}getCameraOrbit(){let t=this.currTheta,e=this.currPhi,i=this.currDistance;return{theta:t,phi:e,radius:i,toString(){return`${t.toFixed(4)}rad ${e.toFixed(4)}rad ${i.toFixed(4)}m`}}}getCameraTarget(){let t=this.customTarget||this.bounds.center;return{x:t[0],y:t[1],z:t[2],toString(){return`${t[0].toFixed(4)}m ${t[1].toFixed(4)}m ${t[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let t=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return t.map((e,i)=>{let r=this.meshes.flatMap(h=>h.primitives.filter(c=>c.materialIndex===i||t.length===1&&c.materialIndex===void 0)),s=r[0],a=s?[...s.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],o=s?s.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,n=s?s.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,l={baseColorFactor:a,metallicFactor:o,roughnessFactor:n,setBaseColorFactor:h=>{let c=[h[0],h[1],h[2],h[3]??1];l.baseColorFactor=c,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.baseColorFactor=c);for(let f of r)f.baseColor=c;this.render()},setMetallicFactor:h=>{l.metallicFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.metallicFactor=h);for(let c of r)c.metallic=h;this.render()},setRoughnessFactor:h=>{l.roughnessFactor=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness.roughnessFactor=h);for(let c of r)c.roughness=h;this.render()}};return{name:e.name||`Material_${i}`,pbrMetallicRoughness:l}})}playAnimation(t){if(this.animations.length!==0){if(t){let e=this.animations.find(i=>i.name===t);e&&(this.currentClip=e)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(t=>t.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(t){let e=this.applyVariantMaterial(t);return e&&this.gl&&this.render(),e}applyVariantMaterial(t){let e=t===null||t==="",i=-1;if(e)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(t),i<0)return!1;this.activeVariantName=t}let r=this.gltf?.materials;if(!Array.isArray(r))return e;for(let s of this.meshes)for(let a of s.primitives){let o=a.defaultMaterialIndex;if(!e&&Array.isArray(a.variantMappings)){for(let l of a.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(i)){o=l.material;break}}let n=o!==void 0?r[o]:void 0;a.materialIndex=n?o:void 0,Object.assign(a,Mr(n,this.gpuTextures)),this.applyPrimitiveProgram(a,a.materialIndex,n??null)}return!0}applyPrimitiveProgram(t,e,i){if(!this.gl||!t.primitiveDef)return;t.programCache??(t.programCache=new Map);let r=e??-1,s=t.programCache.get(r);s||(s=yr(this.gl,{...t.primitiveDef,material:e},i),t.programCache.set(r,s)),t.customProgram=s.program,t.customUniforms=s.uniforms,t.pluginData&&(t.pluginData.materials=t.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(t){this.autoplay=t,t?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(t){this.animationName=t,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(t)}evaluateAnimation(t){for(let e of he)if(e.evaluateAnimation){e.evaluateAnimation(this,t);return}}setTarget(t,e,i){this.customTarget=[t,e,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(t){let e=Math.max(10,Math.min(90,t));this.fov=e*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(t){if(this.distanceMode=t,!this.customDistance){let e=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=e,this.targetDistance=e,this.currDistance=e,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(t){t.minTheta!==void 0&&(this.minTheta=t.minTheta*Math.PI/180),t.maxTheta!==void 0&&(this.maxTheta=t.maxTheta*Math.PI/180),t.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,t.minPhi*Math.PI/180)),t.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,t.maxPhi*Math.PI/180)),t.minDistance!==void 0&&(this.minDistanceLimit=t.minDistance),t.maxDistance!==void 0&&(this.maxDistanceLimit=t.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(t){return Math.max(this.minTheta,Math.min(this.maxTheta,t))}clampPhi(t){return Math.max(this.minPhi,Math.min(this.maxPhi,t))}clampDistance(t){let e=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(e,Math.min(i,t))}setCamera(t,e,i,r){t!==void 0&&(this.targetTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.targetPhi=this.clampPhi(e*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(t,e,i,r){if(t!==void 0&&(this.initialTheta=this.clampTheta(t*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),e!==void 0&&(this.initialPhi=this.clampPhi(e*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),i!==void 0&&i>0){let s=this.clampDistance(i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(r!==void 0&&r>0){let s=this.clampDistance(this.bounds.radius*2.5/r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(t,e){let i=de();pe(i,this.projMatrix,this.viewMatrix);let[r,s,a]=t,o=e?e[0]:0,n=e?e[1]:0,l=e?e[2]:0,h=this.modelRootMatrix;h&&(r=h[0]*t[0]+h[4]*t[1]+h[8]*t[2]+h[12],s=h[1]*t[0]+h[5]*t[1]+h[9]*t[2]+h[13],a=h[2]*t[0]+h[6]*t[1]+h[10]*t[2]+h[14],e&&(o=h[0]*e[0]+h[4]*e[1]+h[8]*e[2],n=h[1]*e[0]+h[5]*e[1]+h[9]*e[2],l=h[2]*e[0]+h[6]*e[1]+h[10]*e[2]));let c=i[0]*r+i[4]*s+i[8]*a+i[12],f=i[1]*r+i[5]*s+i[9]*a+i[13],g=i[2]*r+i[6]*s+i[10]*a+i[14],w=i[3]*r+i[7]*s+i[11]*a+i[15];if(w<=1e-4)return{x:0,y:0,z:1,visible:!1};let d=c/w,p=f/w,A=g/w,b=this.canvas.getBoundingClientRect(),x=b.width||this.canvas.clientWidth||this.canvas.width||300,u=b.height||this.canvas.clientHeight||this.canvas.height||150,m=(d*.5+.5)*x,v=(-p*.5+.5)*u,S=d>=-1.1&&d<=1.1&&p>=-1.1&&p<=1.1&&A>=-1&&A<=1;if(S&&e){let[_,D,P]=rt(this),N=[r-_,s-D,a-P];o*N[0]+n*N[1]+l*N[2]>.05&&(S=!1)}return{x:m,y:v,z:A,visible:S}}setSelectedMesh(t){this.selectedMeshName=t||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let t=this.canvas,e=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=i=>{i.preventDefault()},t.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=e(),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist=0,this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.isPanning=i.button===2||i.shiftKey||this.activePointers.size===2,t.setPointerCapture(i.pointerId))},t.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=e();let r=this.activePointers.get(i.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},s=i.clientX-r.x,a=i.clientY-r.y;if(this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist+=Math.hypot(s,a),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let o=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],n=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],l=this.customTarget?[...this.customTarget]:[...this.bounds.center],h=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;l[0]+=(-s*o[0]+a*n[0])*h,l[1]+=(-s*o[1]+a*n[1])*h,l[2]+=(-s*o[2]+a*n[2])*h,this.customTarget=l}else this.targetTheta=this.clampTheta(this.targetTheta-s*.008),this.targetPhi=this.clampPhi(this.targetPhi+a*.008)},t.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=e(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{t.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=t.getBoundingClientRect(),s=Math.floor((i.clientX-r.left)*(t.width/Math.max(r.width,1))),a=Math.floor((i.clientY-r.top)*(t.height/Math.max(r.height,1)));this.performMeshPick(s,a,!0)}},t.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=e();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},t.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=i=>{let r=i.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),t.tabIndex!==void 0&&t.tabIndex<0&&(t.tabIndex=0),t.getAttribute?.("role")||t.setAttribute?.("role","region"),t.getAttribute?.("aria-label")||t.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=i=>{if(this.interactive){switch(i.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=e(),i.preventDefault()}},t.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let t=(i,r,s)=>{this[s]&&(i.removeEventListener(r,this[s]),this[s]=null)},e=this.canvas;t(e,"webglcontextlost","boundContextLost"),t(e,"webglcontextrestored","boundContextRestored"),t(e,"contextmenu","boundContextMenu"),t(e,"pointerdown","boundPointerDown"),t(e,"pointermove","boundPointerMove"),t(e,"pointerup","boundPointerUp"),t(e,"wheel","boundWheel"),t(e,"keydown","boundKeyDown"),t(this.container,"setCamera","boundSetCamera"),t(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(t,e){let i=this.canvas,r=i.getBoundingClientRect(),s=i.width||300,a=i.height||300,o=r.width>0?Math.floor((t-r.left)*(s/r.width)):Math.floor(t),n=r.height>0?Math.floor((e-r.top)*(a/r.height)):Math.floor(e);return this.performMeshPick(o,n,!1)}performMeshPick(t,e,i=!0){if(this.meshes.length===0)return null;let r=this.gl,s=Math.max(1,this.canvas.width||300),a=Math.max(1,this.canvas.height||300);t=this.mapStereoPickX(t,s);let o=de();pe(o,this.projMatrix,this.viewMatrix);let n=[],l=Math.max(0,Math.min(s-1,t)),h=Math.max(0,Math.min(a-1,a-1-e));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==a)&&this.resizePickingFbo(s,a),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,s,a),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16640),r.useProgram(this.pickProg);for(let v=0;v<this.meshes.length;v++){let S=this.meshes[v];if(S.visible===!1||S.isPluginMesh)continue;let _=v+1,D=(_&255)/255,P=(_>>8&255)/255,N=(_>>16&255)/255;r.uniform4f(this.uPick.uColorId,D,P,N,1),pe(this.modelMatrix,this.modelRootMatrix,S.transform);let E=S.instanceMatrices;if(E&&E.length>=16){let F=E.length>>4,L=de();for(let M of S.primitives){r.bindVertexArray(M.vao);for(let O=0;O<F;O++)pe(L,this.modelMatrix,E.subarray(O*16,O*16+16)),pe(this.mvpMatrix,o,L),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),gt(r,M)}}else{pe(this.mvpMatrix,o,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let F of S.primitives)r.bindVertexArray(F.vao),gt(r,F)}}let u=new Uint8Array(4);r.readPixels(l,h,1,1,6408,5121,u),r.bindFramebuffer(36160,null);let m=u[0]+(u[1]<<8)+(u[2]<<16);m>0&&m<=this.meshes.length&&(n=[this.meshes[m-1]])}n.length===0&&(n=this.meshes.filter(u=>u.visible!==!1));let c=null,f=1/0,g=[0,0,0],w=[0,1,0],[d,p,A]=rt(this),b=de();for(let u of n){pe(b,this.modelRootMatrix,u.transform);let m=u.instanceMatrices,v=m&&m.length>=16?m.length>>4:1;for(let S=0;S<v;S++){m&&m.length>=16?pe(this.modelMatrix,b,m.subarray(S*16,S*16+16)):this.modelMatrix.set(b),pe(this.mvpMatrix,o,this.modelMatrix);let _=de();if(!or(_,this.mvpMatrix))continue;let D=(l+.5)/s*2-1,P=(h+.5)/a*2-1,N=[0,0,0],E=[0,0,0];en(N,D,P,-1,_),en(E,D,P,1,_);let F=E[0]-N[0],L=E[1]-N[1],M=E[2]-N[2],O=Math.hypot(F,L,M)||1,H=F/O,R=L/O,C=M/O,y={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((T=>{for(let z of u.primitives){if(!z.positions)continue;let G=z.positions,B=z.indices,te=Math.floor(B?B.length/3:G.length/9);for(let I=0;I<te;I++){let W=B?B[I*3]:I*3,Z=B?B[I*3+1]:I*3+1,se=B?B[I*3+2]:I*3+2;ar(N[0],N[1],N[2],H,R,C,G[W*3],G[W*3+1],G[W*3+2],G[Z*3],G[Z*3+1],G[Z*3+2],G[se*3],G[se*3+1],G[se*3+2],y,T)}}})(1e-4),isFinite(y.distance)){let T=y.point[0],z=y.point[1],G=y.point[2],B=this.modelMatrix,te=B[0]*T+B[4]*z+B[8]*G+B[12],I=B[1]*T+B[5]*z+B[9]*G+B[13],W=B[2]*T+B[6]*z+B[10]*G+B[14],Z=te-d,se=I-p,U=W-A,ee=Math.hypot(Z,se,U);if(ee<f){Ce(this.normalMatrix,this.modelMatrix);let $=this.normalMatrix,q=y.normal[0],X=y.normal[1],k=y.normal[2],V=$[0]*q+$[3]*X+$[6]*k,j=$[1]*q+$[4]*X+$[7]*k,K=$[2]*q+$[5]*X+$[8]*k,Q=Math.hypot(V,j,K)||1;V/=Q,j/=Q,K/=Q,V*Z+j*se+K*U>0&&(V=-V,j=-j,K=-K),c=u,f=Math.round(ee*1e3)/1e3,g=[Math.round(te*1e3)/1e3,Math.round(I*1e3)/1e3,Math.round(W*1e3)/1e3],w=[Math.round(V*1e3)/1e3,Math.round(j*1e3)/1e3,Math.round(K*1e3)/1e3]}}}}if(!c)return null;let x={meshIndex:this.meshes.indexOf(c),meshName:c.name,nodeIndex:c.nodeIndex,distance:f,hitPoint:g,normal:w,screenX:t,screenY:e};if(i){for(let u of he)u.onMeshSelect?.(this,x);this.opts.onMeshClick&&this.opts.onMeshClick(x),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:x}))}return x}mapStereoPickX(t,e){if(!this.stereoSBS||this.xrSessionActive||e<2)return t;let i=Math.max(1,Math.floor(e*.5)),r=t>=i,s=r?t-i:t,a=r?Math.max(1,e-i):i,o=(s+.5)/a*2-1;return Math.floor((o*.5+1)*.5*e)}setStereoSBS(t){this.stereoSBS=!!t,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let t=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),e=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);pt(this.projMatrix,this.fov,t,.1,e);let i=this.customTarget||this.bounds.center;qe(this.viewMatrix,rt(this),i,[0,1,0]),pe(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(),i=Math.max(1,Math.floor(e.width*t)),r=Math.max(1,Math.floor(e.height*t));this.canvas.width!==i||this.canvas.height!==r?(this.canvas.width=i,this.canvas.height=r,this.resizePickingFbo(i,r),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(t){let e=this.xrSessionActive;if(this.xrSessionActive=t,e&&!t){this.xrDepthState.enabled=!1;for(let i of he)i.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(i){this.reportRenderError(i)}}}reportRenderError(t){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",t))}stepXRUpdate(t){for(let e of he)e.onUpdate?.(this,t)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let t=e=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((e-this.lastTime)/1e3,0),.1);if(this.lastTime=e,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(t))};this.animFrameId=requestAnimationFrame(t)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(t){this.autoRotate=t}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(t){this.autoRotateSpeed=t}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(t){this.autoRotateDelay=Math.max(0,Number(t)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(t=0){this.turntableRotation=Number(t)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let t=Math.cos(this.turntableRotation),e=Math.sin(this.turntableRotation),i=this.bounds.center[0],r=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]=i-(t*i+e*r),s[13]=0,s[14]=r-(-e*i+t*r),s[15]=1}setVisible(t){this.isVisible=t}update(t){for(let a of he)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 he)a.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let i=Math.round((this.currTheta*180/Math.PI%360+360)%360),r=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(i-this.lastReportedTheta)>=1||Math.abs(r-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=s;let a={theta:i,phi:r,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,i,r,s=!0,a=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let o=t?.transform?.inverse?.matrix||this.viewMatrix,n=t?.projectionMatrix||this.projMatrix,l=t?.transform?.position,h=l?[l.x,l.y,l.z]:[0,1.6,0];e?this.modelRootMatrix.set(e):i&&e&&this.modelRootMatrix.set(e),this.render({viewMatrix:o,projMatrix:n,eyePos:h,viewport:r,eye:t?.eye||"none",clear:a>0?!1:t?.eye!=="right",isAR:s})}render(t){if(this.contextLost)return;if(!t&&this.stereoSBS){let x=Math.max(2,this.canvas.width||2),u=Math.max(1,this.canvas.height||1),m=Math.max(1,Math.floor(x*.5)),v=Math.max(1,x-m),S=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),_=this.customTarget||this.bounds.center,[D,P,N]=rt(this),E=Math.cos(this.currTheta),F=-Math.sin(this.currTheta),L=.032,M=de(),O=de(),H=[D-E*L,P,N-F*L],R=[_[0]-E*L*.25,_[1],_[2]-F*L*.25];pt(M,this.fov,m/u,.1,S),qe(O,H,R,[0,1,0]);let C=de(),y=de(),T=[D+E*L,P,N+F*L],z=[_[0]+E*L*.25,_[1],_[2]+F*L*.25];pt(C,this.fov,v/u,.1,S),qe(y,T,z,[0,1,0]),this.render({viewMatrix:O,projMatrix:M,eyePos:H,viewport:[0,0,m,u],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:y,projMatrix:C,eyePos:T,viewport:[m,0,v,u],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,x,u);return}let e=this.gl,i=0,r=0,s=this.canvas.width,a=this.canvas.height;t?.viewport?(i=t.viewport[0],r=t.viewport[1],s=t.viewport[2],a=t.viewport[3],e.viewport(i,r,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(16640));let o=de(),n=t?.viewMatrix??this.viewMatrix;this.activeViewMatrix=n,pe(o,t?.projMatrix??this.projMatrix,n);let l=ue().xrDepthShader,h=di(this.toneMapping),[c,f,g]=t?t.eyePos:rt(this);for(let x of he)x.onBeforeDrawScene?.(this,e,o,[c,f,g],h);let w=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&w===0)return;let d=t?.eye||"none",p=!1,A=w>0?[...this.backdropMeshes,...this.meshes]:this.meshes,b=x=>{for(let u=0;u<A.length;u++){let m=A[u];if(m.visible===!1)continue;let v=this.selectedMeshName!==""&&m.name===this.selectedMeshName;u<w||m.worldSpace===!0||m.name==="__xr_reticle__"?this.modelMatrix.set(m.transform):pe(this.modelMatrix,this.modelRootMatrix,m.transform),pe(this.mvpMatrix,o,this.modelMatrix),Ce(m.normalMatrix,this.modelMatrix);let S=m.extras?.xr?.stereo||m.userData?.xr?.stereo,_=0,D=0,P=1,N=1;S==="sbs"?(P=.5,_=d==="right"?.5:0):S==="ou"&&(N=.5,D=d==="right"?.5:0);for(let E of m.primitives){let F=!!E.isTransmissive;if(!x&&F){p=!0;continue}if(x&&!F)continue;let L=E.customProgram||this.renderProg,M=E.customUniforms||this.uRender;e.useProgram(L),e.vertexAttrib3f(3,0,0,0),M.uInstanced&&e.uniform1i(M.uInstanced,0),e.uniform1i(M.uToneMapping,h),e.uniform1f(M.uEnvIntensity,this.envIntensity),M.uExposure&&e.uniform1f(M.uExposure,this.exposure),e.uniform3f(M.uCameraPos,c,f,g),e.uniform1f(M.uEmissive,v?1:0),e.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(M.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(M.uNormalMatrix,!1,m.normalMatrix),M.uUvTransform&&e.uniform4f(M.uUvTransform,_,D,P,N),M.uViewportSize&&e.uniform2f(M.uViewportSize,Math.max(1,s),Math.max(1,a)),l?.bind(e,M,this.xrDepthState,n,[i,r,Math.max(1,s),Math.max(1,a)]),this.environmentTexture?(e.activeTexture(33988),e.bindTexture(3553,this.environmentTexture),e.uniform1i(M.uEnvironmentMap,4),e.uniform1i(M.uHasEnvironmentMap,1)):e.uniform1i(M.uHasEnvironmentMap,0),this.bindLights(M),M.uSectionEnabled&&e.uniform1i(M.uSectionEnabled,0);for(let H of he)H.onBeforeDrawPrimitive?.(e,L,E,m,this.worldMatrices||[],this.gltf);e.uniform4fv(M.uBaseColor,E.baseColor),e.uniform1f(M.uMetallic,E.metallic),e.uniform1f(M.uRoughness,E.roughness),M.uClearcoat&&e.uniform2f(M.uClearcoat,E.clearcoat??0,E.clearcoatRoughness??.04),E.texture?(e.activeTexture(33984),e.bindTexture(3553,E.texture),e.uniform1i(M.uBaseColorTexture,0),e.uniform1i(M.uHasTexture,1)):e.uniform1i(M.uHasTexture,0),E.metallicRoughnessTexture?(e.activeTexture(33985),e.bindTexture(3553,E.metallicRoughnessTexture),e.uniform1i(M.uMetallicRoughnessTexture,1),e.uniform1i(M.uHasMetallicRoughnessTexture,1)):e.uniform1i(M.uHasMetallicRoughnessTexture,0),E.normalTexture?(e.activeTexture(33986),e.bindTexture(3553,E.normalTexture),e.uniform1i(M.uNormalTexture,2),e.uniform1i(M.uHasNormalTexture,1),e.uniform1f(M.uNormalScale,E.normalScale)):e.uniform1i(M.uHasNormalTexture,0),E.occlusionTexture?(e.activeTexture(33987),e.bindTexture(3553,E.occlusionTexture),e.uniform1i(M.uOcclusionTexture,3),e.uniform1i(M.uHasOcclusionTexture,1),e.uniform1f(M.uOcclusionStrength,E.occlusionStrength)):e.uniform1i(M.uHasOcclusionTexture,0),e.bindVertexArray(E.vao);let O=m.instanceMatrices;if(E.instanceCount!==void 0)e.drawElementsInstanced(4,E.indexCount,E.indexType,0,E.instanceCount);else if(O&&O.length>=16&&E.instanced&&M.uInstanced&&M.uViewProj){let H=O.length>>4;e.uniform1i(M.uInstanced,1),e.uniformMatrix4fv(M.uViewProj,!1,o),E.indices?e.drawElementsInstanced(4,E.indexCount,E.indexType,0,H):e.drawArraysInstanced(4,0,E.indexCount,H),e.uniform1i(M.uInstanced,0)}else if(O&&O.length>=16){let H=O.length>>4,R=m.instanceColors,C=de(),y=new Float32Array(9),T=[E.baseColor[0],E.baseColor[1],E.baseColor[2],E.baseColor[3]];for(let z=0;z<H;z++)pe(C,this.modelMatrix,O.subarray(z*16,z*16+16)),pe(this.mvpMatrix,o,C),Ce(y,C),e.uniformMatrix4fv(M.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(M.uModel,!1,C),e.uniformMatrix3fv(M.uNormalMatrix,!1,y),R&&(T[0]=E.baseColor[0]*R[z*3],T[1]=E.baseColor[1]*R[z*3+1],T[2]=E.baseColor[2]*R[z*3+2],T[3]=E.baseColor[3],e.uniform4fv(M.uBaseColor,T)),gt(e,E)}else gt(e,E)}}};if(b(!1),p){for(let x of he)x.onBeforeTransmissivePass?.(e,this);b(!0)}for(let x of he)x.onAfterRender?.(e,this,o,t?.eye??"none",[i,r,s,a],t?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(t,e){wr(this.gl,t,e)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let t=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let e of he)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()}};Me.registerPlugin=ht,Me.getRegisteredPlugins=nr;function Ai(t){return t+3&-4}var oe=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function Ar(t,e){let i=e,r=1;for(;t.has(i);)i=`${e}_${r++}`;return t.add(i),i}function Rr(t,e=0){let[i,r,s,,a,o,n,,l,h,c,,f,g,w]=Array.from({length:15},(y,T)=>oe(t[e+T],T%5===0?1:0)),d=Math.hypot(i,r,s),p=Math.hypot(a,o,n),A=Math.hypot(l,h,c);i*(o*c-h*n)-a*(r*c-h*s)+l*(r*n-o*s)<0&&(d=-d);let b=Math.abs(d)>1e-8?1/d:0,x=Math.abs(p)>1e-8?1/p:0,u=Math.abs(A)>1e-8?1/A:0,m=i*b,v=r*b,S=s*b,_=a*x,D=o*x,P=n*x,N=l*u,E=h*u,F=c*u,L=m+D+F,M=0,O=0,H=0,R=1;if(L>0){let y=.5/Math.sqrt(L+1);R=.25/y,M=(P-E)*y,O=(N-S)*y,H=(v-_)*y}else if(m>D&&m>F){let y=2*Math.sqrt(Math.max(0,1+m-D-F));y>1e-8&&(R=(P-E)/y,M=.25*y,O=(_+v)/y,H=(N+S)/y)}else if(D>F){let y=2*Math.sqrt(Math.max(0,1+D-m-F));y>1e-8&&(R=(N-S)/y,M=(_+v)/y,O=.25*y,H=(P+E)/y)}else{let y=2*Math.sqrt(Math.max(0,1+F-m-D));y>1e-8&&(R=(v-_)/y,M=(N+S)/y,O=(P+E)/y,H=.25*y)}let C=Math.hypot(M,O,H,R);return C>1e-8&&Number.isFinite(C)?(M/=C,O/=C,H/=C,R/=C):(M=0,O=0,H=0,R=1),{t:[f,g,w],r:[M,O,H,R],s:[d,p,A]}}function Ri(t){let e={};return t.grab&&(e.interactable={mode:typeof t.grab=="string"?t.grab:"2-hand"},e.movable={scaleInZ:!!t.scale,minScale:typeof t.scale=="object"?t.scale.min??.1:.1,maxScale:typeof t.scale=="object"?t.scale.max??10:10}),t.billboard&&(e.billboard={mode:typeof t.billboard=="string"?t.billboard:"capsule"}),t.follow&&(e.follow={target:typeof t.follow=="object"?t.follow.mode??"head":t.follow}),t.anchor&&(e.anchor={plane:t.anchor}),t.physics&&t.physics!=="none"&&(e.rigidbody={type:t.physics}),e}var Be=(t,e,i,r)=>typeof t=="number"&&Number.isFinite(t)?Math.max(e,Math.min(i,t)):r;function Tr(t){let e=t?.audioEmitter??t?.spatialAudio??(typeof t?.audio=="object"&&t.audio&&("preset"in t.audio||"distanceModel"in t.audio||"coneInnerAngle"in t.audio||"maxDistance"in t.audio||"volume"in t.audio)?t.audio:typeof t?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(t.audio)?{preset:t.audio}:void 0);if(!e||typeof e=="object"&&e.enabled===!1)return null;let i=typeof e=="string"?{preset:e}:e,r=typeof i.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(i.src)?i.src:void 0,s=typeof i.preset=="string"?i.preset:void 0;return!r&&!s?null:{ae:i,src:r,preset:s,volume:Be(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function it(t,e){return Er(t,e)[0]}function Er(t,e){t.updateMatrixWorld(!0);let i=[],r=0,s=[],a=[],o=[],n=[],l=new Set,h=[],c=[],f=new Map,g=[],w=[],d=[],p=new Map,A=[],b=[];function x(R){let C=f.get(R);if(C!==void 0)return C;C=c.length,f.set(R,C);let y=R,T=y.color?.r??1,z=y.color?.g??1,G=y.color?.b??1,B=y.opacity??1,te={baseColorFactor:[T,z,G,B],metallicFactor:y.metalness??0,roughnessFactor:y.roughness??.5},I={},W=V=>{if(!V)return;let j=(typeof V=="string"?V:typeof V.source=="string"?V.source:typeof V.image=="string"?V.image:"").trim();if(!j||/[\x00-\x1f\x7f\\]|\.\./.test(j)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(j)||!j.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(j)))return;let K=p.get(j);if(K===void 0){let Q=g.length;g.push({uri:j}),w.length===0&&w.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),K=d.length,d.push({sampler:0,source:Q}),p.set(j,K)}return{index:K}},Z=W(y.map);Z&&(te.baseColorTexture=Z);let se=W(y.roughnessMap||y.metalnessMap);se&&(te.metallicRoughnessTexture=se);let U=y.map?.avgColor;Array.isArray(U)&&U.length>=3&&(I.avgColor=[U[0],U[1],U[2]]);let ee=W(y.normalMap),$=W(y.emissiveMap),q=W(y.aoMap),X={name:y.name||"",pbrMetallicRoughness:te,doubleSided:y.side===2||!!y.doubleSided,...ee?{normalTexture:ee}:{},...$?{emissiveTexture:$}:{},...q?{occlusionTexture:q}:{},...Object.keys(I).length>0?{extras:I}:{}};if(y.emissive&&(y.emissive.r>0||y.emissive.g>0||y.emissive.b>0)){let V=y.emissiveIntensity??1;X.emissiveFactor=[y.emissive.r*V,y.emissive.g*V,y.emissive.b*V]}let k={};return y.clearcoat&&y.clearcoat>0&&(k.KHR_materials_clearcoat={clearcoatFactor:y.clearcoat,clearcoatRoughnessFactor:y.clearcoatRoughness||0}),y.sheen&&y.sheen>0&&(k.KHR_materials_sheen={sheenColorFactor:y.sheenColor?[y.sheenColor.r,y.sheenColor.g,y.sheenColor.b]:[1,1,1],sheenRoughnessFactor:y.sheenRoughness||0}),y.transmission&&y.transmission>0&&(k.KHR_materials_transmission={transmissionFactor:y.transmission}),y.thickness&&y.thickness>0&&(k.KHR_materials_volume={thicknessFactor:y.thickness,attenuationDistance:y.attenuationDistance??1/0,attenuationColor:y.attenuationColor?[y.attenuationColor.r,y.attenuationColor.g,y.attenuationColor.b]:[1,1,1]}),y.ior!==void 0&&y.ior!==1.5&&(k.KHR_materials_ior={ior:y.ior}),y.dispersion&&y.dispersion>0&&(k.KHR_materials_dispersion={dispersion:y.dispersion}),y.iridescence&&y.iridescence>0&&(k.KHR_materials_iridescence={iridescenceFactor:y.iridescence,iridescenceIor:y.iridescenceIOR??1.3}),Object.keys(k).length>0&&(X.extensions=k),c.push(X),C}function u(R,C){let y=new Uint8Array(R.buffer,R.byteOffset,R.byteLength),T=Ai(y.byteLength),z=new Uint8Array(T);z.set(y),i.push(z);let G=s.length;return s.push({buffer:0,byteOffset:r,byteLength:y.byteLength,target:C}),r+=T,G}function m(R,C,y,T,z,G,B){let te=u(R,y),I=a.length,W={bufferView:te,byteOffset:0,componentType:T,count:z,type:C};return G&&(W.min=G),B&&(W.max=B),a.push(W),I}t.traverse(R=>{if(R.isLight||R.color&&R.intensity!==void 0){let C=R.matrixWorld?.elements,y=oe(C?C[12]:R.position?.x,0),T=oe(C?C[13]:R.position?.y,0),z=oe(C?C[14]:R.position?.z,0),G=R.target,B=G?.parent?G?.matrixWorld?.elements:void 0,te=oe(B?B[12]:G?.position?.x,0),I=oe(B?B[13]:G?.position?.y,0),W=oe(B?B[14]:G?.position?.z,0),Z=te-y,se=I-T,U=W-z,ee=Math.hypot(Z,se,U),$=Math.max(.01,Math.min(Math.PI/2,oe(R.angle,Math.PI/3))),q=Math.max(0,Math.min(1,oe(R.penumbra,0)));b.push({type:R.type,color:[R.color.r,R.color.g,R.color.b],intensity:R.intensity,position:[y,T,z],...R.type==="spot"?{direction:ee>1e-6?[Z/ee,se/ee,U/ee]:[0,-1,0],outerConeAngle:$,innerConeAngle:Math.max(0,$*(1-q)),range:Math.max(0,oe(R.distance,0))}:R.type==="point"?{range:Math.max(0,oe(R.distance,0))}:{}})}});let v=[],S=new Set([t]),_=[];if(Array.isArray(t.children))for(let R=t.children.length-1;R>=0;R--)_.push({obj:t.children[R],parentKids:v});for(;_.length>0;){let{obj:R,parentKids:C}=_.pop();if(!R||typeof R!="object"||S.has(R))continue;S.add(R),R._bakeAuthorGeometry?.(),ue().materializeDeclarativeGeometry?.(R);let y=!!(R.userData&&(R.userData.xr&&typeof R.userData.xr=="object"&&Object.keys(R.userData.xr).length>0||R.userData.interactivity&&typeof R.userData.interactivity=="object"&&Object.keys(R.userData.interactivity).length>0)),T={name:R.name||(y?`Node_${n.length}`:"")},z=oe(R.position?.x,0),G=oe(R.position?.y,0),B=oe(R.position?.z,0),te=oe(R.quaternion?.x,0),I=oe(R.quaternion?.y,0),W=oe(R.quaternion?.z,0),Z=oe(R.quaternion?.w,1),se=oe(R.scale?.x,1),U=oe(R.scale?.y,1),ee=oe(R.scale?.z,1);if((z||G||B)&&(T.translation=[z,G,B]),(te||I||W||Z!==1)&&(T.rotation=[te,I,W,Z]),(se!==1||U!==1||ee!==1)&&(T.scale=[se,U,ee]),R.visible===!1&&(T.extensions={...T.extensions||{},KHR_node_visibility:{visible:!1}},l.add("KHR_node_visibility")),R.userData&&Object.keys(R.userData).length>0&&(T.extras=JSON.parse(JSON.stringify(R.userData,(X,k)=>{if(!(X==="__proto__"||X==="prototype"||X==="constructor"))return typeof k=="function"?void 0:k})),R.userData.xr)){let X=Ri(R.userData.xr);T.extensions={...T.extensions||{},MOZ_hubs_components:X,ANDROID_xr_scenecore:X},ue().xrTraitSerializer?.gltfNode(T,R.userData.xr),l.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(R.geometry){let X=R.geometry,k=X.attributes.position;if(k&&k.count>0){let V=[1/0,1/0,1/0],j=[-1/0,-1/0,-1/0];for(let re=0;re<k.count;re++){let ae=k.getX(re),ne=k.getY(re),le=k.getZ(re);ae<V[0]&&(V[0]=ae),ae>j[0]&&(j[0]=ae),ne<V[1]&&(V[1]=ne),ne>j[1]&&(j[1]=ne),le<V[2]&&(V[2]=le),le>j[2]&&(j[2]=le)}let K={attributes:{POSITION:m(k.array,"VEC3",34962,5126,k.count,V,j)}};if(X.attributes.normal&&(K.attributes.NORMAL=m(X.attributes.normal.array,"VEC3",34962,5126,X.attributes.normal.count)),X.attributes.uv&&(K.attributes.TEXCOORD_0=m(X.attributes.uv.array,"VEC2",34962,5126,X.attributes.uv.count)),X.index){let re=X.index.array instanceof Uint32Array;K.indices=m(X.index.array,"SCALAR",34963,re?5125:5123,X.index.count)}let Q=Array.isArray(R.material)?R.material[0]:R.material;Q&&(K.material=x(Q));let J=R.userData?.variants;if(J&&typeof J=="object"){let re=new Map;for(let ae of Object.keys(J)){if(!ae||ae==="__proto__"||ae==="constructor"||ae==="prototype")continue;let ne=J[ae];if(!ne||typeof ne!="object")continue;let le=A.indexOf(ae);if(le===-1&&A.length<256&&(le=A.length,A.push(ae)),le===-1)continue;let Se=x(ne),_e=re.get(Se);_e||(_e=[],re.set(Se,_e)),_e.push(le)}if(re.size>0){let ae=[];for(let[ne,le]of re.entries())ae.push({material:ne,variants:le});K.extensions={...K.extensions||{},KHR_materials_variants:{mappings:ae}},l.add("KHR_materials_variants")}}let Y=R;if(Y.isInstancedMesh&&typeof Y.count=="number"&&Y.count>0&&Y.instanceMatrix?.array){let re=Math.min(1e4,Math.floor(Y.count)),ae=Y.instanceMatrix.array,ne=new Float32Array(re*3),le=new Float32Array(re*4),Se=new Float32Array(re*3);for(let fe=0;fe<re;fe++){let{t:Ie,r:Ye,s:Kt}=Rr(ae,fe*16);ne[fe*3]=Ie[0],ne[fe*3+1]=Ie[1],ne[fe*3+2]=Ie[2],le[fe*4]=Ye[0],le[fe*4+1]=Ye[1],le[fe*4+2]=Ye[2],le[fe*4+3]=Ye[3],Se[fe*3]=Kt[0],Se[fe*3+1]=Kt[1],Se[fe*3+2]=Kt[2]}let _e={TRANSLATION:m(ne,"VEC3",0,5126,re),ROTATION:m(le,"VEC4",0,5126,re),SCALE:m(Se,"VEC3",0,5126,re)};if(Y.instanceColor?.array&&Y.instanceColor.array.length>=re*3){let fe=new Float32Array(Y.instanceColor.array.subarray(0,re*3));_e._COLOR_0=m(fe,"VEC3",0,5126,re)}T.extensions={...T.extensions||{},EXT_mesh_gpu_instancing:{attributes:_e}},l.add("EXT_mesh_gpu_instancing")}let ce=o.length;o.push({primitives:[K],name:R.name,...T.extras?{extras:T.extras}:{}}),T.mesh=ce}}let $=n.length;n.push(T),h.push(R),C.push($);let q=R.children;if(Array.isArray(q)&&q.length>0){let X=[];T.children=X;for(let k=q.length-1;k>=0;k--)_.push({obj:q[k],parentKids:X})}}for(let R=0;R<n.length;R++){let C=n[R];C.children&&C.children.length===0?delete C.children:C.children&&C.children.length>0&&(C.extras?.xr?.lod||C.extensions?.ANDROID_xr_scenecore?.lod||h[R]?.isLOD)&&(C.extensions={...C.extensions||{},MSFT_lod:{ids:[...C.children]}},l.add("MSFT_lod"))}let D=e?.animateCallback||e?.animateFn||(typeof t.userData?.animate=="function"?t.userData.animate:typeof t.__animateFn=="function"?t.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),P=[];if(typeof D=="function"&&h.length>0){let R=e?.duration??4,C=e?.fps??15,y=Math.max(2,Math.round(R*C)+1),T=new Float32Array(y),z=h.map(U=>[oe(U.position?.x,0),oe(U.position?.y,0),oe(U.position?.z,0),oe(U.quaternion?.x,0),oe(U.quaternion?.y,0),oe(U.quaternion?.z,0),oe(U.quaternion?.w,1),oe(U.scale?.x,1),oe(U.scale?.y,1),oe(U.scale?.z,1)]),G=h.map(()=>new Float32Array(y*3)),B=h.map(()=>new Float32Array(y*4)),te=h.map(()=>new Float32Array(y*3));for(let U=0;U<y;U++){let ee=U/(y-1)*R;T[U]=ee;try{D(ee)}catch{}for(let $=0;$<h.length;$++){let q=h[$];G[$][U*3]=oe(q.position?.x,0),G[$][U*3+1]=oe(q.position?.y,0),G[$][U*3+2]=oe(q.position?.z,0);let X=oe(q.quaternion?.x,0),k=oe(q.quaternion?.y,0),V=oe(q.quaternion?.z,0),j=oe(q.quaternion?.w,1),K=Math.hypot(X,k,V,j)||1;if(X/=K,k/=K,V/=K,j/=K,U>0){let Q=(U-1)*4,J=B[$];J[Q]*X+J[Q+1]*k+J[Q+2]*V+J[Q+3]*j<0&&(X=-X,k=-k,V=-V,j=-j)}B[$][U*4]=X,B[$][U*4+1]=k,B[$][U*4+2]=V,B[$][U*4+3]=j,te[$][U*3]=oe(q.scale?.x,1),te[$][U*3+1]=oe(q.scale?.y,1),te[$][U*3+2]=oe(q.scale?.z,1)}}for(let U=0;U<h.length;U++){let ee=h[U],$=z[U];ee.position?.set($[0],$[1],$[2]),ee.quaternion?.set($[3],$[4],$[5],$[6]),ee.scale?.set($[7],$[8],$[9])}t.updateMatrixWorld(!0);let I=null,W=()=>(I===null&&(I=m(T,"SCALAR",0,5126,y,[0],[R])),I),Z=[],se=[];for(let U=0;U<h.length;U++){let ee=z[U],$=(X,k,V)=>X.some((j,K)=>Math.abs(j-ee[V+K%k])>1e-4),q=(X,k,V,j)=>{X&&se.push({sampler:Z.push({input:W(),interpolation:"LINEAR",output:m(k,V,0,5126,y)})-1,target:{node:U,path:j}})};q($(G[U],3,0),G[U],"VEC3","translation"),q($(B[U],4,3),B[U],"VEC4","rotation"),q($(te[U],3,7),te[U],"VEC3","scale")}se.length>0&&P.push({name:"ProceduralLoop",samplers:Z,channels:se})}let N=sr(n,o,t.userData),E=[],F=[],L=[];for(let R=0;R<n.length;R++){let C=n[R],y=Tr(C.extras?.xr);if(!y)continue;let{ae:T,src:z,preset:G,volume:B,loop:te,isGlobal:I}=y,W=C.name||`Node_${R}`,Z=F.length;F.push({name:`${W}_source`,gain:B,loop:te,autoPlay:typeof T.autoplay=="boolean"?T.autoplay:!0,...z!==void 0?{audio:E.push({uri:z})-1}:{},...G?{extras:{preset:G,pitch:Be(T.pitch,.25,4,1)}}:{}});let se=L.length,U=Be(T.refDistance,.05,100,1),ee=Be(T.coneInnerAngle,0,360,360),$=Be(T.coneOuterAngle,ee,360,360);L.push({name:`${W}_emitter`,type:I?"global":"positional",gain:B,sources:[Z],...I?{}:{positional:{distanceModel:T.distanceModel==="linear"||T.distanceModel==="exponential"?T.distanceModel:"inverse",refDistance:U,maxDistance:Be(T.maxDistance,U,500,Math.max(U,25)),rolloffFactor:Be(T.rolloffFactor,0,10,1),coneInnerAngle:+(ee*Math.PI/180).toFixed(6),coneOuterAngle:+($*Math.PI/180).toFixed(6),coneOuterGain:Be(T.coneOuterGain,0,1,0)}}}),C.extensions={...C.extensions||{},KHR_audio_emitter:{emitter:se}},l.add("KHR_audio_emitter")}let M={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:t.environmentIntensity}},scenes:[{nodes:v}],scene:0,nodes:n,meshes:o,materials:c,...g.length>0?{images:g}:{},...w.length>0?{samplers:w}:{},...d.length>0?{textures:d}:{},accessors:a,bufferViews:s,buffers:[{byteLength:r}],...P.length>0?{animations:P}:{},...N||l.size>0?{extensionsUsed:[...N?["KHR_interactivity"]:[],...l]}:{},...N||A.length>0||L.length>0?{extensions:{...N?{KHR_interactivity:N}:{},...A.length>0?{KHR_materials_variants:{variants:A.map(R=>({name:R}))}}:{},...L.length>0?{KHR_audio_emitter:{...E.length>0?{audio:E}:{},sources:F,emitters:L}}:{}}}:{}},O=new Uint8Array(r),H=0;for(let R of i)O.set(R,H),H+=R.byteLength;return[{gltf:M,bin:O.buffer,lights:b,environmentIntensity:t.environmentIntensity},h]}function on(t){return new TextEncoder().encode(t)}function wt(t,e){let{gltf:i,bin:r}=it(t,e),s=JSON.stringify(i),a=on(s),o=(4-a.byteLength%4)%4,n=a.byteLength+o,l=20+n+8+r.byteLength,h=new Uint8Array(l),c=new DataView(h.buffer);c.setUint32(0,1179937895,!0),c.setUint32(4,2,!0),c.setUint32(8,l,!0),c.setUint32(12,n,!0),c.setUint32(16,1313821514,!0),h.set(a,20);for(let g=0;g<o;g++)h[20+a.byteLength+g]=32;let f=20+n;return c.setUint32(f,r.byteLength,!0),c.setUint32(f+4,5130562,!0),h.set(new Uint8Array(r),f+8),h}function Ti(t,e){let[i,r]=Er(t,e);return _r(i,r)}function _r(t,e){let i=[],r=t.gltf,s=ue().decoders.get("meshopt");s&&typeof s.decodeBufferViews=="function"&&s.decodeBufferViews(r,t);let a=t.bin,o=a instanceof ArrayBuffer?a:a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),n=r.accessors||[],l=r.bufferViews||[],h=r.materials||[],c=r.meshes||[],f=r.nodes||[],g=r.textures||[],w=r.images||[],d=r.samplers||[],p=new Set,A=h.map((S,_)=>Ar(p,Mt(S?.name,`Material_${_}`))),b=new Map;function x(S){let _=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(S);if(!_)return null;let D=_[2].replace(/\s+/g,""),P=D.endsWith("==")?2:D.endsWith("=")?1:0,N=new Uint8Array((D.length*3>>2)-P),E=L=>{let M=D.charCodeAt(L);return M>96?M-71:M>64?M-65:M>47?M+4:M===43?62:M===47?63:0},F=0;for(let L=0;L<D.length;L+=4){let M=E(L)<<18|E(L+1)<<12|E(L+2)<<6|E(L+3);N[F++]=M>>16&255,F<N.length&&(N[F++]=M>>8&255),F<N.length&&(N[F++]=M&255)}return N}function u(S,_,D){let P=S?.index;if(typeof P!="number")return;let N=g[P],E=N?.source;if(typeof E!="number"||!w[E])return;let F=b.get(E);if(F===void 0){F=null;let O=w[E],H=null;if(typeof O.bufferView=="number"){let R=l[O.bufferView],C=R?.byteOffset||0,y=R?.byteLength||0;R&&y>0&&C>=0&&C+y<=o.byteLength&&(H=new Uint8Array(o,C,y))}else typeof O.uri=="string"&&(H=x(O.uri));if(H&&H.byteLength>0){let R=H[0]===255&&H[1]===216&&H[2]===255||!(H[0]===137&&H[1]===80)&&/jpe?g/i.test(O.mimeType||O.uri||"");F={file:`texture_${E}.${R?"jpg":"png"}`,data:H}}b.set(E,F)}if(!F)return;let L=typeof N.sampler=="number"?d[N.sampler]:void 0,M=O=>O===33071?"clamp":O===33648?"mirror":"repeat";return{file:F.file,data:F.data,wrapS:M(L?.wrapS),wrapT:M(L?.wrapT),..._?{scale:_}:{},...D?{bias:D}:{}}}function m(S){let _=n[S];if(!_)throw new Error(`Accessor ${S} not found`);let D=l[_.bufferView||0],P=(D.byteOffset||0)+(_.byteOffset||0),N=D.byteLength||0;return{acc:_,buffer:o.slice(P,P+N)}}function v(S,_,D,P){let N=[],E=c[S];if(!E)return N;let F=E.primitives||[];for(let L=0;L<F.length;L++){let M=F[L],O=M.attributes?.POSITION;if(O===void 0)continue;let{acc:H,buffer:R}=m(O),C=new Float32Array(R,0,H.count*3),y,T=M.attributes?.NORMAL;if(T!==void 0){let{acc:k,buffer:V}=m(T),j=new Float32Array(V,0,k.count*3);y=new Float32Array(j.length);for(let K=0;K<k.count;K++){let Q=j[K*3],J=j[K*3+1],Y=j[K*3+2],ce=Math.hypot(Q,J,Y)||1;y[K*3]=Q/ce,y[K*3+1]=J/ce,y[K*3+2]=Y/ce}}let z,G=M.attributes?.TEXCOORD_0;if(G!==void 0){let{acc:k,buffer:V}=m(G);z=new Float32Array(V,0,k.count*2)}let B;if(M.indices!==void 0){let{acc:k,buffer:V}=m(M.indices);B=k.componentType===5125?new Uint32Array(V,0,k.count):new Uint16Array(V,0,k.count);let j=H.count;for(let K of B)if(K>=j)throw new Error(`SecurityError: Index buffer value (${K}) out of vertex bounds [0, ${j}).`)}else{let k=H.count;B=k>65535?new Uint32Array(k):new Uint16Array(k);for(let V=0;V<k;V++)B[V]=V}let te="DefaultMaterial",I=[1,1,1],W=.5,Z=0,se=0,U=0,ee=1.5,$=1,q=[0,0,0],X;if(M.material!==void 0&&h[M.material]){let k=h[M.material];te=A[M.material]||`Material_${M.material}`;let V=k.pbrMetallicRoughness||{},j=(Ie,Ye)=>Array.isArray(Ie)&&Ie.length>=3?[Ie[0],Ie[1],Ie[2]]:Ye;I=j(V.baseColorFactor,[1,1,1]);let K=Array.isArray(V.baseColorFactor)&&typeof V.baseColorFactor[3]=="number"?V.baseColorFactor[3]:1,Q=I[0]!==1||I[1]!==1||I[2]!==1||K!==1,J=u(V.baseColorTexture,Q?[I[0],I[1],I[2],K]:void 0),Y=k.extras?.avgColor;!J&&Array.isArray(Y)&&Y.length>=3&&(I=[I[0]*Y[0],I[1]*Y[1],I[2]*Y[2]]),typeof V.roughnessFactor=="number"&&(W=V.roughnessFactor),typeof V.metallicFactor=="number"&&(Z=V.metallicFactor);let ce=typeof V.roughnessFactor=="number"?V.roughnessFactor:1,re=typeof V.metallicFactor=="number"?V.metallicFactor:1,ae=u(V.metallicRoughnessTexture,ce!==1||re!==1?[1,ce,re,1]:void 0);q=j(k.emissiveFactor,[0,0,0]);let ne=(q[0]>0||q[1]>0||q[2]>0)&&(q[0]!==1||q[1]!==1||q[2]!==1)?[q[0],q[1],q[2],1]:void 0,le=u(k.emissiveTexture,ne),Se=u(k.normalTexture,[2,2,2,1],[-1,-1,-1,0]),_e=u(k.occlusionTexture);(J||ae||Se||le||_e)&&(X=[J,ae,Se,le,_e]);let fe=k.extensions||{};fe.KHR_materials_clearcoat&&(se=fe.KHR_materials_clearcoat.clearcoatFactor??0,U=fe.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof fe.KHR_materials_ior?.ior=="number"&&(ee=fe.KHR_materials_ior.ior),$=K*(1-(fe.KHR_materials_transmission?.transmissionFactor??0))}N.push({name:F.length>1?`${_}_p${L}`:_,positions:C,indices:B,normals:y,uvs:z,materialName:te,color:I,roughness:W,metallic:Z,clearcoat:se,clearcoatRoughness:U,ior:ee,opacity:$,emissiveColor:q,...X?{textures:X}:{},xrTraits:D||E.extras?.xr,...P?{invisible:!0}:{}})}return N}if(f.length>0){let S=new Float32Array(0),_=new Uint16Array(0),D=(C,y)=>{if(C===void 0)return null;let{acc:T,buffer:z}=m(C);return new Float32Array(z,0,T.count*y)},P=(C,y)=>Array.isArray(C)&&C.length>=3?[oe(C[0],y),oe(C[1],y),oe(C[2],y)]:[y,y,y],N=(C,y,T)=>C&&C.length>=(y+1)*3?[C[y*3],C[y*3+1],C[y*3+2]]:T,E=(C,y,T)=>C&&C.length>=(y+1)*4?[C[y*4],C[y*4+1],C[y*4+2],C[y*4+3]]:T,F=new Map,L=r.animations?.[0];if(L&&Array.isArray(L.channels)&&Array.isArray(L.samplers))for(let C of L.channels){let y=L.samplers[C?.sampler],T=C?.target?.node,z=C?.target?.path;if(!y||typeof T!="number"||y.input===void 0)continue;let G=F.get(T);G||(G={input:y.input},F.set(T,G)),z==="translation"?G.t=y.output:z==="rotation"?G.r=y.output:z==="scale"&&(G.s=y.output)}let M=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(M)||M.length===0){let C=new Set;for(let y of f)if(Array.isArray(y?.children))for(let T of y.children)C.add(T);M=[];for(let y=0;y<f.length;y++)C.has(y)||M.push(y);M.length===0&&(M=[0])}let O=new Set,H=[],R=(C,y)=>{if(Array.isArray(C))for(let T=C.length-1;T>=0;T--)H.push({idx:C[T],out:y})};for(R(M,i);H.length>0;){let{idx:C,out:y}=H.pop();if(typeof C!="number"||C<0||C>=f.length||O.has(C))continue;O.add(C);let T=f[C];if(!T)continue;let z=[0,0,0],G=[0,0,0,1],B=[1,1,1];if(Array.isArray(T.matrix)&&T.matrix.length===16){let $=Rr(T.matrix);z=$.t,G=$.r,B=$.s}else z=P(T.translation,0),Array.isArray(T.rotation)&&T.rotation.length>=4&&(G=[oe(T.rotation[0],0),oe(T.rotation[1],0),oe(T.rotation[2],0),oe(T.rotation[3],1)]),B=P(T.scale,1);let te,I=F.get(C);if(I){let $=D(I.input,1);if($&&$.length>0){let q=D(I.t,3),X=D(I.r,4),k=D(I.s,3),V=Array.from($),j=[],K=[],Q=[];for(let J=0;J<$.length;J++)j.push(N(q,J,z)),K.push(E(X,J,G)),Q.push(N(k,J,B));te={times:V,translations:j,rotations:K,scales:Q}}}let W=Array.isArray(T.children)?T.children:[],Z=typeof T.mesh=="number"&&T.mesh>=0&&T.mesh<c.length,se=e?.[C]?.userData?.xr??T.extras?.xr;if(!Z&&W.length===0&&(T.camera!==void 0||T.extensions?.KHR_lights_punctual||!T.name&&!T.extras&&!se&&!te))continue;let U=($,q,X)=>({name:$,positions:S,indices:_,isXform:!0,xrTraits:se,timeSamples:te,translation:z,rotation:G,scale:B,children:q,...X?{invisible:!0}:{}}),ee=T.visible===!1||T.extensions?.KHR_node_visibility?.visible===!1||e?.[C]?.visible===!1;if(Z){let $=T.name||c[T.mesh]?.name||`Mesh_${C}`,q=v(T.mesh,$,se,ee),X=T.extensions?.EXT_mesh_gpu_instancing?.attributes;if(X&&typeof X=="object"&&q.length>0){let k=D(X.TRANSLATION,3),V=D(X.ROTATION,4),j=D(X.SCALE,3),K=D(X._COLOR_0,3),Q=Math.min(1e3,k?k.length/3:V?V.length/4:j?j.length/3:0);if(Q>0){let J=[];for(let Y=0;Y<Q;Y++){let ce=N(k,Y,[0,0,0]),re=E(V,Y,[0,0,0,1]),ae=N(j,Y,[1,1,1]);for(let ne of q){let le=ne.color||[.8,.8,.8],Se=K&&K.length>=(Y+1)*3;J.push({...ne,name:`${ne.name}_${Y}`,materialName:Se?`${ne.materialName}_inst_${Y}`:ne.materialName,color:Se?[le[0]*K[Y*3],le[1]*K[Y*3+1],le[2]*K[Y*3+2]]:ne.color,translation:ce,rotation:re,scale:ae})}}R(W,J),y.push(U($,J,ee));continue}}if(q.length===1)q[0].translation=z,q[0].rotation=G,q[0].scale=B,q[0].timeSamples=te,W.length>0&&(q[0].children=[],R(W,q[0].children)),y.push(q[0]);else{let k=[...q];R(W,k),y.push(U($,k,ee))}}else{let $=[];R(W,$),y.push(U(T.name||`Group_${C}`,$,ee))}}}else for(let S=0;S<c.length;S++){let _=c[S].name||`Mesh_${S}`;i.push(...v(S,_,c[S].extras?.xr))}return i}function Mt(t,e){if(!t||typeof t!="string")return e;let i=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(i)&&(i="_"+i),i||e}function yt(t){return String(t??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function xe(t){if(!Number.isFinite(t)||Math.abs(t)<1e-7)return"0";let e=Number(t.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}var Ne=(t,e,i)=>`(${xe(t)}, ${xe(e)}, ${xe(i)})`,xt=(t,e,i,r)=>`(${xe(t)}, ${xe(e)}, ${xe(i)}, ${xe(r)})`;function Sr(t){let e=t.length/3,i=new Array(e);for(let r=0;r<e;r++)i[r]=Ne(t[r*3],t[r*3+1],t[r*3+2]);return i.join(", ")}function Ei(t,e){let i=new Array(e);for(let r=0;r<e;r++)i[r]=`(${xe(t[r*2])}, ${xe(1-t[r*2+1])})`;return i.join(", ")}function _i(t){return Array.from(t).join(", ")}function Ci(t){let e=new Map,i=0,r=null,s=[...t];for(;s.length>0;){let d=s.pop();if(!d.isXform&&d.positions&&d.positions.length>0){let p=Mt(d.materialName,"DefaultMaterial");e.has(p)||e.set(p,{color:d.color||[1,1,1],roughness:d.roughness??.5,metallic:d.metallic??0,clearcoat:d.clearcoat??0,clearcoatRoughness:d.clearcoatRoughness??0,ior:d.ior??1.5,opacity:d.opacity??1,emissiveColor:d.emissiveColor||[0,0,0],textures:d.textures})}if(d.timeSamples&&d.timeSamples.times.length>0){let p=d.timeSamples.times[d.timeSamples.times.length-1];p>i&&(i=p)}if(d.xrTraits?.anchor&&!r&&(r=d.xrTraits.anchor==="vertical"||d.xrTraits.anchor==="wall"?"vertical":"horizontal"),d.children)for(let p=d.children.length-1;p>=0;p--)s.push(d.children[p])}let a="";i>0&&(a=`startTimeCode = 0
|
|
252
|
-
endTimeCode = ${
|
|
216
|
+
void main(){fragColor=uColorId;}`;function _t(t,e,i){let r={};for(let n of i)r[n]=t.getUniformLocation(e,n);return r}var Ui="uMVP uModel uInstanced uViewProj uNormalMatrix uUvTransform uBaseColor uMetallic uRoughness uClearcoat uEmissive uCameraPos uBaseColorTexture uHasTexture uMetallicRoughnessTexture uHasMetallicRoughnessTexture uNormalTexture uHasNormalTexture uNormalScale uOcclusionTexture uHasOcclusionTexture uOcclusionStrength uEmissiveFactor uEmissiveTexture uHasEmissiveTexture uToneMapping uEnvironmentMap uHasEnvironmentMap uAmbientColor uHemi uNumDirLights uDirLightDir uDirLightColor uNumPointLights uPointLightPos uPointLightColor uPointLightSpotDir uPointLightSpotCone uEnvIntensity uExposure uViewportSize uSectionPlane uSectionEnabled".split(" ");function Sn(){let t=ue(),e=t.xrDepthShader,i=t.shadowMapShader;return{fs:ki.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||"").replace("/*SHD_U*/",i?.uniformsGLSL||"").replace("/*SHD_D*/",i?.dirGLSL||"").replace("/*SHD_P*/",i?.ptGLSL||""),uniforms:[...Ui,...e?.uniformNames||[],...i?.uniformNames||[]]}}function Oi(t){if(typeof t!="string")return null;let e=t.trim();if(!e||/[\x00-\x1f\x7f]/.test(e))return null;let i=e.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(e)?e:null:i.startsWith("https://")||i.startsWith("blob:")?e:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(e)||/(^|[\\/])\.\.([\\/]|$)/.test(e)?null:e}function yn(t,e,i,r,n,s,a,o){if(r===void 0||!e.accessors?.[r])return null;let l=gn(e,i,e.accessors[r],s);if(!l)return null;o&&(l=l.slice(),Lr(l,o));let m=t.createBuffer();return a.push(m),t.bindBuffer(34962,m),t.bufferData(34962,l,35044),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,s,5126,!1,0,0),l}function xn(t){let e=Number(t);return Number.isFinite(e)?Math.max(0,e):1}function Nr(t,e,i){let r=Sn(),n=vn,s=r.fs,a=!1;for(let l of ge)if(l.onResolveShader){let m=l.onResolveShader(e,i,n,s);m&&(n=m.vs,s=m.fs,a=!0)}let o=a?ut(t,n,s):null;return{program:o,uniforms:o?_t(t,o,r.uniforms):null}}function Bi(t,e,i){let r=e.instanceMatrices;if(!r||r.length<16||typeof t.vertexAttribDivisor!="function"||typeof t.drawElementsInstanced!="function")return!1;let n=r.length>>4,s=e.instanceColors,a=new Float32Array(n*20);for(let l=0;l<n;l++)a.set(r.subarray(l*16,l*16+16),l*20),a[l*20+16]=s?s[l*3]:1,a[l*20+17]=s?s[l*3+1]:1,a[l*20+18]=s?s[l*3+2]:1,a[l*20+19]=1;let o=t.createBuffer();i.push(o),t.bindBuffer(34962,o),t.bufferData(34962,a,35044);for(let l=0;l<5;l++)t.enableVertexAttribArray(8+l),t.vertexAttribPointer(8+l,4,5126,!1,80,l*16),t.vertexAttribDivisor(8+l,1);return!0}function Vi(t,e){let i=t.materials?.[e?.material];if(!i)return null;let r=[i.pbrMetallicRoughness?.baseColorTexture,i.pbrMetallicRoughness?.metallicRoughnessTexture,i.normalTexture,i.occlusionTexture,i.emissiveTexture];for(let n of r){let s=n?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var Fr=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),Ur=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Rt(t,e){e.indices?t.drawElements(4,e.indexCount,e.indexType,0):t.drawArrays(4,0,e.indexCount)}function Or(t,e){let i=t?.pbrMetallicRoughness,r=i?.baseColorFactor,n=t?.emissiveFactor,s=t?.extensions?.KHR_materials_clearcoat,a=o=>o!==void 0&&e[o.index]?e[o.index]:null;return{baseColor:r?[r[0],r[1],r[2],r[3]??1]:[.8,.8,.8,1],metallic:i?.metallicFactor??.1,roughness:i?.roughnessFactor??.5,clearcoat:s?s.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,s?.clearcoatRoughnessFactor??.04),texture:a(i?.baseColorTexture),metallicRoughnessTexture:a(i?.metallicRoughnessTexture),normalTexture:a(t?.normalTexture),normalScale:t?.normalTexture?.scale??1,occlusionTexture:a(t?.occlusionTexture),occlusionStrength:t?.occlusionTexture?.strength??1,emissiveTexture:a(t?.emissiveTexture),emissiveFactor:Array.isArray(n)&&n.length>=3?[n[0],n[1],n[2]]:[0,0,0],isTransmissive:(t?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function Br(t,e,i){let r=new Set,n=s=>{s&&!r.has(s)&&(r.add(s),t.deleteTexture(s))};for(let s of e)for(let a of s.primitives){if(a.vao&&t.deleteVertexArray(a.vao),a.buffers)for(let l of a.buffers)t.deleteBuffer(l);for(let l of[a.texture,a.metallicRoughnessTexture,a.normalTexture,a.occlusionTexture,a.emissiveTexture])n(l);let o=new Set;a.customProgram&&o.add(a.customProgram);for(let l of a.programCache?.values()??[])l.program&&o.add(l.program);for(let l of o)t.deleteProgram(l)}if(i)for(let s of i)n(s)}function Cr(t,e,i=Ur,r){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return zi(t,e,i,r,n)}catch(s){let a=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;Br(t,a,n.gpuTextures),n.vao&&t.deleteVertexArray(n.vao);for(let o of n.buffers)t.deleteBuffer(o);throw s}}function zi(t,e,i,r,n){if(!e||!e.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=e,a=Et("meshopt");a?.decodeBufferViews&&a.decodeBufferViews(s,e);let o=e.bin,l=[];n.meshes=l;let m=[],p=s.extensions?.KHR_materials_variants;p&&Array.isArray(p.variants)&&p.variants.forEach((R,A)=>{m.push(typeof R?.name=="string"&&R.name?R.name:`Variant_${A}`)});let v=pn(s),h=[];if(Array.isArray(s.nodes))for(let R=0;R<s.nodes.length;R++){let A=s.nodes[R];A.mesh!==void 0&&s.meshes&&s.meshes[A.mesh]&&h.push({node:A,nodeIdx:R,meshIdx:A.mesh})}let b=h.length>0?h:(s.meshes||[]).map((R,A)=>({node:R,nodeIdx:-1,meshIdx:A})),x=[],g=Array.isArray(e.lights)&&e.lights.length>0?e.lights:Array.isArray(s.asset?.extras?.lights)&&s.asset.extras.lights.length>0?s.asset.extras.lights:null;if(g)for(let R of g)x.push({...R,type:R.type||R.light_type||"point",groundColor:R.groundColor??R.ground_color,innerConeAngle:R.innerConeAngle??R.inner_cone_angle,outerConeAngle:R.outerConeAngle??R.outer_cone_angle});else s.extensions?.KHR_lights_punctual?.lights&&x.push(...wn(s,v));if(x.length===0&&(x.push({type:"ambient",color:[1,1,1],intensity:.35}),x.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),b.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${b.length}`);let c=[];if(n.gpuTextures=c,s.textures&&s.images){if(s.textures.length>i.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${i.maxTextures}). Found: ${s.textures.length}`);for(let R=0;R<s.textures.length;R++){let A=s.textures[R],T=s.images[A.source];if(T){let D=t.createTexture();t.bindTexture(3553,D),t.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255]));for(let[k,I]of[[10242,10497],[10243,10497],[10241,9729],[10240,9729]])t.texParameteri(3553,k,I);let E=k=>{D.__gpuImageSource=k,t.bindTexture(3553,D),t.texImage2D(3553,0,6408,6408,5121,k),t.generateMipmap(3553),r?.()};if(T.bufferView!==void 0){let k=s.bufferViews[T.bufferView],I=k.byteOffset||0,$=new Blob([o.slice(I,I+k.byteLength)],{type:T.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap($).then(E).catch(()=>{})}else if(T.uri){let k=Oi(T.uri);if(k){let I=new Image;I.crossOrigin="anonymous",I.referrerPolicy="no-referrer",I.onload=()=>E(I),I.src=k}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",T.uri)}c.push(D)}else c.push(null)}}let u=[1/0,1/0,1/0],y=[-1/0,-1/0,-1/0],f=0,w=0;for(let R=0;R<b.length;R++){let A=b[R],T=s.meshes[A.meshIdx],D=A.nodeIdx>=0?v[A.nodeIdx]:we(),E=new Float32Array(9);Fe(E,D);let k=A.node?.extras?.shadow,I={name:A.node.name||T.name||`Mesh_${A.meshIdx}`,nodeIndex:A.nodeIdx,transform:D,normalMatrix:E,primitives:[],extras:A.node.extras||T.extras,...A.node?.visible===!1||A.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{},...typeof k?.cast=="boolean"?{castShadow:k.cast}:{},...typeof k?.receive=="boolean"?{receiveShadow:k.receive}:{}};n.mesh=I;let $=A.node?.extensions?.EXT_mesh_gpu_instancing;if($&&$.attributes&&typeof $.attributes=="object"){let N=$.attributes,U=N.TRANSLATION!==void 0?s.accessors?.[N.TRANSLATION]:null,d=N.ROTATION!==void 0?s.accessors?.[N.ROTATION]:null,F=N.SCALE!==void 0?s.accessors?.[N.SCALE]:null,_=N._COLOR_0!==void 0?s.accessors?.[N._COLOR_0]:null,O=Number(U?.count??d?.count??F?.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 q=(G,Y)=>{if(!G||G.bufferView===void 0||!s.bufferViews?.[G.bufferView])return null;let V=G.componentType??5126,J=K=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${K})`),null);if(V!==5120&&V!==5121&&V!==5122&&V!==5123&&V!==5126)return J(`componentType ${V}`);if(!(Number(G.count)>=O))return J(`count ${G.count} < ${O}`);let Z=null;try{Z=gn(s,o,{...G,count:O},Y)}catch{return J("out of bounds")}return!Z||!Z.every(Number.isFinite)?J("non-finite value"):Z},z=q(U,3),W=q(d,4),X=q(F,3),oe=_?.type==="VEC4"?4:3,se=q(_,oe),ae=new Float32Array(O*16),le=we();for(let G=0;G<O;G++){let Y=G*3,V=G*4;ct(le,W?[W[V],W[V+1],W[V+2],W[V+3]]:[0,0,0,1],z?[z[Y],z[Y+1],z[Y+2]]:[0,0,0],X?[X[Y],X[Y+1],X[Y+2]]:[1,1,1]),ae.set(le,G*16)}if(I.instanceMatrices=ae,se){let G=new Float32Array(O*3);for(let Y=0;Y<O;Y++)G[Y*3]=se[Y*oe],G[Y*3+1]=se[Y*oe+1],G[Y*3+2]=se[Y*oe+2];I.instanceColors=G}}}for(let N of T.primitives||[]){if(N.extensions?.KHR_draco_mesh_compression){let B=Et("draco");B&&B.decodePrimitive(s,N,o)}let U=[],d=t.createVertexArray();n.vao=d,n.buffers=U,t.bindVertexArray(d);let F=Bi(t,I,U),_=s.accessors[N.attributes.POSITION],O=Number(_?.count??0);if(!Number.isFinite(O)||O<0||f+O>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(f+=O,_?.min&&_?.max){let B=j=>{for(let H=0;H<3;H++){let Q=j[12+H],ee=Q;for(let re=0;re<3;re++){let he=j[re*4+H]*_.min[re],ne=j[re*4+H]*_.max[re];Q+=he<ne?he:ne,ee+=he>ne?he:ne}Q<u[H]&&(u[H]=Q),ee>y[H]&&(y[H]=ee)}};if(I.instanceMatrices&&I.instanceMatrices.length>=16){let j=I.instanceMatrices.length>>4,H=we();for(let Q=0;Q<j;Q++)xe(H,D,I.instanceMatrices.subarray(Q*16,Q*16+16)),B(H)}else B(D)}let q=yn(t,s,o,N.attributes.POSITION,0,3,U),z=yn(t,s,o,N.attributes.NORMAL,1,3,U),W=yn(t,s,o,N.attributes.TEXCOORD_0,2,2,U,Vi(s,N)),X=0,oe=5123,se=null;if(N.indices!==void 0){let B=s.accessors[N.indices],j=(s.bufferViews[B.bufferView].byteOffset||0)+(B.byteOffset||0);if(X=Number(B.count??0),!Number.isFinite(X)||X<0||w+X>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);w+=X,oe=B.componentType===5125?5125:5123;let H=t.createBuffer();U.push(H),t.bindBuffer(34963,H),B.componentType===5125?se=new Uint32Array(o,j,B.count):B.componentType===5121?se=Uint16Array.from(new Uint8Array(o,j,B.count)):se=j%2===0?new Uint16Array(o,j,B.count):new Uint16Array(o.slice(j,j+B.count*2)),t.bufferData(34963,se,35044)}else X=_.count;let ae={};for(let B of ge)if(B.onBuildPrimitiveVAO){let j=B.onBuildPrimitiveVAO(t,d,N,s,o);j&&(ae[B.name]=j)}t.bindVertexArray(null);let le=s.materials&&N.material!==void 0?s.materials[N.material]:null,{program:G,uniforms:Y}=Nr(t,N,le),V=Or(le,c),J=!!(le?.extensions?.KHR_materials_transmission||ae.materials?.isTransmissive),Z=N.extensions?.KHR_materials_variants?.mappings,K=Array.isArray(Z)?Z.filter(B=>B&&typeof B.material=="number"&&Array.isArray(B.variants)).map(B=>({material:B.material|0,variants:B.variants.map(j=>Number(j)|0)})):void 0;I.primitives.push({vao:d,instanced:F,indexCount:X,indexType:oe,...V,positions:q,normals:z,uvs:W,indices:se,buffers:U,materialIndex:N.material,defaultMaterialIndex:N.material,variantMappings:K,primitiveDef:N,programCache:new Map([[N.material??-1,{program:G,uniforms:Y}]]),pluginData:ae,customProgram:G,customUniforms:Y,isTransmissive:J})}l.push(I)}isFinite(u[0])||(u=[-1,-1,-1]),isFinite(y[0])||(y=[1,1,1]);let M=[(u[0]+y[0])/2,(u[1]+y[1])/2,(u[2]+y[2])/2],S=Math.max(Math.hypot(y[0]-u[0],y[1]-u[1],y[2]-u[2])/2,.5),L=[...u],P=[...y],C=e.animations;if(e.animationsParsed===!1||!C){for(let R of ge)if(R.onParseGLB?.(e),e.animations){C=e.animations;break}}return C||(C=[]),{meshes:l,bounds:{center:M,radius:S,min:L,max:P},lights:x,animations:C,worldMatrices:v,gpuTextures:c,availableVariants:m}}function Tt(){return typeof performance<"u"?performance.now():Date.now()}function lt(t){let e=t.customTarget||t.bounds.center,i=t.currDistance*Math.cos(t.currPhi);return[e[0]+i*Math.sin(t.currTheta),e[1]+t.currDistance*Math.sin(t.currPhi),e[2]+i*Math.cos(t.currTheta)]}var _e=class{constructor(t,e,i){this.supportsInstanceOffsets=!0,this.meshes=[],this.backdropMeshes=[],this.bounds={center:[0,0,0],radius:1,min:[-1,-1,-1],max:[1,1,1]},this.lights=[],this.modelRootMatrix=we(),this.clearColor=[0,0,0,0],this.envIntensity=1,this.exposure=1,this.shadowIntensity=0,this.shadowSoftness=.5,this.toneMapping="neutral",this.environmentTexture=null,this.environmentSource=null,this.animations=[],this.currentClip=null,this.animationTime=0,this.isPlayingAnimation=!1,this.autoplay=!1,this.animationName="",this.gpuTextures=[],this.availableVariants=[],this.activeVariantName=null,this.gltf=null,this.worldMatrices=[],this.initialNodeTransforms=[],this.projMatrix=we(),this.viewMatrix=we(),this.activeViewMatrix=null,this.modelMatrix=we(),this.mvpMatrix=we(),this.normalMatrix=new Float32Array(9),this.initialTheta=.6,this.initialPhi=.35,this.initialDistance=null,this.customDistance=!1,this.distanceMode="auto",this.initialCustomTarget=null,this.customTarget=null,this.fov=Math.PI/4,this.minTheta=-1/0,this.maxTheta=1/0,this.minPhi=-Math.PI*.48,this.maxPhi=Math.PI*.48,this.minDistanceLimit=null,this.maxDistanceLimit=null,this.activePointers=new Map,this.isPanning=!1,this.targetTheta=.6,this.currTheta=.6,this.targetPhi=.35,this.currPhi=.35,this.targetDistance=3,this.currDistance=3,this.autoRotate=!1,this.autoRotateSpeed=Math.PI/6,this.autoRotateDelay=3e3,this.lastInteractionTime=-1/0,this.turntableRotation=0,this.isPointerDown=!1,this.interactive=!0,this.skyboxTexture=null,this.lastPointerX=0,this.lastPointerY=0,this.totalDragDist=0,this.selectedMeshNames=new Set,this.pickFbo=null,this.pickTexture=null,this.pickDepth=null,this.pickFboWidth=0,this.pickFboHeight=0,this.animFrameId=null,this.isVisible=!0,this.xrSessionActive=!1,this.lastTime=0,this.lastReportedTheta=-999,this.lastReportedPhi=-999,this.lastReportedZoom=-999,this.boundPointerDown=null,this.boundPointerMove=null,this.boundPointerUp=null,this.boundWheel=null,this.boundKeyDown=null,this.boundContextMenu=null,this.boundSetCamera=null,this.boundResetCamera=null,this.contextLost=!1,this.lastGlbData=null,this.boundContextLost=null,this.boundContextRestored=null,this.stereoSBS=!1,this.renderErrorReported=!1,this.xrDepthState={enabled:!1,texture:null,uvTransform:we(),rawValueToMeters:.001,format:0},this.container=t;let r,n;if(e&&typeof e.getContext=="function"?(r=e,n=i):(n=e,r=n?.canvas),!r){let l=t.querySelector("canvas");l||(l=document.createElement("canvas"),l.style.cssText="width:100%;height:100%;display:block;touch-action:none",t.prepend(l)),r=l}this.canvas=r;let s=this.opts=n||{};s.clearColor&&(this.clearColor=s.clearColor);let a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;s.autoRotate!==void 0?this.autoRotate=s.autoRotate&&!a:a&&(this.autoRotate=!1),s.autoRotateSpeed!==void 0&&(this.autoRotateSpeed=s.autoRotateSpeed),s.autoRotateDelay!==void 0&&(this.autoRotateDelay=Math.max(0,Number(s.autoRotateDelay)||0)),s.exposure!==void 0&&(this.exposure=xn(s.exposure)),s.camera&&this.setInitialCamera(s.camera.theta,s.camera.phi,s.camera.distance,s.camera.zoom),(s.shadowIntensity!==void 0||s.shadowSoftness!==void 0)&&this.setShadow(s.shadowIntensity??0,s.shadowSoftness),s.shadowMaps!==void 0&&(this.shadowMaps=s.shadowMaps),s.toneMapping!==void 0&&(this.toneMapping=Ke(s.toneMapping)),s.autoplay!==void 0&&(this.autoplay=s.autoplay),s.animationName!==void 0&&(this.animationName=s.animationName),s.variantName!==void 0&&(this.activeVariantName=s.variantName||null),s.fieldOfView!==void 0&&(this.fov=s.fieldOfView*Math.PI/180),s.distanceMode!==void 0&&(this.distanceMode=s.distanceMode),s.cameraTarget!==void 0&&(this.setTarget(s.cameraTarget[0],s.cameraTarget[1],s.cameraTarget[2]),this.initialCustomTarget=[...s.cameraTarget]),(s.minCameraOrbit||s.maxCameraOrbit)&&this.setOrbitLimits({minTheta:s.minCameraOrbit?.theta,maxTheta:s.maxCameraOrbit?.theta,minPhi:s.minCameraOrbit?.phi,maxPhi:s.maxCameraOrbit?.phi,minDistance:s.minCameraOrbit?.distance,maxDistance:s.maxCameraOrbit?.distance});let o=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!o)throw new Error("WebGL2 not supported");this.gl=o,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),s.environmentImage&&this.setEnvironmentImage(s.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&s.autoStart!==!1&&this.start()}static registerDecoder(t,e){Pi(t,e)}static getDecoder(t){return Et(t)}setupContextLossHandling(){let t=this.canvas;typeof t?.addEventListener=="function"&&(this.boundContextLost=e=>{e.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),t.addEventListener("webglcontextlost",this.boundContextLost),t.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let t=this.gl,e=Sn();this.renderProg=ut(t,vn,e.fs),this.pickProg=ut(t,Ni,Fi),this.uRender=_t(t,this.renderProg,e.uniforms),this.uPick=_t(t,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}recompileRenderProgram(){if(this.contextLost)return;let t=this.gl,e=Sn();this.renderProg&&t.deleteProgram(this.renderProg),this.renderProg=ut(t,vn,e.fs),this.uRender=_t(t,this.renderProg,e.uniforms);for(let i of this.meshes)for(let r of i.primitives)r.customProgram&&(t.deleteProgram(r.customProgram),r.programCache?.clear(),this.applyPrimitiveProgram(r,r.materialIndex,this.gltf?.materials?.[r.materialIndex??-1]??null))}restoreContext(){let t=this.gl;this.contextLost=!1,this.initGlState();for(let e of ge)e.onContextRestored?.(t,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let t=this.gl;typeof t.createFramebuffer=="function"&&(this.pickFbo=t.createFramebuffer(),this.pickTexture=t.createTexture(),this.pickDepth=t.createRenderbuffer(),this.resizePickingFbo(this.canvas.width,this.canvas.height),t.bindFramebuffer(36160,this.pickFbo),t.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),t.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),t.bindFramebuffer(36160,null))}resizePickingFbo(t,e){if(!this.pickFbo)return;let i=this.gl,r=Math.max(1,t),n=Math.max(1,e);this.pickFboWidth=r,this.pickFboHeight=n,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,n,0,6408,5121,null),i.texParameteri(3553,10241,9728),i.texParameteri(3553,10240,9728),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,n)}loadGLBData(t,e){let{meshes:i,bounds:r,lights:n,animations:s,worldMatrices:a,gpuTextures:o,availableVariants:l}=Cr(this.gl,t,e,()=>this.render());this.lastGlbData=t,this.lastLimits=e,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=n,this.animations=s||[],this.worldMatrices=a||[],this.gpuTextures=o||[],this.availableVariants=l||[],this.gltf=t.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=(t.gltf?.nodes||[]).map(v=>({t:[v.translation?.[0]??0,v.translation?.[1]??0,v.translation?.[2]??0],r:[v.rotation?.[0]??0,v.rotation?.[1]??0,v.rotation?.[2]??0,v.rotation?.[3]??1],s:[v.scale?.[0]??1,v.scale?.[1]??1,v.scale?.[2]??1]})),this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let v of ge)v.onLoadModel?.(this,this.gltf);this.customDistance||(this.initialDistance=this.distanceMode==="absolute"?3:r.radius*2.5,this.targetDistance=this.initialDistance,this.currDistance=this.initialDistance);let m=t.exposure??t.gltf?.extras?.exposure??t.gltf?.asset?.extras?.exposure;m!==void 0&&(this.exposure=xn(m));let p=t.environmentIntensity??t.gltf?.extras?.environmentIntensity??t.gltf?.asset?.extras?.environmentIntensity;p!==void 0&&(this.envIntensity=Math.max(0,Number(p)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(t){this.loadGLBData(Ir(t))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let t of ge)t.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(t){this.loadGLBData(Xe(t))}setBackdropGLB(t,e){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!t){this.update(0),this.render();return}let i=Xe(t),{meshes:r}=Cr(this.gl,i,Ur,()=>this.render());if(e)for(let n of r)n.transform[12]+=e[0],n.transform[13]+=e[1],n.transform[14]+=e[2],Fe(n.normalMatrix,n.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(t,e,i,r=1){this.clearColor=[t,e,i,r]}updateMeshTransforms(t){for(let e=0;e<this.meshes.length;e++){let i=this.meshes[e],r=t instanceof Map?t.get(i.name)??t.get(e):Array.isArray(t)?t[e]:t&&typeof t=="object"?Object.prototype.hasOwnProperty.call(t,i.name)?t[i.name]:Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0:void 0;r&&r.length===16&&(i.transform.set(r),Fe(i.normalMatrix,i.transform))}}bindLights(t=this.uRender){let e=this.gl,i=[.28,.28,.28],r=[0,0,0,0,0,0,0,1,0],n=!1,s=[],a=[],o=[],l=[],m=[],p=[];for(let v of this.lights){let h=v.color||[1,1,1],b=v.intensity!==void 0?v.intensity:1;if(v.type==="ambient")i=[h[0]*b,h[1]*b,h[2]*b];else if(v.type==="hemisphere"){n=!0;let x=v.groundColor||[.2,.2,.2],g=b*.65;for(let y=0;y<3;y++)r[y]+=h[y]*g,r[y+3]+=x[y]*g;let c=v.position||[0,1,0],u=Math.hypot(c[0],c[1],c[2]);u>1e-5&&(r[6]=c[0]/u,r[7]=c[1]/u,r[8]=c[2]/u)}else if(v.type==="directional"&&s.length<6){let x=v.direction||[.5,1,.8];s.push(x[0],x[1],x[2]),a.push(h[0]*b,h[1]*b,h[2]*b)}else if((v.type==="point"||v.type==="spot")&&o.length<6){let x=v.position||[0,0,0];if(o.push(x[0],x[1],x[2]),l.push(h[0]*b,h[1]*b,h[2]*b),v.type==="spot"){let g=v.direction||[0,-1,0],c=Math.max(.01,Math.min(Math.PI/2,v.outerConeAngle??Math.PI/3)),u=Math.max(0,Math.min(c-1e-4,v.innerConeAngle??0));m.push(g[0],g[1],g[2]),p.push(Math.cos(u),Math.cos(c))}else m.push(0,-1,0),p.push(-2,-3)}}s.length===0&&!n&&(s.push(.5,1,.8),a.push(1,1,1)),e.uniform3fv(t.uAmbientColor,i),t.uHemi&&e.uniformMatrix3fv(t.uHemi,!1,r),e.uniform1i(t.uNumDirLights,s.length/3),s.length>0&&(e.uniform3fv(t.uDirLightDir,s),e.uniform3fv(t.uDirLightColor,a)),e.uniform1i(t.uNumPointLights,o.length/3),o.length>0&&(e.uniform3fv(t.uPointLightPos,o),e.uniform3fv(t.uPointLightColor,l),t.uPointLightSpotDir&&e.uniform3fv(t.uPointLightSpotDir,m),t.uPointLightSpotCone&&e.uniform2fv(t.uPointLightSpotCone,p)),e.uniform1f(t.uEnvIntensity,this.envIntensity)}setExposure(t){this.exposure=xn(t)}getExposure(){return this.exposure}setShadow(t,e){this.shadowIntensity=Math.max(0,Math.min(1,Number(t)||0)),e!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(e)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(t){this.toneMapping=Ke(t)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(t){this.environmentSource=t&&typeof t=="object"?t:null;for(let e of ge)if(e.setEnvironmentImage){await e.setEnvironmentImage(this,t),this.render();return}this.render()}async setSkyboxImage(t){for(let e of ge)if(e.setSkyboxImage){await e.setSkyboxImage(this,t);return}}setInteractive(t){this.interactive=t}isInteractive(){return this.interactive}getCameraOrbit(){let t=this.currTheta,e=this.currPhi,i=this.currDistance;return{theta:t,phi:e,radius:i,toString(){return`${t.toFixed(4)}rad ${e.toFixed(4)}rad ${i.toFixed(4)}m`}}}getCameraTarget(){let t=this.customTarget||this.bounds.center;return{x:t[0],y:t[1],z:t[2],toString(){return`${t[0].toFixed(4)}m ${t[1].toFixed(4)}m ${t[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let t=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return t.map((e,i)=>{let r=this.meshes.flatMap(p=>p.primitives.filter(v=>v.materialIndex===i||t.length===1&&v.materialIndex===void 0)),n=r[0],s=n?[...n.baseColor]:e.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],a=n?n.metallic:e.pbrMetallicRoughness?.metallicFactor??.1,o=n?n.roughness:e.pbrMetallicRoughness?.roughnessFactor??.5,l=(p,v,h)=>{m[p]=h,e.pbrMetallicRoughness&&(e.pbrMetallicRoughness[p]=h);for(let b of r)b[v]=h;this.render()},m={baseColorFactor:s,metallicFactor:a,roughnessFactor:o,setBaseColorFactor:p=>l("baseColorFactor","baseColor",[p[0],p[1],p[2],p[3]??1]),setMetallicFactor:p=>l("metallicFactor","metallic",p),setRoughnessFactor:p=>l("roughnessFactor","roughness",p)};return{name:e.name||`Material_${i}`,pbrMetallicRoughness:m}})}playAnimation(t){if(this.animations.length!==0){if(t){let e=this.animations.find(i=>i.name===t);e&&(this.currentClip=e)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(t=>t.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(t){let e=this.applyVariantMaterial(t);return e&&this.gl&&this.render(),e}applyVariantMaterial(t){let e=t===null||t==="",i=-1;if(e)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(t),i<0)return!1;this.activeVariantName=t}let r=this.gltf?.materials;if(!Array.isArray(r))return e;for(let n of this.meshes)for(let s of n.primitives){let a=s.defaultMaterialIndex;if(!e&&Array.isArray(s.variantMappings)){for(let l of s.variantMappings)if(Array.isArray(l.variants)&&l.variants.includes(i)){a=l.material;break}}let o=a!==void 0?r[a]:void 0;s.materialIndex=o?a:void 0,Object.assign(s,Or(o,this.gpuTextures)),this.applyPrimitiveProgram(s,s.materialIndex,o??null)}return!0}applyPrimitiveProgram(t,e,i){if(!this.gl||!t.primitiveDef)return;t.programCache??(t.programCache=new Map);let r=e??-1,n=t.programCache.get(r);n||(n=Nr(this.gl,{...t.primitiveDef,material:e},i),t.programCache.set(r,n)),t.customProgram=n.program,t.customUniforms=n.uniforms,t.pluginData&&(t.pluginData.materials=t.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(t){this.autoplay=t,t?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(t){this.animationName=t,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(t)}evaluateAnimation(t){for(let e of ge)if(e.evaluateAnimation){e.evaluateAnimation(this,t);return}}setTarget(t,e,i){this.customTarget=[t,e,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(t){let e=Math.max(10,Math.min(90,t));this.fov=e*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(t){if(this.distanceMode=t,!this.customDistance){let e=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=e,this.targetDistance=e,this.currDistance=e,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(t){let e=Math.PI/180,i=Math.PI*.48;t.minTheta!==void 0&&(this.minTheta=t.minTheta*e),t.maxTheta!==void 0&&(this.maxTheta=t.maxTheta*e),t.minPhi!==void 0&&(this.minPhi=Math.max(-i,t.minPhi*e)),t.maxPhi!==void 0&&(this.maxPhi=Math.min(i,t.maxPhi*e)),t.minDistance!==void 0&&(this.minDistanceLimit=t.minDistance),t.maxDistance!==void 0&&(this.maxDistanceLimit=t.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){let t=180/Math.PI;return{minTheta:isFinite(this.minTheta)?this.minTheta*t:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*t:void 0,minPhi:this.minPhi*t,maxPhi:this.maxPhi*t,minDistance:this.minDistanceLimit??void 0,maxDistance:this.maxDistanceLimit??void 0}}clampTheta(t){return Math.max(this.minTheta,Math.min(this.maxTheta,t))}clampPhi(t){return Math.max(this.minPhi,Math.min(this.maxPhi,t))}clampDistance(t){let e=this.bounds?.radius;return Math.max(this.minDistanceLimit??(e?e*.5:.1),Math.min(this.maxDistanceLimit??(e?e*8:100),t))}setCamera(t,e,i,r){t!==void 0&&(this.targetTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.targetPhi=this.clampPhi(e*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(t,e,i,r){t!==void 0&&(this.initialTheta=this.targetTheta=this.currTheta=this.clampTheta(t*Math.PI/180)),e!==void 0&&(this.initialPhi=this.targetPhi=this.currPhi=this.clampPhi(e*Math.PI/180));let n=i!==void 0&&i>0?i:r!==void 0&&r>0?this.bounds.radius*2.5/r:null;this.customDistance=n!==null,this.initialDistance=this.targetDistance=this.currDistance=this.clampDistance(n??(this.distanceMode==="absolute"?3:this.bounds.radius*2.5)),this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.targetDistance=this.clampDistance(this.initialDistance??this.bounds.radius*2.5),this.customTarget=this.initialCustomTarget?[...this.initialCustomTarget]:null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(t,e){let i=we();xe(i,this.projMatrix,this.viewMatrix);let r=(P,C,R=1)=>[P[0]*C[0]+P[4]*C[1]+P[8]*C[2]+P[12]*R,P[1]*C[0]+P[5]*C[1]+P[9]*C[2]+P[13]*R,P[2]*C[0]+P[6]*C[1]+P[10]*C[2]+P[14]*R,P[3]*C[0]+P[7]*C[1]+P[11]*C[2]+P[15]*R],n=this.modelRootMatrix,[s,a,o]=n?r(n,t):t,[l,m,p]=e?n?r(n,e,0):e:[0,0,0],[v,h,b,x]=r(i,[s,a,o]);if(x<=1e-4)return{x:0,y:0,z:1,visible:!1};let g=v/x,c=h/x,u=b/x,y=this.canvas.getBoundingClientRect(),f=y.width||this.canvas.clientWidth||this.canvas.width||300,w=y.height||this.canvas.clientHeight||this.canvas.height||150,M=(g*.5+.5)*f,S=(-c*.5+.5)*w,L=g>=-1.1&&g<=1.1&&c>=-1.1&&c<=1.1&&u>=-1&&u<=1;if(L&&e){let[P,C,R]=lt(this),A=[s-P,a-C,o-R];l*A[0]+m*A[1]+p*A[2]>.05&&(L=!1)}return{x:M,y:S,z:u,visible:L}}setSelectedMesh(t){this.setSelectedMeshes([t])}setSelectedMeshes(t){this.selectedMeshNames=new Set(t.filter(Boolean))}getSelectedMesh(){return[...this.selectedMeshNames][0]||""}setupEvents(){let t=this.canvas,e=Tt;this.boundContextMenu=i=>{i.preventDefault()},t.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=e(),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist=0,this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.isPanning=i.button===2||i.shiftKey||this.activePointers.size===2,t.setPointerCapture(i.pointerId))},t.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=e();let r=this.activePointers.get(i.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},n=i.clientX-r.x,s=i.clientY-r.y;if(this.activePointers.set(i.pointerId,{x:i.clientX,y:i.clientY}),this.lastPointerX=i.clientX,this.lastPointerY=i.clientY,this.totalDragDist+=Math.hypot(n,s),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let a=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],o=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],l=this.customTarget?[...this.customTarget]:[...this.bounds.center],m=this.currDistance/Math.max(t.clientHeight||300,1)*1.5;l[0]+=(-n*a[0]+s*o[0])*m,l[1]+=(-n*a[1]+s*o[1])*m,l[2]+=(-n*a[2]+s*o[2])*m,this.customTarget=l}else this.targetTheta=this.clampTheta(this.targetTheta-n*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},t.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=e(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{t.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=t.getBoundingClientRect(),n=Math.floor((i.clientX-r.left)*(t.width/Math.max(r.width,1))),s=Math.floor((i.clientY-r.top)*(t.height/Math.max(r.height,1)));this.performMeshPick(n,s,!0)}},t.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=e();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},t.addEventListener("wheel",this.boundWheel,{passive:!1}),this.boundSetCamera=i=>{let r=i.detail||{};r.reset?this.resetCamera():this.setCamera(r.theta,r.phi,r.distance,r.zoom)},this.container.addEventListener("setCamera",this.boundSetCamera),this.boundResetCamera=()=>{this.resetCamera()},this.container.addEventListener("resetCamera",this.boundResetCamera),t.tabIndex!==void 0&&t.tabIndex<0&&(t.tabIndex=0),t.getAttribute?.("role")||t.setAttribute?.("role","region"),t.getAttribute?.("aria-label")||t.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=i=>{if(this.interactive){switch(i.key){case"ArrowLeft":this.targetTheta=this.clampTheta(this.targetTheta-.1);break;case"ArrowRight":this.targetTheta=this.clampTheta(this.targetTheta+.1);break;case"ArrowUp":this.targetPhi=this.clampPhi(this.targetPhi+.08);break;case"ArrowDown":this.targetPhi=this.clampPhi(this.targetPhi-.08);break;case"+":case"=":this.targetDistance=this.clampDistance(this.targetDistance*.9);break;case"-":case"_":this.targetDistance=this.clampDistance(this.targetDistance*1.1);break;case"Home":this.resetCamera();break;default:return}this.lastInteractionTime=e(),i.preventDefault()}},t.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let t=(i,r,n)=>{this[n]&&(i.removeEventListener(r,this[n]),this[n]=null)},e=this.canvas;for(let[i,r]of[["webglcontextlost","boundContextLost"],["webglcontextrestored","boundContextRestored"],["contextmenu","boundContextMenu"],["pointerdown","boundPointerDown"],["pointermove","boundPointerMove"],["pointerup","boundPointerUp"],["wheel","boundWheel"],["keydown","boundKeyDown"]])t(e,i,r);t(this.container,"setCamera","boundSetCamera"),t(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(t,e){let i=this.canvas,r=i.getBoundingClientRect(),n=i.width||300,s=i.height||300,a=r.width>0?Math.floor((t-r.left)*(n/r.width)):Math.floor(t),o=r.height>0?Math.floor((e-r.top)*(s/r.height)):Math.floor(e);return this.performMeshPick(a,o,!1)}performMeshPick(t,e,i=!0){if(this.meshes.length===0)return null;let r=this.gl,n=Math.max(1,this.canvas.width||300),s=Math.max(1,this.canvas.height||300);t=this.mapStereoPickX(t,n);let a=we();xe(a,this.projMatrix,this.viewMatrix);let o=[],l=Math.max(0,Math.min(n-1,t)),m=Math.max(0,Math.min(s-1,s-1-e));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==n||this.pickFboHeight!==s)&&this.resizePickingFbo(n,s),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,n,s),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16640),r.useProgram(this.pickProg);for(let M=0;M<this.meshes.length;M++){let S=this.meshes[M];if(S.visible===!1||S.isPluginMesh)continue;let L=M+1,P=(L&255)/255,C=(L>>8&255)/255,R=(L>>16&255)/255;r.uniform4f(this.uPick.uColorId,P,C,R,1),xe(this.modelMatrix,this.modelRootMatrix,S.transform);let A=S.instanceMatrices;if(A&&A.length>=16){let T=A.length>>4,D=we();for(let E of S.primitives){r.bindVertexArray(E.vao);for(let k=0;k<T;k++)xe(D,this.modelMatrix,A.subarray(k*16,k*16+16)),xe(this.mvpMatrix,a,D),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Rt(r,E)}}else{xe(this.mvpMatrix,a,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let T of S.primitives)r.bindVertexArray(T.vao),Rt(r,T)}}let f=new Uint8Array(4);r.readPixels(l,m,1,1,6408,5121,f),r.bindFramebuffer(36160,null);let w=f[0]+(f[1]<<8)+(f[2]<<16);w>0&&w<=this.meshes.length&&(o=[this.meshes[w-1]])}o.length===0&&(o=this.meshes.filter(f=>f.visible!==!1));let p=null,v=1/0,h=[0,0,0],b=[0,1,0],[x,g,c]=lt(this),u=we();for(let f of o){xe(u,this.modelRootMatrix,f.transform);let w=f.instanceMatrices,M=w&&w.length>=16?w.length>>4:1;for(let S=0;S<M;S++){w&&w.length>=16?xe(this.modelMatrix,u,w.subarray(S*16,S*16+16)):this.modelMatrix.set(u),xe(this.mvpMatrix,a,this.modelMatrix);let L=we();if(!_r(L,this.mvpMatrix))continue;let P=(l+.5)/n*2-1,C=(m+.5)/s*2-1,R=[0,0,0],A=[0,0,0];fn(R,P,C,-1,L),fn(A,P,C,1,L);let T=A[0]-R[0],D=A[1]-R[1],E=A[2]-R[2],k=Math.hypot(T,D,E)||1,I=T/k,$=D/k,N=E/k,U={distance:1/0,point:[0,0,0],normal:[0,1,0]};for(let d of f.primitives){if(!d.positions)continue;let F=d.positions,_=d.indices,O=Math.floor(_?_.length/3:F.length/9);for(let q=0;q<O;q++){let z=(_?_[q*3]:q*3)*3,W=(_?_[q*3+1]:q*3+1)*3,X=(_?_[q*3+2]:q*3+2)*3;Er(R[0],R[1],R[2],I,$,N,F[z],F[z+1],F[z+2],F[W],F[W+1],F[W+2],F[X],F[X+1],F[X+2],U,1e-4)}}if(isFinite(U.distance)){let d=U.point[0],F=U.point[1],_=U.point[2],O=this.modelMatrix,q=O[0]*d+O[4]*F+O[8]*_+O[12],z=O[1]*d+O[5]*F+O[9]*_+O[13],W=O[2]*d+O[6]*F+O[10]*_+O[14],X=q-x,oe=z-g,se=W-c,ae=Math.hypot(X,oe,se);if(ae<v){Fe(this.normalMatrix,this.modelMatrix);let le=this.normalMatrix,G=U.normal[0],Y=U.normal[1],V=U.normal[2],J=le[0]*G+le[3]*Y+le[6]*V,Z=le[1]*G+le[4]*Y+le[7]*V,K=le[2]*G+le[5]*Y+le[8]*V,B=Math.hypot(J,Z,K)||1;J/=B,Z/=B,K/=B,J*X+Z*oe+K*se>0&&(J=-J,Z=-Z,K=-K);let j=H=>Math.round(H*1e3)/1e3;p=f,v=j(ae),h=[j(q),j(z),j(W)],b=[j(J),j(Z),j(K)]}}}}if(!p)return null;let y={meshIndex:this.meshes.indexOf(p),meshName:p.name,nodeIndex:p.nodeIndex,distance:v,hitPoint:h,normal:b,screenX:t,screenY:e};if(i){for(let f of ge)f.onMeshSelect?.(this,y);this.opts.onMeshClick&&this.opts.onMeshClick(y),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:y}))}return y}mapStereoPickX(t,e){if(!this.stereoSBS||this.xrSessionActive||e<2)return t;let i=Math.max(1,Math.floor(e*.5)),r=t>=i,n=r?t-i:t,s=r?Math.max(1,e-i):i,a=(n+.5)/s*2-1;return Math.floor((a*.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);dn(this.projMatrix,this.fov,t,.1,e);let i=this.customTarget||this.bounds.center;at(this.viewMatrix,lt(this),i,[0,1,0]),xe(this.mvpMatrix,this.projMatrix,this.viewMatrix),Fe(this.normalMatrix,this.modelMatrix)}resize(){let t=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),e=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.floor(e.width*t)),r=Math.max(1,Math.floor(e.height*t));this.canvas.width!==i||this.canvas.height!==r?(this.canvas.width=i,this.canvas.height=r,this.resizePickingFbo(i,r),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(t){let e=this.xrSessionActive;if(this.xrSessionActive=t,e&&!t){this.xrDepthState.enabled=!1;for(let i of ge)i.onXRSessionEnd?.(this);if(this.lastTime=Tt(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(i){this.reportRenderError(i)}}}reportRenderError(t){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",t))}stepXRUpdate(t){for(let e of ge)e.onUpdate?.(this,t)}start(){if(this.animFrameId!==null)return;this.lastTime=Tt();let t=e=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((e-this.lastTime)/1e3,0),.1);if(this.lastTime=e,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(t))};this.animFrameId=requestAnimationFrame(t)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(t){this.autoRotate=t}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(t){this.autoRotateSpeed=t}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(t){this.autoRotateDelay=Math.max(0,Number(t)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(t=0){this.turntableRotation=Number(t)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let t=Math.cos(this.turntableRotation),e=Math.sin(this.turntableRotation),[i,,r]=this.bounds.center;this.modelRootMatrix.set([t,0,-e,0,0,1,0,0,e,0,t,0,i-(t*i+e*r),0,r-(-e*i+t*r),1])}setVisible(t){this.isVisible=t}update(t){for(let s of ge)s.onUpdate?.(this,t);let e=Tt();if(!this.isPointerDown&&this.autoRotate&&e-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*t,this.updateTurntableMatrix();for(let s of ge)s.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let i=Math.round((this.currTheta*180/Math.PI%360+360)%360),r=Math.round(this.currPhi*180/Math.PI),n=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(i-this.lastReportedTheta)>=1||Math.abs(r-this.lastReportedPhi)>=1||Math.abs(n-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=n;let s={theta:i,phi:r,zoom:n,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(s),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:s}))}}renderXRView(t,e,i,r,n=!0,s=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(t);let a=t?.transform?.inverse?.matrix||this.viewMatrix,o=t?.projectionMatrix||this.projMatrix,l=t?.transform?.position,m=l?[l.x,l.y,l.z]:[0,1.6,0];e&&this.modelRootMatrix.set(e),this.render({viewMatrix:a,projMatrix:o,eyePos:m,viewport:r,eye:t?.eye||"none",clear:s>0?!1:t?.eye!=="right",isAR:n})}render(t){if(this.contextLost)return;if(!t&&this.stereoSBS){let S=Math.max(2,this.canvas.width||2),L=Math.max(1,this.canvas.height||1),P=Math.max(1,Math.floor(S*.5)),C=Math.max(1,S-P),R=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),A=this.customTarget||this.bounds.center,[T,D,E]=lt(this),k=Math.cos(this.currTheta),I=-Math.sin(this.currTheta),$=.032;for(let N of[-1,1]){let U=we(),d=we(),F=N<0?P:C,_=[T+N*k*$,D,E+N*I*$];dn(U,this.fov,F/L,.1,R),at(d,_,[A[0]+N*k*$*.25,A[1],A[2]+N*I*$*.25],[0,1,0]),this.render({viewMatrix:d,projMatrix:U,eyePos:_,viewport:[N<0?0:P,0,F,L],eye:N<0?"left":"right",clear:N<0,isAR:!1})}this.gl.viewport(0,0,S,L);return}let e=this.gl,[i,r,n,s]=t?.viewport||[0,0,this.canvas.width,this.canvas.height];if(e.viewport(i,r,n,s),e.enable(2929),!t||t.clear!==!1){let S=t?.isAR?[0,0,0,0]:this.clearColor;e.clearColor(S[0],S[1],S[2],S[3]),e.clear(16640)}let a=we(),o=t?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o;let l=t?.projMatrix??this.projMatrix;xe(a,l,o);let m=ue(),p=m.xrDepthShader,v=Ci(this.toneMapping),[h,b,x]=t?t.eyePos:lt(this);for(let S of ge)S.onBeforeDrawScene?.(this,e,a,[h,b,x],v);let g=t?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&g===0){m.gpuSceneAccelerator?.hideLayer?.(this);return}let c=t?.eye||"none",u=!t||t.clear!==!1;if(!this.xrSessionActive&&m.gpuSceneAccelerator?.renderScene(this,a,l,o,[h,b,x],v,[i,r,n,s],c,u,!!t?.isAR)){u&&!this.skyboxTexture&&(e.clearColor(0,0,0,0),e.clear(16384));for(let S of ge)S.name.includes("webgpu")&&S.onAfterRender?.(e,this,a,c,[i,r,n,s],l);return}let y=!1,f=g>0?[...this.backdropMeshes,...this.meshes]:this.meshes,w=(S,L,P,C)=>{L?(e.activeTexture(33984+S),e.bindTexture(3553,L),e.uniform1i(P,S),e.uniform1i(C,1)):e.uniform1i(C,0)},M=S=>{for(let L=0;L<f.length;L++){let P=f[L];if(P.visible===!1)continue;let C=this.selectedMeshNames.has(P.name);if(L<g||P.worldSpace===!0||P.name==="__xr_reticle__")this.modelMatrix.set(P.transform);else{xe(this.modelMatrix,this.modelRootMatrix,P.transform);let k=!t&&(P.extras?.xr?.billboard??P.userData?.xr?.billboard);if(k){let I=this.modelMatrix,$=Math.hypot(I[0],I[1],I[2])||1,N=Math.hypot(I[4],I[5],I[6])||1,U=Math.hypot(I[8],I[9],I[10])||1,d=k==="y"||k==="cylindrical"||k==="capsule",F=h-I[12],_=x-I[14],O=Math.hypot(F,_),q=O>1e-5?F/O:0,z=O>1e-5?_/O:1;I.set(d?[z*$,0,-q*$,0,0,N,0,0,q*U,0,z*U]:[o[0]*$,o[4]*$,o[8]*$,0,o[1]*N,o[5]*N,o[9]*N,0,o[2]*U,o[6]*U,o[10]*U])}}xe(this.mvpMatrix,a,this.modelMatrix),Fe(P.normalMatrix,this.modelMatrix);let R=P.extras?.xr?.stereo||P.userData?.xr?.stereo,A=0,T=0,D=1,E=1;R==="sbs"?(D=.5,A=c==="right"?.5:0):R==="ou"&&(E=.5,T=c==="right"?.5:0);for(let k of P.primitives){let I=!!k.isTransmissive;if(!S&&I){y=!0;continue}if(S&&!I)continue;let $=k.customProgram||this.renderProg,N=k.customUniforms||this.uRender;e.useProgram($),e.vertexAttrib3f(3,0,0,0),N.uInstanced&&e.uniform1i(N.uInstanced,0),e.uniform1i(N.uToneMapping,v),e.uniform1f(N.uEnvIntensity,this.envIntensity),N.uExposure&&e.uniform1f(N.uExposure,this.exposure),e.uniform3f(N.uCameraPos,h,b,x),e.uniform1f(N.uEmissive,C?1:0),e.uniformMatrix4fv(N.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(N.uModel,!1,this.modelMatrix),e.uniformMatrix3fv(N.uNormalMatrix,!1,P.normalMatrix),N.uUvTransform&&e.uniform4f(N.uUvTransform,A,T,D,E),N.uViewportSize&&e.uniform2f(N.uViewportSize,Math.max(1,n),Math.max(1,s)),p?.bind(e,N,this.xrDepthState,o,[i,r,Math.max(1,n),Math.max(1,s)]),m.shadowMapShader?.bind(e,N,this,P),w(4,this.environmentTexture,N.uEnvironmentMap,N.uHasEnvironmentMap),this.bindLights(N),N.uSectionEnabled&&e.uniform1i(N.uSectionEnabled,0);for(let d of ge)d.onBeforeDrawPrimitive?.(e,$,k,P,this.worldMatrices||[],this.gltf);e.uniform4fv(N.uBaseColor,k.baseColor),e.uniform1f(N.uMetallic,k.metallic),e.uniform1f(N.uRoughness,k.roughness),N.uClearcoat&&e.uniform2f(N.uClearcoat,k.clearcoat??0,k.clearcoatRoughness??.04),w(0,k.texture,N.uBaseColorTexture,N.uHasTexture),w(1,k.metallicRoughnessTexture,N.uMetallicRoughnessTexture,N.uHasMetallicRoughnessTexture),w(2,k.normalTexture,N.uNormalTexture,N.uHasNormalTexture),k.normalTexture&&e.uniform1f(N.uNormalScale,k.normalScale),w(3,k.occlusionTexture,N.uOcclusionTexture,N.uHasOcclusionTexture),k.occlusionTexture&&e.uniform1f(N.uOcclusionStrength,k.occlusionStrength),e.uniform3fv(N.uEmissiveFactor,k.emissiveFactor),w(8,k.emissiveTexture,N.uEmissiveTexture,N.uHasEmissiveTexture),e.bindVertexArray(k.vao);let U=P.instanceMatrices;if(k.instanceCount!==void 0)e.drawElementsInstanced(4,k.indexCount,k.indexType,0,k.instanceCount);else if(U&&U.length>=16&&k.instanced&&N.uInstanced&&N.uViewProj){let d=U.length>>4;e.uniform1i(N.uInstanced,1),e.uniformMatrix4fv(N.uViewProj,!1,a),k.indices?e.drawElementsInstanced(4,k.indexCount,k.indexType,0,d):e.drawArraysInstanced(4,0,k.indexCount,d),e.uniform1i(N.uInstanced,0)}else if(U&&U.length>=16){let d=U.length>>4,F=P.instanceColors,_=we(),O=new Float32Array(9);for(let q=0;q<d;q++){if(xe(_,this.modelMatrix,U.subarray(q*16,q*16+16)),xe(this.mvpMatrix,a,_),Fe(O,_),e.uniformMatrix4fv(N.uMVP,!1,this.mvpMatrix),e.uniformMatrix4fv(N.uModel,!1,_),e.uniformMatrix3fv(N.uNormalMatrix,!1,O),F){let z=k.baseColor,W=q*3;e.uniform4fv(N.uBaseColor,[z[0]*F[W],z[1]*F[W+1],z[2]*F[W+2],z[3]])}Rt(e,k)}}else Rt(e,k)}}};if(M(!1),y){for(let S of ge)S.onBeforeTransmissivePass?.(e,this);M(!0)}for(let S of ge)S.onAfterRender?.(e,this,a,c,[i,r,n,s],l)}disposeMeshListGpuResources(t,e){Br(this.gl,t,e)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let t=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let e of ge)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()}};_e.registerPlugin=wt,_e.getRegisteredPlugins=Mr;function Gi(t){return t+3&-4}var te=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function Mn(t,e){let i=e,r=1;for(;t.has(i);)i=`${e}_${r++}`;return t.add(i),i}function zr(t,e,i){let r=Math.hypot(t,e,i)||1,n=t/r,s=e/r,a=-(i/r);if(a<-.999999)return[0,1,0,0];let o=Math.sqrt((1+a)*2);return[s/o,-n/o,0,o*.5]}function Gr(t,e=0){let[i,r,n,,s,a,o,,l,m,p,,v,h,b]=Array.from({length:15},(U,d)=>te(t[e+d],d%5===0?1:0)),x=Math.hypot(i,r,n),g=Math.hypot(s,a,o),c=Math.hypot(l,m,p);i*(a*p-m*o)-s*(r*p-m*n)+l*(r*o-a*n)<0&&(x=-x);let u=Math.abs(x)>1e-8?1/x:0,y=Math.abs(g)>1e-8?1/g:0,f=Math.abs(c)>1e-8?1/c:0,w=i*u,M=r*u,S=n*u,L=s*y,P=a*y,C=o*y,R=l*f,A=m*f,T=p*f,D=w+P+T,E=0,k=0,I=0,$=1;if(D>0){let U=.5/Math.sqrt(D+1);$=.25/U,E=(C-A)*U,k=(R-S)*U,I=(M-L)*U}else if(w>P&&w>T){let U=2*Math.sqrt(Math.max(0,1+w-P-T));U>1e-8&&($=(C-A)/U,E=.25*U,k=(L+M)/U,I=(R+S)/U)}else if(P>T){let U=2*Math.sqrt(Math.max(0,1+P-w-T));U>1e-8&&($=(R-S)/U,E=(L+M)/U,k=.25*U,I=(C+A)/U)}else{let U=2*Math.sqrt(Math.max(0,1+T-w-P));U>1e-8&&($=(M-L)/U,E=(R+S)/U,k=(C+A)/U,I=.25*U)}let N=Math.hypot(E,k,I,$);return N>1e-8&&Number.isFinite(N)?(E/=N,k/=N,I/=N,$/=N):(E=0,k=0,I=0,$=1),{t:[v,h,b],r:[E,k,I,$],s:[x,g,c]}}function Hi(t){let e={};return t.grab&&(e.interactable={mode:typeof t.grab=="string"?t.grab:"2-hand"},e.movable={scaleInZ:!!t.scale,minScale:typeof t.scale=="object"?t.scale.min??.1:.1,maxScale:typeof t.scale=="object"?t.scale.max??10:10}),t.billboard&&(e.billboard={mode:typeof t.billboard=="string"?t.billboard:"capsule"}),t.follow&&(e.follow={target:typeof t.follow=="object"?t.follow.mode??"head":t.follow}),t.anchor&&(e.anchor={plane:t.anchor}),t.physics&&t.physics!=="none"&&(e.rigidbody={type:t.physics}),e}var ke=(t,e,i,r)=>typeof t=="number"&&Number.isFinite(t)?Math.max(e,Math.min(i,t)):r;function Hr(t){let e=t?.audioEmitter??t?.spatialAudio??(typeof t?.audio=="object"&&t.audio&&("preset"in t.audio||"distanceModel"in t.audio||"coneInnerAngle"in t.audio||"maxDistance"in t.audio||"volume"in t.audio)?t.audio:typeof t?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(t.audio)?{preset:t.audio}:void 0);if(!e||typeof e=="object"&&e.enabled===!1)return null;let i=typeof e=="string"?{preset:e}:e,r=typeof i.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(i.src)?i.src:void 0,n=typeof i.preset=="string"?i.preset:void 0;return!r&&!n?null:{ae:i,src:r,preset:n,volume:ke(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function Wi(t){let e=t?.material,i=e?._presetMaps?.map;if(!i||i!==e.map)return null;let r=/^ai_([0-9a-f]{16})_albedo$/.exec(String(i.name??""));return r?r[1]:null}function dt(t,e){return Wr(t,e)[0]}function Wr(t,e){t.updateMatrixWorld(!0);let i=[],r=0,n=[],s=[],a=[],o=[],l=new Set,m=[],p=[],v=new Map,h=[],b=[],x=[],g=new Map,c=[],u=[],y=[],f=!1;function w(d){let F=v.get(d);if(F!==void 0)return F;F=p.length,v.set(d,F);let _=d,O=_.color?.r??1,q=_.color?.g??1,z=_.color?.b??1,W=_.opacity??1,X={baseColorFactor:[O,q,z,W],metallicFactor:_.metalness??0,roughnessFactor:_.roughness??.5},oe={},se=ne=>{if(!ne)return;let be=(typeof ne=="string"?ne:typeof ne.source=="string"?ne.source:typeof ne.image=="string"?ne.image:"").trim();if(!be||/[\x00-\x1f\x7f\\]|\.\./.test(be)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(be)||!be.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(be)))return;let ce=g.get(be);if(ce===void 0){let pe=h.length;h.push({uri:be}),b.length===0&&b.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),ce=x.length,x.push({sampler:0,source:pe}),g.set(be,ce)}return{index:ce}},ae=_._packPbr?.(),le=se(_.map);le&&(X.baseColorTexture=le);let G=se(ae?.mrUri||_.roughnessMap||_.metalnessMap);G&&(X.metallicRoughnessTexture=G);let Y=_.map?.avgColor;Array.isArray(Y)&&Y.length>=3&&(oe.avgColor=[Y[0],Y[1],Y[2]]);let V=se(ae?.normUri||_.normalMap),J=_.normalScale,Z=ae?.normUri?ae.normScale??1:typeof J=="number"?Math.max(0,te(J,1)):J?Math.max(0,(te(J.x,1)+te(J.y,1))*.5):1;V&&Z!==1&&(V.scale=Z);let K=se(_.emissiveMap),B=se(_.aoMap),j=Math.max(0,Math.min(1,te(_.aoMapIntensity,1)));B&&j!==1&&(B.strength=j);let H={name:_.name||"",pbrMetallicRoughness:X,doubleSided:_.side===2||!!_.doubleSided,...W<1||_.transparent?{alphaMode:"BLEND"}:{},...V?{normalTexture:V}:{},...K?{emissiveTexture:K}:{},...B?{occlusionTexture:B}:{},...Object.keys(oe).length>0?{extras:oe}:{}},Q=Math.max(0,te(_.emissiveIntensity,1)),ee=_.emissive&&(_.emissive.r>0||_.emissive.g>0||_.emissive.b>0);(ee||K&&!_._em&&Q>0)&&(H.emissiveFactor=ee?[_.emissive.r*Q,_.emissive.g*Q,_.emissive.b*Q]:[Q,Q,Q]);let re={};_.clearcoat&&_.clearcoat>0&&(re.KHR_materials_clearcoat={clearcoatFactor:_.clearcoat,clearcoatRoughnessFactor:_.clearcoatRoughness||0}),_.sheen&&_.sheen>0&&(re.KHR_materials_sheen={sheenColorFactor:_.sheenColor?[_.sheenColor.r,_.sheenColor.g,_.sheenColor.b]:[1,1,1],sheenRoughnessFactor:_.sheenRoughness||0}),_.transmission&&_.transmission>0&&(re.KHR_materials_transmission={transmissionFactor:_.transmission}),_.thickness&&_.thickness>0&&(re.KHR_materials_volume={thicknessFactor:_.thickness,attenuationDistance:_.attenuationDistance??1/0,attenuationColor:_.attenuationColor?[_.attenuationColor.r,_.attenuationColor.g,_.attenuationColor.b]:[1,1,1]}),_.ior!==void 0&&_.ior!==1.5&&(re.KHR_materials_ior={ior:_.ior}),_.dispersion&&_.dispersion>0&&(re.KHR_materials_dispersion={dispersion:_.dispersion}),_.iridescence&&_.iridescence>0&&(re.KHR_materials_iridescence={iridescenceFactor:_.iridescence,iridescenceIor:_.iridescenceIOR??1.3});let he=_._serializeTslGraph?.();return he&&(re.GOOGLE_material_tsl=he,l.add("GOOGLE_material_tsl")),Object.keys(re).length>0&&(H.extensions=re),p.push(H),F}function M(d,F){let _=new Uint8Array(d.buffer,d.byteOffset,d.byteLength),O=Gi(_.byteLength),q=new Uint8Array(O);q.set(_),i.push(q);let z=n.length;return n.push({buffer:0,byteOffset:r,byteLength:_.byteLength,target:F}),r+=O,z}function S(d,F,_,O,q,z,W){let X=M(d,_),oe=s.length,se={bufferView:X,byteOffset:0,componentType:O,count:q,type:F};return z&&(se.min=z),W&&(se.max=W),s.push(se),oe}let L=[],P=[],C=new Set([t]),R=[];if(Array.isArray(t.children))for(let d=t.children.length-1;d>=0;d--)R.push({obj:t.children[d],parentKids:P});for(;R.length>0;){let{obj:d,parentKids:F}=R.pop();if(!d||typeof d!="object"||C.has(d))continue;C.add(d),d._bakeAuthorGeometry?.(),ue().materializeDeclarativeGeometry?.(d);let _=!!(d.userData&&(d.userData.xr&&typeof d.userData.xr=="object"&&Object.keys(d.userData.xr).length>0||d.userData.interactivity&&typeof d.userData.interactivity=="object"&&Object.keys(d.userData.interactivity).length>0)),O={name:d.name||(_?`Node_${o.length}`:"")},q=te(d.position?.x,0),z=te(d.position?.y,0),W=te(d.position?.z,0),X=te(d.quaternion?.x,0),oe=te(d.quaternion?.y,0),se=te(d.quaternion?.z,0),ae=te(d.quaternion?.w,1),le=te(d.scale?.x,1),G=te(d.scale?.y,1),Y=te(d.scale?.z,1);if((q||z||W)&&(O.translation=[q,z,W]),(X||oe||se||ae!==1)&&(O.rotation=[X,oe,se,ae]),(le!==1||G!==1||Y!==1)&&(O.scale=[le,G,Y]),d.visible===!1&&(O.extensions={...O.extensions||{},KHR_node_visibility:{visible:!1}},l.add("KHR_node_visibility")),d.userData&&Object.keys(d.userData).length>0&&(O.extras=JSON.parse(JSON.stringify(d.userData,(B,j)=>{if(!(B==="__proto__"||B==="prototype"||B==="constructor"))return typeof j=="function"?void 0:j})),d.userData.xr)){let B=Hi(d.userData.xr);O.extensions={...O.extensions||{},MOZ_hubs_components:B,ANDROID_xr_scenecore:B},ue().xrTraitSerializer?.gltfNode(O,d.userData.xr);let j=Wi(d),H=O.extras?.xr?.material;j&&H&&typeof H=="object"&&!Array.isArray(H)&&(H.textureKey=j),l.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}let V=d,J=V.isLight||V.color&&V.intensity!==void 0;if(!J&&(V._castShdSet||V._recvShdSet||d.castShadow||d.receiveShadow)&&(O.extras={...O.extras||{},shadow:{cast:!!d.castShadow,receive:V._recvShdSet?!!d.receiveShadow:!!(d.receiveShadow||d.castShadow)}}),J){let B=V.matrixWorld?.elements,j=te(B?B[12]:d.position?.x,0),H=te(B?B[13]:d.position?.y,0),Q=te(B?B[14]:d.position?.z,0),ee=V.target,re=ee?.parent?ee?.matrixWorld?.elements:void 0,he=te(re?re[12]:ee?.position?.x,0),ne=te(re?re[13]:ee?.position?.y,0),be=te(re?re[14]:ee?.position?.z,0),ce=he-j,pe=ne-H,me=be-Q,de=Math.hypot(ce,pe,me),Se=Math.max(.01,Math.min(Math.PI/2,te(V.angle,Math.PI/3))),Te=Math.max(0,Math.min(1,te(V.penumbra,0))),fe=Math.max(0,Se*(1-Te)),Ce=Math.max(0,te(V.distance,0)),Ye=d.type==="directional"||d.type==="spot"||d.type==="point",Ve;if(d.castShadow&&Ye){let st=V.shadow,Rs=Math.max(256,Math.min(2048,Math.round(te(st?.mapSize?.x??st?.mapSize?.width,1024))));Ve={cast:!0,mapSize:Rs<=384?256:Rs<=768?512:Rs<=1536?1024:2048,bias:ke(st?.bias,-.05,.05,-5e-4),normalBias:ke(st?.normalBias,0,.2,.015),radius:ke(st?.radius,0,8,1.5)},f=!0}let gs=j-he,bs=H-ne,As=Q-be,vt=Math.hypot(gs,bs,As);u.push({type:d.type,color:[d.color.r,d.color.g,d.color.b],intensity:d.intensity,position:d.type==="directional"?[gs,bs,As]:[j,H,Q],...d.type==="directional"?{direction:vt>1e-6?[gs/vt,bs/vt,As/vt]:[0,1,0]}:d.type==="spot"?{direction:de>1e-6?[ce/de,pe/de,me/de]:[0,-1,0],outerConeAngle:Se,innerConeAngle:fe,range:Ce}:d.type==="point"?{range:Ce}:d.type==="hemisphere"&&V.groundColor?{groundColor:[V.groundColor.r,V.groundColor.g,V.groundColor.b]}:{},...Ve?{shadow:Ve}:{}}),Ye&&L.push({node:O,obj:d,px:j,py:H,pz:Q,tx:he,ty:ne,tz:be,dx:ce,dy:pe,dz:me,dLen:de,outerAngle:Se,innerAngle:fe,range:Ce,shadowSpec:Ve})}if(d.geometry){let B=d.geometry,j=B.attributes.position;if(j&&j.count>0){let H=[1/0,1/0,1/0],Q=[-1/0,-1/0,-1/0];for(let ce=0;ce<j.count;ce++){let pe=j.getX(ce),me=j.getY(ce),de=j.getZ(ce);pe<H[0]&&(H[0]=pe),pe>Q[0]&&(Q[0]=pe),me<H[1]&&(H[1]=me),me>Q[1]&&(Q[1]=me),de<H[2]&&(H[2]=de),de>Q[2]&&(Q[2]=de)}let ee={attributes:{POSITION:S(j.array,"VEC3",34962,5126,j.count,H,Q)}};if(B.attributes.normal&&(ee.attributes.NORMAL=S(B.attributes.normal.array,"VEC3",34962,5126,B.attributes.normal.count)),B.attributes.uv&&(ee.attributes.TEXCOORD_0=S(B.attributes.uv.array,"VEC2",34962,5126,B.attributes.uv.count)),B.index){let ce=B.index.array instanceof Uint32Array;ee.indices=S(B.index.array,"SCALAR",34963,ce?5125:5123,B.index.count)}let re=Array.isArray(d.material)?d.material[0]:d.material;re&&(ee.material=w(re));let he=d.userData?.variants;if(he&&typeof he=="object"){let ce=new Map;for(let pe of Object.keys(he)){if(!pe||pe==="__proto__"||pe==="constructor"||pe==="prototype")continue;let me=he[pe];if(!me||typeof me!="object")continue;let de=c.indexOf(pe);if(de===-1&&c.length<256&&(de=c.length,c.push(pe)),de===-1)continue;let Se=w(me),Te=ce.get(Se);Te||(Te=[],ce.set(Se,Te)),Te.push(de)}if(ce.size>0){let pe=[];for(let[me,de]of ce.entries())pe.push({material:me,variants:de});ee.extensions={...ee.extensions||{},KHR_materials_variants:{mappings:pe}},l.add("KHR_materials_variants")}}let ne=d;if(ne.isInstancedMesh&&typeof ne.count=="number"&&ne.count>0&&ne.instanceMatrix?.array){let ce=Math.min(1e4,Math.floor(ne.count)),pe=ne.instanceMatrix.array,me=new Float32Array(ce*3),de=new Float32Array(ce*4),Se=new Float32Array(ce*3);for(let fe=0;fe<ce;fe++){let{t:Ce,r:Ye,s:Ve}=Gr(pe,fe*16);me[fe*3]=Ce[0],me[fe*3+1]=Ce[1],me[fe*3+2]=Ce[2],de[fe*4]=Ye[0],de[fe*4+1]=Ye[1],de[fe*4+2]=Ye[2],de[fe*4+3]=Ye[3],Se[fe*3]=Ve[0],Se[fe*3+1]=Ve[1],Se[fe*3+2]=Ve[2]}let Te={TRANSLATION:S(me,"VEC3",0,5126,ce),ROTATION:S(de,"VEC4",0,5126,ce),SCALE:S(Se,"VEC3",0,5126,ce)};if(ne.instanceColor?.array&&ne.instanceColor.array.length>=ce*3){let fe=new Float32Array(ne.instanceColor.array.subarray(0,ce*3));Te._COLOR_0=S(fe,"VEC3",0,5126,ce)}O.extensions={...O.extensions||{},EXT_mesh_gpu_instancing:{attributes:Te}},l.add("EXT_mesh_gpu_instancing")}let be=a.length;a.push({primitives:[ee],name:d.name,...O.extras?{extras:O.extras}:{}}),O.mesh=be}}let Z=o.length;o.push(O),m.push(d),F.push(Z);let K=d.children;if(Array.isArray(K)&&K.length>0){let B=[];O.children=B;for(let j=K.length-1;j>=0;j--)R.push({obj:K[j],parentKids:B})}}if(f)for(let d of L){let F=y.length;if(y.push({name:d.obj.name||`Light_${F}`,type:d.obj.type,color:[d.obj.color.r,d.obj.color.g,d.obj.color.b],intensity:d.obj.intensity,...d.range>0&&(d.obj.type==="point"||d.obj.type==="spot")?{range:d.range}:{},...d.obj.type==="spot"?{spot:{innerConeAngle:d.innerAngle,outerConeAngle:d.outerAngle}}:{},...d.shadowSpec?{extras:{shadow:d.shadowSpec}}:{}}),d.node.extensions={...d.node.extensions||{},KHR_lights_punctual:{light:F}},l.add("KHR_lights_punctual"),d.obj.type==="directional"||d.obj.type==="spot"){let _=d.dLen>1e-6?d.dx/d.dLen:0,O=d.dLen>1e-6?d.dy/d.dLen:-1,q=d.dLen>1e-6?d.dz/d.dLen:0;d.node.rotation=zr(_,O,q),d.obj.type==="directional"&&(d.tx||d.ty||d.tz)&&(d.node.translation=[d.px-d.tx,d.py-d.ty,d.pz-d.tz])}}for(let d=0;d<o.length;d++){let F=o[d];F.children&&F.children.length===0?delete F.children:F.children&&F.children.length>0&&(F.extras?.xr?.lod||F.extensions?.ANDROID_xr_scenecore?.lod||m[d]?.isLOD)&&(F.extensions={...F.extensions||{},MSFT_lod:{ids:[...F.children]}},l.add("MSFT_lod"))}let A=e?.animateCallback||e?.animateFn||(typeof t.userData?.animate=="function"?t.userData.animate:typeof t.__animateFn=="function"?t.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),T=[];if(typeof A=="function"&&m.length>0){let d=e?.duration??4,F=e?.fps??15,_=Math.max(2,Math.round(d*F)+1),O=new Float32Array(_),q=m.map(G=>[te(G.position?.x,0),te(G.position?.y,0),te(G.position?.z,0),te(G.quaternion?.x,0),te(G.quaternion?.y,0),te(G.quaternion?.z,0),te(G.quaternion?.w,1),te(G.scale?.x,1),te(G.scale?.y,1),te(G.scale?.z,1)]),z=m.map(()=>new Float32Array(_*3)),W=m.map(()=>new Float32Array(_*4)),X=m.map(()=>new Float32Array(_*3));for(let G=0;G<_;G++){let Y=G/(_-1)*d;O[G]=Y;try{A(Y)}catch{}for(let V=0;V<m.length;V++){let J=m[V];z[V][G*3]=te(J.position?.x,0),z[V][G*3+1]=te(J.position?.y,0),z[V][G*3+2]=te(J.position?.z,0);let Z=te(J.quaternion?.x,0),K=te(J.quaternion?.y,0),B=te(J.quaternion?.z,0),j=te(J.quaternion?.w,1),H=Math.hypot(Z,K,B,j)||1;if(Z/=H,K/=H,B/=H,j/=H,G>0){let Q=(G-1)*4,ee=W[V];ee[Q]*Z+ee[Q+1]*K+ee[Q+2]*B+ee[Q+3]*j<0&&(Z=-Z,K=-K,B=-B,j=-j)}W[V][G*4]=Z,W[V][G*4+1]=K,W[V][G*4+2]=B,W[V][G*4+3]=j,X[V][G*3]=te(J.scale?.x,1),X[V][G*3+1]=te(J.scale?.y,1),X[V][G*3+2]=te(J.scale?.z,1)}}for(let G=0;G<m.length;G++){let Y=m[G],V=q[G];Y.position?.set(V[0],V[1],V[2]),Y.quaternion?.set(V[3],V[4],V[5],V[6]),Y.scale?.set(V[7],V[8],V[9])}t.updateMatrixWorld(!0);let oe=null,se=()=>(oe===null&&(oe=S(O,"SCALAR",0,5126,_,[0],[d])),oe),ae=[],le=[];for(let G=0;G<m.length;G++){let Y=q[G],V=(Z,K,B)=>Z.some((j,H)=>Math.abs(j-Y[B+H%K])>1e-4),J=(Z,K,B,j)=>{Z&&le.push({sampler:ae.push({input:se(),interpolation:"LINEAR",output:S(K,B,0,5126,_)})-1,target:{node:G,path:j}})};J(V(z[G],3,0),z[G],"VEC3","translation"),J(V(W[G],4,3),W[G],"VEC4","rotation"),J(V(X[G],3,7),X[G],"VEC3","scale")}le.length>0&&T.push({name:"ProceduralLoop",samplers:ae,channels:le})}let D=Tr(o,a,t.userData),E=[],k=[],I=[];for(let d=0;d<o.length;d++){let F=o[d],_=Hr(F.extras?.xr);if(!_)continue;let{ae:O,src:q,preset:z,volume:W,loop:X,isGlobal:oe}=_,se=F.name||`Node_${d}`,ae=k.length;k.push({name:`${se}_source`,gain:W,loop:X,autoPlay:typeof O.autoplay=="boolean"?O.autoplay:!0,...q!==void 0?{audio:E.push({uri:q})-1}:{},...z?{extras:{preset:z,pitch:ke(O.pitch,.25,4,1)}}:{}});let le=I.length,G=ke(O.refDistance,.05,100,1),Y=ke(O.coneInnerAngle,0,360,360),V=ke(O.coneOuterAngle,Y,360,360);I.push({name:`${se}_emitter`,type:oe?"global":"positional",gain:W,sources:[ae],...oe?{}:{positional:{distanceModel:O.distanceModel==="linear"||O.distanceModel==="exponential"?O.distanceModel:"inverse",refDistance:G,maxDistance:ke(O.maxDistance,G,500,Math.max(G,25)),rolloffFactor:ke(O.rolloffFactor,0,10,1),coneInnerAngle:+(Y*Math.PI/180).toFixed(6),coneOuterAngle:+(V*Math.PI/180).toFixed(6),coneOuterGain:ke(O.coneOuterGain,0,1,0)}}}),F.extensions={...F.extensions||{},KHR_audio_emitter:{emitter:le}},l.add("KHR_audio_emitter")}let $={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:t.environmentIntensity,...u.length>0?{lights:u}:{}}},scenes:[{nodes:P}],scene:0,nodes:o,meshes:a,materials:p,...h.length>0?{images:h}:{},...b.length>0?{samplers:b}:{},...x.length>0?{textures:x}:{},accessors:s,bufferViews:n,buffers:[{byteLength:r}],...T.length>0?{animations:T}:{},...D||l.size>0?{extensionsUsed:[...D?["KHR_interactivity"]:[],...l]}:{},...D||c.length>0||I.length>0||y.length>0?{extensions:{...D?{KHR_interactivity:D}:{},...c.length>0?{KHR_materials_variants:{variants:c.map(d=>({name:d}))}}:{},...I.length>0?{KHR_audio_emitter:{...E.length>0?{audio:E}:{},sources:k,emitters:I}}:{},...y.length>0?{KHR_lights_punctual:{lights:y}}:{}}}:{}},N=new Uint8Array(r),U=0;for(let d of i)N.set(d,U),U+=d.byteLength;return[{gltf:$,bin:N.buffer,lights:u,environmentIntensity:t.environmentIntensity},m]}function An(t){return new TextEncoder().encode(t)}function Dt(t,e){let{gltf:i,bin:r}=dt(t,e),n=JSON.stringify(i),s=An(n),a=(4-s.byteLength%4)%4,o=s.byteLength+a,l=20+o+8+r.byteLength,m=new Uint8Array(l),p=new DataView(m.buffer);p.setUint32(0,1179937895,!0),p.setUint32(4,2,!0),p.setUint32(8,l,!0),p.setUint32(12,o,!0),p.setUint32(16,1313821514,!0),m.set(s,20);for(let h=0;h<a;h++)m[20+s.byteLength+h]=32;let v=20+o;return p.setUint32(v,r.byteLength,!0),p.setUint32(v+4,5130562,!0),m.set(new Uint8Array(r),v+8),m}function Xi(t,e){let[i,r]=Wr(t,e);return Xr(i,r)}function Xr(t,e){let i=[],r=t.gltf,n=ue().decoders.get("meshopt");n&&typeof n.decodeBufferViews=="function"&&n.decodeBufferViews(r,t);let s=t.bin,a=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),o=r.accessors||[],l=r.bufferViews||[],m=r.materials||[],p=r.meshes||[],v=r.nodes||[],h=r.textures||[],b=r.images||[],x=r.samplers||[],g=new Set,c=m.map((P,C)=>Mn(g,ht(P?.name,`Material_${C}`))),u=new Map;function y(P){let C=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(P);if(!C)return null;let R=C[2].replace(/\s+/g,""),A=R.endsWith("==")?2:R.endsWith("=")?1:0,T=new Uint8Array((R.length*3>>2)-A),D=k=>{let I=R.charCodeAt(k);return I>96?I-71:I>64?I-65:I>47?I+4:I===43?62:I===47?63:0},E=0;for(let k=0;k<R.length;k+=4){let I=D(k)<<18|D(k+1)<<12|D(k+2)<<6|D(k+3);T[E++]=I>>16&255,E<T.length&&(T[E++]=I>>8&255),E<T.length&&(T[E++]=I&255)}return T}function f(P,C,R){let A=P?.index;if(typeof A!="number")return;let T=h[A],D=T?.source;if(typeof D!="number"||!b[D])return;let E=u.get(D);if(E===void 0){E=null;let $=b[D],N=null;if(typeof $.bufferView=="number"){let U=l[$.bufferView],d=U?.byteOffset||0,F=U?.byteLength||0;U&&F>0&&d>=0&&d+F<=a.byteLength&&(N=new Uint8Array(a,d,F))}else typeof $.uri=="string"&&(N=y($.uri));if(N&&N.byteLength>0){let U=N[0]===255&&N[1]===216&&N[2]===255||!(N[0]===137&&N[1]===80)&&/jpe?g/i.test($.mimeType||$.uri||"");E={file:`texture_${D}.${U?"jpg":"png"}`,data:N}}u.set(D,E)}if(!E)return;let k=typeof T.sampler=="number"?x[T.sampler]:void 0,I=$=>$===33071?"clamp":$===33648?"mirror":"repeat";return{file:E.file,data:E.data,wrapS:I(k?.wrapS),wrapT:I(k?.wrapT),...C?{scale:C}:{},...R?{bias:R}:{}}}function w(P){let C=o[P];if(!C)throw new Error(`Accessor ${P} not found`);let R=l[C.bufferView||0],A=(R.byteOffset||0)+(C.byteOffset||0),T=R.byteLength||0;return{acc:C,buffer:a.slice(A,A+T)}}function M(P,C,R,A){let T=[],D=p[P];if(!D)return T;let E=D.primitives||[];for(let k=0;k<E.length;k++){let I=E[k],$=I.attributes?.POSITION;if($===void 0)continue;let{acc:N,buffer:U}=w($),d=new Float32Array(U,0,N.count*3),F,_=I.attributes?.NORMAL;if(_!==void 0){let{acc:K,buffer:B}=w(_),j=new Float32Array(B,0,K.count*3);F=new Float32Array(j.length);for(let H=0;H<K.count;H++){let Q=j[H*3],ee=j[H*3+1],re=j[H*3+2],he=Math.hypot(Q,ee,re)||1;F[H*3]=Q/he,F[H*3+1]=ee/he,F[H*3+2]=re/he}}let O,q=I.attributes?.TEXCOORD_0;if(q!==void 0){let{acc:K,buffer:B}=w(q);O=new Float32Array(B,0,K.count*2)}let z;if(I.indices!==void 0){let{acc:K,buffer:B}=w(I.indices);z=K.componentType===5125?new Uint32Array(B,0,K.count):new Uint16Array(B,0,K.count);let j=N.count;for(let H of z)if(H>=j)throw new Error(`SecurityError: Index buffer value (${H}) out of vertex bounds [0, ${j}).`)}else{let K=N.count;z=K>65535?new Uint32Array(K):new Uint16Array(K);for(let B=0;B<K;B++)z[B]=B}let W="DefaultMaterial",X=[1,1,1],oe=.5,se=0,ae=0,le=0,G=1.5,Y=1,V=[0,0,0],J,Z={};if(I.material!==void 0&&m[I.material]){let K=m[I.material];W=c[I.material]||`Material_${I.material}`;let B=K.pbrMetallicRoughness||{},j=(fe,Ce)=>Array.isArray(fe)&&fe.length>=3?[fe[0],fe[1],fe[2]]:Ce;X=j(B.baseColorFactor,[1,1,1]);let H=Array.isArray(B.baseColorFactor)&&typeof B.baseColorFactor[3]=="number"?B.baseColorFactor[3]:1,Q=X[0]!==1||X[1]!==1||X[2]!==1||H!==1,ee=f(B.baseColorTexture,Q?[X[0],X[1],X[2],H]:void 0),re=K.extras?.avgColor;!ee&&Array.isArray(re)&&re.length>=3&&(X=[X[0]*re[0],X[1]*re[1],X[2]*re[2]]),typeof B.roughnessFactor=="number"&&(oe=B.roughnessFactor),typeof B.metallicFactor=="number"&&(se=B.metallicFactor);let he=typeof B.roughnessFactor=="number"?B.roughnessFactor:1,ne=typeof B.metallicFactor=="number"?B.metallicFactor:1,be=f(B.metallicRoughnessTexture,he!==1||ne!==1?[1,he,ne,1]:void 0);V=j(K.emissiveFactor,[0,0,0]);let ce=(V[0]>0||V[1]>0||V[2]>0)&&(V[0]!==1||V[1]!==1||V[2]!==1)?[V[0],V[1],V[2],1]:void 0,pe=f(K.emissiveTexture,ce),me=typeof K.normalTexture?.scale=="number"?K.normalTexture.scale:1,de=f(K.normalTexture,[2*me,2*me,2,1],[-me,-me,-1,0]),Se=typeof K.occlusionTexture?.strength=="number"?K.occlusionTexture.strength:1,Te=Se!==1?f(K.occlusionTexture,[Se,Se,Se,1],[1-Se,1-Se,1-Se,0]):f(K.occlusionTexture);(ee||be||de||pe||Te)&&(J=[ee,be,de,pe,Te]),Z=K.extensions||{},Z.KHR_materials_clearcoat&&(ae=Z.KHR_materials_clearcoat.clearcoatFactor??0,le=Z.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof Z.KHR_materials_ior?.ior=="number"&&(G=Z.KHR_materials_ior.ior),Y=H*(1-(Z.KHR_materials_transmission?.transmissionFactor??0))}T.push({name:E.length>1?`${C}_p${k}`:C,positions:d,indices:z,normals:F,uvs:O,materialName:W,color:X,roughness:oe,metallic:se,clearcoat:ae,clearcoatRoughness:le,ior:G,opacity:Y,emissiveColor:V,...J?{textures:J}:{},...Z.GOOGLE_material_tsl?{tslGraph:Z.GOOGLE_material_tsl}:{},xrTraits:R||D.extras?.xr,...A?{invisible:!0}:{}})}return T}if(v.length>0){let P=new Float32Array(0),C=new Uint16Array(0),R=(d,F)=>{if(d===void 0)return null;let{acc:_,buffer:O}=w(d);return new Float32Array(O,0,_.count*F)},A=(d,F)=>Array.isArray(d)&&d.length>=3?[te(d[0],F),te(d[1],F),te(d[2],F)]:[F,F,F],T=(d,F,_)=>d&&d.length>=(F+1)*3?[d[F*3],d[F*3+1],d[F*3+2]]:_,D=(d,F,_)=>d&&d.length>=(F+1)*4?[d[F*4],d[F*4+1],d[F*4+2],d[F*4+3]]:_,E=new Map,k=r.animations?.[0];if(k&&Array.isArray(k.channels)&&Array.isArray(k.samplers))for(let d of k.channels){let F=k.samplers[d?.sampler],_=d?.target?.node,O=d?.target?.path;if(!F||typeof _!="number"||F.input===void 0)continue;let q=E.get(_);q||(q={input:F.input},E.set(_,q)),O==="translation"?q.t=F.output:O==="rotation"?q.r=F.output:O==="scale"&&(q.s=F.output)}let I=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(I)||I.length===0){let d=new Set;for(let F of v)if(Array.isArray(F?.children))for(let _ of F.children)d.add(_);I=[];for(let F=0;F<v.length;F++)d.has(F)||I.push(F);I.length===0&&(I=[0])}let $=new Set,N=[],U=(d,F)=>{if(Array.isArray(d))for(let _=d.length-1;_>=0;_--)N.push({idx:d[_],out:F})};for(U(I,i);N.length>0;){let{idx:d,out:F}=N.pop();if(typeof d!="number"||d<0||d>=v.length||$.has(d))continue;$.add(d);let _=v[d];if(!_)continue;let O=[0,0,0],q=[0,0,0,1],z=[1,1,1];if(Array.isArray(_.matrix)&&_.matrix.length===16){let Y=Gr(_.matrix);O=Y.t,q=Y.r,z=Y.s}else O=A(_.translation,0),Array.isArray(_.rotation)&&_.rotation.length>=4&&(q=[te(_.rotation[0],0),te(_.rotation[1],0),te(_.rotation[2],0),te(_.rotation[3],1)]),z=A(_.scale,1);let W,X=E.get(d);if(X){let Y=R(X.input,1);if(Y&&Y.length>0){let V=R(X.t,3),J=R(X.r,4),Z=R(X.s,3),K=Array.from(Y),B=[],j=[],H=[];for(let Q=0;Q<Y.length;Q++)B.push(T(V,Q,O)),j.push(D(J,Q,q)),H.push(T(Z,Q,z));W={times:K,translations:B,rotations:j,scales:H}}}let oe=Array.isArray(_.children)?_.children:[],se=typeof _.mesh=="number"&&_.mesh>=0&&_.mesh<p.length,ae=e?.[d]?.userData?.xr??_.extras?.xr;if(!se&&oe.length===0&&(_.camera!==void 0||_.extensions?.KHR_lights_punctual||!_.name&&!_.extras&&!ae&&!W))continue;let le=(Y,V,J)=>({name:Y,positions:P,indices:C,isXform:!0,xrTraits:ae,timeSamples:W,translation:O,rotation:q,scale:z,children:V,...J?{invisible:!0}:{}}),G=_.visible===!1||_.extensions?.KHR_node_visibility?.visible===!1||e?.[d]?.visible===!1;if(se){let Y=_.name||p[_.mesh]?.name||`Mesh_${d}`,V=M(_.mesh,Y,ae,G),J=e?.[d],Z=!!(J?._castShdSet||J?._recvShdSet),K=typeof _.extras?.shadow?.cast=="boolean"?_.extras.shadow.cast:Z?!!J?.castShadow:void 0;if(K!==void 0)for(let j of V)j.castShadow=K;let B=_.extensions?.EXT_mesh_gpu_instancing?.attributes;if(B&&typeof B=="object"&&V.length>0){let j=R(B.TRANSLATION,3),H=R(B.ROTATION,4),Q=R(B.SCALE,3),ee=R(B._COLOR_0,3),re=Math.min(1e3,j?j.length/3:H?H.length/4:Q?Q.length/3:0);if(re>0){let he=[];for(let ne=0;ne<re;ne++){let be=T(j,ne,[0,0,0]),ce=D(H,ne,[0,0,0,1]),pe=T(Q,ne,[1,1,1]);for(let me of V){let de=me.color||[.8,.8,.8],Se=ee&&ee.length>=(ne+1)*3;he.push({...me,name:`${me.name}_${ne}`,materialName:Se?`${me.materialName}_inst_${ne}`:me.materialName,color:Se?[de[0]*ee[ne*3],de[1]*ee[ne*3+1],de[2]*ee[ne*3+2]]:me.color,translation:be,rotation:ce,scale:pe})}}U(oe,he),F.push(le(Y,he,G));continue}}if(V.length===1)V[0].translation=O,V[0].rotation=q,V[0].scale=z,V[0].timeSamples=W,oe.length>0&&(V[0].children=[],U(oe,V[0].children)),F.push(V[0]);else{let j=[...V];U(oe,j),F.push(le(Y,j,G))}}else{let Y=[];U(oe,Y),F.push(le(_.name||`Group_${d}`,Y,G))}}}else for(let P=0;P<p.length;P++){let C=p[P].name||`Mesh_${P}`;i.push(...M(P,C,p[P].extras?.xr))}let S=(Array.isArray(t.lights)&&t.lights.length>0?t.lights:void 0)??wn(r)??(Array.isArray(r?.asset?.extras?.lights)?r.asset.extras.lights:[]),L=[];for(let P=0;P<S.length;P++){let C=S[P];C?.shadow?.cast&&(C.type==="directional"||C.type==="spot"||C.type==="point")&&L.push({name:`Light_${P}`,type:C.type,color:C.color,intensity:C.intensity,position:C.position,direction:C.direction,range:C.range,innerConeAngle:C.innerConeAngle,outerConeAngle:C.outerConeAngle,shadow:C.shadow})}return L.length>0&&(i.__usdaShadowLights=L),i}function ht(t,e){if(!t||typeof t!="string")return e;let i=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(i)&&(i="_"+i),i||e}function Lt(t){return String(t??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ve(t){if(!Number.isFinite(t)||Math.abs(t)<1e-7)return"0";let e=Number(t.toFixed(5)).toString();return e.indexOf(".")===-1?`${e}.0`:e}var Ne=(t,e,i)=>`(${ve(t)}, ${ve(e)}, ${ve(i)})`,mt=(t,e,i,r)=>`(${ve(t)}, ${ve(e)}, ${ve(i)}, ${ve(r)})`;function Vr(t){let e=t.length/3,i=new Array(e);for(let r=0;r<e;r++)i[r]=Ne(t[r*3],t[r*3+1],t[r*3+2]);return i.join(", ")}function ji(t,e){let i=new Array(e);for(let r=0;r<e;r++)i[r]=`(${ve(t[r*2])}, ${ve(1-t[r*2+1])})`;return i.join(", ")}function $i(t){return Array.from(t).join(", ")}function qi(t,e){let i=(e??t.__usdaShadowLights??[]).filter(c=>c?.shadow?.cast),r=new Map,n=0,s=null,a=[...t];for(;a.length>0;){let c=a.pop();if(!c.isXform&&c.positions&&c.positions.length>0){let u=ht(c.materialName,"DefaultMaterial");r.has(u)||r.set(u,{color:c.color||[1,1,1],roughness:c.roughness??.5,metallic:c.metallic??0,clearcoat:c.clearcoat??0,clearcoatRoughness:c.clearcoatRoughness??0,ior:c.ior??1.5,opacity:c.opacity??1,emissiveColor:c.emissiveColor||[0,0,0],textures:c.textures,tslGraph:c.tslGraph})}if(c.timeSamples&&c.timeSamples.times.length>0){let u=c.timeSamples.times[c.timeSamples.times.length-1];u>n&&(n=u)}else c.tslGraph&&n<=0&&JSON.stringify(c.tslGraph).includes('"time"')&&(n=60);if(c.xrTraits?.anchor&&!s&&(s=c.xrTraits.anchor==="vertical"||c.xrTraits.anchor==="wall"?"vertical":"horizontal"),c.children)for(let u=c.children.length-1;u>=0;u--)a.push(c.children[u])}let o="";n>0&&(o=`startTimeCode = 0
|
|
217
|
+
endTimeCode = ${ve(n)}
|
|
253
218
|
timeCodesPerSecond = 1.0
|
|
254
|
-
`);let
|
|
255
|
-
uniform token preliminary:planeAnchoring:alignment = "${
|
|
256
|
-
`);let
|
|
219
|
+
`);let l="";s&&(l=`uniform token preliminary:anchoring:type = "plane"
|
|
220
|
+
uniform token preliminary:planeAnchoring:alignment = "${s}"
|
|
221
|
+
`);let m=`#usda 1.0
|
|
257
222
|
(
|
|
258
223
|
defaultPrim = "Root"
|
|
259
224
|
metersPerUnit = 1.0
|
|
260
225
|
upAxis = "Y"
|
|
261
|
-
${
|
|
226
|
+
${o})
|
|
262
227
|
|
|
263
228
|
def Xform "Root" (
|
|
264
229
|
kind = "component"
|
|
265
230
|
)
|
|
266
231
|
{
|
|
267
|
-
${
|
|
232
|
+
${l}def Scope "Materials"
|
|
268
233
|
{
|
|
269
|
-
`;for(let[
|
|
270
|
-
float inputs:roughness${
|
|
271
|
-
float inputs:roughness = ${
|
|
272
|
-
|
|
273
|
-
`),
|
|
274
|
-
`),
|
|
275
|
-
`),
|
|
276
|
-
`:(
|
|
277
|
-
`),
|
|
278
|
-
`),
|
|
279
|
-
`);let
|
|
234
|
+
`;for(let[c,u]of r.entries()){let[y,f,w]=u.color,[M,S,L]=u.emissiveColor,P=`/Root/Materials/${c}`,[C,R,A,T,D]=u.textures||[],E=(F,_)=>`.connect = <${P}/${F}.outputs:${_}>`,k=C?`color3f inputs:diffuseColor${E("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${Ne(y,f,w)}`,I=R?`float inputs:metallic${E("MetallicRoughnessTexture","b")}
|
|
235
|
+
float inputs:roughness${E("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${ve(u.metallic)}
|
|
236
|
+
float inputs:roughness = ${ve(u.roughness)}`,$="";u.clearcoat>0&&($+=`float inputs:clearcoat = ${ve(u.clearcoat)}
|
|
237
|
+
`,$+=`float inputs:clearcoatRoughness = ${ve(u.clearcoatRoughness)}
|
|
238
|
+
`),u.ior!==1.5&&($+=`float inputs:ior = ${ve(u.ior)}
|
|
239
|
+
`),u.opacity<1&&($+=`float inputs:opacity = ${ve(u.opacity)}
|
|
240
|
+
`),T?$+=`color3f inputs:emissiveColor${E("EmissiveTexture","rgb")}
|
|
241
|
+
`:(M>0||S>0||L>0)&&($+=`color3f inputs:emissiveColor = ${Ne(M,S,L)}
|
|
242
|
+
`),A&&($+=`normal3f inputs:normal${E("NormalTexture","rgb")}
|
|
243
|
+
`),D&&($+=`float inputs:occlusion${E("OcclusionTexture","r")}
|
|
244
|
+
`);let N="";if(C||R||A||T||D){N+=`def Shader "PrimvarReader"
|
|
280
245
|
{
|
|
281
246
|
uniform token info:id = "UsdPrimvarReader_float2"
|
|
282
247
|
string inputs:varname = "st"
|
|
283
248
|
float2 outputs:result
|
|
284
249
|
}
|
|
285
|
-
`;let
|
|
286
|
-
`:"",
|
|
287
|
-
`:"";
|
|
250
|
+
`;let F=(_,O,q,z)=>{if(!O)return;let W=O.scale?`float4 inputs:scale = ${mt(O.scale[0],O.scale[1],O.scale[2],O.scale[3])}
|
|
251
|
+
`:"",X=O.bias?`float4 inputs:bias = ${mt(O.bias[0],O.bias[1],O.bias[2],O.bias[3])}
|
|
252
|
+
`:"";N+=`def Shader "${_}"
|
|
288
253
|
{
|
|
289
254
|
uniform token info:id = "UsdUVTexture"
|
|
290
|
-
asset inputs:file = @${
|
|
291
|
-
float2 inputs:st${
|
|
292
|
-
token inputs:sourceColorSpace = "${
|
|
293
|
-
token inputs:wrapS = "${
|
|
294
|
-
token inputs:wrapT = "${
|
|
295
|
-
${
|
|
296
|
-
`};
|
|
297
|
-
`),
|
|
255
|
+
asset inputs:file = @${Lt(O.file)}@
|
|
256
|
+
float2 inputs:st${E("PrimvarReader","result")}
|
|
257
|
+
token inputs:sourceColorSpace = "${q}"
|
|
258
|
+
token inputs:wrapS = "${O.wrapS||"repeat"}"
|
|
259
|
+
token inputs:wrapT = "${O.wrapT||"repeat"}"
|
|
260
|
+
${W}${X}${z}}
|
|
261
|
+
`};F("DiffuseTexture",C,"sRGB",`float3 outputs:rgb
|
|
262
|
+
`),F("MetallicRoughnessTexture",R,"raw",`float outputs:g
|
|
298
263
|
float outputs:b
|
|
299
|
-
`),
|
|
300
|
-
`),
|
|
301
|
-
`),
|
|
302
|
-
`)}
|
|
264
|
+
`),F("NormalTexture",A,"raw",`float3 outputs:rgb
|
|
265
|
+
`),F("EmissiveTexture",T,"sRGB",`float3 outputs:rgb
|
|
266
|
+
`),F("OcclusionTexture",D,"raw",`float outputs:r
|
|
267
|
+
`)}let U=`${k}
|
|
268
|
+
${I}
|
|
269
|
+
${$}`,d=u.tslGraph&&ue().tslUsdzSerializer?.(u.tslGraph,c,U);d&&(U=d.surfaceInputsUsda||U,N+=d.nodeGraphUsda),m+=`def Material "${c}"
|
|
303
270
|
{
|
|
304
271
|
def Shader "PBRShader"
|
|
305
272
|
{
|
|
306
273
|
uniform token info:id = "UsdPreviewSurface"
|
|
307
|
-
${
|
|
308
|
-
${M}
|
|
309
|
-
${O}token outputs:surface
|
|
274
|
+
${U}token outputs:surface
|
|
310
275
|
}
|
|
311
|
-
token outputs:surface${
|
|
312
|
-
${
|
|
313
|
-
`}
|
|
276
|
+
token outputs:surface${E("PBRShader","surface")}
|
|
277
|
+
${N}}
|
|
278
|
+
`}m+=`}
|
|
314
279
|
def Scope "Meshes"
|
|
315
280
|
{
|
|
316
|
-
`;let
|
|
281
|
+
`;let p=(c,u,y)=>{let f=[];u&&f.push('"MaterialBindingAPI"');let w=!!(c?.rigidBody&&c.rigidBody!=="none"&&(typeof c.rigidBody!="object"||c.rigidBody.enabled!==!1)),M=!!(c?.physics&&c.physics!=="none"||w);M&&f.push(...w?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let S=[];f.length>0&&S.push(`prepend apiSchemas = [${f.join(", ")}]`);let L=ue().xrTraitSerializer;if(c){let T=L?.usdLines(c,Lt)??[];if(!T.length)for(let D of["grab","billboard","follow","anchor","physics"]){let E=D==="follow"&&typeof c.follow=="object"?c.follow.mode??"head":c[D];E!==void 0&&T.push(`string ${D} = "${Lt(E)}"`)}T.length>0&&S.push(`customData = {
|
|
317
282
|
dictionary xr = {
|
|
318
|
-
${
|
|
283
|
+
${T.join(`
|
|
319
284
|
`)}
|
|
320
285
|
}
|
|
321
|
-
}`)}let
|
|
322
|
-
${
|
|
286
|
+
}`)}let P=S.length>0?` (
|
|
287
|
+
${S.join(`
|
|
323
288
|
`)}
|
|
324
|
-
)`:"",
|
|
325
|
-
`:"";if(
|
|
326
|
-
bool physics:kinematicEnabled = ${
|
|
289
|
+
)`:"",C=y?`uniform token visibility = "invisible"
|
|
290
|
+
`:"";if(M){let T=c?.rigidBody??c?.physics,D=T?.body??T?.mode??T;C+=`bool physics:rigidBodyEnabled = true
|
|
291
|
+
bool physics:kinematicEnabled = ${D==="static"||D==="kinematic"}
|
|
327
292
|
bool physics:collisionEnabled = true
|
|
328
|
-
`,
|
|
329
|
-
`)}let
|
|
293
|
+
`,T?.mass>0&&Number.isFinite(T.mass)&&(C+=`float physics:mass = ${ve(T.mass)}
|
|
294
|
+
`)}let R=Hr(c),A=(R?`def SpatialAudio "AudioEmitter"
|
|
330
295
|
{
|
|
331
|
-
${
|
|
332
|
-
`:""}uniform token inputs:auralMode = "${
|
|
333
|
-
uniform token inputs:playbackMode = "${
|
|
334
|
-
double gain = ${
|
|
296
|
+
${R.src?`asset inputs:file = @${Lt(R.src)}@
|
|
297
|
+
`:""}uniform token inputs:auralMode = "${R.isGlobal?"nonSpatial":"spatial"}"
|
|
298
|
+
uniform token inputs:playbackMode = "${R.loop?"loopFromStart":"onceFromStart"}"
|
|
299
|
+
double gain = ${ve(R.volume)}
|
|
335
300
|
}
|
|
336
|
-
`:"";return{header:
|
|
337
|
-
quatf xformOp:orient.timeSamples = { ${
|
|
338
|
-
double3 xformOp:scale.timeSamples = { ${
|
|
301
|
+
`:"")+(c?L?.usdPrims?.(c)??"":"");return{header:P,body:C,tail:A}},v=c=>{if(c.timeSamples&&c.timeSamples.times.length>0){let S=c.timeSamples,L=(A,T,D)=>S.times.map((E,k)=>`${ve(E)}: ${D(A?.[k]||T)}`).join(", "),P=L(S.translations,[0,0,0],A=>Ne(A[0],A[1],A[2])),C=L(S.rotations,[0,0,0,1],A=>{let T=Math.hypot(A[0],A[1],A[2],A[3])||1;return mt(A[3]/T,A[0]/T,A[1]/T,A[2]/T)}),R=L(S.scales,[1,1,1],A=>Ne(A[0],A[1],A[2]));return`double3 xformOp:translate.timeSamples = { ${P} }
|
|
302
|
+
quatf xformOp:orient.timeSamples = { ${C} }
|
|
303
|
+
double3 xformOp:scale.timeSamples = { ${R} }
|
|
339
304
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
|
|
340
|
-
`}let
|
|
341
|
-
`,
|
|
342
|
-
`,
|
|
343
|
-
`,
|
|
344
|
-
`),
|
|
345
|
-
int[] faceVertexCounts = [${
|
|
346
|
-
int[] faceVertexIndices = [${
|
|
347
|
-
point3f[] points = [${
|
|
348
|
-
`;return
|
|
305
|
+
`}let u=[],y="",f=c.translation;f&&(Math.abs(f[0])>1e-7||Math.abs(f[1])>1e-7||Math.abs(f[2])>1e-7)&&(y+=`double3 xformOp:translate = ${Ne(f[0],f[1],f[2])}
|
|
306
|
+
`,u.push('"xformOp:translate"'));let w=c.rotation;if(w){let S=Math.hypot(w[0],w[1],w[2],w[3])||1,L=w[0]/S,P=w[1]/S,C=w[2]/S,R=w[3]/S;(1-Math.abs(R)>1e-7||Math.hypot(L,P,C)>1e-7)&&(y+=`quatf xformOp:orient = ${mt(R,L,P,C)}
|
|
307
|
+
`,u.push('"xformOp:orient"'))}let M=c.scale;return M&&(Math.abs(M[0]-1)>1e-7||Math.abs(M[1]-1)>1e-7||Math.abs(M[2]-1)>1e-7)&&(y+=`float3 xformOp:scale = ${Ne(M[0],M[1],M[2])}
|
|
308
|
+
`,u.push('"xformOp:scale"')),u.length>0&&(y+=`uniform token[] xformOpOrder = [${u.join(", ")}]
|
|
309
|
+
`),y},h=c=>{let u=c.positions.length/3,y=1/0,f=1/0,w=1/0,M=-1/0,S=-1/0,L=-1/0;for(let T=0;T<u;T++){let D=c.positions[T*3],E=c.positions[T*3+1],k=c.positions[T*3+2];D<y&&(y=D),D>M&&(M=D),E<f&&(f=E),E>S&&(S=E),k<w&&(w=k),k>L&&(L=k)}isFinite(y)||(y=f=w=-1,M=S=L=1);let P=Math.floor(c.indices.length/3),C=ht(c.materialName,"DefaultMaterial"),R=P>0?P===1?"3":"3, ".repeat(P-1)+"3":"",A=`float3[] extent = [${Ne(y,f,w)}, ${Ne(M,S,L)}]
|
|
310
|
+
int[] faceVertexCounts = [${R}]
|
|
311
|
+
int[] faceVertexIndices = [${$i(c.indices)}]
|
|
312
|
+
point3f[] points = [${Vr(c.positions)}]
|
|
313
|
+
`;return c.normals&&c.normals.length===c.positions.length&&(A+=`normal3f[] normals = [${Vr(c.normals)}] (
|
|
349
314
|
interpolation = "vertex"
|
|
350
315
|
)
|
|
351
|
-
`),
|
|
316
|
+
`),c.uvs&&c.uvs.length===u*2&&(A+=`texCoord2f[] primvars:st = [${ji(c.uvs,u)}] (
|
|
352
317
|
interpolation = "vertex"
|
|
353
318
|
)
|
|
354
|
-
`),
|
|
355
|
-
`,
|
|
356
|
-
|
|
319
|
+
`),A+=`rel material:binding = </Root/Materials/${C}>
|
|
320
|
+
`,c.castShadow===!1&&i.length>0&&(A+=`bool primvars:doNotCastShadows = 1
|
|
321
|
+
`),A},b=new Set,x=[];for(let c=t.length-1;c>=0;c--)x.push({node:t[c],siblings:b});let g=0;for(;x.length>0;){let c=x.pop();if(c.close){m+=`}
|
|
322
|
+
`;continue}let{node:u,siblings:y}=c,f=!!(u.isXform||u.positions.length===0),w=Mn(y,ht(u.name,f?`Group_${g}`:`Mesh_${g}`));g++;let M=u.children||[];if(f){let S=p(u.xrTraits,!1,u.invisible);m+=`def Xform "${w}"${S.header}
|
|
357
323
|
{
|
|
358
|
-
${
|
|
324
|
+
${S.body}${v(u)}${S.tail}`,x.push({close:!0});let L=new Set;for(let P=M.length-1;P>=0;P--)x.push({node:M[P],siblings:L})}else if(M.length>0){let S=p(u.xrTraits,!1,u.invisible),L=`${w}_mesh`;m+=`def Xform "${w}"${S.header}
|
|
359
325
|
{
|
|
360
|
-
${
|
|
326
|
+
${S.body}${v(u)}${S.tail}`,m+=`def Mesh "${L}" (
|
|
361
327
|
prepend apiSchemas = ["MaterialBindingAPI"]
|
|
362
328
|
)
|
|
363
329
|
{
|
|
364
|
-
${
|
|
365
|
-
`,
|
|
330
|
+
${h(u)}}
|
|
331
|
+
`,x.push({close:!0});let P=new Set([L]);for(let C=M.length-1;C>=0;C--)x.push({node:M[C],siblings:P})}else{let S=p(u.xrTraits,!0,u.invisible);m+=`def Mesh "${w}"${S.header}
|
|
366
332
|
{
|
|
367
|
-
${
|
|
368
|
-
`}}
|
|
369
|
-
|
|
370
|
-
`,n}var vt=null;function st(t){if(!vt){vt=new Uint32Array(256);for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;vt[i]=r}}let e=4294967295;for(let i=0;i<t.length;i++)e=vt[(e^t[i])&255]^e>>>8;return(e^4294967295)>>>0}function Cr(t){let e=[],i=0,r=[];for(let c of t){let f=on(c.filename),g=st(c.data),w=c.data.length,d=30+f.length,p=(i+d)%64,A=p!==0?64-p:0;A>0&&A<4&&(A+=64);let b=new Uint8Array(d+A),x=new DataView(b.buffer);x.setUint32(0,67324752,!0),x.setUint16(4,20,!0),x.setUint32(14,g,!0),x.setUint32(18,w,!0),x.setUint32(22,w,!0),x.setUint16(26,f.length,!0),x.setUint16(28,A,!0),b.set(f,30),A>=4&&(x.setUint16(d,6534,!0),x.setUint16(d+2,A-4,!0)),e.push({offset:i,size:w,crc:g,filenameBytes:f,entry:c}),r.push(b,c.data),i+=b.length+c.data.length}let s=i;for(let c of e){let f=new Uint8Array(46+c.filenameBytes.length),g=new DataView(f.buffer);g.setUint32(0,33639248,!0),g.setUint16(4,20,!0),g.setUint16(6,20,!0),g.setUint32(16,c.crc,!0),g.setUint32(20,c.size,!0),g.setUint32(24,c.size,!0),g.setUint16(28,c.filenameBytes.length,!0),g.setUint32(42,c.offset,!0),f.set(c.filenameBytes,46),r.push(f),i+=f.length}let a=i-s,o=new Uint8Array(22),n=new DataView(o.buffer);n.setUint32(0,101010256,!0),n.setUint16(8,e.length,!0),n.setUint16(10,e.length,!0),n.setUint32(12,a,!0),n.setUint32(16,s,!0),r.push(o),i+=22;let l=new Uint8Array(i),h=0;for(let c of r)l.set(c,h),h+=c.length;return l}function Lr(t){let e=[{filename:"model.usda",data:on(Ci(t))}],i=new Set(["model.usda"]),r=[...t];for(;r.length>0;){let s=r.pop();for(let a of s.textures||[])a?.file&&a.data?.byteLength&&!i.has(a.file)&&(i.add(a.file),e.push({filename:a.file,data:a.data}));if(s.children)for(let a=s.children.length-1;a>=0;a--)r.push(s.children[a])}return Cr(e)}function St(t){return Lr(Ti(t))}function At(t){return Lr(_r(Ue(t)))}function Rt(t){return t&&typeof t.toUSDZ=="function"?t.toUSDZ():At(t)}function Ze(t){let e=Rt(t);return new Blob([e],{type:"model/vnd.usdz+zip"})}var Ee=class Qt{constructor(e=0,i=0){this.x=Number(e),this.y=Number(i)}set(e,i){return this.x=Number(e),this.y=Number(i),this}clone(){return new Qt(this.x,this.y)}copy(e){return this.set(e.x,e.y)}add(e){return this.x+=e.x,this.y+=e.y,this}sub(e){return this.x-=e.x,this.y-=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divideScalar(e){return this.multiplyScalar(e?1/e:0)}setScalar(e){return this.set(e,e)}},ie=class Qi{constructor(e=0,i=0,r=0){this.x=Number(e),this.y=Number(i),this.z=Number(r)}set(e,i,r){return this.x=Number(e),this.y=Number(i),this.z=Number(r),this}clone(){return new Qi(this.x,this.y,this.z)}copy(e){return this.set(e.x,e.y,e.z)}add(e){return this.addVectors(this,e)}addVectors(e,i){return this.set(e.x+i.x,e.y+i.y,e.z+i.z)}sub(e){return this.subVectors(this,e)}subVectors(e,i){return this.set(e.x-i.x,e.y-i.y,e.z-i.z)}multiplyScalar(e){return this.set(this.x*e,this.y*e,this.z*e)}divideScalar(e){return this.multiplyScalar(e?1/e:0)}setScalar(e){return this.set(e,e,e)}addScaledVector(e,i){return this.set(this.x+e.x*i,this.y+e.y*i,this.z+e.z*i)}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let e=this.length();return e>1e-5?this.multiplyScalar(1/e):this}cross(e){return this.crossVectors(this,e)}crossVectors(e,i){let r=e.x,s=e.y,a=e.z,o=i.x,n=i.y,l=i.z;return this.set(s*l-a*n,a*o-r*l,r*n-s*o)}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y,this.z-e.z)}lerp(e,i){return this.lerpVectors(this,e,i)}lerpVectors(e,i,r){return this.x=e.x+(i.x-e.x)*r,this.y=e.y+(i.y-e.y)*r,this.z=e.z+(i.z-e.z)*r,this}applyMatrix4(e){let i=this.x,r=this.y,s=this.z,a=e.elements,o=1/(a[3]*i+a[7]*r+a[11]*s+a[15]);return this.x=(a[0]*i+a[4]*r+a[8]*s+a[12])*o,this.y=(a[1]*i+a[5]*r+a[9]*s+a[13])*o,this.z=(a[2]*i+a[6]*r+a[10]*s+a[14])*o,this}},un=class{constructor(t=0,e=0,i=0,r=1){this.x=Number(t),this.y=Number(e),this.z=Number(i),this.w=Number(r)}set(t,e,i,r){return this.x=Number(t),this.y=Number(e),this.z=Number(i),this.w=Number(r),this}},Dt=class Ji{constructor(e=0,i=0,r=0,s="XYZ"){this._onChangeCallback=null,this._x=Number(e),this._y=Number(i),this._z=Number(r),this.order=s}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}set(e,i,r,s=this.order){return this._x=Number(e),this._y=Number(i),this._z=Number(r),this.order=s,this._onChangeCallback?.(),this}copy(e){return this.set(e.x,e.y,e.z,e.order)}clone(){return new Ji(this._x,this._y,this._z,this.order)}_onChange(e){return this._onChangeCallback=e,this}},at=class as{constructor(e=0,i=0,r=0,s=1){this._onChangeCallback=null,this._x=Number(e),this._y=Number(i),this._z=Number(r),this._w=Number(s)}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}get w(){return this._w}set w(e){this._w=Number(e),this._onChangeCallback?.()}set(e,i,r,s){return this._x=Number(e),this._y=Number(i),this._z=Number(r),this._w=Number(s),this._onChangeCallback?.(),this}copy(e){return this.set(e.x,e.y,e.z,e.w)}clone(){return new as(this._x,this._y,this._z,this._w)}identity(){return this.set(0,0,0,1)}setFromEuler(e,i=!0){let r=e.x,s=e.y,a=e.z,o=Math.cos(r/2),n=Math.cos(s/2),l=Math.cos(a/2),h=Math.sin(r/2),c=Math.sin(s/2),f=Math.sin(a/2);return this._x=h*n*l+o*c*f,this._y=o*c*l-h*n*f,this._z=o*n*f+h*c*l,this._w=o*n*l-h*c*f,i&&this._onChangeCallback?.(),this}setFromAxisAngle(e,i){let r=i/2,s=Math.sin(r);return this.set(e.x*s,e.y*s,e.z*s,Math.cos(r))}normalize(){let e=Math.hypot(this._x,this._y,this._z,this._w);return e===0?this.set(0,0,0,1):this.set(this._x/e,this._y/e,this._z/e,this._w/e)}setFromUnitVectors(e,i){let r=e.dot(i)+1;return r<1e-6?(Math.abs(e.x)>Math.abs(e.z)?this.set(-e.y,e.x,0,0):this.set(0,-e.z,e.y,0)).normalize():this.set(e.y*i.z-e.z*i.y,e.z*i.x-e.x*i.z,e.x*i.y-e.y*i.x,r).normalize()}multiply(e){return this.multiplyQuaternions(this,e)}multiplyQuaternions(e,i){let r=e.x,s=e.y,a=e.z,o=e.w,n=i.x,l=i.y,h=i.z,c=i.w;return this._x=r*c+o*n+s*h-a*l,this._y=s*c+o*l+a*n-r*h,this._z=a*c+o*h+r*l-s*n,this._w=o*c-r*n-s*l-a*h,this._onChangeCallback?.(),this}_onChange(e){return this._onChangeCallback=e,this}},He=class os{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,this}copy(e){return this.elements.set(e.elements),this}clone(){let e=new os;return e.copy(this),e}compose(e,i,r){return nt(this.elements,[i.x,i.y,i.z,i.w],[e.x,e.y,e.z],[r.x,r.y,r.z]),this}multiply(e){return this.multiplyMatrices(this,e)}multiplyMatrices(e,i){return pe(this.elements,e.elements,i.elements),this}lookAt(e,i,r){return qe(this.elements,[e.x,e.y,e.z],[i.x,i.y,i.z],[r.x,r.y,r.z]),this}makeRotationFromQuaternion(e){let i=new ie(0,0,0),r=new ie(1,1,1);return this.compose(i,e,r)}makeTranslation(e,i,r){return this.identity(),this.elements[12]=Number(e),this.elements[13]=Number(i),this.elements[14]=Number(r),this}makeScale(e,i,r){return this.identity(),this.elements[0]=Number(e),this.elements[5]=Number(i),this.elements[10]=Number(r),this}},ln=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let t=this.elements;return t.fill(0),t[0]=1,t[4]=1,t[8]=1,this}getNormalMatrix(t){return Ce(this.elements,t.elements),this}},Ae=t=>t<=.04045?t/12.92:((t+.055)/1.055)**2.4,Tt=t=>t<=.0031308?t*12.92:1.055*t**(1/2.4)-.055,Dr={black:0,white:16777215,red:16711680,green:32768,lime:65280,blue:255,yellow:16776960,cyan:65535,aqua:65535,magenta:16711935,fuchsia:16711935,gray:8421504,grey:8421504,silver:12632256,orange:16753920,purple:8388736,pink:16761035,gold:16766720},Le=class ls{constructor(e,i,r){this.r=1,this.g=1,this.b=1,e!==void 0&&(i!==void 0&&r!==void 0?this.setRGB(e,i,r):this.set(e))}set(e){return typeof e=="number"?this.setHex(e):typeof e=="string"?this.setStyle(e):(e&&typeof e=="object"&&"r"in e&&(this.r=Number(e.r),this.g=Number(e.g),this.b=Number(e.b)),this)}setStyle(e){let i=e.trim().toLowerCase();if(i[0]==="#"){let r=i.slice(1);r.length===3||r.length===4?r=r[0]+r[0]+r[1]+r[1]+r[2]+r[2]:r.length===8&&(r=r.slice(0,6));let s=parseInt(r,16);r.length===6&&!Number.isNaN(s)&&this.setHex(s)}else if(i in Dr)this.setHex(Dr[i]);else if(i.startsWith("hsl")){let r=/^hsla?\(([^)]+)\)$/.exec(i)?.[1].trim().split(/[\s,/]+/);r&&r.length>=3&&this.setHSL((parseFloat(r[0])||0)/360,(parseFloat(r[1])||0)/100,(parseFloat(r[2])||0)/100)}else{let r=/^rgba?\(([^)]+)\)$/.exec(i)?.[1].trim().split(/[\s,/]+/);if(r&&r.length>=3){let s=a=>Ae(Math.max(0,Math.min(1,(parseFloat(a)||0)/(a.endsWith("%")?100:255))));this.setRGB(s(r[0]),s(r[1]),s(r[2]))}}return this}setHSL(e,i,r){if(e=((Number(e)||0)%1+1)%1,i=Math.max(0,Math.min(1,Number(i)||0)),r=Math.max(0,Math.min(1,Number(r)||0)),i===0){let n=Ae(r);return this.setRGB(n,n,n)}let s=r<=.5?r*(1+i):r+i-r*i,a=2*r-s,o=n=>(n<0&&(n+=1),n>1&&(n-=1),n<1/6?a+(s-a)*6*n:n<1/2?s:n<2/3?a+(s-a)*6*(2/3-n):a);return this.setRGB(Ae(o(e+1/3)),Ae(o(e)),Ae(o(e-1/3)))}lerp(e,i){return this.lerpColors(this,e,i)}lerpColors(e,i,r){let s=Number(r)||0;return this.setRGB(e.r+(i.r-e.r)*s,e.g+(i.g-e.g)*s,e.b+(i.b-e.b)*s)}multiplyScalar(e){let i=Number(e)||0;return this.setRGB(this.r*i,this.g*i,this.b*i)}setScalar(e){let i=Number(e)||0;return this.setRGB(i,i,i)}setHex(e){let i=Math.floor(e);return this.setRGB(Ae((i>>16&255)/255),Ae((i>>8&255)/255),Ae((i&255)/255))}setRGB(e,i,r){return this.r=Number(e),this.g=Number(i),this.b=Number(r),this}convertSRGBToLinear(){return this.setRGB(Ae(this.r),Ae(this.g),Ae(this.b))}convertLinearToSRGB(){return this.setRGB(Tt(this.r),Tt(this.g),Tt(this.b))}getHex(){let e=i=>Math.round(Tt(Math.max(0,Math.min(1,i)))*255);return e(this.r)<<16|e(this.g)<<8|e(this.b)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(e){return this.setRGB(e.r,e.g,e.b)}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}clone(){return new ls(this.r,this.g,this.b)}},Li={degToRad:t=>t*Math.PI/180,radToDeg:t=>t*180/Math.PI,clamp:(t,e,i)=>Math.max(e,Math.min(i,t)),lerp:(t,e,i)=>t+(e-t)*i,generateUUID:()=>Math.random().toString(36).substring(2,15),randFloat:(t,e)=>t+Math.random()*(e-t)},ve=class hs{constructor(e,i){if(this.needsUpdate=!1,typeof i!="number"||!Number.isInteger(i)||i<1||i>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(i)}`);Array.isArray(e)?this.array=new Float32Array(e):this.array=e,this.itemSize=i;let r=this.array?this.array.length:0;if(!Number.isFinite(r)||r<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(r)}`);this.count=Math.floor(r/i)}getX(e){return this.array[e*this.itemSize]}getY(e){return this.array[e*this.itemSize+1]}getZ(e){return this.array[e*this.itemSize+2]}setX(e,i){return this.array[e*this.itemSize]=i,this.needsUpdate=!0,this}setY(e,i){return this.array[e*this.itemSize+1]=i,this.needsUpdate=!0,this}setZ(e,i){return this.array[e*this.itemSize+2]=i,this.needsUpdate=!0,this}setXYZ(e,i,r,s){let a=e*this.itemSize;return this.array[a]=i,this.array[a+1]=r,this.array[a+2]=s,this.needsUpdate=!0,this}setUsage(e){return this}clone(){let e=this.array?.constructor||Float32Array;return new hs(new e(this.array),this.itemSize)}},mn=class extends ve{constructor(t,e){super(t instanceof Float32Array||Array.isArray(t)?t:new Float32Array(t),e)}},hn=class extends ve{constructor(t,e){super(t instanceof Uint16Array?t:new Uint16Array(t),e)}},dn=class extends ve{constructor(t,e){super(t instanceof Uint32Array?t:new Uint32Array(t),e)}},ge=class us{constructor(){this.name="",this.attributes={},this.index=null,this.boundingBox=null}setAttribute(e,i){return this.attributes[e]=i,this}getAttribute(e){return this.attributes[e]}setIndex(e){if(e instanceof ve)this.index=e;else if(Array.isArray(e)){let i=0;for(let r of e)r>i&&(i=r);this.index=new ve(new(i>65535?Uint32Array:Uint16Array)(e),1)}else e&&e.buffer&&(this.index=new ve(e,1));return this}computeVertexNormals(){let e=this.attributes.position;if(!e)return this;let i=!1;if(typeof i=="function"){let l=i(e.array,this.index?.array);return this.setAttribute("normal",new ve(l,3)),this}let r=e.count,s=e.array,a=new Float32Array(r*3),o=this.index?.array,n=o?o.length:r;for(let l=0;l<n;l+=3){let h=(o?o[l]:l)*3,c=(o?o[l+1]:l+1)*3,f=(o?o[l+2]:l+2)*3,g=s[c],w=s[c+1],d=s[c+2],p=s[f]-g,A=s[f+1]-w,b=s[f+2]-d,x=s[h]-g,u=s[h+1]-w,m=s[h+2]-d,v=A*m-b*u,S=b*x-p*m,_=p*u-A*x;a[h]+=v,a[h+1]+=S,a[h+2]+=_,a[c]+=v,a[c+1]+=S,a[c+2]+=_,a[f]+=v,a[f+1]+=S,a[f+2]+=_}for(let l=0;l<r*3;l+=3){let h=a[l],c=a[l+1],f=a[l+2],g=Math.hypot(h,c,f)||1;a[l]=h/g,a[l+1]=c/g,a[l+2]=f/g}return this.setAttribute("normal",new ve(a,3)),this}setFromBuffers(e,i,r,s){this.setAttribute("position",new ve(e,3)),this.setAttribute("normal",new ve(i,3)),this.setAttribute("uv",new ve(r,2)),this.setIndex(s)}setFromPoints(e){let i=[];if(Array.isArray(e))for(let r of e)i.push(Number(r?.x)||0,Number(r?.y)||0,Number(r?.z)||0);return this.setAttribute("position",new ve(i,3))}computeBoundingBox(){let e=this.attributes.position,i=new ie(1/0,1/0,1/0),r=new ie(-1/0,-1/0,-1/0);if(e&&e.count>0)for(let s=0;s<e.count;s++){let a=e.getX(s),o=e.getY(s),n=e.getZ(s);a<i.x&&(i.x=a),o<i.y&&(i.y=o),n<i.z&&(i.z=n),a>r.x&&(r.x=a),o>r.y&&(r.y=o),n>r.z&&(r.z=n)}else i.set(0,0,0),r.set(0,0,0);return this.boundingBox={min:i,max:r},this.boundingBox}center(){let e=this.computeBoundingBox();return this.translate(-(e.min.x+e.max.x)*.5,-(e.min.y+e.max.y)*.5,-(e.min.z+e.max.z)*.5)}_xform(e,i){let r=this.attributes.position;if(r){let s=r.array;for(let a=0;a<s.length;a+=3)e(s,a);r.needsUpdate=!0,i&&this.computeVertexNormals(),this.computeBoundingBox()}return this}translate(e=0,i=0,r=0){return this._xform((s,a)=>{s[a]+=e,s[a+1]+=i,s[a+2]+=r})}scale(e=1,i=1,r=1){return this._xform((s,a)=>{s[a]*=e,s[a+1]*=i,s[a+2]*=r},!0)}_rot(e,i,r){let s=Math.cos(r),a=Math.sin(r);for(let o of[this.attributes.position,this.attributes.normal]){if(!o)continue;let n=o.array;for(let l=0;l<n.length;l+=3){let h=n[l+e],c=n[l+i];n[l+e]=h*s-c*a,n[l+i]=h*a+c*s}o.needsUpdate=!0}return this}rotateX(e){return this._rot(1,2,e)}rotateY(e){return this._rot(2,0,e)}rotateZ(e){return this._rot(0,1,e)}applyMatrix4(e){let i=this.attributes.position;if(i&&e?.elements){let r=new ie;for(let s=0;s<i.count;s++)r.set(i.getX(s),i.getY(s),i.getZ(s)).applyMatrix4(e),i.setXYZ(s,r.x,r.y,r.z);this.computeVertexNormals()}return this}clone(){let e=new us;e.name=this.name;for(let i of Object.keys(this.attributes))e.attributes[i]=this.attributes[i].clone();return this.index&&(e.index=this.index.clone()),e}dispose(){}},It=class extends ge{constructor(t=1,e=1,i=1){super();let r=t/2,s=e/2,a=i/2,o=[-r,-s,a,r,-s,a,r,s,a,-r,s,a,r,-s,-a,-r,-s,-a,-r,s,-a,r,s,-a,-r,s,a,r,s,a,r,s,-a,-r,s,-a,-r,-s,-a,r,-s,-a,r,-s,a,-r,-s,a,r,-s,a,r,-s,-a,r,s,-a,r,s,a,-r,-s,-a,-r,-s,a,-r,s,a,-r,s,-a],n=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0],l=[],h=[];for(let c=0;c<6;c++){let f=c*4;l.push(0,0,1,0,1,1,0,1),h.push(f,f+1,f+2,f,f+2,f+3)}this.setFromBuffers(o,n,l,h)}},fn=class extends ge{constructor(t=1,e=1,i=1,r=1){super(),i=Math.max(1,Math.floor(i)),r=Math.max(1,Math.floor(r));let s=[],a=[],o=[],n=[];for(let l=0;l<=r;l++){let h=l/r;for(let c=0;c<=i;c++){let f=c/i;if(s.push((f-.5)*t,(.5-h)*e,0),a.push(0,0,1),o.push(f,1-h),l>0&&c>0){let g=(i+1)*l+c-1,w=g-(i+1);n.push(w,g,w+1,g,g+1,w+1)}}}this.setFromBuffers(s,a,o,n)}},pn=class extends ge{constructor(t=1,e=16,i=12,r=0,s=Math.PI*2,a=0,o=Math.PI){super(),e=Math.max(3,Math.floor(e)),i=Math.max(2,Math.floor(i));let n=[],l=[],h=[],c=[],f=Math.min(a+o,Math.PI);for(let g=0;g<=i;g++){let w=g/i,d=a+w*o;for(let p=0;p<=e;p++){let A=p/e,b=r+A*s,x=-Math.cos(b)*Math.sin(d),u=Math.cos(d),m=Math.sin(b)*Math.sin(d);if(n.push(t*x,t*u,t*m),l.push(x,u,m),h.push(A,1-w),g>0&&p>0){let v=(e+1)*g+p,S=v-(e+1),_=S-1,D=v-1;(g!==1||a>0)&&c.push(S,_,v),(g!==i||f<Math.PI)&&c.push(_,D,v)}}}this.setFromBuffers(n,l,h,c)}},Nt=class extends ge{constructor(t=1,e=1,i=1,r=16,s=1,a=!1,o=0,n=Math.PI*2){super(),r=Math.max(3,Math.floor(r)),s=Math.max(1,Math.floor(Number(s)||1));let l=[],h=[],c=[],f=[],g=i/2,w=(e-t)/(i||1),d=r+1;for(let A=0;A<=s;A++){let b=A/s,x=b*(e-t)+t,u=g-b*i;for(let m=0;m<=r;m++){let v=m/r,S=o+v*n,_=Math.sin(S),D=Math.cos(S),P=Math.hypot(_,w,D)||1;if(l.push(x*_,u,x*D),h.push(_/P,w/P,D/P),c.push(v,1-b),A<s&&m<r){let N=A*d+m,E=N+d;f.push(N,E,N+1,E,E+1,N+1)}}}let p=(A,b)=>{if(a||A<=0)return;let x=b*g,u=l.length/3;l.push(0,x,0),h.push(0,b,0),c.push(.5,.5);let m=u+1;for(let v=0;v<=r;v++){let S=o+v/r*n,_=Math.sin(S),D=Math.cos(S);l.push(A*_,x,A*D),h.push(0,b,0),c.push(D*.5+.5,.5+b*_*.5),v<r&&f.push(u,m+v+(b>0?0:1),m+v+(b>0?1:0))}};p(t,1),p(e,-1),this.setFromBuffers(l,h,c,f)}},bn=class extends Nt{constructor(t=1,e=1,i=16,r=1,s=!1,a=0,o=Math.PI*2){super(0,t,e,i,r,s,a,o)}},gn=class extends ge{constructor(t=1,e=.4,i=12,r=48,s=Math.PI*2){super(),i=Math.max(3,Math.floor(i)),r=Math.max(3,Math.floor(r));let a=[],o=[],n=[],l=[];for(let h=0;h<=i;h++){let c=h/i*Math.PI*2,f=Math.cos(c),g=Math.sin(c);for(let w=0;w<=r;w++){let d=w/r*s,p=Math.cos(d),A=Math.sin(d);if(a.push((t+e*f)*p,(t+e*f)*A,e*g),o.push(f*p,f*A,g),n.push(w/r,h/i),h>0&&w>0){let b=(r+1)*h+w-1,x=b-(r+1);l.push(b,x,b+1,x,x+1,b+1)}}}this.setFromBuffers(a,o,n,l)}};function Br(t,e,i,r,s){let a=Math.max(2,Math.min(256,Math.floor(Number(e)||64))),o=Math.max(3,Math.min(64,Math.floor(Number(i)||8))),n=Number(r)||.1,l=[],h=[],c=[],f=[],g=[],w=new ie,d=new ie,p=new ie;for(let b=0;b<=a;b++){let x=new ie;s(b/a,x),g.push(x)}let A=o+1;for(let b=0;b<=a;b++){let x=b/a,u=g[b];w.subVectors(g[Math.min(a,b+1)],g[Math.max(0,b-1)]).normalize(),b===0&&d.set(Math.abs(w.y)>.9?1:0,Math.abs(w.y)>.9?0:1,0),p.crossVectors(w,d).normalize(),d.crossVectors(p,w).normalize();for(let m=0;m<=o;m++){let v=m/o*Math.PI*2,S=-Math.cos(v),_=Math.sin(v),D=S*d.x+_*p.x,P=S*d.y+_*p.y,N=S*d.z+_*p.z;if(l.push(u.x+n*D,u.y+n*P,u.z+n*N),h.push(D,P,N),c.push(x,m/o),b>0&&m>0){let E=A*(b-1)+m-1,F=E+A;f.push(E,F,E+1,F,F+1,E+1)}}}t.setFromBuffers(l,h,c,f)}var yn=class extends ge{constructor(t=1,e=.4,i=64,r=8,s=2,a=3){super(),i=Math.floor(i),r=Math.floor(r),Br(this,i,r,e,(o,n)=>{let l=o*s*Math.PI*2,h=a/s*l,c=t*(2+Math.cos(h))*.5;n.set(c*Math.cos(l),c*Math.sin(l),t*Math.sin(h)*.5)})}},ze=class{getPoint(t,e=new ie){return e}getPointAt(t,e=new ie){return this.getPoint(t,e)}getTangent(t,e=new ie){return e.subVectors(this.getPoint(Math.min(1,t+.001)),this.getPoint(Math.max(0,t-.001))).normalize()}getPoints(t=5){let e=Math.max(1,Math.min(512,Math.floor(Number(t)||5))),i=[];for(let r=0;r<=e;r++)i.push(this.getPoint(r/e));return i}getSpacedPoints(t=5){return this.getPoints(t)}},xn=class extends ze{constructor(t=new ie,e=new ie){super(),this.v1=t,this.v2=e}getPoint(t,e=new ie){return e.lerpVectors(this.v1,this.v2,t)}},vn=class extends ze{constructor(t=new ie,e=new ie,i=new ie){super(),this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new ie){return e.lerpVectors(this.v0,this.v1,t).lerp(new ie().lerpVectors(this.v1,this.v2,t),t)}},Mn=class extends ze{constructor(t=new ie,e=new ie,i=new ie,r=new ie){super(),this.v0=t,this.v1=e,this.v2=i,this.v3=r}getPoint(t,e=new ie){let i=new ie().lerpVectors(this.v0,this.v1,t),r=new ie().lerpVectors(this.v1,this.v2,t),s=new ie().lerpVectors(this.v2,this.v3,t);return e.lerpVectors(i.lerp(r,t),r.lerp(s,t),t)}},wn=class extends ze{constructor(t=[],e=!1){super(),this.points=Array.isArray(t)?t:[],this.closed=!!e}getPoint(t,e=new ie){let i=this.points,r=i.length;if(!r)return e.set(0,0,0);if(r===1)return e.copy(i[0]);let s=(this.closed?r:r-1)*Math.max(0,Math.min(1,Number(t)||0)),a=Math.floor(s),o=s-a;!this.closed&&a>=r-1&&(a=r-2,o=1);let n=p=>i[this.closed?(p%r+r)%r:Math.max(0,Math.min(r-1,p))],l=n(a-1),h=n(a),c=n(a+1),f=n(a+2),g=o*o,w=g*o,d=(p,A,b,x)=>.5*(2*A+(b-p)*o+(2*p-5*A+4*b-x)*g+(3*A-p-3*b+x)*w);return e.set(d(l.x,h.x,c.x,f.x),d(l.y,h.y,c.y,f.y),d(l.z,h.z,c.z,f.z))}},Pt=class extends ge{constructor(t=[new Ee(0,-.5),new Ee(.5,0),new Ee(0,.5)],e=12,i=0,r=Math.PI*2){super();let s=Array.isArray(t)&&t.length>=2?t:[new Ee(.2,0),new Ee(.2,.5)],a=Math.max(3,Math.min(128,Math.floor(Number(e)||12))),o=[],n=[],l=[],h=[],c=s.length;for(let f=0;f<=a;f++){let g=f/a,w=i+g*r,d=Math.sin(w),p=Math.cos(w),A=f*c;for(let b=0;b<c;b++){let x=s[b],u=Number(x?.x)||0,m=Number(x?.y)||0;o.push(u*d,m,u*p);let v=s[Math.max(0,b-1)],S=s[Math.min(c-1,b+1)],_=(Number(S?.x)||0)-(Number(v?.x)||0),D=(Number(S?.y)||0)-(Number(v?.y)||0),P=Math.hypot(D,_)||1;if(n.push(D/P*d,-_/P,D/P*p),l.push(g,b/(c-1)),f<a&&b<c-1){let N=A+b,E=N+c;h.push(N,E,N+1,E,E+1,N+1)}}}this.setFromBuffers(o,n,l,h)}},Sn=class extends ge{constructor(t,e=64,i=1,r=8,s=!1){super(),Br(this,e,r,i,(a,o)=>{let n=t?.getPointAt??t?.getPoint;if(typeof n=="function"){let l=n.call(t,a,o);l&&l!==o&&o.copy(l)}else o.set(0,a,0)})}},Et="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ct=class{constructor(t=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new Ee(1,1),this.offset=new Ee(0,0),this.image=null,this.width=0,this.height=0,this.source=t,t&&typeof t=="object"&&(this.image=t)}dispose(){}},An=class extends ct{constructor(t=null,e=1,i=1,r=1023,s=1009,a,o=1001,n=1001,l=1003,h=1003,c=1,f=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1,this._sig=0;let g=Number(e),w=Number(i),d=t&&typeof t.length=="number"?t:null;this.width=g,this.height=w,this.image={data:d,width:g,height:w},this.format=Number(r)||1023,this.type=Number(s)||1009,this.wrapS=Number(o)||1001,this.wrapT=Number(n)||1001,this.magFilter=Number(l)||1003,this.minFilter=Number(h)||1003,this.colorSpace=f||"",this._bake()}get needsUpdate(){return!1}set needsUpdate(t){t&&this._bake()}_bake(){let t=this.image,e=t?.data,i=Number(t?.width??this.width),r=Number(t?.height??this.height);if(!e||!e.length||!(i>0&&r>0)||i>2048||r>2048){this.source="";return}let s=Math.max(1,i|0),a=Math.max(1,r|0),o=s*a,n=this.format,l=n===1021||n===1024||n===1028||e.length===o?1:n===1025||n===1030||e.length===o*2?2:n===1022||e.length===o*3?3:4,h=this.type===1015||this.type===1016||e instanceof Float32Array||e instanceof Float64Array,c=Math.min(s,48),f=Math.min(a,48),g=(this.flipY?257:1)^this.colorSpace.length^e.length,w=Math.max(1,e.length>>6|0);for(let F=0;F<e.length;F+=w)g=Math.imul(g^(e[F]*256|0),16777619)|0;if(g===this._sig&&this.source)return;this._sig=g;let d=f*(1+c*4),p=new Uint8Array(68+d),A=new DataView(p.buffer);A.setUint32(0,2303741511),A.setUint32(4,218765834),A.setUint32(8,13),A.setUint32(12,1229472850),A.setUint32(16,c),A.setUint32(20,f),p[24]=8,p[25]=6,A.setUint32(29,st(p.subarray(12,29))),A.setUint32(33,d+11),A.setUint32(37,1229209940),p[41]=120,p[42]=1,p[43]=1,A.setUint16(44,d,!0),A.setUint16(46,~d&65535,!0);let b=48,x=1,u=0,m=0,v=0,S=0,_=0,D=F=>{if(!Number.isFinite(F))return 0;let L=h&&F<=1?F*255:F;return L>0?L<255?L+.5|0:255:0};for(let F=0;F<f;F++){let L=F*a/f|0,M=this.flipY?a-1-L:L;p[b++]=0,u+=x;for(let O=0;O<c;O++){let H=(M*s+(O*s/c|0))*l,R=n===1021?255:D(e[H]??0),C=l>=3||n===1030?D(e[H+1]??0):R,y=l>=3?D(e[H+2]??0):n===1030?0:R,T=l===4?D(e[H+3]??255):n===1021?D(e[H]??255):n===1025?D(e[H+1]??255):255;p[b++]=R,x+=R,u+=x,p[b++]=C,x+=C,u+=x,p[b++]=y,x+=y,u+=x,p[b++]=T,x+=T,u+=x,m+=R,v+=C,S+=y,_+=T}x%=65521,u%=65521}A.setUint32(b,(u<<16|x)>>>0),A.setUint32(b+4,st(p.subarray(37,b+4))),A.setUint32(b+12,1229278788),A.setUint32(b+16,2923585666);let P=c*f*255,N=this.colorSpace==="srgb-linear";this.avgColor=[N?m/P:Ae(m/P),N?v/P:Ae(v/P),N?S/P:Ae(S/P),_/P];let E=["data:image/png;base64,"];for(let F=0;F<p.length;F+=3){let L=p[F]<<16|(p[F+1]??0)<<8|(p[F+2]??0);E.push(Et[L>>18&63]+Et[L>>12&63]+(F+1<p.length?Et[L>>6&63]:"=")+(F+2<p.length?Et[L&63]:"="))}this.source=E.join("")}},Rn=class{load(t,e){let i=new ct(t);return e?.(i),i}};function we(t,e){return t!==void 0?Number(t):e}function an(t,e){return t!==void 0?!!t:e}var Te=class{constructor(t={}){this.name=t.name||"",this.color=new Le(t.color??16777215),this.emissive=new Le(t.emissive??0),this.emissiveIntensity=we(t.emissiveIntensity,1),this.roughness=we(t.roughness,.5),this.metalness=we(t.metalness,0),this.opacity=we(t.opacity,1),this.transparent=an(t.transparent,!1),this.wireframe=an(t.wireframe,!1),this.side=we(t.side,2),this.doubleSided=an(t.doubleSided,!0),this.map=t.map||null;for(let e of["normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"])t[e]&&(this[e]=t[e]);this.clearcoat=we(t.clearcoat,0),this.clearcoatRoughness=we(t.clearcoatRoughness,0),this.sheen=we(t.sheen,0),this.sheenColor=new Le(t.sheenColor??0),this.sheenRoughness=we(t.sheenRoughness,0),this.transmission=we(t.transmission,0),this.thickness=we(t.thickness,0),this.attenuationColor=new Le(t.attenuationColor??16777215),this.attenuationDistance=we(t.attenuationDistance,1/0),this.ior=we(t.ior,1.5),this.dispersion=we(t.dispersion,0),this.iridescence=we(t.iridescence,0),this.iridescenceIOR=we(t.iridescenceIOR,1.3)}dispose(){}},Je=class extends Te{},Tn=class extends Te{},En=class extends Te{},_n=class extends Te{},Cn=class extends Te{},De=class cs{constructor(){this.name="",this.matrixAutoUpdate=!0,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.parent=null,this.children=[],this.userData={},this.position=new ie,this.rotation=new Dt,this.quaternion=new at,this.scale=new ie(1,1,1),this.matrix=new He,this.matrixWorld=new He,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let e=this.quaternion,i=Math.atan2(2*(e.w*e.x+e.y*e.z),1-2*(e.x*e.x+e.y*e.y)),r=Math.asin(Math.max(-1,Math.min(1,2*(e.w*e.y-e.z*e.x)))),s=Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z));this.rotation.set(i,r,s)})}add(...e){for(let i of e)i&&i instanceof cs&&(i.parent&&i.parent.remove(i),i.parent=this,this.children.push(i));return this}remove(...e){for(let i of e){let r=this.children.indexOf(i);r!==-1&&(i.parent=null,this.children.splice(r,1))}return this}traverse(e){let i=new Set,r=[this];for(;r.length>0;){let s=r.pop();if(!s||typeof s!="object"||i.has(s))continue;i.add(s),e(s);let a=s.children;if(Array.isArray(a))for(let o=a.length-1;o>=0;o--)r.push(a[o])}}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(e=!1){this.traverse(i=>{Vr(i),(i.matrixAutoUpdate||e)&&i.updateMatrix?.(),i.parent&&i.parent.matrixWorld?i.matrixWorld?.multiplyMatrices(i.parent.matrixWorld,i.matrix):i.matrix&&i.matrixWorld?.copy(i.matrix)})}lookAt(e,i,r){let s=typeof e=="object"?e:new ie(e,i,r);this.target instanceof ie?this.target.copy(s):this.target?.position instanceof ie&&this.target.position.copy(s),this.updateMatrixWorld(!0);let a=new He;a.lookAt(this.position,s,new ie(0,1,0));let o=a.elements,n=o[0],l=o[4],h=o[8],c=o[1],f=o[5],g=o[9],w=o[2],d=o[6],p=o[10],A=n+f+p;if(A>0){let b=.5/Math.sqrt(A+1);this.quaternion.set((d-g)*b,(h-w)*b,(c-l)*b,.25/b)}}translateOnAxis(e,i){let r=e.clone().applyMatrix4(new He().makeRotationFromQuaternion(this.quaternion)).multiplyScalar(i);return this.position.add(r),this}translateX(e){return this.translateOnAxis(new ie(1,0,0),e)}translateY(e){return this.translateOnAxis(new ie(0,1,0),e)}translateZ(e){return this.translateOnAxis(new ie(0,0,1),e)}rotateX(e){return this.rotation.x+=e,this}rotateY(e){return this.rotation.y+=e,this}rotateZ(e){return this.rotation.z+=e,this}_chain(){let e=[];for(let i=this;i&&e.length<64;i=i.parent)e.push(i);return e}_syncWorld(){let e=this._chain();for(let i=e.length-1;i>=0;i--){let r=e[i];r.updateMatrix?.(),r.parent?.matrixWorld?r.matrixWorld.multiplyMatrices(r.parent.matrixWorld,r.matrix):r.matrixWorld?.copy(r.matrix)}return this.matrixWorld.elements}getWorldPosition(e=new ie){let i=this._syncWorld();return e.set(i[12],i[13],i[14])}getWorldScale(e=new ie){let i=this._syncWorld();return e.set(Math.hypot(i[0],i[1],i[2]),Math.hypot(i[4],i[5],i[6]),Math.hypot(i[8],i[9],i[10]))}getWorldDirection(e=new ie){let i=this._syncWorld();return e.set(i[8],i[9],i[10]).normalize()}getWorldQuaternion(e=new at){let i=this._chain();e.set(0,0,0,1);for(let r=i.length-1;r>=0;r--)e.multiply(i[r].quaternion);return e}clone(e=!0){let i=this instanceof We?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof Fe?new Fe(this.geometry,this.material):new this.constructor;i.name=this.name,i.position.copy(this.position),i.quaternion.copy(this.quaternion),i.scale.copy(this.scale),i.visible=this.visible,i.castShadow=this.castShadow,i.receiveShadow=this.receiveShadow;try{i.userData=JSON.parse(JSON.stringify(this.userData||{}))}catch{i.userData={...this.userData||{}}}if(e)for(let r of this.children)i.add(r.clone(!0));return i}},Ln=class extends De{},Fe=class extends De{constructor(t,e){super(),this.isMesh=!0;let i=Array.isArray(e)?e[0]:e;this.geometry=t instanceof ge?t:t?(et("unsupported geometry","BoxGeometry"),new It(.5,.5,.5)):new ge,this.material=i instanceof Te?i:i?(et("unsupported material","MeshStandardMaterial"),new Je({color:13421772})):new Je}};function Vr(t){typeof t?._bakeAuthorGeometry=="function"&&t._bakeAuthorGeometry();let e=ue().materializeDeclarativeGeometry;typeof e=="function"&&e(t)}var kt=1e4,Ft=class extends Fe{constructor(t,e,i=1){super(t,e),this.instanceColor=null,this.isInstancedMesh=!0;let r=Number(i);if(!Number.isFinite(r)||r<0||r>kt)throw new RangeError(`SecurityError: InstancedMesh count (${String(i)}) exceeds MAX_INSTANCES_PER_MESH (${kt})`);this.count=Math.floor(r);let s=new Float32Array(this.count*16);for(let a=0;a<this.count;a++){let o=a*16;s[o]=1,s[o+5]=1,s[o+10]=1,s[o+15]=1}this.instanceMatrix=new ve(s,16)}setMatrixAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e||!e.elements)return;let r=this.instanceMatrix.array,s=i*16;if(!(s+16>r.length))for(let a=0;a<16;a++){let o=Number(e.elements[a]);r[s+a]=Number.isFinite(o)?o:a%5===0?1:0}}getMatrixAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e||!e.elements)return;let r=this.instanceMatrix.array,s=i*16;if(!(s+16>r.length))for(let a=0;a<16;a++)e.elements[a]=r[s+a]}setColorAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let a=new Float32Array(this.count*3);a.fill(1),this.instanceColor=new ve(a,3)}let r=this.instanceColor.array,s=i*3;r[s]=Number.isFinite(e.r)?e.r:1,r[s+1]=Number.isFinite(e.g)?e.g:1,r[s+2]=Number.isFinite(e.b)?e.b:1}getColorAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e)return;if(!this.instanceColor||this.instanceColor.array.length<(i+1)*3){e.setRGB(1,1,1);return}let r=this.instanceColor.array,s=i*3;e.setRGB(r[s],r[s+1],r[s+2])}dispose(){}},Qe=class extends De{constructor(t=16777215,e=1){super(),this.color=new Le(t),this.intensity=Number(e),this.type="directional"}},Ot=class extends Qe{constructor(t,e){super(t,e),this.type="ambient"}},Dn=class extends Qe{constructor(t,e){super(t,e),this.target=new De,this.type="directional"}},Ut=class extends Qe{constructor(t,e,i=0,r=2){super(t,e),this.type="point",this.distance=i,this.decay=r}},Bt=class extends De{},In=class extends Bt{constructor(t=45,e=1,i=.1,r=1e3){super(),this.target=new ie(0,0,0),this.fov=Number(t),this.aspect=Number(e),this.near=Number(i),this.far=Number(r)}},Vt=class extends De{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return ke.validate(this),it(this)}toGLB(){return ke.validate(this),wt(this)}toUSDZ(){return ke.validate(this),St(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let t=new Map,e=0;return this.traverse(i=>{if(i instanceof Fe){let r=new Float32Array(i.matrixWorld.elements);t.set(e,r),i.name&&t.set(i.name,r),e++}}),t}},zr=it,Gr=wt,Di=St,ke=class{static validate(t){let e=0,i=0,r=0,s=new Set,a=(n,l,h)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${n} (${l}). Found: ${h}`)},o=(n,l)=>{if(!Number.isFinite(l))throw new Error(`SecurityError: Scene reports a non-finite ${n} count (${String(l)}), which cannot be bounds-checked.`);return l};t.traverse(n=>{if(Vr(n),n instanceof Fe||n.geometry?.attributes?.position?.count){if(r++,r>1e3&&a("MESHES",1e3,r),n instanceof Ft){let h=o("instance",n.count);(h<0||h>kt)&&a("INSTANCES",kt,h)}let l=n.geometry;if(l){let h=0;if(l.attributes.position&&(h=o("vertex",l.attributes.position.count),e+=h,e>1e5&&a("VERTICES",1e5,e)),l.index){let c=o("index",l.index.count);i+=c,i>3e5&&a("INDICES",3e5,i);let f=l.index.array;if(f&&h>0){let g=Math.min(c,f.length);for(let w=0;w<g;w++){let d=f[w];if(!Number.isFinite(d)||d<0||d>=h)throw new Error(`SecurityError: Index buffer value (${String(d)}) out of vertex bounds [0, ${h}).`)}}}}if(n.material){let h=n.material;for(let c of["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"])h[c]&&s.add(h[c])}}}),s.size>16&&a("TEXTURES",16,s.size);for(let n of s){let l=n,h=l.image,c=Number(h?.width??l.width??0)||0,f=Number(h?.height??l.height??0)||0;(!Number.isFinite(c)||!Number.isFinite(f)||c>2048||f>2048)&&a("TEXTURE_DIMENSION",2048,Math.max(c,f))}}},Nn=class{constructor(t={}){this.shadowMap={enabled:!1,type:0},this.capabilities={isWebGL2:!0,maxTextures:16},this.boundViewer=null,this.hasInitialModelRendered=!1,this.domElement=t.canvas||(typeof document<"u"?document.createElement("canvas"):{}),t.viewer&&(this.boundViewer=t.viewer),t.container?.threeLiveViewer&&(this.boundViewer=t.container.threeLiveViewer),t.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=t.canvas.parentElement.threeLiveViewer);let e=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=t.isSandboxed||e,this.containerId=t.containerId||""}setSize(t,e){return this}setPixelRatio(t){return this}setClearColor(t,e=1){let i=new Le(t);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(i.r,i.g,i.b,e),this}clear(){return this}dispose(){}render(t,e){if(this.isSandboxed){ke.validate(t);let r=(s,a)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(a&&a.length?self.postMessage(s,a):self.postMessage(s))};if(this.hasInitialModelRendered){let s=t.getMeshTransforms(),a={};for(let[o,n]of s.entries())a[o]=Array.from(n);r({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:a})}else{this.hasInitialModelRendered=!0;let s=zr(t),a=Gr(t),o=(s.lights||[]).map(n=>({type:n.type,color:n.color,intensity:n.intensity,position:n.position}));r({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:a.buffer,dynamicLights:o,camera:e?{fov:e.fov||60,position:[e.position.x,e.position.y,e.position.z]}:void 0},[a.buffer])}return}let i=this.boundViewer;!i&&this.domElement?.parentElement&&this.domElement.parentElement.threeLiveViewer&&(i=this.domElement.parentElement.threeLiveViewer,this.boundViewer=i),!i&&typeof window<"u"&&(i=window.__three_live_active_viewer__,this.boundViewer=i),i&&typeof i.loadModel=="function"&&(i._hasThreeLiveModelLoaded?typeof i.updateMeshTransforms=="function"&&i.updateMeshTransforms(t.getMeshTransforms()):(i.loadModel(t.toCanvas3D()),i._hasThreeLiveModelLoaded=!0))}};function Ir(){return typeof globalThis<"u"&&typeof globalThis.__three_live_sim_time_ms__=="number"?globalThis.__three_live_sim_time_ms__:typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Pn=class{constructor(t=!0){this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1,this.autoStart=t,t&&this.start()}start(){this.startTime=Ir(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let t=0;if(this.autoStart&&!this.running&&this.start(),this.running){let e=Ir();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}};function Ii(){}var _t=new Proxy(Ii,{get:(t,e)=>{if(e==="isProxy")return!0;if(!(e==="constructor"||e==="__proto__"||e==="prototype"))return e==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:e==="shadowMap"?{enabled:!1,type:0}:e==="capabilities"?{isWebGL2:!0,maxTextures:16}:e===Symbol.toPrimitive?()=>0:_t},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>_t,construct:()=>_t}),Nr=(()=>{try{if(typeof document>"u")return null;let t=document.currentScript;return t?.src?t.src:t?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([t.textContent],{type:"text/javascript"})):null}catch{return null}})();function $t(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function ut(t,e){if(!t||typeof t!="string")return!1;let i=t.trim();if(!i)return!1;try{let r=new URL(i,$t());return!(r.protocol!=="https:"&&r.protocol!=="http:"&&r.protocol!=="blob:"||e?.requireSameOrigin&&r.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&r.origin!==location.origin)}catch{return!1}}var Pr,ot;function Ni(t){if(!ut(t))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${t}".`);let e=globalThis.trustedTypes;if(!e||typeof e.createPolicy!="function")return t;if(ot===void 0||Pr!==e){Pr=e;try{ot=e.createPolicy("three-live#worker",{createScriptURL:i=>{if(!ut(i))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${i}".`);return i}})}catch{ot=null}}return ot?ot.createScriptURL(t):t}function Hr(){let t=ue().sandboxEngineSrc;if(t)return t;if(Nr)return Nr;try{if(typeof document>"u")return null;let e=$t(),i=Array.from(document.querySelectorAll("script[src]"));for(let r of i){let s=r.src;if(!s)continue;let a=new URL(s,e).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(a)&&ut(s,{requireSameOrigin:!0}))return s}}catch{}return null}function Yn(t,e){if(!ut(t))throw new Error(`SecurityError: Refusing to load ${e} from disallowed URL "${t}". Only http:, https:, and blob: URLs are permitted.`);return new URL(t,$t()).href}function Pi(){let t=Hr();if(!t)throw new Error("Three-Live could not locate its own bundle URL, which the worker sandbox needs in order to load the THREE runtime. Set it explicitly, e.g. ThreeLiveElement.sandboxEngineSrc = new URL('three-live.min.js', import.meta.url).href. Refusing to execute the script, because unsandboxed host-realm execution is prohibited.");return Yn(t,"sandbox engine")}function ki(){let t=ue().sandboxIframeSrc;if(t)return t;let e=Hr();if(!e||!ut(e))return null;let i=new URL(e,$t());return i.protocol==="blob:"?null:new URL("three-live-sandbox.html",i).href}function Fi(){let t=ki();if(!t)throw new Error("Three-Live could not locate three-live-sandbox.html for iframe sandbox execution. Set ThreeLiveElement.sandboxIframeSrc (or ThreeLiveElement.sandboxEngineSrc) explicitly.");return Yn(t,"sandbox iframe")}function Oi(){return!!ue().allowClientScripts}function Ui(t){return Yn(t,"procedural scene script")}var Bi=["fetch","XMLHttpRequest","WebSocket","WebSocketStream","WebTransport","EventSource","importScripts","Request","Response","Headers","navigator","WorkerNavigator","WorkerLocation","RTCPeerConnection","RTCDataChannel","FontFace","FontFaceSet","fonts","PerformanceObserver","ReportingObserver","indexedDB","IDBFactory","caches","CacheStorage","Cache","cookieStore","StorageManager","FileSystemHandle","Worker","SharedWorker","ServiceWorker","ServiceWorkerContainer","ServiceWorkerRegistration","registration","clients","BroadcastChannel","MessageChannel","MessagePort","createImageBitmap","OffscreenCanvas","WebAssembly","WorkerGlobalScope","DedicatedWorkerGlobalScope","trustedTypes","TrustedTypePolicyFactory","SharedArrayBuffer","Atomics"];function Vi(t,e){let i=self,r=t.nonce,s=t.engineSrc,a=t.allowedScriptUrl,o=t.allowClientScripts,n=t.revoked,l=i.postMessage.bind(i);function h(u){l({type:"ERROR",nonce:r,message:String(u)})}let c=typeof i.importScripts=="function"?i.importScripts.bind(i):null,f=a,g=null;try{let u=s;if(typeof i.trustedTypes<"u"&&i.trustedTypes&&typeof i.trustedTypes.createPolicy=="function")try{let m={createScriptURL:function(S){if(S!==s&&(!a||S!==a))throw new TypeError("Disallowed worker importScripts URL");return S}};o&&(m.createScript=function(S){return String(S)});let v=i.trustedTypes.createPolicy("three-live#worker-boot",m);u=v.createScriptURL(s),a&&(f=v.createScriptURL(a)),o&&typeof v.createScript=="function"&&(g=v.createScript.bind(v))}catch{}c(u)}catch(u){h('Sandbox failed to load the Three-Live engine from "'+s+'". It must be a same-origin (or CORS-enabled) IIFE bundle such as three-live.min.js. Underlying error: '+(u&&u.message||u));return}let w=i.THREE;if(!w||typeof w.Scene!="function"){h('Sandbox loaded "'+s+'" but it did not install a THREE namespace. Point sandboxEngineSrc at an IIFE build (three-live.min.js), not an ES module build.');return}if(Array.isArray(e)){let u=i.__THREE_LIVE_REGISTRY__;for(let m=0;m<e.length;m++)if(typeof e[m]=="function")try{e[m](w,u)}catch{}}function d(u,m,v){let S=i;for(;S&&S!==Object.prototype;){if(!v&&S!==i)try{delete S[u]}catch{}if(!v||S===i||Object.prototype.hasOwnProperty.call(S,u))try{Object.defineProperty(S,u,v?{value:m,writable:!1,configurable:!1}:{value:m,writable:!1,configurable:!1,enumerable:!1})}catch{}try{S=Object.getPrototypeOf(S)}catch{break}}}for(let u=0;u<n.length;u++)d(n[u],void 0);d("performance",Object.freeze({now:function(){return Date.now()}}));let p=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],A=!1;function b(u,m){if(u.type==="3D_MODEL_READY"){if(A)return;A=!0}u.nonce=r,m&&m.length?l(u,m):l(u)}d("postMessage",function(u,m){if(!u||p.indexOf(u.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+p.join(", ")+").");b(u,m)},!0);let x=!1;i.onmessage=function(u){let m=u&&u.data;if(!(!m||m.nonce!==r)&&!(m.type!=="EXECUTE"&&m.type!=="EXECUTE_URL")&&!x){x=!0;try{let v=new w.Scene,S=new w.PerspectiveCamera(60,1,.1,1e3),_=new w.WebGLRenderer({isSandboxed:!0});if(m.type==="EXECUTE_URL"){if(!a||m.scriptUrl!==a||typeof c!="function"){h("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let D=f||a,P=c;if(c=null,f=null,i.THREE=w,i.scene=v,i.camera=S,i.renderer=_,P(D),typeof i.__THREE_LIVE_SCENE__=="function"){let N=i.__THREE_LIVE_SCENE__(w,v,S,_);N&&typeof N.toGLB=="function"&&(v=N)}else i.scene&&typeof i.scene.toGLB=="function"&&(v=i.scene)}else{if(!o){h("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let D=g?(0,eval)(g(`(function (THREE, scene, camera, renderer) {
|
|
333
|
+
${S.body}${v(u)}${h(u)}${S.tail}}
|
|
334
|
+
`}}if(m+=`}
|
|
335
|
+
`,i.length>0){m+=`def Scope "Lights"
|
|
336
|
+
{
|
|
337
|
+
`;let c=new Set;for(let u=0;u<i.length;u++){let y=i[u],f=Mn(c,ht(y.name,`Light_${u}`)),w=y.type==="directional"?"DistantLight":y.type==="spot"?"DiskLight":"SphereLight",M=y.type==="spot"?'["ShapingAPI", "ShadowAPI"]':'["ShadowAPI"]',[S,L,P]=y.color||[1,1,1],[C,R,A]=y.position||[0,5,5],T=-C,D=-R,E=-A;y.direction&&y.direction.length>=3&&(y.type==="directional"?(T=-y.direction[0],D=-y.direction[1],E=-y.direction[2]):(T=y.direction[0],D=y.direction[1],E=y.direction[2]));let[k,I,$,N]=zr(T,D,E),U="",d=[];y.type!=="directional"&&(Math.abs(C)>1e-7||Math.abs(R)>1e-7||Math.abs(A)>1e-7)&&(U+=`double3 xformOp:translate = ${Ne(C,R,A)}
|
|
338
|
+
`,d.push('"xformOp:translate"')),y.type!=="point"&&(1-Math.abs(N)>1e-7||Math.hypot(k,I,$)>1e-7)&&(U+=`quatf xformOp:orient = ${mt(N,k,I,$)}
|
|
339
|
+
`,d.push('"xformOp:orient"')),d.length>0&&(U+=`uniform token[] xformOpOrder = [${d.join(", ")}]
|
|
340
|
+
`);let F="";if(y.type==="spot"){let _=(y.outerConeAngle??Math.PI/3)*180/Math.PI,O=(y.innerConeAngle??_*.8)*180/Math.PI,q=_>1e-4?Math.max(0,Math.min(1,1-O/_)):0;F=`float inputs:shaping:cone:angle = ${ve(_)}
|
|
341
|
+
float inputs:shaping:cone:softness = ${ve(q)}
|
|
342
|
+
`}m+=`def ${w} "${f}" (
|
|
343
|
+
prepend apiSchemas = ${M}
|
|
344
|
+
)
|
|
345
|
+
{
|
|
346
|
+
color3f inputs:color = ${Ne(S,L,P)}
|
|
347
|
+
float inputs:intensity = ${ve(y.intensity??1)}
|
|
348
|
+
bool inputs:shadow:enable = 1
|
|
349
|
+
${F}${U}}
|
|
350
|
+
`}m+=`}
|
|
351
|
+
`}return m+=`}
|
|
352
|
+
`,m}var Ct=null;function ft(t){if(!Ct){Ct=new Uint32Array(256);for(let i=0;i<256;i++){let r=i;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;Ct[i]=r}}let e=4294967295;for(let i=0;i<t.length;i++)e=Ct[(e^t[i])&255]^e>>>8;return(e^4294967295)>>>0}function jr(t){let e=[],i=0,r=[];for(let p of t){let v=An(p.filename),h=ft(p.data),b=p.data.length,x=30+v.length,g=(i+x)%64,c=g!==0?64-g:0;c>0&&c<4&&(c+=64);let u=new Uint8Array(x+c),y=new DataView(u.buffer);y.setUint32(0,67324752,!0),y.setUint16(4,20,!0),y.setUint32(14,h,!0),y.setUint32(18,b,!0),y.setUint32(22,b,!0),y.setUint16(26,v.length,!0),y.setUint16(28,c,!0),u.set(v,30),c>=4&&(y.setUint16(x,6534,!0),y.setUint16(x+2,c-4,!0)),e.push({offset:i,size:b,crc:h,filenameBytes:v,entry:p}),r.push(u,p.data),i+=u.length+p.data.length}let n=i;for(let p of e){let v=new Uint8Array(46+p.filenameBytes.length),h=new DataView(v.buffer);h.setUint32(0,33639248,!0),h.setUint16(4,20,!0),h.setUint16(6,20,!0),h.setUint32(16,p.crc,!0),h.setUint32(20,p.size,!0),h.setUint32(24,p.size,!0),h.setUint16(28,p.filenameBytes.length,!0),h.setUint32(42,p.offset,!0),v.set(p.filenameBytes,46),r.push(v),i+=v.length}let s=i-n,a=new Uint8Array(22),o=new DataView(a.buffer);o.setUint32(0,101010256,!0),o.setUint16(8,e.length,!0),o.setUint16(10,e.length,!0),o.setUint32(12,s,!0),o.setUint32(16,n,!0),r.push(a),i+=22;let l=new Uint8Array(i),m=0;for(let p of r)l.set(p,m),m+=p.length;return l}function $r(t){let e=[{filename:"model.usda",data:An(qi(t))}],i=new Set(["model.usda"]),r=[...t];for(;r.length>0;){let n=r.pop();for(let s of n.textures||[])s?.file&&s.data?.byteLength&&!i.has(s.file)&&(i.add(s.file),e.push({filename:s.file,data:s.data}));if(n.children)for(let s=n.children.length-1;s>=0;s--)r.push(n.children[s])}return jr(e)}function Pt(t){return $r(Xi(t))}function It(t){return $r(Xr(Xe(t)))}function kt(t){return t&&typeof t.toUSDZ=="function"?t.toUSDZ():It(t)}function rt(t){let e=kt(t);return new Blob([e],{type:"model/vnd.usdz+zip"})}var Le=class Ts{constructor(e=0,i=0){this.x=Number(e),this.y=Number(i)}set(e,i){return this.x=Number(e),this.y=Number(i),this}clone(){return new Ts(this.x,this.y)}copy(e){return this.set(e.x,e.y)}add(e){return this.x+=e.x,this.y+=e.y,this}sub(e){return this.x-=e.x,this.y-=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divideScalar(e){return this.multiplyScalar(e?1/e:0)}setScalar(e){return this.set(e,e)}get width(){return this.x}set width(e){this.x=Number(e)}get height(){return this.y}set height(e){this.y=Number(e)}},ie=class Ps{constructor(e=0,i=0,r=0){this.x=Number(e),this.y=Number(i),this.z=Number(r)}set(e,i,r){return this.x=Number(e),this.y=Number(i),this.z=Number(r),this}clone(){return new Ps(this.x,this.y,this.z)}copy(e){return this.set(e.x,e.y,e.z)}add(e){return this.addVectors(this,e)}addVectors(e,i){return this.set(e.x+i.x,e.y+i.y,e.z+i.z)}sub(e){return this.subVectors(this,e)}subVectors(e,i){return this.set(e.x-i.x,e.y-i.y,e.z-i.z)}multiplyScalar(e){return this.set(this.x*e,this.y*e,this.z*e)}divideScalar(e){return this.multiplyScalar(e?1/e:0)}setScalar(e){return this.set(e,e,e)}addScaledVector(e,i){return this.set(this.x+e.x*i,this.y+e.y*i,this.z+e.z*i)}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let e=this.length();return e>1e-5?this.multiplyScalar(1/e):this}cross(e){return this.crossVectors(this,e)}crossVectors(e,i){let r=e.x,n=e.y,s=e.z,a=i.x,o=i.y,l=i.z;return this.set(n*l-s*o,s*a-r*l,r*o-n*a)}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y,this.z-e.z)}lerp(e,i){return this.lerpVectors(this,e,i)}lerpVectors(e,i,r){return this.x=e.x+(i.x-e.x)*r,this.y=e.y+(i.y-e.y)*r,this.z=e.z+(i.z-e.z)*r,this}applyMatrix4(e){let i=this.x,r=this.y,n=this.z,s=e.elements,a=1/(s[3]*i+s[7]*r+s[11]*n+s[15]);return this.x=(s[0]*i+s[4]*r+s[8]*n+s[12])*a,this.y=(s[1]*i+s[5]*r+s[9]*n+s[13])*a,this.z=(s[2]*i+s[6]*r+s[10]*n+s[14])*a,this}},En=class{constructor(t=0,e=0,i=0,r=1){this.x=Number(t),this.y=Number(e),this.z=Number(i),this.w=Number(r)}set(t,e,i,r){return this.x=Number(t),this.y=Number(e),this.z=Number(i),this.w=Number(r),this}},Vt=class Cs{constructor(e=0,i=0,r=0,n="XYZ"){this._onChangeCallback=null,this._x=Number(e),this._y=Number(i),this._z=Number(r),this.order=n}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}set(e,i,r,n=this.order){return this._x=Number(e),this._y=Number(i),this._z=Number(r),this.order=n,this._onChangeCallback?.(),this}copy(e){return this.set(e.x,e.y,e.z,e.order)}clone(){return new Cs(this._x,this._y,this._z,this.order)}_onChange(e){return this._onChangeCallback=e,this}},bt=class Es{constructor(e=0,i=0,r=0,n=1){this._onChangeCallback=null,this._x=Number(e),this._y=Number(i),this._z=Number(r),this._w=Number(n)}get x(){return this._x}set x(e){this._x=Number(e),this._onChangeCallback?.()}get y(){return this._y}set y(e){this._y=Number(e),this._onChangeCallback?.()}get z(){return this._z}set z(e){this._z=Number(e),this._onChangeCallback?.()}get w(){return this._w}set w(e){this._w=Number(e),this._onChangeCallback?.()}set(e,i,r,n){return this._x=Number(e),this._y=Number(i),this._z=Number(r),this._w=Number(n),this._onChangeCallback?.(),this}copy(e){return this.set(e.x,e.y,e.z,e.w)}clone(){return new Es(this._x,this._y,this._z,this._w)}identity(){return this.set(0,0,0,1)}setFromEuler(e,i=!0){let r=e.x,n=e.y,s=e.z,a=Math.cos(r/2),o=Math.cos(n/2),l=Math.cos(s/2),m=Math.sin(r/2),p=Math.sin(n/2),v=Math.sin(s/2);return this._x=m*o*l+a*p*v,this._y=a*p*l-m*o*v,this._z=a*o*v+m*p*l,this._w=a*o*l-m*p*v,i&&this._onChangeCallback?.(),this}setFromAxisAngle(e,i){let r=i/2,n=Math.sin(r);return this.set(e.x*n,e.y*n,e.z*n,Math.cos(r))}normalize(){let e=Math.hypot(this._x,this._y,this._z,this._w);return e===0?this.set(0,0,0,1):this.set(this._x/e,this._y/e,this._z/e,this._w/e)}setFromUnitVectors(e,i){let r=e.dot(i)+1;return r<1e-6?(Math.abs(e.x)>Math.abs(e.z)?this.set(-e.y,e.x,0,0):this.set(0,-e.z,e.y,0)).normalize():this.set(e.y*i.z-e.z*i.y,e.z*i.x-e.x*i.z,e.x*i.y-e.y*i.x,r).normalize()}multiply(e){return this.multiplyQuaternions(this,e)}multiplyQuaternions(e,i){let r=e.x,n=e.y,s=e.z,a=e.w,o=i.x,l=i.y,m=i.z,p=i.w;return this._x=r*p+a*o+n*m-s*l,this._y=n*p+a*l+s*o-r*m,this._z=s*p+a*m+r*l-n*o,this._w=a*p-r*o-n*l-s*m,this._onChangeCallback?.(),this}_onChange(e){return this._onChangeCallback=e,this}},Ze=class _s{constructor(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}identity(){let e=this.elements;return e.fill(0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,this}copy(e){return this.elements.set(e.elements),this}clone(){let e=new _s;return e.copy(this),e}compose(e,i,r){return ct(this.elements,[i.x,i.y,i.z,i.w],[e.x,e.y,e.z],[r.x,r.y,r.z]),this}multiply(e){return this.multiplyMatrices(this,e)}multiplyMatrices(e,i){return xe(this.elements,e.elements,i.elements),this}lookAt(e,i,r){return at(this.elements,[e.x,e.y,e.z],[i.x,i.y,i.z],[r.x,r.y,r.z]),this}makeRotationFromQuaternion(e){let i=new ie(0,0,0),r=new ie(1,1,1);return this.compose(i,e,r)}makeTranslation(e,i,r){return this.identity(),this.elements[12]=Number(e),this.elements[13]=Number(i),this.elements[14]=Number(r),this}makeScale(e,i,r){return this.identity(),this.elements[0]=Number(e),this.elements[5]=Number(i),this.elements[10]=Number(r),this}},Ln=class{constructor(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1])}identity(){let t=this.elements;return t.fill(0),t[0]=1,t[4]=1,t[8]=1,this}getNormalMatrix(t){return Fe(this.elements,t.elements),this}},Ee=t=>t<=.04045?t/12.92:((t+.055)/1.055)**2.4,Nt=t=>t<=.0031308?t*12.92:1.055*t**(1/2.4)-.055,qr={black:0,white:16777215,red:16711680,green:32768,lime:65280,blue:255,yellow:16776960,cyan:65535,aqua:65535,magenta:16711935,fuchsia:16711935,gray:8421504,grey:8421504,silver:12632256,orange:16753920,purple:8388736,pink:16761035,gold:16766720},Ue=class Ls{constructor(e,i,r){this.r=1,this.g=1,this.b=1,e!==void 0&&(i!==void 0&&r!==void 0?this.setRGB(e,i,r):this.set(e))}set(e){return typeof e=="number"?this.setHex(e):typeof e=="string"?this.setStyle(e):(e&&typeof e=="object"&&"r"in e&&(this.r=Number(e.r),this.g=Number(e.g),this.b=Number(e.b)),this)}setStyle(e){let i=e.trim().toLowerCase();if(i[0]==="#"){let r=i.slice(1);r.length===3||r.length===4?r=r[0]+r[0]+r[1]+r[1]+r[2]+r[2]:r.length===8&&(r=r.slice(0,6));let n=parseInt(r,16);r.length===6&&!Number.isNaN(n)&&this.setHex(n)}else if(i in qr)this.setHex(qr[i]);else if(i.startsWith("hsl")){let r=/^hsla?\(([^)]+)\)$/.exec(i)?.[1].trim().split(/[\s,/]+/);r&&r.length>=3&&this.setHSL((parseFloat(r[0])||0)/360,(parseFloat(r[1])||0)/100,(parseFloat(r[2])||0)/100)}else{let r=/^rgba?\(([^)]+)\)$/.exec(i)?.[1].trim().split(/[\s,/]+/);if(r&&r.length>=3){let n=s=>Ee(Math.max(0,Math.min(1,(parseFloat(s)||0)/(s.endsWith("%")?100:255))));this.setRGB(n(r[0]),n(r[1]),n(r[2]))}}return this}setHSL(e,i,r){if(e=((Number(e)||0)%1+1)%1,i=Math.max(0,Math.min(1,Number(i)||0)),r=Math.max(0,Math.min(1,Number(r)||0)),i===0){let o=Ee(r);return this.setRGB(o,o,o)}let n=r<=.5?r*(1+i):r+i-r*i,s=2*r-n,a=o=>(o<0&&(o+=1),o>1&&(o-=1),o<1/6?s+(n-s)*6*o:o<1/2?n:o<2/3?s+(n-s)*6*(2/3-o):s);return this.setRGB(Ee(a(e+1/3)),Ee(a(e)),Ee(a(e-1/3)))}lerp(e,i){return this.lerpColors(this,e,i)}lerpColors(e,i,r){let n=Number(r)||0;return this.setRGB(e.r+(i.r-e.r)*n,e.g+(i.g-e.g)*n,e.b+(i.b-e.b)*n)}multiplyScalar(e){let i=Number(e)||0;return this.setRGB(this.r*i,this.g*i,this.b*i)}setScalar(e){let i=Number(e)||0;return this.setRGB(i,i,i)}setHex(e){let i=Math.floor(e);return this.setRGB(Ee((i>>16&255)/255),Ee((i>>8&255)/255),Ee((i&255)/255))}setRGB(e,i,r){return this.r=Number(e),this.g=Number(i),this.b=Number(r),this}convertSRGBToLinear(){return this.setRGB(Ee(this.r),Ee(this.g),Ee(this.b))}convertLinearToSRGB(){return this.setRGB(Nt(this.r),Nt(this.g),Nt(this.b))}getHex(){let e=i=>Math.round(Nt(Math.max(0,Math.min(1,i)))*255);return e(this.r)<<16|e(this.g)<<8|e(this.b)}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}copy(e){return this.setRGB(e.r,e.g,e.b)}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}clone(){return new Ls(this.r,this.g,this.b)}},Rn=1234567,Yi={degToRad:t=>t*Math.PI/180,radToDeg:t=>t*180/Math.PI,clamp:(t,e,i)=>Math.max(e,Math.min(i,t)),lerp:(t,e,i)=>t+(e-t)*i,generateUUID:()=>Math.random().toString(36).substring(2,15),randInt:(t,e)=>t+Math.floor(Math.random()*(e-t+1)),randFloat:(t,e)=>t+Math.random()*(e-t),randFloatSpread:t=>t*(.5-Math.random()),seededRandom:t=>{t!==void 0&&(Rn=Number.isFinite(t)?t|0:0);let e=Rn=Rn+1831565813|0;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}},Re=class Ns{constructor(e,i){if(this.needsUpdate=!1,typeof i!="number"||!Number.isInteger(i)||i<1||i>16)throw new Error(`SecurityError: BufferAttribute itemSize must be an integer in [1, 16]. Received: ${String(i)}`);Array.isArray(e)?this.array=new Float32Array(e):this.array=e,this.itemSize=i;let r=this.array?this.array.length:0;if(!Number.isFinite(r)||r<0)throw new Error(`SecurityError: BufferAttribute array has a non-finite length: ${String(r)}`);this.count=Math.floor(r/i)}getX(e){return this.array[e*this.itemSize]}getY(e){return this.itemSize>=2?this.array[e*this.itemSize+1]:0}getZ(e){return this.itemSize>=3?this.array[e*this.itemSize+2]:0}setX(e,i){return this.array[e*this.itemSize]=i,this.needsUpdate=!0,this}setY(e,i){return this.array[e*this.itemSize+1]=i,this.needsUpdate=!0,this}setZ(e,i){return this.array[e*this.itemSize+2]=i,this.needsUpdate=!0,this}setXYZ(e,i,r,n){let s=e*this.itemSize;return this.array[s]=i,this.array[s+1]=r,this.array[s+2]=n,this.needsUpdate=!0,this}setUsage(e){return this}clone(){let e=this.array?.constructor||Float32Array;return new Ns(new e(this.array),this.itemSize)}},Cn=class extends Re{constructor(t,e){super(t instanceof Float32Array||Array.isArray(t)?t:new Float32Array(t),e)}},Dn=class extends Re{constructor(t,e){super(t instanceof Uint16Array?t:new Uint16Array(t),e)}},Pn=class extends Re{constructor(t,e){super(t instanceof Uint32Array?t:new Uint32Array(t),e)}},Me=class Ds{constructor(){this.name="",this.attributes={},this.index=null,this.boundingBox=null}setAttribute(e,i){return this.attributes[e]=i,this}getAttribute(e){return this.attributes[e]}setIndex(e){if(e instanceof Re)this.index=e;else if(Array.isArray(e)){let i=0;for(let r of e)r>i&&(i=r);this.index=new Re(new(i>65535?Uint32Array:Uint16Array)(e),1)}else e&&e.buffer&&(this.index=new Re(e,1));return this}computeVertexNormals(){let e=this.attributes.position;if(!e)return this;let i=!1;if(typeof i=="function"){let l=i(e.array,this.index?.array);return this.setAttribute("normal",new Re(l,3)),this}let r=e.count,n=e.array,s=new Float32Array(r*3),a=this.index?.array,o=a?a.length:r;for(let l=0;l<o;l+=3){let m=(a?a[l]:l)*3,p=(a?a[l+1]:l+1)*3,v=(a?a[l+2]:l+2)*3,h=n[p],b=n[p+1],x=n[p+2],g=n[v]-h,c=n[v+1]-b,u=n[v+2]-x,y=n[m]-h,f=n[m+1]-b,w=n[m+2]-x,M=c*w-u*f,S=u*y-g*w,L=g*f-c*y;s[m]+=M,s[m+1]+=S,s[m+2]+=L,s[p]+=M,s[p+1]+=S,s[p+2]+=L,s[v]+=M,s[v+1]+=S,s[v+2]+=L}for(let l=0;l<r*3;l+=3){let m=s[l],p=s[l+1],v=s[l+2],h=Math.hypot(m,p,v)||1;s[l]=m/h,s[l+1]=p/h,s[l+2]=v/h}return this.setAttribute("normal",new Re(s,3)),this}setFromBuffers(e,i,r,n){this.setAttribute("position",new Re(e,3)),this.setAttribute("normal",new Re(i,3)),this.setAttribute("uv",new Re(r,2)),this.setIndex(n)}setFromPoints(e){let i=[];if(Array.isArray(e))for(let r of e)i.push(Number(r?.x)||0,Number(r?.y)||0,Number(r?.z)||0);return this.setAttribute("position",new Re(i,3))}computeBoundingBox(){let e=this.attributes.position,i=new ie(1/0,1/0,1/0),r=new ie(-1/0,-1/0,-1/0);if(e&&e.count>0)for(let n=0;n<e.count;n++){let s=e.getX(n),a=e.getY(n),o=e.getZ(n);s<i.x&&(i.x=s),a<i.y&&(i.y=a),o<i.z&&(i.z=o),s>r.x&&(r.x=s),a>r.y&&(r.y=a),o>r.z&&(r.z=o)}else i.set(0,0,0),r.set(0,0,0);return this.boundingBox={min:i,max:r},this.boundingBox}center(){let e=this.computeBoundingBox();return e.max.x<e.min.x?this:this.translate(-(e.min.x+e.max.x)*.5,-(e.min.y+e.max.y)*.5,-(e.min.z+e.max.z)*.5)}_xform(e,i){let r=this.attributes.position;if(r){let n=r.array;for(let s=0;s<n.length;s+=3)e(n,s);r.needsUpdate=!0,i&&this.computeVertexNormals(),this.computeBoundingBox()}return this}translate(e=0,i=0,r=0){return this._xform((n,s)=>{n[s]+=e,n[s+1]+=i,n[s+2]+=r})}scale(e=1,i=1,r=1){return this._xform((n,s)=>{n[s]*=e,n[s+1]*=i,n[s+2]*=r},!0)}_rot(e,i,r){let n=Math.cos(r),s=Math.sin(r);for(let a of[this.attributes.position,this.attributes.normal]){if(!a)continue;let o=a.array;for(let l=0;l<o.length;l+=3){let m=o[l+e],p=o[l+i];o[l+e]=m*n-p*s,o[l+i]=m*s+p*n}a.needsUpdate=!0}return this}rotateX(e){return this._rot(1,2,e)}rotateY(e){return this._rot(2,0,e)}rotateZ(e){return this._rot(0,1,e)}applyMatrix4(e){let i=this.attributes.position;if(i&&e?.elements){let r=new ie;for(let n=0;n<i.count;n++)r.set(i.getX(n),i.getY(n),i.getZ(n)).applyMatrix4(e),i.setXYZ(n,r.x,r.y,r.z);this.computeVertexNormals()}return this}clone(){let e=new Ds;e.name=this.name;for(let i of Object.keys(this.attributes))e.attributes[i]=this.attributes[i].clone();return this.index&&(e.index=this.index.clone()),e}dispose(){}},zt=class extends Me{constructor(t=1,e=1,i=1){super();let r=t/2,n=e/2,s=i/2,a=[-r,-n,s,r,-n,s,r,n,s,-r,n,s,r,-n,-s,-r,-n,-s,-r,n,-s,r,n,-s,-r,n,s,r,n,s,r,n,-s,-r,n,-s,-r,-n,-s,r,-n,-s,r,-n,s,-r,-n,s,r,-n,s,r,-n,-s,r,n,-s,r,n,s,-r,-n,-s,-r,-n,s,-r,n,s,-r,n,-s],o=[],l=[],m=[];for(let p=0;p<6;p++){let v=p*4,h=2-(p>>1),b=p&1?-1:1;for(let x=0;x<4;x++)o.push(h===0?b:0,h===1?b:0,h===2?b:0);l.push(0,0,1,0,1,1,0,1),m.push(v,v+1,v+2,v,v+2,v+3)}this.setFromBuffers(a,o,l,m)}},In=class extends Me{constructor(t=1,e=1,i=1,r=1){super(),i=Math.max(1,Math.floor(i)),r=Math.max(1,Math.floor(r));let n=[],s=[],a=[],o=[];for(let l=0;l<=r;l++){let m=l/r;for(let p=0;p<=i;p++){let v=p/i;if(n.push((v-.5)*t,(.5-m)*e,0),s.push(0,0,1),a.push(v,1-m),l>0&&p>0){let h=(i+1)*l+p-1,b=h-(i+1);o.push(b,h,b+1,h,h+1,b+1)}}}this.setFromBuffers(n,s,a,o)}},kn=class extends Me{constructor(t=1,e=16,i=12,r=0,n=Math.PI*2,s=0,a=Math.PI){super(),e=Math.max(3,Math.floor(e)),i=Math.max(2,Math.floor(i));let o=[],l=[],m=[],p=[],v=Math.min(s+a,Math.PI);for(let h=0;h<=i;h++){let b=h/i,x=s+b*a;for(let g=0;g<=e;g++){let c=g/e,u=r+c*n,y=-Math.cos(u)*Math.sin(x),f=Math.cos(x),w=Math.sin(u)*Math.sin(x);if(o.push(t*y,t*f,t*w),l.push(y,f,w),m.push(c,1-b),h>0&&g>0){let M=(e+1)*h+g,S=M-(e+1),L=S-1,P=M-1;(h!==1||s>0)&&p.push(S,L,M),(h!==i||v<Math.PI)&&p.push(L,P,M)}}}this.setFromBuffers(o,l,m,p)}},Gt=class extends Me{constructor(t=1,e=1,i=1,r=16,n=1,s=!1,a=0,o=Math.PI*2){super(),r=Math.max(3,Math.floor(r)),n=Math.max(1,Math.floor(Number(n)||1));let l=[],m=[],p=[],v=[],h=i/2,b=(e-t)/(i||1),x=r+1;for(let c=0;c<=n;c++){let u=c/n,y=u*(e-t)+t,f=h-u*i;for(let w=0;w<=r;w++){let M=w/r,S=a+M*o,L=Math.sin(S),P=Math.cos(S),C=Math.hypot(L,b,P)||1;if(l.push(y*L,f,y*P),m.push(L/C,b/C,P/C),p.push(M,1-u),c<n&&w<r){let R=c*x+w,A=R+x;v.push(R,A,R+1,A,A+1,R+1)}}}let g=(c,u)=>{if(s||c<=0)return;let y=u*h,f=l.length/3;l.push(0,y,0),m.push(0,u,0),p.push(.5,.5);let w=f+1;for(let M=0;M<=r;M++){let S=a+M/r*o,L=Math.sin(S),P=Math.cos(S);l.push(c*L,y,c*P),m.push(0,u,0),p.push(P*.5+.5,.5+u*L*.5),M<r&&v.push(f,w+M+(u>0?0:1),w+M+(u>0?1:0))}};g(t,1),g(e,-1),this.setFromBuffers(l,m,p,v)}},Nn=class extends Gt{constructor(t=1,e=1,i=16,r=1,n=!1,s=0,a=Math.PI*2){super(0,t,e,i,r,n,s,a)}},Fn=class extends Me{constructor(t=1,e=.4,i=12,r=48,n=Math.PI*2){super(),i=Math.max(3,Math.floor(i)),r=Math.max(3,Math.floor(r));let s=[],a=[],o=[],l=[];for(let m=0;m<=i;m++){let p=m/i*Math.PI*2,v=Math.cos(p),h=Math.sin(p);for(let b=0;b<=r;b++){let x=b/r*n,g=Math.cos(x),c=Math.sin(x);if(s.push((t+e*v)*g,(t+e*v)*c,e*h),a.push(v*g,v*c,h),o.push(b/r,m/i),m>0&&b>0){let u=(r+1)*m+b-1,y=u-(r+1);l.push(u,y,u+1,y,y+1,u+1)}}}this.setFromBuffers(s,a,o,l)}};function ni(t,e,i,r,n){let s=Math.max(2,Math.min(256,Math.floor(Number(e)||64))),a=Math.max(3,Math.min(64,Math.floor(Number(i)||8))),o=Number(r)||.1,l=[],m=[],p=[],v=[],h=[],b=new ie,x=new ie,g=new ie;for(let u=0;u<=s;u++){let y=new ie;n(u/s,y),h.push(y)}let c=a+1;for(let u=0;u<=s;u++){let y=u/s,f=h[u];b.subVectors(h[Math.min(s,u+1)],h[Math.max(0,u-1)]).normalize(),u===0&&x.set(Math.abs(b.y)>.9?1:0,Math.abs(b.y)>.9?0:1,0),g.crossVectors(b,x).normalize(),x.crossVectors(g,b).normalize();for(let w=0;w<=a;w++){let M=w/a*Math.PI*2,S=-Math.cos(M),L=Math.sin(M),P=S*x.x+L*g.x,C=S*x.y+L*g.y,R=S*x.z+L*g.z;if(l.push(f.x+o*P,f.y+o*C,f.z+o*R),m.push(P,C,R),p.push(y,w/a),u>0&&w>0){let A=c*(u-1)+w-1,T=A+c;v.push(A,T,A+1,T,T+1,A+1)}}}t.setFromBuffers(l,m,p,v)}var Un=class extends Me{constructor(t=1,e=.4,i=64,r=8,n=2,s=3){super(),i=Math.floor(i),r=Math.floor(r),ni(this,i,r,e,(a,o)=>{let l=a*n*Math.PI*2,m=s/n*l,p=t*(2+Math.cos(m))*.5;o.set(p*Math.cos(l),p*Math.sin(l),t*Math.sin(m)*.5)})}},$e=class{getPoint(t,e=new ie){return e}getPointAt(t,e=new ie){return this.getPoint(t,e)}getTangent(t,e=new ie){return e.subVectors(this.getPoint(Math.min(1,t+.001)),this.getPoint(Math.max(0,t-.001))).normalize()}getPoints(t=5){let e=Math.max(1,Math.min(512,Math.floor(Number(t)||5))),i=[];for(let r=0;r<=e;r++)i.push(this.getPoint(r/e));return i}getSpacedPoints(t=5){return this.getPoints(t)}},On=class extends $e{constructor(t=new ie,e=new ie){super(),this.v1=t,this.v2=e}getPoint(t,e=new ie){return e.lerpVectors(this.v1,this.v2,t)}},Bn=class extends $e{constructor(t=new ie,e=new ie,i=new ie){super(),this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new ie){return e.lerpVectors(this.v0,this.v1,t).lerp(new ie().lerpVectors(this.v1,this.v2,t),t)}},Vn=class extends $e{constructor(t=new ie,e=new ie,i=new ie,r=new ie){super(),this.v0=t,this.v1=e,this.v2=i,this.v3=r}getPoint(t,e=new ie){let i=new ie().lerpVectors(this.v0,this.v1,t),r=new ie().lerpVectors(this.v1,this.v2,t),n=new ie().lerpVectors(this.v2,this.v3,t);return e.lerpVectors(i.lerp(r,t),r.lerp(n,t),t)}},zn=class extends $e{constructor(t=[],e=!1){super(),this.points=Array.isArray(t)?t:[],this.closed=!!e}getPoint(t,e=new ie){let i=this.points,r=i.length;if(!r)return e.set(0,0,0);if(r===1)return e.copy(i[0]);let n=(this.closed?r:r-1)*Math.max(0,Math.min(1,Number(t)||0)),s=Math.floor(n),a=n-s;!this.closed&&s>=r-1&&(s=r-2,a=1);let o=g=>i[this.closed?(g%r+r)%r:Math.max(0,Math.min(r-1,g))],l=o(s-1),m=o(s),p=o(s+1),v=o(s+2),h=a*a,b=h*a,x=(g,c,u,y)=>.5*(2*c+(u-g)*a+(2*g-5*c+4*u-y)*h+(3*c-g-3*u+y)*b);return e.set(x(l.x,m.x,p.x,v.x),x(l.y,m.y,p.y,v.y),x(l.z,m.z,p.z,v.z))}},Ht=class extends Me{constructor(t=[new Le(0,-.5),new Le(.5,0),new Le(0,.5)],e=12,i=0,r=Math.PI*2){super();let n=Array.isArray(t)&&t.length>=2?t:[new Le(.2,0),new Le(.2,.5)],s=Math.max(3,Math.min(128,Math.floor(Number(e)||12))),a=[],o=[],l=[],m=[],p=n.length;for(let v=0;v<=s;v++){let h=v/s,b=i+h*r,x=Math.sin(b),g=Math.cos(b),c=v*p;for(let u=0;u<p;u++){let y=n[u],f=Number(y?.x)||0,w=Number(y?.y)||0;a.push(f*x,w,f*g);let M=n[Math.max(0,u-1)],S=n[Math.min(p-1,u+1)],L=(Number(S?.x)||0)-(Number(M?.x)||0),P=(Number(S?.y)||0)-(Number(M?.y)||0),C=Math.hypot(P,L)||1;if(o.push(P/C*x,-L/C,P/C*g),l.push(h,u/(p-1)),v<s&&u<p-1){let R=c+u,A=R+p;m.push(R,A,R+1,A,A+1,R+1)}}}this.setFromBuffers(a,o,l,m)}},Gn=class extends Me{constructor(t,e=64,i=1,r=8,n=!1){super(),ni(this,e,r,i,(s,a)=>{let o=t?.getPointAt??t?.getPoint;if(typeof o=="function"){let l=o.call(t,s,a);l&&l!==a&&a.copy(l)}else a.set(0,s,0)})}},Ft="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gt=class{constructor(t=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new Le(1,1),this.offset=new Le(0,0),this.image=null,this.width=0,this.height=0,this.source=t,t&&typeof t=="object"&&(this.image=t)}dispose(){}},Hn=class extends gt{constructor(t=null,e=1,i=1,r=1023,n=1009,s,a=1001,o=1001,l=1003,m=1003,p=1,v=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1,this._sig=0;let h=Number(e),b=Number(i),x=t&&typeof t.length=="number"?t:null;this.width=h,this.height=b,this.image={data:x,width:h,height:b},this.format=Number(r)||1023,this.type=Number(n)||1009,this.wrapS=Number(a)||1001,this.wrapT=Number(o)||1001,this.magFilter=Number(l)||1003,this.minFilter=Number(m)||1003,this.colorSpace=v||"",this._bake()}get needsUpdate(){return!1}set needsUpdate(t){t&&this._bake()}_bake(){let t=this.image,e=t?.data,i=Number(t?.width??this.width),r=Number(t?.height??this.height);if(!e||!e.length||!(i>0&&r>0)||i>2048||r>2048){this.source="";return}let n=Math.max(1,i|0),s=Math.max(1,r|0),a=n*s,o=this.format,l=o===1021||o===1024||o===1028||e.length===a?1:o===1025||o===1030||e.length===a*2?2:o===1022||e.length===a*3?3:4,m=this.type===1015||this.type===1016||e instanceof Float32Array||e instanceof Float64Array,p=Math.min(n,64),v=Math.min(s,64),h=(this.flipY?257:1)^this.colorSpace.length^e.length,b=Math.max(1,e.length>>6|0);for(let T=0;T<e.length;T+=b)h=Math.imul(h^(e[T]*256|0),16777619)|0;if(h===this._sig&&this.source)return;this._sig=h;let x=v*(1+p*4),g=new Uint8Array(68+x),c=new DataView(g.buffer);c.setUint32(0,2303741511),c.setUint32(4,218765834),c.setUint32(8,13),c.setUint32(12,1229472850),c.setUint32(16,p),c.setUint32(20,v),g[24]=8,g[25]=6,c.setUint32(29,ft(g.subarray(12,29))),c.setUint32(33,x+11),c.setUint32(37,1229209940),g[41]=120,g[42]=1,g[43]=1,c.setUint16(44,x,!0),c.setUint16(46,~x&65535,!0);let u=48,y=1,f=0,w=0,M=0,S=0,L=0,P=T=>{if(!Number.isFinite(T))return 0;let D=m&&T<=1?T*255:T;return D>0?D<255?D+.5|0:255:0};for(let T=0;T<v;T++){let D=T*s/v|0,E=this.flipY?s-1-D:D;g[u++]=0,f+=y;for(let k=0;k<p;k++){let I=(E*n+(k*n/p|0))*l,$=o===1021?255:P(e[I]??0),N=l>=3||o===1030?P(e[I+1]??0):$,U=l>=3?P(e[I+2]??0):o===1030?0:$,d=l===4?P(e[I+3]??255):o===1021?P(e[I]??255):o===1025?P(e[I+1]??255):255;g[u++]=$,y+=$,f+=y,g[u++]=N,y+=N,f+=y,g[u++]=U,y+=U,f+=y,g[u++]=d,y+=d,f+=y,w+=$,M+=N,S+=U,L+=d}y%=65521,f%=65521}c.setUint32(u,(f<<16|y)>>>0),c.setUint32(u+4,ft(g.subarray(37,u+4))),c.setUint32(u+12,1229278788),c.setUint32(u+16,2923585666);let C=p*v*255,R=this.colorSpace==="srgb-linear";this.avgColor=[R?w/C:Ee(w/C),R?M/C:Ee(M/C),R?S/C:Ee(S/C),L/C];let A=["data:image/png;base64,"];for(let T=0;T<g.length;T+=3){let D=g[T]<<16|(g[T+1]??0)<<8|(g[T+2]??0);A.push(Ft[D>>18&63]+Ft[D>>12&63]+(T+1<g.length?Ft[D>>6&63]:"=")+(T+2<g.length?Ft[D&63]:"="))}this.source=A.join("")}},Wn=class{load(t,e){let i=new gt(t);return e?.(i),i}};function Ae(t,e){return t!==void 0?Number(t):e}function Tn(t,e){return t!==void 0?!!t:e}var Pe=class{constructor(t={}){this.name=t.name||"",this.color=new Ue(t.color??16777215),this._em=t.emissive!==void 0,this.emissive=new Ue(t.emissive??0),this.emissiveIntensity=Ae(t.emissiveIntensity,1),this.roughness=Ae(t.roughness,t.roughnessMap?1:.5),this.metalness=Ae(t.metalness,t.metalnessMap?1:0),this.opacity=Ae(t.opacity,1),this.transparent=Tn(t.transparent,!1),this.wireframe=Tn(t.wireframe,!1),this.side=Ae(t.side,2),this.doubleSided=Tn(t.doubleSided,!0),this.map=t.map||null,this.normalMap=t.normalMap||null;let e=t.normalScale;this.normalScale=typeof e=="number"?new Le(e,e):new Le(Ae(e?.x,1),Ae(e?.y,1)),this.roughnessMap=t.roughnessMap||null,this.metalnessMap=t.metalnessMap||null,this.emissiveMap=t.emissiveMap||null,this.aoMap=t.aoMap||null,this.aoMapIntensity=Ae(t.aoMapIntensity,1),this.bumpMap=t.bumpMap||null,this.bumpScale=Ae(t.bumpScale,1),this.clearcoat=Ae(t.clearcoat,0),this.clearcoatRoughness=Ae(t.clearcoatRoughness,0),this.sheen=Ae(t.sheen,0),this.sheenColor=new Ue(t.sheenColor??0),this.sheenRoughness=Ae(t.sheenRoughness,0),this.transmission=Ae(t.transmission,0),this.thickness=Ae(t.thickness,0),this.attenuationColor=new Ue(t.attenuationColor??16777215),this.attenuationDistance=Ae(t.attenuationDistance,1/0),this.ior=Ae(t.ior,1.5),this.dispersion=Ae(t.dispersion,0),this.iridescence=Ae(t.iridescence,0),this.iridescenceIOR=Ae(t.iridescenceIOR,1.3)}dispose(){}},it=class extends Pe{},Xn=class extends Pe{},jn=class extends Pe{},$n=class extends Pe{},qn=class extends Pe{},Oe=class ks{constructor(){this.name="",this.matrixAutoUpdate=!0,this.visible=!0,this._castShd=!1,this._castShdSet=!1,this._recvShd=!1,this._recvShdSet=!1,this.parent=null,this.children=[],this.userData={},this.position=new ie,this.rotation=new Vt,this.quaternion=new bt,this.scale=new ie(1,1,1),this.matrix=new Ze,this.matrixWorld=new Ze,this.rotation._onChange(()=>{this.quaternion.setFromEuler(this.rotation,!1)}),this.quaternion._onChange(()=>{let e=this.quaternion,i=Math.atan2(2*(e.w*e.x+e.y*e.z),1-2*(e.x*e.x+e.y*e.y)),r=Math.asin(Math.max(-1,Math.min(1,2*(e.w*e.y-e.z*e.x)))),n=Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z));this.rotation.set(i,r,n)})}get castShadow(){return this._castShd}set castShadow(e){this._castShd=!!e,this._castShdSet=!0}get receiveShadow(){return this._recvShd}set receiveShadow(e){this._recvShd=!!e,this._recvShdSet=!0}add(...e){for(let i of e)i&&i instanceof ks&&(i.parent&&i.parent.remove(i),i.parent=this,this.children.push(i));return this}remove(...e){for(let i of e){let r=this.children.indexOf(i);r!==-1&&(i.parent=null,this.children.splice(r,1))}return this}traverse(e){let i=new Set,r=[this];for(;r.length>0;){let n=r.pop();if(!n||typeof n!="object"||i.has(n))continue;i.add(n),e(n);let s=n.children;if(Array.isArray(s))for(let a=s.length-1;a>=0;a--)r.push(s[a])}}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(e=!1){this.traverse(i=>{ri(i),(i.matrixAutoUpdate||e)&&i.updateMatrix?.(),i.parent&&i.parent.matrixWorld?i.matrixWorld?.multiplyMatrices(i.parent.matrixWorld,i.matrix):i.matrix&&i.matrixWorld?.copy(i.matrix)})}lookAt(e,i,r){let n=typeof e=="object"?e:new ie(e,i,r);this.target instanceof ie?this.target.copy(n):this.target?.position instanceof ie&&this.target.position.copy(n),this.updateMatrixWorld(!0);let s=new Ze;s.lookAt(this.position,n,new ie(0,1,0));let a=s.elements,o=a[0],l=a[4],m=a[8],p=a[1],v=a[5],h=a[9],b=a[2],x=a[6],g=a[10],c=o+v+g;if(c>0){let u=.5/Math.sqrt(c+1);this.quaternion.set((x-h)*u,(m-b)*u,(p-l)*u,.25/u)}}translateOnAxis(e,i){let r=e.clone().applyMatrix4(new Ze().makeRotationFromQuaternion(this.quaternion)).multiplyScalar(i);return this.position.add(r),this}translateX(e){return this.translateOnAxis(new ie(1,0,0),e)}translateY(e){return this.translateOnAxis(new ie(0,1,0),e)}translateZ(e){return this.translateOnAxis(new ie(0,0,1),e)}rotateX(e){return this.rotation.x+=e,this}rotateY(e){return this.rotation.y+=e,this}rotateZ(e){return this.rotation.z+=e,this}_chain(){let e=[];for(let i=this;i&&e.length<64;i=i.parent)e.push(i);return e}_syncWorld(){let e=this._chain();for(let i=e.length-1;i>=0;i--){let r=e[i];r.updateMatrix?.(),r.parent?.matrixWorld?r.matrixWorld.multiplyMatrices(r.parent.matrixWorld,r.matrix):r.matrixWorld?.copy(r.matrix)}return this.matrixWorld.elements}getWorldPosition(e=new ie){let i=this._syncWorld();return e.set(i[12],i[13],i[14])}getWorldScale(e=new ie){let i=this._syncWorld();return e.set(Math.hypot(i[0],i[1],i[2]),Math.hypot(i[4],i[5],i[6]),Math.hypot(i[8],i[9],i[10]))}getWorldDirection(e=new ie){let i=this._syncWorld();return e.set(i[8],i[9],i[10]).normalize()}getWorldQuaternion(e=new bt){let i=this._chain();e.set(0,0,0,1);for(let r=i.length-1;r>=0;r--)e.multiply(i[r].quaternion);return e}clone(e=!0){let i=typeof this._cloneCustom=="function"?this._cloneCustom():this instanceof et?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof He?new He(this.geometry,this.material):new this.constructor;if(this instanceof qe){i.color.copy(this.color),i.intensity=this.intensity,i.shadow.copy(this.shadow);let r=this.target;r?.position&&i.target?.position&&i.target.position.copy(r.position),this instanceof tn&&i.groundColor.copy(this.groundColor)}i.name=this.name,i.position.copy(this.position),i.quaternion.copy(this.quaternion),i.scale.copy(this.scale),i.visible=this.visible,this._castShdSet&&(i.castShadow=this.castShadow),this._recvShdSet&&(i.receiveShadow=this.receiveShadow);try{i.userData=JSON.parse(JSON.stringify(this.userData||{}))}catch{i.userData={...this.userData||{}}}if(e)for(let r of this.children)i.add(r.clone(!0));return i}},Yn=class extends Oe{},He=class extends Oe{constructor(t,e){super(),this.isMesh=!0;let i=Array.isArray(e)?e[0]:e;this.geometry=t instanceof Me?t:t?(Je("unsupported geometry","BoxGeometry"),new zt(.5,.5,.5)):new Me,this.material=i instanceof Pe?i:i?(Je("unsupported material","MeshStandardMaterial"),new it({color:13421772})):new it}};function ri(t){typeof t?._bakeAuthorGeometry=="function"&&t._bakeAuthorGeometry();let e=ue().materializeDeclarativeGeometry;typeof e=="function"&&e(t)}var Wt=1e4,Xt=class extends He{constructor(t,e,i=1){super(t,e),this.instanceColor=null,this.isInstancedMesh=!0;let r=Number(i);if(!Number.isFinite(r)||r<0||r>Wt)throw new RangeError(`SecurityError: InstancedMesh count (${String(i)}) exceeds MAX_INSTANCES_PER_MESH (${Wt})`);this.count=Math.floor(r);let n=new Float32Array(this.count*16);for(let s=0;s<this.count;s++){let a=s*16;n[a]=1,n[a+5]=1,n[a+10]=1,n[a+15]=1}this.instanceMatrix=new Re(n,16)}setMatrixAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e||!e.elements)return;let r=this.instanceMatrix.array,n=i*16;if(!(n+16>r.length))for(let s=0;s<16;s++){let a=Number(e.elements[s]);r[n+s]=Number.isFinite(a)?a:s%5===0?1:0}}getMatrixAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e||!e.elements)return;let r=this.instanceMatrix.array,n=i*16;if(!(n+16>r.length))for(let s=0;s<16;s++)e.elements[s]=r[n+s]}setColorAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e)return;if(!this.instanceColor||this.instanceColor.array.length<this.count*3){let s=new Float32Array(this.count*3);s.fill(1),this.instanceColor=new Re(s,3)}let r=this.instanceColor.array,n=i*3;r[n]=Number.isFinite(e.r)?e.r:1,r[n+1]=Number.isFinite(e.g)?e.g:1,r[n+2]=Number.isFinite(e.b)?e.b:1}getColorAt(t,e){let i=Math.floor(Number(t));if(!Number.isFinite(i)||i<0||i>=this.count||!e)return;if(!this.instanceColor||this.instanceColor.array.length<(i+1)*3){e.setRGB(1,1,1);return}let r=this.instanceColor.array,n=i*3;e.setRGB(r[n],r[n+1],r[n+2])}dispose(){}},jt=class Fs{constructor(){this.mapSize=new Le(1024,1024),this.bias=-5e-4,this.normalBias=.015,this.radius=1.5,this.camera={near:.1,far:100,left:-5,right:5,top:5,bottom:-5,fov:50,updateProjectionMatrix:()=>{}}}copy(e){return this.mapSize.copy(e.mapSize),this.bias=Number(e.bias),this.normalBias=Number(e.normalBias),this.radius=Number(e.radius),this}clone(){return new Fs().copy(this)}},qe=class extends Oe{constructor(t=16777215,e=1){super(),this.isLight=!0,this.shadow=new jt,this.color=new Ue(t),this.intensity=Number(e),this.type="directional"}},$t=class extends qe{constructor(t,e){super(t,e),this.type="ambient"}},Kn=class extends qe{constructor(t,e){super(t,e),this.target=new Oe,this.type="directional"}},qt=class extends qe{constructor(t,e,i=0,r=2){super(t,e),this.type="point",this.distance=i,this.decay=r}},Yt=class extends Oe{},Zn=class extends Yt{constructor(t=45,e=1,i=.1,r=1e3){super(),this.target=new ie(0,0,0),this.fov=Number(t),this.aspect=Number(e),this.near=Number(i),this.far=Number(r)}},Kt=class extends Oe{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return Ge.validate(this),dt(this)}toGLB(){return Ge.validate(this),Dt(this)}toUSDZ(){return Ge.validate(this),Pt(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let t=new Map,e=0;return this.traverse(i=>{if(i instanceof He){let r=new Float32Array(i.matrixWorld.elements);t.set(e,r),i.name&&t.set(i.name,r),e++}}),t}},ii=dt,si=Dt,Ki=Pt;ue().makePngDeflater=bn;var Ge=class{static validate(t){let e=0,i=0,r=0,n=new Set,s=(o,l,m)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${o} (${l}). Found: ${m}`)},a=(o,l)=>{if(!Number.isFinite(l))throw new Error(`SecurityError: Scene reports a non-finite ${o} count (${String(l)}), which cannot be bounds-checked.`);return l};t.traverse(o=>{if(ri(o),o instanceof He||o.geometry?.attributes?.position?.count){if(r++,r>1e3&&s("MESHES",1e3,r),o instanceof Xt){let m=a("instance",o.count);(m<0||m>Wt)&&s("INSTANCES",Wt,m)}let l=o.geometry;if(l){let m=0;if(l.attributes.position&&(m=a("vertex",l.attributes.position.count),e+=m,e>1e5&&s("VERTICES",1e5,e)),l.index){let p=a("index",l.index.count);i+=p,i>3e5&&s("INDICES",3e5,i);let v=l.index.array;if(v&&m>0){let h=Math.min(p,v.length);for(let b=0;b<h;b++){let x=v[b];if(!Number.isFinite(x)||x<0||x>=m)throw new Error(`SecurityError: Index buffer value (${String(x)}) out of vertex bounds [0, ${m}).`)}}}}if(o.material){let m=o.material;for(let p of["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap","bumpMap"])m[p]&&n.add(m[p])}}}),n.size>16&&s("TEXTURES",16,n.size);for(let o of n){let l=o,m=l.image,p=Number(m?.width??l.width??0)||0,v=Number(m?.height??l.height??0)||0;(!Number.isFinite(p)||!Number.isFinite(v)||p>2048||v>2048)&&s("TEXTURE_DIMENSION",2048,Math.max(p,v))}}},Jn=class{constructor(t={}){this.shadowMap={enabled:!1,type:0},this.capabilities={isWebGL2:!0,maxTextures:16},this.boundViewer=null,this.hasInitialModelRendered=!1,this.domElement=t.canvas||(typeof document<"u"?document.createElement("canvas"):{}),t.viewer&&(this.boundViewer=t.viewer),t.container?.threeLiveViewer&&(this.boundViewer=t.container.threeLiveViewer),t.canvas?.parentElement?.threeLiveViewer&&(this.boundViewer=t.canvas.parentElement.threeLiveViewer);let e=typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope;this.isSandboxed=t.isSandboxed||e,this.containerId=t.containerId||""}setSize(t,e){return this}setPixelRatio(t){return this}setClearColor(t,e=1){let i=new Ue(t);return this.boundViewer&&typeof this.boundViewer.setClearColor=="function"&&this.boundViewer.setClearColor(i.r,i.g,i.b,e),this}clear(){return this}dispose(){}render(t,e){if(this.isSandboxed){Ge.validate(t);let r=(n,s)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(s&&s.length?self.postMessage(n,s):self.postMessage(n))};if(this.hasInitialModelRendered){let n=t.getMeshTransforms(),s={};for(let[a,o]of n.entries())s[a]=Array.from(o);r({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:s})}else{this.hasInitialModelRendered=!0;let n=ii(t),s=si(t),a=(n.lights||[]).map(o=>({type:o.type,color:o.color,intensity:o.intensity,position:o.position}));r({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:s.buffer,dynamicLights:a,camera:e?{fov:e.fov||60,position:[e.position.x,e.position.y,e.position.z]}:void 0},[s.buffer])}return}let i=this.boundViewer;!i&&this.domElement?.parentElement&&this.domElement.parentElement.threeLiveViewer&&(i=this.domElement.parentElement.threeLiveViewer,this.boundViewer=i),!i&&typeof window<"u"&&(i=window.__three_live_active_viewer__,this.boundViewer=i),i&&typeof i.loadModel=="function"&&(i._hasThreeLiveModelLoaded?typeof i.updateMeshTransforms=="function"&&i.updateMeshTransforms(t.getMeshTransforms()):(i.loadModel(t.toCanvas3D()),i._hasThreeLiveModelLoaded=!0))}};function Yr(){return typeof globalThis<"u"&&typeof globalThis.__three_live_sim_time_ms__=="number"?globalThis.__three_live_sim_time_ms__:typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Qn=class{constructor(t=!0){this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1,this.autoStart=t,t&&this.start()}start(){this.startTime=Yr(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let t=0;if(this.autoStart&&!this.running&&this.start(),this.running){let e=Yr();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}};function Zi(){}var Ut=new Proxy(Zi,{get:(t,e)=>{if(e==="isProxy")return!0;if(!(e==="constructor"||e==="__proto__"||e==="prototype"))return e==="domElement"?typeof document<"u"?document.createElement("canvas"):{}:e==="shadowMap"?{enabled:!1,type:0}:e==="capabilities"?{isWebGL2:!0,maxTextures:16}:e===Symbol.toPrimitive?()=>0:Ut},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>Ut,construct:()=>Ut}),Kr=(()=>{try{if(typeof document>"u")return null;let t=document.currentScript;return t?.src?t.src:t?.textContent&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(new Blob([t.textContent],{type:"text/javascript"})):null}catch{return null}})();function nn(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function yt(t,e){if(!t||typeof t!="string")return!1;let i=t.trim();if(!i)return!1;try{let r=new URL(i,nn());return!(r.protocol!=="https:"&&r.protocol!=="http:"&&r.protocol!=="blob:"||e?.requireSameOrigin&&r.protocol!=="blob:"&&typeof location<"u"&&location.origin&&location.origin!=="null"&&r.origin!==location.origin)}catch{return!1}}var Zr,pt;function Ji(t){if(!yt(t))throw new Error(`SecurityError: Refusing to create TrustedScriptURL for disallowed URL "${t}".`);let e=globalThis.trustedTypes;if(!e||typeof e.createPolicy!="function")return t;if(pt===void 0||Zr!==e){Zr=e;try{pt=e.createPolicy("three-live#worker",{createScriptURL:i=>{if(!yt(i))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${i}".`);return i}})}catch{pt=null}}return pt?pt.createScriptURL(t):t}function oi(){let t=ue().sandboxEngineSrc;if(t)return t;if(Kr)return Kr;try{if(typeof document>"u")return null;let e=nn(),i=Array.from(document.querySelectorAll("script[src]"));for(let r of i){let n=r.src;if(!n)continue;let s=new URL(n,e).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(s)&&yt(n,{requireSameOrigin:!0}))return n}}catch{}return null}function fr(t,e){if(!yt(t))throw new Error(`SecurityError: Disallowed ${e} URL "${t}" (http:, https:, or blob: required).`);return new URL(t,nn()).href}function Qi(){let t=oi();if(!t)throw new Error("SecurityError: Could not locate Three-Live bundle URL for worker sandbox; set ThreeLiveElement.sandboxEngineSrc explicitly.");return fr(t,"sandbox engine")}function es(){let t=ue().sandboxIframeSrc;if(t)return t;let e=oi();if(!e||!yt(e))return null;let i=new URL(e,nn());return i.protocol==="blob:"?null:new URL("three-live-sandbox.html",i).href}function ts(){let t=es();if(!t)throw new Error("SecurityError: Could not locate three-live-sandbox.html; set ThreeLiveElement.sandboxIframeSrc explicitly.");return fr(t,"sandbox iframe")}function ns(){return!!ue().allowClientScripts}function rs(t){return fr(t,"procedural scene script")}var is="fetch XMLHttpRequest WebSocket WebSocketStream WebTransport EventSource importScripts Request Response Headers navigator WorkerNavigator WorkerLocation RTCPeerConnection RTCDataChannel FontFace FontFaceSet fonts PerformanceObserver ReportingObserver indexedDB IDBFactory caches CacheStorage Cache cookieStore StorageManager FileSystemHandle Worker SharedWorker ServiceWorker ServiceWorkerContainer ServiceWorkerRegistration registration clients BroadcastChannel MessageChannel MessagePort createImageBitmap OffscreenCanvas WebAssembly WorkerGlobalScope DedicatedWorkerGlobalScope trustedTypes TrustedTypePolicyFactory SharedArrayBuffer Atomics".split(" ");function ss(t,e,i){let r=self,n=t.nonce,s=t.engineSrc,a=t.allowedScriptUrl,o=t.allowClientScripts,l=t.revoked,m=r.postMessage.bind(r),p=null;try{p=i?i(r.CompressionStream):null}catch{}let v=null;function h(L,P){let C=()=>P&&P.length?m(L,P):m(L);v?v=v.then(C,C):C()}function b(L){h({type:"ERROR",nonce:n,message:String(L)})}let x=typeof r.importScripts=="function"?r.importScripts.bind(r):null,g=a,c=null;try{let L=s;if(typeof r.trustedTypes<"u"&&r.trustedTypes&&typeof r.trustedTypes.createPolicy=="function")try{let P={createScriptURL:function(R){if(R!==s&&(!a||R!==a))throw new TypeError("Disallowed worker importScripts URL");return R}};o&&(P.createScript=function(R){return String(R)});let C=r.trustedTypes.createPolicy("three-live#worker-boot",P);L=C.createScriptURL(s),a&&(g=C.createScriptURL(a)),o&&typeof C.createScript=="function"&&(c=C.createScript.bind(C))}catch{}x(L)}catch(L){b('Sandbox failed to load "'+s+'" (must be an IIFE bundle like three-live.min.js): '+(L&&L.message||L));return}let u=r.THREE;if(!u||typeof u.Scene!="function"){b('Sandbox "'+s+'" did not install THREE; point sandboxEngineSrc at three-live.min.js.');return}if(Array.isArray(e)){let L=r.__THREE_LIVE_REGISTRY__;for(let P=0;P<e.length;P++)if(typeof e[P]=="function")try{e[P](u,L)}catch{}}function y(L,P,C){let R=r;for(;R&&R!==Object.prototype;){if(!C&&R!==r)try{delete R[L]}catch{}if(!C||R===r||Object.prototype.hasOwnProperty.call(R,L))try{Object.defineProperty(R,L,C?{value:P,writable:!1,configurable:!1}:{value:P,writable:!1,configurable:!1,enumerable:!1})}catch{}try{R=Object.getPrototypeOf(R)}catch{break}}}for(let L=0;L<l.length;L++)y(l[L],void 0);y("performance",Object.freeze({now:function(){return Date.now()}}));let f=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],w=!1;function M(L,P){if(L.type==="3D_MODEL_READY"){if(w)return;w=!0}if(L.nonce=n,L.type==="3D_MODEL_READY"&&p&&L.glbBuffer instanceof ArrayBuffer){let C=L.glbBuffer;v=(v||Promise.resolve()).then(()=>p.glb(new Uint8Array(C))).then(R=>{R.buffer!==C&&(L.glbBuffer=R.byteOffset===0&&R.byteLength===R.buffer.byteLength?R.buffer:R.slice().buffer),m(L,[L.glbBuffer])},()=>m(L,[C]));return}P&&P.length?h(L,P):h(L)}y("postMessage",function(L,P){if(!L||f.indexOf(L.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+f.join(", ")+").");M(L,P)},!0);let S=!1;r.onmessage=function(L){let P=L&&L.data;if(!P||P.nonce!==n||P.type!=="EXECUTE"&&P.type!=="EXECUTE_URL"||S)return;S=!0;let C=P.texturePack;if(C&&typeof C=="object"){let R=Object.create(null),A=0;for(let T of Object.keys(C)){let D=C[T],E=D&&D.size;A<64&&/^[0-9a-f]{16}$/.test(T)&&(E===256||E===512||E===1024)&&D.rgba instanceof Uint8Array&&D.rgba.length===E*E*4&&(R[T]=Object.freeze({size:E,rgba:D.rgba}),A++)}r.__three_live_texture_pack__=Object.freeze(R)}try{let R=new u.Scene,A=new u.PerspectiveCamera(60,1,.1,1e3),T=new u.WebGLRenderer({isSandboxed:!0});if(P.type==="EXECUTE_URL"){if(!a||P.scriptUrl!==a||typeof x!="function"){b("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let D=g||a,E=x;if(x=null,g=null,r.THREE=u,r.scene=R,r.camera=A,r.renderer=T,E(D),typeof r.__THREE_LIVE_SCENE__=="function"){let k=r.__THREE_LIVE_SCENE__(u,R,A,T);k&&typeof k.toGLB=="function"&&(R=k)}else r.scene&&typeof r.scene.toGLB=="function"&&(R=r.scene)}else{if(!o){b("SecurityError: Client-modified script compilation (Use Case 1) is disabled in this sandbox worker.");return}let D=c?(0,eval)(c(`(function (THREE, scene, camera, renderer) {
|
|
371
353
|
return (function () {
|
|
372
|
-
`+
|
|
354
|
+
`+P.script+`
|
|
373
355
|
;
|
|
374
356
|
return typeof scene === "object" && scene ? scene : undefined;
|
|
375
357
|
})();
|
|
376
358
|
})`)):new Function("THREE","scene","camera","renderer",`return (function () {
|
|
377
|
-
`+
|
|
359
|
+
`+P.script+`
|
|
378
360
|
;
|
|
379
361
|
return typeof scene === "object" && scene ? scene : undefined;
|
|
380
|
-
})();`);g=null;let P=D(w,v,S,_);P&&typeof P.toGLB=="function"&&(v=P)}if(!A){w.SceneQuotaValidator&&w.SceneQuotaValidator.validate(v);let D=v.toGLB(),P=D instanceof ArrayBuffer?D:D.buffer.slice(D.byteOffset,D.byteOffset+D.byteLength);b({type:"3D_MODEL_READY",glbBuffer:P},[P])}l({type:"DONE",nonce:r})}catch(v){h(v&&v.message||v)}}},l({type:"READY",nonce:r})}function Xr(t,e,i){let r=i?.allowedScriptUrl??null,s=i?.allowClientScripts??r===null,a={nonce:e,engineSrc:t,allowedScriptUrl:r,allowClientScripts:s,revoked:Bi},o=(ue().workerExtensionInstallers??[]).map(n=>`(${n.toString()})`).join(",");return`'use strict';(${Vi.toString()})(${JSON.stringify(a)},[${o}]);`}function Wr(t){t.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),t.onToast?.("Security Error: script timed out and was stopped.")}var Ve=0;function $r(){try{let t=new Uint32Array(4);return globalThis.crypto?.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function zi(t){try{return new TextEncoder().encode(t).length}catch{return t.length}}var Gi=1024,Hi=256;function kr(t){if(!Array.isArray(t)&&!(t instanceof Float32Array)||t.length!==16)return!1;for(let e=0;e<16;e++){let i=t[e];if(typeof i!="number"||!Number.isFinite(i))return!1}return!0}function jr(t,e){if(!t||typeof t!="object")return null;let i=t;if(i.nonce!==e)return null;switch(i.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof i.message=="string"?i.message:String(i.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,Gi)};case"3D_UPDATE_TRANSFORMS":{let r=i.transforms;if(Array.isArray(r)){if(r.length>1e3)return null;for(let s of r)if(!kr(s))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:r}}if(r&&typeof r=="object"){let s=Object.keys(r);if(s.length>1e3)return null;let a=Object.create(null),o=r;for(let n of s){if(n.length>Hi||n==="__proto__"||n==="constructor"||n==="prototype")return null;let l=o[n];if(!kr(l))return null;a[n]=l}return{type:"3D_UPDATE_TRANSFORMS",transforms:a}}return null}case"3D_MODEL_READY":{let r=i.glbBuffer;return!(r instanceof ArrayBuffer)||r.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:r}}default:return null}}function Xi(t){let e=zi(t);if(e>1048576)throw new Error(`SecurityError: Script length (${e} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Yr(t,e,i,r){switch(t.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":e.onUpdateTransforms?.(t.transforms);return;case"3D_MODEL_READY":if(r.modelDispatched)return;r.modelDispatched=!0,e.onModelReady(t.payload);return;case"DONE":i();return;case"ERROR":i(),e.onError?.(new Error(`Worker script error: ${t.message}`));return;default:return t}}function Wi(t,e,i,r){let s=$r(),a=Xr(e,s,t.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:t.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),o=document.createElement("iframe");o.setAttribute("sandbox","allow-scripts"),o.setAttribute("aria-hidden","true"),o.tabIndex=-1,o.style.display="none",o.src=i,Ve++;let n=!1,l=!1,h={modelDispatched:!1},c,f=()=>{if(n||l)return;let p=o.contentWindow;!p||typeof p.postMessage!="function"||(l=!0,p.postMessage(t.kind==="url"?{type:"SANDBOX_RUN",nonce:s,workerSource:a,scriptUrl:t.scriptUrl}:{type:"SANDBOX_RUN",nonce:s,workerSource:a,script:t.script},"*"))},g=()=>{},w=p=>{if(n||!o.contentWindow||p.source!==o.contentWindow)return;let A=p.data;if(A&&typeof A=="object"&&A.type==="IFRAME_READY"){f();return}let b=jr(A,s);b&&Yr(b,r,g,h)};g=()=>{n||(n=!0,c!==void 0&&clearTimeout(c),Ve=Math.max(0,Ve-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",w),typeof o.remove=="function"?o.remove():o.parentNode&&o.parentNode.removeChild(o))},c=setTimeout(()=>{n||(g(),Wr(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",w),o.onload=()=>{f()},o.onerror=()=>{g(),r.onError?.(new Error(`Sandbox iframe failed to load "${i}". Verify that three-live-sandbox.html is served at that URL.`))};let d=document.body||document.documentElement;if(!d||typeof d.appendChild!="function"){g();let p=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(p),p}return d.appendChild(o),{terminate:g}}function Fr(t,e,i,r){if(e==="worker"&&typeof Worker>"u")return r("Sandboxed procedural execution requires Web Workers, but Workers are unavailable in this environment. For host security, Three-Live prohibits unsandboxed in-process evaluation.","Security Error: Web Workers unavailable. Script execution aborted.");if(e==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return r("Sandboxed iframe execution requires a DOM environment with document.createElement. Refusing to evaluate in the host realm.","Security Error: DOM unavailable for iframe sandbox.");if(Ve>=32)return r(`SecurityError: ${Ve} sandbox workers are already running, which meets SECURITY_3D_MAX_CONCURRENT_TASKS (32). Refusing to start another.`,"Security Error: too many concurrent sandboxed scripts.");let s;try{s=Pi()}catch(g){let w=g instanceof Error?g.message:String(g);return r(w,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let g;try{g=Fi()}catch(w){let d=w instanceof Error?w.message:String(w);return r(d,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Wi(t,s,g,i))}catch(w){return Promise.reject(w)}}let a=$r(),o=Xr(s,a,t.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:t.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),n;try{let g=new Blob([o],{type:"application/javascript"}),w=URL.createObjectURL(g);try{let d=Ni(w);n=new Worker(d)}finally{URL.revokeObjectURL(w)}}catch(g){let w=g instanceof Error?g.message:String(g);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${w}`,"Security Error: Failed to start Worker sandbox.")}Ve++;let l=!1,h={modelDispatched:!1},c,f=()=>{l||(l=!0,c!==void 0&&clearTimeout(c),Ve=Math.max(0,Ve-1),n.terminate())};return c=setTimeout(()=>{l||(f(),Wr(i))},3e3),n.onmessage=g=>{let w=jr(g.data,a);w&&Yr(w,i,f,h)},n.onerror=g=>{f(),i.onError?.(new Error(`Worker execution error: ${g.message}`))},t.kind==="url"?n.postMessage({type:"EXECUTE_URL",scriptUrl:t.scriptUrl,nonce:a}):n.postMessage({type:"EXECUTE",script:t.script,nonce:a}),Promise.resolve({terminate:f})}function Or(t,e){return t==="none"||t==="unsafe-host-realm"?e(`SecurityError: sandbox="${t}" is prohibited. Sandboxing is mandatory for live compilation and cannot be bypassed. Use sandbox="worker" (default) or sandbox="iframe".`,`Security Error: sandbox="${t}" is not permitted.`):t!=="worker"&&t!=="iframe"?e(`SecurityError: Unsupported sandbox mode "${t}". Live compilation requires sandbox="worker" or sandbox="iframe".`,"Security Error: unsupported sandbox mode."):null}var Ur=t=>(e,i)=>{let r=new Error(e);return t.onError?.(r),i&&t.onToast?.(i),Promise.reject(r)},qn={execute(t,e,i,r){let s=Ur(i),a=Or(e,s);if(a)return a;try{Xi(t)}catch(o){let n=o instanceof Error?o.message:String(o);return s(n,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??Oi()?Fr({kind:"script",script:t},e,i,s):s(dt,ft)},executeUrl(t,e,i){let r=Ur(i),s=Or(e,r);if(s)return s;let a;try{a=Ui(t)}catch(o){let n=o instanceof Error?o.message:String(o);return r(n,"Security Error: disallowed scene script URL.")}return Fr({kind:"url",scriptUrl:a},e,i,r)}},zt=new Set;function et(t,e){let i=`[three-live] ${t} is unsupported; degraded to ${e}.`;zt.has(i)||(zt.add(i),typeof console<"u"&&typeof console.warn=="function"&&console.warn(i))}function $i(){return Array.from(zt)}function ji(){zt.clear()}var Gt=class extends Je{constructor(t={}){et("ShaderMaterial","MeshStandardMaterial");let e=t.uniforms||{},i=e.color?.value??e.uColor?.value??e.diffuse?.value??t.color;super({color:i!==void 0?i:8421504,opacity:e.opacity?.value??t.opacity??1,transparent:!!t.transparent,wireframe:!!t.wireframe,side:t.side}),this.uniforms=e}},Yi=Gt,Xe=class extends ge{constructor(t=[],e=[],i=1,r=0){super();let s=Number(i)||1,a=Math.max(0,Math.min(7,Math.floor(Number(r)||0))),o=a+1,n=[],l=[],h=[],c=[],f=new ie,g=new ie,w=new ie,d=(b,x)=>x.set(t[b*3]||0,t[b*3+1]||0,t[b*3+2]||0),p=(b,x)=>{let u=b.clone().normalize();n.push(u.x*s,u.y*s,u.z*s),l.push(x.x,x.y,x.z),h.push(Math.atan2(u.z,-u.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,u.y)))/Math.PI)},A=(b,x,u)=>{let m=n.length/3,v=a===0?new ie().subVectors(u,x).cross(new ie().subVectors(b,x)).normalize():null;p(b,v||b.clone().normalize()),p(x,v||x.clone().normalize()),p(u,v||u.clone().normalize()),c.push(m,m+1,m+2)};for(let b=0;b<e.length;b+=3){d(e[b],f),d(e[b+1],g),d(e[b+2],w);let x=[];for(let u=0;u<=o;u++){x[u]=[];let m=f.clone().lerp(w,u/o),v=g.clone().lerp(w,u/o),S=o-u;for(let _=0;_<=S;_++)x[u][_]=S===0?m.clone():m.clone().lerp(v,_/S)}for(let u=0;u<o;u++)for(let m=0;m<2*(o-u)-1;m++){let v=m>>1;(m&1)===0?A(x[u][v+1],x[u+1][v],x[u][v]):A(x[u][v+1],x[u+1][v+1],x[u+1][v])}}this.setFromBuffers(n,l,h,c)}},kn=class extends Xe{constructor(t=1,e=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],t,e)}},Ct=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],qr=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],Fn=class extends Xe{constructor(t=1,e=0){super(Ct,qr,t,e)}},me=(1+Math.sqrt(5))/2,On=class extends Xe{constructor(t=1,e=0){super([-1,me,0,1,me,0,-1,-me,0,1,-me,0,0,-1,me,0,1,me,0,-1,-me,0,1,-me,me,0,-1,me,0,1,-me,0,-1,-me,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],t,e)}},Re=1/me,Un=class extends Xe{constructor(t=1,e=0){super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-Re,-me,0,-Re,me,0,Re,-me,0,Re,me,-Re,-me,0,-Re,me,0,Re,-me,0,Re,me,0,-me,0,-Re,me,0,-Re,-me,0,Re,me,0,Re],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],t,e)}},Bn=class extends Pt{constructor(t=1,e=1,i=4,r=8){let s=Math.max(1e-4,Number(t)||1),a=Math.max(0,Number.isFinite(Number(e))?Number(e):1)*.5,o=Math.max(2,Math.min(64,Math.floor(Number(i)||4))),n=[];for(let l=-1;l<=1;l+=2)for(let h=0;h<=o;h++){if(l>0&&h===0&&a===0)continue;let c=(l<0?h/o-1:h/o)*(Math.PI/2);n.push(new Ee(Math.max(0,Math.cos(c)*s),l*a+Math.sin(c)*s))}super(n,Math.max(4,Math.min(128,Math.floor(Number(r)||8))))}},Ht=class extends ge{constructor(t=.5,e=1,i=32,r=1,s=0,a=Math.PI*2){super();let o=Math.max(1e-4,Number(e)||1),n=Number(t),l=Number.isFinite(n)?Math.max(0,n):o*.5,h=Math.max(o,l),c=Math.min(h*.999,Math.min(o,l)),f=Math.max(3,Math.min(256,Math.floor(Number(i)||32))),g=Math.max(1,Math.min(64,Math.floor(Number(r)||1))),w=Number.isFinite(Number(s))?Number(s):0,d=Number.isFinite(Number(a))?Number(a):Math.PI*2,p=[],A=[],b=[],x=[];for(let u=0;u<=g;u++){let m=c+u/g*(h-c);for(let v=0;v<=f;v++){let S=w+v/f*d,_=Math.cos(S),D=Math.sin(S);if(p.push(m*_,m*D,0),A.push(0,0,1),b.push(m/h*_*.5+.5,m/h*D*.5+.5),u<g&&v<f){let P=u*(f+1)+v,N=P+f+1;m>1e-6&&x.push(P,N,P+1),x.push(N,N+1,P+1)}}}this.setFromBuffers(p,A,b,x)}},Vn=class extends Ht{constructor(t=1,e=32,i=0,r=Math.PI*2){super(0,t,e,1,i,r)}},Xt=class extends Te{constructor(t={}){super({roughness:.35,metalness:.1,side:2,...t});let e=Number(t.size);this.size=Number.isFinite(e)?Math.max(.002,Math.min(2,e)):.05,this.sizeAttenuation=t.sizeAttenuation!==!1,t.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35)}},lt=class extends Te{constructor(t={}){super({roughness:.4,metalness:.1,side:2,...t});let e=Number(t.linewidth);this.linewidth=Number.isFinite(e)?Math.max(.5,Math.min(20,e)):1,t.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.3)}},zn=class extends lt{constructor(t={}){super(t),this.dashSize=Number(t.dashSize)||3,this.gapSize=Number(t.gapSize)||1,this.scale=Number(t.scale)||1}};function Kr(t,e){let i=t?.attributes?.position;if(!i?.array||i.count<3)return new Float32Array(0);let r=i.array,s=t?.index?.array,a=Math.min(8192,Math.floor((s?s.length:i.count)/3)),o=g=>`${Math.round((r[g*3]||0)*1e4)},${Math.round((r[g*3+1]||0)*1e4)},${Math.round((r[g*3+2]||0)*1e4)}`,n=e===void 0,l=n?1:Math.cos(e*Math.PI/180),h={},c=[],f=(g,w)=>c.push(r[g*3]||0,r[g*3+1]||0,r[g*3+2]||0,r[w*3]||0,r[w*3+1]||0,r[w*3+2]||0);for(let g=0;g<a;g++){let w=s?s[g*3]:g*3,d=s?s[g*3+1]:g*3+1,p=s?s[g*3+2]:g*3+2,A=r[w*3]||0,b=r[w*3+1]||0,x=r[w*3+2]||0,u=(r[d*3]||0)-A,m=(r[d*3+1]||0)-b,v=(r[d*3+2]||0)-x,S=(r[p*3]||0)-A,_=(r[p*3+1]||0)-b,D=(r[p*3+2]||0)-x,P=m*D-v*_,N=v*S-u*D,E=u*_-m*S,F=Math.hypot(P,N,E);if(!n&&F<1e-8)continue;F>0&&(P/=F,N/=F,E/=F);let L=[w,d,p];for(let M=0;M<3;M++){let O=L[M],H=L[(M+1)%3],R=o(O),C=o(H);if(R===C)continue;let y=R<C?`${R}|${C}`:`${C}|${R}`,T=h[y];T?T.m||(T.m=1,T.nx*P+T.ny*N+T.nz*E<=l&&f(O,H)):(h[y]={va:O,vb:H,nx:P,ny:N,nz:E,m:n?1:0},n&&f(O,H))}}if(!n){let g=Object.keys(h);for(let w=0;w<g.length;w++){let d=h[g[w]];d&&!d.m&&f(d.va,d.vb)}}return new Float32Array(c)}var Gn=class extends ge{constructor(t){super(),this.setAttribute("position",new ve(Kr(t),3)),this.__isSegmentPairs=!0}},Hn=class extends ge{constructor(t,e=1){super();let i=Number.isFinite(Number(e))?Number(e):1;this.setAttribute("position",new ve(Kr(t,i),3)),this.__isSegmentPairs=!0}};function qi(t,e,i=1){let r=new ge;r.__baked=!0;let s=t?.attributes?.position;if(!s?.array||s.count<2)return r;let a=s.array,o=t.index?.array,n=t.__isSegmentPairs?"segments":e,l=o?o.length:s.count,h=Math.min(4096,Math.max(0,n==="segments"?Math.floor(l/2):n==="loop"&&l>=3?l:l-1));if(h===0)return r;t.computeBoundingBox();let c=t.boundingBox,f=c&&c.max.distanceTo(c.min)||1,g=Math.max(.0015,Math.min(.025,f*.003))*(.5+.5*Math.max(.5,Math.min(6,Number(i)||1))),w=[],d=[],p=[],A=[];for(let b=0;b<h;b++){let x=n==="segments"?b*2:b,u=n==="segments"?b*2+1:(b+1)%l,m=o?o[x]:x,v=o?o[u]:u,S=a[m*3]||0,_=a[m*3+1]||0,D=a[m*3+2]||0,P=(a[v*3]||0)-S,N=(a[v*3+1]||0)-_,E=(a[v*3+2]||0)-D,F=Math.hypot(P,N,E);if(F<1e-6)continue;let L=P/F,M=N/F,O=E/F,H=(Math.abs(M)<.9?Math.hypot(O,L):Math.hypot(O,M))||1,R=Math.abs(M)<.9?O/H:0,C=Math.abs(M)<.9?0:-O/H,y=Math.abs(M)<.9?-L/H:M/H,T=M*y-O*C,z=O*R-L*y,G=L*C-M*R,B=w.length/3,te=[[R,C,y],[T,z,G],[-R,-C,-y],[-T,-z,-G]];for(let I=0;I<2;I++){let W=S+I*P,Z=_+I*N,se=D+I*E;for(let U=0;U<4;U++){let ee=te[U];w.push(W+ee[0]*g,Z+ee[1]*g,se+ee[2]*g),d.push(ee[0],ee[1],ee[2]),p.push(U/4,I)}}for(let I=0;I<4;I++){let W=(I+1)%4;A.push(B+I,B+W,B+4+W,B+I,B+4+W,B+4+I)}}return w.length>0&&r.setFromBuffers(w,d,p,A),r}function Ki(t,e=.05){let i=new ge;i.__baked=!0;let r=t?.attributes?.position;if(!r?.array||r.count<1)return i;let s=r.array,a=r.count,o=Math.min(a,5e3),n=Math.max(.003,Math.min(.25,(Number(e)||.05)*.6)),l=[],h=[],c=[],f=[];for(let g=0;g<o;g++){let w=a<=5e3?g:Math.floor(g*a/o),d=s[w*3]||0,p=s[w*3+1]||0,A=s[w*3+2]||0,b=g*6;for(let x=0;x<6;x++){let u=Ct[x*3],m=Ct[x*3+1],v=Ct[x*3+2];l.push(d+u*n,p+m*n,A+v*n),h.push(u,m,v),c.push(.5,.5)}for(let x=0;x<24;x++)f.push(b+qr[x])}return i.setFromBuffers(l,h,c,f),i}var We=class extends Fe{constructor(t,e,i="strip"){let r=e&&typeof e=="object"?e:{},s=e instanceof Te?e:i==="points"?new Xt(r):new lt(r),a=t instanceof ge?t:new ge;super(a,s),this.isLine=!0,this._lineMode=i,this._sourceGeo=a}computeLineDistances(){return this}_bakeAuthorGeometry(){this.geometry&&!this.geometry.__baked&&(this._sourceGeo=this.geometry);let t=this._lineMode==="points";if(t){let e=this._sourceGeo?.attributes?.color;if(e?.array&&e.count>0&&this.material?.color.r===1&&this.material.color.g===1&&this.material.color.b===1){let i=e.array,r=Math.min(e.count,64),s=0,a=0,o=0;for(let n=0;n<r;n++)s+=i[n*3]||0,a+=i[n*3+1]||0,o+=i[n*3+2]||0;this.material.color.setRGB(s/r,a/r,o/r)}}!this.geometry?.__baked&&this._sourceGeo?.attributes?.position?.count>=(t?1:2)&&(this.geometry=t?Ki(this._sourceGeo,this.material?.size??.05):qi(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},Xn=class extends We{constructor(t,e){super(t,e,"loop"),this.isLineLoop=!0}},Wn=class extends We{constructor(t,e){super(t,e,"segments"),this.isLineSegments=!0}},$n=class extends We{constructor(t,e){super(t,e,"points"),this.isPoints=!0}},jn=class extends Ut{constructor(t,e,i=0,r=Math.PI/3,s=0,a=2){super(t,e,i,a),this.target=new De,this.type="spot";let o=Number(r);this.angle=Number.isFinite(o)?Math.max(.01,Math.min(Math.PI/2,o)):Math.PI/3;let n=Number(s);this.penumbra=Number.isFinite(n)?Math.max(0,Math.min(1,n)):0}},Wt=class extends Ot{constructor(t,e,i){et("HemisphereLight","AmbientLight"),super(t,i),this.groundColor=new Le(e??4473924)}},Zi=Wt,Zr={Vector2:Ee,Vector3:ie,Vector4:un,Euler:Dt,Quaternion:at,Matrix4:He,Matrix3:ln,Color:Le,MathUtils:Li,BufferAttribute:ve,Float32BufferAttribute:mn,Uint16BufferAttribute:hn,Uint32BufferAttribute:dn,BufferGeometry:ge,BoxGeometry:It,PlaneGeometry:fn,SphereGeometry:pn,CylinderGeometry:Nt,ConeGeometry:bn,TorusGeometry:gn,TorusKnotGeometry:yn,Curve:ze,Curve3:ze,LineCurve3:xn,QuadraticBezierCurve3:vn,CubicBezierCurve3:Mn,CatmullRomCurve3:wn,LatheGeometry:Pt,TubeGeometry:Sn,PolyhedronGeometry:Xe,IcosahedronGeometry:On,OctahedronGeometry:Fn,DodecahedronGeometry:Un,TetrahedronGeometry:kn,CapsuleGeometry:Bn,RingGeometry:Ht,CircleGeometry:Vn,WireframeGeometry:Gn,EdgesGeometry:Hn,FrontSide:0,BackSide:1,DoubleSide:2,NoBlending:0,NormalBlending:1,AdditiveBlending:2,MultiplyBlending:4,RepeatWrapping:1e3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002,NearestFilter:1003,NearestMipmapNearestFilter:1004,NearestMipmapLinearFilter:1005,LinearFilter:1006,LinearMipmapNearestFilter:1007,LinearMipmapLinearFilter:1008,UnsignedByteType:1009,ByteType:1010,ShortType:1011,UnsignedShortType:1012,IntType:1013,UnsignedIntType:1014,FloatType:1015,HalfFloatType:1016,AlphaFormat:1021,RGBFormat:1022,RGBAFormat:1023,LuminanceFormat:1024,LuminanceAlphaFormat:1025,RedFormat:1028,RGFormat:1030,NoColorSpace:"",SRGBColorSpace:"srgb",LinearSRGBColorSpace:"srgb-linear",StaticDrawUsage:35044,DynamicDrawUsage:35048,ACESFilmicToneMapping:4,PCFSoftShadowMap:2,Texture:ct,DataTexture:An,TextureLoader:Rn,Material:Te,MeshStandardMaterial:Je,MeshBasicMaterial:Tn,MeshLambertMaterial:En,MeshPhongMaterial:_n,MeshPhysicalMaterial:Cn,PointsMaterial:Xt,LineBasicMaterial:lt,LineDashedMaterial:zn,ShaderMaterial:Gt,RawShaderMaterial:Yi,Object3D:De,Group:Ln,Mesh:Fe,InstancedMesh:Ft,Line:We,LineLoop:Xn,LineSegments:Wn,Points:$n,Light:Qe,AmbientLight:Ot,DirectionalLight:Dn,PointLight:Ut,SpotLight:jn,HemisphereLight:Wt,RectAreaLight:Zi,Camera:Bt,PerspectiveCamera:In,Scene:Vt,WebGLRenderer:Nn,Clock:Pn,SceneQuotaValidator:ke,exportSceneToCanvas3D:zr,exportSceneToGLB:Gr,exportSceneToUSDZ:Di,generateUSDZ:Rt,glbToUSDZ:At,sceneToCanvas3D:it,sceneToGLB:wt,sceneToUSDZ:St,authorScriptRunner:qn,getAuthorWarnings:$i,clearAuthorWarnings:ji};Object.freeze(ke),Object.freeze(ke.prototype),Object.freeze(Vt.prototype),Object.freeze(Zr);var $e=new Proxy(Zr,{get:(t,e)=>{if(e in t)return t[e];let i=ue().authorNamespace;return i&&typeof e=="string"&&e in i?i[e]:(typeof e=="string"&&e!=="then"&&e!=="toJSON"&&!e.startsWith("__")&&et(`THREE.${e}`,"no-op proxy"),_t)},has:(t,e)=>{if(e in t)return!0;let i=ue().authorNamespace;return!!(i&&typeof e=="string"&&e in i)},set:(t,e)=>{throw new TypeError(`Cannot assign to read only property '${String(e)}' of #<THREE>`)},defineProperty:(t,e)=>{throw new TypeError(`Cannot define property '${String(e)}', object is not extensible`)},deleteProperty:(t,e)=>{throw new TypeError(`Cannot delete property '${String(e)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),Lt=ue();if(Lt.threeNamespace=$e,Lt.workerExtensionInstallers)for(let t of Lt.workerExtensionInstallers)t($e,Lt);var cn={name:"three_author",THREE:$e},Pe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof Pe.THREE>"u"&&(Pe.THREE=$e),typeof Pe.requestAnimationFrame!="function"&&(Pe.requestAnimationFrame=t=>(typeof t=="function"&&typeof Pe.__three_live_raf_cb__!="function"&&(Pe.__three_live_raf_cb__=t),Pe.__three_live_in_step__||et("requestAnimationFrame","single-frame static evaluation"),0)),typeof Pe.cancelAnimationFrame!="function"&&(Pe.cancelAnimationFrame=()=>{}),typeof window<"u"){let t=window;t.ThreeLive=t.ThreeLive||{},t.ThreeLive.THREE=$e,t.ThreeLivePlugins=t.ThreeLivePlugins||{},t.ThreeLivePlugins.threeAuthor=cn,t.ThreeLivePlugins.three_author=cn,t.ThreeLivePlugins["three-author"]=cn}function Kn(t,e){let i=t?.trim(),r=i?Number(i):NaN;return Number.isFinite(r)?r:e}var Zn=(t,e,i)=>({x:t,y:e,z:i,toString:()=>`${t}m ${e}m ${i}m`}),es=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(t,e){super(t,e),this.detail=e?.detail??null}});var be=class ye extends es{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.loadController=null,this.resizeObserver=null,this.mutationObserver=null}static get arProvider(){return ue().arProvider}static set arProvider(e){ue().arProvider=e}static get scriptRunner(){return ue().scriptRunner}static set scriptRunner(e){ue().scriptRunner=e}static get sandboxEngineSrc(){return ue().sandboxEngineSrc??null}static set sandboxEngineSrc(e){ue().sandboxEngineSrc=e}static get sandboxIframeSrc(){return ue().sandboxIframeSrc??null}static set sandboxIframeSrc(e){ue().sandboxIframeSrc=e}static get allowClientScripts(){return!!ue().allowClientScripts}static set allowClientScripts(e){ue().allowClientScripts=e}static registerScriptRunner(e){ye.scriptRunner=e}static defineModelViewer(e="model-viewer"){if(typeof customElements>"u")return!1;let i=customElements.get(e);if(i!=null)return i===ye||i.prototype instanceof ye;class r extends ye{}return customElements.define(e,r),!0}static registerDecoder(e,i){Me.registerDecoder(e,i)}static getDecoder(e){return Me.getDecoder(e)}static registerAR(e){typeof e=="function"?ye.arProvider={activateAR:e}:ye.arProvider=e,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof ye&&i.updateARButtonVisibility()})}static isARSupported(){return!!ye.arProvider}getLoadedModel(){return this.currentModel}beginLoad(){let e=this.loadController,i=this.scriptHandle,r=new AbortController;return this.loadController=r,this.scriptHandle=null,e?.abort(),i?.terminate(),r}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"),i=this.getAttribute("script-src");if(e)this.loadModel(e).catch(()=>{});else if(i)this.loadScriptFromSrc(i).catch(()=>{});else{let r=this.querySelector('script[type="text/three"], script[type="text/three-live"]');r&&r.textContent&&this.executeScript(r.textContent).catch(()=>{})}for(let r of Me.getRegisteredPlugins())r.onElementConnected?.(this)}disconnectedCallback(){for(let e of Me.getRegisteredPlugins())e.onElementDisconnected?.(this);this.beginLoad().abort(),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,this.viewer?.destroy(),this.viewer=null,this.isModelLoaded=!1}attributeChangedCallback(e,i,r){if(i!==r){switch(e){case"src":r&&this.loadModel(r).catch(()=>{});break;case"camera-target":this.applyCameraTarget(r);break;case"min-camera-orbit":case"max-camera-orbit":this.applyOrbitLimits();break;case"field-of-view":this.applyFieldOfView(r);break;case"script-src":r&&this.loadScriptFromSrc(r).catch(()=>{});break;case"sandbox":case"allow-client-scripts":case"ios-src":break;case"poster":this.updatePoster(r);break;case"camera-orbit":this.applyCameraOrbit(r);break;case"selected-mesh":this.viewer&&r!==null&&this.viewer.setSelectedMesh(r);break;case"exposure":if(this.viewer&&r!==null){let s=parseFloat(r);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?.setToneMapping(Ge(r));break;case"environment-image":this.viewer&&this.viewer.setEnvironmentImage(r).catch(()=>{});break;case"skybox-image":this.viewer&&this.viewer.setSkyboxImage?.(r)?.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(r!==null&&r!=="false");break;case"animation-name":this.viewer&&r!==null&&this.viewer.setAnimationName(r);break;case"variant-name":this.viewer&&this.selectVariant(r);break;case"auto-rotate":this.viewer&&this.viewer.setAutoRotate(r!==null&&r!=="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(r));break;case"ar":this.updateARButtonVisibility();break}for(let s of Me.getRegisteredPlugins())s.onAttributeChanged?.(this,e,i,r)}}getAttr(e){return this.getAttribute(e)}setAttr(e,i){i!==null?this.setAttribute(e,String(i)):this.removeAttribute(e)}getBoolAttr(e){return this.hasAttribute(e)&&this.getAttr(e)!=="false"}setBoolAttr(e,i){this.setAttr(e,i?"":null)}getFloatAttr(e,i){let r=this.getAttr(e);return r!==null?parseFloat(r):i}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.getAttr("sandbox")||(ue().sandboxIframeSrc?"iframe":"worker")}set sandbox(e){this.setAttr("sandbox",e)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||ye.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.setAttr("exposure",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.setAttr("auto-rotate-delay",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.getAttr("ar-scale")||"auto"}set arScale(e){this.setAttr("ar-scale",e)}get arPlacement(){return this.getAttr("ar-placement")||"floor"}set arPlacement(e){this.setAttr("ar-placement",e)}get canActivateAR(){return ye.isARSupported()}get shadowIntensity(){return this.getFloatAttr("shadow-intensity",0)}set shadowIntensity(e){this.setAttr("shadow-intensity",e)}get shadowSoftness(){return this.getFloatAttr("shadow-softness",.5)}set shadowSoftness(e){this.setAttr("shadow-softness",e)}get toneMapping(){return Ge(this.getAttr("tone-mapping"))}set toneMapping(e){this.setAttr("tone-mapping",e)}get bloom(){return this.getFloatAttr("bloom",0)}set bloom(e){this.setAttr("bloom",e)}get bloomThreshold(){return Kn(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(e){this.setAttr("bloom-threshold",e)}get bloomRadius(){return Kn(this.getAttr("bloom-radius"),.75)}set bloomRadius(e){this.setAttr("bloom-radius",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():[]}fireEvent(e,i){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:i}))}setSlotVisible(e,i){let r=typeof this.querySelector=="function"?this.querySelector(`[slot="${e}"]`):null;r&&(r.hidden=!i,r.style&&(r.style.display=i?"":"none"))}emitError(e,i="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:e}),this.fireEvent("three-error",{error:e,message:e?.message||String(e),stage:i})}selectVariant(e){if(!this.viewer)return!1;let i=this.viewer.selectVariant(e);return i&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),i}get model(){let e=this.viewer?this.viewer.getModelMaterials():[];return{materials:e,getMaterialByName(i){return e.find(r=>r.name===i)??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,i,r,s){this.viewer&&this.viewer.setCamera(e,i,r,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():Zn(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(e,i){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(e,i):""}toBlob(e){return this.viewer?.render?.(),new Promise((i,r)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){r(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(s=>{s?i(s):r(new Error("Failed to capture canvas blob."))},e?.mimeType,e?.qualityArgument)})}positionAndNormalFromPoint(e,i){let r=this.viewer?.raycastFromScreenPoint(e,i);if(!r)return null;let[s,a,o]=r.hitPoint||r.point,[n,l,h]=r.normal;return{position:Zn(s,a,o),normal:Zn(n,l,h)}}loadModel(e){return this.loadModelWithLimits(e)}async loadModelWithLimits(e,i,r=this.beginLoad()){if(r.signal.throwIfAborted(),!this.viewer){this.currentModel=e,this.currentModelLimits=i;return}try{let s;if(typeof e=="string"){let l=await fetch(e,{signal:r.signal});if(!l.ok)throw new Error(`Failed to load "${e}": HTTP ${l.status}`);s=await l.arrayBuffer()}else s=e;r.signal.throwIfAborted();let a=Ue(s);this.viewer.loadGLBData(a,i),this.currentModel=a,this.currentModelLimits=i,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let o=this.getAttr("selected-mesh");o&&this.viewer.setSelectedMesh(o);let n=this.getAttr("variant-name");n&&this.selectVariant(n),this.fireEvent("load",{model:a}),this.fireEvent("three-load",{model:a,source:typeof e=="string"?"src":"model"})}catch(s){throw r.signal.aborted||this.emitError(s,"load"),s}}showToast(e,i=4500){if(typeof document>"u")return;let r=this.querySelector(".three-live-toast");r||(r=document.createElement("div"),r.className="three-live-toast",r.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(r)),r.textContent=e,this.toastTimer&&clearTimeout(this.toastTimer);let s=()=>{r&&(r.style.opacity="1",r.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(s):s(),this.toastTimer=setTimeout(()=>{r&&(r.style.opacity="0",r.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},i)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let e=(s,a=s.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(a,6e3),s};this.currentModel||e(new Error("No 3D model is loaded in <three-live>.")),ye.arProvider||e(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let i=this.getAttr("ios-src"),r=(this.getAttr("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let s=await ye.arProvider.activateAR({model:i||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.fireEvent("ar-status",{status:"not-presenting"})},onError:a=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:a}),this.showToast(`AR error: ${a.message}`,6e3)}}});if(s.success){s.session&&(this.activeXRSession=s.session);let a=s.mode==="quick-look"?"Opening Apple AR Quick Look...":s.mode==="scene-viewer"?"Opening Google Scene Viewer...":s.mode==="webxr"?"WebXR AR session started.":"";a&&this.showToast(a)}else{let a=s.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(this.isDesktopMac()&&typeof document<"u"&&this.currentModel&&ye.arProvider.createUSDZBlob)try{let o=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:ye.arProvider.createUSDZBlob(this.currentModel),n=URL.createObjectURL(o),l=document.createElement("a");l.href=n,l.download="three_live_model.usdz",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(n),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(a,6e3)}else this.showToast(a,6e3);s.error&&this.fireEvent("ar-status",{status:"failed",error:s.error})}return s}catch(s){return this.activeXRSession=null,e(s,`AR error: ${s.message||String(s)}`)}}setupDOM(){let e=this.querySelector("canvas");e||(e=document.createElement("canvas"),e.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(e)),this.canvas=e,typeof e.addEventListener=="function"&&!e.__tlCtxBound&&(e.__tlCtxBound=!0,e.addEventListener("webglcontextlost",r=>this.fireEvent("three-context-lost",{originalEvent:r})),e.addEventListener("webglcontextrestored",r=>this.fireEvent("three-context-restored",{originalEvent:r}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);let i=this.getAttr("poster");i&&this.updatePoster(i),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,i=this.exposure,r=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),s=this.parseOrbitLimit(this.getAttr("max-camera-orbit")),a=this.parseCameraTarget(this.getAttr("camera-target")),o=this.parseFieldOfView(this.getAttr("field-of-view"));this.viewer=new Me(this,this.canvas,{autoRotate:e,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttr("rotation-per-second")),exposure:i,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttr("variant-name")||void 0,fieldOfView:o,cameraTarget:a,minCameraOrbit:r,maxCameraOrbit:s,onMeshClick:l=>{this.fireEvent("meshclick",l)},onCameraChange:l=>{this.updateHotspots();for(let h of Me.getRegisteredPlugins())h.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",l)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let n=this.getAttr("camera-orbit");n&&this.applyCameraOrbit(n),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.alt="3D Scene Preview",this.posterEl.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=e,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}isDesktopMac(){let e=typeof navigator<"u"&&navigator.userAgent||"";return/Macintosh/i.test(e)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1)&&!/Android|iPhone|iPad|iPod/i.test(e)}syncARButtonLabel(e){let i=this.isDesktopMac(),r=i?"Quick Look (.usdz)":"View in AR",s=i?"Download .usdz preview for macOS Quick Look (live camera AR requires iOS or Android)":"View in Augmented Reality";typeof e.setAttribute=="function"&&(e.setAttribute("aria-label",s),e.setAttribute("title",s));let a=e._labelSpan||(typeof e.querySelector=="function"?e.querySelector("span"):null);a&&(a.textContent=r)}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let e=document.createElement("button");e.type="button",e.className="three-live-ar-button",e.setAttribute("part","default-ar-button");let i="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let s=document.createElementNS(i,"svg");for(let[o,n]of[["width","20"],["height","20"],["viewBox","0 0 24 24"],["fill","none"],["stroke","currentColor"],["stroke-width","2"],["stroke-linecap","round"],["stroke-linejoin","round"]])s.setAttribute(o,n);s.style.marginRight="6px";let a=document.createElementNS(i,"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 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),s.appendChild(a),e.appendChild(s)}let r=document.createElement("span");e._labelSpan=r,e.appendChild(r),this.syncARButtonLabel(e),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")&&!!ye.arProvider,i=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;i?(this.arButton&&(this.arButton.style.display="none"),i.__tlARBound||(i.__tlARBound=!0,i.addEventListener("click",r=>{r.stopPropagation(),this.activateAR()})),i.dataset.tlOrigDisplay===void 0&&(i.dataset.tlOrigDisplay=i.style.display==="none"?"":i.style.display),i.style.display=e?i.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.syncARButtonLabel(this.arButton),this.arButton.style.display=e?"flex":"none")}applyCameraOrbit(e){if(!(!e||!this.viewer))try{let i=JSON.parse(e);this.viewer.setInitialCamera(i.theta,i.phi,i.distance,i.zoom)}catch{let i=this.parseOrbitLimit(e);(i.theta!==void 0||i.phi!==void 0)&&this.viewer.setInitialCamera(i.theta,i.phi,i.distance)}}parseOrbitLimit(e){if(!e)return{};let[i,r,s]=e.trim().split(/\s+/),a=s&&s!=="auto"?parseFloat(s):NaN;return{theta:i&&i!=="auto"?this.parseFieldOfView(i):void 0,phi:r&&r!=="auto"?this.parseFieldOfView(r):void 0,distance:isNaN(a)?void 0:a}}applyOrbitLimits(){if(!this.viewer)return;let e=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),i=this.parseOrbitLimit(this.getAttr("max-camera-orbit"));this.viewer.setOrbitLimits({minTheta:e.theta,maxTheta:i.theta,minPhi:e.phi,maxPhi:i.phi,minDistance:e.distance,maxDistance:i.distance})}parseCameraTarget(e){if(!e)return;let i=e.trim().split(/\s+/).map(parseFloat);return i.length>=3&&!i.some(isNaN)?[i[0],i[1],i[2]]:void 0}parseFieldOfView(e){if(!e)return;let i=parseFloat(e);return isNaN(i)?void 0:e.endsWith("rad")?i*180/Math.PI:i}parseRotationPerSecond(e){if(!e)return Math.PI/6;let i=e.trim(),r=parseFloat(i);return isNaN(r)?Math.PI/6:i.endsWith("rad")?r:i.endsWith("%")?r/100*Math.PI*2:r*Math.PI/180}applyCameraTarget(e){let i=this.parseCameraTarget(e);this.viewer&&i&&this.viewer.setTarget(i[0],i[1],i[2])}applyFieldOfView(e){let i=this.parseFieldOfView(e);this.viewer&&i!==void 0&&this.viewer.setFieldOfView(i)}updateHotspot(e){let i=this.querySelector(`[slot="${e.name}"]`);i&&(e.position!==void 0&&i.setAttribute("data-position",e.position),e.normal!==void 0&&i.setAttribute("data-normal",e.normal)),this.updateHotspots()}updateHotspots(){for(let e of Me.getRegisteredPlugins())if(e.updateHotspotsForElement){e.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(e){let i=ye.scriptRunner;if(!i){let a=new Error('Script execution requires "three-live/full" or registerScriptRunner().');return this.showToast(a.message),this.emitError(a,"script"),Promise.reject(a)}let r=this.beginLoad(),s=()=>!r.signal.aborted;return new Promise((a,o)=>{let n=()=>o(r.signal.reason);if(r.signal.addEventListener("abort",n,{once:!0}),!s()){n();return}let l={onModelReady:h=>{this.loadModelWithLimits(h,xr,r).then(()=>a(h),o)},onUpdateTransforms:h=>{s()&&this.viewer?.updateMeshTransforms(h)},onError:h=>{s()&&(this.showToast(h.message),this.emitError(h,"script"),o(h))},onToast:h=>{s()&&this.showToast(h)}};e(i,l).then(h=>{s()?this.scriptHandle=h||null:h?.terminate()},h=>{s()&&l.onError?.(h)})})}loadScriptFromSrc(e){return this.runWithScriptRunner((i,r)=>{if(typeof i.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return r.onError?.(s),Promise.reject(s)}return i.executeUrl(e,this.sandbox,r)})}executeScript(e){if(!ye.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let i=new Error(dt);return this.showToast(ft),this.emitError(i,"security"),Promise.reject(i)}return this.runWithScriptRunner((i,r)=>i.execute(e,this.sandbox,r,{allowClientScripts:!0}))}};be.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"],be.registerPlugin=Me.registerPlugin,be.getRegisteredPlugins=Me.getRegisteredPlugins;var Oe=be;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",Oe);function Jr(t="model-viewer"){return Oe.defineModelViewer(t)}function Qn(){if(typeof window>"u"||typeof navigator>"u")return!1;let t=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(t)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let e=document.createElement("a");return e.relList!==void 0&&e.relList.supports!==void 0&&e.relList.supports("ar")}function er(){if(typeof navigator>"u")return!1;let t=navigator.userAgent||"";return/android/i.test(t)}async function tr(){if(typeof navigator>"u")return!1;let t=navigator;if(!t.xr||typeof t.xr.isSessionSupported!="function")return!1;try{return await t.xr.isSessionSupported("immersive-ar")?!0:await t.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function ti(){return(await Yt()).bestMode}async function Yt(){let[t,e,i]=await Promise.all([tr(),Promise.resolve(Qn()),Promise.resolve(er())]),r=[];e&&r.push("quick-look"),t&&r.push("webxr"),i&&r.push("scene-viewer");let s=null;return e?s="quick-look":t?s="webxr":i&&(s="scene-viewer"),{webxr:t,quickLook:e,sceneViewer:i,availableModes:r,bestMode:s}}function Qr(t,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let i,r=!1;if(typeof t=="string"){if(i=ts(t),!i)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else i=URL.createObjectURL(t),r=!0;let s=[];if(e.allowScale===!1&&s.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let n=jt(e.canonicalWebPageUrl,!1);n&&s.push(`canonicalWebPageURL=${encodeURIComponent(n)}`)}e.checkoutTitle&&s.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&s.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&s.push(`price=${encodeURIComponent(e.price)}`),s.length>0&&(i+=`#${s.join("&")}`);let a=document.createElement("a");a.setAttribute("rel","ar"),a.setAttribute("href",i);let o=document.createElement("img");o.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),o.style.display="none",a.appendChild(o),document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),r&&URL.revokeObjectURL(i.split("#")[0])},3e3)}function jt(t,e=!1){if(typeof t!="string")return"";let i=t.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!i)return"";if(/^[\\/]{2}/.test(i))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${i.slice(0,32)}`);let r=i.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||e&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(i))return i;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${i.slice(0,32)}`)}function ts(t){try{return jt(t,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(t||"").trim().slice(0,32)}`)}}function ns(t,e={}){let i=jt(t,!0),r=e.mode||"ar_preferred",s=new URLSearchParams({file:i,mode:r,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&s.set("title",e.title),e.link&&s.set("link",jt(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${s.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function rs(t,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let i=ns(t,e);window.location.href=i}var je=null;function is(t,e){let i=new Float32Array(144),r=new Float32Array(144),s=new Float32Array(96),a=new Uint16Array(144);for(let c=0;c<24;c++){let f=c/24*Math.PI*2,g=Math.cos(f),w=Math.sin(f),d=c*2,p=d+1,A=(c+1)%24*2;i[d*3]=g*.11,i[d*3+1]=.002,i[d*3+2]=w*.11,i[p*3]=g*.145,i[p*3+1]=.002,i[p*3+2]=w*.145,r[d*3+1]=r[p*3+1]=1,a.set([d,A,p,p,A,A+1],c*6)}let o=t.createVertexArray();t.bindVertexArray(o);let n=(c,f,g)=>{let w=t.createBuffer();return t.bindBuffer(34962,w),t.bufferData(34962,c,35044),t.enableVertexAttribArray(f),t.vertexAttribPointer(f,g,5126,!1,0,0),w},l=[n(i,0,3),n(r,1,3),n(s,2,2)],h=t.createBuffer();return l.push(h),t.bindBuffer(34963,h),t.bufferData(34963,a,35044),t.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:o,indexCount:a.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:i,indices:a,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:l}]}}function ei(t,e,i,r,s){let a=Math.cos(r),o=Math.sin(r),n=Math.max(.01,s);t.fill(0),t[0]=n*a,t[2]=-n*o,t[5]=n,t[8]=n*o,t[10]=n*a,t[12]=e[0]-n*(a*i[0]+o*i[2]),t[13]=e[1]-n*i[1],t[14]=e[2]-n*(-o*i[0]+a*i[2]),t[15]=1}var Jn=class{constructor(t={}){this.s=null,this.placed=!1,this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.cleanFn=null,this.opts=t}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(t,e){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");je&&je!==this&&je.isSessionActive()&&await je.stop().catch(()=>{});let i=navigator.xr,r=this.opts,s=e||t?.container,a=String(s?.tagName||"").toLowerCase()==="xr-live",o=t?.bounds,n=Number(o?.radius)||1,l=Array.isArray(o?.center)?o.center:[0,0,0],h=Array.isArray(o?.min)?o.min:[-.5,-.5,-.5],c=typeof navigator<"u"&&navigator.userAgent||"",f=/Android|iPhone|iPad|iPod/i.test(c)&&!/Quest|Oculus|Pico|Vision/i.test(c),g=a?r.arScale==="fixed"?1:f?.55:1:r.arScale==="fixed"?1:n>.45?.3/n:n<.05?.12/Math.max(n,.001):1,w=a?[0,-.25,0]:[l[0]||0,r.arPlacement==="wall"?l[1]:h[1]??0,l[2]||0],d="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(d="immersive-vr")}catch{d="immersive-vr"}let p=s?.querySelector?.('[slot="ar-overlay"]')||null,A=!1,b=null,x=()=>{A&&p?.parentNode&&p.parentNode.removeChild(p),p=null,b=null,A=!1};if(d==="immersive-ar"){if(p)p.addEventListener?.("beforexrselect",I=>I.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let I=document.createElement("div");I.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let W=document.createElement("button");W.type="button",W.textContent="\u2715 Exit AR",W.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",W.addEventListener("beforexrselect",Z=>Z.preventDefault()),W.addEventListener("click",Z=>{Z.stopPropagation(),this.stop().catch(()=>{})}),b=document.createElement("div"),b.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",b.textContent="Move phone to detect a surface \u2022 Tap to place",I.appendChild(W),I.appendChild(b),document.body.appendChild(I),p=I,A=!0}}let u=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),m={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(u)};p&&(u.add("dom-overlay"),m.optionalFeatures=Array.from(u),m.domOverlay={root:p});for(let I of he)I.onConfigureXRSessionInit?.(s,m);Array.isArray(m.optionalFeatures)&&m.optionalFeatures.includes("dom-overlay")&&!m.domOverlay?.root&&(m.optionalFeatures=m.optionalFeatures.filter(I=>I!=="dom-overlay"));let v=I=>{let W=String(I?.name||"");return W==="NotAllowedError"||W==="SecurityError"};try{this.s=await i.requestSession(d,m)}catch(I){if(x(),v(I))throw r.onError?.(I),I;try{this.s=await i.requestSession(d,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(W){if(v(W))throw r.onError?.(W),W;try{this.s=await i.requestSession(d)}catch(Z){throw r.onError?.(Z),Z}}}let S=this.s;je=this,this.placed=!1;let _=null,D=null,P=null,N=null,E=null,F=[0,-.25,-1.2],L=[0,-.25,-1.2],M=new Float32Array(16),O=new Float32Array(16),H=!1,R=1,C=0,y=!1,T=null,z=null,G=0,B=null,te=()=>{je===this&&(je=null),B?.(),B=null;try{D?.cancel?.()}catch{}if(D=null,P){let I=t?.meshes;if(Array.isArray(I)){let Z=I.indexOf(P);Z!==-1&&I.splice(Z,1)}let W=t.getGLContext?.()||t?.gl;if(W)for(let Z of P.primitives||[]){W.deleteVertexArray?.(Z.vao);for(let se of Z.buffers||[])W.deleteBuffer?.(se)}P=null}t?.setXRSessionActive?.(!1),x(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=te,S.addEventListener("end",()=>{te(),r.onExit?.()}),S.addEventListener("select",()=>{if(!this.placed){let I=E||F;L=[I[0],I[1],I[2]],ei(this.placedMat,L,w,C,g*R),this.placed=!0,P&&(P.visible=!1),b&&(b.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let I=t.getGLContext?.()||t?.gl;I&&typeof I.makeXRCompatible=="function"&&await I.makeXRCompatible();let W=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;I&&typeof W=="function"&&typeof S.updateRenderState=="function"&&S.updateRenderState({baseLayer:new W(S,I,{alpha:!0})});try{_=await S.requestReferenceSpace("local")}catch{try{_=await S.requestReferenceSpace("local-floor")}catch{_=await S.requestReferenceSpace("viewer")}}let Z=await S.requestReferenceSpace("viewer").catch(()=>_);if(typeof S.requestHitTestSource=="function"&&Z&&(D=await S.requestHitTestSource({space:Z}).catch(()=>null)),d==="immersive-ar"&&I&&typeof I.createVertexArray=="function"&&Array.isArray(t.meshes)&&(P=is(I,r.reticleColor),t.meshes.push(P)),typeof window<"u"&&typeof window.addEventListener=="function"){let U=k=>Math.hypot(k.touches[1].clientX-k.touches[0].clientX,k.touches[1].clientY-k.touches[0].clientY),ee=k=>Math.atan2(k.touches[1].clientY-k.touches[0].clientY,k.touches[1].clientX-k.touches[0].clientX),$=k=>{this.s&&(k.touches.length===1&&this.placed?y=!0:k.touches.length>=2&&(y=!1,T=U(k),z=ee(k)))},q=k=>{if(!this.s||k.touches.length<2)return;let V=U(k),j=ee(k);if(T&&T>4&&r.arScale!=="fixed"&&(R=Math.max(.15,Math.min(6,R*(V/T)))),z!==null){let K=j-z;K>Math.PI&&(K-=Math.PI*2),K<-Math.PI&&(K+=Math.PI*2),C-=K}T=V,z=j},X=k=>{(!k.touches||k.touches.length===0)&&(y=!1),(!k.touches||k.touches.length<2)&&(T=null,z=null)};window.addEventListener("touchstart",$,{passive:!0}),window.addEventListener("touchmove",q,{passive:!0}),window.addEventListener("touchend",X,{passive:!0}),window.addEventListener("touchcancel",X,{passive:!0}),B=()=>{window.removeEventListener("touchstart",$),window.removeEventListener("touchmove",q),window.removeEventListener("touchend",X),window.removeEventListener("touchcancel",X)}}t.setXRSessionActive?.(!0);let se=(U,ee)=>{if(this.s!==S)return;S.requestAnimationFrame(se);let $=G>0?Math.min(Math.max((U-G)/1e3,0),.1):1/60;G=U,t?.stepXRUpdate?.($);let q=ee.getViewerPose(_);if(!q)return;let X=q.views?.[0];if(!H&&X?.transform){let J=X.transform.position,Y=X.transform.matrix,ce=J?.x??(Y?Y[12]:0),re=J?.y??(Y?Y[13]:0),ae=J?.z??(Y?Y[14]:0),ne=Y?-Y[8]:0,le=Y?-Y[10]:-1,Se=Math.hypot(ne,le);Se>1e-4?(ne/=Se,le/=Se):(ne=0,le=-1),F=[ce+ne*1.2,re-.25,ae+le*1.2],C=Math.atan2(-ne,-le),H=!0}if(D&&typeof ee.getHitTestResults=="function"&&(!this.placed||y)){let J=ee.getHitTestResults(D)||[],Y=!1;for(let ce of J){let re=ce.getPose(_);if(re?.transform?.matrix){let ae=re.transform.matrix,ne=ae[5];if(r.arPlacement==="wall"&&Math.abs(ne)>.35||r.arPlacement==="floor"&&Math.abs(ne)<.65)continue;N||(N=new Float32Array(16)),N.set(ae),E=[ae[12],ae[13],ae[14]],this.placed&&y&&(L=[ae[12],ae[13],ae[14]]),P&&(P.visible=!this.placed||y,P.transform.set(ae)),!this.placed&&b&&(b.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(N),Y=!0;break}}!Y&&P&&(P.visible=!1)}ei(M,this.placed?L:E||F,w,C,g*R),this.placed&&this.placedMat.set(M);let k=t.xrRigMatrix;k instanceof Float32Array&&k.length===16?pe(O,k,M):O.set(M),t.modelRootMatrix&&t.modelRootMatrix.set(O);for(let J of he)J.onXRFrame?.(t,S,ee,_);let V=t.getGLContext?.()||t?.gl,j=S.renderState?.baseLayer;V&&j&&j.framebuffer!==void 0&&V.bindFramebuffer(36160,j.framebuffer);let K=d==="immersive-ar",Q=q.views||[];for(let J=0;J<Q.length;J++){let Y=Q[J];if(typeof t.renderXRView=="function"){let ce;if(j&&typeof j.getViewport=="function"){let re=j.getViewport(Y);re&&re.width>0&&re.height>0&&(ce=[re.x,re.y,re.width,re.height])}else j?.framebufferWidth>0&&j?.framebufferHeight>0&&(ce=[0,0,j.framebufferWidth,j.framebufferHeight]);t.renderXRView(Y,O,this.placed,ce,K,J)}}V&&j&&j.framebuffer&&V.bindFramebuffer(36160,null)};S.requestAnimationFrame(se)}catch(I){throw typeof S.end=="function"&&await S.end().catch(()=>{}),te(),r.onError?.(I),I}}async stop(){let t=this.s;if(t)try{await t.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function qt(t){let e=await Yt(),i=t.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let n of i)if(e.availableModes.includes(n)){r=n;break}if(r||(r=e.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let s={...t.quickLookOptions,allowScale:t.arScale==="fixed"?!1:t.quickLookOptions?.allowScale},a={...t.sceneViewerOptions,resizable:t.arScale==="fixed"?!1:t.sceneViewerOptions?.resizable,enableVerticalPlacement:t.arPlacement==="wall"?!0:t.sceneViewerOptions?.enableVerticalPlacement},o={...t.webXROptions,arScale:t.arScale||t.webXROptions?.arScale,arPlacement:t.arPlacement||t.webXROptions?.arPlacement};try{if(r==="quick-look"){let n;if(t.model instanceof Blob&&t.model.type==="model/vnd.usdz+zip")n=t.model;else{if(typeof t.model=="string")return Qr(t.model,s),{mode:"quick-look",success:!0};n=Ze(t.model)}return Qr(n,s),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let n=t.glbUrl||(typeof t.model=="string"?t.model:null);if(!n)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return rs(n,a),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!t.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let n=new Jn(o);return await n.start(t.view,t.element),{mode:"webxr",success:!0,session:n}}}catch(n){return{mode:r,success:!1,error:n}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}Oe.registerAR({activateAR:qt,createUSDZBlob:Ze}),Oe.registerScriptRunner(qn),ht(ir);
|
|
362
|
+
})();`);c=null;let E=D(u,R,A,T);E&&typeof E.toGLB=="function"&&(R=E)}if(!w){u.SceneQuotaValidator&&u.SceneQuotaValidator.validate(R);let D=R.toGLB(),E=D instanceof ArrayBuffer?D:D.buffer.slice(D.byteOffset,D.byteOffset+D.byteLength);M({type:"3D_MODEL_READY",glbBuffer:E},[E])}h({type:"DONE",nonce:n})}catch(R){b(R&&R.message||R)}},h({type:"READY",nonce:n})}function ai(t,e,i){let r=i?.allowedScriptUrl??null,n=i?.allowClientScripts??r===null,s={nonce:e,engineSrc:t,allowedScriptUrl:r,allowClientScripts:n,revoked:is},a=(ue().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${ss.toString()})(${JSON.stringify(s)},[${a}],(${bn.toString()}));`}function ci(t){t.onError?.(new Error("SecurityError: Sandboxed script exceeded SECURITY_3D_SANDBOX_TIMEOUT_MS (3000 ms) and was terminated.")),t.onToast?.("Security Error: script timed out and was stopped.")}var je=0;function ui(){try{let t=new Uint32Array(4);return globalThis.crypto?.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(8,"0")).join("")}catch{return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}}function os(t){try{return new TextEncoder().encode(t).length}catch{return t.length}}var as=1024,cs=256;function Jr(t){if(!Array.isArray(t)&&!(t instanceof Float32Array)||t.length!==16)return!1;for(let e=0;e<16;e++){let i=t[e];if(typeof i!="number"||!Number.isFinite(i))return!1}return!0}function li(t,e){if(!t||typeof t!="object")return null;let i=t;if(i.nonce!==e)return null;switch(i.type){case"READY":return{type:"READY"};case"DONE":return{type:"DONE"};case"ERROR":return{type:"ERROR",message:(typeof i.message=="string"?i.message:String(i.message??"Unknown worker error")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").slice(0,as)};case"3D_UPDATE_TRANSFORMS":{let r=i.transforms;if(Array.isArray(r)){if(r.length>1e3)return null;for(let n of r)if(!Jr(n))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:r}}if(r&&typeof r=="object"){let n=Object.keys(r);if(n.length>1e3)return null;let s=Object.create(null),a=r;for(let o of n){if(o.length>cs||o==="__proto__"||o==="constructor"||o==="prototype")return null;let l=a[o];if(!Jr(l))return null;s[o]=l}return{type:"3D_UPDATE_TRANSFORMS",transforms:s}}return null}case"3D_MODEL_READY":{let r=i.glbBuffer;return!(r instanceof ArrayBuffer)||r.byteLength>16777216?null:{type:"3D_MODEL_READY",payload:r}}default:return null}}function us(t){let e=os(t);if(e>1048576)throw new Error(`SecurityError: Script length (${e} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function mi(t,e,i,r){switch(t.type){case"READY":return;case"3D_UPDATE_TRANSFORMS":e.onUpdateTransforms?.(t.transforms);return;case"3D_MODEL_READY":if(r.modelDispatched)return;r.modelDispatched=!0,e.onModelReady(t.payload);return;case"DONE":i();return;case"ERROR":i(),e.onError?.(new Error(`Worker script error: ${t.message}`));return;default:return t}}function ls(t,e,i,r){let n=ui(),s=ai(e,n,t.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:t.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),a=document.createElement("iframe");a.setAttribute("sandbox","allow-scripts"),a.setAttribute("aria-hidden","true"),a.tabIndex=-1,a.style.display="none",a.src=i,je++;let o=!1,l=!1,m={modelDispatched:!1},p,v=()=>{if(o||l)return;let g=a.contentWindow;!g||typeof g.postMessage!="function"||(l=!0,g.postMessage(t.kind==="url"?{type:"SANDBOX_RUN",nonce:n,workerSource:s,scriptUrl:t.scriptUrl,texturePack:t.texturePack??null}:{type:"SANDBOX_RUN",nonce:n,workerSource:s,script:t.script,texturePack:t.texturePack??null},"*"))},h=()=>{},b=g=>{if(o||!a.contentWindow||g.source!==a.contentWindow)return;let c=g.data;if(c&&typeof c=="object"&&c.type==="IFRAME_READY"){v();return}let u=li(c,n);u&&mi(u,r,h,m)};h=()=>{o||(o=!0,p!==void 0&&clearTimeout(p),je=Math.max(0,je-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",b),typeof a.remove=="function"?a.remove():a.parentNode&&a.parentNode.removeChild(a))},p=setTimeout(()=>{o||(h(),ci(r))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",b),a.onload=()=>{v()},a.onerror=()=>{h(),r.onError?.(new Error(`Sandbox iframe failed to load "${i}". Verify that three-live-sandbox.html is served at that URL.`))};let x=document.body||document.documentElement;if(!x||typeof x.appendChild!="function"){h();let g=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw r.onError?.(g),g}return x.appendChild(a),{terminate:h}}function Qr(t,e,i,r){if(e==="worker"&&typeof Worker>"u")return r("SecurityError: Web Workers are unavailable for sandboxed execution.","Security Error: Web Workers unavailable.");if(e==="iframe"&&(typeof document>"u"||typeof document.createElement!="function"))return r("SecurityError: DOM unavailable for iframe sandbox execution.","Security Error: DOM unavailable for iframe sandbox.");if(je>=32)return r(`SecurityError: ${je} workers running, meeting SECURITY_3D_MAX_CONCURRENT_TASKS (32).`,"Security Error: too many concurrent sandboxed scripts.");let n;try{n=Qi()}catch(h){let b=h instanceof Error?h.message:String(h);return r(b,"Security Error: sandbox engine URL is not configured.")}if(e==="iframe"){let h;try{h=ts()}catch(b){let x=b instanceof Error?b.message:String(b);return r(x,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(ls(t,n,h,i))}catch(b){return Promise.reject(b)}}let s=ui(),a=ai(n,s,t.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:t.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),o;try{let h=new Blob([a],{type:"application/javascript"}),b=URL.createObjectURL(h);try{let x=Ji(b);o=new Worker(x)}finally{URL.revokeObjectURL(b)}}catch(h){let b=h instanceof Error?h.message:String(h);return r(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${b}`,"Security Error: Failed to start Worker sandbox.")}je++;let l=!1,m={modelDispatched:!1},p,v=()=>{l||(l=!0,p!==void 0&&clearTimeout(p),je=Math.max(0,je-1),o.terminate())};return p=setTimeout(()=>{l||(v(),ci(i))},3e3),o.onmessage=h=>{let b=li(h.data,s);b&&mi(b,i,v,m)},o.onerror=h=>{v(),i.onError?.(new Error(`Worker execution error: ${h.message}`))},t.kind==="url"?o.postMessage({type:"EXECUTE_URL",scriptUrl:t.scriptUrl,nonce:s,texturePack:t.texturePack??null}):o.postMessage({type:"EXECUTE",script:t.script,nonce:s,texturePack:t.texturePack??null}),Promise.resolve({terminate:v})}function ei(t,e){return t!=="worker"&&t!=="iframe"?e(`SecurityError: Unsupported sandbox="${t}"; require "worker" or "iframe".`,`Security Error: sandbox="${t}" is not permitted.`):null}var ti=t=>(e,i)=>{let r=new Error(e);return t.onError?.(r),i&&t.onToast?.(i),Promise.reject(r)},pr={execute(t,e,i,r){let n=ti(i),s=ei(e,n);if(s)return s;try{us(t)}catch(a){let o=a instanceof Error?a.message:String(a);return n(o,"Security Error: script exceeds the size limit.")}return r?.allowClientScripts??ns()?Qr({kind:"script",script:t,texturePack:r?.texturePack},e,i,n):n(Mt,At)},executeUrl(t,e,i,r){let n=ti(i),s=ei(e,n);if(s)return s;let a;try{a=rs(t)}catch(o){let l=o instanceof Error?o.message:String(o);return n(l,"Security Error: disallowed scene script URL.")}return Qr({kind:"url",scriptUrl:a,texturePack:r?.texturePack},e,i,n)}},Zt=new Set;function Je(t,e){let i=`[three-live] ${t} is unsupported; degraded to ${e}.`;Zt.has(i)||(Zt.add(i),typeof console<"u"&&typeof console.warn=="function"&&console.warn(i))}function ms(){return Array.from(Zt)}function hs(){Zt.clear()}var Jt=class extends it{constructor(t={}){Je("ShaderMaterial","MeshStandardMaterial");let e=t.uniforms||{},i=e.color?.value??e.uColor?.value??e.diffuse?.value??t.color;super({color:i!==void 0?i:8421504,opacity:e.opacity?.value??t.opacity??1,transparent:!!t.transparent,wireframe:!!t.wireframe,side:t.side}),this.uniforms=e}},ds=Jt,Qe=class extends Me{constructor(t=[],e=[],i=1,r=0){super();let n=Number(i)||1,s=Math.max(0,Math.min(7,Math.floor(Number(r)||0))),a=s+1,o=[],l=[],m=[],p=[],v=new ie,h=new ie,b=new ie,x=(u,y)=>y.set(t[u*3]||0,t[u*3+1]||0,t[u*3+2]||0),g=(u,y)=>{let f=u.clone().normalize();o.push(f.x*n,f.y*n,f.z*n),l.push(y.x,y.y,y.z),m.push(Math.atan2(f.z,-f.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,f.y)))/Math.PI)},c=(u,y,f)=>{let w=o.length/3,M=s===0?new ie().subVectors(f,y).cross(new ie().subVectors(u,y)).normalize():null;g(u,M||u.clone().normalize()),g(y,M||y.clone().normalize()),g(f,M||f.clone().normalize()),p.push(w,w+1,w+2)};for(let u=0;u<e.length;u+=3){x(e[u],v),x(e[u+1],h),x(e[u+2],b);let y=[];for(let f=0;f<=a;f++){y[f]=[];let w=v.clone().lerp(b,f/a),M=h.clone().lerp(b,f/a),S=a-f;for(let L=0;L<=S;L++)y[f][L]=S===0?w.clone():w.clone().lerp(M,L/S)}for(let f=0;f<a;f++)for(let w=0;w<2*(a-f)-1;w++){let M=w>>1;(w&1)===0?c(y[f][M+1],y[f+1][M],y[f][M]):c(y[f][M+1],y[f+1][M+1],y[f+1][M])}}this.setFromBuffers(o,l,m,p)}},er=class extends Qe{constructor(t=1,e=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],t,e)}},br=t=>Array.from(t,e=>parseInt(e,36)),Ot=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],hi=br("024043035052125153134142"),tr=class extends Qe{constructor(t=1,e=0){super(Ot,hi,t,e)}},ye=(1+Math.sqrt(5))/2,nr=class extends Qe{constructor(t=1,e=0){super([-1,ye,0,1,ye,0,-1,-ye,0,1,-ye,0,0,-1,ye,0,1,ye,0,-1,-ye,0,1,-ye,ye,0,-1,ye,0,1,-ye,0,-1,-ye,0,1],br("0b505101707a0ab1595b4ba2a7671839434232636838949524b62a867981"),t,e)}},De=1/ye,rr=class extends Qe{constructor(t=1,e=0){super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-De,-ye,0,-De,ye,0,De,-ye,0,De,ye,-De,-ye,0,-De,ye,0,De,-ye,0,De,ye,0,-ye,0,-De,ye,0,-De,-ye,0,De,ye,0,De],br("3b737f3fd7jh7h676fh48h8aha680g8g282a0c101i0ig6a262d6df2gi2i323di19i9bib34ec4c0408b95b5jbj7j5eje4j4h1ce1e5159"),t,e)}},ir=class extends Ht{constructor(t=1,e=1,i=4,r=8){let n=Math.max(1e-4,Number(t)||1),s=Math.max(0,Number.isFinite(Number(e))?Number(e):1)*.5,a=Math.max(2,Math.min(64,Math.floor(Number(i)||4))),o=[];for(let l=-1;l<=1;l+=2)for(let m=0;m<=a;m++){if(l>0&&m===0&&s===0)continue;let p=(l<0?m/a-1:m/a)*(Math.PI/2);o.push(new Le(Math.max(0,Math.cos(p)*n),l*s+Math.sin(p)*n))}super(o,Math.max(4,Math.min(128,Math.floor(Number(r)||8))))}},Qt=class extends Me{constructor(t=.5,e=1,i=32,r=1,n=0,s=Math.PI*2){super();let a=Math.max(1e-4,Number(e)||1),o=Number(t),l=Number.isFinite(o)?Math.max(0,o):a*.5,m=Math.max(a,l),p=Math.min(m*.999,Math.min(a,l)),v=Math.max(3,Math.min(256,Math.floor(Number(i)||32))),h=Math.max(1,Math.min(64,Math.floor(Number(r)||1))),b=Number.isFinite(Number(n))?Number(n):0,x=Number.isFinite(Number(s))?Number(s):Math.PI*2,g=[],c=[],u=[],y=[];for(let f=0;f<=h;f++){let w=p+f/h*(m-p);for(let M=0;M<=v;M++){let S=b+M/v*x,L=Math.cos(S),P=Math.sin(S);if(g.push(w*L,w*P,0),c.push(0,0,1),u.push(w/m*L*.5+.5,w/m*P*.5+.5),f<h&&M<v){let C=f*(v+1)+M,R=C+v+1;w>1e-6&&y.push(C,R,C+1),y.push(R,R+1,C+1)}}}this.setFromBuffers(g,c,u,y)}},sr=class extends Qt{constructor(t=1,e=32,i=0,r=Math.PI*2){super(0,t,e,1,i,r)}},en=class extends Pe{constructor(t={}){super({roughness:.35,metalness:.1,side:2,...t});let e=Number(t.size);this.size=Number.isFinite(e)?Math.max(.002,Math.min(2,e)):.05,this.sizeAttenuation=t.sizeAttenuation!==!1,t.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.35)}},xt=class extends Pe{constructor(t={}){super({roughness:.4,metalness:.1,side:2,...t});let e=Number(t.linewidth);this.linewidth=Number.isFinite(e)?Math.max(.5,Math.min(20,e)):1,t.emissive===void 0&&(this.emissive=this.color.clone(),this.emissiveIntensity=.3)}},or=class extends xt{constructor(t={}){super(t),this.dashSize=Number(t.dashSize)||3,this.gapSize=Number(t.gapSize)||1,this.scale=Number(t.scale)||1}};function di(t,e){let i=t?.attributes?.position;if(!i?.array||i.count<3)return new Float32Array(0);let r=i.array,n=t?.index?.array,s=Math.min(8192,Math.floor((n?n.length:i.count)/3)),a=h=>`${Math.round((r[h*3]||0)*1e4)},${Math.round((r[h*3+1]||0)*1e4)},${Math.round((r[h*3+2]||0)*1e4)}`,o=e===void 0,l=o?1:Math.cos(e*Math.PI/180),m={},p=[],v=(h,b)=>p.push(r[h*3]||0,r[h*3+1]||0,r[h*3+2]||0,r[b*3]||0,r[b*3+1]||0,r[b*3+2]||0);for(let h=0;h<s;h++){let b=n?n[h*3]:h*3,x=n?n[h*3+1]:h*3+1,g=n?n[h*3+2]:h*3+2,c=r[b*3]||0,u=r[b*3+1]||0,y=r[b*3+2]||0,f=(r[x*3]||0)-c,w=(r[x*3+1]||0)-u,M=(r[x*3+2]||0)-y,S=(r[g*3]||0)-c,L=(r[g*3+1]||0)-u,P=(r[g*3+2]||0)-y,C=w*P-M*L,R=M*S-f*P,A=f*L-w*S,T=Math.hypot(C,R,A);if(!o&&T<1e-8)continue;T>0&&(C/=T,R/=T,A/=T);let D=[b,x,g];for(let E=0;E<3;E++){let k=D[E],I=D[(E+1)%3],$=a(k),N=a(I);if($===N)continue;let U=$<N?`${$}|${N}`:`${N}|${$}`,d=m[U];d?d.m||(d.m=1,d.nx*C+d.ny*R+d.nz*A<=l&&v(k,I)):(m[U]={va:k,vb:I,nx:C,ny:R,nz:A,m:o?1:0},o&&v(k,I))}}if(!o){let h=Object.keys(m);for(let b=0;b<h.length;b++){let x=m[h[b]];x&&!x.m&&v(x.va,x.vb)}}return new Float32Array(p)}var ar=class extends Me{constructor(t){super(),this.setAttribute("position",new Re(di(t),3)),this.__isSegmentPairs=!0}},cr=class extends Me{constructor(t,e=1){super();let i=Number.isFinite(Number(e))?Number(e):1;this.setAttribute("position",new Re(di(t,i),3)),this.__isSegmentPairs=!0}};function fs(t,e,i=1){let r=new Me;r.__baked=!0;let n=t?.attributes?.position;if(!n?.array||n.count<2)return r;let s=n.array,a=t.index?.array,o=t.__isSegmentPairs?"segments":e,l=a?a.length:n.count,m=Math.min(4096,Math.max(0,o==="segments"?Math.floor(l/2):o==="loop"&&l>=3?l:l-1));if(m===0)return r;t.computeBoundingBox();let p=t.boundingBox,v=p&&p.max.x>=p.min.x&&p.max.distanceTo(p.min)||1,h=Math.max(.0015,Math.min(.025,v*.003))*(.5+.5*Math.max(.5,Math.min(6,Number(i)||1))),b=[],x=[],g=[],c=[];for(let u=0;u<m;u++){let y=o==="segments"?u*2:u,f=o==="segments"?u*2+1:(u+1)%l,w=a?a[y]:y,M=a?a[f]:f,S=s[w*3]||0,L=s[w*3+1]||0,P=s[w*3+2]||0,C=(s[M*3]||0)-S,R=(s[M*3+1]||0)-L,A=(s[M*3+2]||0)-P,T=Math.hypot(C,R,A);if(T<1e-6)continue;let D=C/T,E=R/T,k=A/T,I=(Math.abs(E)<.9?Math.hypot(k,D):Math.hypot(k,E))||1,$=Math.abs(E)<.9?k/I:0,N=Math.abs(E)<.9?0:-k/I,U=Math.abs(E)<.9?-D/I:E/I,d=E*U-k*N,F=k*$-D*U,_=D*N-E*$,O=b.length/3,q=[[$,N,U],[d,F,_],[-$,-N,-U],[-d,-F,-_]];for(let z=0;z<2;z++){let W=S+z*C,X=L+z*R,oe=P+z*A;for(let se=0;se<4;se++){let ae=q[se];b.push(W+ae[0]*h,X+ae[1]*h,oe+ae[2]*h),x.push(ae[0],ae[1],ae[2]),g.push(se/4,z)}}for(let z=0;z<4;z++){let W=(z+1)%4;c.push(O+z,O+W,O+4+W,O+z,O+4+W,O+4+z)}}return b.length>0&&r.setFromBuffers(b,x,g,c),r}function ps(t,e=.05){let i=new Me;i.__baked=!0;let r=t?.attributes?.position;if(!r?.array||r.count<1)return i;let n=r.array,s=r.count,a=Math.min(s,5e3),o=Math.max(.003,Math.min(.25,(Number(e)||.05)*.6)),l=[],m=[],p=[],v=[];for(let h=0;h<a;h++){let b=s<=5e3?h:Math.floor(h*s/a),x=n[b*3]||0,g=n[b*3+1]||0,c=n[b*3+2]||0,u=h*6;for(let y=0;y<6;y++){let f=Ot[y*3],w=Ot[y*3+1],M=Ot[y*3+2];l.push(x+f*o,g+w*o,c+M*o),m.push(f,w,M),p.push(.5,.5)}for(let y=0;y<24;y++)v.push(u+hi[y])}return i.setFromBuffers(l,m,p,v),i}var et=class extends He{constructor(t,e,i="strip"){let r=e&&typeof e=="object"?e:{},n=e instanceof Pe?e:i==="points"?new en(r):new xt(r),s=t instanceof Me?t:new Me;super(s,n),this.isLine=!0,this._lineMode=i,this._sourceGeo=s}computeLineDistances(){return this}_bakeAuthorGeometry(){this.geometry&&!this.geometry.__baked&&(this._sourceGeo=this.geometry);let t=this._lineMode==="points";if(t){let e=this._sourceGeo?.attributes?.color;if(e?.array&&e.count>0&&this.material?.color.r===1&&this.material.color.g===1&&this.material.color.b===1){let i=e.array,r=Math.min(e.count,64),n=0,s=0,a=0;for(let o=0;o<r;o++)n+=i[o*3]||0,s+=i[o*3+1]||0,a+=i[o*3+2]||0;this.material.color.setRGB(n/r,s/r,a/r)}}!this.geometry?.__baked&&this._sourceGeo?.attributes?.position?.count>=(t?1:2)&&(this.geometry=t?ps(this._sourceGeo,this.material?.size??.05):fs(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},ur=class extends et{constructor(t,e){super(t,e,"loop"),this.isLineLoop=!0}},lr=class extends et{constructor(t,e){super(t,e,"segments"),this.isLineSegments=!0}},mr=class extends et{constructor(t,e){super(t,e,"points"),this.isPoints=!0}},hr=class extends qt{constructor(t,e,i=0,r=Math.PI/3,n=0,s=2){super(t,e,i,s),this.target=new Oe,this.type="spot";let a=Number(r);this.angle=Number.isFinite(a)?Math.max(.01,Math.min(Math.PI/2,a)):Math.PI/3;let o=Number(n);this.penumbra=Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}},tn=class extends qe{constructor(t,e,i){super(t,i),this.type="hemisphere",this.groundColor=new Ue(e??4473924),this.position.set(0,1,0)}},dr=class extends $t{constructor(t,e){Je("RectAreaLight","AmbientLight"),super(t,e)}},fi={Vector2:Le,Vector3:ie,Vector4:En,Euler:Vt,Quaternion:bt,Matrix4:Ze,Matrix3:Ln,Color:Ue,MathUtils:Yi,BufferAttribute:Re,Float32BufferAttribute:Cn,Uint16BufferAttribute:Dn,Uint32BufferAttribute:Pn,BufferGeometry:Me,BoxGeometry:zt,PlaneGeometry:In,SphereGeometry:kn,CylinderGeometry:Gt,ConeGeometry:Nn,TorusGeometry:Fn,TorusKnotGeometry:Un,Curve:$e,Curve3:$e,LineCurve3:On,QuadraticBezierCurve3:Bn,CubicBezierCurve3:Vn,CatmullRomCurve3:zn,LatheGeometry:Ht,TubeGeometry:Gn,PolyhedronGeometry:Qe,IcosahedronGeometry:nr,OctahedronGeometry:tr,DodecahedronGeometry:rr,TetrahedronGeometry:er,CapsuleGeometry:ir,RingGeometry:Qt,CircleGeometry:sr,WireframeGeometry:ar,EdgesGeometry:cr,FrontSide:0,BackSide:1,DoubleSide:2,NoBlending:0,NormalBlending:1,AdditiveBlending:2,MultiplyBlending:4,RepeatWrapping:1e3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002,NearestFilter:1003,NearestMipmapNearestFilter:1004,NearestMipmapLinearFilter:1005,LinearFilter:1006,LinearMipmapNearestFilter:1007,LinearMipmapLinearFilter:1008,UnsignedByteType:1009,ByteType:1010,ShortType:1011,UnsignedShortType:1012,IntType:1013,UnsignedIntType:1014,FloatType:1015,HalfFloatType:1016,AlphaFormat:1021,RGBFormat:1022,RGBAFormat:1023,LuminanceFormat:1024,LuminanceAlphaFormat:1025,RedFormat:1028,RGFormat:1030,NoColorSpace:"",SRGBColorSpace:"srgb",LinearSRGBColorSpace:"srgb-linear",StaticDrawUsage:35044,DynamicDrawUsage:35048,ACESFilmicToneMapping:4,BasicShadowMap:0,PCFShadowMap:1,PCFSoftShadowMap:2,VSMShadowMap:3,Texture:gt,DataTexture:Hn,TextureLoader:Wn,Material:Pe,MeshStandardMaterial:it,MeshBasicMaterial:Xn,MeshLambertMaterial:jn,MeshPhongMaterial:$n,MeshPhysicalMaterial:qn,PointsMaterial:en,LineBasicMaterial:xt,LineDashedMaterial:or,ShaderMaterial:Jt,RawShaderMaterial:ds,Object3D:Oe,Group:Yn,Mesh:He,InstancedMesh:Xt,Line:et,LineLoop:ur,LineSegments:lr,Points:mr,LightShadow:jt,Light:qe,AmbientLight:$t,DirectionalLight:Kn,PointLight:qt,SpotLight:hr,HemisphereLight:tn,RectAreaLight:dr,Camera:Yt,PerspectiveCamera:Zn,Scene:Kt,WebGLRenderer:Jn,Clock:Qn,SceneQuotaValidator:Ge,exportSceneToCanvas3D:ii,exportSceneToGLB:si,exportSceneToUSDZ:Ki,generateUSDZ:kt,glbToUSDZ:It,sceneToCanvas3D:dt,sceneToGLB:Dt,sceneToUSDZ:Pt,authorScriptRunner:pr,warnUnsupported:Je,getAuthorWarnings:ms,clearAuthorWarnings:hs};Object.freeze(Ge),Object.freeze(Ge.prototype),Object.freeze(Kt.prototype),Object.freeze(fi);var tt=new Proxy(fi,{get:(t,e)=>{if(e in t)return t[e];let i=ue().authorNamespace;return i&&typeof e=="string"&&e in i?i[e]:(typeof e=="string"&&e!=="then"&&e!=="toJSON"&&!e.startsWith("__")&&Je(`THREE.${e}`,"no-op proxy"),Ut)},has:(t,e)=>{if(e in t)return!0;let i=ue().authorNamespace;return!!(i&&typeof e=="string"&&e in i)},set:(t,e)=>{throw new TypeError(`Cannot assign to read only property '${String(e)}' of #<THREE>`)},defineProperty:(t,e)=>{throw new TypeError(`Cannot define property '${String(e)}', object is not extensible`)},deleteProperty:(t,e)=>{throw new TypeError(`Cannot delete property '${String(e)}' of #<THREE>`)},setPrototypeOf:()=>{throw new TypeError("#<THREE> is not extensible")}}),Bt=ue();if(Bt.threeNamespace=tt,Bt.workerExtensionInstallers)for(let t of Bt.workerExtensionInstallers)t(tt,Bt);var _n={name:"three_author",THREE:tt},ze=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof ze.THREE>"u"&&(ze.THREE=tt),typeof ze.requestAnimationFrame!="function"&&(ze.requestAnimationFrame=t=>(typeof t=="function"&&typeof ze.__three_live_raf_cb__!="function"&&(ze.__three_live_raf_cb__=t),ze.__three_live_in_step__||Je("requestAnimationFrame","single-frame static evaluation"),0)),typeof ze.cancelAnimationFrame!="function"&&(ze.cancelAnimationFrame=()=>{}),typeof window<"u"){let t=window;t.ThreeLive=t.ThreeLive||{},t.ThreeLive.THREE=tt,t.ThreeLivePlugins=t.ThreeLivePlugins||{},t.ThreeLivePlugins.threeAuthor=_n,t.ThreeLivePlugins.three_author=_n,t.ThreeLivePlugins["three-author"]=_n}function gr(t,e){let i=t?.trim(),r=i?Number(i):NaN;return Number.isFinite(r)?r:e}var yr=(t,e,i)=>({x:t,y:e,z:i,toString:()=>`${t}m ${e}m ${i}m`}),ys=typeof HTMLElement<"u"?HTMLElement:class{};typeof CustomEvent>"u"&&typeof Event<"u"&&(globalThis.CustomEvent=class extends Event{constructor(t,e){super(t,e),this.detail=e?.detail??null}});var Ie=class We extends ys{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.loadController=null,this.resizeObserver=null,this.mutationObserver=null}static get sandboxEngineSrc(){return ue().sandboxEngineSrc??null}static set sandboxEngineSrc(e){ue().sandboxEngineSrc=e}static get sandboxIframeSrc(){return ue().sandboxIframeSrc??null}static set sandboxIframeSrc(e){ue().sandboxIframeSrc=e}static get allowClientScripts(){return!!ue().allowClientScripts}static set allowClientScripts(e){ue().allowClientScripts=e}static registerScriptRunner(e){ue().scriptRunner=e}static defineModelViewer(e="model-viewer"){if(typeof customElements>"u")return!1;let i=customElements.get(e);return i!=null?i===We||i.prototype instanceof We:(customElements.define(e,class extends We{}),!0)}static registerDecoder(e,i){_e.registerDecoder(e,i)}static getDecoder(e){return _e.getDecoder(e)}static registerAR(e){ue().arProvider=typeof e=="function"?{activateAR:e}:e,typeof document<"u"&&document.querySelectorAll("three-live").forEach(i=>{i instanceof We&&i.updateARButtonVisibility()})}static isARSupported(){return!!ue().arProvider}getLoadedModel(){return this.currentModel}beginLoad(){let e=this.loadController,i=this.scriptHandle,r=new AbortController;return this.loadController=r,this.scriptHandle=null,e?.abort(),i?.terminate(),r}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"),i=this.getAttribute("script-src");e?this.loadModel(e).catch(()=>{}):i?this.loadScriptFromSrc(i).catch(()=>{}):this.scheduleInlineScript();for(let r of _e.getRegisteredPlugins())r.onElementConnected?.(this)}scheduleInlineScript(){let e=this.loadController,i=()=>{let r=this.querySelector('script[type="text/three"], script[type="text/three-live"]');return this.loadController===e&&r?.textContent?(this.executeScript(r.textContent).catch(()=>{}),!0):!1};queueMicrotask(()=>i()||document.addEventListener("DOMContentLoaded",i))}disconnectedCallback(){for(let e of _e.getRegisteredPlugins())e.onElementDisconnected?.(this);this.beginLoad().abort(),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.activeXRSession?.stop?.().catch?.(()=>{}),this.activeXRSession=null,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=null,this.viewer?.destroy(),this.viewer=null,this.isModelLoaded=!1}attributeChangedCallback(e,i,r){if(i===r)return;let n=this.viewer;switch(e){case"src":r&&this.loadModel(r).catch(()=>{});break;case"camera-target":{let s=this.parseCameraTarget(r);n&&s&&n.setTarget(s[0],s[1],s[2]);break}case"min-camera-orbit":case"max-camera-orbit":if(n){let s=this.parseOrbitLimit(this.getAttr("min-camera-orbit")),a=this.parseOrbitLimit(this.getAttr("max-camera-orbit"));n.setOrbitLimits({minTheta:s.theta,maxTheta:a.theta,minPhi:s.phi,maxPhi:a.phi,minDistance:s.distance,maxDistance:a.distance})}break;case"field-of-view":{let s=this.parseFieldOfView(r);n&&s!==void 0&&n.setFieldOfView(s);break}case"script-src":r&&this.loadScriptFromSrc(r).catch(()=>{});break;case"poster":this.updatePoster(r);break;case"camera-orbit":this.applyCameraOrbit(r);break;case"selected-mesh":n?.setSelectedMesh(r??"");break;case"exposure":if(n&&r!==null){let s=parseFloat(r);isNaN(s)||n.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":n?.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":n?.setToneMapping(Ke(r));break;case"environment-image":n?.setEnvironmentImage(r).catch(()=>{});break;case"skybox-image":n?.setSkyboxImage?.(r)?.catch?.(()=>{});break;case"camera-controls":{let s=this.cameraControls;n?.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"none":"auto");break}case"autoplay":n?.setAutoplay(r!==null&&r!=="false");break;case"animation-name":n&&r!==null&&n.setAnimationName(r);break;case"variant-name":n&&this.selectVariant(r);break;case"auto-rotate":n?.setAutoRotate(r!==null&&r!=="false");break;case"auto-rotate-delay":n?.setAutoRotateDelay(this.autoRotateDelay);break;case"rotation-per-second":n?.setAutoRotateSpeed(this.parseRotationPerSecond(r));break;case"ar":this.updateARButtonVisibility();break;case"renderer":n?.render();break;case"shadow-maps":n&&(n.shadowMaps=r!==null?this.shadowMaps:void 0),n?.render();break}for(let s of _e.getRegisteredPlugins())s.onAttributeChanged?.(this,e,i,r)}getAttr(e){return this.getAttribute(e)}setAttr(e,i){i!==null?this.setAttribute(e,String(i)):this.removeAttribute(e)}getBoolAttr(e){return this.hasAttribute(e)&&this.getAttr(e)!=="false"}setBoolAttr(e,i){this.setAttr(e,i?"":null)}getFloatAttr(e,i){let r=this.getAttr(e);return r!==null?parseFloat(r):i}get sandbox(){return this.getAttr("sandbox")||(ue().sandboxIframeSrc?"iframe":"worker")}set sandbox(e){this.setAttr("sandbox",e)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||We.allowClientScripts}set allowClientScripts(e){this.setBoolAttr("allow-client-scripts",e)}get turntableRotation(){return this.viewer?this.viewer.turntableRotation:0}get ar(){return this.hasAttribute("ar")}set ar(e){this.setBoolAttr("ar",e)}get canActivateAR(){return We.isARSupported()}get toneMapping(){return Ke(this.getAttr("tone-mapping"))}set toneMapping(e){this.setAttr("tone-mapping",e)}get bloomThreshold(){return gr(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(e){this.setAttr("bloom-threshold",e)}get bloomRadius(){return gr(this.getAttr("bloom-radius"),.75)}set bloomRadius(e){this.setAttr("bloom-radius",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():[]}get renderer(){let e=this.getAttr("renderer")?.trim().toLowerCase();return e==="webgpu"||e==="webgl2"?e:"auto"}set renderer(e){this.setAttr("renderer",e)}get shadowMaps(){let e=this.getAttr("shadow-maps")?.trim().toLowerCase();return e==="pcf"||e==="off"?e:"auto"}set shadowMaps(e){this.setAttr("shadow-maps",e)}fireEvent(e,i){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:i}))}setSlotVisible(e,i){let r=typeof this.querySelector=="function"?this.querySelector(`[slot="${e}"]`):null;r&&(r.hidden=!i,r.style&&(r.style.display=i?"":"none"))}emitError(e,i="script"){this.setSlotVisible("error",!0),this.fireEvent("error",{error:e}),this.fireEvent("three-error",{error:e,message:e?.message||String(e),stage:i})}selectVariant(e){if(!this.viewer)return!1;let i=this.viewer.selectVariant(e);return i&&this.fireEvent("variant-applied",{variantName:this.viewer.getVariantName()}),i}get model(){let e=this.viewer?this.viewer.getModelMaterials():[];return{materials:e,getMaterialByName(i){return e.find(r=>r.name===i)??null}}}play(){this.viewer?.playAnimation(this.animationName||void 0)}pause(){this.viewer?.pauseAnimation()}resetCamera(){this.viewer?.resetCamera()}resetTurntableRotation(e=0){this.viewer?.resetTurntableRotation(e)}setCamera(e,i,r,n){this.viewer?.setCamera(e,i,r,n)}getCameraOrbit(){return this.viewer?.getCameraOrbit()??{theta:0,phi:0,radius:3,toString:()=>"0rad 0rad 3m"}}getCameraTarget(){return this.viewer?this.viewer.getCameraTarget():yr(0,0,0)}getFieldOfView(){return this.viewer?this.viewer.getFieldOfView():45}jumpCameraToGoal(){this.viewer?.jumpCameraToGoal()}toDataURL(e,i){return this.viewer?.render?.(),this.canvas?this.canvas.toDataURL(e,i):""}toBlob(e){return this.viewer?.render?.(),new Promise((i,r)=>{if(!this.canvas||typeof this.canvas.toBlob!="function"){r(new Error("Canvas toBlob is not supported in this environment."));return}this.canvas.toBlob(n=>{n?i(n):r(new Error("Failed to capture canvas blob."))},e?.mimeType,e?.qualityArgument)})}positionAndNormalFromPoint(e,i){let r=this.viewer?.raycastFromScreenPoint(e,i);if(!r)return null;let[n,s,a]=r.hitPoint||r.point,[o,l,m]=r.normal;return{position:yr(n,s,a),normal:yr(o,l,m)}}loadModel(e){return this.loadModelWithLimits(e)}async loadModelWithLimits(e,i,r=this.beginLoad()){if(r.signal.throwIfAborted(),!this.viewer){this.currentModel=e,this.currentModelLimits=i;return}try{let n;if(typeof e=="string"){let l=await fetch(e,{signal:r.signal});if(!l.ok)throw new Error(`Failed to load "${e}": HTTP ${l.status}`);n=await l.arrayBuffer()}else n=e;r.signal.throwIfAborted();let s=Xe(n);this.viewer.loadGLBData(s,i),this.currentModel=s,this.currentModelLimits=i,this.isModelLoaded=!0,this.hidePoster(),this.setSlotVisible("error",!1),this.updateHotspots();let a=this.getAttr("selected-mesh");a&&this.viewer.setSelectedMesh(a);let o=this.getAttr("variant-name");o&&this.selectVariant(o),this.fireEvent("load",{model:s}),this.fireEvent("three-load",{model:s,source:typeof e=="string"?"src":"model"})}catch(n){throw r.signal.aborted||this.emitError(n,"load"),n}}showToast(e,i=4500){if(typeof document>"u")return;let r=this.querySelector(".three-live-toast");r||(r=document.createElement("div"),r.className="three-live-toast",r.style.cssText="position:absolute;bottom:70px;left:50%;transform:translateX(-50%) translateY(10px);z-index:10;padding:10px 16px;background:rgba(15,23,42,.94);color:#f8fafc;border:1px solid rgba(56,189,248,.45);border-radius:14px;font:500 13px/1.35 system-ui,-apple-system,sans-serif;box-shadow:0 10px 25px rgba(0,0,0,.45);backdrop-filter:blur(12px);pointer-events:none;opacity:0;transition:opacity .25s,transform .25s;max-width:88%;text-align:center;white-space:normal;word-break:break-word",this.appendChild(r)),r.textContent=e,this.toastTimer&&clearTimeout(this.toastTimer);let n=()=>{r&&(r.style.opacity="1",r.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(n):n(),this.toastTimer=setTimeout(()=>{r&&(r.style.opacity="0",r.style.transform="translateX(-50%) translateY(10px)"),this.toastTimer=null},i)}async activateAR(){this.activeXRSession?.isSessionActive?.()&&(await this.activeXRSession.stop().catch(()=>{}),this.activeXRSession=null);let e=(s,a=s.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(a,6e3),s};this.currentModel||e(new Error("No 3D model is loaded in <three-live>."));let i=ue().arProvider;i||e(new Error("AR module not bundled. Use the default 'three-live' bundle or call ThreeLiveElement.registerAR()."));let r=this.getAttr("ios-src"),n=(this.getAttr("ar-modes")||"").split(/\s+/).filter(Boolean);try{this.fireEvent("ar-status",{status:"session-started"});let s=await i.activateAR({model:r||this.currentModel,glbUrl:typeof this.currentModel=="string"?this.currentModel:void 0,view:this.viewer||void 0,element:this,preferredModes:n.length>0?n:void 0,arScale:this.arScale,arPlacement:this.arPlacement,webXROptions:{onExit:()=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"not-presenting"})},onError:a=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:a}),this.showToast(`AR error: ${a.message}`,6e3)}}});if(s.success){s.session&&(this.activeXRSession=s.session);let a={"quick-look":"Opening Apple AR Quick Look...","scene-viewer":"Opening Google Scene Viewer...",webxr:"WebXR AR session started."}[s.mode||""]||"";a&&this.showToast(a)}else{let a=s.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(this.isDesktopMac()&&typeof document<"u"&&this.currentModel&&i.createUSDZBlob)try{let o=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:i.createUSDZBlob(this.currentModel),l=URL.createObjectURL(o),m=document.createElement("a");m.href=l,m.download="three_live_model.usdz",document.body.appendChild(m),m.click(),document.body.removeChild(m),setTimeout(()=>URL.revokeObjectURL(l),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(a,6e3)}else this.showToast(a,6e3);s.error&&this.fireEvent("ar-status",{status:"failed",error:s.error})}return s}catch(s){return this.activeXRSession=null,e(s,`AR error: ${s.message||String(s)}`)}}setupDOM(){let e=this.querySelector("canvas");e||(e=document.createElement("canvas"),e.style.cssText=`width:100%;height:100%;display:block;touch-action:${this.cameraControls?"none":"auto"};outline:none`,this.appendChild(e)),this.canvas=e,typeof e.addEventListener=="function"&&!e.__tlCtxBound&&(e.__tlCtxBound=!0,e.addEventListener("webglcontextlost",r=>this.fireEvent("three-context-lost",{originalEvent:r})),e.addEventListener("webglcontextrestored",r=>this.fireEvent("three-context-restored",{originalEvent:r}))),this.setSlotVisible("error",!1),this.isModelLoaded||this.setSlotVisible("poster",!0);let i=this.getAttr("poster");i&&this.updatePoster(i),this.createARButton(),typeof MutationObserver<"u"&&!this.mutationObserver&&(this.mutationObserver=new MutationObserver(()=>{this.updateARButtonVisibility()}),this.mutationObserver.observe(this,{childList:!0}))}initViewer(){if(!this.canvas)return;this.viewer=new _e(this,this.canvas,{autoRotate:this.autoRotate,autoRotateDelay:this.autoRotateDelay,autoRotateSpeed:this.parseRotationPerSecond(this.getAttr("rotation-per-second")),exposure:this.exposure,shadowIntensity:this.shadowIntensity,shadowSoftness:this.shadowSoftness,shadowMaps:this.hasAttribute("shadow-maps")?this.shadowMaps:void 0,toneMapping:this.toneMapping,environmentImage:this.environmentImage,autoplay:this.autoplay,animationName:this.animationName||void 0,variantName:this.getAttr("variant-name")||void 0,fieldOfView:this.parseFieldOfView(this.getAttr("field-of-view")),cameraTarget:this.parseCameraTarget(this.getAttr("camera-target")),minCameraOrbit:this.parseOrbitLimit(this.getAttr("min-camera-orbit")),maxCameraOrbit:this.parseOrbitLimit(this.getAttr("max-camera-orbit")),onMeshClick:i=>{this.fireEvent("meshclick",i)},onCameraChange:i=>{this.updateHotspots();for(let r of _e.getRegisteredPlugins())r.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",i)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let e=this.getAttr("camera-orbit");e&&this.applyCameraOrbit(e),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.alt="3D Scene Preview",this.posterEl.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .35s ease-out;pointer-events:none;z-index:1",this.appendChild(this.posterEl)),this.posterEl.src=e,this.isModelLoaded||(this.posterEl.style.opacity="1")}}hidePoster(){this.setSlotVisible("poster",!1),this.posterEl&&(this.posterEl.style.opacity="0",setTimeout(()=>{this.isModelLoaded&&this.posterEl&&(this.posterEl.remove(),this.posterEl=null)},400))}isDesktopMac(){let e=typeof navigator<"u"&&navigator.userAgent||"";return/Macintosh/i.test(e)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1)&&!/Android|iPhone|iPad|iPod/i.test(e)}syncARButtonLabel(e){let i=this.isDesktopMac(),r=i?"Quick Look (.usdz)":"View in AR",n=i?"Download .usdz preview for macOS Quick Look (live camera AR requires iOS or Android)":"View in Augmented Reality";typeof e.setAttribute=="function"&&(e.setAttribute("aria-label",n),e.setAttribute("title",n));let s=e._labelSpan||(typeof e.querySelector=="function"?e.querySelector("span"):null);s&&(s.textContent=r)}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let e=document.createElement("button");e.type="button",e.className="three-live-ar-button",e.setAttribute("part","default-ar-button");let i="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let n=document.createElementNS(i,"svg");for(let[a,o]of Object.entries({width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}))n.setAttribute(a,o);n.style.marginRight="6px";let s=document.createElementNS(i,"path");s.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 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"),n.appendChild(s),e.appendChild(n)}let r=document.createElement("span");e._labelSpan=r,e.appendChild(r),this.syncARButtonLabel(e),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,.85);color:#fff;border:1px solid rgba(255,255,255,.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,.25);transition:transform .15s,background-color .15s;display:none";for(let[n,s,a]of[["mouseenter","rgba(30, 41, 59, 0.95)","scale(1.04)"],["mouseleave","rgba(15, 23, 42, 0.85)","scale(1)"]])e.addEventListener(n,()=>{e.style.backgroundColor=s,e.style.transform=a});e.addEventListener("click",n=>{n.stopPropagation(),this.activateAR()}),this.arButton=e,this.appendChild(e)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let e=this.hasAttribute("ar")&&We.isARSupported(),i=typeof this.querySelector=="function"?this.querySelector('[slot="ar-button"]'):null;i?(this.arButton&&(this.arButton.style.display="none"),i.__tlARBound||(i.__tlARBound=!0,i.addEventListener("click",r=>{r.stopPropagation(),this.activateAR()})),i.dataset.tlOrigDisplay===void 0&&(i.dataset.tlOrigDisplay=i.style.display==="none"?"":i.style.display),i.style.display=e?i.dataset.tlOrigDisplay||"":"none"):this.arButton&&(this.syncARButtonLabel(this.arButton),this.arButton.style.display=e?"flex":"none")}applyCameraOrbit(e){if(!(!e||!this.viewer))try{let i=JSON.parse(e);this.viewer.setInitialCamera(i.theta,i.phi,i.distance,i.zoom)}catch{let i=this.parseOrbitLimit(e);(i.theta!==void 0||i.phi!==void 0)&&this.viewer.setInitialCamera(i.theta,i.phi,i.distance)}}parseOrbitLimit(e){if(!e)return{};let[i,r,n]=e.trim().split(/\s+/),s=n&&n!=="auto"?parseFloat(n):NaN;return{theta:i&&i!=="auto"?this.parseFieldOfView(i):void 0,phi:r&&r!=="auto"?this.parseFieldOfView(r):void 0,distance:isNaN(s)?void 0:s}}parseCameraTarget(e){if(!e)return;let i=e.trim().split(/\s+/).map(parseFloat);return i.length>=3&&!i.some(isNaN)?[i[0],i[1],i[2]]:void 0}parseFieldOfView(e){if(!e)return;let i=parseFloat(e);return isNaN(i)?void 0:e.endsWith("rad")?i*180/Math.PI:i}parseRotationPerSecond(e){if(!e)return Math.PI/6;let i=e.trim(),r=parseFloat(i);return isNaN(r)?Math.PI/6:i.endsWith("rad")?r:i.endsWith("%")?r/100*Math.PI*2:r*Math.PI/180}updateHotspot(e){let i=this.querySelector(`[slot="${e.name}"]`);i&&(e.position!==void 0&&i.setAttribute("data-position",e.position),e.normal!==void 0&&i.setAttribute("data-normal",e.normal)),this.updateHotspots()}updateHotspots(){for(let e of _e.getRegisteredPlugins())if(e.updateHotspotsForElement){e.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(e){let i=ue().scriptRunner;if(!i){let s=new Error('Script execution requires "three-live/full" or registerScriptRunner().');return this.showToast(s.message),this.emitError(s,"script"),Promise.reject(s)}let r=this.beginLoad(),n=()=>!r.signal.aborted;return new Promise((s,a)=>{let o=()=>a(r.signal.reason);if(r.signal.addEventListener("abort",o,{once:!0}),!n()){o();return}let l={onModelReady:m=>{this.loadModelWithLimits(m,Fr,r).then(()=>s(m),a)},onUpdateTransforms:m=>{n()&&this.viewer?.updateMeshTransforms(m)},onError:m=>{n()&&(this.showToast(m.message),this.emitError(m,"script"),a(m))},onToast:m=>{n()&&this.showToast(m)}};e(i,l).then(m=>{n()?this.scriptHandle=m||null:m?.terminate()},m=>{n()&&l.onError?.(m)})})}loadScriptFromSrc(e){return this.runWithScriptRunner((i,r)=>{if(typeof i.executeUrl!="function"){let n=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return r.onError?.(n),Promise.reject(n)}return i.executeUrl(e,this.sandbox,r)})}executeScript(e){if(!ue().scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let i=new Error(Mt);return this.showToast(At),this.emitError(i,"security"),Promise.reject(i)}return this.runWithScriptRunner((i,r)=>i.execute(e,this.sandbox,r,{allowClientScripts:!0}))}};Ie.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 renderer shadow-maps".split(" "),Ie.registerPlugin=_e.registerPlugin,Ie.getRegisteredPlugins=_e.getRegisteredPlugins;var Be=Ie;{let t=Be.prototype,e=(r,n,s)=>Object.defineProperty(t,r,{get:n,set:s,configurable:!0}),i=r=>r.replace(/[A-Z]/g,n=>"-"+n.toLowerCase());for(let r of"src cameraOrbit cameraTarget minCameraOrbit maxCameraOrbit fieldOfView iosSrc scriptSrc poster selectedMesh environmentImage skyboxImage animationName".split(" ")){let n=i(r);e(r,function(){return this.getAttr(n)},function(s){this.setAttr(n,s)})}for(let r of"cameraControls autoRotate outlineSelected autoplay".split(" ")){let n=i(r);e(r,function(){return this.getBoolAttr(n)},function(s){this.setBoolAttr(n,s)})}for(let[r,n]of[["exposure",1],["autoRotateDelay",3e3],["shadowIntensity",0],["shadowSoftness",.5],["bloom",0]]){let s=i(r);e(r,function(){return this.getFloatAttr(s,n)},function(a){this.setAttr(s,a)})}for(let[r,n]of[["rotationPerSecond","30deg"],["arScale","auto"],["arPlacement","floor"],["outlineColor","#38bdf8"]]){let s=i(r);e(r,function(){return this.getAttr(s)||n},function(a){this.setAttr(s,a)})}}typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",Be);function pi(t="model-viewer"){return Be.defineModelViewer(t)}function vr(){if(typeof window>"u"||typeof navigator>"u")return!1;let t=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(t)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let e=document.createElement("a");return e.relList!==void 0&&e.relList.supports!==void 0&&e.relList.supports("ar")}function Sr(){if(typeof navigator>"u")return!1;let t=navigator.userAgent||"";return/android/i.test(t)}async function wr(){if(typeof navigator>"u")return!1;let t=navigator;if(!t.xr||typeof t.xr.isSessionSupported!="function")return!1;try{return await t.xr.isSessionSupported("immersive-ar")?!0:await t.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function yi(){return(await sn()).bestMode}async function sn(){let[t,e,i]=await Promise.all([wr(),Promise.resolve(vr()),Promise.resolve(Sr())]),r=[];e&&r.push("quick-look"),t&&r.push("webxr"),i&&r.push("scene-viewer");let n=null;return e?n="quick-look":t?n="webxr":i&&(n="scene-viewer"),{webxr:t,quickLook:e,sceneViewer:i,availableModes:r,bestMode:n}}function bi(t,e={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let i,r=!1;if(typeof t=="string"){if(i=xs(t),!i)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else i=URL.createObjectURL(t),r=!0;let n=[];if(e.allowScale===!1&&n.push("allowsContentScaling=0"),e.canonicalWebPageUrl){let o=rn(e.canonicalWebPageUrl,!1);o&&n.push(`canonicalWebPageURL=${encodeURIComponent(o)}`)}e.checkoutTitle&&n.push(`checkoutTitle=${encodeURIComponent(e.checkoutTitle)}`),e.checkoutSubtitle&&n.push(`checkoutSubtitle=${encodeURIComponent(e.checkoutSubtitle)}`),e.price&&n.push(`price=${encodeURIComponent(e.price)}`),n.length>0&&(i+=`#${n.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",i);let a=document.createElement("img");a.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),a.style.display="none",s.appendChild(a),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),r&&URL.revokeObjectURL(i.split("#")[0])},3e3)}function rn(t,e=!1){if(typeof t!="string")return"";let i=t.replace(/[\x00-\x1f\x7f]+/g,"").trim();if(!i)return"";if(/^[\\/]{2}/.test(i))throw new Error(`[XR-Live Security] Rejected protocol-relative URL in Scene Viewer intent: ${i.slice(0,32)}`);let r=i.toLowerCase();if(r.startsWith("https://")||r.startsWith("http://")||e&&r.startsWith("blob:")||!/^[a-z][a-z0-9+.-]*:/i.test(i))return i;throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Scene Viewer intent: ${i.slice(0,32)}`)}function xs(t){try{return rn(t,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(t||"").trim().slice(0,32)}`)}}function vs(t,e={}){let i=rn(t,!0),r=e.mode||"ar_preferred",n=new URLSearchParams({file:i,mode:r,resizable:e.resizable!==!1?"true":"false",enable_vertical_placement:e.enableVerticalPlacement?"true":"false"});return e.title&&n.set("title",e.title),e.link&&n.set("link",rn(e.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${n.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function Ss(t,e={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let i=vs(t,e);window.location.href=i}var nt=null;function ws(t,e){let i=new Float32Array(144),r=new Float32Array(144),n=new Float32Array(96),s=new Uint16Array(144);for(let p=0;p<24;p++){let v=p/24*Math.PI*2,h=Math.cos(v),b=Math.sin(v),x=p*2,g=x+1,c=(p+1)%24*2;i[x*3]=h*.11,i[x*3+1]=.002,i[x*3+2]=b*.11,i[g*3]=h*.145,i[g*3+1]=.002,i[g*3+2]=b*.145,r[x*3+1]=r[g*3+1]=1,s.set([x,c,g,g,c,c+1],p*6)}let a=t.createVertexArray();t.bindVertexArray(a);let o=(p,v,h)=>{let b=t.createBuffer();return t.bindBuffer(34962,b),t.bufferData(34962,p,35044),t.enableVertexAttribArray(v),t.vertexAttribPointer(v,h,5126,!1,0,0),b},l=[o(i,0,3),o(r,1,3),o(n,2,2)],m=t.createBuffer();return l.push(m),t.bindBuffer(34963,m),t.bufferData(34963,s,35044),t.bindVertexArray(null),{name:"__xr_reticle__",nodeIndex:-1,worldSpace:!0,visible:!1,transform:new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),normalMatrix:new Float32Array([1,0,0,0,1,0,0,0,1]),primitives:[{vao:a,indexCount:s.length,indexType:5123,baseColor:e&&e.length>=3?[e[0],e[1],e[2],e[3]??.95]:[.22,.74,.97,.95],metallic:0,roughness:.2,positions:i,indices:s,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:l}]}}function gi(t,e,i,r,n){let s=Math.cos(r),a=Math.sin(r),o=Math.max(.01,n);t.fill(0),t[0]=o*s,t[2]=-o*a,t[5]=o,t[8]=o*a,t[10]=o*s,t[12]=e[0]-o*(s*i[0]+a*i[2]),t[13]=e[1]-o*i[1],t[14]=e[2]-o*(-a*i[0]+s*i[2]),t[15]=1}var xr=class{constructor(t={}){this.s=null,this.placed=!1,this.placedMat=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.cleanFn=null,this.opts=t}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(t,e){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");nt&&nt!==this&&nt.isSessionActive()&&await nt.stop().catch(()=>{});let i=navigator.xr,r=this.opts,n=e||t?.container,s=String(n?.tagName||"").toLowerCase()==="xr-live",a=t?.bounds,o=Number(a?.radius)||1,l=Array.isArray(a?.center)?a.center:[0,0,0],m=Array.isArray(a?.min)?a.min:[-.5,-.5,-.5],p=typeof navigator<"u"&&navigator.userAgent||"",v=/Android|iPhone|iPad|iPod/i.test(p)&&!/Quest|Oculus|Pico|Vision/i.test(p),h=s?r.arScale==="fixed"?1:v?.55:1:r.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,b=s?[0,-.25,0]:[l[0]||0,r.arPlacement==="wall"?l[1]:m[1]??0,l[2]||0],x="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(x="immersive-vr")}catch{x="immersive-vr"}let g=n?.querySelector?.('[slot="ar-overlay"]')||null,c=!1,u=null,y=()=>{c&&g?.parentNode&&g.parentNode.removeChild(g),g=null,u=null,c=!1};if(x==="immersive-ar"){if(g)g.addEventListener?.("beforexrselect",z=>z.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let z=document.createElement("div");z.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let W=document.createElement("button");W.type="button",W.textContent="\u2715 Exit AR",W.style.cssText="position:absolute;top:max(16px,env(safe-area-inset-top,16px));right:16px;pointer-events:auto;padding:8px 14px;border-radius:99px;border:1px solid rgba(255,255,255,.3);background:rgba(15,23,42,.8);color:#f8fafc;font:600 13px system-ui,sans-serif",W.addEventListener("beforexrselect",X=>X.preventDefault()),W.addEventListener("click",X=>{X.stopPropagation(),this.stop().catch(()=>{})}),u=document.createElement("div"),u.style.cssText="position:absolute;bottom:max(28px,env(safe-area-inset-bottom,28px));left:50%;transform:translateX(-50%);padding:8px 15px;border-radius:99px;border:1px solid rgba(56,189,248,.4);background:rgba(15,23,42,.82);color:#f8fafc;font:500 12.5px system-ui,sans-serif;text-align:center;max-width:88vw",u.textContent="Move phone to detect a surface \u2022 Tap to place",z.appendChild(W),z.appendChild(u),document.body.appendChild(z),g=z,c=!0}}let f=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),w={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(f)};g&&(f.add("dom-overlay"),w.optionalFeatures=Array.from(f),w.domOverlay={root:g});for(let z of ge)z.onConfigureXRSessionInit?.(n,w);Array.isArray(w.optionalFeatures)&&w.optionalFeatures.includes("dom-overlay")&&!w.domOverlay?.root&&(w.optionalFeatures=w.optionalFeatures.filter(z=>z!=="dom-overlay"));let M=z=>{let W=String(z?.name||"");return W==="NotAllowedError"||W==="SecurityError"};try{this.s=await i.requestSession(x,w)}catch(z){if(y(),M(z))throw r.onError?.(z),z;try{this.s=await i.requestSession(x,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(W){if(M(W))throw r.onError?.(W),W;try{this.s=await i.requestSession(x)}catch(X){throw r.onError?.(X),X}}}let S=this.s;nt=this,this.placed=!1;let L=null,P=null,C=null,R=null,A=null,T=[0,-.25,-1.2],D=[0,-.25,-1.2],E=new Float32Array(16),k=new Float32Array(16),I=!1,$=1,N=0,U=!1,d=null,F=null,_=0,O=null,q=()=>{nt===this&&(nt=null),O?.(),O=null;try{P?.cancel?.()}catch{}if(P=null,C){let z=t?.meshes;if(Array.isArray(z)){let X=z.indexOf(C);X!==-1&&z.splice(X,1)}let W=t.getGLContext?.()||t?.gl;if(W)for(let X of C.primitives||[]){W.deleteVertexArray?.(X.vao);for(let oe of X.buffers||[])W.deleteBuffer?.(oe)}C=null}t?.setXRSessionActive?.(!1),y(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=q,S.addEventListener("end",()=>{q(),r.onExit?.()}),S.addEventListener("select",()=>{if(!this.placed){let z=A||T;D=[z[0],z[1],z[2]],gi(this.placedMat,D,b,N,h*$),this.placed=!0,C&&(C.visible=!1),u&&(u.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let z=t.getGLContext?.()||t?.gl;z&&typeof z.makeXRCompatible=="function"&&await z.makeXRCompatible();let W=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;z&&typeof W=="function"&&typeof S.updateRenderState=="function"&&S.updateRenderState({baseLayer:new W(S,z,{alpha:!0})});try{L=await S.requestReferenceSpace("local")}catch{try{L=await S.requestReferenceSpace("local-floor")}catch{L=await S.requestReferenceSpace("viewer")}}let X=await S.requestReferenceSpace("viewer").catch(()=>L);if(typeof S.requestHitTestSource=="function"&&X&&(P=await S.requestHitTestSource({space:X}).catch(()=>null)),x==="immersive-ar"&&z&&typeof z.createVertexArray=="function"&&Array.isArray(t.meshes)&&(C=ws(z,r.reticleColor),t.meshes.push(C)),typeof window<"u"&&typeof window.addEventListener=="function"){let se=V=>Math.hypot(V.touches[1].clientX-V.touches[0].clientX,V.touches[1].clientY-V.touches[0].clientY),ae=V=>Math.atan2(V.touches[1].clientY-V.touches[0].clientY,V.touches[1].clientX-V.touches[0].clientX),le=V=>{this.s&&(V.touches.length===1&&this.placed?U=!0:V.touches.length>=2&&(U=!1,d=se(V),F=ae(V)))},G=V=>{if(!this.s||V.touches.length<2)return;let J=se(V),Z=ae(V);if(d&&d>4&&r.arScale!=="fixed"&&($=Math.max(.15,Math.min(6,$*(J/d)))),F!==null){let K=Z-F;K>Math.PI&&(K-=Math.PI*2),K<-Math.PI&&(K+=Math.PI*2),N-=K}d=J,F=Z},Y=V=>{(!V.touches||V.touches.length===0)&&(U=!1),(!V.touches||V.touches.length<2)&&(d=null,F=null)};window.addEventListener("touchstart",le,{passive:!0}),window.addEventListener("touchmove",G,{passive:!0}),window.addEventListener("touchend",Y,{passive:!0}),window.addEventListener("touchcancel",Y,{passive:!0}),O=()=>{window.removeEventListener("touchstart",le),window.removeEventListener("touchmove",G),window.removeEventListener("touchend",Y),window.removeEventListener("touchcancel",Y)}}t.setXRSessionActive?.(!0);let oe=(se,ae)=>{if(this.s!==S)return;S.requestAnimationFrame(oe);let le=_>0?Math.min(Math.max((se-_)/1e3,0),.1):1/60;_=se,t?.stepXRUpdate?.(le);let G=ae.getViewerPose(L);if(!G)return;let Y=G.views?.[0];if(!I&&Y?.transform){let j=Y.transform.position,H=Y.transform.matrix,Q=j?.x??(H?H[12]:0),ee=j?.y??(H?H[13]:0),re=j?.z??(H?H[14]:0),he=H?-H[8]:0,ne=H?-H[10]:-1,be=Math.hypot(he,ne);be>1e-4?(he/=be,ne/=be):(he=0,ne=-1),T=[Q+he*1.2,ee-.25,re+ne*1.2],N=Math.atan2(-he,-ne),I=!0}if(P&&typeof ae.getHitTestResults=="function"&&(!this.placed||U)){let j=ae.getHitTestResults(P)||[],H=!1;for(let Q of j){let ee=Q.getPose(L);if(ee?.transform?.matrix){let re=ee.transform.matrix,he=re[5];if(r.arPlacement==="wall"&&Math.abs(he)>.35||r.arPlacement==="floor"&&Math.abs(he)<.65)continue;R||(R=new Float32Array(16)),R.set(re),A=[re[12],re[13],re[14]],this.placed&&U&&(D=[re[12],re[13],re[14]]),C&&(C.visible=!this.placed||U,C.transform.set(re)),!this.placed&&u&&(u.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(R),H=!0;break}}!H&&C&&(C.visible=!1)}gi(E,this.placed?D:A||T,b,N,h*$),this.placed&&this.placedMat.set(E);let V=t.xrRigMatrix;V instanceof Float32Array&&V.length===16?xe(k,V,E):k.set(E),t.modelRootMatrix&&t.modelRootMatrix.set(k);for(let j of ge)j.onXRFrame?.(t,S,ae,L);let J=t.getGLContext?.()||t?.gl,Z=S.renderState?.baseLayer;J&&Z&&Z.framebuffer!==void 0&&J.bindFramebuffer(36160,Z.framebuffer);let K=x==="immersive-ar",B=G.views||[];for(let j=0;j<B.length;j++){let H=B[j];if(typeof t.renderXRView=="function"){let Q;if(Z&&typeof Z.getViewport=="function"){let ee=Z.getViewport(H);ee&&ee.width>0&&ee.height>0&&(Q=[ee.x,ee.y,ee.width,ee.height])}else Z?.framebufferWidth>0&&Z?.framebufferHeight>0&&(Q=[0,0,Z.framebufferWidth,Z.framebufferHeight]);t.renderXRView(H,k,this.placed,Q,K,j)}}J&&Z&&Z.framebuffer&&J.bindFramebuffer(36160,null)};S.requestAnimationFrame(oe)}catch(z){throw typeof S.end=="function"&&await S.end().catch(()=>{}),q(),r.onError?.(z),z}}async stop(){let t=this.s;if(t)try{await t.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function on(t){let e=await sn(),i=t.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let o of i)if(e.availableModes.includes(o)){r=o;break}if(r||(r=e.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let n={...t.quickLookOptions,allowScale:t.arScale==="fixed"?!1:t.quickLookOptions?.allowScale},s={...t.sceneViewerOptions,resizable:t.arScale==="fixed"?!1:t.sceneViewerOptions?.resizable,enableVerticalPlacement:t.arPlacement==="wall"?!0:t.sceneViewerOptions?.enableVerticalPlacement},a={...t.webXROptions,arScale:t.arScale||t.webXROptions?.arScale,arPlacement:t.arPlacement||t.webXROptions?.arPlacement};try{if(r==="quick-look"){let o;if(t.model instanceof Blob&&t.model.type==="model/vnd.usdz+zip")o=t.model;else{if(typeof t.model=="string")return bi(t.model,n),{mode:"quick-look",success:!0};o=rt(t.model)}return bi(o,n),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let o=t.glbUrl||(typeof t.model=="string"?t.model:null);if(!o)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return Ss(o,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!t.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let o=new xr(a);return await o.start(t.view,t.element),{mode:"webxr",success:!0,session:o}}}catch(o){return{mode:r,success:!1,error:o}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}Be.registerAR({activateAR:on,createUSDZBlob:rt}),Be.registerScriptRunner(pr),wt(Rr);
|