three-live 1.3.1 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -0
- package/dist/three-author-engine.js +89 -62
- package/dist/three-author.cjs +86 -59
- package/dist/three-author.d.ts +1 -0
- package/dist/three-author.js +86 -59
- package/dist/three-convert.cjs +79 -52
- package/dist/three-convert.d.ts +1 -0
- package/dist/three-convert.js +80 -53
- package/dist/three-live-animation.d.ts +1 -0
- package/dist/three-live-cad.cjs +2 -2
- package/dist/three-live-cad.d.ts +1 -0
- package/dist/three-live-cad.js +2 -2
- package/dist/three-live-cad.min.js +2 -2
- package/dist/three-live-element.cjs +2 -2
- package/dist/three-live-element.d.ts +1 -0
- package/dist/three-live-element.js +2 -2
- package/dist/three-live-full.cjs +94 -67
- package/dist/three-live-full.js +102 -75
- package/dist/three-live-full.min.js +95 -68
- package/dist/three-live-studio.d.ts +1 -0
- package/dist/three-live-viewer.cjs +2 -2
- package/dist/three-live-viewer.d.ts +1 -0
- package/dist/three-live-viewer.js +2 -2
- package/dist/three-live-viewer.min.js +2 -2
- package/dist/three-live.cjs +85 -58
- package/dist/three-live.js +85 -58
- package/dist/three-live.min.js +85 -58
- package/dist/three-view.d.ts +1 -0
- package/dist/three-xr.cjs +80 -53
- package/dist/three-xr.d.ts +1 -0
- package/dist/three-xr.js +83 -56
- package/package.json +19 -1
package/dist/three-xr.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/function le(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function _e(e,t,i,r,a){let s=1/Math.tan(t/2);e.fill(0),e[0]=s/i,e[5]=s,e[11]=-1;let u=1/(r-a);return e[10]=(a+r)*u,e[14]=2*a*r*u,e}function Fe(e,t,i,r){let[a,s,u]=t,[o,d,f]=r,[p,y,D]=i,S=a-p,h=s-y,v=u-D,P=Math.hypot(S,h,v);P<=1e-5?(S=0,h=0,v=1):(S/=P,h/=P,v/=P);let T=d*v-f*h,x=f*S-o*v,c=o*h-d*S;P=Math.hypot(T,x,c),P<=1e-5?(T=0,x=0,c=0):(T/=P,x/=P,c/=P);let l=h*c-v*x,b=v*T-S*c,w=S*x-h*T;return P=Math.hypot(l,b,w),P<=1e-5?(l=0,b=0,w=0):(l/=P,b/=P,w/=P),e[0]=T,e[1]=l,e[2]=S,e[3]=0,e[4]=x,e[5]=b,e[6]=h,e[7]=0,e[8]=c,e[9]=w,e[10]=v,e[11]=0,e[12]=-(T*a+x*s+c*u),e[13]=-(l*a+b*s+w*u),e[14]=-(S*a+h*s+v*u),e[15]=1,e}function me(e,t,i){let r=t[0],a=t[1],s=t[2],u=t[3],o=t[4],d=t[5],f=t[6],p=t[7],y=t[8],D=t[9],S=t[10],h=t[11],v=t[12],P=t[13],T=t[14],x=t[15],c=i[0],l=i[1],b=i[2],w=i[3];return e[0]=c*r+l*o+b*y+w*v,e[1]=c*a+l*d+b*D+w*P,e[2]=c*s+l*f+b*S+w*T,e[3]=c*u+l*p+b*h+w*x,c=i[4],l=i[5],b=i[6],w=i[7],e[4]=c*r+l*o+b*y+w*v,e[5]=c*a+l*d+b*D+w*P,e[6]=c*s+l*f+b*S+w*T,e[7]=c*u+l*p+b*h+w*x,c=i[8],l=i[9],b=i[10],w=i[11],e[8]=c*r+l*o+b*y+w*v,e[9]=c*a+l*d+b*D+w*P,e[10]=c*s+l*f+b*S+w*T,e[11]=c*u+l*p+b*h+w*x,c=i[12],l=i[13],b=i[14],w=i[15],e[12]=c*r+l*o+b*y+w*v,e[13]=c*a+l*d+b*D+w*P,e[14]=c*s+l*f+b*S+w*T,e[15]=c*u+l*p+b*h+w*x,e}function Ke(e,t,i,r){let a=t[0],s=t[1],u=t[2],o=t[3],d=a+a,f=s+s,p=u+u,y=a*d,D=a*f,S=a*p,h=s*f,v=s*p,P=u*p,T=o*d,x=o*f,c=o*p,l=r[0],b=r[1],w=r[2];return e[0]=(1-(h+P))*l,e[1]=(D+c)*l,e[2]=(S-x)*l,e[3]=0,e[4]=(D-c)*b,e[5]=(1-(y+P))*b,e[6]=(v+T)*b,e[7]=0,e[8]=(S+x)*w,e[9]=(v-T)*w,e[10]=(1-(y+h))*w,e[11]=0,e[12]=i[0],e[13]=i[1],e[14]=i[2],e[15]=1,e}function be(e,t,i=0){let r=t[0],a=t[1],s=t[2],u=t[4],o=t[5],d=t[6],f=t[8],p=t[9],y=t[10],D=y*o-d*p,S=-y*u+d*f,h=p*u-o*f,v=r*D+a*S+s*h;return!v||i>0&&(!Number.isFinite(v)||Math.abs(v)<=i)||(v=1/v,e[0]=D*v,e[1]=S*v,e[2]=h*v,e[3]=(-y*a+s*p)*v,e[4]=(y*r-s*f)*v,e[5]=(-p*r+a*f)*v,e[6]=(d*a-s*o)*v,e[7]=(-d*r+s*u)*v,e[8]=(o*r-a*u)*v),e}function Tt(e,t){let i=t[0],r=t[1],a=t[2],s=t[3],u=t[4],o=t[5],d=t[6],f=t[7],p=t[8],y=t[9],D=t[10],S=t[11],h=t[12],v=t[13],P=t[14],T=t[15],x=i*o-r*u,c=i*d-a*u,l=i*f-s*u,b=r*d-a*o,w=r*f-s*o,O=a*f-s*d,B=p*v-y*h,E=p*P-D*h,N=p*T-S*h,R=y*P-D*v,L=y*T-S*v,M=D*T-S*P,n=x*M-c*L+l*R+b*N-w*E+O*B;return n?(n=1/n,e[0]=(o*M-d*L+f*R)*n,e[1]=(a*L-r*M-s*R)*n,e[2]=(v*O-P*w+T*b)*n,e[3]=(D*w-y*O-S*b)*n,e[4]=(d*N-u*M-f*E)*n,e[5]=(i*M-a*N+s*E)*n,e[6]=(P*l-h*O-T*c)*n,e[7]=(p*O-D*l+S*c)*n,e[8]=(u*L-o*N+f*B)*n,e[9]=(r*N-i*L-s*B)*n,e[10]=(h*w-v*l+T*x)*n,e[11]=(y*l-p*w-S*x)*n,e[12]=(o*E-u*R-d*B)*n,e[13]=(i*R-r*E+a*B)*n,e[14]=(v*c-h*b-P*x)*n,e[15]=(p*b-y*c+D*x)*n,e):null}function Xe(e,t,i,r,a){let s=a[0]*t+a[4]*i+a[8]*r+a[12],u=a[1]*t+a[5]*i+a[9]*r+a[13],o=a[2]*t+a[6]*i+a[10]*r+a[14],d=a[3]*t+a[7]*i+a[11]*r+a[15],f=d!==0?1/d:1;e[0]=s*f,e[1]=u*f,e[2]=o*f}function Pt(e,t,i,r,a,s,u,o,d,f,p,y,D,S,h,v,P=0){let T=f-u,x=p-o,c=y-d,l=D-u,b=S-o,w=h-d,O=a*w-s*b,B=s*l-r*w,E=r*b-a*l,N=T*O+x*B+c*E;if(N>-1e-7&&N<1e-7)return!1;let R=1/N,L=e-u,M=t-o,n=i-d,$=R*(L*O+M*B+n*E);if($<-P||$>1+P)return!1;let W=M*c-n*x,g=n*T-L*c,_=L*x-M*T,m=R*(r*W+a*g+s*_);if(m<-P||$+m>1+P)return!1;let A=R*(l*W+b*g+w*_);if(A>1e-4&&A<v.distance){v.distance=A,v.point=[e+r*A,t+a*A,i+s*A];let q=x*w-c*b,K=c*l-T*w,H=T*b-x*l,Q=Math.hypot(q,K,H)||1;return v.normal=[q/Q,K/Q,H/Q],!0}return!1}function At(e,t){let i=Array.isArray(e?.nodes)?e.nodes.length:0,r=[];for(let p=0;p<i;p++)r.push(le());if(i===0)return r;let a=new Set;for(let p of e.nodes)if(Array.isArray(p.children))for(let y of p.children)a.add(y);let s=new Set,u=128,o=(p,y,D=0)=>{if(D>u||p<0||p>=i||s.has(p))return;s.add(p);let S=e.nodes[p];if(!S)return;let h=le();if(t&&t[p])h.set(t[p]);else if(S.matrix&&S.matrix.length===16)h.set(S.matrix);else{let P=S.translation||[0,0,0],T=S.rotation||[0,0,0,1],x=S.scale||[1,1,1];Ke(h,T,P,x)}let v=r[p];if(y?me(v,y,h):v.set(h),Array.isArray(S.children))for(let P of S.children)typeof P=="number"&&o(P,v,D+1)},d=[],f=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(f&&Array.isArray(f.nodes))d.push(...f.nodes);else for(let p=0;p<i;p++)a.has(p)||d.push(p);for(let p of d)o(p,null);for(let p=0;p<i;p++)!a.has(p)&&!d.includes(p)&&o(p,null);return r}var Pe="__THREE_LIVE_REGISTRY__";function pe(){let e=typeof globalThis<"u"?globalThis:{};if(!e[Pe]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,Pe,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[Pe]=t}}return e[Pe]}var he=pe().plugins;function Rt(e){let t=pe().plugins;t.some(i=>i.name===e.name)||t.push(e),e.onRegister?.()}function Ct(){return pe().plugins}function St(e,t,i){let r=[],a=new Map,s=[],u=[],o=[],d=new Map,f=c=>{let l=a.get(c);return l===void 0&&(l=r.length,r.push({op:c}),a.set(c,l)),l},p=c=>{let l=d.get(c);return l===void 0&&(l=o.length,o.push({id:c}),d.set(c,l)),l},y=(c,l={})=>s.push({declaration:f(c),...l})-1,D=(c,l,b)=>u.push({id:c,type:l,value:b})-1,S=c=>({node:c,socket:"value"}),h=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(h&&typeof h=="object"){let c=Array.isArray(h.graphs)?h.graphs[h.graph??0]:h;if(c&&Array.isArray(c.nodes)){let l=Array.isArray(c.declarations)?c.declarations:[];for(let b of l)b?.op&&f(b.op);Array.isArray(c.variables)&&u.push(...c.variables);for(let b of c.events||[])b?.id&&p(b.id);for(let b of c.nodes){if(!b||typeof b!="object")continue;let w=b.op||(typeof b.declaration=="number"?l[b.declaration]?.op:"");s.push(w?{...b,declaration:f(w)}:{...b})}}}let v=(c,l,b="translation")=>b==="baseColorFactor"||b==="metallicFactor"||b==="roughnessFactor"?`/materials/${Math.max(0,l)}/pbrMetallicRoughness/${b}`:b==="emissiveFactor"||b==="alphaCutoff"?`/materials/${Math.max(0,l)}/${b}`:b==="visible"?`/nodes/${c}/extensions/KHR_node_visibility/visible`:`/nodes/${c}/${b}`,P=new Map;e.forEach((c,l)=>{typeof c?.name=="string"&&!P.has(c.name)&&P.set(c.name,l)});let T=(c,l)=>typeof c.target=="string"&&P.has(c.target)?P.get(c.target):typeof c.targetNode=="number"?c.targetNode:l,x=c=>{let l=e[c];return(typeof l?.mesh=="number"?t[l.mesh]?.primitives?.[0]?.material:0)??0};for(let c=0;c<e.length;c++){let l=e[c],b=l?.extras?.interactivity;if(!b||typeof b!="object")continue;let w=(typeof l.mesh=="number"?t[l.mesh]?.primitives?.[0]?.material:0)??0,O=E=>{let N=Array.isArray(E)?E:[E],R=[];for(let M=0;M<N.length;M++){let n=N[M];if(!n||typeof n!="object")continue;let $=n.action||"interpolate",W=typeof n.duration=="number"?n.duration:.35;if($==="toggleTransform"){let g=n.property==="rotation"||n.property==="scale"?n.property:"translation",_=g==="rotation"?l.rotation||[0,0,0,1]:g==="scale"?l.scale||[1,1,1]:l.translation||[0,0,0],m=`/nodes/${c}/${g}`,A=D(`__toggle_${c}_${M}`,"bool",!1),q=y("variable/get",{configuration:{variable:A}}),K=y("math/not",{values:{a:S(q)}}),H=y("variable/set",{configuration:{variable:A},values:{value:S(K)}}),Q=y("pointer/interpolate",{configuration:{pointer:m},values:{value:{value:Array.isArray(n.to)?n.to:_},duration:{value:W}}}),C=y("pointer/interpolate",{configuration:{pointer:m},values:{value:{value:Array.isArray(n.from)?n.from:_},duration:{value:W}}});s[H].flows={out:{node:y("flow/branch",{values:{condition:S(q)},flows:{true:{node:Q},false:{node:C}}})}},R.push(H)}else if($==="interpolate"){let g=n.to??n.value;if(g===void 0)continue;let _={value:{value:g},duration:{value:W}};n.from!==void 0&&(_.from={value:n.from}),R.push(y("pointer/interpolate",{configuration:{pointer:typeof n.pointer=="string"?n.pointer:v(T(n,c),x(T(n,c)),n.property)},values:_}))}else if($==="setProperty"){if(n.value===void 0)continue;R.push(y("pointer/set",{configuration:{pointer:typeof n.pointer=="string"?n.pointer:v(T(n,c),x(T(n,c)),n.property)},values:{value:{value:n.value}}}))}else if($==="toggleVisibility"){let g=T(n,c),_=D(`__vis_${g}_${M}`,"bool",!0),m=y("variable/get",{configuration:{variable:_}}),A=y("math/not",{values:{a:S(m)}}),q=y("variable/set",{configuration:{variable:_},values:{value:S(A)}});s[q].flows={out:{node:y("pointer/set",{configuration:{pointer:`/nodes/${g}/extensions/KHR_node_visibility/visible`},values:{value:S(m)}})}},R.push(q)}else if($==="cycleMaterialColor"&&Array.isArray(n.colors)&&n.colors.length>0){let g=typeof n.duration=="number"?n.duration:.25,_=`/materials/${Math.max(0,w)}/pbrMetallicRoughness/baseColorFactor`,m=D(`__color_idx_${c}_${M}`,"int",0),A=y("variable/get",{configuration:{variable:m}}),q=y("math/add",{values:{a:S(A),b:{value:1}}}),K=y("math/rem",{values:{a:S(q),b:{value:n.colors.length}}}),H=y("variable/set",{configuration:{variable:m},values:{value:S(K)}}),Q={};for(let C=0;C<n.colors.length;C++){let U=n.colors[C],k=Array.isArray(U)&&U.length>=3?[U[0],U[1],U[2],U[3]??1]:[1,1,1,1];Q[String(C)]={node:g>0?y("pointer/interpolate",{configuration:{pointer:_},values:{value:{value:k},duration:{value:g}}}):y("pointer/set",{configuration:{pointer:_},values:{value:{value:k}}})}}s[H].flows={out:{node:y("flow/switch",{values:{selection:S(A)},flows:Q})}},R.push(H)}else if($==="playAnimation")R.push(y("animation/start",{configuration:{animation:n.animation??n.clip??0}}));else if($==="stopAnimation")R.push(y("animation/stop"));else if($==="sendEvent"){let g={};for(let[_,m]of Object.entries(n.values||{}))g[_]={value:m};R.push(y("event/send",{configuration:{event:p(String(n.event??n.id??"custom"))},values:g}))}}if(!R.length)return null;if(R.length===1)return R[0];let L={};return R.forEach((M,n)=>{L[String(n)]={node:M}}),y("flow/sequence",{flows:L})},B=(E,N,R)=>{let L=O(N);L!==null&&y(E,{...R?{configuration:R}:{},flows:{out:{node:L}}})};if(b.onSelect&&B("pointer/onSelect",b.onSelect,{nodeIndex:c}),b.onHoverIn&&B("pointer/onHoverIn",b.onHoverIn,{nodeIndex:c}),b.onHoverOut&&B("pointer/onHoverOut",b.onHoverOut,{nodeIndex:c}),b.onStart&&B("event/onStart",b.onStart),b.onReceive&&typeof b.onReceive=="object")for(let[E,N]of Object.entries(b.onReceive))B("event/receive",N,{event:p(E)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:u,events:o}],graph:0}:null}var Dt={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function We(e,t,i,r){if(!i||i.bufferView===void 0)return null;let a=e.bufferViews?.[i.bufferView];if(!a)return null;let s=Number(i.count??0);if(!Number.isInteger(s)||s<=0)return null;let u=i.componentType??5126,o=Dt[u];if(!o)throw new RangeError(`glTF accessor has unsupported componentType ${u}`);let d=o*r,f=a.byteStride&&a.byteStride>0?a.byteStride:d,p=(a.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(p)||p<0||f<d||p+(s-1)*f+d>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(u===5126&&f===d&&p%4===0)return new Float32Array(t,p,s*r);let y=new DataView(t),D=i.normalized===!0,S=new Float32Array(s*r);for(let h=0;h<s;h++){let v=p+h*f;for(let P=0;P<r;P++){let T=v+P*o,x;switch(u){case 5126:x=y.getFloat32(T,!0);break;case 5120:x=y.getInt8(T),D&&(x=Math.max(x/127,-1));break;case 5121:x=y.getUint8(T),D&&(x/=255);break;case 5122:x=y.getInt16(T,!0),D&&(x=Math.max(x/32767,-1));break;case 5123:x=y.getUint16(T,!0),D&&(x/=65535);break;default:x=y.getUint32(T,!0),D&&(x/=4294967295)}S[h*r+P]=x}}return S}function Lt(e,t){let i=Number(t.offset?.[0]??0)||0,r=Number(t.offset?.[1]??0)||0,a=Number(t.scale?.[0]??1),s=Number(t.scale?.[1]??1),u=Number(t.rotation??0)||0,o=Math.cos(u),d=Math.sin(u),f=(Number.isFinite(a)?a:1)*o,p=(Number.isFinite(a)?a:1)*d,y=-(Number.isFinite(s)?s:1)*d,D=(Number.isFinite(s)?s:1)*o;for(let S=0;S+1<e.length;S+=2){let h=e[S],v=e[S+1];e[S]=f*h+p*v+i,e[S+1]=y*h+D*v+r}}function Ee(e,t,i,r=!0){let a=[],s=null;try{for(let[u,o]of[[35633,t],[35632,i]]){let d=e.createShader(u);if(!d){if(r)throw new Error("Shader allocation failed");return null}if(a.push(d),e.shaderSource(d,o),e.compileShader(d),e.getShaderParameter&&!e.getShaderParameter(d,35713)){if(r)throw new Error(`Shader compile error: ${e.getShaderInfoLog(d)}`);return null}}if(s=e.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let u of a)e.attachShader(s,u);if(e.linkProgram(s),e.getProgramParameter&&!e.getProgramParameter(s,35714)){let u=r?e.getProgramInfoLog(s):null;if(e.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${u}`);return null}return s}finally{for(let u of a)s&&e.detachShader?.(s,u),e.deleteShader?.(u)}}var Ye=["neutral","reinhard","none","aces","agx"];function ke(e){let t=String(e??"").trim().toLowerCase();return Ye.includes(t)?t:"neutral"}function It(e){return Ye.indexOf(ke(e))}function _t(e){return new TextDecoder().decode(e)}var Ze=pe().decoders;function Ft(e,t){Ze.set(e.toLowerCase(),t)}function Me(e){return Ze.get(e.toLowerCase())}function Qe(e){let t=ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e,i=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let r=i.getUint32(0,!0);if(r!==1179937895){let D=i.getUint8(0);throw D===123||D===32||D===10||D===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 a=i.getUint32(4,!0);if(a!==2)throw new Error(`Unsupported GLB version: ${a}`);let s=i.getUint32(8,!0),u=12,o=null,d=null;for(;u+8<=s&&u+8<=t.byteLength;){let D=i.getUint32(u,!0),S=i.getUint32(u+4,!0),h=u+8;if(h+D>t.byteLength)throw new Error(`Truncated GLB chunk: required ${h+D} bytes, buffer has ${t.byteLength}`);if(S===1313821514){let v=new Uint8Array(t,h,D),P=_t(v);o=JSON.parse(P,(T,x)=>T==="__proto__"||T==="constructor"||T==="prototype"?void 0:x)}else S===5130562&&(d=t.slice(h,h+D));u=h+D}if(!o)throw new Error("Missing JSON chunk in GLB");let f=o.extensionsRequired||[];if(f.includes("KHR_draco_mesh_compression")&&!Me("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let D of["EXT_meshopt_compression","KHR_meshopt_compression"])if(f.includes(D)&&!Me("meshopt"))throw new Error(`Model requires ${D}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(f.includes("KHR_texture_basisu")&&!Me("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let p=d||new ArrayBuffer(0),y={gltf:o,bin:p,animations:[]};for(let D of he)D.onParseGLB?.(y);return y}function Et(e){return typeof e=="object"&&e!==null&&"gltf"in e&&typeof e.gltf=="object"&&e.gltf!==null&&"bin"in e&&(e.bin instanceof ArrayBuffer||ArrayBuffer.isView(e.bin))}function Ae(e){if(Et(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Qe(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var Je=`#version 300 es
|
|
16
|
+
*/function he(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function Ee(e,t,i,r,a){let s=1/Math.tan(t/2);e.fill(0),e[0]=s/i,e[5]=s,e[11]=-1;let c=1/(r-a);return e[10]=(a+r)*c,e[14]=2*a*r*c,e}function Fe(e,t,i,r){let[a,s,c]=t,[l,g,d]=r,[v,M,I]=i,D=a-v,u=s-M,x=c-I,C=Math.hypot(D,u,x);C<=1e-5?(D=0,u=0,x=1):(D/=C,u/=C,x/=C);let R=g*x-d*u,T=d*D-l*x,m=l*u-g*D;C=Math.hypot(R,T,m),C<=1e-5?(R=0,T=0,m=0):(R/=C,T/=C,m/=C);let h=u*m-x*T,w=x*R-D*m,y=D*T-u*R;return C=Math.hypot(h,w,y),C<=1e-5?(h=0,w=0,y=0):(h/=C,w/=C,y/=C),e[0]=R,e[1]=h,e[2]=D,e[3]=0,e[4]=T,e[5]=w,e[6]=u,e[7]=0,e[8]=m,e[9]=y,e[10]=x,e[11]=0,e[12]=-(R*a+T*s+m*c),e[13]=-(h*a+w*s+y*c),e[14]=-(D*a+u*s+x*c),e[15]=1,e}function fe(e,t,i){let r=t[0],a=t[1],s=t[2],c=t[3],l=t[4],g=t[5],d=t[6],v=t[7],M=t[8],I=t[9],D=t[10],u=t[11],x=t[12],C=t[13],R=t[14],T=t[15],m=i[0],h=i[1],w=i[2],y=i[3];return e[0]=m*r+h*l+w*M+y*x,e[1]=m*a+h*g+w*I+y*C,e[2]=m*s+h*d+w*D+y*R,e[3]=m*c+h*v+w*u+y*T,m=i[4],h=i[5],w=i[6],y=i[7],e[4]=m*r+h*l+w*M+y*x,e[5]=m*a+h*g+w*I+y*C,e[6]=m*s+h*d+w*D+y*R,e[7]=m*c+h*v+w*u+y*T,m=i[8],h=i[9],w=i[10],y=i[11],e[8]=m*r+h*l+w*M+y*x,e[9]=m*a+h*g+w*I+y*C,e[10]=m*s+h*d+w*D+y*R,e[11]=m*c+h*v+w*u+y*T,m=i[12],h=i[13],w=i[14],y=i[15],e[12]=m*r+h*l+w*M+y*x,e[13]=m*a+h*g+w*I+y*C,e[14]=m*s+h*d+w*D+y*R,e[15]=m*c+h*v+w*u+y*T,e}function We(e,t,i,r){let a=t[0],s=t[1],c=t[2],l=t[3],g=a+a,d=s+s,v=c+c,M=a*g,I=a*d,D=a*v,u=s*d,x=s*v,C=c*v,R=l*g,T=l*d,m=l*v,h=r[0],w=r[1],y=r[2];return e[0]=(1-(u+C))*h,e[1]=(I+m)*h,e[2]=(D-T)*h,e[3]=0,e[4]=(I-m)*w,e[5]=(1-(M+C))*w,e[6]=(x+R)*w,e[7]=0,e[8]=(D+T)*y,e[9]=(x-R)*y,e[10]=(1-(M+u))*y,e[11]=0,e[12]=i[0],e[13]=i[1],e[14]=i[2],e[15]=1,e}function ye(e,t,i=0){let r=t[0],a=t[1],s=t[2],c=t[4],l=t[5],g=t[6],d=t[8],v=t[9],M=t[10],I=M*l-g*v,D=-M*c+g*d,u=v*c-l*d,x=r*I+a*D+s*u;return!x||i>0&&(!Number.isFinite(x)||Math.abs(x)<=i)||(x=1/x,e[0]=I*x,e[1]=D*x,e[2]=u*x,e[3]=(-M*a+s*v)*x,e[4]=(M*r-s*d)*x,e[5]=(-v*r+a*d)*x,e[6]=(g*a-s*l)*x,e[7]=(-g*r+s*c)*x,e[8]=(l*r-a*c)*x),e}function Tt(e,t){let i=t[0],r=t[1],a=t[2],s=t[3],c=t[4],l=t[5],g=t[6],d=t[7],v=t[8],M=t[9],I=t[10],D=t[11],u=t[12],x=t[13],C=t[14],R=t[15],T=i*l-r*c,m=i*g-a*c,h=i*d-s*c,w=r*g-a*l,y=r*d-s*l,F=a*d-s*g,U=v*x-M*u,_=v*C-I*u,k=v*R-D*u,P=M*C-I*x,N=M*R-D*x,S=I*R-D*C,o=T*S-m*N+h*P+w*k-y*_+F*U;return o?(o=1/o,e[0]=(l*S-g*N+d*P)*o,e[1]=(a*N-r*S-s*P)*o,e[2]=(x*F-C*y+R*w)*o,e[3]=(I*y-M*F-D*w)*o,e[4]=(g*k-c*S-d*_)*o,e[5]=(i*S-a*k+s*_)*o,e[6]=(C*h-u*F-R*m)*o,e[7]=(v*F-I*h+D*m)*o,e[8]=(c*N-l*k+d*U)*o,e[9]=(r*k-i*N-s*U)*o,e[10]=(u*y-x*h+R*T)*o,e[11]=(M*h-v*y-D*T)*o,e[12]=(l*_-c*P-g*U)*o,e[13]=(i*P-r*_+a*U)*o,e[14]=(x*m-u*w-C*T)*o,e[15]=(v*w-M*m+I*T)*o,e):null}function Ke(e,t,i,r,a){let s=a[0]*t+a[4]*i+a[8]*r+a[12],c=a[1]*t+a[5]*i+a[9]*r+a[13],l=a[2]*t+a[6]*i+a[10]*r+a[14],g=a[3]*t+a[7]*i+a[11]*r+a[15],d=g!==0?1/g:1;e[0]=s*d,e[1]=c*d,e[2]=l*d}function Pt(e,t,i,r,a,s,c,l,g,d,v,M,I,D,u,x,C=0){let R=d-c,T=v-l,m=M-g,h=I-c,w=D-l,y=u-g,F=a*y-s*w,U=s*h-r*y,_=r*w-a*h,k=R*F+T*U+m*_;if(k>-1e-7&&k<1e-7)return!1;let P=1/k,N=e-c,S=t-l,o=i-g,V=P*(N*F+S*U+o*_);if(V<-C||V>1+C)return!1;let K=S*m-o*T,f=o*R-N*m,b=N*T-S*R,n=P*(r*K+a*f+s*b);if(n<-C||V+n>1+C)return!1;let p=P*(h*K+w*f+y*b);if(p>1e-4&&p<x.distance){x.distance=p,x.point=[e+r*p,t+a*p,i+s*p];let B=T*y-m*w,j=m*h-R*y,z=R*w-T*h,ee=Math.hypot(B,j,z)||1;return x.normal=[B/ee,j/ee,z/ee],!0}return!1}function At(e,t){let i=Array.isArray(e?.nodes)?e.nodes.length:0,r=[];for(let v=0;v<i;v++)r.push(he());if(i===0)return r;let a=new Set;for(let v of e.nodes)if(Array.isArray(v.children))for(let M of v.children)a.add(M);let s=new Set,c=128,l=(v,M,I=0)=>{if(I>c||v<0||v>=i||s.has(v))return;s.add(v);let D=e.nodes[v];if(!D)return;let u=he();if(t&&t[v])u.set(t[v]);else if(D.matrix&&D.matrix.length===16)u.set(D.matrix);else{let C=D.translation||[0,0,0],R=D.rotation||[0,0,0,1],T=D.scale||[1,1,1];We(u,R,C,T)}let x=r[v];if(M?fe(x,M,u):x.set(u),Array.isArray(D.children))for(let C of D.children)typeof C=="number"&&l(C,x,I+1)},g=[],d=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(d&&Array.isArray(d.nodes))g.push(...d.nodes);else for(let v=0;v<i;v++)a.has(v)||g.push(v);for(let v of g)l(v,null);for(let v=0;v<i;v++)!a.has(v)&&!g.includes(v)&&l(v,null);return r}var Ae="__THREE_LIVE_REGISTRY__";function ge(){let e=typeof globalThis<"u"?globalThis:{};if(!e[Ae]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,Ae,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[Ae]=t}}return e[Ae]}var ce=ge().plugins;function Rt(e){let t=ge().plugins;t.some(i=>i.name===e.name)||t.push(e),e.onRegister?.()}function Ct(){return ge().plugins}function St(e,t,i){let r=[],a=new Map,s=[],c=[],l=[],g=new Map,d=m=>{let h=a.get(m);return h===void 0&&(h=r.length,r.push({op:m}),a.set(m,h)),h},v=m=>{let h=g.get(m);return h===void 0&&(h=l.length,l.push({id:m}),g.set(m,h)),h},M=(m,h={})=>s.push({declaration:d(m),...h})-1,I=(m,h,w)=>c.push({id:m,type:h,value:w})-1,D=m=>({node:m,socket:"value"}),u=i?.interactivity??i?.gltfExtensions?.KHR_interactivity;if(u&&typeof u=="object"){let m=Array.isArray(u.graphs)?u.graphs[u.graph??0]:u;if(m&&Array.isArray(m.nodes)){let h=Array.isArray(m.declarations)?m.declarations:[];for(let w of h)w?.op&&d(w.op);Array.isArray(m.variables)&&c.push(...m.variables);for(let w of m.events||[])w?.id&&v(w.id);for(let w of m.nodes){if(!w||typeof w!="object")continue;let y=w.op||(typeof w.declaration=="number"?h[w.declaration]?.op:"");s.push(y?{...w,declaration:d(y)}:{...w})}}}let x=(m,h,w="translation")=>w==="baseColorFactor"||w==="metallicFactor"||w==="roughnessFactor"?`/materials/${Math.max(0,h)}/pbrMetallicRoughness/${w}`:w==="emissiveFactor"||w==="alphaCutoff"?`/materials/${Math.max(0,h)}/${w}`:w==="visible"?`/nodes/${m}/extensions/KHR_node_visibility/visible`:`/nodes/${m}/${w}`,C=new Map;e.forEach((m,h)=>{typeof m?.name=="string"&&!C.has(m.name)&&C.set(m.name,h)});let R=(m,h)=>typeof m.target=="string"&&C.has(m.target)?C.get(m.target):typeof m.targetNode=="number"?m.targetNode:h,T=m=>{let h=e[m];return(typeof h?.mesh=="number"?t[h.mesh]?.primitives?.[0]?.material:0)??0};for(let m=0;m<e.length;m++){let h=e[m],w=h?.extras?.interactivity;if(!w||typeof w!="object")continue;let y=(typeof h.mesh=="number"?t[h.mesh]?.primitives?.[0]?.material:0)??0,F=_=>{let k=Array.isArray(_)?_:[_],P=[];for(let S=0;S<k.length;S++){let o=k[S];if(!o||typeof o!="object")continue;let V=o.action||"interpolate",K=typeof o.duration=="number"?o.duration:.35;if(V==="toggleTransform"){let f=o.property==="rotation"||o.property==="scale"?o.property:"translation",b=f==="rotation"?h.rotation||[0,0,0,1]:f==="scale"?h.scale||[1,1,1]:h.translation||[0,0,0],n=`/nodes/${m}/${f}`,p=I(`__toggle_${m}_${S}`,"bool",!1),B=M("variable/get",{configuration:{variable:p}}),j=M("math/not",{values:{a:D(B)}}),z=M("variable/set",{configuration:{variable:p},values:{value:D(j)}}),ee=M("pointer/interpolate",{configuration:{pointer:n},values:{value:{value:Array.isArray(o.to)?o.to:b},duration:{value:K}}}),L=M("pointer/interpolate",{configuration:{pointer:n},values:{value:{value:Array.isArray(o.from)?o.from:b},duration:{value:K}}});s[z].flows={out:{node:M("flow/branch",{values:{condition:D(B)},flows:{true:{node:ee},false:{node:L}}})}},P.push(z)}else if(V==="interpolate"){let f=o.to??o.value;if(f===void 0)continue;let b={value:{value:f},duration:{value:K}};o.from!==void 0&&(b.from={value:o.from}),P.push(M("pointer/interpolate",{configuration:{pointer:typeof o.pointer=="string"?o.pointer:x(R(o,m),T(R(o,m)),o.property)},values:b}))}else if(V==="setProperty"){if(o.value===void 0)continue;P.push(M("pointer/set",{configuration:{pointer:typeof o.pointer=="string"?o.pointer:x(R(o,m),T(R(o,m)),o.property)},values:{value:{value:o.value}}}))}else if(V==="toggleVisibility"){let f=R(o,m),b=I(`__vis_${f}_${S}`,"bool",!0),n=M("variable/get",{configuration:{variable:b}}),p=M("math/not",{values:{a:D(n)}}),B=M("variable/set",{configuration:{variable:b},values:{value:D(p)}});s[B].flows={out:{node:M("pointer/set",{configuration:{pointer:`/nodes/${f}/extensions/KHR_node_visibility/visible`},values:{value:D(n)}})}},P.push(B)}else if(V==="cycleMaterialColor"&&Array.isArray(o.colors)&&o.colors.length>0){let f=typeof o.duration=="number"?o.duration:.25,b=`/materials/${Math.max(0,y)}/pbrMetallicRoughness/baseColorFactor`,n=I(`__color_idx_${m}_${S}`,"int",0),p=M("variable/get",{configuration:{variable:n}}),B=M("math/add",{values:{a:D(p),b:{value:1}}}),j=M("math/rem",{values:{a:D(B),b:{value:o.colors.length}}}),z=M("variable/set",{configuration:{variable:n},values:{value:D(j)}}),ee={};for(let L=0;L<o.colors.length;L++){let X=o.colors[L],J=Array.isArray(X)&&X.length>=3?[X[0],X[1],X[2],X[3]??1]:[1,1,1,1];ee[String(L)]={node:f>0?M("pointer/interpolate",{configuration:{pointer:b},values:{value:{value:J},duration:{value:f}}}):M("pointer/set",{configuration:{pointer:b},values:{value:{value:J}}})}}s[z].flows={out:{node:M("flow/switch",{values:{selection:D(p)},flows:ee})}},P.push(z)}else if(V==="playAnimation")P.push(M("animation/start",{configuration:{animation:o.animation??o.clip??0}}));else if(V==="stopAnimation")P.push(M("animation/stop"));else if(V==="sendEvent"){let f={};for(let[b,n]of Object.entries(o.values||{}))f[b]={value:n};P.push(M("event/send",{configuration:{event:v(String(o.event??o.id??"custom"))},values:f}))}}if(!P.length)return null;if(P.length===1)return P[0];let N={};return P.forEach((S,o)=>{N[String(o)]={node:S}}),M("flow/sequence",{flows:N})},U=(_,k,P)=>{let N=F(k);N!==null&&M(_,{...P?{configuration:P}:{},flows:{out:{node:N}}})};if(w.onSelect&&U("pointer/onSelect",w.onSelect,{nodeIndex:m}),w.onHoverIn&&U("pointer/onHoverIn",w.onHoverIn,{nodeIndex:m}),w.onHoverOut&&U("pointer/onHoverOut",w.onHoverOut,{nodeIndex:m}),w.onStart&&U("event/onStart",w.onStart),w.onReceive&&typeof w.onReceive=="object")for(let[_,k]of Object.entries(w.onReceive))U("event/receive",k,{event:v(_)})}return s.length?{graphs:[{declarations:r,nodes:s,variables:c,events:l}],graph:0}:null}var Dt={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Ye(e,t,i,r){if(!i||i.bufferView===void 0)return null;let a=e.bufferViews?.[i.bufferView];if(!a)return null;let s=Number(i.count??0);if(!Number.isInteger(s)||s<=0)return null;let c=i.componentType??5126,l=Dt[c];if(!l)throw new RangeError(`glTF accessor has unsupported componentType ${c}`);let g=l*r,d=a.byteStride&&a.byteStride>0?a.byteStride:g,v=(a.byteOffset||0)+(i.byteOffset||0);if(!Number.isInteger(v)||v<0||d<g||v+(s-1)*d+g>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(c===5126&&d===g&&v%4===0)return new Float32Array(t,v,s*r);let M=new DataView(t),I=i.normalized===!0,D=new Float32Array(s*r);for(let u=0;u<s;u++){let x=v+u*d;for(let C=0;C<r;C++){let R=x+C*l,T;switch(c){case 5126:T=M.getFloat32(R,!0);break;case 5120:T=M.getInt8(R),I&&(T=Math.max(T/127,-1));break;case 5121:T=M.getUint8(R),I&&(T/=255);break;case 5122:T=M.getInt16(R,!0),I&&(T=Math.max(T/32767,-1));break;case 5123:T=M.getUint16(R,!0),I&&(T/=65535);break;default:T=M.getUint32(R,!0),I&&(T/=4294967295)}D[u*r+C]=T}}return D}function Lt(e,t){let i=Number(t.offset?.[0]??0)||0,r=Number(t.offset?.[1]??0)||0,a=Number(t.scale?.[0]??1),s=Number(t.scale?.[1]??1),c=Number(t.rotation??0)||0,l=Math.cos(c),g=Math.sin(c),d=(Number.isFinite(a)?a:1)*l,v=(Number.isFinite(a)?a:1)*g,M=-(Number.isFinite(s)?s:1)*g,I=(Number.isFinite(s)?s:1)*l;for(let D=0;D+1<e.length;D+=2){let u=e[D],x=e[D+1];e[D]=d*u+v*x+i,e[D+1]=M*u+I*x+r}}function Ne(e,t,i,r=!0){let a=[],s=null;try{for(let[c,l]of[[35633,t],[35632,i]]){let g=e.createShader(c);if(!g){if(r)throw new Error("Shader allocation failed");return null}if(a.push(g),e.shaderSource(g,l),e.compileShader(g),e.getShaderParameter&&!e.getShaderParameter(g,35713)){if(r)throw new Error(`Shader compile error: ${e.getShaderInfoLog(g)}`);return null}}if(s=e.createProgram(),!s){if(r)throw new Error("Program allocation failed");return null}for(let c of a)e.attachShader(s,c);if(e.linkProgram(s),e.getProgramParameter&&!e.getProgramParameter(s,35714)){let c=r?e.getProgramInfoLog(s):null;if(e.deleteProgram?.(s),s=null,r)throw new Error(`Program link error: ${c}`);return null}return s}finally{for(let c of a)s&&e.detachShader?.(s,c),e.deleteShader?.(c)}}var Ze=["neutral","reinhard","none","aces","agx"];function Ve(e){let t=String(e??"").trim().toLowerCase();return Ze.includes(t)?t:"neutral"}function It(e){return Ze.indexOf(Ve(e))}function _t(e){return new TextDecoder().decode(e)}var Qe=ge().decoders;function kt(e,t){Qe.set(e.toLowerCase(),t)}function Te(e){return Qe.get(e.toLowerCase())}function Je(e){let t=ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e,i=new DataView(t);if(t.byteLength<12)throw new Error(`Invalid GLB buffer size: ${t.byteLength} bytes`);let r=i.getUint32(0,!0);if(r!==1179937895){let I=i.getUint8(0);throw I===123||I===32||I===10||I===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 a=i.getUint32(4,!0);if(a!==2)throw new Error(`Unsupported GLB version: ${a}`);let s=i.getUint32(8,!0),c=12,l=null,g=null;for(;c+8<=s&&c+8<=t.byteLength;){let I=i.getUint32(c,!0),D=i.getUint32(c+4,!0),u=c+8;if(u+I>t.byteLength)throw new Error(`Truncated GLB chunk: required ${u+I} bytes, buffer has ${t.byteLength}`);if(D===1313821514){let x=new Uint8Array(t,u,I),C=_t(x);l=JSON.parse(C,(R,T)=>R==="__proto__"||R==="constructor"||R==="prototype"?void 0:T)}else D===5130562&&(g=t.slice(u,u+I));c=u+I}if(!l)throw new Error("Missing JSON chunk in GLB");let d=l.extensionsRequired||[];if(d.includes("KHR_draco_mesh_compression")&&!Te("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let I of["EXT_meshopt_compression","KHR_meshopt_compression"])if(d.includes(I)&&!Te("meshopt"))throw new Error(`Model requires ${I}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(d.includes("KHR_texture_basisu")&&!Te("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let v=g||new ArrayBuffer(0),M={gltf:l,bin:v,animations:[]};for(let I of ce)I.onParseGLB?.(M);return M}function Et(e){return typeof e=="object"&&e!==null&&"gltf"in e&&typeof e.gltf=="object"&&e.gltf!==null&&"bin"in e&&(e.bin instanceof ArrayBuffer||ArrayBuffer.isView(e.bin))}function Re(e){if(Et(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Je(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var et=`#version 300 es
|
|
17
17
|
layout(location=0) in vec3 aPos;
|
|
18
18
|
layout(location=3) in vec3 aOff;
|
|
19
19
|
layout(location=1) in vec3 aNormal;
|
|
@@ -48,7 +48,7 @@ vec2 scaleUV=uUvTransform.zw;
|
|
|
48
48
|
if(scaleUV.x==0.0&&scaleUV.y==0.0)scaleUV=vec2(1.0);
|
|
49
49
|
vUV=aUV*scaleUV+uUvTransform.xy;
|
|
50
50
|
gl_Position=uMVP*vec4(aPosition,1.0);
|
|
51
|
-
}`,
|
|
51
|
+
}`,Ft=`#version 300 es
|
|
52
52
|
precision highp float;
|
|
53
53
|
in vec3 vNormal,vWorldPos;
|
|
54
54
|
in vec2 vUV;
|
|
@@ -246,12 +246,12 @@ void main(){gl_Position=uMVP*vec4(aPosition,1.0);}`,Vt=`#version 300 es
|
|
|
246
246
|
precision highp float;
|
|
247
247
|
uniform vec4 uColorId;
|
|
248
248
|
out vec4 fragColor;
|
|
249
|
-
void main(){fragColor=uColorId;}`;function Ne(e,t,i){let r={};for(let a of i)r[a]=e.getUniformLocation(t,a);return r}var et=["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 tt(){let e=pe().xrDepthShader;return{fs:kt.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...et,...e.uniformNames]:et}}function Ot(e){if(typeof e!="string")return null;let t=e.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let i=t.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:i.startsWith("https://")||i.startsWith("blob:")?t:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function Ve(e,t,i,r,a,s,u,o){if(r===void 0||!t.accessors?.[r])return null;let d=We(t,i,t.accessors[r],s);if(!d)return null;o&&(d=d.slice(),Lt(d,o));let f=e.createBuffer();return u.push(f),e.bindBuffer(34962,f),e.bufferData(34962,d,35044),e.enableVertexAttribArray(a),e.vertexAttribPointer(a,s,5126,!1,0,0),d}function Oe(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function it(e,t,i){let r=tt(),a=Je,s=r.fs,u=!1;for(let d of he)if(d.onResolveShader){let f=d.onResolveShader(t,i,a,s);f&&(a=f.vs,s=f.fs,u=!0)}let o=u?Ee(e,a,s):null;return{program:o,uniforms:o?Ne(e,o,r.uniforms):null}}function $t(e,t,i){let r=t.instanceMatrices;if(!r||r.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let a=r.length>>4,s=t.instanceColors,u=new Float32Array(a*20);for(let d=0;d<a;d++)u.set(r.subarray(d*16,d*16+16),d*20),u[d*20+16]=s?s[d*3]:1,u[d*20+17]=s?s[d*3+1]:1,u[d*20+18]=s?s[d*3+2]:1,u[d*20+19]=1;let o=e.createBuffer();i.push(o),e.bindBuffer(34962,o),e.bufferData(34962,u,35044);for(let d=0;d<5;d++)e.enableVertexAttribArray(8+d),e.vertexAttribPointer(8+d,4,5126,!1,80,d*16),e.vertexAttribDivisor(8+d,1);return!0}function Ut(e,t){let i=e.materials?.[t?.material];if(!i)return null;let r=[i.pbrMetallicRoughness?.baseColorTexture,i.pbrMetallicRoughness?.metallicRoughnessTexture,i.normalTexture,i.occlusionTexture,i.emissiveTexture];for(let a of r){let s=a?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var ti=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),rt=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Re(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function at(e,t){let i=e?.pbrMetallicRoughness,r=i?.baseColorFactor,a=e?.extensions?.KHR_materials_clearcoat,s=u=>u!==void 0&&t[u.index]?t[u.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:a?a.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,a?.clearcoatRoughnessFactor??.04),texture:s(i?.baseColorTexture),metallicRoughnessTexture:s(i?.metallicRoughnessTexture),normalTexture:s(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:s(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function st(e,t,i){let r=new Set,a=s=>{s&&!r.has(s)&&(r.add(s),e.deleteTexture(s))};for(let s of t)for(let u of s.primitives){if(u.vao&&e.deleteVertexArray(u.vao),u.buffers)for(let d of u.buffers)e.deleteBuffer(d);a(u.texture),a(u.metallicRoughnessTexture),a(u.normalTexture),a(u.occlusionTexture);let o=new Set;u.customProgram&&o.add(u.customProgram);for(let d of u.programCache?.values()??[])d.program&&o.add(d.program);for(let d of o)e.deleteProgram(d)}if(i)for(let s of i)a(s)}function nt(e,t,i=rt,r){let a={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Bt(e,t,i,r,a)}catch(s){let u=a.mesh&&!a.meshes.includes(a.mesh)?[...a.meshes,a.mesh]:a.meshes;st(e,u,a.gpuTextures),a.vao&&e.deleteVertexArray(a.vao);for(let o of a.buffers)e.deleteBuffer(o);throw s}}function Bt(e,t,i,r,a){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=t,u=Me("meshopt");u?.decodeBufferViews&&u.decodeBufferViews(s,t);let o=t.bin,d=[];a.meshes=d;let f=[],p=s.extensions?.KHR_materials_variants;p&&Array.isArray(p.variants)&&p.variants.forEach((M,n)=>{f.push(typeof M?.name=="string"&&M.name?M.name:`Variant_${n}`)});let y=At(s),D=[];if(Array.isArray(s.nodes))for(let M=0;M<s.nodes.length;M++){let n=s.nodes[M];n.mesh!==void 0&&s.meshes&&s.meshes[n.mesh]&&D.push({node:n,nodeIdx:M,meshIdx:n.mesh})}let S=D.length>0?D:(s.meshes||[]).map((M,n)=>({node:M,nodeIdx:-1,meshIdx:n})),h=[],v=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(s.asset?.extras?.lights)&&s.asset.extras.lights.length>0?s.asset.extras.lights:null;if(v)for(let M of v)h.push({...M,type:M.type||M.light_type||"point",innerConeAngle:M.innerConeAngle??M.inner_cone_angle,outerConeAngle:M.outerConeAngle??M.outer_cone_angle});else if(s.extensions?.KHR_lights_punctual?.lights){let M=s.extensions.KHR_lights_punctual.lights;for(let n of M){let $=n.type==="directional"?"directional":n.type==="point"?"point":n.type==="spot"?"spot":"ambient";h.push({type:$,color:n.color||[1,1,1],intensity:n.intensity!==void 0?n.intensity:1})}}if(h.length===0&&(h.push({type:"ambient",color:[1,1,1],intensity:.35}),h.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),S.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${S.length}`);let P=[];if(a.gpuTextures=P,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 M=0;M<s.textures.length;M++){let n=s.textures[M],$=s.images[n.source];if($){let W=e.createTexture();e.bindTexture(3553,W),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),e.texParameteri(3553,10242,10497),e.texParameteri(3553,10243,10497),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729);let g=_=>{e.bindTexture(3553,W),e.texImage2D(3553,0,6408,6408,5121,_),e.generateMipmap(3553),r?.()};if($.bufferView!==void 0){let _=s.bufferViews[$.bufferView],m=_.byteOffset||0,A=new Blob([o.slice(m,m+_.byteLength)],{type:$.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(A).then(g).catch(()=>{})}else if($.uri){let _=Ot($.uri);if(_){let m=new Image;m.crossOrigin="anonymous",m.referrerPolicy="no-referrer",m.onload=()=>g(m),m.src=_}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",$.uri)}P.push(W)}else P.push(null)}}let T=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0],c=0,l=0;for(let M=0;M<S.length;M++){let n=S[M],$=s.meshes[n.meshIdx],W=n.nodeIdx>=0?y[n.nodeIdx]:le(),g=new Float32Array(9);be(g,W);let _={name:n.node.name||$.name||`Mesh_${n.meshIdx}`,nodeIndex:n.nodeIdx,transform:W,normalMatrix:g,primitives:[],extras:n.node.extras||$.extras,...n.node?.visible===!1||n.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};a.mesh=_;let m=n.node?.extensions?.EXT_mesh_gpu_instancing;if(m&&m.attributes&&typeof m.attributes=="object"){let A=m.attributes,q=A.TRANSLATION!==void 0?s.accessors?.[A.TRANSLATION]:null,K=A.ROTATION!==void 0?s.accessors?.[A.ROTATION]:null,H=A.SCALE!==void 0?s.accessors?.[A.SCALE]:null,Q=A._COLOR_0!==void 0?s.accessors?.[A._COLOR_0]:null,C=Number(q?.count??K?.count??H?.count??0);if(!Number.isFinite(C)||C<0||C>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${C}`);if(C>0){let U=(I,J)=>{if(!I||I.bufferView===void 0||!s.bufferViews?.[I.bufferView])return null;let Y=I.componentType??5126,ae=te=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${te})`),null);if(Y!==5120&&Y!==5121&&Y!==5122&&Y!==5123&&Y!==5126)return ae(`componentType ${Y}`);if(!(Number(I.count)>=C))return ae(`count ${I.count} < ${C}`);let Z=null;try{Z=We(s,o,{...I,count:C},J)}catch{return ae("out of bounds")}return!Z||!Z.every(Number.isFinite)?ae("non-finite value"):Z},k=U(q,3),j=U(K,4),F=U(H,3),G=Q?.type==="VEC4"?4:3,V=U(Q,G),X=new Float32Array(C*16),z=le();for(let I=0;I<C;I++){let J=k?[k[I*3],k[I*3+1],k[I*3+2]]:[0,0,0],Y=j?[j[I*4],j[I*4+1],j[I*4+2],j[I*4+3]]:[0,0,0,1],ae=F?[F[I*3],F[I*3+1],F[I*3+2]]:[1,1,1];Ke(z,Y,J,ae),X.set(z,I*16)}if(_.instanceMatrices=X,V){let I=new Float32Array(C*3);for(let J=0;J<C;J++)I[J*3]=V[J*G],I[J*3+1]=V[J*G+1],I[J*3+2]=V[J*G+2];_.instanceColors=I}}}for(let A of $.primitives||[]){if(A.extensions?.KHR_draco_mesh_compression){let Z=Me("draco");Z&&Z.decodePrimitive(s,A,o)}let q=[],K=e.createVertexArray();a.vao=K,a.buffers=q,e.bindVertexArray(K);let H=$t(e,_,q),Q=s.accessors[A.attributes.POSITION],C=Number(Q?.count??0);if(!Number.isFinite(C)||C<0||c+C>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(c+=C,Q?.min&&Q?.max){let Z=te=>{for(let ie=0;ie<3;ie++){let ce=te[12+ie],re=te[12+ie];for(let se=0;se<3;se++){let ne=te[se*4+ie]*Q.min[se],oe=te[se*4+ie]*Q.max[se];ce+=ne<oe?ne:oe,re+=ne>oe?ne:oe}ce<T[ie]&&(T[ie]=ce),re>x[ie]&&(x[ie]=re)}};if(_.instanceMatrices&&_.instanceMatrices.length>=16){let te=_.instanceMatrices.length>>4,ie=le();for(let ce=0;ce<te;ce++){let re=_.instanceMatrices.subarray(ce*16,ce*16+16);me(ie,W,re),Z(ie)}}else Z(W)}let U=Ve(e,s,o,A.attributes.POSITION,0,3,q);Ve(e,s,o,A.attributes.NORMAL,1,3,q),Ve(e,s,o,A.attributes.TEXCOORD_0,2,2,q,Ut(s,A));let k=0,j=5123,F=null;if(A.indices!==void 0){let Z=s.accessors[A.indices],te=(s.bufferViews[Z.bufferView].byteOffset||0)+(Z.byteOffset||0);if(k=Number(Z.count??0),!Number.isFinite(k)||k<0||l+k>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);l+=k,j=Z.componentType===5125?5125:5123;let ie=e.createBuffer();q.push(ie),e.bindBuffer(34963,ie),Z.componentType===5125?F=new Uint32Array(o,te,Z.count):Z.componentType===5121?F=Uint16Array.from(new Uint8Array(o,te,Z.count)):F=te%2===0?new Uint16Array(o,te,Z.count):new Uint16Array(o.slice(te,te+Z.count*2)),e.bufferData(34963,F,35044)}else k=Q.count;let G={};for(let Z of he)if(Z.onBuildPrimitiveVAO){let te=Z.onBuildPrimitiveVAO(e,K,A,s,o);te&&(G[Z.name]=te)}e.bindVertexArray(null);let V=s.materials&&A.material!==void 0?s.materials[A.material]:null,{program:X,uniforms:z}=it(e,A,V),I=at(V,P),J=!!(V?.extensions?.KHR_materials_transmission||G.materials?.isTransmissive),Y=A.extensions?.KHR_materials_variants?.mappings,ae=Array.isArray(Y)?Y.filter(Z=>Z&&typeof Z.material=="number"&&Array.isArray(Z.variants)).map(Z=>({material:Z.material|0,variants:Z.variants.map(te=>Number(te)|0)})):void 0;_.primitives.push({vao:K,instanced:H,indexCount:k,indexType:j,...I,positions:U,indices:F,buffers:q,materialIndex:A.material,defaultMaterialIndex:A.material,variantMappings:ae,primitiveDef:A,programCache:new Map([[A.material??-1,{program:X,uniforms:z}]]),pluginData:G,customProgram:X,customUniforms:z,isTransmissive:J})}d.push(_)}isFinite(T[0])||(T=[-1,-1,-1]),isFinite(x[0])||(x=[1,1,1]);let b=[(T[0]+x[0])/2,(T[1]+x[1])/2,(T[2]+x[2])/2],w=x[0]-T[0],O=x[1]-T[1],B=x[2]-T[2],E=Math.max(Math.hypot(w,O,B)/2,.5),N=[T[0],T[1],T[2]],R=[x[0],x[1],x[2]],L=t.animations;if(!L){for(let M of he)if(M.onParseGLB?.(t),t.animations){L=t.animations;break}}return L||(L=[]),{meshes:d,bounds:{center:b,radius:E,min:N,max:R},lights:h,animations:L,worldMatrices:y,gpuTextures:P,availableVariants:f}}function we(e){let t=e.customTarget||e.bounds.center,i=e.currDistance*Math.cos(e.currPhi);return[t[0]+i*Math.sin(e.currTheta),t[1]+e.currDistance*Math.sin(e.currPhi),t[2]+i*Math.cos(e.currTheta)]}var ot=class{constructor(e,t,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=le(),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=le(),this.viewMatrix=le(),this.activeViewMatrix=null,this.modelMatrix=le(),this.mvpMatrix=le(),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:le(),rawValueToMeters:.001,format:0},this.container=e;let r,a;if(t&&typeof t.getContext=="function"?(r=t,a=i):(a=t,r=a?.canvas),!r){let o=e.querySelector("canvas");o||(o=document.createElement("canvas"),o.style.width="100%",o.style.height="100%",o.style.display="block",o.style.touchAction="none",e.prepend(o)),r=o}this.canvas=r,this.opts=a||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!s:s&&(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=Oe(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=ke(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 u=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!u)throw new Error("WebGL2 not supported");this.gl=u,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){Ft(e,t)}static getDecoder(e){return Me(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=tt();this.renderProg=Ee(e,Je,t.fs),this.pickProg=Ee(e,Nt,Vt),this.uRender=Ne(e,this.renderProg,t.uniforms),this.uPick=Ne(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of he)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),i=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=i,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,i,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,i),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let i=this.gl,r=Math.max(1,e),a=Math.max(1,t);this.pickFboWidth=r,this.pickFboHeight=a,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,a,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,a)}loadGLBData(e,t){let{meshes:i,bounds:r,lights:a,animations:s,worldMatrices:u,gpuTextures:o,availableVariants:d}=nt(this.gl,e,t,()=>this.render());if(this.lastGlbData=e,this.lastLimits=t,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=a,this.animations=s||[],this.worldMatrices=u||[],this.gpuTextures=o||[],this.availableVariants=d||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let y of e.gltf.nodes)this.initialNodeTransforms.push({t:y.translation?[y.translation[0],y.translation[1],y.translation[2]]:[0,0,0],r:y.rotation?[y.rotation[0],y.rotation[1],y.rotation[2],y.rotation[3]]:[0,0,0,1],s:y.scale?[y.scale[0],y.scale[1],y.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let y of he)y.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 f=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;f!==void 0&&(this.exposure=Oe(f));let p=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.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(e){this.loadGLBData(Qe(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of he)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Ae(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=Ae(e),{meshes:r}=nt(this.gl,i,rt,()=>this.render());if(t)for(let a of r)a.transform[12]+=t[0],a.transform[13]+=t[1],a.transform[14]+=t[2],be(a.normalMatrix,a.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(e,t,i,r=1){this.clearColor=[e,t,i,r]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let i=this.meshes[t],r;e instanceof Map?r=e.get(i.name)??e.get(t):Array.isArray(e)?r=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,i.name)?r=e[i.name]:Object.prototype.hasOwnProperty.call(e,t)&&(r=e[t])),r&&r.length===16&&(i.transform.set(r),be(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[],a=[],s=[],u=[],o=[],d=[];for(let f of this.lights){let p=f.color||[1,1,1],y=f.intensity!==void 0?f.intensity:1;if(f.type==="ambient")i=[p[0]*y,p[1]*y,p[2]*y];else if(f.type==="directional"&&r.length<6){let D=f.direction||[.5,1,.8];r.push(D[0],D[1],D[2]),a.push(p[0]*y,p[1]*y,p[2]*y)}else if((f.type==="point"||f.type==="spot")&&s.length<6){let D=f.position||[0,0,0];if(s.push(D[0],D[1],D[2]),u.push(p[0]*y,p[1]*y,p[2]*y),f.type==="spot"){let S=f.direction||[0,-1,0],h=Math.max(.01,Math.min(Math.PI/2,f.outerConeAngle??Math.PI/3)),v=Math.max(0,Math.min(h-1e-4,f.innerConeAngle??0));o.push(S[0],S[1],S[2]),d.push(Math.cos(v),Math.cos(h))}else o.push(0,-1,0),d.push(-2,-3)}}r.length===0&&(r.push(.5,1,.8),a.push(1,1,1)),t.uniform3fv(e.uAmbientColor,i),t.uniform1i(e.uNumDirLights,r.length/3),r.length>0&&(t.uniform3fv(e.uDirLightDir,r),t.uniform3fv(e.uDirLightColor,a)),t.uniform1i(e.uNumPointLights,s.length/3),s.length>0&&(t.uniform3fv(e.uPointLightPos,s),t.uniform3fv(e.uPointLightColor,u),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,o),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,d)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Oe(e)}getExposure(){return this.exposure}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=ke(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of he)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of he)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,i=this.currDistance;return{theta:e,phi:t,radius:i,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${i.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,i)=>{let r=this.meshes.flatMap(f=>f.primitives.filter(p=>p.materialIndex===i||e.length===1&&p.materialIndex===void 0)),a=r[0],s=a?[...a.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],u=a?a.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,o=a?a.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,d={baseColorFactor:s,metallicFactor:u,roughnessFactor:o,setBaseColorFactor:f=>{let p=[f[0],f[1],f[2],f[3]??1];d.baseColorFactor=p,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=p);for(let y of r)y.baseColor=p;this.render()},setMetallicFactor:f=>{d.metallicFactor=f,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=f);for(let p of r)p.metallic=f;this.render()},setRoughnessFactor:f=>{d.roughnessFactor=f,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=f);for(let p of r)p.roughness=f;this.render()}};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:d}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(i=>i.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",i=-1;if(t)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(e),i<0)return!1;this.activeVariantName=e}let r=this.gltf?.materials;if(!Array.isArray(r))return t;for(let a of this.meshes)for(let s of a.primitives){let u=s.defaultMaterialIndex;if(!t&&Array.isArray(s.variantMappings)){for(let d of s.variantMappings)if(Array.isArray(d.variants)&&d.variants.includes(i)){u=d.material;break}}let o=u!==void 0?r[u]:void 0;s.materialIndex=o?u:void 0,Object.assign(s,at(o,this.gpuTextures)),this.applyPrimitiveProgram(s,s.materialIndex,o??null)}return!0}applyPrimitiveProgram(e,t,i){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let r=t??-1,a=e.programCache.get(r);a||(a=it(this.gl,{...e.primitiveDef,material:t},i),e.programCache.set(r,a)),e.customProgram=a.program,e.customUniforms=a.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of he)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,i){this.customTarget=[e,t,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(i,e))}setCamera(e,t,i,r){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(e,t,i,r){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),i!==void 0&&i>0){let a=this.clampDistance(i);this.initialDistance=a,this.customDistance=!0,this.targetDistance=a,this.currDistance=a}else if(r!==void 0&&r>0){let a=this.clampDistance(this.bounds.radius*2.5/r);this.initialDistance=a,this.customDistance=!0,this.targetDistance=a,this.currDistance=a}else{this.customDistance=!1;let a=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=a,this.targetDistance=a,this.currDistance=a}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let i=le();me(i,this.projMatrix,this.viewMatrix);let[r,a,s]=e,u=t?t[0]:0,o=t?t[1]:0,d=t?t[2]:0,f=this.modelRootMatrix;f&&(r=f[0]*e[0]+f[4]*e[1]+f[8]*e[2]+f[12],a=f[1]*e[0]+f[5]*e[1]+f[9]*e[2]+f[13],s=f[2]*e[0]+f[6]*e[1]+f[10]*e[2]+f[14],t&&(u=f[0]*t[0]+f[4]*t[1]+f[8]*t[2],o=f[1]*t[0]+f[5]*t[1]+f[9]*t[2],d=f[2]*t[0]+f[6]*t[1]+f[10]*t[2]));let p=i[0]*r+i[4]*a+i[8]*s+i[12],y=i[1]*r+i[5]*a+i[9]*s+i[13],D=i[2]*r+i[6]*a+i[10]*s+i[14],S=i[3]*r+i[7]*a+i[11]*s+i[15];if(S<=1e-4)return{x:0,y:0,z:1,visible:!1};let h=p/S,v=y/S,P=D/S,T=this.canvas.getBoundingClientRect(),x=T.width||this.canvas.clientWidth||this.canvas.width||300,c=T.height||this.canvas.clientHeight||this.canvas.height||150,l=(h*.5+.5)*x,b=(-v*.5+.5)*c,w=h>=-1.1&&h<=1.1&&v>=-1.1&&v<=1.1&&P>=-1&&P<=1;if(w&&t){let[O,B,E]=we(this),N=[r-O,a-B,s-E];u*N[0]+o*N[1]+d*N[2]>.05&&(w=!1)}return{x:l,y:b,z:P,visible:w}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas,t=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=i=>{i.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=t(),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,e.setPointerCapture(i.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=t();let r=this.activePointers.get(i.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},a=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(a,s),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let u=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],o=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],d=this.customTarget?[...this.customTarget]:[...this.bounds.center],f=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;d[0]+=(-a*u[0]+s*o[0])*f,d[1]+=(-a*u[1]+s*o[1])*f,d[2]+=(-a*u[2]+s*o[2])*f,this.customTarget=d}else this.targetTheta=this.clampTheta(this.targetTheta-a*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=t(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=e.getBoundingClientRect(),a=Math.floor((i.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((i.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(a,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=t();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.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),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=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=t(),i.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(i,r,a)=>{this[a]&&(i.removeEventListener(r,this[a]),this[a]=null)},t=this.canvas;e(t,"webglcontextlost","boundContextLost"),e(t,"webglcontextrestored","boundContextRestored"),e(t,"contextmenu","boundContextMenu"),e(t,"pointerdown","boundPointerDown"),e(t,"pointermove","boundPointerMove"),e(t,"pointerup","boundPointerUp"),e(t,"wheel","boundWheel"),e(t,"keydown","boundKeyDown"),e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let i=this.canvas,r=i.getBoundingClientRect(),a=i.width||300,s=i.height||300,u=r.width>0?Math.floor((e-r.left)*(a/r.width)):Math.floor(e),o=r.height>0?Math.floor((t-r.top)*(s/r.height)):Math.floor(t);return this.performMeshPick(u,o,!1)}performMeshPick(e,t,i=!0){if(this.meshes.length===0)return null;let r=this.gl,a=Math.max(1,this.canvas.width||300),s=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,a);let u=le();me(u,this.projMatrix,this.viewMatrix);let o=[],d=Math.max(0,Math.min(a-1,e)),f=Math.max(0,Math.min(s-1,s-1-t));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==a||this.pickFboHeight!==s)&&this.resizePickingFbo(a,s),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,a,s),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16640),r.useProgram(this.pickProg);for(let b=0;b<this.meshes.length;b++){let w=this.meshes[b];if(w.visible===!1||w.isPluginMesh)continue;let O=b+1,B=(O&255)/255,E=(O>>8&255)/255,N=(O>>16&255)/255;r.uniform4f(this.uPick.uColorId,B,E,N,1),me(this.modelMatrix,this.modelRootMatrix,w.transform);let R=w.instanceMatrices;if(R&&R.length>=16){let L=R.length>>4,M=le();for(let n of w.primitives){r.bindVertexArray(n.vao);for(let $=0;$<L;$++)me(M,this.modelMatrix,R.subarray($*16,$*16+16)),me(this.mvpMatrix,u,M),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Re(r,n)}}else{me(this.mvpMatrix,u,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let L of w.primitives)r.bindVertexArray(L.vao),Re(r,L)}}let c=new Uint8Array(4);r.readPixels(d,f,1,1,6408,5121,c),r.bindFramebuffer(36160,null);let l=c[0]+(c[1]<<8)+(c[2]<<16);l>0&&l<=this.meshes.length&&(o=[this.meshes[l-1]])}o.length===0&&(o=this.meshes.filter(c=>c.visible!==!1));let p=null,y=1/0,D=[0,0,0],S=[0,1,0],[h,v,P]=we(this),T=le();for(let c of o){me(T,this.modelRootMatrix,c.transform);let l=c.instanceMatrices,b=l&&l.length>=16?l.length>>4:1;for(let w=0;w<b;w++){l&&l.length>=16?me(this.modelMatrix,T,l.subarray(w*16,w*16+16)):this.modelMatrix.set(T),me(this.mvpMatrix,u,this.modelMatrix);let O=le();if(!Tt(O,this.mvpMatrix))continue;let B=(d+.5)/a*2-1,E=(f+.5)/s*2-1,N=[0,0,0],R=[0,0,0];Xe(N,B,E,-1,O),Xe(R,B,E,1,O);let L=R[0]-N[0],M=R[1]-N[1],n=R[2]-N[2],$=Math.hypot(L,M,n)||1,W=L/$,g=M/$,_=n/$,m={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((A=>{for(let q of c.primitives){if(!q.positions)continue;let K=q.positions,H=q.indices,Q=Math.floor(H?H.length/3:K.length/9);for(let C=0;C<Q;C++){let U=H?H[C*3]:C*3,k=H?H[C*3+1]:C*3+1,j=H?H[C*3+2]:C*3+2;Pt(N[0],N[1],N[2],W,g,_,K[U*3],K[U*3+1],K[U*3+2],K[k*3],K[k*3+1],K[k*3+2],K[j*3],K[j*3+1],K[j*3+2],m,A)}}})(1e-4),isFinite(m.distance)){let A=m.point[0],q=m.point[1],K=m.point[2],H=this.modelMatrix,Q=H[0]*A+H[4]*q+H[8]*K+H[12],C=H[1]*A+H[5]*q+H[9]*K+H[13],U=H[2]*A+H[6]*q+H[10]*K+H[14],k=Q-h,j=C-v,F=U-P,G=Math.hypot(k,j,F);if(G<y){be(this.normalMatrix,this.modelMatrix);let V=this.normalMatrix,X=m.normal[0],z=m.normal[1],I=m.normal[2],J=V[0]*X+V[3]*z+V[6]*I,Y=V[1]*X+V[4]*z+V[7]*I,ae=V[2]*X+V[5]*z+V[8]*I,Z=Math.hypot(J,Y,ae)||1;J/=Z,Y/=Z,ae/=Z,J*k+Y*j+ae*F>0&&(J=-J,Y=-Y,ae=-ae),p=c,y=Math.round(G*1e3)/1e3,D=[Math.round(Q*1e3)/1e3,Math.round(C*1e3)/1e3,Math.round(U*1e3)/1e3],S=[Math.round(J*1e3)/1e3,Math.round(Y*1e3)/1e3,Math.round(ae*1e3)/1e3]}}}}if(!p)return null;let x={meshIndex:this.meshes.indexOf(p),meshName:p.name,nodeIndex:p.nodeIndex,distance:y,hitPoint:D,normal:S,screenX:e,screenY:t};if(i){for(let c of he)c.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(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,a=r?e-i:e,s=r?Math.max(1,t-i):i,u=(a+.5)/s*2-1;return Math.floor((u*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);_e(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center;Fe(this.viewMatrix,we(this),i,[0,1,0]),me(this.mvpMatrix,this.projMatrix,this.viewMatrix),be(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.floor(t.width*e)),r=Math.max(1,Math.floor(t.height*e));this.canvas.width!==i||this.canvas.height!==r?(this.canvas.width=i,this.canvas.height=r,this.resizePickingFbo(i,r),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let i of 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(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of he)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),i=this.bounds.center[0],r=this.bounds.center[2],a=this.modelRootMatrix;a[0]=e,a[1]=0,a[2]=-t,a[3]=0,a[4]=0,a[5]=1,a[6]=0,a[7]=0,a[8]=t,a[9]=0,a[10]=e,a[11]=0,a[12]=i-(e*i+t*r),a[13]=0,a[14]=r-(-t*i+e*r),a[15]=1}setVisible(e){this.isVisible=e}update(e){for(let s of he)s.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let s of he)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),a=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(a-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=a;let s={theta:i,phi:r,zoom:a,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(e,t,i,r,a=!0,s=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let u=e?.transform?.inverse?.matrix||this.viewMatrix,o=e?.projectionMatrix||this.projMatrix,d=e?.transform?.position,f=d?[d.x,d.y,d.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):i&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:u,projMatrix:o,eyePos:f,viewport:r,eye:e?.eye||"none",clear:s>0?!1:e?.eye!=="right",isAR:a})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let x=Math.max(2,this.canvas.width||2),c=Math.max(1,this.canvas.height||1),l=Math.max(1,Math.floor(x*.5)),b=Math.max(1,x-l),w=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),O=this.customTarget||this.bounds.center,[B,E,N]=we(this),R=Math.cos(this.currTheta),L=-Math.sin(this.currTheta),M=.032,n=le(),$=le(),W=[B-R*M,E,N-L*M],g=[O[0]-R*M*.25,O[1],O[2]-L*M*.25];_e(n,this.fov,l/c,.1,w),Fe($,W,g,[0,1,0]);let _=le(),m=le(),A=[B+R*M,E,N+L*M],q=[O[0]+R*M*.25,O[1],O[2]+L*M*.25];_e(_,this.fov,b/c,.1,w),Fe(m,A,q,[0,1,0]),this.render({viewMatrix:$,projMatrix:n,eyePos:W,viewport:[0,0,l,c],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:m,projMatrix:_,eyePos:A,viewport:[l,0,b,c],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,x,c);return}let t=this.gl,i=0,r=0,a=this.canvas.width,s=this.canvas.height;e?.viewport?(i=e.viewport[0],r=e.viewport[1],a=e.viewport[2],s=e.viewport[3],t.viewport(i,r,a,s)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16640));let u=le(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o,me(u,e?.projMatrix??this.projMatrix,o);let d=pe().xrDepthShader,f=It(this.toneMapping),[p,y,D]=e?e.eyePos:we(this);for(let x of he)x.onBeforeDrawScene?.(this,t,u,[p,y,D],f);let S=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&S===0)return;let h=e?.eye||"none",v=!1,P=S>0?[...this.backdropMeshes,...this.meshes]:this.meshes,T=x=>{for(let c=0;c<P.length;c++){let l=P[c];if(l.visible===!1)continue;let b=this.selectedMeshName!==""&&l.name===this.selectedMeshName;c<S||l.worldSpace===!0||l.name==="__xr_reticle__"?this.modelMatrix.set(l.transform):me(this.modelMatrix,this.modelRootMatrix,l.transform),me(this.mvpMatrix,u,this.modelMatrix),be(l.normalMatrix,this.modelMatrix);let w=l.extras?.xr?.stereo||l.userData?.xr?.stereo,O=0,B=0,E=1,N=1;w==="sbs"?(E=.5,O=h==="right"?.5:0):w==="ou"&&(N=.5,B=h==="right"?.5:0);for(let R of l.primitives){let L=!!R.isTransmissive;if(!x&&L){v=!0;continue}if(x&&!L)continue;let M=R.customProgram||this.renderProg,n=R.customUniforms||this.uRender;t.useProgram(M),t.vertexAttrib3f(3,0,0,0),n.uInstanced&&t.uniform1i(n.uInstanced,0),t.uniform1i(n.uToneMapping,f),t.uniform1f(n.uEnvIntensity,this.envIntensity),n.uExposure&&t.uniform1f(n.uExposure,this.exposure),t.uniform3f(n.uCameraPos,p,y,D),t.uniform1f(n.uEmissive,b?1:0),t.uniformMatrix4fv(n.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(n.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(n.uNormalMatrix,!1,l.normalMatrix),n.uUvTransform&&t.uniform4f(n.uUvTransform,O,B,E,N),n.uViewportSize&&t.uniform2f(n.uViewportSize,Math.max(1,a),Math.max(1,s)),d?.bind(t,n,this.xrDepthState,o,[i,r,Math.max(1,a),Math.max(1,s)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(n.uEnvironmentMap,4),t.uniform1i(n.uHasEnvironmentMap,1)):t.uniform1i(n.uHasEnvironmentMap,0),this.bindLights(n),n.uSectionEnabled&&t.uniform1i(n.uSectionEnabled,0);for(let W of he)W.onBeforeDrawPrimitive?.(t,M,R,l,this.worldMatrices||[],this.gltf);t.uniform4fv(n.uBaseColor,R.baseColor),t.uniform1f(n.uMetallic,R.metallic),t.uniform1f(n.uRoughness,R.roughness),n.uClearcoat&&t.uniform2f(n.uClearcoat,R.clearcoat??0,R.clearcoatRoughness??.04),R.texture?(t.activeTexture(33984),t.bindTexture(3553,R.texture),t.uniform1i(n.uBaseColorTexture,0),t.uniform1i(n.uHasTexture,1)):t.uniform1i(n.uHasTexture,0),R.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,R.metallicRoughnessTexture),t.uniform1i(n.uMetallicRoughnessTexture,1),t.uniform1i(n.uHasMetallicRoughnessTexture,1)):t.uniform1i(n.uHasMetallicRoughnessTexture,0),R.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,R.normalTexture),t.uniform1i(n.uNormalTexture,2),t.uniform1i(n.uHasNormalTexture,1),t.uniform1f(n.uNormalScale,R.normalScale)):t.uniform1i(n.uHasNormalTexture,0),R.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,R.occlusionTexture),t.uniform1i(n.uOcclusionTexture,3),t.uniform1i(n.uHasOcclusionTexture,1),t.uniform1f(n.uOcclusionStrength,R.occlusionStrength)):t.uniform1i(n.uHasOcclusionTexture,0),t.bindVertexArray(R.vao);let $=l.instanceMatrices;if(R.instanceCount!==void 0)t.drawElementsInstanced(4,R.indexCount,R.indexType,0,R.instanceCount);else if($&&$.length>=16&&R.instanced&&n.uInstanced&&n.uViewProj){let W=$.length>>4;t.uniform1i(n.uInstanced,1),t.uniformMatrix4fv(n.uViewProj,!1,u),R.indices?t.drawElementsInstanced(4,R.indexCount,R.indexType,0,W):t.drawArraysInstanced(4,0,R.indexCount,W),t.uniform1i(n.uInstanced,0)}else if($&&$.length>=16){let W=$.length>>4,g=l.instanceColors,_=le(),m=new Float32Array(9),A=[R.baseColor[0],R.baseColor[1],R.baseColor[2],R.baseColor[3]];for(let q=0;q<W;q++)me(_,this.modelMatrix,$.subarray(q*16,q*16+16)),me(this.mvpMatrix,u,_),be(m,_),t.uniformMatrix4fv(n.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(n.uModel,!1,_),t.uniformMatrix3fv(n.uNormalMatrix,!1,m),g&&(A[0]=R.baseColor[0]*g[q*3],A[1]=R.baseColor[1]*g[q*3+1],A[2]=R.baseColor[2]*g[q*3+2],A[3]=R.baseColor[3],t.uniform4fv(n.uBaseColor,A)),Re(t,R)}else Re(t,R)}}};if(T(!1),v){for(let x of he)x.onBeforeTransmissivePass?.(t,this);T(!0)}for(let x of he)x.onAfterRender?.(t,this,u,e?.eye??"none",[i,r,a,s],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){st(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of he)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};ot.registerPlugin=Rt,ot.getRegisteredPlugins=Ct;function Ht(e){return e+3&-4}var ee=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function lt(e,t){let i=t,r=1;for(;e.has(i);)i=`${t}_${r++}`;return e.add(i),i}function ht(e,t=0){let[i,r,a,,s,u,o,,d,f,p,,y,D,S]=Array.from({length:15},(m,A)=>ee(e[t+A],A%5===0?1:0)),h=Math.hypot(i,r,a),v=Math.hypot(s,u,o),P=Math.hypot(d,f,p);i*(u*p-f*o)-s*(r*p-f*a)+d*(r*o-u*a)<0&&(h=-h);let T=Math.abs(h)>1e-8?1/h:0,x=Math.abs(v)>1e-8?1/v:0,c=Math.abs(P)>1e-8?1/P:0,l=i*T,b=r*T,w=a*T,O=s*x,B=u*x,E=o*x,N=d*c,R=f*c,L=p*c,M=l+B+L,n=0,$=0,W=0,g=1;if(M>0){let m=.5/Math.sqrt(M+1);g=.25/m,n=(E-R)*m,$=(N-w)*m,W=(b-O)*m}else if(l>B&&l>L){let m=2*Math.sqrt(Math.max(0,1+l-B-L));m>1e-8&&(g=(E-R)/m,n=.25*m,$=(O+b)/m,W=(N+w)/m)}else if(B>L){let m=2*Math.sqrt(Math.max(0,1+B-l-L));m>1e-8&&(g=(N-w)/m,n=(O+b)/m,$=.25*m,W=(E+R)/m)}else{let m=2*Math.sqrt(Math.max(0,1+L-l-B));m>1e-8&&(g=(b-O)/m,n=(N+w)/m,$=(E+R)/m,W=.25*m)}let _=Math.hypot(n,$,W,g);return _>1e-8&&Number.isFinite(_)?(n/=_,$/=_,W/=_,g/=_):(n=0,$=0,W=0,g=1),{t:[y,D,S],r:[n,$,W,g],s:[h,v,P]}}function zt(e){let t={};return e.grab&&(t.interactable={mode:typeof e.grab=="string"?e.grab:"2-hand"},t.movable={scaleInZ:!!e.scale,minScale:typeof e.scale=="object"?e.scale.min??.1:.1,maxScale:typeof e.scale=="object"?e.scale.max??10:10}),e.billboard&&(t.billboard={mode:typeof e.billboard=="string"?e.billboard:"capsule"}),e.follow&&(t.follow={target:typeof e.follow=="object"?e.follow.mode??"head":e.follow}),e.anchor&&(t.anchor={plane:e.anchor}),e.physics&&e.physics!=="none"&&(t.rigidbody={type:e.physics}),t}var ve=(e,t,i,r)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(i,e)):r;function ut(e){let t=e?.audioEmitter??e?.spatialAudio??(typeof e?.audio=="object"&&e.audio&&("preset"in e.audio||"distanceModel"in e.audio||"coneInnerAngle"in e.audio||"maxDistance"in e.audio||"volume"in e.audio)?e.audio:typeof e?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(e.audio)?{preset:e.audio}:void 0);if(!t||typeof t=="object"&&t.enabled===!1)return null;let i=typeof t=="string"?{preset:t}:t,r=typeof i.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(i.src)?i.src:void 0,a=typeof i.preset=="string"?i.preset:void 0;return!r&&!a?null:{ae:i,src:r,preset:a,volume:ve(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function jt(e,t){e.updateMatrixWorld(!0);let i=[],r=0,a=[],s=[],u=[],o=[],d=new Set,f=[],p=[],y=new Map,D=[],S=[],h=[],v=new Map,P=[],T=[];function x(g){let _=y.get(g);if(_!==void 0)return _;_=p.length,y.set(g,_);let m=g,A=m.color?.r??.8,q=m.color?.g??.8,K=m.color?.b??.8,H=m.opacity??1,Q={baseColorFactor:[A,q,K,H],metallicFactor:m.metalness??0,roughnessFactor:m.roughness??.5},C={};if(m.map){let j="";typeof m.map=="string"?j=m.map:typeof m.map.source=="string"?j=m.map.source:typeof m.map.image=="string"&&(j=m.map.image);let F=j.trim(),G=F&&!/[\x00-\x1f\x7f\\]|\.\./.test(F)&&(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(F)||!F.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(F))?F:null;if(G){let X=v.get(G);if(X===void 0){let z=D.length;D.push({uri:G}),S.length===0&&S.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),X=h.length,h.push({sampler:0,source:z}),v.set(G,X)}Q.baseColorTexture={index:X}}let V=m.map.avgColor;Array.isArray(V)&&V.length>=3&&(C.avgColor=[V[0],V[1],V[2]])}let U={name:m.name||"",pbrMetallicRoughness:Q,doubleSided:m.side===2||!!m.doubleSided,...Object.keys(C).length>0?{extras:C}:{}};if(m.emissive&&(m.emissive.r>0||m.emissive.g>0||m.emissive.b>0)){let j=m.emissiveIntensity??1;U.emissiveFactor=[m.emissive.r*j,m.emissive.g*j,m.emissive.b*j]}let k={};return m.clearcoat&&m.clearcoat>0&&(k.KHR_materials_clearcoat={clearcoatFactor:m.clearcoat,clearcoatRoughnessFactor:m.clearcoatRoughness||0}),m.sheen&&m.sheen>0&&(k.KHR_materials_sheen={sheenColorFactor:m.sheenColor?[m.sheenColor.r,m.sheenColor.g,m.sheenColor.b]:[1,1,1],sheenRoughnessFactor:m.sheenRoughness||0}),m.transmission&&m.transmission>0&&(k.KHR_materials_transmission={transmissionFactor:m.transmission}),m.thickness&&m.thickness>0&&(k.KHR_materials_volume={thicknessFactor:m.thickness,attenuationDistance:m.attenuationDistance??1/0,attenuationColor:m.attenuationColor?[m.attenuationColor.r,m.attenuationColor.g,m.attenuationColor.b]:[1,1,1]}),m.ior!==void 0&&m.ior!==1.5&&(k.KHR_materials_ior={ior:m.ior}),m.dispersion&&m.dispersion>0&&(k.KHR_materials_dispersion={dispersion:m.dispersion}),m.iridescence&&m.iridescence>0&&(k.KHR_materials_iridescence={iridescenceFactor:m.iridescence,iridescenceIor:m.iridescenceIOR??1.3}),Object.keys(k).length>0&&(U.extensions=k),p.push(U),_}function c(g,_){let m=new Uint8Array(g.buffer,g.byteOffset,g.byteLength),A=Ht(m.byteLength),q=new Uint8Array(A);q.set(m),i.push(q);let K=a.length;return a.push({buffer:0,byteOffset:r,byteLength:m.byteLength,target:_}),r+=A,K}function l(g,_,m,A,q,K,H){let Q=c(g,m),C=s.length,U={bufferView:Q,byteOffset:0,componentType:A,count:q,type:_};return K&&(U.min=K),H&&(U.max=H),s.push(U),C}e.traverse(g=>{if(g.isLight||g.color&&g.intensity!==void 0){let _=g.matrixWorld?.elements,m=ee(_?_[12]:g.position?.x,0),A=ee(_?_[13]:g.position?.y,0),q=ee(_?_[14]:g.position?.z,0),K=g.target,H=K?.parent?K?.matrixWorld?.elements:void 0,Q=ee(H?H[12]:K?.position?.x,0),C=ee(H?H[13]:K?.position?.y,0),U=ee(H?H[14]:K?.position?.z,0),k=Q-m,j=C-A,F=U-q,G=Math.hypot(k,j,F),V=Math.max(.01,Math.min(Math.PI/2,ee(g.angle,Math.PI/3))),X=Math.max(0,Math.min(1,ee(g.penumbra,0)));T.push({type:g.type,color:[g.color.r,g.color.g,g.color.b],intensity:g.intensity,position:[m,A,q],...g.type==="spot"?{direction:G>1e-6?[k/G,j/G,F/G]:[0,-1,0],outerConeAngle:V,innerConeAngle:Math.max(0,V*(1-X)),range:Math.max(0,ee(g.distance,0))}:g.type==="point"?{range:Math.max(0,ee(g.distance,0))}:{}})}});let b=[],w=new Set([e]),O=[];if(Array.isArray(e.children))for(let g=e.children.length-1;g>=0;g--)O.push({obj:e.children[g],parentKids:b});for(;O.length>0;){let{obj:g,parentKids:_}=O.pop();if(!g||typeof g!="object"||w.has(g))continue;w.add(g),g._bakeAuthorGeometry?.(),pe().materializeDeclarativeGeometry?.(g);let m=!!(g.userData&&(g.userData.xr&&typeof g.userData.xr=="object"&&Object.keys(g.userData.xr).length>0||g.userData.interactivity&&typeof g.userData.interactivity=="object"&&Object.keys(g.userData.interactivity).length>0)),A={name:g.name||(m?`Node_${o.length}`:"")},q=ee(g.position?.x,0),K=ee(g.position?.y,0),H=ee(g.position?.z,0),Q=ee(g.quaternion?.x,0),C=ee(g.quaternion?.y,0),U=ee(g.quaternion?.z,0),k=ee(g.quaternion?.w,1),j=ee(g.scale?.x,1),F=ee(g.scale?.y,1),G=ee(g.scale?.z,1);if((q||K||H)&&(A.translation=[q,K,H]),(Q||C||U||k!==1)&&(A.rotation=[Q,C,U,k]),(j!==1||F!==1||G!==1)&&(A.scale=[j,F,G]),g.visible===!1&&(A.extensions={...A.extensions||{},KHR_node_visibility:{visible:!1}},d.add("KHR_node_visibility")),g.userData&&Object.keys(g.userData).length>0&&(A.extras=JSON.parse(JSON.stringify(g.userData,(z,I)=>{if(!(z==="__proto__"||z==="prototype"||z==="constructor"))return typeof I=="function"?void 0:I})),g.userData.xr)){let z=zt(g.userData.xr);A.extensions={...A.extensions||{},MOZ_hubs_components:z,ANDROID_xr_scenecore:z},pe().xrTraitSerializer?.gltfNode(A,g.userData.xr),d.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(g.geometry){let z=g.geometry,I=z.attributes.position;if(I&&I.count>0){let J=[1/0,1/0,1/0],Y=[-1/0,-1/0,-1/0];for(let re=0;re<I.count;re++){let se=I.getX(re),ne=I.getY(re),oe=I.getZ(re);se<J[0]&&(J[0]=se),se>Y[0]&&(Y[0]=se),ne<J[1]&&(J[1]=ne),ne>Y[1]&&(Y[1]=ne),oe<J[2]&&(J[2]=oe),oe>Y[2]&&(Y[2]=oe)}let ae={attributes:{POSITION:l(I.array,"VEC3",34962,5126,I.count,J,Y)}};if(z.attributes.normal&&(ae.attributes.NORMAL=l(z.attributes.normal.array,"VEC3",34962,5126,z.attributes.normal.count)),z.attributes.uv&&(ae.attributes.TEXCOORD_0=l(z.attributes.uv.array,"VEC2",34962,5126,z.attributes.uv.count)),z.index){let re=z.index.array instanceof Uint32Array;ae.indices=l(z.index.array,"SCALAR",34963,re?5125:5123,z.index.count)}let Z=Array.isArray(g.material)?g.material[0]:g.material;Z&&(ae.material=x(Z));let te=g.userData?.variants;if(te&&typeof te=="object"){let re=new Map;for(let se of Object.keys(te)){if(!se||se==="__proto__"||se==="constructor"||se==="prototype")continue;let ne=te[se];if(!ne||typeof ne!="object")continue;let oe=P.indexOf(se);if(oe===-1&&P.length<256&&(oe=P.length,P.push(se)),oe===-1)continue;let de=x(ne),xe=re.get(de);xe||(xe=[],re.set(de,xe)),xe.push(oe)}if(re.size>0){let se=[];for(let[ne,oe]of re.entries())se.push({material:ne,variants:oe});ae.extensions={...ae.extensions||{},KHR_materials_variants:{mappings:se}},d.add("KHR_materials_variants")}}let ie=g;if(ie.isInstancedMesh&&typeof ie.count=="number"&&ie.count>0&&ie.instanceMatrix?.array){let re=Math.min(1e4,Math.floor(ie.count)),se=ie.instanceMatrix.array,ne=new Float32Array(re*3),oe=new Float32Array(re*4),de=new Float32Array(re*3);for(let fe=0;fe<re;fe++){let{t:Le,r:Te,s:Ie}=ht(se,fe*16);ne[fe*3]=Le[0],ne[fe*3+1]=Le[1],ne[fe*3+2]=Le[2],oe[fe*4]=Te[0],oe[fe*4+1]=Te[1],oe[fe*4+2]=Te[2],oe[fe*4+3]=Te[3],de[fe*3]=Ie[0],de[fe*3+1]=Ie[1],de[fe*3+2]=Ie[2]}let xe={TRANSLATION:l(ne,"VEC3",0,5126,re),ROTATION:l(oe,"VEC4",0,5126,re),SCALE:l(de,"VEC3",0,5126,re)};if(ie.instanceColor?.array&&ie.instanceColor.array.length>=re*3){let fe=new Float32Array(ie.instanceColor.array.subarray(0,re*3));xe._COLOR_0=l(fe,"VEC3",0,5126,re)}A.extensions={...A.extensions||{},EXT_mesh_gpu_instancing:{attributes:xe}},d.add("EXT_mesh_gpu_instancing")}let ce=u.length;u.push({primitives:[ae],name:g.name,...A.extras?{extras:A.extras}:{}}),A.mesh=ce}}let V=o.length;o.push(A),f.push(g),_.push(V);let X=g.children;if(Array.isArray(X)&&X.length>0){let z=[];A.children=z;for(let I=X.length-1;I>=0;I--)O.push({obj:X[I],parentKids:z})}}for(let g=0;g<o.length;g++){let _=o[g];_.children&&_.children.length===0?delete _.children:_.children&&_.children.length>0&&(_.extras?.xr?.lod||_.extensions?.ANDROID_xr_scenecore?.lod||f[g]?.isLOD)&&(_.extensions={..._.extensions||{},MSFT_lod:{ids:[..._.children]}},d.add("MSFT_lod"))}let B=t?.animateCallback||t?.animateFn||(typeof e.userData?.animate=="function"?e.userData.animate:typeof e.__animateFn=="function"?e.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),E=[];if(typeof B=="function"&&f.length>0){let g=t?.duration??4,_=t?.fps??15,m=Math.max(2,Math.round(g*_)+1),A=new Float32Array(m),q=f.map(F=>[ee(F.position?.x,0),ee(F.position?.y,0),ee(F.position?.z,0),ee(F.quaternion?.x,0),ee(F.quaternion?.y,0),ee(F.quaternion?.z,0),ee(F.quaternion?.w,1),ee(F.scale?.x,1),ee(F.scale?.y,1),ee(F.scale?.z,1)]),K=f.map(()=>new Float32Array(m*3)),H=f.map(()=>new Float32Array(m*4)),Q=f.map(()=>new Float32Array(m*3));for(let F=0;F<m;F++){let G=F/(m-1)*g;A[F]=G;try{B(G)}catch{}for(let V=0;V<f.length;V++){let X=f[V];K[V][F*3]=ee(X.position?.x,0),K[V][F*3+1]=ee(X.position?.y,0),K[V][F*3+2]=ee(X.position?.z,0);let z=ee(X.quaternion?.x,0),I=ee(X.quaternion?.y,0),J=ee(X.quaternion?.z,0),Y=ee(X.quaternion?.w,1),ae=Math.hypot(z,I,J,Y)||1;if(z/=ae,I/=ae,J/=ae,Y/=ae,F>0){let Z=(F-1)*4,te=H[V];te[Z]*z+te[Z+1]*I+te[Z+2]*J+te[Z+3]*Y<0&&(z=-z,I=-I,J=-J,Y=-Y)}H[V][F*4]=z,H[V][F*4+1]=I,H[V][F*4+2]=J,H[V][F*4+3]=Y,Q[V][F*3]=ee(X.scale?.x,1),Q[V][F*3+1]=ee(X.scale?.y,1),Q[V][F*3+2]=ee(X.scale?.z,1)}}for(let F=0;F<f.length;F++){let G=f[F],V=q[F];G.position?.set(V[0],V[1],V[2]),G.quaternion?.set(V[3],V[4],V[5],V[6]),G.scale?.set(V[7],V[8],V[9])}e.updateMatrixWorld(!0);let C=null,U=()=>(C===null&&(C=l(A,"SCALAR",0,5126,m,[0],[g])),C),k=[],j=[];for(let F=0;F<f.length;F++){let G=q[F],V=(z,I,J)=>z.some((Y,ae)=>Math.abs(Y-G[J+ae%I])>1e-4),X=(z,I,J,Y)=>{z&&j.push({sampler:k.push({input:U(),interpolation:"LINEAR",output:l(I,J,0,5126,m)})-1,target:{node:F,path:Y}})};X(V(K[F],3,0),K[F],"VEC3","translation"),X(V(H[F],4,3),H[F],"VEC4","rotation"),X(V(Q[F],3,7),Q[F],"VEC3","scale")}j.length>0&&E.push({name:"ProceduralLoop",samplers:k,channels:j})}let N=St(o,u,e.userData),R=[],L=[],M=[];for(let g=0;g<o.length;g++){let _=o[g],m=ut(_.extras?.xr);if(!m)continue;let{ae:A,src:q,preset:K,volume:H,loop:Q,isGlobal:C}=m,U=_.name||`Node_${g}`,k=L.length;L.push({name:`${U}_source`,gain:H,loop:Q,autoPlay:typeof A.autoplay=="boolean"?A.autoplay:!0,...q!==void 0?{audio:R.push({uri:q})-1}:{},...K?{extras:{preset:K,pitch:ve(A.pitch,.25,4,1)}}:{}});let j=M.length,F=ve(A.refDistance,.05,100,1),G=ve(A.coneInnerAngle,0,360,360),V=ve(A.coneOuterAngle,G,360,360);M.push({name:`${U}_emitter`,type:C?"global":"positional",gain:H,sources:[k],...C?{}:{positional:{distanceModel:A.distanceModel==="linear"||A.distanceModel==="exponential"?A.distanceModel:"inverse",refDistance:F,maxDistance:ve(A.maxDistance,F,500,Math.max(F,25)),rolloffFactor:ve(A.rolloffFactor,0,10,1),coneInnerAngle:+(G*Math.PI/180).toFixed(6),coneOuterAngle:+(V*Math.PI/180).toFixed(6),coneOuterGain:ve(A.coneOuterGain,0,1,0)}}}),_.extensions={..._.extensions||{},KHR_audio_emitter:{emitter:j}},d.add("KHR_audio_emitter")}let n={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity}},scenes:[{nodes:b}],scene:0,nodes:o,meshes:u,materials:p,...D.length>0?{images:D}:{},...S.length>0?{samplers:S}:{},...h.length>0?{textures:h}:{},accessors:s,bufferViews:a,buffers:[{byteLength:r}],...E.length>0?{animations:E}:{},...N||d.size>0?{extensionsUsed:[...N?["KHR_interactivity"]:[],...d]}:{},...N||P.length>0||M.length>0?{extensions:{...N?{KHR_interactivity:N}:{},...P.length>0?{KHR_materials_variants:{variants:P.map(g=>({name:g}))}}:{},...M.length>0?{KHR_audio_emitter:{...R.length>0?{audio:R}:{},sources:L,emitters:M}}:{}}}:{}},$=new Uint8Array(r),W=0;for(let g of i)$.set(g,W),W+=g.byteLength;return[{gltf:n,bin:$.buffer,lights:T,environmentIntensity:e.environmentIntensity},f]}function ct(e){return new TextEncoder().encode(e)}function qt(e,t){let[i,r]=jt(e,t);return $e(i,r)}function $e(e,t){let i=[],r=e.gltf,a=pe().decoders.get("meshopt");a&&typeof a.decodeBufferViews=="function"&&a.decodeBufferViews(r,e);let s=e.bin,u=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),o=r.accessors||[],d=r.bufferViews||[],f=r.materials||[],p=r.meshes||[],y=r.nodes||[],D=new Set,S=f.map((P,T)=>lt(D,Ce(P?.name,`Material_${T}`)));function h(P){let T=o[P];if(!T)throw new Error(`Accessor ${P} not found`);let x=d[T.bufferView||0],c=(x.byteOffset||0)+(T.byteOffset||0),l=x.byteLength||0;return{acc:T,buffer:u.slice(c,c+l)}}function v(P,T,x,c){let l=[],b=p[P];if(!b)return l;let w=b.primitives||[];for(let O=0;O<w.length;O++){let B=w[O],E=B.attributes?.POSITION;if(E===void 0)continue;let{acc:N,buffer:R}=h(E),L=new Float32Array(R,0,N.count*3),M,n=B.attributes?.NORMAL;if(n!==void 0){let{acc:k,buffer:j}=h(n),F=new Float32Array(j,0,k.count*3);M=new Float32Array(F.length);for(let G=0;G<k.count;G++){let V=F[G*3],X=F[G*3+1],z=F[G*3+2],I=Math.hypot(V,X,z)||1;M[G*3]=V/I,M[G*3+1]=X/I,M[G*3+2]=z/I}}let $,W=B.attributes?.TEXCOORD_0;if(W!==void 0){let{acc:k,buffer:j}=h(W);$=new Float32Array(j,0,k.count*2)}let g;if(B.indices!==void 0){let{acc:k,buffer:j}=h(B.indices);g=k.componentType===5125?new Uint32Array(j,0,k.count):new Uint16Array(j,0,k.count);let F=N.count;for(let G of g)if(G>=F)throw new Error(`SecurityError: Index buffer value (${G}) out of vertex bounds [0, ${F}).`)}else{let k=N.count;g=k>65535?new Uint32Array(k):new Uint16Array(k);for(let j=0;j<k;j++)g[j]=j}let _="DefaultMaterial",m=[.8,.8,.8],A=.5,q=0,K=0,H=0,Q=1.5,C=1,U=[0,0,0];if(B.material!==void 0&&f[B.material]){let k=f[B.material];_=S[B.material]||`Material_${B.material}`;let j=k.pbrMetallicRoughness||{},F=(z,I)=>Array.isArray(z)&&z.length>=3?[z[0],z[1],z[2]]:I;m=F(j.baseColorFactor,[1,1,1]);let G=k.extras?.avgColor;Array.isArray(G)&&G.length>=3&&(m=[m[0]*G[0],m[1]*G[1],m[2]*G[2]]);let V=Array.isArray(j.baseColorFactor)&&typeof j.baseColorFactor[3]=="number"?j.baseColorFactor[3]:1;typeof j.roughnessFactor=="number"&&(A=j.roughnessFactor),typeof j.metallicFactor=="number"&&(q=j.metallicFactor),U=F(k.emissiveFactor,[0,0,0]);let X=k.extensions||{};X.KHR_materials_clearcoat&&(K=X.KHR_materials_clearcoat.clearcoatFactor??0,H=X.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof X.KHR_materials_ior?.ior=="number"&&(Q=X.KHR_materials_ior.ior),C=V*(1-(X.KHR_materials_transmission?.transmissionFactor??0))}l.push({name:w.length>1?`${T}_p${O}`:T,positions:L,indices:g,normals:M,uvs:$,materialName:_,color:m,roughness:A,metallic:q,clearcoat:K,clearcoatRoughness:H,ior:Q,opacity:C,emissiveColor:U,xrTraits:x||b.extras?.xr,...c?{invisible:!0}:{}})}return l}if(y.length>0){let P=new Float32Array(0),T=new Uint16Array(0),x=(L,M)=>{if(L===void 0)return null;let{acc:n,buffer:$}=h(L);return new Float32Array($,0,n.count*M)},c=(L,M)=>Array.isArray(L)&&L.length>=3?[ee(L[0],M),ee(L[1],M),ee(L[2],M)]:[M,M,M],l=(L,M,n)=>L&&L.length>=(M+1)*3?[L[M*3],L[M*3+1],L[M*3+2]]:n,b=(L,M,n)=>L&&L.length>=(M+1)*4?[L[M*4],L[M*4+1],L[M*4+2],L[M*4+3]]:n,w=new Map,O=r.animations?.[0];if(O&&Array.isArray(O.channels)&&Array.isArray(O.samplers))for(let L of O.channels){let M=O.samplers[L?.sampler],n=L?.target?.node,$=L?.target?.path;if(!M||typeof n!="number"||M.input===void 0)continue;let W=w.get(n);W||(W={input:M.input},w.set(n,W)),$==="translation"?W.t=M.output:$==="rotation"?W.r=M.output:$==="scale"&&(W.s=M.output)}let B=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(B)||B.length===0){let L=new Set;for(let M of y)if(Array.isArray(M?.children))for(let n of M.children)L.add(n);B=[];for(let M=0;M<y.length;M++)L.has(M)||B.push(M);B.length===0&&(B=[0])}let E=new Set,N=[],R=(L,M)=>{if(Array.isArray(L))for(let n=L.length-1;n>=0;n--)N.push({idx:L[n],out:M})};for(R(B,i);N.length>0;){let{idx:L,out:M}=N.pop();if(typeof L!="number"||L<0||L>=y.length||E.has(L))continue;E.add(L);let n=y[L];if(!n)continue;let $=[0,0,0],W=[0,0,0,1],g=[1,1,1];if(Array.isArray(n.matrix)&&n.matrix.length===16){let C=ht(n.matrix);$=C.t,W=C.r,g=C.s}else $=c(n.translation,0),Array.isArray(n.rotation)&&n.rotation.length>=4&&(W=[ee(n.rotation[0],0),ee(n.rotation[1],0),ee(n.rotation[2],0),ee(n.rotation[3],1)]),g=c(n.scale,1);let _,m=w.get(L);if(m){let C=x(m.input,1);if(C&&C.length>0){let U=x(m.t,3),k=x(m.r,4),j=x(m.s,3),F=Array.from(C),G=[],V=[],X=[];for(let z=0;z<C.length;z++)G.push(l(U,z,$)),V.push(b(k,z,W)),X.push(l(j,z,g));_={times:F,translations:G,rotations:V,scales:X}}}let A=Array.isArray(n.children)?n.children:[],q=typeof n.mesh=="number"&&n.mesh>=0&&n.mesh<p.length,K=t?.[L]?.userData?.xr??n.extras?.xr;if(!q&&A.length===0&&(n.camera!==void 0||n.extensions?.KHR_lights_punctual||!n.name&&!n.extras&&!K&&!_))continue;let H=(C,U,k)=>({name:C,positions:P,indices:T,isXform:!0,xrTraits:K,timeSamples:_,translation:$,rotation:W,scale:g,children:U,...k?{invisible:!0}:{}}),Q=n.visible===!1||n.extensions?.KHR_node_visibility?.visible===!1||t?.[L]?.visible===!1;if(q){let C=n.name||p[n.mesh]?.name||`Mesh_${L}`,U=v(n.mesh,C,K,Q),k=n.extensions?.EXT_mesh_gpu_instancing?.attributes;if(k&&typeof k=="object"&&U.length>0){let j=x(k.TRANSLATION,3),F=x(k.ROTATION,4),G=x(k.SCALE,3),V=x(k._COLOR_0,3),X=Math.min(1e3,j?j.length/3:F?F.length/4:G?G.length/3:0);if(X>0){let z=[];for(let I=0;I<X;I++){let J=l(j,I,[0,0,0]),Y=b(F,I,[0,0,0,1]),ae=l(G,I,[1,1,1]);for(let Z of U){let te=Z.color||[.8,.8,.8],ie=V&&V.length>=(I+1)*3;z.push({...Z,name:`${Z.name}_${I}`,materialName:ie?`${Z.materialName}_inst_${I}`:Z.materialName,color:ie?[te[0]*V[I*3],te[1]*V[I*3+1],te[2]*V[I*3+2]]:Z.color,translation:J,rotation:Y,scale:ae})}}R(A,z),M.push(H(C,z,Q));continue}}if(U.length===1)U[0].translation=$,U[0].rotation=W,U[0].scale=g,U[0].timeSamples=_,A.length>0&&(U[0].children=[],R(A,U[0].children)),M.push(U[0]);else{let j=[...U];R(A,j),M.push(H(C,j,Q))}}else{let C=[];R(A,C),M.push(H(n.name||`Group_${L}`,C,Q))}}}else for(let P=0;P<p.length;P++){let T=p[P].name||`Mesh_${P}`;i.push(...v(P,T,p[P].extras?.xr))}return i}function Ce(e,t){if(!e||typeof e!="string")return t;let i=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(i)&&(i="_"+i),i||t}function Ue(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ue(e){if(!Number.isFinite(e)||Math.abs(e)<1e-7)return"0";let t=Number(e.toFixed(5)).toString();return t.indexOf(".")===-1?`${t}.0`:t}var ge=(e,t,i)=>`(${ue(e)}, ${ue(t)}, ${ue(i)})`,mt=(e,t,i,r)=>`(${ue(e)}, ${ue(t)}, ${ue(i)}, ${ue(r)})`;function ft(e){let t=e.length/3,i=new Array(t);for(let r=0;r<t;r++)i[r]=ge(e[r*3],e[r*3+1],e[r*3+2]);return i.join(", ")}function Gt(e,t){let i=new Array(t);for(let r=0;r<t;r++)i[r]=`(${ue(e[r*2])}, ${ue(1-e[r*2+1])})`;return i.join(", ")}function Kt(e){return Array.from(e).join(", ")}function Be(e){let t=new Map,i=0,r=null,a=[...e];for(;a.length>0;){let h=a.pop();if(!h.isXform&&h.positions&&h.positions.length>0){let v=Ce(h.materialName,"DefaultMaterial");t.has(v)||t.set(v,{color:h.color||[.8,.8,.8],roughness:h.roughness??.5,metallic:h.metallic??0,clearcoat:h.clearcoat??0,clearcoatRoughness:h.clearcoatRoughness??0,ior:h.ior??1.5,opacity:h.opacity??1,emissiveColor:h.emissiveColor||[0,0,0]})}if(h.timeSamples&&h.timeSamples.times.length>0){let v=h.timeSamples.times[h.timeSamples.times.length-1];v>i&&(i=v)}if(h.xrTraits?.anchor&&!r&&(r=h.xrTraits.anchor==="vertical"||h.xrTraits.anchor==="wall"?"vertical":"horizontal"),h.children)for(let v=h.children.length-1;v>=0;v--)a.push(h.children[v])}let s="";i>0&&(s=`startTimeCode = 0
|
|
250
|
-
endTimeCode = ${
|
|
249
|
+
void main(){fragColor=uColorId;}`;function $e(e,t,i){let r={};for(let a of i)r[a]=e.getUniformLocation(t,a);return r}var tt=["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 it(){let e=ge().xrDepthShader;return{fs:Ft.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...tt,...e.uniformNames]:tt}}function $t(e){if(typeof e!="string")return null;let t=e.trim();if(!t||/[\x00-\x1f\x7f]/.test(t))return null;let i=t.toLowerCase();return i.startsWith("data:")?/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(t)?t:null:i.startsWith("https://")||i.startsWith("blob:")?t:i.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(t)||/(^|[\\/])\.\.([\\/]|$)/.test(t)?null:t}function Oe(e,t,i,r,a,s,c,l){if(r===void 0||!t.accessors?.[r])return null;let g=Ye(t,i,t.accessors[r],s);if(!g)return null;l&&(g=g.slice(),Lt(g,l));let d=e.createBuffer();return c.push(d),e.bindBuffer(34962,d),e.bufferData(34962,g,35044),e.enableVertexAttribArray(a),e.vertexAttribPointer(a,s,5126,!1,0,0),g}function Ue(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function rt(e,t,i){let r=it(),a=et,s=r.fs,c=!1;for(let g of ce)if(g.onResolveShader){let d=g.onResolveShader(t,i,a,s);d&&(a=d.vs,s=d.fs,c=!0)}let l=c?Ne(e,a,s):null;return{program:l,uniforms:l?$e(e,l,r.uniforms):null}}function Ot(e,t,i){let r=t.instanceMatrices;if(!r||r.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let a=r.length>>4,s=t.instanceColors,c=new Float32Array(a*20);for(let g=0;g<a;g++)c.set(r.subarray(g*16,g*16+16),g*20),c[g*20+16]=s?s[g*3]:1,c[g*20+17]=s?s[g*3+1]:1,c[g*20+18]=s?s[g*3+2]:1,c[g*20+19]=1;let l=e.createBuffer();i.push(l),e.bindBuffer(34962,l),e.bufferData(34962,c,35044);for(let g=0;g<5;g++)e.enableVertexAttribArray(8+g),e.vertexAttribPointer(8+g,4,5126,!1,80,g*16),e.vertexAttribDivisor(8+g,1);return!0}function Ut(e,t){let i=e.materials?.[t?.material];if(!i)return null;let r=[i.pbrMetallicRoughness?.baseColorTexture,i.pbrMetallicRoughness?.metallicRoughnessTexture,i.normalTexture,i.occlusionTexture,i.emissiveTexture];for(let a of r){let s=a?.extensions?.KHR_texture_transform;if(s&&typeof s=="object")return s}return null}var ti=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),at=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function Ce(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function st(e,t){let i=e?.pbrMetallicRoughness,r=i?.baseColorFactor,a=e?.extensions?.KHR_materials_clearcoat,s=c=>c!==void 0&&t[c.index]?t[c.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:a?a.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,a?.clearcoatRoughnessFactor??.04),texture:s(i?.baseColorTexture),metallicRoughnessTexture:s(i?.metallicRoughnessTexture),normalTexture:s(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:s(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function nt(e,t,i){let r=new Set,a=s=>{s&&!r.has(s)&&(r.add(s),e.deleteTexture(s))};for(let s of t)for(let c of s.primitives){if(c.vao&&e.deleteVertexArray(c.vao),c.buffers)for(let g of c.buffers)e.deleteBuffer(g);a(c.texture),a(c.metallicRoughnessTexture),a(c.normalTexture),a(c.occlusionTexture);let l=new Set;c.customProgram&&l.add(c.customProgram);for(let g of c.programCache?.values()??[])g.program&&l.add(g.program);for(let g of l)e.deleteProgram(g)}if(i)for(let s of i)a(s)}function ot(e,t,i=at,r){let a={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return Bt(e,t,i,r,a)}catch(s){let c=a.mesh&&!a.meshes.includes(a.mesh)?[...a.meshes,a.mesh]:a.meshes;nt(e,c,a.gpuTextures),a.vao&&e.deleteVertexArray(a.vao);for(let l of a.buffers)e.deleteBuffer(l);throw s}}function Bt(e,t,i,r,a){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:s}=t,c=Te("meshopt");c?.decodeBufferViews&&c.decodeBufferViews(s,t);let l=t.bin,g=[];a.meshes=g;let d=[],v=s.extensions?.KHR_materials_variants;v&&Array.isArray(v.variants)&&v.variants.forEach((S,o)=>{d.push(typeof S?.name=="string"&&S.name?S.name:`Variant_${o}`)});let M=At(s),I=[];if(Array.isArray(s.nodes))for(let S=0;S<s.nodes.length;S++){let o=s.nodes[S];o.mesh!==void 0&&s.meshes&&s.meshes[o.mesh]&&I.push({node:o,nodeIdx:S,meshIdx:o.mesh})}let D=I.length>0?I:(s.meshes||[]).map((S,o)=>({node:S,nodeIdx:-1,meshIdx:o})),u=[],x=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(s.asset?.extras?.lights)&&s.asset.extras.lights.length>0?s.asset.extras.lights:null;if(x)for(let S of x)u.push({...S,type:S.type||S.light_type||"point",innerConeAngle:S.innerConeAngle??S.inner_cone_angle,outerConeAngle:S.outerConeAngle??S.outer_cone_angle});else if(s.extensions?.KHR_lights_punctual?.lights){let S=s.extensions.KHR_lights_punctual.lights;for(let o of S){let V=o.type==="directional"?"directional":o.type==="point"?"point":o.type==="spot"?"spot":"ambient";u.push({type:V,color:o.color||[1,1,1],intensity:o.intensity!==void 0?o.intensity:1})}}if(u.length===0&&(u.push({type:"ambient",color:[1,1,1],intensity:.35}),u.push({type:"directional",color:[1,1,1],intensity:.85,direction:[.5,1,.8]})),D.length>i.maxMeshes)throw new Error(`SecurityError: GLB scene exceeds host mesh limit (${i.maxMeshes}). Found: ${D.length}`);let C=[];if(a.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 S=0;S<s.textures.length;S++){let o=s.textures[S],V=s.images[o.source];if(V){let K=e.createTexture();e.bindTexture(3553,K),e.texImage2D(3553,0,6408,1,1,0,6408,5121,new Uint8Array([255,255,255,255])),e.texParameteri(3553,10242,10497),e.texParameteri(3553,10243,10497),e.texParameteri(3553,10241,9729),e.texParameteri(3553,10240,9729);let f=b=>{e.bindTexture(3553,K),e.texImage2D(3553,0,6408,6408,5121,b),e.generateMipmap(3553),r?.()};if(V.bufferView!==void 0){let b=s.bufferViews[V.bufferView],n=b.byteOffset||0,p=new Blob([l.slice(n,n+b.byteLength)],{type:V.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(p).then(f).catch(()=>{})}else if(V.uri){let b=$t(V.uri);if(b){let n=new Image;n.crossOrigin="anonymous",n.referrerPolicy="no-referrer",n.onload=()=>f(n),n.src=b}else console.warn("[Three-Live Security] Blocked unsafe glTF image URI:",V.uri)}C.push(K)}else C.push(null)}}let R=[1/0,1/0,1/0],T=[-1/0,-1/0,-1/0],m=0,h=0;for(let S=0;S<D.length;S++){let o=D[S],V=s.meshes[o.meshIdx],K=o.nodeIdx>=0?M[o.nodeIdx]:he(),f=new Float32Array(9);ye(f,K);let b={name:o.node.name||V.name||`Mesh_${o.meshIdx}`,nodeIndex:o.nodeIdx,transform:K,normalMatrix:f,primitives:[],extras:o.node.extras||V.extras,...o.node?.visible===!1||o.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};a.mesh=b;let n=o.node?.extensions?.EXT_mesh_gpu_instancing;if(n&&n.attributes&&typeof n.attributes=="object"){let p=n.attributes,B=p.TRANSLATION!==void 0?s.accessors?.[p.TRANSLATION]:null,j=p.ROTATION!==void 0?s.accessors?.[p.ROTATION]:null,z=p.SCALE!==void 0?s.accessors?.[p.SCALE]:null,ee=p._COLOR_0!==void 0?s.accessors?.[p._COLOR_0]:null,L=Number(B?.count??j?.count??z?.count??0);if(!Number.isFinite(L)||L<0||L>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${L}`);if(L>0){let X=(A,E)=>{if(!A||A.bufferView===void 0||!s.bufferViews?.[A.bufferView])return null;let H=A.componentType??5126,W=Q=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${Q})`),null);if(H!==5120&&H!==5121&&H!==5122&&H!==5123&&H!==5126)return W(`componentType ${H}`);if(!(Number(A.count)>=L))return W(`count ${A.count} < ${L}`);let Z=null;try{Z=Ye(s,l,{...A,count:L},E)}catch{return W("out of bounds")}return!Z||!Z.every(Number.isFinite)?W("non-finite value"):Z},J=X(B,3),ae=X(j,4),$=X(z,3),te=ee?.type==="VEC4"?4:3,O=X(ee,te),G=new Float32Array(L*16),q=he();for(let A=0;A<L;A++){let E=J?[J[A*3],J[A*3+1],J[A*3+2]]:[0,0,0],H=ae?[ae[A*4],ae[A*4+1],ae[A*4+2],ae[A*4+3]]:[0,0,0,1],W=$?[$[A*3],$[A*3+1],$[A*3+2]]:[1,1,1];We(q,H,E,W),G.set(q,A*16)}if(b.instanceMatrices=G,O){let A=new Float32Array(L*3);for(let E=0;E<L;E++)A[E*3]=O[E*te],A[E*3+1]=O[E*te+1],A[E*3+2]=O[E*te+2];b.instanceColors=A}}}for(let p of V.primitives||[]){if(p.extensions?.KHR_draco_mesh_compression){let Z=Te("draco");Z&&Z.decodePrimitive(s,p,l)}let B=[],j=e.createVertexArray();a.vao=j,a.buffers=B,e.bindVertexArray(j);let z=Ot(e,b,B),ee=s.accessors[p.attributes.POSITION],L=Number(ee?.count??0);if(!Number.isFinite(L)||L<0||m+L>i.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${i.maxVertices}).`);if(m+=L,ee?.min&&ee?.max){let Z=Q=>{for(let Y=0;Y<3;Y++){let le=Q[12+Y],re=Q[12+Y];for(let se=0;se<3;se++){let ne=Q[se*4+Y]*ee.min[se],oe=Q[se*4+Y]*ee.max[se];le+=ne<oe?ne:oe,re+=ne>oe?ne:oe}le<R[Y]&&(R[Y]=le),re>T[Y]&&(T[Y]=re)}};if(b.instanceMatrices&&b.instanceMatrices.length>=16){let Q=b.instanceMatrices.length>>4,Y=he();for(let le=0;le<Q;le++){let re=b.instanceMatrices.subarray(le*16,le*16+16);fe(Y,K,re),Z(Y)}}else Z(K)}let X=Oe(e,s,l,p.attributes.POSITION,0,3,B);Oe(e,s,l,p.attributes.NORMAL,1,3,B),Oe(e,s,l,p.attributes.TEXCOORD_0,2,2,B,Ut(s,p));let J=0,ae=5123,$=null;if(p.indices!==void 0){let Z=s.accessors[p.indices],Q=(s.bufferViews[Z.bufferView].byteOffset||0)+(Z.byteOffset||0);if(J=Number(Z.count??0),!Number.isFinite(J)||J<0||h+J>i.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${i.maxIndices}).`);h+=J,ae=Z.componentType===5125?5125:5123;let Y=e.createBuffer();B.push(Y),e.bindBuffer(34963,Y),Z.componentType===5125?$=new Uint32Array(l,Q,Z.count):Z.componentType===5121?$=Uint16Array.from(new Uint8Array(l,Q,Z.count)):$=Q%2===0?new Uint16Array(l,Q,Z.count):new Uint16Array(l.slice(Q,Q+Z.count*2)),e.bufferData(34963,$,35044)}else J=ee.count;let te={};for(let Z of ce)if(Z.onBuildPrimitiveVAO){let Q=Z.onBuildPrimitiveVAO(e,j,p,s,l);Q&&(te[Z.name]=Q)}e.bindVertexArray(null);let O=s.materials&&p.material!==void 0?s.materials[p.material]:null,{program:G,uniforms:q}=rt(e,p,O),A=st(O,C),E=!!(O?.extensions?.KHR_materials_transmission||te.materials?.isTransmissive),H=p.extensions?.KHR_materials_variants?.mappings,W=Array.isArray(H)?H.filter(Z=>Z&&typeof Z.material=="number"&&Array.isArray(Z.variants)).map(Z=>({material:Z.material|0,variants:Z.variants.map(Q=>Number(Q)|0)})):void 0;b.primitives.push({vao:j,instanced:z,indexCount:J,indexType:ae,...A,positions:X,indices:$,buffers:B,materialIndex:p.material,defaultMaterialIndex:p.material,variantMappings:W,primitiveDef:p,programCache:new Map([[p.material??-1,{program:G,uniforms:q}]]),pluginData:te,customProgram:G,customUniforms:q,isTransmissive:E})}g.push(b)}isFinite(R[0])||(R=[-1,-1,-1]),isFinite(T[0])||(T=[1,1,1]);let w=[(R[0]+T[0])/2,(R[1]+T[1])/2,(R[2]+T[2])/2],y=T[0]-R[0],F=T[1]-R[1],U=T[2]-R[2],_=Math.max(Math.hypot(y,F,U)/2,.5),k=[R[0],R[1],R[2]],P=[T[0],T[1],T[2]],N=t.animations;if(!N){for(let S of ce)if(S.onParseGLB?.(t),t.animations){N=t.animations;break}}return N||(N=[]),{meshes:g,bounds:{center:w,radius:_,min:k,max:P},lights:u,animations:N,worldMatrices:M,gpuTextures:C,availableVariants:d}}function Pe(e){let t=e.customTarget||e.bounds.center,i=e.currDistance*Math.cos(e.currPhi);return[t[0]+i*Math.sin(e.currTheta),t[1]+e.currDistance*Math.sin(e.currPhi),t[2]+i*Math.cos(e.currTheta)]}var lt=class{constructor(e,t,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=he(),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=he(),this.viewMatrix=he(),this.activeViewMatrix=null,this.modelMatrix=he(),this.mvpMatrix=he(),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:he(),rawValueToMeters:.001,format:0},this.container=e;let r,a;if(t&&typeof t.getContext=="function"?(r=t,a=i):(a=t,r=a?.canvas),!r){let l=e.querySelector("canvas");l||(l=document.createElement("canvas"),l.style.width="100%",l.style.height="100%",l.style.display="block",l.style.touchAction="none",e.prepend(l)),r=l}this.canvas=r,this.opts=a||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!s:s&&(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=Ue(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=Ve(this.opts.toneMapping)),this.opts.autoplay!==void 0&&(this.autoplay=this.opts.autoplay),this.opts.animationName!==void 0&&(this.animationName=this.opts.animationName),this.opts.variantName!==void 0&&(this.activeVariantName=this.opts.variantName||null),this.opts.fieldOfView!==void 0&&(this.fov=this.opts.fieldOfView*Math.PI/180),this.opts.distanceMode!==void 0&&(this.distanceMode=this.opts.distanceMode),this.opts.cameraTarget!==void 0&&(this.setTarget(this.opts.cameraTarget[0],this.opts.cameraTarget[1],this.opts.cameraTarget[2]),this.initialCustomTarget=[...this.opts.cameraTarget]),(this.opts.minCameraOrbit||this.opts.maxCameraOrbit)&&this.setOrbitLimits({minTheta:this.opts.minCameraOrbit?.theta,maxTheta:this.opts.maxCameraOrbit?.theta,minPhi:this.opts.minCameraOrbit?.phi,maxPhi:this.opts.maxCameraOrbit?.phi,minDistance:this.opts.minCameraOrbit?.distance,maxDistance:this.opts.maxCameraOrbit?.distance});let c=r.getContext("webgl2",{antialias:!0,alpha:!0,xrCompatible:!0});if(!c)throw new Error("WebGL2 not supported");this.gl=c,this.initGlState(),this.setupEvents(),this.setupContextLossHandling(),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}static registerDecoder(e,t){kt(e,t)}static getDecoder(e){return Te(e)}setupContextLossHandling(){let e=this.canvas;typeof e?.addEventListener=="function"&&(this.boundContextLost=t=>{t.preventDefault?.(),this.contextLost=!0,this.stop()},this.boundContextRestored=()=>this.restoreContext(),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored))}initGlState(){let e=this.gl,t=it();this.renderProg=Ne(e,et,t.fs),this.pickProg=Ne(e,Nt,Vt),this.uRender=$e(e,this.renderProg,t.uniforms),this.uPick=$e(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of ce)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),i=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=i,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,i,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,i),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let i=this.gl,r=Math.max(1,e),a=Math.max(1,t);this.pickFboWidth=r,this.pickFboHeight=a,i.bindTexture(3553,this.pickTexture),i.texImage2D(3553,0,6408,r,a,0,6408,5121,null),i.bindRenderbuffer(36161,this.pickDepth),i.renderbufferStorage(36161,33189,r,a)}loadGLBData(e,t){let{meshes:i,bounds:r,lights:a,animations:s,worldMatrices:c,gpuTextures:l,availableVariants:g}=ot(this.gl,e,t,()=>this.render());if(this.lastGlbData=e,this.lastLimits=t,this.disposeMeshGpuResources(),this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.meshes=i,this.bounds=r,this.turntableRotation=0,this.updateTurntableMatrix(),this.lights=a,this.animations=s||[],this.worldMatrices=c||[],this.gpuTextures=l||[],this.availableVariants=g||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let M of e.gltf.nodes)this.initialNodeTransforms.push({t:M.translation?[M.translation[0],M.translation[1],M.translation[2]]:[0,0,0],r:M.rotation?[M.rotation[0],M.rotation[1],M.rotation[2],M.rotation[3]]:[0,0,0,1],s:M.scale?[M.scale[0],M.scale[1],M.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let M of ce)M.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 d=e.exposure??e.gltf?.extras?.exposure??e.gltf?.asset?.extras?.exposure;d!==void 0&&(this.exposure=Ue(d));let v=e.environmentIntensity??e.gltf?.extras?.environmentIntensity??e.gltf?.asset?.extras?.environmentIntensity;v!==void 0&&(this.envIntensity=Math.max(0,Number(v)||0)),this.container&&typeof this.container.hasAttribute=="function"&&this.container.hasAttribute("poster")&&this.container.removeAttribute("poster"),this.resize(),this.update(0),this.render(),this.animFrameId===null&&typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}loadGLB(e){this.loadGLBData(Je(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of ce)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Re(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let i=Re(e),{meshes:r}=ot(this.gl,i,at,()=>this.render());if(t)for(let a of r)a.transform[12]+=t[0],a.transform[13]+=t[1],a.transform[14]+=t[2],ye(a.normalMatrix,a.transform);this.backdropMeshes=r,this.update(0),this.render()}setClearColor(e,t,i,r=1){this.clearColor=[e,t,i,r]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let i=this.meshes[t],r;e instanceof Map?r=e.get(i.name)??e.get(t):Array.isArray(e)?r=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,i.name)?r=e[i.name]:Object.prototype.hasOwnProperty.call(e,t)&&(r=e[t])),r&&r.length===16&&(i.transform.set(r),ye(i.normalMatrix,i.transform))}}bindLights(e=this.uRender){let t=this.gl,i=[.28,.28,.28],r=[],a=[],s=[],c=[],l=[],g=[];for(let d of this.lights){let v=d.color||[1,1,1],M=d.intensity!==void 0?d.intensity:1;if(d.type==="ambient")i=[v[0]*M,v[1]*M,v[2]*M];else if(d.type==="directional"&&r.length<6){let I=d.direction||[.5,1,.8];r.push(I[0],I[1],I[2]),a.push(v[0]*M,v[1]*M,v[2]*M)}else if((d.type==="point"||d.type==="spot")&&s.length<6){let I=d.position||[0,0,0];if(s.push(I[0],I[1],I[2]),c.push(v[0]*M,v[1]*M,v[2]*M),d.type==="spot"){let D=d.direction||[0,-1,0],u=Math.max(.01,Math.min(Math.PI/2,d.outerConeAngle??Math.PI/3)),x=Math.max(0,Math.min(u-1e-4,d.innerConeAngle??0));l.push(D[0],D[1],D[2]),g.push(Math.cos(x),Math.cos(u))}else l.push(0,-1,0),g.push(-2,-3)}}r.length===0&&(r.push(.5,1,.8),a.push(1,1,1)),t.uniform3fv(e.uAmbientColor,i),t.uniform1i(e.uNumDirLights,r.length/3),r.length>0&&(t.uniform3fv(e.uDirLightDir,r),t.uniform3fv(e.uDirLightColor,a)),t.uniform1i(e.uNumPointLights,s.length/3),s.length>0&&(t.uniform3fv(e.uPointLightPos,s),t.uniform3fv(e.uPointLightColor,c),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,l),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,g)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=Ue(e)}getExposure(){return this.exposure}setShadow(e,t){this.shadowIntensity=Math.max(0,Math.min(1,Number(e)||0)),t!==void 0&&(this.shadowSoftness=Math.max(0,Math.min(1,Number(t)||0)))}getShadowIntensity(){return this.shadowIntensity}getShadowSoftness(){return this.shadowSoftness}setToneMapping(e){this.toneMapping=Ve(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of ce)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of ce)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,i=this.currDistance;return{theta:e,phi:t,radius:i,toString(){return`${e.toFixed(4)}rad ${t.toFixed(4)}rad ${i.toFixed(4)}m`}}}getCameraTarget(){let e=this.customTarget||this.bounds.center;return{x:e[0],y:e[1],z:e[2],toString(){return`${e[0].toFixed(4)}m ${e[1].toFixed(4)}m ${e[2].toFixed(4)}m`}}}jumpCameraToGoal(){this.currTheta=this.targetTheta,this.currPhi=this.targetPhi,this.currDistance=this.targetDistance,this.update(0),this.render()}getModelMaterials(){let e=this.gltf?.materials?.length?this.gltf.materials:[{name:"DefaultMaterial",pbrMetallicRoughness:{}}];return e.map((t,i)=>{let r=this.meshes.flatMap(d=>d.primitives.filter(v=>v.materialIndex===i||e.length===1&&v.materialIndex===void 0)),a=r[0],s=a?[...a.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],c=a?a.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,l=a?a.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,g={baseColorFactor:s,metallicFactor:c,roughnessFactor:l,setBaseColorFactor:d=>{let v=[d[0],d[1],d[2],d[3]??1];g.baseColorFactor=v,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=v);for(let M of r)M.baseColor=v;this.render()},setMetallicFactor:d=>{g.metallicFactor=d,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=d);for(let v of r)v.metallic=d;this.render()},setRoughnessFactor:d=>{g.roughnessFactor=d,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.roughnessFactor=d);for(let v of r)v.roughness=d;this.render()}};return{name:t.name||`Material_${i}`,pbrMetallicRoughness:g}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(i=>i.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",i=-1;if(t)this.activeVariantName=null;else{if(i=this.availableVariants.indexOf(e),i<0)return!1;this.activeVariantName=e}let r=this.gltf?.materials;if(!Array.isArray(r))return t;for(let a of this.meshes)for(let s of a.primitives){let c=s.defaultMaterialIndex;if(!t&&Array.isArray(s.variantMappings)){for(let g of s.variantMappings)if(Array.isArray(g.variants)&&g.variants.includes(i)){c=g.material;break}}let l=c!==void 0?r[c]:void 0;s.materialIndex=l?c:void 0,Object.assign(s,st(l,this.gpuTextures)),this.applyPrimitiveProgram(s,s.materialIndex,l??null)}return!0}applyPrimitiveProgram(e,t,i){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let r=t??-1,a=e.programCache.get(r);a||(a=rt(this.gl,{...e.primitiveDef,material:t},i),e.programCache.set(r,a)),e.customProgram=a.program,e.customUniforms=a.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of ce)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,i){this.customTarget=[e,t,i],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,i=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(i,e))}setCamera(e,t,i,r){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(i)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/r))}setInitialCamera(e,t,i,r){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),i!==void 0&&i>0){let a=this.clampDistance(i);this.initialDistance=a,this.customDistance=!0,this.targetDistance=a,this.currDistance=a}else if(r!==void 0&&r>0){let a=this.clampDistance(this.bounds.radius*2.5/r);this.initialDistance=a,this.customDistance=!0,this.targetDistance=a,this.currDistance=a}else{this.customDistance=!1;let a=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=a,this.targetDistance=a,this.currDistance=a}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let i=he();fe(i,this.projMatrix,this.viewMatrix);let[r,a,s]=e,c=t?t[0]:0,l=t?t[1]:0,g=t?t[2]:0,d=this.modelRootMatrix;d&&(r=d[0]*e[0]+d[4]*e[1]+d[8]*e[2]+d[12],a=d[1]*e[0]+d[5]*e[1]+d[9]*e[2]+d[13],s=d[2]*e[0]+d[6]*e[1]+d[10]*e[2]+d[14],t&&(c=d[0]*t[0]+d[4]*t[1]+d[8]*t[2],l=d[1]*t[0]+d[5]*t[1]+d[9]*t[2],g=d[2]*t[0]+d[6]*t[1]+d[10]*t[2]));let v=i[0]*r+i[4]*a+i[8]*s+i[12],M=i[1]*r+i[5]*a+i[9]*s+i[13],I=i[2]*r+i[6]*a+i[10]*s+i[14],D=i[3]*r+i[7]*a+i[11]*s+i[15];if(D<=1e-4)return{x:0,y:0,z:1,visible:!1};let u=v/D,x=M/D,C=I/D,R=this.canvas.getBoundingClientRect(),T=R.width||this.canvas.clientWidth||this.canvas.width||300,m=R.height||this.canvas.clientHeight||this.canvas.height||150,h=(u*.5+.5)*T,w=(-x*.5+.5)*m,y=u>=-1.1&&u<=1.1&&x>=-1.1&&x<=1.1&&C>=-1&&C<=1;if(y&&t){let[F,U,_]=Pe(this),k=[r-F,a-U,s-_];c*k[0]+l*k[1]+g*k[2]>.05&&(y=!1)}return{x:h,y:w,z:C,visible:y}}setSelectedMesh(e){this.selectedMeshName=e||""}getSelectedMesh(){return this.selectedMeshName}setupEvents(){let e=this.canvas,t=()=>typeof performance<"u"?performance.now():Date.now();this.boundContextMenu=i=>{i.preventDefault()},e.addEventListener("contextmenu",this.boundContextMenu),this.boundPointerDown=i=>{this.interactive&&(this.isPointerDown=!0,this.lastInteractionTime=t(),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,e.setPointerCapture(i.pointerId))},e.addEventListener("pointerdown",this.boundPointerDown),this.boundPointerMove=i=>{if(!this.isPointerDown||!this.interactive)return;this.lastInteractionTime=t();let r=this.activePointers.get(i.pointerId)||{x:this.lastPointerX,y:this.lastPointerY},a=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(a,s),this.isPanning||i.button===2||i.shiftKey||this.activePointers.size===2){let c=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],l=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],g=this.customTarget?[...this.customTarget]:[...this.bounds.center],d=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;g[0]+=(-a*c[0]+s*l[0])*d,g[1]+=(-a*c[1]+s*l[1])*d,g[2]+=(-a*c[2]+s*l[2])*d,this.customTarget=g}else this.targetTheta=this.clampTheta(this.targetTheta-a*.008),this.targetPhi=this.clampPhi(this.targetPhi+s*.008)},e.addEventListener("pointermove",this.boundPointerMove),this.boundPointerUp=i=>{this.lastInteractionTime=t(),this.activePointers.delete(i.pointerId),this.activePointers.size===0?(this.isPointerDown=!1,this.isPanning=!1):this.activePointers.size===1&&(this.isPanning=!1);try{e.releasePointerCapture(i.pointerId)}catch{}if(this.totalDragDist<5&&i.button===0){let r=e.getBoundingClientRect(),a=Math.floor((i.clientX-r.left)*(e.width/Math.max(r.width,1))),s=Math.floor((i.clientY-r.top)*(e.height/Math.max(r.height,1)));this.performMeshPick(a,s,!0)}},e.addEventListener("pointerup",this.boundPointerUp),this.boundWheel=i=>{if(!this.interactive)return;i.preventDefault(),this.lastInteractionTime=t();let r=Math.exp(i.deltaY*.001);this.targetDistance=this.clampDistance(this.targetDistance*r)},e.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),e.tabIndex!==void 0&&e.tabIndex<0&&(e.tabIndex=0),e.getAttribute?.("role")||e.setAttribute?.("role","region"),e.getAttribute?.("aria-label")||e.setAttribute?.("aria-label","Interactive 3D model viewport"),this.boundKeyDown=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=t(),i.preventDefault()}},e.addEventListener("keydown",this.boundKeyDown)}teardownEvents(){let e=(i,r,a)=>{this[a]&&(i.removeEventListener(r,this[a]),this[a]=null)},t=this.canvas;e(t,"webglcontextlost","boundContextLost"),e(t,"webglcontextrestored","boundContextRestored"),e(t,"contextmenu","boundContextMenu"),e(t,"pointerdown","boundPointerDown"),e(t,"pointermove","boundPointerMove"),e(t,"pointerup","boundPointerUp"),e(t,"wheel","boundWheel"),e(t,"keydown","boundKeyDown"),e(this.container,"setCamera","boundSetCamera"),e(this.container,"resetCamera","boundResetCamera")}raycastFromScreenPoint(e,t){let i=this.canvas,r=i.getBoundingClientRect(),a=i.width||300,s=i.height||300,c=r.width>0?Math.floor((e-r.left)*(a/r.width)):Math.floor(e),l=r.height>0?Math.floor((t-r.top)*(s/r.height)):Math.floor(t);return this.performMeshPick(c,l,!1)}performMeshPick(e,t,i=!0){if(this.meshes.length===0)return null;let r=this.gl,a=Math.max(1,this.canvas.width||300),s=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,a);let c=he();fe(c,this.projMatrix,this.viewMatrix);let l=[],g=Math.max(0,Math.min(a-1,e)),d=Math.max(0,Math.min(s-1,s-1-t));if(this.pickFbo&&r&&!this.xrSessionActive){(this.pickFboWidth!==a||this.pickFboHeight!==s)&&this.resizePickingFbo(a,s),r.bindFramebuffer(36160,this.pickFbo),r.viewport(0,0,a,s),r.enable(2929),r.clearColor(0,0,0,0),r.clear(16640),r.useProgram(this.pickProg);for(let w=0;w<this.meshes.length;w++){let y=this.meshes[w];if(y.visible===!1||y.isPluginMesh)continue;let F=w+1,U=(F&255)/255,_=(F>>8&255)/255,k=(F>>16&255)/255;r.uniform4f(this.uPick.uColorId,U,_,k,1),fe(this.modelMatrix,this.modelRootMatrix,y.transform);let P=y.instanceMatrices;if(P&&P.length>=16){let N=P.length>>4,S=he();for(let o of y.primitives){r.bindVertexArray(o.vao);for(let V=0;V<N;V++)fe(S,this.modelMatrix,P.subarray(V*16,V*16+16)),fe(this.mvpMatrix,c,S),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),Ce(r,o)}}else{fe(this.mvpMatrix,c,this.modelMatrix),r.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let N of y.primitives)r.bindVertexArray(N.vao),Ce(r,N)}}let m=new Uint8Array(4);r.readPixels(g,d,1,1,6408,5121,m),r.bindFramebuffer(36160,null);let h=m[0]+(m[1]<<8)+(m[2]<<16);h>0&&h<=this.meshes.length&&(l=[this.meshes[h-1]])}l.length===0&&(l=this.meshes.filter(m=>m.visible!==!1));let v=null,M=1/0,I=[0,0,0],D=[0,1,0],[u,x,C]=Pe(this),R=he();for(let m of l){fe(R,this.modelRootMatrix,m.transform);let h=m.instanceMatrices,w=h&&h.length>=16?h.length>>4:1;for(let y=0;y<w;y++){h&&h.length>=16?fe(this.modelMatrix,R,h.subarray(y*16,y*16+16)):this.modelMatrix.set(R),fe(this.mvpMatrix,c,this.modelMatrix);let F=he();if(!Tt(F,this.mvpMatrix))continue;let U=(g+.5)/a*2-1,_=(d+.5)/s*2-1,k=[0,0,0],P=[0,0,0];Ke(k,U,_,-1,F),Ke(P,U,_,1,F);let N=P[0]-k[0],S=P[1]-k[1],o=P[2]-k[2],V=Math.hypot(N,S,o)||1,K=N/V,f=S/V,b=o/V,n={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((p=>{for(let B of m.primitives){if(!B.positions)continue;let j=B.positions,z=B.indices,ee=Math.floor(z?z.length/3:j.length/9);for(let L=0;L<ee;L++){let X=z?z[L*3]:L*3,J=z?z[L*3+1]:L*3+1,ae=z?z[L*3+2]:L*3+2;Pt(k[0],k[1],k[2],K,f,b,j[X*3],j[X*3+1],j[X*3+2],j[J*3],j[J*3+1],j[J*3+2],j[ae*3],j[ae*3+1],j[ae*3+2],n,p)}}})(1e-4),isFinite(n.distance)){let p=n.point[0],B=n.point[1],j=n.point[2],z=this.modelMatrix,ee=z[0]*p+z[4]*B+z[8]*j+z[12],L=z[1]*p+z[5]*B+z[9]*j+z[13],X=z[2]*p+z[6]*B+z[10]*j+z[14],J=ee-u,ae=L-x,$=X-C,te=Math.hypot(J,ae,$);if(te<M){ye(this.normalMatrix,this.modelMatrix);let O=this.normalMatrix,G=n.normal[0],q=n.normal[1],A=n.normal[2],E=O[0]*G+O[3]*q+O[6]*A,H=O[1]*G+O[4]*q+O[7]*A,W=O[2]*G+O[5]*q+O[8]*A,Z=Math.hypot(E,H,W)||1;E/=Z,H/=Z,W/=Z,E*J+H*ae+W*$>0&&(E=-E,H=-H,W=-W),v=m,M=Math.round(te*1e3)/1e3,I=[Math.round(ee*1e3)/1e3,Math.round(L*1e3)/1e3,Math.round(X*1e3)/1e3],D=[Math.round(E*1e3)/1e3,Math.round(H*1e3)/1e3,Math.round(W*1e3)/1e3]}}}}if(!v)return null;let T={meshIndex:this.meshes.indexOf(v),meshName:v.name,nodeIndex:v.nodeIndex,distance:M,hitPoint:I,normal:D,screenX:e,screenY:t};if(i){for(let m of ce)m.onMeshSelect?.(this,T);this.opts.onMeshClick&&this.opts.onMeshClick(T),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("meshClick",{bubbles:!0,detail:T}))}return T}mapStereoPickX(e,t){if(!this.stereoSBS||this.xrSessionActive||t<2)return e;let i=Math.max(1,Math.floor(t*.5)),r=e>=i,a=r?e-i:e,s=r?Math.max(1,t-i):i,c=(a+.5)/s*2-1;return Math.floor((c*.5+1)*.5*t)}setStereoSBS(e){this.stereoSBS=!!e,this.xrSessionActive||(this.syncCameraMatrices(),this.render())}syncCameraMatrices(){let e=Math.max(1,this.canvas.width||1)/Math.max(1,this.canvas.height||1),t=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10);Ee(this.projMatrix,this.fov,e,.1,t);let i=this.customTarget||this.bounds.center;Fe(this.viewMatrix,Pe(this),i,[0,1,0]),fe(this.mvpMatrix,this.projMatrix,this.viewMatrix),ye(this.normalMatrix,this.modelMatrix)}resize(){let e=Math.min((typeof window<"u"?window.devicePixelRatio:1)||1,2),t=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.floor(t.width*e)),r=Math.max(1,Math.floor(t.height*e));this.canvas.width!==i||this.canvas.height!==r?(this.canvas.width=i,this.canvas.height=r,this.resizePickingFbo(i,r),this.xrSessionActive||this.syncCameraMatrices()):!this.xrSessionActive&&this.projMatrix[0]===0&&this.syncCameraMatrices()}getGLContext(){return this.gl}setXRSessionActive(e){let t=this.xrSessionActive;if(this.xrSessionActive=e,t&&!e){this.xrDepthState.enabled=!1;for(let i of ce)i.onXRSessionEnd?.(this);if(this.lastTime=typeof performance<"u"?performance.now():Date.now(),this.updateTurntableMatrix(),this.isVisible)try{this.resize(),this.syncCameraMatrices(),this.render()}catch(i){this.reportRenderError(i)}}}reportRenderError(e){this.renderErrorReported||(this.renderErrorReported=!0,typeof console<"u"&&console.warn("[three-live] render frame failed:",e))}stepXRUpdate(e){for(let t of ce)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let i=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(i),this.render()}catch(r){this.reportRenderError(r)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),i=this.bounds.center[0],r=this.bounds.center[2],a=this.modelRootMatrix;a[0]=e,a[1]=0,a[2]=-t,a[3]=0,a[4]=0,a[5]=1,a[6]=0,a[7]=0,a[8]=t,a[9]=0,a[10]=e,a[11]=0,a[12]=i-(e*i+t*r),a[13]=0,a[14]=r-(-t*i+e*r),a[15]=1}setVisible(e){this.isVisible=e}update(e){for(let s of ce)s.onUpdate?.(this,e);let t=typeof performance<"u"?performance.now():Date.now();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let s of ce)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),a=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(a-this.lastReportedZoom)>=.02){this.lastReportedTheta=i,this.lastReportedPhi=r,this.lastReportedZoom=a;let s={theta:i,phi:r,zoom:a,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(e,t,i,r,a=!0,s=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let c=e?.transform?.inverse?.matrix||this.viewMatrix,l=e?.projectionMatrix||this.projMatrix,g=e?.transform?.position,d=g?[g.x,g.y,g.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):i&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:c,projMatrix:l,eyePos:d,viewport:r,eye:e?.eye||"none",clear:s>0?!1:e?.eye!=="right",isAR:a})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let T=Math.max(2,this.canvas.width||2),m=Math.max(1,this.canvas.height||1),h=Math.max(1,Math.floor(T*.5)),w=Math.max(1,T-h),y=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),F=this.customTarget||this.bounds.center,[U,_,k]=Pe(this),P=Math.cos(this.currTheta),N=-Math.sin(this.currTheta),S=.032,o=he(),V=he(),K=[U-P*S,_,k-N*S],f=[F[0]-P*S*.25,F[1],F[2]-N*S*.25];Ee(o,this.fov,h/m,.1,y),Fe(V,K,f,[0,1,0]);let b=he(),n=he(),p=[U+P*S,_,k+N*S],B=[F[0]+P*S*.25,F[1],F[2]+N*S*.25];Ee(b,this.fov,w/m,.1,y),Fe(n,p,B,[0,1,0]),this.render({viewMatrix:V,projMatrix:o,eyePos:K,viewport:[0,0,h,m],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:n,projMatrix:b,eyePos:p,viewport:[h,0,w,m],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,T,m);return}let t=this.gl,i=0,r=0,a=this.canvas.width,s=this.canvas.height;e?.viewport?(i=e.viewport[0],r=e.viewport[1],a=e.viewport[2],s=e.viewport[3],t.viewport(i,r,a,s)):t.viewport(0,0,this.canvas.width,this.canvas.height),t.enable(2929),(!e||e.clear!==!1)&&(e?.isAR?t.clearColor(0,0,0,0):t.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),t.clear(16640));let c=he(),l=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=l,fe(c,e?.projMatrix??this.projMatrix,l);let g=ge().xrDepthShader,d=It(this.toneMapping),[v,M,I]=e?e.eyePos:Pe(this);for(let T of ce)T.onBeforeDrawScene?.(this,t,c,[v,M,I],d);let D=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&D===0)return;let u=e?.eye||"none",x=!1,C=D>0?[...this.backdropMeshes,...this.meshes]:this.meshes,R=T=>{for(let m=0;m<C.length;m++){let h=C[m];if(h.visible===!1)continue;let w=this.selectedMeshName!==""&&h.name===this.selectedMeshName;m<D||h.worldSpace===!0||h.name==="__xr_reticle__"?this.modelMatrix.set(h.transform):fe(this.modelMatrix,this.modelRootMatrix,h.transform),fe(this.mvpMatrix,c,this.modelMatrix),ye(h.normalMatrix,this.modelMatrix);let y=h.extras?.xr?.stereo||h.userData?.xr?.stereo,F=0,U=0,_=1,k=1;y==="sbs"?(_=.5,F=u==="right"?.5:0):y==="ou"&&(k=.5,U=u==="right"?.5:0);for(let P of h.primitives){let N=!!P.isTransmissive;if(!T&&N){x=!0;continue}if(T&&!N)continue;let S=P.customProgram||this.renderProg,o=P.customUniforms||this.uRender;t.useProgram(S),t.vertexAttrib3f(3,0,0,0),o.uInstanced&&t.uniform1i(o.uInstanced,0),t.uniform1i(o.uToneMapping,d),t.uniform1f(o.uEnvIntensity,this.envIntensity),o.uExposure&&t.uniform1f(o.uExposure,this.exposure),t.uniform3f(o.uCameraPos,v,M,I),t.uniform1f(o.uEmissive,w?1:0),t.uniformMatrix4fv(o.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(o.uModel,!1,this.modelMatrix),t.uniformMatrix3fv(o.uNormalMatrix,!1,h.normalMatrix),o.uUvTransform&&t.uniform4f(o.uUvTransform,F,U,_,k),o.uViewportSize&&t.uniform2f(o.uViewportSize,Math.max(1,a),Math.max(1,s)),g?.bind(t,o,this.xrDepthState,l,[i,r,Math.max(1,a),Math.max(1,s)]),this.environmentTexture?(t.activeTexture(33988),t.bindTexture(3553,this.environmentTexture),t.uniform1i(o.uEnvironmentMap,4),t.uniform1i(o.uHasEnvironmentMap,1)):t.uniform1i(o.uHasEnvironmentMap,0),this.bindLights(o),o.uSectionEnabled&&t.uniform1i(o.uSectionEnabled,0);for(let K of ce)K.onBeforeDrawPrimitive?.(t,S,P,h,this.worldMatrices||[],this.gltf);t.uniform4fv(o.uBaseColor,P.baseColor),t.uniform1f(o.uMetallic,P.metallic),t.uniform1f(o.uRoughness,P.roughness),o.uClearcoat&&t.uniform2f(o.uClearcoat,P.clearcoat??0,P.clearcoatRoughness??.04),P.texture?(t.activeTexture(33984),t.bindTexture(3553,P.texture),t.uniform1i(o.uBaseColorTexture,0),t.uniform1i(o.uHasTexture,1)):t.uniform1i(o.uHasTexture,0),P.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,P.metallicRoughnessTexture),t.uniform1i(o.uMetallicRoughnessTexture,1),t.uniform1i(o.uHasMetallicRoughnessTexture,1)):t.uniform1i(o.uHasMetallicRoughnessTexture,0),P.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,P.normalTexture),t.uniform1i(o.uNormalTexture,2),t.uniform1i(o.uHasNormalTexture,1),t.uniform1f(o.uNormalScale,P.normalScale)):t.uniform1i(o.uHasNormalTexture,0),P.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,P.occlusionTexture),t.uniform1i(o.uOcclusionTexture,3),t.uniform1i(o.uHasOcclusionTexture,1),t.uniform1f(o.uOcclusionStrength,P.occlusionStrength)):t.uniform1i(o.uHasOcclusionTexture,0),t.bindVertexArray(P.vao);let V=h.instanceMatrices;if(P.instanceCount!==void 0)t.drawElementsInstanced(4,P.indexCount,P.indexType,0,P.instanceCount);else if(V&&V.length>=16&&P.instanced&&o.uInstanced&&o.uViewProj){let K=V.length>>4;t.uniform1i(o.uInstanced,1),t.uniformMatrix4fv(o.uViewProj,!1,c),P.indices?t.drawElementsInstanced(4,P.indexCount,P.indexType,0,K):t.drawArraysInstanced(4,0,P.indexCount,K),t.uniform1i(o.uInstanced,0)}else if(V&&V.length>=16){let K=V.length>>4,f=h.instanceColors,b=he(),n=new Float32Array(9),p=[P.baseColor[0],P.baseColor[1],P.baseColor[2],P.baseColor[3]];for(let B=0;B<K;B++)fe(b,this.modelMatrix,V.subarray(B*16,B*16+16)),fe(this.mvpMatrix,c,b),ye(n,b),t.uniformMatrix4fv(o.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(o.uModel,!1,b),t.uniformMatrix3fv(o.uNormalMatrix,!1,n),f&&(p[0]=P.baseColor[0]*f[B*3],p[1]=P.baseColor[1]*f[B*3+1],p[2]=P.baseColor[2]*f[B*3+2],p[3]=P.baseColor[3],t.uniform4fv(o.uBaseColor,p)),Ce(t,P)}else Ce(t,P)}}};if(R(!1),x){for(let T of ce)T.onBeforeTransmissivePass?.(t,this);R(!0)}for(let T of ce)T.onAfterRender?.(t,this,c,e?.eye??"none",[i,r,a,s],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){nt(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of ce)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};lt.registerPlugin=Rt,lt.getRegisteredPlugins=Ct;function Ht(e){return e+3&-4}var ie=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function ut(e,t){let i=t,r=1;for(;e.has(i);)i=`${t}_${r++}`;return e.add(i),i}function ht(e,t=0){let[i,r,a,,s,c,l,,g,d,v,,M,I,D]=Array.from({length:15},(n,p)=>ie(e[t+p],p%5===0?1:0)),u=Math.hypot(i,r,a),x=Math.hypot(s,c,l),C=Math.hypot(g,d,v);i*(c*v-d*l)-s*(r*v-d*a)+g*(r*l-c*a)<0&&(u=-u);let R=Math.abs(u)>1e-8?1/u:0,T=Math.abs(x)>1e-8?1/x:0,m=Math.abs(C)>1e-8?1/C:0,h=i*R,w=r*R,y=a*R,F=s*T,U=c*T,_=l*T,k=g*m,P=d*m,N=v*m,S=h+U+N,o=0,V=0,K=0,f=1;if(S>0){let n=.5/Math.sqrt(S+1);f=.25/n,o=(_-P)*n,V=(k-y)*n,K=(w-F)*n}else if(h>U&&h>N){let n=2*Math.sqrt(Math.max(0,1+h-U-N));n>1e-8&&(f=(_-P)/n,o=.25*n,V=(F+w)/n,K=(k+y)/n)}else if(U>N){let n=2*Math.sqrt(Math.max(0,1+U-h-N));n>1e-8&&(f=(k-y)/n,o=(F+w)/n,V=.25*n,K=(_+P)/n)}else{let n=2*Math.sqrt(Math.max(0,1+N-h-U));n>1e-8&&(f=(w-F)/n,o=(k+y)/n,V=(_+P)/n,K=.25*n)}let b=Math.hypot(o,V,K,f);return b>1e-8&&Number.isFinite(b)?(o/=b,V/=b,K/=b,f/=b):(o=0,V=0,K=0,f=1),{t:[M,I,D],r:[o,V,K,f],s:[u,x,C]}}function zt(e){let t={};return e.grab&&(t.interactable={mode:typeof e.grab=="string"?e.grab:"2-hand"},t.movable={scaleInZ:!!e.scale,minScale:typeof e.scale=="object"?e.scale.min??.1:.1,maxScale:typeof e.scale=="object"?e.scale.max??10:10}),e.billboard&&(t.billboard={mode:typeof e.billboard=="string"?e.billboard:"capsule"}),e.follow&&(t.follow={target:typeof e.follow=="object"?e.follow.mode??"head":e.follow}),e.anchor&&(t.anchor={plane:e.anchor}),e.physics&&e.physics!=="none"&&(t.rigidbody={type:e.physics}),t}var be=(e,t,i,r)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(i,e)):r;function ct(e){let t=e?.audioEmitter??e?.spatialAudio??(typeof e?.audio=="object"&&e.audio&&("preset"in e.audio||"distanceModel"in e.audio||"coneInnerAngle"in e.audio||"maxDistance"in e.audio||"volume"in e.audio)?e.audio:typeof e?.audio=="string"&&/^(hum|reactor|wind|beacon|geiger|chimeLoop|machinery|water)$/.test(e.audio)?{preset:e.audio}:void 0);if(!t||typeof t=="object"&&t.enabled===!1)return null;let i=typeof t=="string"?{preset:t}:t,r=typeof i.src=="string"&&!/[\x00-\x20\\%]|^\s*(javascript|data|file|http):/i.test(i.src)?i.src:void 0,a=typeof i.preset=="string"?i.preset:void 0;return!r&&!a?null:{ae:i,src:r,preset:a,volume:be(i.volume,0,2,.6),loop:typeof i.loop=="boolean"?i.loop:!0,isGlobal:i.type==="global"||i.positional===!1}}function jt(e,t){e.updateMatrixWorld(!0);let i=[],r=0,a=[],s=[],c=[],l=[],g=new Set,d=[],v=[],M=new Map,I=[],D=[],u=[],x=new Map,C=[],R=[];function T(f){let b=M.get(f);if(b!==void 0)return b;b=v.length,M.set(f,b);let n=f,p=n.color?.r??1,B=n.color?.g??1,j=n.color?.b??1,z=n.opacity??1,ee={baseColorFactor:[p,B,j,z],metallicFactor:n.metalness??0,roughnessFactor:n.roughness??.5},L={},X=E=>{if(!E)return;let H=(typeof E=="string"?E:typeof E.source=="string"?E.source:typeof E.image=="string"?E.image:"").trim();if(!H||/[\x00-\x1f\x7f\\]|\.\./.test(H)||!(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(H)||!H.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(H)))return;let W=x.get(H);if(W===void 0){let Z=I.length;I.push({uri:H}),D.length===0&&D.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),W=u.length,u.push({sampler:0,source:Z}),x.set(H,W)}return{index:W}},J=X(n.map);J&&(ee.baseColorTexture=J);let ae=X(n.roughnessMap||n.metalnessMap);ae&&(ee.metallicRoughnessTexture=ae);let $=n.map?.avgColor;Array.isArray($)&&$.length>=3&&(L.avgColor=[$[0],$[1],$[2]]);let te=X(n.normalMap),O=X(n.emissiveMap),G=X(n.aoMap),q={name:n.name||"",pbrMetallicRoughness:ee,doubleSided:n.side===2||!!n.doubleSided,...te?{normalTexture:te}:{},...O?{emissiveTexture:O}:{},...G?{occlusionTexture:G}:{},...Object.keys(L).length>0?{extras:L}:{}};if(n.emissive&&(n.emissive.r>0||n.emissive.g>0||n.emissive.b>0)){let E=n.emissiveIntensity??1;q.emissiveFactor=[n.emissive.r*E,n.emissive.g*E,n.emissive.b*E]}let A={};return n.clearcoat&&n.clearcoat>0&&(A.KHR_materials_clearcoat={clearcoatFactor:n.clearcoat,clearcoatRoughnessFactor:n.clearcoatRoughness||0}),n.sheen&&n.sheen>0&&(A.KHR_materials_sheen={sheenColorFactor:n.sheenColor?[n.sheenColor.r,n.sheenColor.g,n.sheenColor.b]:[1,1,1],sheenRoughnessFactor:n.sheenRoughness||0}),n.transmission&&n.transmission>0&&(A.KHR_materials_transmission={transmissionFactor:n.transmission}),n.thickness&&n.thickness>0&&(A.KHR_materials_volume={thicknessFactor:n.thickness,attenuationDistance:n.attenuationDistance??1/0,attenuationColor:n.attenuationColor?[n.attenuationColor.r,n.attenuationColor.g,n.attenuationColor.b]:[1,1,1]}),n.ior!==void 0&&n.ior!==1.5&&(A.KHR_materials_ior={ior:n.ior}),n.dispersion&&n.dispersion>0&&(A.KHR_materials_dispersion={dispersion:n.dispersion}),n.iridescence&&n.iridescence>0&&(A.KHR_materials_iridescence={iridescenceFactor:n.iridescence,iridescenceIor:n.iridescenceIOR??1.3}),Object.keys(A).length>0&&(q.extensions=A),v.push(q),b}function m(f,b){let n=new Uint8Array(f.buffer,f.byteOffset,f.byteLength),p=Ht(n.byteLength),B=new Uint8Array(p);B.set(n),i.push(B);let j=a.length;return a.push({buffer:0,byteOffset:r,byteLength:n.byteLength,target:b}),r+=p,j}function h(f,b,n,p,B,j,z){let ee=m(f,n),L=s.length,X={bufferView:ee,byteOffset:0,componentType:p,count:B,type:b};return j&&(X.min=j),z&&(X.max=z),s.push(X),L}e.traverse(f=>{if(f.isLight||f.color&&f.intensity!==void 0){let b=f.matrixWorld?.elements,n=ie(b?b[12]:f.position?.x,0),p=ie(b?b[13]:f.position?.y,0),B=ie(b?b[14]:f.position?.z,0),j=f.target,z=j?.parent?j?.matrixWorld?.elements:void 0,ee=ie(z?z[12]:j?.position?.x,0),L=ie(z?z[13]:j?.position?.y,0),X=ie(z?z[14]:j?.position?.z,0),J=ee-n,ae=L-p,$=X-B,te=Math.hypot(J,ae,$),O=Math.max(.01,Math.min(Math.PI/2,ie(f.angle,Math.PI/3))),G=Math.max(0,Math.min(1,ie(f.penumbra,0)));R.push({type:f.type,color:[f.color.r,f.color.g,f.color.b],intensity:f.intensity,position:[n,p,B],...f.type==="spot"?{direction:te>1e-6?[J/te,ae/te,$/te]:[0,-1,0],outerConeAngle:O,innerConeAngle:Math.max(0,O*(1-G)),range:Math.max(0,ie(f.distance,0))}:f.type==="point"?{range:Math.max(0,ie(f.distance,0))}:{}})}});let w=[],y=new Set([e]),F=[];if(Array.isArray(e.children))for(let f=e.children.length-1;f>=0;f--)F.push({obj:e.children[f],parentKids:w});for(;F.length>0;){let{obj:f,parentKids:b}=F.pop();if(!f||typeof f!="object"||y.has(f))continue;y.add(f),f._bakeAuthorGeometry?.(),ge().materializeDeclarativeGeometry?.(f);let n=!!(f.userData&&(f.userData.xr&&typeof f.userData.xr=="object"&&Object.keys(f.userData.xr).length>0||f.userData.interactivity&&typeof f.userData.interactivity=="object"&&Object.keys(f.userData.interactivity).length>0)),p={name:f.name||(n?`Node_${l.length}`:"")},B=ie(f.position?.x,0),j=ie(f.position?.y,0),z=ie(f.position?.z,0),ee=ie(f.quaternion?.x,0),L=ie(f.quaternion?.y,0),X=ie(f.quaternion?.z,0),J=ie(f.quaternion?.w,1),ae=ie(f.scale?.x,1),$=ie(f.scale?.y,1),te=ie(f.scale?.z,1);if((B||j||z)&&(p.translation=[B,j,z]),(ee||L||X||J!==1)&&(p.rotation=[ee,L,X,J]),(ae!==1||$!==1||te!==1)&&(p.scale=[ae,$,te]),f.visible===!1&&(p.extensions={...p.extensions||{},KHR_node_visibility:{visible:!1}},g.add("KHR_node_visibility")),f.userData&&Object.keys(f.userData).length>0&&(p.extras=JSON.parse(JSON.stringify(f.userData,(q,A)=>{if(!(q==="__proto__"||q==="prototype"||q==="constructor"))return typeof A=="function"?void 0:A})),f.userData.xr)){let q=zt(f.userData.xr);p.extensions={...p.extensions||{},MOZ_hubs_components:q,ANDROID_xr_scenecore:q},ge().xrTraitSerializer?.gltfNode(p,f.userData.xr),g.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(f.geometry){let q=f.geometry,A=q.attributes.position;if(A&&A.count>0){let E=[1/0,1/0,1/0],H=[-1/0,-1/0,-1/0];for(let re=0;re<A.count;re++){let se=A.getX(re),ne=A.getY(re),oe=A.getZ(re);se<E[0]&&(E[0]=se),se>H[0]&&(H[0]=se),ne<E[1]&&(E[1]=ne),ne>H[1]&&(H[1]=ne),oe<E[2]&&(E[2]=oe),oe>H[2]&&(H[2]=oe)}let W={attributes:{POSITION:h(A.array,"VEC3",34962,5126,A.count,E,H)}};if(q.attributes.normal&&(W.attributes.NORMAL=h(q.attributes.normal.array,"VEC3",34962,5126,q.attributes.normal.count)),q.attributes.uv&&(W.attributes.TEXCOORD_0=h(q.attributes.uv.array,"VEC2",34962,5126,q.attributes.uv.count)),q.index){let re=q.index.array instanceof Uint32Array;W.indices=h(q.index.array,"SCALAR",34963,re?5125:5123,q.index.count)}let Z=Array.isArray(f.material)?f.material[0]:f.material;Z&&(W.material=T(Z));let Q=f.userData?.variants;if(Q&&typeof Q=="object"){let re=new Map;for(let se of Object.keys(Q)){if(!se||se==="__proto__"||se==="constructor"||se==="prototype")continue;let ne=Q[se];if(!ne||typeof ne!="object")continue;let oe=C.indexOf(se);if(oe===-1&&C.length<256&&(oe=C.length,C.push(se)),oe===-1)continue;let pe=T(ne),de=re.get(pe);de||(de=[],re.set(pe,de)),de.push(oe)}if(re.size>0){let se=[];for(let[ne,oe]of re.entries())se.push({material:ne,variants:oe});W.extensions={...W.extensions||{},KHR_materials_variants:{mappings:se}},g.add("KHR_materials_variants")}}let Y=f;if(Y.isInstancedMesh&&typeof Y.count=="number"&&Y.count>0&&Y.instanceMatrix?.array){let re=Math.min(1e4,Math.floor(Y.count)),se=Y.instanceMatrix.array,ne=new Float32Array(re*3),oe=new Float32Array(re*4),pe=new Float32Array(re*3);for(let ue=0;ue<re;ue++){let{t:ve,r:we,s:ke}=ht(se,ue*16);ne[ue*3]=ve[0],ne[ue*3+1]=ve[1],ne[ue*3+2]=ve[2],oe[ue*4]=we[0],oe[ue*4+1]=we[1],oe[ue*4+2]=we[2],oe[ue*4+3]=we[3],pe[ue*3]=ke[0],pe[ue*3+1]=ke[1],pe[ue*3+2]=ke[2]}let de={TRANSLATION:h(ne,"VEC3",0,5126,re),ROTATION:h(oe,"VEC4",0,5126,re),SCALE:h(pe,"VEC3",0,5126,re)};if(Y.instanceColor?.array&&Y.instanceColor.array.length>=re*3){let ue=new Float32Array(Y.instanceColor.array.subarray(0,re*3));de._COLOR_0=h(ue,"VEC3",0,5126,re)}p.extensions={...p.extensions||{},EXT_mesh_gpu_instancing:{attributes:de}},g.add("EXT_mesh_gpu_instancing")}let le=c.length;c.push({primitives:[W],name:f.name,...p.extras?{extras:p.extras}:{}}),p.mesh=le}}let O=l.length;l.push(p),d.push(f),b.push(O);let G=f.children;if(Array.isArray(G)&&G.length>0){let q=[];p.children=q;for(let A=G.length-1;A>=0;A--)F.push({obj:G[A],parentKids:q})}}for(let f=0;f<l.length;f++){let b=l[f];b.children&&b.children.length===0?delete b.children:b.children&&b.children.length>0&&(b.extras?.xr?.lod||b.extensions?.ANDROID_xr_scenecore?.lod||d[f]?.isLOD)&&(b.extensions={...b.extensions||{},MSFT_lod:{ids:[...b.children]}},g.add("MSFT_lod"))}let U=t?.animateCallback||t?.animateFn||(typeof e.userData?.animate=="function"?e.userData.animate:typeof e.__animateFn=="function"?e.__animateFn:typeof globalThis.animate=="function"?globalThis.animate:void 0),_=[];if(typeof U=="function"&&d.length>0){let f=t?.duration??4,b=t?.fps??15,n=Math.max(2,Math.round(f*b)+1),p=new Float32Array(n),B=d.map($=>[ie($.position?.x,0),ie($.position?.y,0),ie($.position?.z,0),ie($.quaternion?.x,0),ie($.quaternion?.y,0),ie($.quaternion?.z,0),ie($.quaternion?.w,1),ie($.scale?.x,1),ie($.scale?.y,1),ie($.scale?.z,1)]),j=d.map(()=>new Float32Array(n*3)),z=d.map(()=>new Float32Array(n*4)),ee=d.map(()=>new Float32Array(n*3));for(let $=0;$<n;$++){let te=$/(n-1)*f;p[$]=te;try{U(te)}catch{}for(let O=0;O<d.length;O++){let G=d[O];j[O][$*3]=ie(G.position?.x,0),j[O][$*3+1]=ie(G.position?.y,0),j[O][$*3+2]=ie(G.position?.z,0);let q=ie(G.quaternion?.x,0),A=ie(G.quaternion?.y,0),E=ie(G.quaternion?.z,0),H=ie(G.quaternion?.w,1),W=Math.hypot(q,A,E,H)||1;if(q/=W,A/=W,E/=W,H/=W,$>0){let Z=($-1)*4,Q=z[O];Q[Z]*q+Q[Z+1]*A+Q[Z+2]*E+Q[Z+3]*H<0&&(q=-q,A=-A,E=-E,H=-H)}z[O][$*4]=q,z[O][$*4+1]=A,z[O][$*4+2]=E,z[O][$*4+3]=H,ee[O][$*3]=ie(G.scale?.x,1),ee[O][$*3+1]=ie(G.scale?.y,1),ee[O][$*3+2]=ie(G.scale?.z,1)}}for(let $=0;$<d.length;$++){let te=d[$],O=B[$];te.position?.set(O[0],O[1],O[2]),te.quaternion?.set(O[3],O[4],O[5],O[6]),te.scale?.set(O[7],O[8],O[9])}e.updateMatrixWorld(!0);let L=null,X=()=>(L===null&&(L=h(p,"SCALAR",0,5126,n,[0],[f])),L),J=[],ae=[];for(let $=0;$<d.length;$++){let te=B[$],O=(q,A,E)=>q.some((H,W)=>Math.abs(H-te[E+W%A])>1e-4),G=(q,A,E,H)=>{q&&ae.push({sampler:J.push({input:X(),interpolation:"LINEAR",output:h(A,E,0,5126,n)})-1,target:{node:$,path:H}})};G(O(j[$],3,0),j[$],"VEC3","translation"),G(O(z[$],4,3),z[$],"VEC4","rotation"),G(O(ee[$],3,7),ee[$],"VEC3","scale")}ae.length>0&&_.push({name:"ProceduralLoop",samplers:J,channels:ae})}let k=St(l,c,e.userData),P=[],N=[],S=[];for(let f=0;f<l.length;f++){let b=l[f],n=ct(b.extras?.xr);if(!n)continue;let{ae:p,src:B,preset:j,volume:z,loop:ee,isGlobal:L}=n,X=b.name||`Node_${f}`,J=N.length;N.push({name:`${X}_source`,gain:z,loop:ee,autoPlay:typeof p.autoplay=="boolean"?p.autoplay:!0,...B!==void 0?{audio:P.push({uri:B})-1}:{},...j?{extras:{preset:j,pitch:be(p.pitch,.25,4,1)}}:{}});let ae=S.length,$=be(p.refDistance,.05,100,1),te=be(p.coneInnerAngle,0,360,360),O=be(p.coneOuterAngle,te,360,360);S.push({name:`${X}_emitter`,type:L?"global":"positional",gain:z,sources:[J],...L?{}:{positional:{distanceModel:p.distanceModel==="linear"||p.distanceModel==="exponential"?p.distanceModel:"inverse",refDistance:$,maxDistance:be(p.maxDistance,$,500,Math.max($,25)),rolloffFactor:be(p.rolloffFactor,0,10,1),coneInnerAngle:+(te*Math.PI/180).toFixed(6),coneOuterAngle:+(O*Math.PI/180).toFixed(6),coneOuterGain:be(p.coneOuterGain,0,1,0)}}}),b.extensions={...b.extensions||{},KHR_audio_emitter:{emitter:ae}},g.add("KHR_audio_emitter")}let o={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity}},scenes:[{nodes:w}],scene:0,nodes:l,meshes:c,materials:v,...I.length>0?{images:I}:{},...D.length>0?{samplers:D}:{},...u.length>0?{textures:u}:{},accessors:s,bufferViews:a,buffers:[{byteLength:r}],..._.length>0?{animations:_}:{},...k||g.size>0?{extensionsUsed:[...k?["KHR_interactivity"]:[],...g]}:{},...k||C.length>0||S.length>0?{extensions:{...k?{KHR_interactivity:k}:{},...C.length>0?{KHR_materials_variants:{variants:C.map(f=>({name:f}))}}:{},...S.length>0?{KHR_audio_emitter:{...P.length>0?{audio:P}:{},sources:N,emitters:S}}:{}}}:{}},V=new Uint8Array(r),K=0;for(let f of i)V.set(f,K),K+=f.byteLength;return[{gltf:o,bin:V.buffer,lights:R,environmentIntensity:e.environmentIntensity},d]}function mt(e){return new TextEncoder().encode(e)}function Xt(e,t){let[i,r]=jt(e,t);return Be(i,r)}function Be(e,t){let i=[],r=e.gltf,a=ge().decoders.get("meshopt");a&&typeof a.decodeBufferViews=="function"&&a.decodeBufferViews(r,e);let s=e.bin,c=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),l=r.accessors||[],g=r.bufferViews||[],d=r.materials||[],v=r.meshes||[],M=r.nodes||[],I=r.textures||[],D=r.images||[],u=r.samplers||[],x=new Set,C=d.map((y,F)=>ut(x,Se(y?.name,`Material_${F}`))),R=new Map;function T(y){let F=/^data:image\/(png|jpe?g)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\s]+)$/i.exec(y);if(!F)return null;let U=F[2].replace(/\s+/g,""),_=U.endsWith("==")?2:U.endsWith("=")?1:0,k=new Uint8Array((U.length*3>>2)-_),P=S=>{let o=U.charCodeAt(S);return o>96?o-71:o>64?o-65:o>47?o+4:o===43?62:o===47?63:0},N=0;for(let S=0;S<U.length;S+=4){let o=P(S)<<18|P(S+1)<<12|P(S+2)<<6|P(S+3);k[N++]=o>>16&255,N<k.length&&(k[N++]=o>>8&255),N<k.length&&(k[N++]=o&255)}return k}function m(y,F,U){let _=y?.index;if(typeof _!="number")return;let k=I[_],P=k?.source;if(typeof P!="number"||!D[P])return;let N=R.get(P);if(N===void 0){N=null;let V=D[P],K=null;if(typeof V.bufferView=="number"){let f=g[V.bufferView],b=f?.byteOffset||0,n=f?.byteLength||0;f&&n>0&&b>=0&&b+n<=c.byteLength&&(K=new Uint8Array(c,b,n))}else typeof V.uri=="string"&&(K=T(V.uri));if(K&&K.byteLength>0){let f=K[0]===255&&K[1]===216&&K[2]===255||!(K[0]===137&&K[1]===80)&&/jpe?g/i.test(V.mimeType||V.uri||"");N={file:`texture_${P}.${f?"jpg":"png"}`,data:K}}R.set(P,N)}if(!N)return;let S=typeof k.sampler=="number"?u[k.sampler]:void 0,o=V=>V===33071?"clamp":V===33648?"mirror":"repeat";return{file:N.file,data:N.data,wrapS:o(S?.wrapS),wrapT:o(S?.wrapT),...F?{scale:F}:{},...U?{bias:U}:{}}}function h(y){let F=l[y];if(!F)throw new Error(`Accessor ${y} not found`);let U=g[F.bufferView||0],_=(U.byteOffset||0)+(F.byteOffset||0),k=U.byteLength||0;return{acc:F,buffer:c.slice(_,_+k)}}function w(y,F,U,_){let k=[],P=v[y];if(!P)return k;let N=P.primitives||[];for(let S=0;S<N.length;S++){let o=N[S],V=o.attributes?.POSITION;if(V===void 0)continue;let{acc:K,buffer:f}=h(V),b=new Float32Array(f,0,K.count*3),n,p=o.attributes?.NORMAL;if(p!==void 0){let{acc:A,buffer:E}=h(p),H=new Float32Array(E,0,A.count*3);n=new Float32Array(H.length);for(let W=0;W<A.count;W++){let Z=H[W*3],Q=H[W*3+1],Y=H[W*3+2],le=Math.hypot(Z,Q,Y)||1;n[W*3]=Z/le,n[W*3+1]=Q/le,n[W*3+2]=Y/le}}let B,j=o.attributes?.TEXCOORD_0;if(j!==void 0){let{acc:A,buffer:E}=h(j);B=new Float32Array(E,0,A.count*2)}let z;if(o.indices!==void 0){let{acc:A,buffer:E}=h(o.indices);z=A.componentType===5125?new Uint32Array(E,0,A.count):new Uint16Array(E,0,A.count);let H=K.count;for(let W of z)if(W>=H)throw new Error(`SecurityError: Index buffer value (${W}) out of vertex bounds [0, ${H}).`)}else{let A=K.count;z=A>65535?new Uint32Array(A):new Uint16Array(A);for(let E=0;E<A;E++)z[E]=E}let ee="DefaultMaterial",L=[1,1,1],X=.5,J=0,ae=0,$=0,te=1.5,O=1,G=[0,0,0],q;if(o.material!==void 0&&d[o.material]){let A=d[o.material];ee=C[o.material]||`Material_${o.material}`;let E=A.pbrMetallicRoughness||{},H=(ve,we)=>Array.isArray(ve)&&ve.length>=3?[ve[0],ve[1],ve[2]]:we;L=H(E.baseColorFactor,[1,1,1]);let W=Array.isArray(E.baseColorFactor)&&typeof E.baseColorFactor[3]=="number"?E.baseColorFactor[3]:1,Z=L[0]!==1||L[1]!==1||L[2]!==1||W!==1,Q=m(E.baseColorTexture,Z?[L[0],L[1],L[2],W]:void 0),Y=A.extras?.avgColor;!Q&&Array.isArray(Y)&&Y.length>=3&&(L=[L[0]*Y[0],L[1]*Y[1],L[2]*Y[2]]),typeof E.roughnessFactor=="number"&&(X=E.roughnessFactor),typeof E.metallicFactor=="number"&&(J=E.metallicFactor);let le=typeof E.roughnessFactor=="number"?E.roughnessFactor:1,re=typeof E.metallicFactor=="number"?E.metallicFactor:1,se=m(E.metallicRoughnessTexture,le!==1||re!==1?[1,le,re,1]:void 0);G=H(A.emissiveFactor,[0,0,0]);let ne=(G[0]>0||G[1]>0||G[2]>0)&&(G[0]!==1||G[1]!==1||G[2]!==1)?[G[0],G[1],G[2],1]:void 0,oe=m(A.emissiveTexture,ne),pe=m(A.normalTexture,[2,2,2,1],[-1,-1,-1,0]),de=m(A.occlusionTexture);(Q||se||pe||oe||de)&&(q=[Q,se,pe,oe,de]);let ue=A.extensions||{};ue.KHR_materials_clearcoat&&(ae=ue.KHR_materials_clearcoat.clearcoatFactor??0,$=ue.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof ue.KHR_materials_ior?.ior=="number"&&(te=ue.KHR_materials_ior.ior),O=W*(1-(ue.KHR_materials_transmission?.transmissionFactor??0))}k.push({name:N.length>1?`${F}_p${S}`:F,positions:b,indices:z,normals:n,uvs:B,materialName:ee,color:L,roughness:X,metallic:J,clearcoat:ae,clearcoatRoughness:$,ior:te,opacity:O,emissiveColor:G,...q?{textures:q}:{},xrTraits:U||P.extras?.xr,..._?{invisible:!0}:{}})}return k}if(M.length>0){let y=new Float32Array(0),F=new Uint16Array(0),U=(b,n)=>{if(b===void 0)return null;let{acc:p,buffer:B}=h(b);return new Float32Array(B,0,p.count*n)},_=(b,n)=>Array.isArray(b)&&b.length>=3?[ie(b[0],n),ie(b[1],n),ie(b[2],n)]:[n,n,n],k=(b,n,p)=>b&&b.length>=(n+1)*3?[b[n*3],b[n*3+1],b[n*3+2]]:p,P=(b,n,p)=>b&&b.length>=(n+1)*4?[b[n*4],b[n*4+1],b[n*4+2],b[n*4+3]]:p,N=new Map,S=r.animations?.[0];if(S&&Array.isArray(S.channels)&&Array.isArray(S.samplers))for(let b of S.channels){let n=S.samplers[b?.sampler],p=b?.target?.node,B=b?.target?.path;if(!n||typeof p!="number"||n.input===void 0)continue;let j=N.get(p);j||(j={input:n.input},N.set(p,j)),B==="translation"?j.t=n.output:B==="rotation"?j.r=n.output:B==="scale"&&(j.s=n.output)}let o=r.scenes?.[r.scene??0]?.nodes??[];if(!Array.isArray(o)||o.length===0){let b=new Set;for(let n of M)if(Array.isArray(n?.children))for(let p of n.children)b.add(p);o=[];for(let n=0;n<M.length;n++)b.has(n)||o.push(n);o.length===0&&(o=[0])}let V=new Set,K=[],f=(b,n)=>{if(Array.isArray(b))for(let p=b.length-1;p>=0;p--)K.push({idx:b[p],out:n})};for(f(o,i);K.length>0;){let{idx:b,out:n}=K.pop();if(typeof b!="number"||b<0||b>=M.length||V.has(b))continue;V.add(b);let p=M[b];if(!p)continue;let B=[0,0,0],j=[0,0,0,1],z=[1,1,1];if(Array.isArray(p.matrix)&&p.matrix.length===16){let O=ht(p.matrix);B=O.t,j=O.r,z=O.s}else B=_(p.translation,0),Array.isArray(p.rotation)&&p.rotation.length>=4&&(j=[ie(p.rotation[0],0),ie(p.rotation[1],0),ie(p.rotation[2],0),ie(p.rotation[3],1)]),z=_(p.scale,1);let ee,L=N.get(b);if(L){let O=U(L.input,1);if(O&&O.length>0){let G=U(L.t,3),q=U(L.r,4),A=U(L.s,3),E=Array.from(O),H=[],W=[],Z=[];for(let Q=0;Q<O.length;Q++)H.push(k(G,Q,B)),W.push(P(q,Q,j)),Z.push(k(A,Q,z));ee={times:E,translations:H,rotations:W,scales:Z}}}let X=Array.isArray(p.children)?p.children:[],J=typeof p.mesh=="number"&&p.mesh>=0&&p.mesh<v.length,ae=t?.[b]?.userData?.xr??p.extras?.xr;if(!J&&X.length===0&&(p.camera!==void 0||p.extensions?.KHR_lights_punctual||!p.name&&!p.extras&&!ae&&!ee))continue;let $=(O,G,q)=>({name:O,positions:y,indices:F,isXform:!0,xrTraits:ae,timeSamples:ee,translation:B,rotation:j,scale:z,children:G,...q?{invisible:!0}:{}}),te=p.visible===!1||p.extensions?.KHR_node_visibility?.visible===!1||t?.[b]?.visible===!1;if(J){let O=p.name||v[p.mesh]?.name||`Mesh_${b}`,G=w(p.mesh,O,ae,te),q=p.extensions?.EXT_mesh_gpu_instancing?.attributes;if(q&&typeof q=="object"&&G.length>0){let A=U(q.TRANSLATION,3),E=U(q.ROTATION,4),H=U(q.SCALE,3),W=U(q._COLOR_0,3),Z=Math.min(1e3,A?A.length/3:E?E.length/4:H?H.length/3:0);if(Z>0){let Q=[];for(let Y=0;Y<Z;Y++){let le=k(A,Y,[0,0,0]),re=P(E,Y,[0,0,0,1]),se=k(H,Y,[1,1,1]);for(let ne of G){let oe=ne.color||[.8,.8,.8],pe=W&&W.length>=(Y+1)*3;Q.push({...ne,name:`${ne.name}_${Y}`,materialName:pe?`${ne.materialName}_inst_${Y}`:ne.materialName,color:pe?[oe[0]*W[Y*3],oe[1]*W[Y*3+1],oe[2]*W[Y*3+2]]:ne.color,translation:le,rotation:re,scale:se})}}f(X,Q),n.push($(O,Q,te));continue}}if(G.length===1)G[0].translation=B,G[0].rotation=j,G[0].scale=z,G[0].timeSamples=ee,X.length>0&&(G[0].children=[],f(X,G[0].children)),n.push(G[0]);else{let A=[...G];f(X,A),n.push($(O,A,te))}}else{let O=[];f(X,O),n.push($(p.name||`Group_${b}`,O,te))}}}else for(let y=0;y<v.length;y++){let F=v[y].name||`Mesh_${y}`;i.push(...w(y,F,v[y].extras?.xr))}return i}function Se(e,t){if(!e||typeof e!="string")return t;let i=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[0-9]/.test(i)&&(i="_"+i),i||t}function De(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function me(e){if(!Number.isFinite(e)||Math.abs(e)<1e-7)return"0";let t=Number(e.toFixed(5)).toString();return t.indexOf(".")===-1?`${t}.0`:t}var xe=(e,t,i)=>`(${me(e)}, ${me(t)}, ${me(i)})`,Le=(e,t,i,r)=>`(${me(e)}, ${me(t)}, ${me(i)}, ${me(r)})`;function ft(e){let t=e.length/3,i=new Array(t);for(let r=0;r<t;r++)i[r]=xe(e[r*3],e[r*3+1],e[r*3+2]);return i.join(", ")}function qt(e,t){let i=new Array(t);for(let r=0;r<t;r++)i[r]=`(${me(e[r*2])}, ${me(1-e[r*2+1])})`;return i.join(", ")}function Gt(e){return Array.from(e).join(", ")}function He(e){let t=new Map,i=0,r=null,a=[...e];for(;a.length>0;){let u=a.pop();if(!u.isXform&&u.positions&&u.positions.length>0){let x=Se(u.materialName,"DefaultMaterial");t.has(x)||t.set(x,{color:u.color||[1,1,1],roughness:u.roughness??.5,metallic:u.metallic??0,clearcoat:u.clearcoat??0,clearcoatRoughness:u.clearcoatRoughness??0,ior:u.ior??1.5,opacity:u.opacity??1,emissiveColor:u.emissiveColor||[0,0,0],textures:u.textures})}if(u.timeSamples&&u.timeSamples.times.length>0){let x=u.timeSamples.times[u.timeSamples.times.length-1];x>i&&(i=x)}if(u.xrTraits?.anchor&&!r&&(r=u.xrTraits.anchor==="vertical"||u.xrTraits.anchor==="wall"?"vertical":"horizontal"),u.children)for(let x=u.children.length-1;x>=0;x--)a.push(u.children[x])}let s="";i>0&&(s=`startTimeCode = 0
|
|
250
|
+
endTimeCode = ${me(i)}
|
|
251
251
|
timeCodesPerSecond = 1.0
|
|
252
|
-
`);let
|
|
252
|
+
`);let c="";r&&(c=`uniform token preliminary:anchoring:type = "plane"
|
|
253
253
|
uniform token preliminary:planeAnchoring:alignment = "${r}"
|
|
254
|
-
`);let
|
|
254
|
+
`);let l=`#usda 1.0
|
|
255
255
|
(
|
|
256
256
|
defaultPrim = "Root"
|
|
257
257
|
metersPerUnit = 1.0
|
|
@@ -262,80 +262,107 @@ def Xform "Root" (
|
|
|
262
262
|
kind = "component"
|
|
263
263
|
)
|
|
264
264
|
{
|
|
265
|
-
${
|
|
265
|
+
${c}def Scope "Materials"
|
|
266
266
|
{
|
|
267
|
-
`;for(let[
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
`),
|
|
272
|
-
`),
|
|
267
|
+
`;for(let[u,x]of t.entries()){let[C,R,T]=x.color,[m,h,w]=x.emissiveColor,y=`/Root/Materials/${u}`,[F,U,_,k,P]=x.textures||[],N=(f,b)=>`.connect = <${y}/${f}.outputs:${b}>`,S=F?`color3f inputs:diffuseColor${N("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${xe(C,R,T)}`,o=U?`float inputs:metallic${N("MetallicRoughnessTexture","b")}
|
|
268
|
+
float inputs:roughness${N("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${me(x.metallic)}
|
|
269
|
+
float inputs:roughness = ${me(x.roughness)}`,V="";x.clearcoat>0&&(V+=`float inputs:clearcoat = ${me(x.clearcoat)}
|
|
270
|
+
`,V+=`float inputs:clearcoatRoughness = ${me(x.clearcoatRoughness)}
|
|
271
|
+
`),x.ior!==1.5&&(V+=`float inputs:ior = ${me(x.ior)}
|
|
272
|
+
`),x.opacity<1&&(V+=`float inputs:opacity = ${me(x.opacity)}
|
|
273
|
+
`),k?V+=`color3f inputs:emissiveColor${N("EmissiveTexture","rgb")}
|
|
274
|
+
`:(m>0||h>0||w>0)&&(V+=`color3f inputs:emissiveColor = ${xe(m,h,w)}
|
|
275
|
+
`),_&&(V+=`normal3f inputs:normal${N("NormalTexture","rgb")}
|
|
276
|
+
`),P&&(V+=`float inputs:occlusion${N("OcclusionTexture","r")}
|
|
277
|
+
`);let K="";if(F||U||_||k||P){K+=`def Shader "PrimvarReader"
|
|
278
|
+
{
|
|
279
|
+
uniform token info:id = "UsdPrimvarReader_float2"
|
|
280
|
+
string inputs:varname = "st"
|
|
281
|
+
float2 outputs:result
|
|
282
|
+
}
|
|
283
|
+
`;let f=(b,n,p,B)=>{if(!n)return;let j=n.scale?`float4 inputs:scale = ${Le(n.scale[0],n.scale[1],n.scale[2],n.scale[3])}
|
|
284
|
+
`:"",z=n.bias?`float4 inputs:bias = ${Le(n.bias[0],n.bias[1],n.bias[2],n.bias[3])}
|
|
285
|
+
`:"";K+=`def Shader "${b}"
|
|
286
|
+
{
|
|
287
|
+
uniform token info:id = "UsdUVTexture"
|
|
288
|
+
asset inputs:file = @${De(n.file)}@
|
|
289
|
+
float2 inputs:st${N("PrimvarReader","result")}
|
|
290
|
+
token inputs:sourceColorSpace = "${p}"
|
|
291
|
+
token inputs:wrapS = "${n.wrapS||"repeat"}"
|
|
292
|
+
token inputs:wrapT = "${n.wrapT||"repeat"}"
|
|
293
|
+
${j}${z}${B}}
|
|
294
|
+
`};f("DiffuseTexture",F,"sRGB",`float3 outputs:rgb
|
|
295
|
+
`),f("MetallicRoughnessTexture",U,"raw",`float outputs:g
|
|
296
|
+
float outputs:b
|
|
297
|
+
`),f("NormalTexture",_,"raw",`float3 outputs:rgb
|
|
298
|
+
`),f("EmissiveTexture",k,"sRGB",`float3 outputs:rgb
|
|
299
|
+
`),f("OcclusionTexture",P,"raw",`float outputs:r
|
|
300
|
+
`)}l+=`def Material "${u}"
|
|
273
301
|
{
|
|
274
302
|
def Shader "PBRShader"
|
|
275
303
|
{
|
|
276
304
|
uniform token info:id = "UsdPreviewSurface"
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
${w}token outputs:surface
|
|
281
|
-
}
|
|
282
|
-
token outputs:surface.connect = </Root/Materials/${h}/PBRShader.outputs:surface>
|
|
305
|
+
${S}
|
|
306
|
+
${o}
|
|
307
|
+
${V}token outputs:surface
|
|
283
308
|
}
|
|
284
|
-
|
|
309
|
+
token outputs:surface${N("PBRShader","surface")}
|
|
310
|
+
${K}}
|
|
311
|
+
`}l+=`}
|
|
285
312
|
def Scope "Meshes"
|
|
286
313
|
{
|
|
287
|
-
`;let
|
|
314
|
+
`;let g=(u,x,C)=>{let R=[];x&&R.push('"MaterialBindingAPI"');let T=!!(u?.rigidBody&&u.rigidBody!=="none"&&(typeof u.rigidBody!="object"||u.rigidBody.enabled!==!1)),m=!!(u?.physics&&u.physics!=="none"||T);m&&R.push(...T?['"PhysicsBodyAPI"','"PhysicsRigidBodyAPI"','"PhysicsCollisionAPI"','"PhysicsMassAPI"']:['"PhysicsBodyAPI"','"PhysicsCollisionAPI"']);let h=[];if(R.length>0&&h.push(`prepend apiSchemas = [${R.join(", ")}]`),u){let _=ge().xrTraitSerializer?.usdLines(u,De)??[];if(!_.length)for(let k of["grab","billboard","follow","anchor","physics"]){let P=k==="follow"&&typeof u.follow=="object"?u.follow.mode??"head":u[k];P!==void 0&&_.push(`string ${k} = "${De(P)}"`)}_.length>0&&h.push(`customData = {
|
|
288
315
|
dictionary xr = {
|
|
289
|
-
${
|
|
316
|
+
${_.join(`
|
|
290
317
|
`)}
|
|
291
318
|
}
|
|
292
|
-
}`)}let
|
|
293
|
-
${
|
|
319
|
+
}`)}let w=h.length>0?` (
|
|
320
|
+
${h.join(`
|
|
294
321
|
`)}
|
|
295
|
-
)`:"",
|
|
296
|
-
`:"";if(
|
|
297
|
-
bool physics:kinematicEnabled = ${
|
|
322
|
+
)`:"",y=C?`uniform token visibility = "invisible"
|
|
323
|
+
`:"";if(m){let _=u?.rigidBody??u?.physics,k=_?.body??_?.mode??_;y+=`bool physics:rigidBodyEnabled = true
|
|
324
|
+
bool physics:kinematicEnabled = ${k==="static"||k==="kinematic"}
|
|
298
325
|
bool physics:collisionEnabled = true
|
|
299
|
-
`,
|
|
300
|
-
`)}let
|
|
326
|
+
`,_?.mass>0&&Number.isFinite(_.mass)&&(y+=`float physics:mass = ${me(_.mass)}
|
|
327
|
+
`)}let F=ct(u),U=F?`def SpatialAudio "AudioEmitter"
|
|
301
328
|
{
|
|
302
|
-
${
|
|
303
|
-
`:""}uniform token inputs:auralMode = "${
|
|
304
|
-
uniform token inputs:playbackMode = "${
|
|
305
|
-
double gain = ${
|
|
329
|
+
${F.src?`asset inputs:file = @${De(F.src)}@
|
|
330
|
+
`:""}uniform token inputs:auralMode = "${F.isGlobal?"nonSpatial":"spatial"}"
|
|
331
|
+
uniform token inputs:playbackMode = "${F.loop?"loopFromStart":"onceFromStart"}"
|
|
332
|
+
double gain = ${me(F.volume)}
|
|
306
333
|
}
|
|
307
|
-
`:"";return{header:
|
|
308
|
-
quatf xformOp:orient.timeSamples = { ${
|
|
309
|
-
double3 xformOp:scale.timeSamples = { ${
|
|
334
|
+
`:"";return{header:w,body:y,tail:U}},d=u=>{if(u.timeSamples&&u.timeSamples.times.length>0){let h=u.timeSamples,w=(_,k,P)=>h.times.map((N,S)=>`${me(N)}: ${P(_?.[S]||k)}`).join(", "),y=w(h.translations,[0,0,0],_=>xe(_[0],_[1],_[2])),F=w(h.rotations,[0,0,0,1],_=>{let k=Math.hypot(_[0],_[1],_[2],_[3])||1;return Le(_[3]/k,_[0]/k,_[1]/k,_[2]/k)}),U=w(h.scales,[1,1,1],_=>xe(_[0],_[1],_[2]));return`double3 xformOp:translate.timeSamples = { ${y} }
|
|
335
|
+
quatf xformOp:orient.timeSamples = { ${F} }
|
|
336
|
+
double3 xformOp:scale.timeSamples = { ${U} }
|
|
310
337
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
|
|
311
|
-
`}let
|
|
312
|
-
`,
|
|
313
|
-
`,
|
|
314
|
-
`,
|
|
315
|
-
`),
|
|
316
|
-
int[] faceVertexCounts = [${
|
|
317
|
-
int[] faceVertexIndices = [${
|
|
318
|
-
point3f[] points = [${ft(
|
|
319
|
-
`;return
|
|
338
|
+
`}let x=[],C="",R=u.translation;R&&(Math.abs(R[0])>1e-7||Math.abs(R[1])>1e-7||Math.abs(R[2])>1e-7)&&(C+=`double3 xformOp:translate = ${xe(R[0],R[1],R[2])}
|
|
339
|
+
`,x.push('"xformOp:translate"'));let T=u.rotation;if(T){let h=Math.hypot(T[0],T[1],T[2],T[3])||1,w=T[0]/h,y=T[1]/h,F=T[2]/h,U=T[3]/h;(1-Math.abs(U)>1e-7||Math.hypot(w,y,F)>1e-7)&&(C+=`quatf xformOp:orient = ${Le(U,w,y,F)}
|
|
340
|
+
`,x.push('"xformOp:orient"'))}let m=u.scale;return m&&(Math.abs(m[0]-1)>1e-7||Math.abs(m[1]-1)>1e-7||Math.abs(m[2]-1)>1e-7)&&(C+=`float3 xformOp:scale = ${xe(m[0],m[1],m[2])}
|
|
341
|
+
`,x.push('"xformOp:scale"')),x.length>0&&(C+=`uniform token[] xformOpOrder = [${x.join(", ")}]
|
|
342
|
+
`),C},v=u=>{let x=u.positions.length/3,C=1/0,R=1/0,T=1/0,m=-1/0,h=-1/0,w=-1/0;for(let k=0;k<x;k++){let P=u.positions[k*3],N=u.positions[k*3+1],S=u.positions[k*3+2];P<C&&(C=P),P>m&&(m=P),N<R&&(R=N),N>h&&(h=N),S<T&&(T=S),S>w&&(w=S)}isFinite(C)||(C=R=T=-1,m=h=w=1);let y=Math.floor(u.indices.length/3),F=Se(u.materialName,"DefaultMaterial"),U=y>0?y===1?"3":"3, ".repeat(y-1)+"3":"",_=`float3[] extent = [${xe(C,R,T)}, ${xe(m,h,w)}]
|
|
343
|
+
int[] faceVertexCounts = [${U}]
|
|
344
|
+
int[] faceVertexIndices = [${Gt(u.indices)}]
|
|
345
|
+
point3f[] points = [${ft(u.positions)}]
|
|
346
|
+
`;return u.normals&&u.normals.length===u.positions.length&&(_+=`normal3f[] normals = [${ft(u.normals)}] (
|
|
320
347
|
interpolation = "vertex"
|
|
321
348
|
)
|
|
322
|
-
`),
|
|
349
|
+
`),u.uvs&&u.uvs.length===x*2&&(_+=`texCoord2f[] primvars:st = [${qt(u.uvs,x)}] (
|
|
323
350
|
interpolation = "vertex"
|
|
324
351
|
)
|
|
325
|
-
`),
|
|
326
|
-
`,
|
|
327
|
-
`;continue}let{node:
|
|
352
|
+
`),_+=`rel material:binding = </Root/Materials/${F}>
|
|
353
|
+
`,_},M=new Set,I=[];for(let u=e.length-1;u>=0;u--)I.push({node:e[u],siblings:M});let D=0;for(;I.length>0;){let u=I.pop();if(u.close){l+=`}
|
|
354
|
+
`;continue}let{node:x,siblings:C}=u,R=!!(x.isXform||x.positions.length===0),T=ut(C,Se(x.name,R?`Group_${D}`:`Mesh_${D}`));D++;let m=x.children||[];if(R){let h=g(x.xrTraits,!1,x.invisible);l+=`def Xform "${T}"${h.header}
|
|
328
355
|
{
|
|
329
|
-
${
|
|
356
|
+
${h.body}${d(x)}${h.tail}`,I.push({close:!0});let w=new Set;for(let y=m.length-1;y>=0;y--)I.push({node:m[y],siblings:w})}else if(m.length>0){let h=g(x.xrTraits,!1,x.invisible),w=`${T}_mesh`;l+=`def Xform "${T}"${h.header}
|
|
330
357
|
{
|
|
331
|
-
${
|
|
358
|
+
${h.body}${d(x)}${h.tail}`,l+=`def Mesh "${w}" (
|
|
332
359
|
prepend apiSchemas = ["MaterialBindingAPI"]
|
|
333
360
|
)
|
|
334
361
|
{
|
|
335
|
-
${
|
|
336
|
-
`,
|
|
362
|
+
${v(x)}}
|
|
363
|
+
`,I.push({close:!0});let y=new Set([w]);for(let F=m.length-1;F>=0;F--)I.push({node:m[F],siblings:y})}else{let h=g(x.xrTraits,!0,x.invisible);l+=`def Mesh "${T}"${h.header}
|
|
337
364
|
{
|
|
338
|
-
${
|
|
339
|
-
`}}return
|
|
365
|
+
${h.body}${d(x)}${v(x)}${h.tail}}
|
|
366
|
+
`}}return l+=`}
|
|
340
367
|
}
|
|
341
|
-
`,o}function Xt(e,t){if(e&&typeof e.traverse=="function"){let a=qt(e,t);return Be(a)}let i=Ae(e),r=$e(i);return Be(r)}var Se=null;function dt(e){if(!Se){Se=new Uint32Array(256);for(let i=0;i<256;i++){let r=i;for(let a=0;a<8;a++)r=r&1?3988292384^r>>>1:r>>>1;Se[i]=r}}let t=4294967295;for(let i=0;i<e.length;i++)t=Se[(t^e[i])&255]^t>>>8;return(t^4294967295)>>>0}function pt(e){let t=[],i=0,r=[];for(let p of e){let y=ct(p.filename),D=dt(p.data),S=p.data.length,h=30+y.length,v=(i+h)%64,P=v!==0?64-v:0,T=new Uint8Array(h+P),x=new DataView(T.buffer);x.setUint32(0,67324752,!0),x.setUint16(4,20,!0),x.setUint32(14,D,!0),x.setUint32(18,S,!0),x.setUint32(22,S,!0),x.setUint16(26,y.length,!0),x.setUint16(28,P,!0),T.set(y,30),t.push({offset:i,size:S,crc:D,filenameBytes:y,entry:p}),r.push(T,p.data),i+=T.length+p.data.length}let a=i;for(let p of t){let y=new Uint8Array(46+p.filenameBytes.length),D=new DataView(y.buffer);D.setUint32(0,33639248,!0),D.setUint16(4,20,!0),D.setUint16(6,20,!0),D.setUint32(16,p.crc,!0),D.setUint32(20,p.size,!0),D.setUint32(24,p.size,!0),D.setUint16(28,p.filenameBytes.length,!0),D.setUint32(42,p.offset,!0),y.set(p.filenameBytes,46),r.push(y),i+=y.length}let s=i-a,u=new Uint8Array(22),o=new DataView(u.buffer);o.setUint32(0,101010256,!0),o.setUint16(8,t.length,!0),o.setUint16(10,t.length,!0),o.setUint32(12,s,!0),o.setUint32(16,a,!0),r.push(u),i+=22;let d=new Uint8Array(i),f=0;for(let p of r)d.set(p,f),f+=p.length;return d}var Wt=e=>pt([{filename:"model.usda",data:ct(e)}]);function gt(e){return Wt(Be($e(Ae(e))))}function vt(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():gt(e)}function xt(e){let t=vt(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function He(){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function ze(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function je(){if(typeof navigator>"u")return!1;let e=navigator;if(!e.xr||typeof e.xr.isSessionSupported!="function")return!1;try{return await e.xr.isSessionSupported("immersive-ar")?!0:await e.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function Yt(){let e=[];return await je()&&e.push("webxr"),He()&&e.push("quick-look"),ze()&&e.push("scene-viewer"),e}async function Zt(){return(await qe()).bestMode}async function qe(){let[e,t,i]=await Promise.all([je(),Promise.resolve(He()),Promise.resolve(ze())]),r=[];t&&r.push("quick-look"),e&&r.push("webxr"),i&&r.push("scene-viewer");let a=null;return t?a="quick-look":e?a="webxr":i&&(a="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:i,availableModes:r,bestMode:a}}function Ge(e,t={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let i,r=!1;if(typeof e=="string"){if(i=Qt(e),!i)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else i=URL.createObjectURL(e),r=!0;let a=[];if(t.allowScale===!1&&a.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let o=De(t.canonicalWebPageUrl,!1);o&&a.push(`canonicalWebPageURL=${encodeURIComponent(o)}`)}t.checkoutTitle&&a.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&a.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&a.push(`price=${encodeURIComponent(t.price)}`),a.length>0&&(i+=`#${a.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",i);let u=document.createElement("img");u.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),u.style.display="none",s.appendChild(u),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),r&&URL.revokeObjectURL(i.split("#")[0])},3e3)}function De(e,t=!1){if(typeof e!="string")return"";let i=e.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://")||t&&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 Qt(e){try{return De(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function bt(e,t={}){let i=De(e,!0),r=t.mode||"ar_preferred",a=new URLSearchParams({file:i,mode:r,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&a.set("title",t.title),t.link&&a.set("link",De(t.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${a.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function yt(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let i=bt(e,t);window.location.href=i}var ye=null;function Jt(e,t){let i=new Float32Array(144),r=new Float32Array(144),a=new Float32Array(96),s=new Uint16Array(144);for(let p=0;p<24;p++){let y=p/24*Math.PI*2,D=Math.cos(y),S=Math.sin(y),h=p*2,v=h+1,P=(p+1)%24*2;i[h*3]=D*.11,i[h*3+1]=.002,i[h*3+2]=S*.11,i[v*3]=D*.145,i[v*3+1]=.002,i[v*3+2]=S*.145,r[h*3+1]=r[v*3+1]=1,s.set([h,P,v,v,P,P+1],p*6)}let u=e.createVertexArray();e.bindVertexArray(u);let o=(p,y,D)=>{let S=e.createBuffer();return e.bindBuffer(34962,S),e.bufferData(34962,p,35044),e.enableVertexAttribArray(y),e.vertexAttribPointer(y,D,5126,!1,0,0),S},d=[o(i,0,3),o(r,1,3),o(a,2,2)],f=e.createBuffer();return d.push(f),e.bindBuffer(34963,f),e.bufferData(34963,s,35044),e.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:u,indexCount:s.length,indexType:5123,baseColor:t&&t.length>=3?[t[0],t[1],t[2],t[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:d}]}}function Mt(e,t,i,r,a){let s=Math.cos(r),u=Math.sin(r),o=Math.max(.01,a);e.fill(0),e[0]=o*s,e[2]=-o*u,e[5]=o,e[8]=o*u,e[10]=o*s,e[12]=t[0]-o*(s*i[0]+u*i[2]),e[13]=t[1]-o*i[1],e[14]=t[2]-o*(-u*i[0]+s*i[2]),e[15]=1}var wt=class{constructor(e={}){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=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");ye&&ye!==this&&ye.isSessionActive()&&await ye.stop().catch(()=>{});let i=navigator.xr,r=this.opts,a=t||e?.container,s=String(a?.tagName||"").toLowerCase()==="xr-live",u=e?.bounds,o=Number(u?.radius)||1,d=Array.isArray(u?.center)?u.center:[0,0,0],f=Array.isArray(u?.min)?u.min:[-.5,-.5,-.5],p=typeof navigator<"u"&&navigator.userAgent||"",y=/Android|iPhone|iPad|iPod/i.test(p)&&!/Quest|Oculus|Pico|Vision/i.test(p),D=s?r.arScale==="fixed"?1:y?.55:1:r.arScale==="fixed"?1:o>.45?.3/o:o<.05?.12/Math.max(o,.001):1,S=s?[0,-.25,0]:[d[0]||0,r.arPlacement==="wall"?d[1]:f[1]??0,d[2]||0],h="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(h="immersive-vr")}catch{h="immersive-vr"}let v=a?.querySelector?.('[slot="ar-overlay"]')||null,P=!1,T=null,x=()=>{P&&v?.parentNode&&v.parentNode.removeChild(v),v=null,T=null,P=!1};if(h==="immersive-ar"){if(v)v.addEventListener?.("beforexrselect",C=>C.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let C=document.createElement("div");C.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 U=document.createElement("button");U.type="button",U.textContent="\u2715 Exit AR",U.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",U.addEventListener("beforexrselect",k=>k.preventDefault()),U.addEventListener("click",k=>{k.stopPropagation(),this.stop().catch(()=>{})}),T=document.createElement("div"),T.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",T.textContent="Move phone to detect a surface \u2022 Tap to place",C.appendChild(U),C.appendChild(T),document.body.appendChild(C),v=C,P=!0}}let c=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),l={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(c)};v&&(c.add("dom-overlay"),l.optionalFeatures=Array.from(c),l.domOverlay={root:v});for(let C of he)C.onConfigureXRSessionInit?.(a,l);Array.isArray(l.optionalFeatures)&&l.optionalFeatures.includes("dom-overlay")&&!l.domOverlay?.root&&(l.optionalFeatures=l.optionalFeatures.filter(C=>C!=="dom-overlay"));let b=C=>{let U=String(C?.name||"");return U==="NotAllowedError"||U==="SecurityError"};try{this.s=await i.requestSession(h,l)}catch(C){if(x(),b(C))throw r.onError?.(C),C;try{this.s=await i.requestSession(h,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(U){if(b(U))throw r.onError?.(U),U;try{this.s=await i.requestSession(h)}catch(k){throw r.onError?.(k),k}}}let w=this.s;ye=this,this.placed=!1;let O=null,B=null,E=null,N=null,R=null,L=[0,-.25,-1.2],M=[0,-.25,-1.2],n=new Float32Array(16),$=new Float32Array(16),W=!1,g=1,_=0,m=!1,A=null,q=null,K=0,H=null,Q=()=>{ye===this&&(ye=null),H?.(),H=null;try{B?.cancel?.()}catch{}if(B=null,E){let C=e?.meshes;if(Array.isArray(C)){let k=C.indexOf(E);k!==-1&&C.splice(k,1)}let U=e.getGLContext?.()||e?.gl;if(U)for(let k of E.primitives||[]){U.deleteVertexArray?.(k.vao);for(let j of k.buffers||[])U.deleteBuffer?.(j)}E=null}e?.setXRSessionActive?.(!1),x(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=Q,w.addEventListener("end",()=>{Q(),r.onExit?.()}),w.addEventListener("select",()=>{if(!this.placed){let C=R||L;M=[C[0],C[1],C[2]],Mt(this.placedMat,M,S,_,D*g),this.placed=!0,E&&(E.visible=!1),T&&(T.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let C=e.getGLContext?.()||e?.gl;C&&typeof C.makeXRCompatible=="function"&&await C.makeXRCompatible();let U=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;C&&typeof U=="function"&&typeof w.updateRenderState=="function"&&w.updateRenderState({baseLayer:new U(w,C,{alpha:!0})});try{O=await w.requestReferenceSpace("local")}catch{try{O=await w.requestReferenceSpace("local-floor")}catch{O=await w.requestReferenceSpace("viewer")}}let k=await w.requestReferenceSpace("viewer").catch(()=>O);if(typeof w.requestHitTestSource=="function"&&k&&(B=await w.requestHitTestSource({space:k}).catch(()=>null)),h==="immersive-ar"&&C&&typeof C.createVertexArray=="function"&&Array.isArray(e.meshes)&&(E=Jt(C,r.reticleColor),e.meshes.push(E)),typeof window<"u"&&typeof window.addEventListener=="function"){let F=I=>Math.hypot(I.touches[1].clientX-I.touches[0].clientX,I.touches[1].clientY-I.touches[0].clientY),G=I=>Math.atan2(I.touches[1].clientY-I.touches[0].clientY,I.touches[1].clientX-I.touches[0].clientX),V=I=>{this.s&&(I.touches.length===1&&this.placed?m=!0:I.touches.length>=2&&(m=!1,A=F(I),q=G(I)))},X=I=>{if(!this.s||I.touches.length<2)return;let J=F(I),Y=G(I);if(A&&A>4&&r.arScale!=="fixed"&&(g=Math.max(.15,Math.min(6,g*(J/A)))),q!==null){let ae=Y-q;ae>Math.PI&&(ae-=Math.PI*2),ae<-Math.PI&&(ae+=Math.PI*2),_-=ae}A=J,q=Y},z=I=>{(!I.touches||I.touches.length===0)&&(m=!1),(!I.touches||I.touches.length<2)&&(A=null,q=null)};window.addEventListener("touchstart",V,{passive:!0}),window.addEventListener("touchmove",X,{passive:!0}),window.addEventListener("touchend",z,{passive:!0}),window.addEventListener("touchcancel",z,{passive:!0}),H=()=>{window.removeEventListener("touchstart",V),window.removeEventListener("touchmove",X),window.removeEventListener("touchend",z),window.removeEventListener("touchcancel",z)}}e.setXRSessionActive?.(!0);let j=(F,G)=>{if(this.s!==w)return;w.requestAnimationFrame(j);let V=K>0?Math.min(Math.max((F-K)/1e3,0),.1):1/60;K=F,e?.stepXRUpdate?.(V);let X=G.getViewerPose(O);if(!X)return;let z=X.views?.[0];if(!W&&z?.transform){let te=z.transform.position,ie=z.transform.matrix,ce=te?.x??(ie?ie[12]:0),re=te?.y??(ie?ie[13]:0),se=te?.z??(ie?ie[14]:0),ne=ie?-ie[8]:0,oe=ie?-ie[10]:-1,de=Math.hypot(ne,oe);de>1e-4?(ne/=de,oe/=de):(ne=0,oe=-1),L=[ce+ne*1.2,re-.25,se+oe*1.2],_=Math.atan2(-ne,-oe),W=!0}if(B&&typeof G.getHitTestResults=="function"&&(!this.placed||m)){let te=G.getHitTestResults(B)||[],ie=!1;for(let ce of te){let re=ce.getPose(O);if(re?.transform?.matrix){let se=re.transform.matrix,ne=se[5];if(r.arPlacement==="wall"&&Math.abs(ne)>.35||r.arPlacement==="floor"&&Math.abs(ne)<.65)continue;N||(N=new Float32Array(16)),N.set(se),R=[se[12],se[13],se[14]],this.placed&&m&&(M=[se[12],se[13],se[14]]),E&&(E.visible=!this.placed||m,E.transform.set(se)),!this.placed&&T&&(T.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(N),ie=!0;break}}!ie&&E&&(E.visible=!1)}Mt(n,this.placed?M:R||L,S,_,D*g),this.placed&&this.placedMat.set(n);let I=e.xrRigMatrix;I instanceof Float32Array&&I.length===16?me($,I,n):$.set(n),e.modelRootMatrix&&e.modelRootMatrix.set($);for(let te of he)te.onXRFrame?.(e,w,G,O);let J=e.getGLContext?.()||e?.gl,Y=w.renderState?.baseLayer;J&&Y&&Y.framebuffer!==void 0&&J.bindFramebuffer(36160,Y.framebuffer);let ae=h==="immersive-ar",Z=X.views||[];for(let te=0;te<Z.length;te++){let ie=Z[te];if(typeof e.renderXRView=="function"){let ce;if(Y&&typeof Y.getViewport=="function"){let re=Y.getViewport(ie);re&&re.width>0&&re.height>0&&(ce=[re.x,re.y,re.width,re.height])}else Y?.framebufferWidth>0&&Y?.framebufferHeight>0&&(ce=[0,0,Y.framebufferWidth,Y.framebufferHeight]);e.renderXRView(ie,$,this.placed,ce,ae,te)}}J&&Y&&Y.framebuffer&&J.bindFramebuffer(36160,null)};w.requestAnimationFrame(j)}catch(C){throw typeof w.end=="function"&&await w.end().catch(()=>{}),Q(),r.onError?.(C),C}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function ei(e){let t=await qe(),i=e.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let o of i)if(t.availableModes.includes(o)){r=o;break}if(r||(r=t.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let a={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},s={...e.sceneViewerOptions,resizable:e.arScale==="fixed"?!1:e.sceneViewerOptions?.resizable,enableVerticalPlacement:e.arPlacement==="wall"?!0:e.sceneViewerOptions?.enableVerticalPlacement},u={...e.webXROptions,arScale:e.arScale||e.webXROptions?.arScale,arPlacement:e.arPlacement||e.webXROptions?.arPlacement};try{if(r==="quick-look"){let o;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")o=e.model;else{if(typeof e.model=="string")return Ge(e.model,a),{mode:"quick-look",success:!0};o=xt(e.model)}return Ge(o,a),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let o=e.glbUrl||(typeof e.model=="string"?e.model:null);if(!o)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return yt(o,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let o=new wt(u);return await o.start(e.view,e.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}`)}}export{wt as WebXRSessionManager,ei as activateAR,pt as buildUSDZZip,dt as calculateCRC32,bt as createSceneViewerIntent,xt as createUSDZBlob,Xt as generateUSDA,vt as generateUSDZ,qe as getARCapabilities,Yt as getAvailableARModes,Zt as getBestARMode,gt as glbToUSDZ,He as isQuickLookSupported,ze as isSceneViewerSupported,je as isWebXRSupported,Ge as launchQuickLook,yt as launchSceneViewer};
|
|
368
|
+
`,l}function Wt(e,t){if(e&&typeof e.traverse=="function"){let a=Xt(e,t);return He(a)}let i=Re(e),r=Be(i);return He(r)}var Ie=null;function pt(e){if(!Ie){Ie=new Uint32Array(256);for(let i=0;i<256;i++){let r=i;for(let a=0;a<8;a++)r=r&1?3988292384^r>>>1:r>>>1;Ie[i]=r}}let t=4294967295;for(let i=0;i<e.length;i++)t=Ie[(t^e[i])&255]^t>>>8;return(t^4294967295)>>>0}function dt(e){let t=[],i=0,r=[];for(let v of e){let M=mt(v.filename),I=pt(v.data),D=v.data.length,u=30+M.length,x=(i+u)%64,C=x!==0?64-x:0;C>0&&C<4&&(C+=64);let R=new Uint8Array(u+C),T=new DataView(R.buffer);T.setUint32(0,67324752,!0),T.setUint16(4,20,!0),T.setUint32(14,I,!0),T.setUint32(18,D,!0),T.setUint32(22,D,!0),T.setUint16(26,M.length,!0),T.setUint16(28,C,!0),R.set(M,30),C>=4&&(T.setUint16(u,6534,!0),T.setUint16(u+2,C-4,!0)),t.push({offset:i,size:D,crc:I,filenameBytes:M,entry:v}),r.push(R,v.data),i+=R.length+v.data.length}let a=i;for(let v of t){let M=new Uint8Array(46+v.filenameBytes.length),I=new DataView(M.buffer);I.setUint32(0,33639248,!0),I.setUint16(4,20,!0),I.setUint16(6,20,!0),I.setUint32(16,v.crc,!0),I.setUint32(20,v.size,!0),I.setUint32(24,v.size,!0),I.setUint16(28,v.filenameBytes.length,!0),I.setUint32(42,v.offset,!0),M.set(v.filenameBytes,46),r.push(M),i+=M.length}let s=i-a,c=new Uint8Array(22),l=new DataView(c.buffer);l.setUint32(0,101010256,!0),l.setUint16(8,t.length,!0),l.setUint16(10,t.length,!0),l.setUint32(12,s,!0),l.setUint32(16,a,!0),r.push(c),i+=22;let g=new Uint8Array(i),d=0;for(let v of r)g.set(v,d),d+=v.length;return g}function Kt(e){let t=[{filename:"model.usda",data:mt(He(e))}],i=new Set(["model.usda"]),r=[...e];for(;r.length>0;){let a=r.pop();for(let s of a.textures||[])s?.file&&s.data?.byteLength&&!i.has(s.file)&&(i.add(s.file),t.push({filename:s.file,data:s.data}));if(a.children)for(let s=a.children.length-1;s>=0;s--)r.push(a.children[s])}return dt(t)}function gt(e){return Kt(Be(Re(e)))}function vt(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():gt(e)}function xt(e){let t=vt(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function ze(){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent||"";if(!(/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))return!1;let t=document.createElement("a");return t.relList!==void 0&&t.relList.supports!==void 0&&t.relList.supports("ar")}function je(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function Xe(){if(typeof navigator>"u")return!1;let e=navigator;if(!e.xr||typeof e.xr.isSessionSupported!="function")return!1;try{return await e.xr.isSessionSupported("immersive-ar")?!0:await e.xr.isSessionSupported("immersive-vr")}catch{return!1}}async function Yt(){let e=[];return await Xe()&&e.push("webxr"),ze()&&e.push("quick-look"),je()&&e.push("scene-viewer"),e}async function Zt(){return(await qe()).bestMode}async function qe(){let[e,t,i]=await Promise.all([Xe(),Promise.resolve(ze()),Promise.resolve(je())]),r=[];t&&r.push("quick-look"),e&&r.push("webxr"),i&&r.push("scene-viewer");let a=null;return t?a="quick-look":e?a="webxr":i&&(a="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:i,availableModes:r,bestMode:a}}function Ge(e,t={}){if(typeof document>"u")throw new Error("launchQuickLook requires a browser DOM environment");let i,r=!1;if(typeof e=="string"){if(i=Qt(e),!i)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else i=URL.createObjectURL(e),r=!0;let a=[];if(t.allowScale===!1&&a.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let l=_e(t.canonicalWebPageUrl,!1);l&&a.push(`canonicalWebPageURL=${encodeURIComponent(l)}`)}t.checkoutTitle&&a.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&a.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&a.push(`price=${encodeURIComponent(t.price)}`),a.length>0&&(i+=`#${a.join("&")}`);let s=document.createElement("a");s.setAttribute("rel","ar"),s.setAttribute("href",i);let c=document.createElement("img");c.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),c.style.display="none",s.appendChild(c),document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),r&&URL.revokeObjectURL(i.split("#")[0])},3e3)}function _e(e,t=!1){if(typeof e!="string")return"";let i=e.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://")||t&&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 Qt(e){try{return _e(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function bt(e,t={}){let i=_e(e,!0),r=t.mode||"ar_preferred",a=new URLSearchParams({file:i,mode:r,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&a.set("title",t.title),t.link&&a.set("link",_e(t.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${a.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function yt(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let i=bt(e,t);window.location.href=i}var Me=null;function Jt(e,t){let i=new Float32Array(144),r=new Float32Array(144),a=new Float32Array(96),s=new Uint16Array(144);for(let v=0;v<24;v++){let M=v/24*Math.PI*2,I=Math.cos(M),D=Math.sin(M),u=v*2,x=u+1,C=(v+1)%24*2;i[u*3]=I*.11,i[u*3+1]=.002,i[u*3+2]=D*.11,i[x*3]=I*.145,i[x*3+1]=.002,i[x*3+2]=D*.145,r[u*3+1]=r[x*3+1]=1,s.set([u,C,x,x,C,C+1],v*6)}let c=e.createVertexArray();e.bindVertexArray(c);let l=(v,M,I)=>{let D=e.createBuffer();return e.bindBuffer(34962,D),e.bufferData(34962,v,35044),e.enableVertexAttribArray(M),e.vertexAttribPointer(M,I,5126,!1,0,0),D},g=[l(i,0,3),l(r,1,3),l(a,2,2)],d=e.createBuffer();return g.push(d),e.bindBuffer(34963,d),e.bufferData(34963,s,35044),e.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:c,indexCount:s.length,indexType:5123,baseColor:t&&t.length>=3?[t[0],t[1],t[2],t[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:g}]}}function Mt(e,t,i,r,a){let s=Math.cos(r),c=Math.sin(r),l=Math.max(.01,a);e.fill(0),e[0]=l*s,e[2]=-l*c,e[5]=l,e[8]=l*c,e[10]=l*s,e[12]=t[0]-l*(s*i[0]+c*i[2]),e[13]=t[1]-l*i[1],e[14]=t[2]-l*(-c*i[0]+s*i[2]),e[15]=1}var wt=class{constructor(e={}){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=e}isSessionActive(){return this.s!==null}hasPlacedModel(){return this.placed}getPlacedMatrix(){return this.placedMat}async start(e,t){if(typeof navigator>"u"||!navigator.xr)throw new Error("WebXR is not supported on this browser.");Me&&Me!==this&&Me.isSessionActive()&&await Me.stop().catch(()=>{});let i=navigator.xr,r=this.opts,a=t||e?.container,s=String(a?.tagName||"").toLowerCase()==="xr-live",c=e?.bounds,l=Number(c?.radius)||1,g=Array.isArray(c?.center)?c.center:[0,0,0],d=Array.isArray(c?.min)?c.min:[-.5,-.5,-.5],v=typeof navigator<"u"&&navigator.userAgent||"",M=/Android|iPhone|iPad|iPod/i.test(v)&&!/Quest|Oculus|Pico|Vision/i.test(v),I=s?r.arScale==="fixed"?1:M?.55:1:r.arScale==="fixed"?1:l>.45?.3/l:l<.05?.12/Math.max(l,.001):1,D=s?[0,-.25,0]:[g[0]||0,r.arPlacement==="wall"?g[1]:d[1]??0,g[2]||0],u="immersive-ar";try{await i.isSessionSupported("immersive-ar")||(u="immersive-vr")}catch{u="immersive-vr"}let x=a?.querySelector?.('[slot="ar-overlay"]')||null,C=!1,R=null,T=()=>{C&&x?.parentNode&&x.parentNode.removeChild(x),x=null,R=null,C=!1};if(u==="immersive-ar"){if(x)x.addEventListener?.("beforexrselect",L=>L.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let L=document.createElement("div");L.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 X=document.createElement("button");X.type="button",X.textContent="\u2715 Exit AR",X.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",X.addEventListener("beforexrselect",J=>J.preventDefault()),X.addEventListener("click",J=>{J.stopPropagation(),this.stop().catch(()=>{})}),R=document.createElement("div"),R.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",R.textContent="Move phone to detect a surface \u2022 Tap to place",L.appendChild(X),L.appendChild(R),document.body.appendChild(L),x=L,C=!0}}let m=new Set(r.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),h={requiredFeatures:r.requiredFeatures?[...r.requiredFeatures]:[],optionalFeatures:Array.from(m)};x&&(m.add("dom-overlay"),h.optionalFeatures=Array.from(m),h.domOverlay={root:x});for(let L of ce)L.onConfigureXRSessionInit?.(a,h);Array.isArray(h.optionalFeatures)&&h.optionalFeatures.includes("dom-overlay")&&!h.domOverlay?.root&&(h.optionalFeatures=h.optionalFeatures.filter(L=>L!=="dom-overlay"));let w=L=>{let X=String(L?.name||"");return X==="NotAllowedError"||X==="SecurityError"};try{this.s=await i.requestSession(u,h)}catch(L){if(T(),w(L))throw r.onError?.(L),L;try{this.s=await i.requestSession(u,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(X){if(w(X))throw r.onError?.(X),X;try{this.s=await i.requestSession(u)}catch(J){throw r.onError?.(J),J}}}let y=this.s;Me=this,this.placed=!1;let F=null,U=null,_=null,k=null,P=null,N=[0,-.25,-1.2],S=[0,-.25,-1.2],o=new Float32Array(16),V=new Float32Array(16),K=!1,f=1,b=0,n=!1,p=null,B=null,j=0,z=null,ee=()=>{Me===this&&(Me=null),z?.(),z=null;try{U?.cancel?.()}catch{}if(U=null,_){let L=e?.meshes;if(Array.isArray(L)){let J=L.indexOf(_);J!==-1&&L.splice(J,1)}let X=e.getGLContext?.()||e?.gl;if(X)for(let J of _.primitives||[]){X.deleteVertexArray?.(J.vao);for(let ae of J.buffers||[])X.deleteBuffer?.(ae)}_=null}e?.setXRSessionActive?.(!1),T(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=ee,y.addEventListener("end",()=>{ee(),r.onExit?.()}),y.addEventListener("select",()=>{if(!this.placed){let L=P||N;S=[L[0],L[1],L[2]],Mt(this.placedMat,S,D,b,I*f),this.placed=!0,_&&(_.visible=!1),R&&(R.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),r.onPlaced?.(this.placedMat)}});try{let L=e.getGLContext?.()||e?.gl;L&&typeof L.makeXRCompatible=="function"&&await L.makeXRCompatible();let X=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;L&&typeof X=="function"&&typeof y.updateRenderState=="function"&&y.updateRenderState({baseLayer:new X(y,L,{alpha:!0})});try{F=await y.requestReferenceSpace("local")}catch{try{F=await y.requestReferenceSpace("local-floor")}catch{F=await y.requestReferenceSpace("viewer")}}let J=await y.requestReferenceSpace("viewer").catch(()=>F);if(typeof y.requestHitTestSource=="function"&&J&&(U=await y.requestHitTestSource({space:J}).catch(()=>null)),u==="immersive-ar"&&L&&typeof L.createVertexArray=="function"&&Array.isArray(e.meshes)&&(_=Jt(L,r.reticleColor),e.meshes.push(_)),typeof window<"u"&&typeof window.addEventListener=="function"){let $=A=>Math.hypot(A.touches[1].clientX-A.touches[0].clientX,A.touches[1].clientY-A.touches[0].clientY),te=A=>Math.atan2(A.touches[1].clientY-A.touches[0].clientY,A.touches[1].clientX-A.touches[0].clientX),O=A=>{this.s&&(A.touches.length===1&&this.placed?n=!0:A.touches.length>=2&&(n=!1,p=$(A),B=te(A)))},G=A=>{if(!this.s||A.touches.length<2)return;let E=$(A),H=te(A);if(p&&p>4&&r.arScale!=="fixed"&&(f=Math.max(.15,Math.min(6,f*(E/p)))),B!==null){let W=H-B;W>Math.PI&&(W-=Math.PI*2),W<-Math.PI&&(W+=Math.PI*2),b-=W}p=E,B=H},q=A=>{(!A.touches||A.touches.length===0)&&(n=!1),(!A.touches||A.touches.length<2)&&(p=null,B=null)};window.addEventListener("touchstart",O,{passive:!0}),window.addEventListener("touchmove",G,{passive:!0}),window.addEventListener("touchend",q,{passive:!0}),window.addEventListener("touchcancel",q,{passive:!0}),z=()=>{window.removeEventListener("touchstart",O),window.removeEventListener("touchmove",G),window.removeEventListener("touchend",q),window.removeEventListener("touchcancel",q)}}e.setXRSessionActive?.(!0);let ae=($,te)=>{if(this.s!==y)return;y.requestAnimationFrame(ae);let O=j>0?Math.min(Math.max(($-j)/1e3,0),.1):1/60;j=$,e?.stepXRUpdate?.(O);let G=te.getViewerPose(F);if(!G)return;let q=G.views?.[0];if(!K&&q?.transform){let Q=q.transform.position,Y=q.transform.matrix,le=Q?.x??(Y?Y[12]:0),re=Q?.y??(Y?Y[13]:0),se=Q?.z??(Y?Y[14]:0),ne=Y?-Y[8]:0,oe=Y?-Y[10]:-1,pe=Math.hypot(ne,oe);pe>1e-4?(ne/=pe,oe/=pe):(ne=0,oe=-1),N=[le+ne*1.2,re-.25,se+oe*1.2],b=Math.atan2(-ne,-oe),K=!0}if(U&&typeof te.getHitTestResults=="function"&&(!this.placed||n)){let Q=te.getHitTestResults(U)||[],Y=!1;for(let le of Q){let re=le.getPose(F);if(re?.transform?.matrix){let se=re.transform.matrix,ne=se[5];if(r.arPlacement==="wall"&&Math.abs(ne)>.35||r.arPlacement==="floor"&&Math.abs(ne)<.65)continue;k||(k=new Float32Array(16)),k.set(se),P=[se[12],se[13],se[14]],this.placed&&n&&(S=[se[12],se[13],se[14]]),_&&(_.visible=!this.placed||n,_.transform.set(se)),!this.placed&&R&&(R.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),r.onHit?.(k),Y=!0;break}}!Y&&_&&(_.visible=!1)}Mt(o,this.placed?S:P||N,D,b,I*f),this.placed&&this.placedMat.set(o);let A=e.xrRigMatrix;A instanceof Float32Array&&A.length===16?fe(V,A,o):V.set(o),e.modelRootMatrix&&e.modelRootMatrix.set(V);for(let Q of ce)Q.onXRFrame?.(e,y,te,F);let E=e.getGLContext?.()||e?.gl,H=y.renderState?.baseLayer;E&&H&&H.framebuffer!==void 0&&E.bindFramebuffer(36160,H.framebuffer);let W=u==="immersive-ar",Z=G.views||[];for(let Q=0;Q<Z.length;Q++){let Y=Z[Q];if(typeof e.renderXRView=="function"){let le;if(H&&typeof H.getViewport=="function"){let re=H.getViewport(Y);re&&re.width>0&&re.height>0&&(le=[re.x,re.y,re.width,re.height])}else H?.framebufferWidth>0&&H?.framebufferHeight>0&&(le=[0,0,H.framebufferWidth,H.framebufferHeight]);e.renderXRView(Y,V,this.placed,le,W,Q)}}E&&H&&H.framebuffer&&E.bindFramebuffer(36160,null)};y.requestAnimationFrame(ae)}catch(L){throw typeof y.end=="function"&&await y.end().catch(()=>{}),ee(),r.onError?.(L),L}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function ei(e){let t=await qe(),i=e.preferredModes||["quick-look","webxr","scene-viewer"],r=null;for(let l of i)if(t.availableModes.includes(l)){r=l;break}if(r||(r=t.bestMode),!r)return{mode:"quick-look",success:!1,error:new Error("No augmented reality viewing mode is supported on this device.")};let a={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},s={...e.sceneViewerOptions,resizable:e.arScale==="fixed"?!1:e.sceneViewerOptions?.resizable,enableVerticalPlacement:e.arPlacement==="wall"?!0:e.sceneViewerOptions?.enableVerticalPlacement},c={...e.webXROptions,arScale:e.arScale||e.webXROptions?.arScale,arPlacement:e.arPlacement||e.webXROptions?.arPlacement};try{if(r==="quick-look"){let l;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")l=e.model;else{if(typeof e.model=="string")return Ge(e.model,a),{mode:"quick-look",success:!0};l=xt(e.model)}return Ge(l,a),{mode:"quick-look",success:!0}}if(r==="scene-viewer"){let l=e.glbUrl||(typeof e.model=="string"?e.model:null);if(!l)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return yt(l,s),{mode:"scene-viewer",success:!0}}if(r==="webxr"){if(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let l=new wt(c);return await l.start(e.view,e.element),{mode:"webxr",success:!0,session:l}}}catch(l){return{mode:r,success:!1,error:l}}return{mode:r,success:!1,error:new Error(`Unhandled AR mode: ${r}`)}}export{wt as WebXRSessionManager,ei as activateAR,dt as buildUSDZZip,pt as calculateCRC32,bt as createSceneViewerIntent,xt as createUSDZBlob,Wt as generateUSDA,vt as generateUSDZ,qe as getARCapabilities,Yt as getAvailableARModes,Zt as getBestARMode,gt as glbToUSDZ,ze as isQuickLookSupported,je as isSceneViewerSupported,Xe as isWebXRSupported,Ge as launchQuickLook,yt as launchSceneViewer};
|