UNPKG

@tresjs/cientos

Version:

Collection of useful helpers and fully functional, ready-made abstractions for Tres

90 lines (83 loc) 547 kB
/** * name: @tresjs/cientos * version: v4.3.1 * (c) 2025 * description: Collection of useful helpers and fully functional, ready-made abstractions for Tres * author: Alvaro Saburido <hola@alvarosaburido.dev> (https://github.com/alvarosabu/) */ (function(ne,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("three"),require("vue"),require("@tresjs/core")):typeof define=="function"&&define.amd?define(["exports","three","vue","@tresjs/core"],l):(ne=typeof globalThis<"u"?globalThis:ne||self,l(ne.trescientos={},ne.Three,ne.Vue,ne.TresjsCore))})(this,function(ne,l,u,H){"use strict";var yp=Object.defineProperty;var _p=(ne,l,u)=>l in ne?yp(ne,l,{enumerable:!0,configurable:!0,writable:!0,value:u}):ne[l]=u;var ue=(ne,l,u)=>_p(ne,typeof l!="symbol"?l+"":l,u);function $s(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const Ot=$s(l);function ei(i){const e=ti(i),t=[];for(const{startFrame:n,endFrame:o,duration:r}of e)if(!(r<=0))if(o<0||n===o){for(let s=0;s<r;s++)t.push(n);continue}else{const s=Math.sign(o-n);for(let a=n;a!==o+s;a+=s)for(let c=0;c<r;c++)t.push(a)}return t}function ti(i){let e="START_FRAME_IN";const t=[];for(const{name:n,value:o,startI:r}of ni(i))e==="START_FRAME_IN"?n==="NUMBER"?(t.push({startFrame:o,endFrame:o,duration:1}),e="START_FRAME_OUT"):Mt("number",n,i,r):e==="START_FRAME_OUT"?n==="COMMA"?e="START_FRAME_IN":n==="HYPHEN"?e="END_FRAME_IN":n==="OPEN_PAREN"?e="DURATION_IN":Mt('",", "-", "("',n,i,r):e==="END_FRAME_IN"?n==="NUMBER"?(t[t.length-1].endFrame=o,e="END_FRAME_OUT"):Mt("number",n,i,r):e==="END_FRAME_OUT"?n==="COMMA"?e="START_FRAME_IN":n==="OPEN_PAREN"?e="DURATION_IN":Mt("',' or '('",n,i,r):e==="DURATION_IN"?n==="NUMBER"?(t[t.length-1].duration=o,e="DURATION_OUT"):Mt("number",n,i,r):e==="DURATION_OUT"?n==="CLOSE_PAREN"?e="NEXT_OR_DONE":Mt('"("',n,i,r):e==="NEXT_OR_DONE"&&(n==="COMMA"?e="START_FRAME_IN":Mt('","',n,i,r));return t}function ni(i){const e=[];for(let t=0;t<i.length;t++){const n=i[t];if("0123456789".includes(n))e.length&&e[e.length-1].name==="NUMBER"?(e[e.length-1].value*=10,e[e.length-1].value+=Number.parseInt(n)):e.push({name:"NUMBER",value:Number.parseInt(n),startI:t});else{if(n===" ")continue;n===","?e.push({name:"COMMA",value:-1,startI:t}):n==="("?e.push({name:"OPEN_PAREN",value:-1,startI:t}):n===")"?e.push({name:"CLOSE_PAREN",value:-1,startI:t}):n==="-"?e.push({name:"HYPHEN",value:-1,startI:t}):oi("0123456789,-()",n,i,t)}}return e}function oi(i,e,t,n){H.useLogger().logError(`Cientos AnimationDefinitionParser: Unexpected character while processing animation definition: expected ${i}, got ${e}. ${t} ${Array.from({length:n+1}).join(" ")}^`)}function Mt(i,e,t,n){H.useLogger().logError(`Cientos AnimationDefinitionParser: Syntax error while processing animation definition: expected ${i}, got ${e}. ${t} ${Array.from({length:n+1}).join(" ")}^`)}const ri=/\d*$/,si=/_*\d*$/;function ii(i){return i.replace(si,"")}function ai(i){const e=i.match(ri);return e?Number.parseInt(e[e.length-1]):null}async function li(i,e){const t=H.useLoader(l.TextureLoader,i),n=typeof e!="string"?new Promise(o=>o(e)):fetch(e).then(o=>o.json()).catch(o=>H.useLogger().logError(`Cientos Atlas - ${o}`));return Promise.all([t,n]).then(([o,r])=>{const s=ci(r,o.image.width,o.image.height);return[o,s]})}function ci(i,e,t){const n=typeof i=="number"||Array.isArray(i)?di(i,e,t):ui(i,e,t);return{frames:n,animations:Xo(n)}}function Yt(i,e,t){let n;return typeof e=="string"?n=mi(i,e):typeof e=="number"?n=Yo(i,e,e):n=Yo(i,e[0],e[1]),t?n.toReversed():n}function Nn(){return{name:"null",width:0,height:0,offsetX:0,offsetY:0,repeatX:0,repeatY:0}}function ui(i,e,t){return Array.isArray(i.frames)?hi(i,e,t):fi(i,e,t)}function hi(i,e,t){const n=1/e,o=1/t;return i.frames.map(r=>({name:r.filename,offsetX:r.frame.x*n,offsetY:1-(r.frame.y+r.frame.h)*o,repeatX:r.frame.w*n,repeatY:r.frame.h*o,width:r.frame.w,height:r.frame.h}))}function fi(i,e,t){const n=1/e,o=1/t;return Object.entries(i.frames).map(([r,s])=>({name:r,offsetX:s.frame.x*n,offsetY:1-(s.frame.y+s.frame.h)*o,repeatX:s.frame.w*n,repeatY:s.frame.h*o,width:s.frame.w,height:s.frame.h}))}function di(i,e,t,n="default"){const[o,r]=Array.isArray(i)?i:[i,1],s=e/o,a=t/r,c=(o*r).toString().length,h=1/o,p=1/r,f=[];let m=0;for(let d=r-1;d>=0;d--)for(let y=0;y<o;y++)m++,f.push({name:n+String(m).padStart(c,"0"),offsetX:y*h,offsetY:d*p,repeatX:h,repeatY:p,width:s,height:a});return f}function pi(i,e={}){const t=Xo(i.frames);for(const[n,o]of Object.entries(e)){const r=Yt(i,n,!1),s=ei(o);for(const a of s)(a<0||r.length<=a)&&H.useLogger().logError(`Cientos Atlas: Attempting to access frame index ${a} in animation ${n}, but it does not exist.`);t[n]=s.map(a=>r[a])}i.animations=t}function mi(i,e){if(!(e in i.animations)){const t=Object.keys(i.animations).map(n=>`* ${n} `).join("");return H.useLogger().logError(`Cientos Atlas: getAtlasFramesByAnimationName The animation name "${e}" does not exist in this atlas. Available names: ${t}`),[Nn()]}return i.animations[e]}function Yo(i,e,t){if(e<0||i.frames.length<=e||t<0||i.frames.length<=t)return H.useLogger().logError(`Cientos Atlas: getFramesByIndex – [${e}, ${t}] is out of bounds.`),[Nn()];const n=[],o=Math.sign(t-e);if(o===0)return[i.frames[e]];for(let r=e;r!==t+o;r+=o)n.push(i.frames[r]);return n}function Xo(i){const e={};for(const t of i)if(ai(t.name)!==null){const n=ii(t.name);Object.prototype.hasOwnProperty.call(e,n)?e[n].push(t):e[n]=[t]}for(const t of Object.values(e))t.sort((n,o)=>n.name.localeCompare(o.name));return e}const gi=["scale","position"],yi=["map","alphaTest"],_i=["scale","position"],vi=["side","map","alphaTest","depthWrite","depthTest"],un=.01,xi=u.defineComponent({__name:"component",props:{image:{},atlas:{},definitions:{},fps:{default:30},loop:{type:Boolean,default:!0},animation:{default:0},paused:{type:Boolean,default:!1},reversed:{type:Boolean,default:!1},flipX:{type:Boolean,default:!1},resetOnEnd:{type:Boolean,default:!1},asSprite:{type:Boolean,default:!0},center:{default:()=>[.5,.5]},alphaTest:{default:0},depthTest:{type:Boolean,default:!0},depthWrite:{type:Boolean,default:!0}},emits:["frame","end","loop"],async setup(i,{expose:e,emit:t}){let n,o;const r=i,s=t,{invalidate:a}=H.useTresContext();u.watch(r,()=>{a()});const c=u.ref(0),h=u.ref(0),p=u.ref(0),f=u.ref(0),m=u.shallowRef();e({instance:m});const[d,y]=([n,o]=u.withAsyncContext(()=>li(r.image,r.atlas)),n=await n,o(),n);d.matrixAutoUpdate=!1;let _=Yt(y,r.animation,r.reversed),v=.5,g=.5,A=1,w=Nn(),C=null,L=0,M=!1,P=!0;H.useLoop().onBeforeRender(({delta:S})=>{for(!r.paused&&!M&&(A-=S*r.fps);A<=0;)A++,L++,r.loop?(L>=_.length&&s("loop",_[_.length-1].name),L%=_.length):L>=_.length&&(M=!0,L=r.resetOnEnd?0:_.length-1,s("end",_[_.length-1].name));_[L]!==w&&(w=_[L],C=w.name,b()),P&&(P=!1,d.offset.x=w.offsetX+(r.flipX?w.repeatX:0),d.offset.y=w.offsetY,d.repeat.x=w.repeatX*(r.flipX?-1:1),d.repeat.y=w.repeatY,d.updateMatrix(),p.value=w.width*un,f.value=w.height*un,c.value=(.5-v)*w.width*un,h.value=(.5-g)*w.height*un),C&&(s("frame",C),C=null)});function b(){P=!0}return u.watch(()=>r.animation,(S,x)=>{JSON.stringify(S)!==JSON.stringify(x)&&(_=Yt(y,r.animation,r.reversed),L=0,A=1,M=!1,b())},{immediate:!0}),u.watch(()=>r.reversed,()=>{L=(_.length-L-1)%_.length,_=Yt(y,r.animation,r.reversed),M&&(L=r.resetOnEnd?0:_.length-1),b()}),u.watch(()=>r.paused,()=>{M=!1}),u.watch(()=>r.loop,()=>{M&&r.loop&&(M=!1)}),u.watch(()=>r.resetOnEnd,()=>{M&&(L=r.resetOnEnd?0:_.length-1,b())}),u.watch(()=>r.flipX,b),u.watch(()=>[r.center],()=>{[v,g]=H.normalizeVectorFlexibleParam(r.center),b()},{immediate:!0}),u.watch(()=>[r.definitions],()=>{pi(y,r.definitions),_=Yt(y,r.animation,r.reversed),A=1,L=0,b()},{immediate:!0}),u.onUnmounted(()=>{d.dispose()}),(S,x)=>(u.openBlock(),u.createElementBlock("TresGroup",{ref_key:"groupRef",ref:m},[r.asSprite?(u.openBlock(),u.createElementBlock("TresSprite",{key:0,scale:[p.value,f.value,1],position:[c.value,h.value,0]},[u.createElementVNode("TresSpriteMaterial",{toneMapped:!1,map:u.unref(d),transparent:!0,alphaTest:r.alphaTest},null,8,yi)],8,gi)):(u.openBlock(),u.createElementBlock("TresMesh",{key:1,scale:[p.value,f.value,1],position:[c.value,h.value,0]},[x[0]||(x[0]=u.createElementVNode("TresPlaneGeometry",{args:[1,1]},null,-1)),u.createElementVNode("TresMeshBasicMaterial",{toneMapped:!1,side:u.unref(l.DoubleSide),map:u.unref(d),transparent:!0,alphaTest:r.alphaTest,depthWrite:r.depthWrite,depthTest:r.depthTest},null,8,vi)],8,_i)),u.renderSlot(S.$slots,"default")],512))}});function hn(i){return u.getCurrentScope()?(u.onScopeDispose(i),!0):!1}function Ge(i){return typeof i=="function"?i():u.unref(i)}const wi=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const bi=Object.prototype.toString,Mi=i=>bi.call(i)==="[object Object]",pt=()=>{};function Fn(i,e){function t(...n){return new Promise((o,r)=>{Promise.resolve(i(()=>e.apply(this,n),{fn:e,thisArg:this,args:n})).then(o).catch(r)})}return t}const Si=i=>i();function Ai(i,e={}){let t,n,o=pt;const r=a=>{clearTimeout(a),o(),o=pt};return a=>{const c=Ge(i),h=Ge(e.maxWait);return t&&r(t),c<=0||h!==void 0&&h<=0?(n&&(r(n),n=null),Promise.resolve(a())):new Promise((p,f)=>{o=e.rejectOnCancel?f:p,h&&!n&&(n=setTimeout(()=>{t&&r(t),n=null,p(a())},h)),t=setTimeout(()=>{n&&r(n),n=null,p(a())},c)})}}function Eo(...i){let e=0,t,n=!0,o=pt,r,s,a,c,h;!u.isRef(i[0])&&typeof i[0]=="object"?{delay:s,trailing:a=!0,leading:c=!0,rejectOnCancel:h=!1}=i[0]:[s,a=!0,c=!0,h=!1]=i;const p=()=>{t&&(clearTimeout(t),t=void 0,o(),o=pt)};return m=>{const d=Ge(s),y=Date.now()-e,_=()=>r=m();return p(),d<=0?(e=Date.now(),_()):(y>d&&(c||!n)?(e=Date.now(),_()):a&&(r=new Promise((v,g)=>{o=h?g:v,t=setTimeout(()=>{e=Date.now(),n=!0,v(_()),p()},Math.max(0,d-y))})),!c&&!t&&(t=setTimeout(()=>n=!0,d)),n=!1,r)}}function Pi(i){return u.getCurrentInstance()}function Ci(i,e=200,t={}){return Fn(Ai(e,t),i)}function Ti(i,e=200,t=!1,n=!0,o=!1){return Fn(Eo(e,t,n,o),i)}function Ii(i,e,t={}){const{eventFilter:n=Si,...o}=t;return u.watch(i,Fn(n,e),o)}function zn(i,e=!0,t){Pi()?u.onMounted(i,t):e?i():u.nextTick(i)}function Oi(i,e,t={}){const{throttle:n=0,trailing:o=!0,leading:r=!0,...s}=t;return Ii(i,e,{...s,eventFilter:Eo(n,o,r)})}const at=wi?window:void 0;function mt(i){var e;const t=Ge(i);return(e=t==null?void 0:t.$el)!=null?e:t}function Ce(...i){let e,t,n,o;if(typeof i[0]=="string"||Array.isArray(i[0])?([t,n,o]=i,e=at):[e,t,n,o]=i,!e)return pt;Array.isArray(t)||(t=[t]),Array.isArray(n)||(n=[n]);const r=[],s=()=>{r.forEach(p=>p()),r.length=0},a=(p,f,m,d)=>(p.addEventListener(f,m,d),()=>p.removeEventListener(f,m,d)),c=u.watch(()=>[mt(e),Ge(o)],([p,f])=>{if(s(),!p)return;const m=Mi(f)?{...f}:f;r.push(...t.flatMap(d=>n.map(y=>a(p,d,y,m))))},{immediate:!0,flush:"post"}),h=()=>{c(),s()};return hn(h),h}function Li(){const i=u.ref(!1),e=u.getCurrentInstance();return e&&u.onMounted(()=>{i.value=!0},e),i}function Zo(i){const e=Li();return u.computed(()=>(e.value,!!i()))}function Di(i,e={}){const{window:t=at}=e,n=Zo(()=>t&&"matchMedia"in t&&typeof t.matchMedia=="function");let o;const r=u.ref(!1),s=h=>{r.value=h.matches},a=()=>{o&&("removeEventListener"in o?o.removeEventListener("change",s):o.removeListener(s))},c=u.watchEffect(()=>{n.value&&(a(),o=t.matchMedia(Ge(i)),"addEventListener"in o?o.addEventListener("change",s):o.addListener(s),r.value=o.matches)});return hn(()=>{c(),a(),o=void 0}),r}function ki(i,e,t={}){const{window:n=at,...o}=t;let r;const s=Zo(()=>n&&"ResizeObserver"in n),a=()=>{r&&(r.disconnect(),r=void 0)},c=u.computed(()=>{const f=Ge(i);return Array.isArray(f)?f.map(m=>mt(m)):[mt(f)]}),h=u.watch(c,f=>{if(a(),s.value&&n){r=new ResizeObserver(e);for(const m of f)m&&r.observe(m,o)}},{immediate:!0,flush:"post"}),p=()=>{a(),h()};return hn(p),{isSupported:s,stop:p}}function Bi(i,e={width:0,height:0},t={}){const{window:n=at,box:o="content-box"}=t,r=u.computed(()=>{var f,m;return(m=(f=mt(i))==null?void 0:f.namespaceURI)==null?void 0:m.includes("svg")}),s=u.ref(e.width),a=u.ref(e.height),{stop:c}=ki(i,([f])=>{const m=o==="border-box"?f.borderBoxSize:o==="content-box"?f.contentBoxSize:f.devicePixelContentBoxSize;if(n&&r.value){const d=mt(i);if(d){const y=d.getBoundingClientRect();s.value=y.width,a.value=y.height}}else if(m){const d=Array.isArray(m)?m:[m];s.value=d.reduce((y,{inlineSize:_})=>y+_,0),a.value=d.reduce((y,{blockSize:_})=>y+_,0)}else s.value=f.contentRect.width,a.value=f.contentRect.height},t);zn(()=>{const f=mt(i);f&&(s.value="offsetWidth"in f?f.offsetWidth:e.width,a.value="offsetHeight"in f?f.offsetHeight:e.height)});const h=u.watch(()=>mt(i),f=>{s.value=f?e.width:0,a.value=f?e.height:0});function p(){c(),h()}return{width:s,height:a,stop:p}}const Ko=1;function Ui(i,e={}){const{throttle:t=0,idle:n=200,onStop:o=pt,onScroll:r=pt,offset:s={left:0,right:0,top:0,bottom:0},eventListenerOptions:a={capture:!1,passive:!0},behavior:c="auto",window:h=at,onError:p=P=>{console.error(P)}}=e,f=u.ref(0),m=u.ref(0),d=u.computed({get(){return f.value},set(P){_(P,void 0)}}),y=u.computed({get(){return m.value},set(P){_(void 0,P)}});function _(P,b){var S,x,I,D;if(!h)return;const z=Ge(i);if(!z)return;(I=z instanceof Document?h.document.body:z)==null||I.scrollTo({top:(S=Ge(b))!=null?S:y.value,left:(x=Ge(P))!=null?x:d.value,behavior:Ge(c)});const G=((D=z==null?void 0:z.document)==null?void 0:D.documentElement)||(z==null?void 0:z.documentElement)||z;d!=null&&(f.value=G.scrollLeft),y!=null&&(m.value=G.scrollTop)}const v=u.ref(!1),g=u.reactive({left:!0,right:!1,top:!0,bottom:!1}),A=u.reactive({left:!1,right:!1,top:!1,bottom:!1}),w=P=>{v.value&&(v.value=!1,A.left=!1,A.right=!1,A.top=!1,A.bottom=!1,o(P))},C=Ci(w,t+n),L=P=>{var b;if(!h)return;const S=((b=P==null?void 0:P.document)==null?void 0:b.documentElement)||(P==null?void 0:P.documentElement)||mt(P),{display:x,flexDirection:I}=getComputedStyle(S),D=S.scrollLeft;A.left=D<f.value,A.right=D>f.value;const z=Math.abs(D)<=(s.left||0),G=Math.abs(D)+S.clientWidth>=S.scrollWidth-(s.right||0)-Ko;x==="flex"&&I==="row-reverse"?(g.left=G,g.right=z):(g.left=z,g.right=G),f.value=D;let E=S.scrollTop;P===h.document&&!E&&(E=h.document.body.scrollTop),A.top=E<m.value,A.bottom=E>m.value;const X=Math.abs(E)<=(s.top||0),oe=Math.abs(E)+S.clientHeight>=S.scrollHeight-(s.bottom||0)-Ko;x==="flex"&&I==="column-reverse"?(g.top=oe,g.bottom=X):(g.top=X,g.bottom=oe),m.value=E},M=P=>{var b;if(!h)return;const S=(b=P.target.documentElement)!=null?b:P.target;L(S),v.value=!0,C(P),r(P)};return Ce(i,"scroll",t?Ti(M,t,!0,!1):M,a),zn(()=>{try{const P=Ge(i);if(!P)return;L(P)}catch(P){p(P)}}),Ce(i,"scrollend",w,a),{x:d,y,isScrolling:v,arrivedState:g,directions:A,measure(){const P=Ge(i);h&&P&&L(P)}}}const Ni={ctrl:"control",command:"meta",cmd:"meta",option:"alt",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright"};function Fi(i={}){const{reactive:e=!1,target:t=at,aliasMap:n=Ni,passive:o=!0,onEventFired:r=pt}=i,s=u.reactive(new Set),a={toJSON(){return{}},current:s},c=e?u.reactive(a):a,h=new Set,p=new Set;function f(_,v){_ in c&&(e?c[_]=v:c[_].value=v)}function m(){s.clear();for(const _ of p)f(_,!1)}function d(_,v){var g,A;const w=(g=_.key)==null?void 0:g.toLowerCase(),L=[(A=_.code)==null?void 0:A.toLowerCase(),w].filter(Boolean);w&&(v?s.add(w):s.delete(w));for(const M of L)p.add(M),f(M,v);w==="meta"&&!v?(h.forEach(M=>{s.delete(M),f(M,!1)}),h.clear()):typeof _.getModifierState=="function"&&_.getModifierState("Meta")&&v&&[...s,...L].forEach(M=>h.add(M))}Ce(t,"keydown",_=>(d(_,!0),r(_)),{passive:o}),Ce(t,"keyup",_=>(d(_,!1),r(_)),{passive:o}),Ce("blur",m,{passive:!0}),Ce("focus",m,{passive:!0});const y=new Proxy(c,{get(_,v,g){if(typeof v!="string")return Reflect.get(_,v,g);if(v=v.toLowerCase(),v in n&&(v=n[v]),!(v in c))if(/[+_-]/.test(v)){const w=v.split(/[+_-]/g).map(C=>C.trim());c[v]=u.computed(()=>w.every(C=>Ge(y[C])))}else c[v]=u.ref(!1);const A=Reflect.get(_,v,g);return e?Ge(A):A}});return y}const zi={page:i=>[i.pageX,i.pageY],client:i=>[i.clientX,i.clientY],screen:i=>[i.screenX,i.screenY],movement:i=>i instanceof Touch?null:[i.movementX,i.movementY]};function Vi(i={}){const{type:e="page",touch:t=!0,resetOnTouchEnds:n=!1,initialValue:o={x:0,y:0},window:r=at,target:s=r,scroll:a=!0,eventFilter:c}=i;let h=null,p=0,f=0;const m=u.ref(o.x),d=u.ref(o.y),y=u.ref(null),_=typeof e=="function"?e:zi[e],v=P=>{const b=_(P);h=P,b&&([m.value,d.value]=b,y.value="mouse"),r&&(p=r.scrollX,f=r.scrollY)},g=P=>{if(P.touches.length>0){const b=_(P.touches[0]);b&&([m.value,d.value]=b,y.value="touch")}},A=()=>{if(!h||!r)return;const P=_(h);h instanceof MouseEvent&&P&&(m.value=P[0]+r.scrollX-p,d.value=P[1]+r.scrollY-f)},w=()=>{m.value=o.x,d.value=o.y},C=c?P=>c(()=>v(P),{}):P=>v(P),L=c?P=>c(()=>g(P),{}):P=>g(P),M=c?()=>c(()=>A(),{}):()=>A();if(s){const P={passive:!0};Ce(s,["mousemove","dragover"],C,P),t&&e!=="movement"&&(Ce(s,["touchstart","touchmove"],L,P),n&&Ce(s,"touchend",w,P)),a&&e==="page"&&Ce(r,"scroll",M,{passive:!0})}return{x:m,y:d,sourceType:y}}function Gi(i={}){const{window:e=at,behavior:t="auto"}=i;if(!e)return{x:u.ref(0),y:u.ref(0)};const n=u.ref(e.scrollX),o=u.ref(e.scrollY),r=u.computed({get(){return n.value},set(a){scrollTo({left:a,behavior:t})}}),s=u.computed({get(){return o.value},set(a){scrollTo({top:a,behavior:t})}});return Ce(e,"scroll",()=>{n.value=e.scrollX,o.value=e.scrollY},{capture:!1,passive:!0}),{x:r,y:s}}function qo(i={}){const{window:e=at,initialWidth:t=Number.POSITIVE_INFINITY,initialHeight:n=Number.POSITIVE_INFINITY,listenOrientation:o=!0,includeScrollbar:r=!0,type:s="inner"}=i,a=u.ref(t),c=u.ref(n),h=()=>{e&&(s==="outer"?(a.value=e.outerWidth,c.value=e.outerHeight):r?(a.value=e.innerWidth,c.value=e.innerHeight):(a.value=e.document.documentElement.clientWidth,c.value=e.document.documentElement.clientHeight))};if(h(),zn(h),Ce("resize",h,{passive:!0}),o){const p=Di("(orientation: portrait)");u.watch(p,()=>h())}return{width:a,height:c}}function Ri(i){let{resolution:e,renderer:t,scene:n,envMap:o,fog:r,near:s,far:a}=i;t=t??H.useTres().renderer,n=n??H.useTres().scene;const c=()=>{e=u.toValue(i.resolution)??255,s=u.toValue(i.near)??.1,a=u.toValue(i.far)??1e3,o=u.toValue(i.envMap)??void 0,r=u.toValue(i.fog)??void 0,t=u.toValue(i.renderer)??t,n=u.toValue(i.scene)??n};u.watchEffect(c);const h=u.computed(()=>new l.WebGLCubeRenderTarget(u.toValue(e)));h.value.texture.type=l.HalfFloatType,hn(()=>{h.value.dispose()});const p=u.computed(()=>new l.CubeCamera(u.toValue(s),u.toValue(a),u.toValue(h))),f=()=>{const m=u.toValue(n),d=m.fog,y=m.background;m.background=u.toValue(o)||y,m.fog=u.toValue(r)||d,p.value.update(u.toValue(t),m),m.fog=d,m.background=y};return u.watchEffect(f),{fbo:h,camera:p,update:f}}const ji=["object"],Wi=u.defineComponent({__name:"component",props:{frames:{default:1/0},resolution:{},near:{},far:{},envMap:{},fog:{},renderer:{},scene:{}},setup(i,{expose:e}){const t=i,n=u.shallowRef(),{fbo:o,camera:r,update:s}=Ri(t);let a=0;return H.useLoop().onBeforeRender(()=>{n.value&&(t.frames===1/0||a<u.toValue(t.frames))&&(n.value.visible=!1,s(),n.value.visible=!0,n.value&&n.value.traverse(c=>{"material"in c&&typeof c.material=="object"&&c.material&&"envMap"in c.material&&(c.material.envMap=o.value.texture)}),a++)}),e({instance:n,fbo:o,camera:r,update:s}),(c,h)=>(u.openBlock(),u.createElementBlock("TresGroup",{ref_key:"groupRef",ref:n},[u.createElementVNode("primitive",{object:u.unref(r)},null,8,ji),u.renderSlot(c.$slots,"default")],512))}}),Yi=u.defineComponent({__name:"Billboard",props:{autoUpdate:{type:Boolean,default:!0},lockX:{type:Boolean,default:!1},lockY:{type:Boolean,default:!1},lockZ:{type:Boolean,default:!1}},setup(i,{expose:e}){const t=i,n=u.shallowRef(new l.Group),o=u.shallowRef(new l.Group),r=new l.Quaternion,s=new l.Euler;function a(c){n.value&&(!c&&(c=H.useTres().camera.value,!c)||(o.value.rotation.copy(s),n.value.updateMatrix(),n.value.updateWorldMatrix(!1,!1),n.value.getWorldQuaternion(r),c.getWorldQuaternion(o.value.quaternion).premultiply(r.invert()),t.lockX&&(o.value.rotation.x=s.x),t.lockY&&(o.value.rotation.y=s.y),t.lockZ&&(o.value.rotation.z=s.z)))}return H.useLoop().onBeforeRender(({camera:c})=>{t.autoUpdate&&a(c)}),e({instance:n,update:a}),(c,h)=>(u.openBlock(),u.createElementBlock("TresGroup",{ref_key:"outerRef",ref:n},[u.createElementVNode("TresGroup",{ref_key:"innerRef",ref:o},[u.renderSlot(c.$slots,"default")],512)],512))}}),Xi=u.defineComponent({name:"GlobalAudio",props:["src","loop","volume","playbackRate","playTrigger","stopTrigger"],async setup(i,{expose:e,emit:t}){var f;const{camera:n,renderer:o}=H.useTresContext(),r=new l.AudioListener;(f=n.value)==null||f.add(r);const s=new l.Audio(r),a=new l.AudioLoader;e({instance:s}),u.onUnmounted(()=>{s&&s.disconnect()}),u.watch(()=>[i.playbackRate],()=>s.setPlaybackRate(i.playbackRate??1),{immediate:!0}),u.watch(()=>[i.volume],()=>s.setVolume(i.volume??.5),{immediate:!0}),u.watch(()=>[i.loop],()=>s.setLoop(i.loop??!1),{immediate:!0}),u.watch(()=>[i.src],async()=>{const m=await a.loadAsync(i.src);s.setBuffer(m)},{immediate:!0});const h=document.getElementById(i.playTrigger??"")||o.value.domElement;Ce(h,"click",()=>{s.isPlaying?s.pause():s.play(),t("isPlaying",s.isPlaying)});const p=document.getElementById(i.stopTrigger??"");return p&&Ce(p,"click",()=>{s.stop(),t("isPlaying",s.isPlaying)}),null}}),Ei=["color-space","args","attach"],Zi=u.defineComponent({__name:"GradientTexture",props:{stops:{},colors:{},attach:{default:"map"},height:{default:1024},width:{default:16},type:{default:"linear"},innerCircleRadius:{default:0},outerCircleRadius:{default:"auto"}},setup(i,{expose:e}){const t=i,n=u.shallowRef(),o=document.createElement("canvas");function r(a){const c=a.getContext("2d");a.width=t.width,a.height=t.height;let h;if(t.type==="linear")h=c.createLinearGradient(0,0,0,t.height);else{const m=a.width/2,d=a.height/2,y=t.outerCircleRadius!=="auto"?Math.abs(Number(t.outerCircleRadius)):Math.sqrt(m**2+d**2);h=c.createRadialGradient(m,d,Math.abs(t.innerCircleRadius),m,d,y)}const p=new Ot.Color;let f=t.stops.length;for(;f--;)h.addColorStop(t.stops[f],p.set(t.colors[f]).getStyle());c.save(),c.fillStyle=h,c.fillRect(0,0,t.width,t.height),c.restore(),n.value&&(n.value.needsUpdate=!0)}const s=H.useTres().renderer;return u.watch(()=>[t.colors,t.stops,t.height,t.width,t.type,t.innerCircleRadius,t.outerCircleRadius],()=>{r(o)},{immediate:!0}),u.isReactive(t.colors)&&u.watch(t.colors,()=>r(o)),u.isReactive(t.stops)&&u.watch(t.stops,()=>r(o)),e({instance:n}),(a,c)=>(u.openBlock(),u.createElementBlock("TresCanvasTexture",{ref_key:"textureRef",ref:n,"color-space":u.unref(s).outputColorSpace,args:[u.unref(o)],attach:t.attach},null,8,Ei))}});function Vn(i,e,t,n){const o=class extends l.ShaderMaterial{constructor(s={}){const a=Object.entries(i);super({uniforms:a.reduce((c,[h,p])=>{const f=l.UniformsUtils.clone({[h]:{value:p}});return{...c,...f}},{}),vertexShader:e,fragmentShader:t});ue(this,"key","");a.forEach(([c])=>Object.defineProperty(this,c,{get:()=>this.uniforms[c].value,set:h=>this.uniforms[c].value=h})),Object.assign(this,s)}};return o.key=l.MathUtils.generateUUID(),o}const Ki=Vn({color:new l.Color("white"),scale:new l.Vector2(1,1),imageBounds:new l.Vector2(1,1),resolution:1024,map:null,zoom:1,radius:0,grayscale:0,opacity:1},` varying vec2 vUv; varying vec2 vPos; void main() { gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.); vUv = uv; vPos = position.xy; } `,` // mostly from https://gist.github.com/statico/df64c5d167362ecf7b34fca0b1459a44 varying vec2 vUv; varying vec2 vPos; uniform vec2 scale; uniform vec2 imageBounds; uniform float resolution; uniform vec3 color; uniform sampler2D map; uniform float radius; uniform float zoom; uniform float grayscale; uniform float opacity; const vec3 luma = vec3(.299, 0.587, 0.114); vec4 toGrayscale(vec4 color, float intensity) { return vec4(mix(color.rgb, vec3(dot(color.rgb, luma)), intensity), color.a); } vec2 aspect(vec2 size) { return size / min(size.x, size.y); } const float PI = 3.14159265; // from https://iquilezles.org/articles/distfunctions float udRoundBox( vec2 p, vec2 b, float r ) { return length(max(abs(p)-b+r,0.0))-r; } void main() { vec2 s = aspect(scale); vec2 i = aspect(imageBounds); float rs = s.x / s.y; float ri = i.x / i.y; vec2 new = rs < ri ? vec2(i.x * s.y / i.y, s.y) : vec2(s.x, i.y * s.x / i.x); vec2 offset = (rs < ri ? vec2((new.x - s.x) / 2.0, 0.0) : vec2(0.0, (new.y - s.y) / 2.0)) / new; vec2 uv = vUv * s / new + offset; vec2 zUv = (uv - vec2(0.5, 0.5)) / zoom + vec2(0.5, 0.5); vec2 res = vec2(scale * resolution); vec2 halfRes = 0.5 * res; float b = udRoundBox(vUv.xy * res - halfRes, halfRes, resolution * radius); vec3 a = mix(vec3(1.0,0.0,0.0), vec3(0.0,0.0,0.0), smoothstep(0.0, 1.0, b)); gl_FragColor = toGrayscale(texture2D(map, zUv) * vec4(color, opacity * a), grayscale); #include <tonemapping_fragment> #include <colorspace_fragment> } `),qi=u.defineComponent({__name:"ImageMaterial",setup(i,{expose:e}){H.extend({ImageMaterial:Ki});const t=u.shallowRef();return e({instance:t}),(n,o)=>(u.openBlock(),u.createElementBlock("TresImageMaterial",{ref_key:"materialRef",ref:t},null,512))}}),Qi=["scale"],Ji=["args"],Hi=u.defineComponent({__name:"component",props:{segments:{default:1},scale:{default:1},color:{default:()=>new l.Color("white")},zoom:{default:1},radius:{default:0},grayscale:{default:0},toneMapped:{type:Boolean,default:!0},transparent:{type:Boolean,default:!1},opacity:{default:1},side:{default:l.FrontSide},texture:{},url:{}},setup(i,{expose:e}){const t=i,n=u.shallowRef(),o=u.shallowRef(t.texture??null),r=H.useTres().sizes,s=u.computed(()=>Array.isArray(t.scale)?[t.scale[0],t.scale[1]]:[t.scale,t.scale]),a=u.computed(()=>{var p,f;return[((p=o.value)==null?void 0:p.image.width)??0,((f=o.value)==null?void 0:f.image.height)??0]}),c=u.computed(()=>Math.max(r.width.value,r.height.value));u.watchEffect(()=>{t.texture?o.value=t.texture:H.useTexture([t.url]).then(p=>o.value=p)});const h=u.computed(()=>Array.isArray(t.scale)?[...t.scale,1]:t.scale);return e({instance:n}),(p,f)=>(u.openBlock(),u.createElementBlock("TresMesh",{ref_key:"imageRef",ref:n,scale:h.value},[u.renderSlot(p.$slots,"default",{},()=>[u.createElementVNode("TresPlaneGeometry",{args:[1,1,t.segments,t.segments]},null,8,Ji)]),u.createVNode(qi,{color:t.color,map:o.value,zoom:t.zoom,grayscale:t.grayscale,opacity:t.opacity,scale:s.value,imageBounds:a.value,resolution:c.value,radius:p.radius,toneMapped:p.toneMapped,transparent:p.transparent,side:p.side},null,8,["color","map","zoom","grayscale","opacity","scale","imageBounds","resolution","radius","toneMapped","transparent","side"])],8,Qi))}}),Xt=parseInt(l.REVISION.replace(/\D+/g,"")),Gn=Xt>=125?"uv1":"uv2";function Qo(i,e){if(e===l.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===l.TriangleFanDrawMode||e===l.TriangleStripDrawMode){let t=i.getIndex();if(t===null){const s=[],a=i.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)s.push(c);i.setIndex(s),t=i.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),i}const n=t.count-2,o=[];if(t)if(e===l.TriangleFanDrawMode)for(let s=1;s<=n;s++)o.push(t.getX(0)),o.push(t.getX(s)),o.push(t.getX(s+1));else for(let s=0;s<n;s++)s%2===0?(o.push(t.getX(s)),o.push(t.getX(s+1)),o.push(t.getX(s+2))):(o.push(t.getX(s+2)),o.push(t.getX(s+1)),o.push(t.getX(s)));o.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=i.clone();return r.setIndex(o),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),i}function $i(i,e=Math.PI/3){const t=Math.cos(e),n=(1+1e-10)*100,o=[new l.Vector3,new l.Vector3,new l.Vector3],r=new l.Vector3,s=new l.Vector3,a=new l.Vector3,c=new l.Vector3;function h(_){const v=~~(_.x*n),g=~~(_.y*n),A=~~(_.z*n);return`${v},${g},${A}`}const p=i.index?i.toNonIndexed():i,f=p.attributes.position,m={};for(let _=0,v=f.count/3;_<v;_++){const g=3*_,A=o[0].fromBufferAttribute(f,g+0),w=o[1].fromBufferAttribute(f,g+1),C=o[2].fromBufferAttribute(f,g+2);r.subVectors(C,w),s.subVectors(A,w);const L=new l.Vector3().crossVectors(r,s).normalize();for(let M=0;M<3;M++){const P=o[M],b=h(P);b in m||(m[b]=[]),m[b].push(L)}}const d=new Float32Array(f.count*3),y=new l.BufferAttribute(d,3,!1);for(let _=0,v=f.count/3;_<v;_++){const g=3*_,A=o[0].fromBufferAttribute(f,g+0),w=o[1].fromBufferAttribute(f,g+1),C=o[2].fromBufferAttribute(f,g+2);r.subVectors(C,w),s.subVectors(A,w),a.crossVectors(r,s).normalize();for(let L=0;L<3;L++){const M=o[L],P=h(M),b=m[P];c.set(0,0,0);for(let S=0,x=b.length;S<x;S++){const I=b[S];a.dot(I)>t&&c.add(I)}c.normalize(),y.setXYZ(g+L,c.x,c.y,c.z)}}return p.setAttribute("normal",y),p}var ea=Object.defineProperty,ta=(i,e,t)=>e in i?ea(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,na=(i,e,t)=>(ta(i,e+"",t),t);async function Jo(i){const e=await i.arrayBuffer(),t=btoa(String.fromCharCode(...new Uint8Array(e)));return`data:${i.type||""};base64,${t}`}let fn,Rn,Lt,dn;function jn(i,e=1/0,t=null){Rn||(Rn=new l.PlaneGeometry(2,2,1,1)),Lt||(Lt=new l.ShaderMaterial({uniforms:{blitTexture:new l.Uniform(i)},vertexShader:` varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy * 1.0,0.,.999999); } `,fragmentShader:` uniform sampler2D blitTexture; varying vec2 vUv; void main(){ gl_FragColor = vec4(vUv.xy, 0, 1); #ifdef IS_SRGB gl_FragColor = LinearTosRGB( texture2D( blitTexture, vUv) ); #else gl_FragColor = texture2D( blitTexture, vUv); #endif } `})),Lt.uniforms.blitTexture.value=i,Lt.defines.IS_SRGB="colorSpace"in i?i.colorSpace==="srgb":i.encoding===3001,Lt.needsUpdate=!0,dn||(dn=new l.Mesh(Rn,Lt),dn.frustrumCulled=!1);const n=new l.PerspectiveCamera,o=new l.Scene;o.add(dn),t||(t=fn=new l.WebGLRenderer({antialias:!1})),t.setSize(Math.min(i.image.width,e),Math.min(i.image.height,e)),t.clear(),t.render(o,n);const r=new l.Texture(t.domElement);return r.minFilter=i.minFilter,r.magFilter=i.magFilter,r.wrapS=i.wrapS,r.wrapT=i.wrapT,r.name=i.name,fn&&(fn.dispose(),fn=null),r}const Ho={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class Wn{constructor(){this.pluginCallbacks=[],this.register(function(e){return new fa(e)}),this.register(function(e){return new da(e)}),this.register(function(e){return new ga(e)}),this.register(function(e){return new ya(e)}),this.register(function(e){return new _a(e)}),this.register(function(e){return new va(e)}),this.register(function(e){return new pa(e)}),this.register(function(e){return new ma(e)}),this.register(function(e){return new xa(e)}),this.register(function(e){return new wa(e)}),this.register(function(e){return new ba(e)})}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,o){const r=new ha,s=[];for(let a=0,c=this.pluginCallbacks.length;a<c;a++)s.push(this.pluginCallbacks[a](r));r.setPlugins(s),r.write(e,t,o).catch(n)}parseAsync(e,t){const n=this;return new Promise(function(o,r){n.parse(e,o,r,t)})}}na(Wn,"Utils",{insertKeyframe:function(i,e){const n=i.getValueSize(),o=new i.TimeBufferType(i.times.length+1),r=new i.ValueBufferType(i.values.length+n),s=i.createInterpolant(new i.ValueBufferType(n));let a;if(i.times.length===0){o[0]=e;for(let c=0;c<n;c++)r[c]=0;a=0}else if(e<i.times[0]){if(Math.abs(i.times[0]-e)<.001)return 0;o[0]=e,o.set(i.times,1),r.set(s.evaluate(e),0),r.set(i.values,n),a=0}else if(e>i.times[i.times.length-1]){if(Math.abs(i.times[i.times.length-1]-e)<.001)return i.times.length-1;o[o.length-1]=e,o.set(i.times,0),r.set(i.values,0),r.set(s.evaluate(e),i.values.length),a=o.length-1}else for(let c=0;c<i.times.length;c++){if(Math.abs(i.times[c]-e)<.001)return c;if(i.times[c]<e&&i.times[c+1]>e){o.set(i.times.slice(0,c+1),0),o[c+1]=e,o.set(i.times.slice(c+1),c+2),r.set(i.values.slice(0,(c+1)*n),0),r.set(s.evaluate(e),(c+1)*n),r.set(i.values.slice((c+1)*n),(c+2)*n),a=c+1;break}}return i.times=o,i.values=r,a},mergeMorphTargetTracks:function(i,e){const t=[],n={},o=i.tracks;for(let r=0;r<o.length;++r){let s=o[r];const a=l.PropertyBinding.parseTrackName(s.name),c=l.PropertyBinding.findNode(e,a.nodeName);if(a.propertyName!=="morphTargetInfluences"||a.propertyIndex===void 0){t.push(s);continue}if(s.createInterpolant!==s.InterpolantFactoryMethodDiscrete&&s.createInterpolant!==s.InterpolantFactoryMethodLinear){if(s.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline)throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."),s=s.clone(),s.setInterpolation(l.InterpolateLinear)}const h=c.morphTargetInfluences.length,p=c.morphTargetDictionary[a.propertyIndex];if(p===void 0)throw new Error("THREE.GLTFExporter: Morph target name not found: "+a.propertyIndex);let f;if(n[c.uuid]===void 0){f=s.clone();const d=new f.ValueBufferType(h*f.times.length);for(let y=0;y<f.times.length;y++)d[y*h+p]=f.values[y];f.name=(a.nodeName||"")+".morphTargetInfluences",f.values=d,n[c.uuid]=f,t.push(f);continue}const m=s.createInterpolant(new s.ValueBufferType(1));f=n[c.uuid];for(let d=0;d<f.times.length;d++)f.values[d*h+p]=m.evaluate(f.times[d]);for(let d=0;d<s.times.length;d++){const y=this.insertKeyframe(f,s.times[d]);f.values[y*h+p]=s.values[d]}}return i.tracks=t,i}});const we={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,ARRAY_BUFFER:34962,ELEMENT_ARRAY_BUFFER:34963,NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497},Yn="KHR_mesh_quantization",Xe={};Xe[l.NearestFilter]=we.NEAREST,Xe[l.NearestMipmapNearestFilter]=we.NEAREST_MIPMAP_NEAREST,Xe[l.NearestMipmapLinearFilter]=we.NEAREST_MIPMAP_LINEAR,Xe[l.LinearFilter]=we.LINEAR,Xe[l.LinearMipmapNearestFilter]=we.LINEAR_MIPMAP_NEAREST,Xe[l.LinearMipmapLinearFilter]=we.LINEAR_MIPMAP_LINEAR,Xe[l.ClampToEdgeWrapping]=we.CLAMP_TO_EDGE,Xe[l.RepeatWrapping]=we.REPEAT,Xe[l.MirroredRepeatWrapping]=we.MIRRORED_REPEAT;const $o={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},oa=new l.Color,er=12,ra=1179937895,sa=2,tr=8,ia=1313821514,aa=5130562;function Et(i,e){return i.length===e.length&&i.every(function(t,n){return t===e[n]})}function la(i){return new TextEncoder().encode(i).buffer}function ca(i){return Et(i.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function ua(i,e,t){const n={min:new Array(i.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(i.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let o=e;o<e+t;o++)for(let r=0;r<i.itemSize;r++){let s;i.itemSize>4?s=i.array[o*i.itemSize+r]:(r===0?s=i.getX(o):r===1?s=i.getY(o):r===2?s=i.getZ(o):r===3&&(s=i.getW(o)),i.normalized===!0&&(s=l.MathUtils.normalize(s,i.array))),n.min[r]=Math.min(n.min[r],s),n.max[r]=Math.max(n.max[r],s)}return n}function nr(i){return Math.ceil(i/4)*4}function Xn(i,e=0){const t=nr(i.byteLength);if(t!==i.byteLength){const n=new Uint8Array(t);if(n.set(new Uint8Array(i)),e!==0)for(let o=i.byteLength;o<t;o++)n[o]=e;return n.buffer}return i}function or(){return typeof document>"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function rr(i,e){if(i.toBlob!==void 0)return new Promise(n=>i.toBlob(n,e));let t;return e==="image/jpeg"?t=.92:e==="image/webp"&&(t=.8),i.convertToBlob({type:e,quality:t})}class ha{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter"}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map}}setPlugins(e){this.plugins=e}async write(e,t,n={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},n),this.options.animations.length>0&&(this.options.trs=!0),this.processInput(e),await Promise.all(this.pending);const o=this,r=o.buffers,s=o.json;n=o.options;const a=o.extensionsUsed,c=o.extensionsRequired,h=new Blob(r,{type:"application/octet-stream"}),p=Object.keys(a),f=Object.keys(c);p.length>0&&(s.extensionsUsed=p),f.length>0&&(s.extensionsRequired=f),s.buffers&&s.buffers.length>0&&(s.buffers[0].byteLength=h.size),n.binary===!0?h.arrayBuffer().then(m=>{const d=Xn(m),y=new DataView(new ArrayBuffer(tr));y.setUint32(0,d.byteLength,!0),y.setUint32(4,aa,!0);const _=Xn(la(JSON.stringify(s)),32),v=new DataView(new ArrayBuffer(tr));v.setUint32(0,_.byteLength,!0),v.setUint32(4,ia,!0);const g=new ArrayBuffer(er),A=new DataView(g);A.setUint32(0,ra,!0),A.setUint32(4,sa,!0);const w=er+v.byteLength+_.byteLength+y.byteLength+d.byteLength;A.setUint32(8,w,!0),new Blob([g,v,_,y,d],{type:"application/octet-stream"}).arrayBuffer().then(t)}):s.buffers&&s.buffers.length>0?Jo(h).then(m=>{s.buffers[0].uri=m,t(s)}):t(s)}serializeUserData(e,t){if(Object.keys(e.userData).length===0)return;const n=this.options,o=this.extensionsUsed;try{const r=JSON.parse(JSON.stringify(e.userData));if(n.includeCustomExtensions&&r.gltfExtensions){t.extensions===void 0&&(t.extensions={});for(const s in r.gltfExtensions)t.extensions[s]=r.gltfExtensions[s],o[s]=!0;delete r.gltfExtensions}Object.keys(r).length>0&&(t.extras=r)}catch(r){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+r.message)}}getUID(e,t=!1){if(this.uids.has(e)===!1){const o=new Map;o.set(!0,this.uid++),o.set(!1,this.uid++),this.uids.set(e,o)}return this.uids.get(e).get(t)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const n=new l.Vector3;for(let o=0,r=e.count;o<r;o++)if(Math.abs(n.fromBufferAttribute(e,o).length()-1)>5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const t=this.cache;if(t.attributesNormalized.has(e))return t.attributesNormalized.get(e);const n=e.clone(),o=new l.Vector3;for(let r=0,s=n.count;r<s;r++)o.fromBufferAttribute(n,r),o.x===0&&o.y===0&&o.z===0?o.setX(1):o.normalize(),n.setXYZ(r,o.x,o.y,o.z);return t.attributesNormalized.set(e,n),n}applyTextureTransform(e,t){let n=!1;const o={};(t.offset.x!==0||t.offset.y!==0)&&(o.offset=t.offset.toArray(),n=!0),t.rotation!==0&&(o.rotation=t.rotation,n=!0),(t.repeat.x!==1||t.repeat.y!==1)&&(o.scale=t.repeat.toArray(),n=!0),n&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=o,this.extensionsUsed.KHR_texture_transform=!0)}buildMetalRoughTexture(e,t){if(e===t)return e;function n(d){return("colorSpace"in d?d.colorSpace==="srgb":d.encoding===3001)?function(_){return _<.04045?_*.0773993808:Math.pow(_*.9478672986+.0521327014,2.4)}:function(_){return _}}console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."),e instanceof l.CompressedTexture&&(e=jn(e)),t instanceof l.CompressedTexture&&(t=jn(t));const o=e?e.image:null,r=t?t.image:null,s=Math.max(o?o.width:0,r?r.width:0),a=Math.max(o?o.height:0,r?r.height:0),c=or();c.width=s,c.height=a;const h=c.getContext("2d");h.fillStyle="#00ffff",h.fillRect(0,0,s,a);const p=h.getImageData(0,0,s,a);if(o){h.drawImage(o,0,0,s,a);const d=n(e),y=h.getImageData(0,0,s,a).data;for(let _=2;_<y.length;_+=4)p.data[_]=d(y[_]/256)*256}if(r){h.drawImage(r,0,0,s,a);const d=n(t),y=h.getImageData(0,0,s,a).data;for(let _=1;_<y.length;_+=4)p.data[_]=d(y[_]/256)*256}h.putImageData(p,0,0);const m=(e||t).clone();return m.source=new l.Texture(c).source,"colorSpace"in m?m.colorSpace="":m.encoding=3e3,m.channel=(e||t).channel,e&&t&&e.channel!==t.channel&&console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."),m}processBuffer(e){const t=this.json,n=this.buffers;return t.buffers||(t.buffers=[{byteLength:0}]),n.push(e),0}processBufferView(e,t,n,o,r){const s=this.json;s.bufferViews||(s.bufferViews=[]);let a;switch(t){case we.BYTE:case we.UNSIGNED_BYTE:a=1;break;case we.SHORT:case we.UNSIGNED_SHORT:a=2;break;default:a=4}const c=nr(o*e.itemSize*a),h=new DataView(new ArrayBuffer(c));let p=0;for(let d=n;d<n+o;d++)for(let y=0;y<e.itemSize;y++){let _;e.itemSize>4?_=e.array[d*e.itemSize+y]:(y===0?_=e.getX(d):y===1?_=e.getY(d):y===2?_=e.getZ(d):y===3&&(_=e.getW(d)),e.normalized===!0&&(_=l.MathUtils.normalize(_,e.array))),t===we.FLOAT?h.setFloat32(p,_,!0):t===we.INT?h.setInt32(p,_,!0):t===we.UNSIGNED_INT?h.setUint32(p,_,!0):t===we.SHORT?h.setInt16(p,_,!0):t===we.UNSIGNED_SHORT?h.setUint16(p,_,!0):t===we.BYTE?h.setInt8(p,_):t===we.UNSIGNED_BYTE&&h.setUint8(p,_),p+=a}const f={buffer:this.processBuffer(h.buffer),byteOffset:this.byteOffset,byteLength:c};return r!==void 0&&(f.target=r),r===we.ARRAY_BUFFER&&(f.byteStride=e.itemSize*a),this.byteOffset+=c,s.bufferViews.push(f),{id:s.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const t=this,n=t.json;return n.bufferViews||(n.bufferViews=[]),e.arrayBuffer().then(o=>{const r=Xn(o),s={buffer:t.processBuffer(r),byteOffset:t.byteOffset,byteLength:r.byteLength};return t.byteOffset+=r.byteLength,n.bufferViews.push(s)-1})}processAccessor(e,t,n,o){const r=this.json,s={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"};let a;if(e.array.constructor===Float32Array)a=we.FLOAT;else if(e.array.constructor===Int32Array)a=we.INT;else if(e.array.constructor===Uint32Array)a=we.UNSIGNED_INT;else if(e.array.constructor===Int16Array)a=we.SHORT;else if(e.array.constructor===Uint16Array)a=we.UNSIGNED_SHORT;else if(e.array.constructor===Int8Array)a=we.BYTE;else if(e.array.constructor===Uint8Array)a=we.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);if(n===void 0&&(n=0),o===void 0&&(o=e.count),o===0)return null;const c=ua(e,n,o);let h;t!==void 0&&(h=e===t.index?we.ELEMENT_ARRAY_BUFFER:we.ARRAY_BUFFER);const p=this.processBufferView(e,a,n,o,h),f={bufferView:p.id,byteOffset:p.byteOffset,componentType:a,count:o,max:c.max,min:c.min,type:s[e.itemSize]};return e.normalized===!0&&(f.normalized=!0),r.accessors||(r.accessors=[]),r.accessors.push(f)-1}processImage(e,t,n,o="image/png"){if(e!==null){const r=this,s=r.cache,a=r.json,c=r.options,h=r.pending;s.images.has(e)||s.images.set(e,{});const p=s.images.get(e),f=o+":flipY/"+n.toString();if(p[f]!==void 0)return p[f];a.images||(a.images=[]);const m={mimeType:o},d=or();d.width=Math.min(e.width,c.maxTextureSize),d.height=Math.min(e.height,c.maxTextureSize);const y=d.getContext("2d");if(n===!0&&(y.translate(0,d.height),y.scale(1,-1)),e.data!==void 0){t!==l.RGBAFormat&&console.error("GLTFExporter: Only RGBAFormat is supported.",t),(e.width>c.maxTextureSize||e.height>c.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);const v=new Uint8ClampedArray(e.height*e.width*4);for(let g=0;g<v.length;g+=4)v[g+0]=e.data[g+0],v[g+1]=e.data[g+1],v[g+2]=e.data[g+2],v[g+3]=e.data[g+3];y.putImageData(new ImageData(v,e.width,e.height),0,0)}else y.drawImage(e,0,0,d.width,d.height);c.binary===!0?h.push(rr(d,o).then(v=>r.processBufferViewImage(v)).then(v=>{m.bufferView=v})):d.toDataURL!==void 0?m.uri=d.toDataURL(o):h.push(rr(d,o).then(Jo).then(v=>{m.uri=v}));const _=a.images.push(m)-1;return p[f]=_,_}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const t=this.json;t.samplers||(t.samplers=[]);const n={magFilter:Xe[e.magFilter],minFilter:Xe[e.minFilter],wrapS:Xe[e.wrapS],wrapT:Xe[e.wrapT]};return t.samplers.push(n)-1}processTexture(e){const n=this.options,o=this.cache,r=this.json;if(o.textures.has(e))return o.textures.get(e);r.textures||(r.textures=[]),e instanceof l.CompressedTexture&&(e=jn(e,n.maxTextureSize));let s=e.userData.mimeType;s==="image/webp"&&(s="image/png");const a={sampler:this.processSampler(e),source:this.processImage(e.image,e.format,e.flipY,s)};e.name&&(a.name=e.name),this._invokeAll(function(h){h.writeTexture&&h.writeTexture(e,a)});const c=r.textures.push(a)-1;return o.textures.set(e,c),c}processMaterial(e){const t=this.cache,n=this.json;if(t.materials.has(e))return t.materials.get(e);if(e.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;n.materials||(n.materials=[]);const o={pbrMetallicRoughness:{}};e.isMeshStandardMaterial!==!0&&e.isMeshBasicMaterial!==!0&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");const r=e.color.toArray().concat([e.opacity]);if(Et(r,[1,1,1,1])||(o.pbrMetallicRoughness.baseColorFactor=r),e.isMeshStandardMaterial?(o.pbrMetallicRoughness.metallicFactor=e.metalness,o.pbrMetallicRoughness.roughnessFactor=e.roughness):(o.pbrMetallicRoughness.metallicFactor=.5,o.pbrMetallicRoughness.roughnessFactor=.5),e.metalnessMap||e.roughnessMap){const a=this.buildMetalRoughTexture(e.metalnessMap,e.roughnessMap),c={index:this.processTexture(a),channel:a.channel};this.applyTextureTransform(c,a),o.pbrMetallicRoughness.metallicRoughnessTexture=c}if(e.map){const a={index:this.processTexture(e.map),texCoord:e.map.channel};this.applyTextureTransform(a,e.map),o.pbrMetallicRoughness.baseColorTexture=a}if(e.emissive){const a=e.emissive;if(Math.max(a.r,a.g,a.b)>0&&(o.emissiveFactor=e.emissive.toArray()),e.emissiveMap){const h={index:this.processTexture(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(h,e.emissiveMap),o.emissiveTexture=h}}if(e.normalMap){const a={index:this.processTexture(e.normalMap),texCoord:e.normalMap.channel};e.normalScale&&e.normalScale.x!==1&&(a.scale=e.normalScale.x),this.applyTextureTransform(a,e.normalMap),o.normalTexture=a}if(e.aoMap){const a={index:this.processTexture(e.aoMap),texCoord:e.aoMap.channel};e.aoMapIntensity!==1&&(a.strength=e.aoMapIntensity),this.applyTextureTransform(a,e.aoMap),o.occlusionTexture=a}e.transparent?o.alphaMode="BLEND":e.alphaTest>0&&(o.alphaMode="MASK",o.alphaCutoff=e.alphaTest),e.side===l.DoubleSide&&(o.doubleSided=!0),e.name!==""&&(o.name=e.name),this.serializeUserData(e,o),this._invokeAll(function(a){a.writeMaterial&&a.writeMaterial(e,o)});const s=n.materials.push(o)-1;return t.materials.set(e,s),s}processMesh(e){const t=this.cache,n=this.json,o=[e.geometry.uuid];if(Array.isArray(e.material))for(let w=0,C=e.material.length;w<C;w++)o.push(e.material[w].uuid);else o.push(e.material.uuid);const r=o.join(":");if(t.meshes.has(r))return t.meshes.get(r);const s=e.geometry;let a;e.isLineSegments?a=we.LINES:e.isLineLoop?a=we.LINE_LOOP:e.isLine?a=we.LINE_STRIP:e.isPoints?a=we.POINTS:a=e.material.wireframe?we.LINES:we.TRIANGLES;const c={},h={},p=[],f=[],m={...Xt>=152?{uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3"}:{uv:"TEXCOORD_0",uv2:"TEXCOORD_1"},color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},d=s.getAttribute("normal");d!==void 0&&!this.isNormalizedNormalAttribute(d)&&(console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."),s.setAttribute("normal",this.createNormalizedNormalAttribute(d)));let y=null;for(let w in s.attributes){if(w.slice(0,5)==="morph")continue;const C=s.attributes[w];if(w=m[w]||w.toUpperCase(),/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(w)||(w="_"+w),t.attributes.has(this.getUID(C))){h[w]=t.attributes.get(this.getUID(C));continue}y=null;const M=C.array;w==="JOINTS_0"&&!(M instanceof Uint16Array)&&!(M instanceof Uint8Array)&&(console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'),y=new l.BufferAttribute(new Uint16Array(M),C.itemSize,C.normalized));const P=this.processAccessor(y||C,s);P!==null&&(w.startsWith("_")||this.detectMeshQuantization(w,C),h[w]=P,t.attributes.set(this.getUID(C),P))}if(d!==void 0&&s.setAttribute("normal",d),Object.keys(h).length===0)return null;if(e.morphTargetInfluences!==void 0&&e.morphTargetInfluences.length>0){const w=[],C=[],L={};if(e.morphTargetDictionary!==void 0)for(const M in e.morphTargetDictionary)L[e.morphTargetDictionary[M]]=M;for(let M=0;M<e.morphTargetInfluences.length;++M){const P={};let b=!1;for(const S in s.morphAttributes){if(S!=="position"&&S!=="normal"){b||(console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."),b=!0);continue}const x=s.morphAttributes[S][M],I=S.toUpperCase(),D=s.attributes[S];if(t.attributes.has(this.getUID(x,!0))){P[I]=t.attributes.get(this.getUID(x,!0));continue}const z=x.clone();if(!s.morphTargetsRelative)for(let G=0,E=x.count;G<E;G++)for(let X=0;X<x.itemSize;X++)X===0&&z.setX(G,x.getX(G)-D.getX(G)),X===1&&z.setY(G,x.getY(G)-D.getY(G)),X===2&&z.setZ(G,x.getZ(G)-D.